text
stringlengths 184
4.48M
|
---|
import './index.css';
import { openPopup, closePopup } from './components/modal.js';
import { enableValidation, clearValidation } from './components/validation.js';
import { pushInfo, getUserInfo, getCards, postCard, pushAvatar} from './components/api.js'
import { createCard, handleLikeClick, handleDeleteClick } from './components/card.js'
import { add } from 'lodash';
// константы
const editingPopup = document.querySelector('.popup_type_edit');
const editingButton = document.querySelector('.profile__edit-button');
const addingPopup = document.querySelector('.popup_type_new-card');
const addingButton = document.querySelector('.profile__add-button');
const closingEditButton = editingPopup.querySelector('.popup__close');
const closingAddButton = addingPopup.querySelector('.popup__close');
const editForm = document.forms['edit-profile'];
const profileNameInput = editForm.elements.name;
const profileDescriptionInput = editForm.elements.description;
const editSubmitButton = editForm.querySelector('.popup__button')
const profileTitle = document.querySelector('.profile__title');
const profileDescription = document.querySelector('.profile__description');
const addForm = document.forms['new-place'];
const cardNameInput = addForm.elements.place;
const cardLinkInput = addForm.elements.link;
const addSubmitButton = addForm.querySelector('.popup__button')
const avatarForm = document.forms['new-avatar'];
const avatarInput = avatarForm.elements.link;
const avatarSubmitButton = avatarForm.querySelector('.popup__button')
const elementsContainer = document.querySelector('.places__list');
const imagePopup = document.querySelector('.popup_type_image');
const imageImagePopup = imagePopup.querySelector('.popup__image');
const captionImagePopup = imagePopup.querySelector('.popup__caption');
const closingImagePopup = imagePopup.querySelector('.popup__close');
const profileAvatar = document.querySelector('.profile__image')
const openPhotoAvatar = document.querySelector('.profile__image-container');
const avatarPopup = document.querySelector('.popup_type_avatar');
const closingAvatarPopup = avatarPopup.querySelector('.popup__close');
const validationConfig = {
formSelector: '.popup__form',
inputSelector: '.popup__input',
submitButtonSelector: '.popup__button',
inputField: '.popup__fieldset',
inactiveButtonClass: 'popup__button_inactive',
inputErrorClass: 'popup__input_err',
errorClass: 'popup__input-error_active',
};
let userId = ''
//функция обновления информации профиля
function editInfo(evt) {
evt.preventDefault();
const newInfo = {
name: profileNameInput.value,
about: profileDescriptionInput.value
};
editSubmitButton.textContent = 'Сохранение...';
pushInfo(newInfo)
.then((newInfo) => {
profileTitle.textContent = newInfo.name;
profileDescription.textContent = newInfo.about;
closePopup(editingPopup);
clearValidation(editingPopup, validationConfig)
})
.catch((error) => {
console.log(`Ошибка при сохранении данных: ${error.message}`);
})
.finally(() => {
editSubmitButton.textContent = "Сохранить";
});
}
// функция обновления аватара
function editAvatar(evt) {
evt.preventDefault();
const avatar = avatarInput.value;
avatarSubmitButton.textContent = 'Сохранение...';
pushAvatar(avatar)
.then((newAvatar) => {
profileAvatar.style['background-image'] = `url(${newAvatar.avatar})`;
closePopup(avatarPopup);
clearValidation(avatarPopup, validationConfig);
})
.catch((error) => {
console.log(`Ошибка при сохранении данных: ${error.message}`);
})
.finally(() => {
avatarSubmitButton.textContent = "Сохранить";
})
}
//обновление попапа с профилем и аватара по сабмиту
editForm.addEventListener('submit', editInfo);
avatarForm.addEventListener('submit', editAvatar);
// сабмит добавления карточки, созданной с помощью попапа
addForm.addEventListener('submit', function() {
addSubmitButton.textContent = 'Сохранение...';
const cardInfo = {
name: cardNameInput.value,
link: cardLinkInput.value
};
postCard(cardInfo)
.then((data) => {
const newCard = {
name: cardInfo.name,
link: cardInfo.link,
likes: data.likes,
_id: data._id,
owner: {
_id: userId
}
}
const newCardElement = createCard(newCard, { handleLikeClick, handleDeleteClick, handleImageClick }, userId);
elementsContainer.prepend(newCardElement);
closePopup(addingPopup);
addForm.reset();
clearValidation(addingPopup, validationConfig);
})
.catch(error => {
console.log(`Ошибка при сохранении данных: ${error.message}`);
})
.finally(() => {
addSubmitButton.textContent = "Сохранить";
});
})
// добавление исходных карточек
function addCards(arr) {
arr.forEach((item) => {
elementsContainer.append(createCard(item, { handleLikeClick, handleDeleteClick, handleImageClick }, userId));
});
};
// открытие попапа приблежения
function handleImageClick(photo, card) {
photo.addEventListener('click', function() {
imageImagePopup.src = card.link;
imageImagePopup.alt = card.name;
captionImagePopup.textContent = card.name;
openPopup(imagePopup);
});
};
// открытие попапа с профилем по нажатию на кнопку
editingButton.addEventListener('click', function() {
openPopup(editingPopup);
profileNameInput.value = profileTitle.textContent;
profileDescriptionInput.value = profileDescription.textContent;
});
// закрытие попапа с профилем (без сабмита)
closingEditButton.addEventListener('click', function() {
closePopup(editingPopup);
clearValidation(editingPopup, validationConfig)
});
// открытие попапа добавления карточки
addingButton.addEventListener('click', function() {
openPopup(addingPopup);
});
// закрытие попапа добавление карточки (без сабмита)
closingAddButton.addEventListener('click', function() {
closePopup(addingPopup);
clearValidation(addingPopup, validationConfig)
});
// закрытие попапа увелечения карточки (без сабмита)
closingImagePopup.addEventListener('click', function() {
closePopup(imagePopup);
});
// открытие попапа изменения аватара
openPhotoAvatar.addEventListener('click', function() {
openPopup(avatarPopup);
});
// закрытие попапа изменения аватара
closingAvatarPopup.addEventListener('click', function() {
closePopup(avatarPopup);
clearValidation(avatarPopup, validationConfig)
});
// валидация
clearValidation(addingPopup, validationConfig);
enableValidation(validationConfig);
Promise.all([getUserInfo(), getCards()])
.then(([userInfo, cards]) => {
profileTitle.textContent = userInfo.name;
profileDescription.textContent = userInfo.about;
profileAvatar.style.backgroundImage = `url("${userInfo.avatar}")`;
userId = userInfo._id;
addCards(cards);
console.log(cards)
})
.catch((error) => {
console.log(`Ошибка при получении данных: ${error.message}`);
}) |
import styled, { css } from 'styled-components';
import { GlobalStyleType } from 'styles/global.styles';
export const StyledAnswerListHead = styled.div.attrs((props) => {})`
${(props) => {
const Theme: GlobalStyleType = props.theme;
const $font_title_big = Theme.font.$font_title_big;
const $font_title_regular = Theme.font.$font_title_regular;
const $font_subtitle = Theme.font.$font_subtitle;
const $color_base_white = Theme.palette.$color_base_white;
const $color_base_line = Theme.palette.$color_base_line;
const $color_base_black = Theme.palette.$color_base_black;
const $color_base_dark = Theme.palette.$color_base_dark;
const $color_key_color = Theme.palette.$color_key_color;
const $color_success = Theme.palette.$color_success;
const $color_failure = Theme.palette.$color_failure;
const $mobile_max_width = Theme.media.$mobile_max_width;
return css`
display: flex;
flex-wrap: wrap;
flex-flow: row;
justify-content: flex-start;
align-items: center;
gap: 20px;
div {
display: flex;
flex-wrap: wrap;
flex-flow: row;
justify-content: flex-start;
align-items: center;
gap: 20px;
span {
display: flex;
justify-content: center;
align-items: center;
width: 44px;
height: 44px;
border-radius: 100%;
color: ${$color_base_white};
${$font_subtitle};
&.correct {
background-color: ${$color_success};
}
&.wrong {
background-color: ${$color_failure};
}
}
svg {
cursor: pointer;
font-size: 44px;
color: ${$color_key_color};
}
}
h4 {
${$font_title_regular};
}
@media screen and (max-width: ${$mobile_max_width}) {
gap: 10px;
flex-flow: column;
align-items: flex-start;
}
`;
}}
`;
export const StyledAnswerList = styled.ul.attrs((props) => {})`
${(props) => {
const Theme: GlobalStyleType = props.theme;
const $font_title_big = Theme.font.$font_title_big;
const $font_title_regular = Theme.font.$font_title_regular;
const $font_subtitle = Theme.font.$font_subtitle;
const $color_base_white = Theme.palette.$color_base_white;
const $color_base_line = Theme.palette.$color_base_line;
const $color_base_black = Theme.palette.$color_base_black;
const $color_base_dark = Theme.palette.$color_base_dark;
const $color_key_color = Theme.palette.$color_key_color;
const $color_success = Theme.palette.$color_success;
const $color_failure = Theme.palette.$color_failure;
const $mobile_max_width = Theme.media.$mobile_max_width;
return css`
list-style: none;
margin: 0;
padding: 0;
li {
display: flex;
justify-content: space-between;
align-items: flex-start;
flex-wrap: wrap;
flex-flow: column;
border-bottom: 1px solid ${$color_base_line};
ol {
padding: 10px 10px 20px 10px;
display: flex;
flex-flow: column;
justify-content: space-between;
align-items: flex-start;
gap: 14px;
li {
${$font_subtitle};
border: none;
&.correct {
color: ${$color_success};
}
&.wrong {
color: ${$color_failure};
}
}
}
}
@media screen and (max-width: ${$mobile_max_width}) {
li {
margin: 10px 0;
}
}
`;
}}
`;
export const IsWrongToggle = styled.div.attrs((props) => {})`
${(props) => {
const Theme: GlobalStyleType = props.theme;
const $color_base_white = Theme.palette.$color_base_white;
const $color_base_black = Theme.palette.$color_base_black;
const $color_base_dark = Theme.palette.$color_base_dark;
const $color_key_color = Theme.palette.$color_key_color;
const $mobile_max_width = Theme.media.$mobile_max_width;
return css`
display: flex;
justify-content: flex-end;
align-items: center;
gap: 10px;
@media screen and (max-width: ${$mobile_max_width}) {
}
`;
}}
`;
export const ResultNum = styled.div.attrs((props) => {})`
${(props) => {
const Theme: GlobalStyleType = props.theme;
const $font_body_head = Theme.font.$font_body_head;
const $color_base_white = Theme.palette.$color_base_white;
const $color_base_black = Theme.palette.$color_base_black;
const $color_base_dark = Theme.palette.$color_base_dark;
const $color_key_color = Theme.palette.$color_key_color;
const $mobile_max_width = Theme.media.$mobile_max_width;
return css`
display: flex;
justify-content: flex-start;
align-items: center;
gap: 10px;
margin-top: 10px;
${$font_body_head};
@media screen and (max-width: ${$mobile_max_width}) {
}
`;
}}
`;
export const GoToProfile = styled.div.attrs((props) => {})`
${(props) => {
const Theme: GlobalStyleType = props.theme;
const $font_body_head = Theme.font.$font_body_head;
const $font_body_info = Theme.font.$font_body_info;
const $color_base_white = Theme.palette.$color_base_white;
const $color_base_black = Theme.palette.$color_base_black;
const $color_base_dark = Theme.palette.$color_base_dark;
const $color_key_color = Theme.palette.$color_key_color;
const $mobile_max_width = Theme.media.$mobile_max_width;
return css`
${$font_body_info};
cursor: pointer;
display: flex;
justify-content: flex-end;
align-items: flex-end;
gap: 10px;
width: fit-content;
/* margin-top: 10px; */
padding: 8px 10px;
background-color: ${$color_key_color};
* {
text-decoration: none;
}
a {
color: ${$color_base_white};
}
@media screen and (max-width: ${$mobile_max_width}) {
}
`;
}}
`;
const StyledQuizResult = styled.section.attrs((props) => {})`
${(props) => {
const Theme: GlobalStyleType = props.theme;
const $font_title_big = Theme.font.$font_title_big;
const $color_base_white = Theme.palette.$color_base_white;
const $color_base_black = Theme.palette.$color_base_black;
const $color_base_dark = Theme.palette.$color_base_dark;
const $color_key_color = Theme.palette.$color_key_color;
const $mobile_max_width = Theme.media.$mobile_max_width;
return css`
h1 {
${$font_title_big};
}
@media screen and (max-width: ${$mobile_max_width}) {
padding: 0 5%;
}
`;
}}
`;
export default StyledQuizResult; |
from .dynamic_model import DynamicModel
from track_model.track import Track
import torch as th
import numpy as np
class BicycleModel2(DynamicModel):
def __init__(self):
super().__init__()
self.max_steer = np.radians(15.0) # [rad] max steering angle
self.L = 3.5 # [m] Wheel base of vehicle
self.Lr = self.L / 2.0 # [m]
self.Lf = self.L - self.Lr
self.Cf = 4.0 # N/rad
self.Cr = self.Cf*1.1
self.Iz = 2250.0 # kg/m2
self.m = 700.0 # kg
# Aerodynamic and friction coefficients
self.c_a = 1.7 # 1.3
self.c_r = 0.1
#
self.x = self.add_state('x')
self.y = self.add_state('y')
self.yaw = self.add_state('yaw')
self.vx = self.add_state('vx')
self.vy = self.add_state('vy')
self.omega = self.add_state('omega')
# track tracing variables
# controls
self.throttle = self.add_control('throttle')
throttle_max = 20.0
self.throttle.set_bounds(-throttle_max, throttle_max)
self.steer_angle = self.add_control('steer')
self.steer_angle.set_bounds(-self.max_steer, +self.max_steer)
# parameters:
self.name = 'linear dynamic bicycle model'
def forward(self, states: th.Tensor, ctrls: th.Tensor, device=None):
# Compute the local velocity in the x-axis
throttle = ctrls[:, self.throttle.get_idx()]
delta = ctrls[:, self.steer_angle.get_idx()]
#
yaw = states[:, self.yaw.get_idx()]
omega = states[:, self.omega.get_idx()]
vx, vy = states[:, self.vx.get_idx()], states[:, self.vy.get_idx()]
velocity = th.sqrt(vx*vx + vy*vy)
delta_x = vx * th.cos(yaw) - vy * th.sin(yaw)
delta_y = vx * th.sin(yaw) + vy * th.cos(yaw)
delta_yaw = omega
# vfac = velocity / 20.0
vfac = 9.81 * self.m + 2.0*vx**2.0
Ffy = -vfac*self.Cf*th.atan(((vy + self.Lf *omega) /vx - delta))
Fry = -vfac*self.Cr*th.atan((vy - self.Lr *omega) /vx)
#
R_x = self.c_r * vx
F_aero = self.c_a * vx ** 2
F_load = F_aero + R_x
delta_vx = (throttle - Ffy * th.sin(delta) / self.m - F_load/self.m + vy * omega)
delta_vy = (Fry / self.m + Ffy * th.cos(delta) / self.m - vx * omega)
delta_omega = (Ffy * self.Lf * th.cos(delta) - Fry * self.Lr) / self.Iz
out_th = th.stack([delta_x, delta_y, delta_yaw, delta_vx, delta_vy, delta_omega]).T
return out_th
def forward_noparam(self, states: th.Tensor, controls: th.Tensor, device='cpu') -> th.Tensor:
'''
Compute the state derivative.
'''
return self.forward(states, controls, device=device) |
import React, { Component } from "react";
import {
Grid,
IconButton,
Icon,
Input,
InputAdornment,
TablePagination,
Button,
Link,
FormControl,
Collapse,
} from "@material-ui/core";
import MaterialTable, {
MTableToolbar,
Chip,
MTableBody,
MTableHeader,
} from "material-table";
import {
deleteItem,
searchByPage,
getById,
deleteByList,
} from "./SpecimenService";
import SpecimenEditorDialog from "./SpecimenEditorDialog";
import { Breadcrumb, ConfirmationDialog } from "egret";
import { useTranslation, withTranslation, Trans } from "react-i18next";
import SearchIcon from "@material-ui/icons/Search";
import UploadExcelDialog from "../uploadExcel/UploadExcelDialog";
import { saveAs } from "file-saver";
import ConstantList from "../../appConfig";
import moment from "moment";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import SpecimenFilter from "./SpecimentFilter";
import ArrowDropDownIcon from "@material-ui/icons/ArrowDropDown";
import FilterListIcon from "@material-ui/icons/FilterList";
import { connect } from "react-redux";
import { getLoading } from "../../redux/actions/LoadingActions";
import NotificationPopup from "../Component/NotificationPopup/NotificationPopup";
toast.configure({
autoClose: 2000,
draggable: false,
limit: 3,
});
function MaterialButton(props) {
const { t, i18n } = useTranslation();
const item = props.item;
return (
<div>
<IconButton size="small" onClick={() => props.onSelect(item, 0)}>
<Icon fontSize="small" color="primary">
edit
</Icon>
</IconButton>
<IconButton size="small" onClick={() => props.onSelect(item, 1)}>
<Icon fontSize="small" color="error">
delete
</Icon>
</IconButton>
</div>
);
};
class Specimen extends Component {
state = {
keyword: "",
rowsPerPage: 10,
page: 0,
item: {},
shouldOpenEditorDialog: false,
shouldOpenConfirmationDialog: false,
selectAllItem: false,
selectedList: [],
totalElements: 0,
shouldOpenConfirmationDeleteAllDialog: false,
loading: true,
showOpenDialogError: false,
};
handleTextChange = (event) => {
this.setState({ keyword: event.target.value }, function () {});
};
handleKeyDownEnterSearch = (e) => {
if (e.key === "Enter") {
this.search();
}
};
setPage = (page) => {
this.setState({ page }, function () {
this.updatePageData();
});
};
setRowsPerPage = (event) => {
this.setState({ rowsPerPage: event.target.value, page: 0 }, function () {
this.updatePageData();
});
};
handleChangePage = (event, newPage) => {
this.setPage(newPage);
};
specimenTypeString = (value) => {
//Khai báo const
let name = "";
if (value == 1) {
name = "Mẫu máu toàn phần";
} else if (value == 2) {
name = "Huyết tương";
} else if (value == 3) {
name = "Huyết thanh";
} else if (value == 4) {
name = "DBS";
} else if (value == 5) {
name = "Khác";
}
return name;
};
specimenStatusString = (value) => {
//Khai báo const
let name = "";
if (value == 1) {
name = "Tốt";
} else if (value == 2) {
name = "Tán huyết";
} else if (value == 3) {
name = "Thiếu thể tích";
} else if (value == 4) {
name = "Có máu cục đông";
} else if (value == 5) {
name = "Khác";
}
return name;
};
search() {
this.props.getLoading(true);
this.setState({ page: 0 }, function () {
var searchObject = {};
searchObject.text = this.state.keyword;
searchObject.pageIndex = this.state.page + 1;
searchObject.pageSize = this.state.rowsPerPage;
searchObject.belongTo = 1; // mẫu thuộc về Viral Load
searchByPage(searchObject)
.then(({ data }) => {
let itemListClone = [...data.content];
this.setState({
itemList: itemListClone,
totalElements: data.totalElements,
});
this.props.getLoading(false);
})
.catch(() => {
toast.error("Đã có lỗi hệ thống");
this.setState({ showOpenDialogError: true });
this.props.getLoading(false);
});
});
}
updatePageData = () => {
this.props.getLoading(true);
var searchObject = {};
searchObject.text = this.state.keyword;
searchObject.pageIndex = this.state.page + 1;
searchObject.pageSize = this.state.rowsPerPage;
searchObject.belongTo = 1; // mẫu thuộc về Viral Load
searchByPage(searchObject)
.then(({ data }) => {
let itemListClone = [...data.content];
this.setState({
itemList: itemListClone,
totalElements: data.totalElements,
});
this.props.getLoading(false);
})
.catch(() => {
toast.error("Đã có lỗi hệ thống");
this.setState({ showOpenDialogError: true });
this.props.getLoading(false);
});
};
handleDownload = () => {
var blob = new Blob(["Hello, world!"], {
type: "text/plain;charset=utf-8",
});
saveAs(blob, "hello world.txt");
};
handleDialogClose = () => {
this.setState(
{
shouldOpenUploadExcelResultDialog: false,
shouldOpenEditorDialog: false,
shouldOpenConfirmationDialog: false,
shouldOpenConfirmationDeleteAllDialog: false,
openPopupShowResult: false,
textPopup: "",
},
() => this.updatePageData()
);
};
handleOKEditClose = () => {
this.setState({
shouldOpenUploadExcelResultDialog: false,
shouldOpenEditorDialog: false,
shouldOpenConfirmationDialog: false,
});
this.updatePageData();
};
handleConfirmationResponse = () => {
let { t } = this.props;
this.props.getLoading(true);
this.handleDialogClose();
deleteItem(this.state.id)
.then((result) => {
if (result.data) {
this.updatePageData();
toast.success(t("deleteSuccess"));
} else {
toast.warning("Mẫu đã được gửi, không thể xóa");
}
this.props.getLoading(false);
})
.catch(() => {
this.props.getLoading(false);
toast.warning("Đã có lỗi khi xóa");
this.handleDialogClose();
});
};
componentDidMount() {
this.updatePageData();
};
handleEditItem = (item) => {
this.setState({
item: item,
shouldOpenEditorDialog: true,
});
};
handleDelete = (id) => {
this.setState({
id,
shouldOpenConfirmationDialog: true,
});
};
handleDeleteAll = (event) => {
this.props.getLoading(true);
this.setState({ shouldOpenConfirmationDeleteAllDialog: false });
deleteByList(this.data)
.then((result) => {
this.setState({
isLoading: false,
openPopupShowResult: true,
textPopup: (
<pre dangerouslySetInnerHTML={{ __html: result.data.message }} />
),
});
this.props.getLoading(false);
})
.catch(() => {
toast.error("Đã có lỗi hệ thống");
this.setState({ showOpenDialogError: true });
this.props.getLoading(false);
this.updatePageData();
});
};
handleCollapseFilter = () => {
let { checkedFilter } = this.state;
this.setState({ checkedFilter: !checkedFilter });
};
handleFilter = (option, actions) => {
const { t } = this.props;
const { niheCodeFrom, niheCodeTo, receiverDateFilter, org } = option;
var searchObject = {};
this.setState({ page: 1, loading: true });
searchObject.niheCodeFrom = niheCodeFrom;
searchObject.niheCodeTo = niheCodeTo;
searchObject.receiverDate = receiverDateFilter;
searchObject.filterOrg = org;
searchObject.belongTo = 1; // mẫu thuộc về Viral Load
searchObject.pageIndex = this.state.page;
searchObject.pageSize = 10000;
searchByPage(searchObject)
.then(({ data }) => {
let itemListClone = [...data.content];
this.setState({
itemList: itemListClone,
totalElements: data.totalElements,
});
})
.catch(() => {
this.setState({
itemListClone: [],
loading: false,
});
toast.error(t("general.error"));
});
if (actions === "clear") {
var searchObject = {};
searchObject.text = this.state.keyword;
searchObject.pageIndex = 1;
searchObject.pageSize = 10000;
searchObject.belongTo = 1; // mẫu thuộc về Viral Load
searchByPage(searchObject).then(({ data }) => {
let itemListClone = [...data.content];
this.setState({
itemList: itemListClone,
totalElements: data.totalElements,
});
});
return null;
}
};
render() {
const { t, i18n } = this.props;
let {
keyword,
itemList,
page,
rowsPerPage,
shouldOpenConfirmationDialog,
shouldOpenEditorDialog,
shouldOpenConfirmationDeleteAllDialog,
checkedFilter,
showOpenDialogError,
} = this.state;
let columns = [
{
title: t("general.STT"),
field: "code",
align: "center",
width: "60",
render: (rowData) => page * rowsPerPage + (rowData.tableData.id + 1),
headerStyle: {
minWidth: "60px",
paddingRight: "0px",
textAlign: "center",
},
cellStyle: {
minWidth: "60px",
paddingRight: "50px",
textAlign: "center",
},
},
{
title: t("general.action"),
field: "custom",
align: "left",
width: "250",
render: (rowData) => (
<MaterialButton
item={rowData}
onSelect={(rowData, method) => {
if (method === 0) {
this.props.getLoading(true);
getById(rowData.id)
.then(({ data }) => {
if (data.parent === null) {
data.parent = {};
}
this.setState({
item: data,
shouldOpenEditorDialog: true,
});
this.props.getLoading(false);
})
.catch(() => {
toast.error("Đã có lỗi hệ thống");
this.setState({ showOpenDialogError: true });
this.props.getLoading(false);
});
} else if (method === 1) {
this.handleDelete(rowData.id);
} else {
alert("Call Selected Here:" + rowData.id);
}
}}
/>
),
},
{
title: t("specimen.code"),
field: "niheCode",
width: "150",
headerStyle: {
minWidth: "100px",
paddingRight: "0px",
textAlign: "center",
},
cellStyle: {
minWidth: "100px",
// paddingLeft: "10px",
paddingRight: "0px",
textAlign: "center",
},
},
{
title: t("specimen.numberOfTest"),
field: "numberOfTests",
width: "150",
headerStyle: {
minWidth: "100px",
paddingRight: "0px",
textAlign: "center",
},
cellStyle: {
minWidth: "100px",
// paddingLeft: "10px",
paddingRight: "0px",
textAlign: "center",
},
},
{
title: t("specimen.type"),
field: "specimenType.name", //nó đang là 1 đối tượng -> chuyển 1 trường trong 1 đói tượng
align: "left",
width: "150",
headerStyle: {
minWidth: "100px",
paddingRight: "0px",
textAlign: "center",
},
cellStyle: {
minWidth: "100px",
// paddingLeft: "10px",
paddingRight: "0px",
textAlign: "center",
},
},
{
title: t("Mã bệnh nhân"),
field: "patientCode",
width: "150",
headerStyle: {
minWidth: "100px",
paddingRight: "0px",
textAlign: "center",
},
cellStyle: {
minWidth: "100px",
// paddingLeft: "10px",
paddingRight: "0px",
textAlign: "center",
},
},
// {
// title: t("Loại mẫu"),
// field: "specimenType",
// align: "left",
// width: "150",
// headerStyle: {
// minWidth: "100px",
// paddingRight: "0px",
// textAlign: "center",
// },
// cellStyle: {
// minWidth: "100px",
// // paddingLeft: "10px",
// paddingRight: "0px",
// textAlign: "center",
// },
// render: rowData => this.specimenTypeString(rowData.specimenType)
// },
{
title: t("specimen.specimenDate"),
field: "specimenDate",
align: "center",
width: "150",
headerStyle: {
minWidth: "100px",
paddingRight: "0px",
textAlign: "center",
},
cellStyle: {
minWidth: "100px",
// paddingLeft: "10px",
paddingRight: "0px",
// textAlign: "center",
},
render: (rowData) =>
rowData.specimenDate ? (
<span>{moment(rowData.specimenDate).format("DD/MM/YYYY")}</span>
) : (
""
),
},
{
title: t("specimen.receiverDate"),
field: "receiverDate",
align: "center",
width: "150",
headerStyle: {
minWidth: "100px",
paddingRight: "0px",
textAlign: "center",
},
cellStyle: {
minWidth: "100px",
// paddingLeft: "10px",
paddingRight: "0px",
// textAlign: "center",
},
render: (rowData) =>
rowData.receiverDate ? (
<span>{moment(rowData.receiverDate).format("DD/MM/YYYY")}</span>
) : (
""
),
},
{
title: t("specimen.status"),
field: "specimenStatus",
align: "center",
width: "150",
headerStyle: {
minWidth: "100px",
paddingRight: "0px",
},
cellStyle: {
minWidth: "100px",
// paddingLeft: "10px",
paddingRight: "0px",
// textAlign: "center",
},
render: (rowData) => this.specimenStatusString(rowData.specimenStatus),
},
];
return (
<div className="m-sm-30">
<div className="mb-sm-30">
<Breadcrumb routeSegments={[{ name: t("specimen.titleName") }]} />
</div>
<Grid container spacing={3}>
<Grid item xs={12} container spacing={2}>
<Grid item lg={6} md={6} sm={12} xs={12}>
<Button
className="mb-16 mr-16 align-bottom"
variant="contained"
color="primary"
onClick={() => {
this.handleEditItem({
startDate: new Date(),
endDate: new Date(),
isAddnew: true,
});
}}
>
{t("general.add")}
</Button>
<Button
className="mb-16 mr-36 align-bottom"
variant="contained"
color="primary"
onClick={() =>
this.setState({ shouldOpenConfirmationDeleteAllDialog: true })
}
>
{t("general.delete")}
</Button>
{/* import excel */}
<Button
className="mb-16 mr-16 align-bottom"
variant="contained"
color="primary"
onClick={() =>
this.setState({ shouldOpenUploadExcelResultDialog: true })
}
>
{t("general.importExcel")}
</Button>
</Grid>
{shouldOpenConfirmationDeleteAllDialog && (
<ConfirmationDialog
open={shouldOpenConfirmationDeleteAllDialog}
onConfirmDialogClose={this.handleDialogClose}
onYesClick={this.handleDeleteAll}
title={t("general.confirm")}
text={t("Xác nhận xóa")}
Yes={t("general.Yes")}
No={t("general.No")}
/>
)}
<Grid item md={6} lg={6} sm={12} xs={12}>
<Grid container spacing={2}>
<Grid item lg={8} md={8} sm={6} xs={6}>
<FormControl fullWidth>
<Input
className="mt-10 search_box w-100 stylePlaceholder"
type="text"
name="keyword"
value={keyword}
onChange={this.handleTextChange}
onKeyDown={this.handleKeyDownEnterSearch}
placeholder={t("general.enterSearch")}
id="search_box"
startAdornment={
<InputAdornment>
<Link to="#">
{" "}
<SearchIcon
onClick={() => this.search(keyword)}
style={{
position: "absolute",
top: "0",
right: "0",
}}
/>
</Link>
</InputAdornment>
}
/>
</FormControl>
</Grid>
<Grid item lg={4} md={4} sm={6} xs={6}>
<Button
className="btn_s_right d-inline-flex btn btn-primary-d"
variant="contained"
onClick={this.handleCollapseFilter}
fullWidth
color="primary"
>
<FilterListIcon />
<span>{t("general.filter")}</span>
<ArrowDropDownIcon
style={
this.state.checkedFilter == true
? {
transform: "rotate(180deg)",
transition: ".3s",
paddingRight: 5,
}
: {
transform: "rotate(0deg)",
transition: ".3s",
paddingLeft: 5,
}
}
/>
</Button>
</Grid>
</Grid>
</Grid>
<Grid item md={12} sm={12} xs={12}>
<Collapse
in={checkedFilter}
style={{
width: "100%",
}}
>
<SpecimenFilter handleFilter={this.handleFilter} t={t} />
</Collapse>
</Grid>
</Grid>
<Grid item xs={12}>
<div>
{shouldOpenEditorDialog && (
<SpecimenEditorDialog
t={t}
i18n={i18n}
handleClose={this.handleDialogClose}
open={shouldOpenEditorDialog}
handleOKEditClose={this.handleOKEditClose}
item={this.state.item ? this.state.item : {}}
/>
)}
{this.state.shouldOpenUploadExcelResultDialog && (
<UploadExcelDialog
t={t}
i18n={i18n}
handleClose={this.handleDialogClose}
open={this.state.shouldOpenUploadExcelResultDialog}
handleOKEditClose={this.handleOKEditClose}
enableConfirm={true}
confirmMessage={
"Tải lên sẽ xóa các thuộc tính cũ của mẫu, bạn có chắc chắn?"
}
acceptType="xlsm;xls;xlsx"
uploadUrl={ ConstantList.API_ENPOINT + "/api/uploadExcel/specimen/false" }
saveListDataUrl = { ConstantList.API_ENPOINT + "/api/specimen/saveOrUpdateList"}
/>
)}
{shouldOpenConfirmationDialog && (
<ConfirmationDialog
title={t("general.confirm")}
open={shouldOpenConfirmationDialog}
onConfirmDialogClose={this.handleDialogClose}
onYesClick={this.handleConfirmationResponse}
text={t("general.DeleteConfirm")}
Yes={t("general.Yes")}
No={t("general.No")}
/>
)}
{this.state.openPopupShowResult && (
<NotificationPopup
title={t("general.noti")}
open={this.state.openPopupShowResult}
onYesClick={this.handleDialogClose}
text={this.state.textPopup}
size="lg"
agree={t("general.agree")}
/>
)}
</div>
<MaterialTable
title={t("")}
data={itemList}
columns={columns}
// parentChildData={(row, rows) => rows.find(a => a.id === row.parentId)}
parentChildData={(row, rows) => {
var list = rows.find((a) => a.id === row.parentId);
return list;
}}
options={{
selection: true,
actionsColumnIndex: -1,
paging: false,
search: false,
rowStyle: (rowData, index) => ({
backgroundColor: index % 2 === 1 ? "#EEE" : "#FFF",
}),
maxBodyHeight: "450px",
minBodyHeight: "370px",
headerStyle: {
backgroundColor: "#358600",
color: "#fff",
},
padding: "dense",
toolbar: false,
}}
components={{
Toolbar: (props) => <MTableToolbar {...props} />,
}}
onSelectionChange={(rows) => {
this.data = rows;
}}
actions={[
{
tooltip: "Remove All Selected Users",
icon: "delete",
onClick: (evt, data) => {
this.handleDeleteAll(data);
alert("You want to delete " + data.length + " rows");
},
},
]}
/>
<TablePagination
align="left"
className="px-16"
rowsPerPageOptions={[1, 2, 5, 10, 25, 50, 100]}
component="div"
labelRowsPerPage={t("general.rows_per_page")}
labelDisplayedRows={({ from, to, count }) =>
`${from}-${to} ${t("general.of")} ${
count !== -1 ? count : `more than ${to}`
}`
}
count={this.state.totalElements}
rowsPerPage={this.state.rowsPerPage}
page={this.state.page}
backIconButtonProps={{
"aria-label": "Previous Page",
}}
nextIconButtonProps={{
"aria-label": "Next Page",
}}
onChangePage={this.handleChangePage}
onChangeRowsPerPage={this.setRowsPerPage}
/>
</Grid>
{showOpenDialogError && (
<NotificationPopup
title={t("general.noti")}
open={this.state.showOpenDialogError}
onYesClick={this.setState({ showOpenDialogError: false })}
text={"Đã có lỗi hệ thống"}
size="lg"
agree={t("confirm")}
/>
)}
</Grid>
</div>
);
}
}
const mapStateToProps = (state) => ({
loading: state.loading.loading,
});
const mapDispatch = {
getLoading,
};
export default connect(mapStateToProps, mapDispatch)(Specimen); |
import java.util.HashMap;
import java.util.Map;
public class CustomerStorage {
private final Map<String, Customer> storage;
public CustomerStorage() {
storage = new HashMap<>();
}
public void addCustomer(String data) {
final int INDEX_NAME = 0;
final int INDEX_SURNAME = 1;
final int INDEX_EMAIL = 2;
final int INDEX_PHONE = 3;
if (data==null){
throw new NullPointerException("Неверный формат ввода");
}
String[] components = data.split("\\s+");
if (components.length!=4){
throw new IllegalArgumentException("Неверный формат добавления. Правильный формат ввода: " + "Василий Петров vasily.petrov@gmail.com +79215637722");
}
if (!components[INDEX_PHONE].matches("\\+\\d+")){
throw new IllegalArgumentException("Неверный формат телефона");
}
if (!components[INDEX_EMAIL].matches(".+@.+")){
throw new IllegalArgumentException("Неверный формат email");
}
String name = components[INDEX_NAME] + " " + components[INDEX_SURNAME];
storage.put(name, new Customer(name, components[INDEX_PHONE], components[INDEX_EMAIL]));
}
public void listCustomers() {
storage.values().forEach(System.out::println);
}
public void removeCustomer(String name) {
storage.remove(name);
}
public Customer getCustomer(String name) {
return storage.get(name);
}
public int getCount() {
return storage.size();
}
} |
// - Return `false` if the input string is empty or contains only whitespace characters.
// - Return `false` if the generated hashtag string is longer than 140 characters.
// - Every word in the hashtag should start with a capital letter.
// - The input string may contain leading/trailing whitespace characters.
/**
* Generates a hashtag from the input string.
* @param {string} str - The input string.
* @returns {string|boolean} - The generated hashtag string or false.
*/
function generateHashtag(str) {
if (str.trim() === "") {
return false;
}
const words = str.trim().split(/\s+/);
const capialized = words.map((word) => word.at(0).toUpperCase() + word.slice(1));
const hashtag = capialized.join("")
if (hashtag.length > 140) {
return false;
} else {
return `#${hashtag}`;
}
}
module.exports = generateHashtag; |
$(document).ready(function () {
const ckeditorName = $('.ckStudent').attr('name');
console.log(ckeditorName);
CKEDITOR.replace(ckeditorName, {
// Define the toolbar: https://ckeditor.com/docs/ckeditor4/latest/features/toolbar.html
// The full preset from CDN which we used as a base provides more features than we need.
// Also by default it comes with a 3-line toolbar. Here we put all buttons in a single row.
toolbar: [
{ name: 'document', items: ['Print'] },
{ name: 'clipboard', items: ['Undo', 'Redo'] },
{ name: 'styles', items: ['Format', 'Font', 'FontSize'] },
{ name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'RemoveFormat', 'CopyFormatting'] },
{ name: 'colors', items: ['TextColor', 'BGColor'] },
{ name: 'align', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] },
{ name: 'links', items: ['Link', 'Unlink'] },
{ name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote'] },
{ name: 'insert', items: ['Table'] },
{ name: 'tools', items: ['Maximize'] },
{ name: 'editing', items: ['Scayt'] }
],
// Since we define all configuration options here, let's instruct CKEditor to not load config.js which it does by default.
// One HTTP request less will result in a faster startup time.
// For more information check https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-customConfig
customConfig: '',
// Sometimes applications that convert HTML to PDF prefer setting image width through attributes instead of CSS styles.
// For more information check:
// - About Advanced Content Filter: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_advanced_content_filter.html
// - About Disallowed Content: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_disallowed_content.html
// - About Allowed Content: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_allowed_content_rules.html
disallowedContent: 'img{width,height,float}',
extraAllowedContent: 'img[width,height,align]',
// Enabling extra plugins, available in the full-all preset: https://ckeditor.com/cke4/presets-all
extraPlugins: '',
/*********************** File management support ***********************/
// In order to turn on support for file uploads, CKEditor has to be configured to use some server side
// solution with file upload/management capabilities, like for example CKFinder.
// For more information see https://ckeditor.com/docs/ckeditor4/latest/guide/dev_ckfinder_integration.html
// Uncomment and correct these lines after you setup your local CKFinder instance.
// filebrowserBrowseUrl: 'http://example.com/ckfinder/ckfinder.html',
// filebrowserUploadUrl: 'http://example.com/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
/*********************** File management support ***********************/
// Make the editing area bigger than default.
height: 800,
// An array of stylesheets to style the WYSIWYG area.
// Note: it is recommended to keep your own styles in a separate file in order to make future updates painless.
contentsCss: ['https://cdn.ckeditor.com/4.8.0/full-all/contents.css', 'mystyles.css'],
// This is optional, but will let us define multiple different styles for multiple editors using the same CSS file.
bodyClass: 'document-editor',
// Reduce the list of block elements listed in the Format dropdown to the most commonly used.
format_tags: 'p;h1;h2;h3;pre',
// Simplify the Image and Link dialog windows. The "Advanced" tab is not needed in most cases.
removeDialogTabs: 'image:advanced;link:advanced',
// Define the list of styles which should be available in the Styles dropdown list.
// If the "class" attribute is used to style an element, make sure to define the style for the class in "mystyles.css"
// (and on your website so that it rendered in the same way).
// Note: by default CKEditor looks for styles.js file. Defining stylesSet inline (as below) stops CKEditor from loading
// that file, which means one HTTP request less (and a faster startup).
// For more information see https://ckeditor.com/docs/ckeditor4/latest/features/styles.html
stylesSet: [
/* Inline Styles */
{ name: 'Marker', element: 'span', attributes: { 'class': 'marker' } },
{ name: 'Cited Work', element: 'cite' },
{ name: 'Inline Quotation', element: 'q' },
/* Object Styles */
{
name: 'Special Container',
element: 'div',
styles: {
padding: '5px 10px',
background: '#eee',
border: '1px solid #ccc'
}
},
{
name: 'Compact table',
element: 'table',
attributes: {
cellpadding: '5',
cellspacing: '0',
border: '1',
bordercolor: '#ccc'
},
styles: {
'border-collapse': 'collapse'
}
},
{ name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
{ name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }
]
});
}); |
****************************************************************************************************************************
--TO CREATE THE TABLE
****************************************************************************************************************************
CREATE TABLE naresh_family
(
S_NO varchar(10),
Name varchar(20),
AGE integer,
OCCUPATION varchar(50),
DESIGNATION varchar(30)
)
****************************************************************************************************************************
--TO INSERT A ROW IN TABLE
****************************************************************************************************************************
INSERT INTO naresh_family
(
S_NO,
Name,
AGE,
OCCUPATION,
DESIGNATION
)
VALUES
(
'2',
'NARESH',
'25',
'DBS BANK',
'Business Analyst'
)
****************************************************************************************************************************
--TO DELETE A ROW IN TABLE
****************************************************************************************************************************
DELETE FROM naresh_family
WHERE Name = 'Priya'
****************************************************************************************************************************
--TO UPDATE A ROW IN TABLE
****************************************************************************************************************************
UPDATE naresh_family
SET
Name = 'Priya',
Age = '23',
Occupation = 'RC Build Fly',
Designation = 'Finance Manager'
WHERE
S_No = '2';
****************************************************************************************************************************
--SQL SELECT DISTINCT Syntax
****************************************************************************************************************************
--In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values.
--The DISTINCT keyword can be used to return only distinct (different) values.
--SELECT DISTINCT Syntax
SELECT DISTINCT column_name,column_name
FROM table_name;
--SELECT DISTINCT Example
SELECT DISTINCT Name,OCCUPATION
FROM naresh_family;
****************************************************************************************************************************
--SQL WHERE Clause
****************************************************************************************************************************
--The WHERE clause is used to extract only those records that fulfill a specified criterion.
--SQL WHERE Syntax
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
--WHERE Clause Example
SELECT Name,Designation
FROM naresh_family
WHERE S_NO = '1';
****************************************************************************************************************************
--SQL AND Operators
****************************************************************************************************************************
--The AND operator displays a record if both the first condition AND the second condition are true.
--SQL AND Syntax
SELECT * FROM naresh_family
WHERE DESIGNATION = 'Business Analyst'
AND OCCUPATION = 'DBS Bank';
****************************************************************************************************************************
--SQL OR Operators
****************************************************************************************************************************
--The OR operator displays a record if either the first condition OR the second condition is true.
--SQL OR Syntax
SELECT * FROM naresh_family
WHERE DESIGNATION = 'Business Analyst'
OR OCCUPATION = 'HOSPITAL';
****************************************************************************************************************************
--Combining AND & OR
****************************************************************************************************************************
--You can also combine AND and OR (use parenthesis to form complex expressions).
SELECT * FROM naresh_family
WHERE DESIGNATION = 'Business Analyst'
AND
(
OCCUPATION = 'HOSPITAL'
OR
OCCUPATION = 'DBS Bank'
);
****************************************************************************************************************************
--SQL ORDER BY Keyword
****************************************************************************************************************************
--The ORDER BY keyword is used to sort the result-set by one or more columns.
--The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword.
--SQL ORDER BY Syntax
SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;
--SQL WHERE Clause Example
SELECT Name, OCCUPATION
FROM naresh_family
ORDER BY S_NO desc
****************************************************************************************************************************
--SQL ROWNUM BY Keyword
****************************************************************************************************************************
SELECT * FROM naresh_family
WHERE ROWNUM<=3; |
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2023 Tokemak Foundation. All rights reserved.
pragma solidity 0.8.17;
import { Test } from "forge-std/Test.sol";
import { Stats } from "src/stats/Stats.sol";
import { SystemRegistry } from "src/SystemRegistry.sol";
import { AccessController } from "src/security/AccessController.sol";
import {
TOKE_MAINNET,
WETH_MAINNET,
RETH_MAINNET,
BAL_VAULT,
RETH_WETH_BAL_POOL,
WSTETH_MAINNET
} from "test/utils/Addresses.sol";
import { Roles } from "src/libs/Roles.sol";
import { Errors } from "src/utils/Errors.sol";
import { IStatsCalculator } from "src/interfaces/stats/IStatsCalculator.sol";
import { IStatsCalculatorRegistry } from "src/interfaces/stats/IStatsCalculatorRegistry.sol";
import { ILSTStats } from "src/interfaces/stats/ILSTStats.sol";
import { ISystemRegistry } from "src/interfaces/ISystemRegistry.sol";
import { IDexLSTStats } from "src/interfaces/stats/IDexLSTStats.sol";
import { IRootPriceOracle } from "src/interfaces/oracles/IRootPriceOracle.sol";
import { IERC20Metadata } from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { BalancerStablePoolCalculatorBase } from "src/stats/calculators/base/BalancerStablePoolCalculatorBase.sol";
import { IVault } from "src/interfaces/external/balancer/IVault.sol";
import { IBalancerPool } from "src/interfaces/external/balancer/IBalancerPool.sol";
import { IProtocolFeesCollector } from "src/interfaces/external/balancer/IProtocolFeesCollector.sol";
import { IERC20 } from "openzeppelin-contracts/token/ERC20/IERC20.sol";
import { StatsCalculatorRegistry } from "src/stats/StatsCalculatorRegistry.sol";
import { StatsCalculatorFactory } from "src/stats/StatsCalculatorFactory.sol";
import { RethLSTCalculator } from "src/stats/calculators/RethLSTCalculator.sol";
import { LSTCalculatorBase } from "src/stats/calculators/base/LSTCalculatorBase.sol";
import { IBalancerMetaStablePool } from "src/interfaces/external/balancer/IBalancerMetaStablePool.sol";
import { RootPriceOracle } from "src/oracles/RootPriceOracle.sol";
import { IRootPriceOracle } from "src/interfaces/oracles/IRootPriceOracle.sol";
contract BalancerStablePoolCalculatorBaseTest is Test {
uint256 private constant TARGET_BLOCK = 17_580_732;
uint256 private constant TARGET_BLOCK_TIMESTAMP = 1_687_990_535;
uint256 private constant TARGET_BLOCK_VIRTUAL_PRICE = 1_023_521_727_648_403_073;
uint256 private constant TARGET_BLOCK_RETH_BACKING = 1_075_219_009_833_433_231;
uint256 private constant TARGET_BLOCK_RESERVE_0 = 22_043_317_920_246_255_530_254;
uint256 private constant TARGET_BLOCK_RESERVE_1 = 23_967_981_419_922_593_304_842;
// solhint-disable-next-line max-line-length
bytes32 private constant RETH_WETH_POOL_ID = 0x1e19cf2d73a72ef1332c882f20534b6519be0276000200000000000000000112; //gitleaks:allow
SystemRegistry private systemRegistry;
AccessController private accessController;
StatsCalculatorRegistry private statsRegistry;
StatsCalculatorFactory private statsFactory;
RethLSTCalculator private rETHStats;
RootPriceOracle private rootPriceOracle;
address private immutable mockWstethStats = vm.addr(1003);
TestBalancerCalculator private calculator;
event DexSnapshotTaken(uint256 snapshotTimestamp, uint256 priorFeeApr, uint256 newFeeApr, uint256 unfilteredFeeApr);
function setUp() public {
vm.createSelectFork(vm.envString("MAINNET_RPC_URL"), TARGET_BLOCK);
systemRegistry = new SystemRegistry(TOKE_MAINNET, WETH_MAINNET);
accessController = new AccessController(address(systemRegistry));
systemRegistry.setAccessController(address(accessController));
accessController.grantRole(Roles.STATS_SNAPSHOT_ROLE, address(this));
statsRegistry = new StatsCalculatorRegistry(systemRegistry);
systemRegistry.setStatsCalculatorRegistry(address(statsRegistry));
statsFactory = new StatsCalculatorFactory(systemRegistry);
statsRegistry.setCalculatorFactory(address(statsFactory));
rootPriceOracle = new RootPriceOracle(systemRegistry);
systemRegistry.setRootPriceOracle(address(rootPriceOracle));
rETHStats = new RethLSTCalculator(systemRegistry);
bytes32[] memory rETHDepAprIds = new bytes32[](0);
LSTCalculatorBase.InitData memory rETHInitData = LSTCalculatorBase.InitData({ lstTokenAddress: RETH_MAINNET });
mockTokenPrice(RETH_MAINNET, 1e18); // required for stats init
rETHStats.initialize(rETHDepAprIds, abi.encode(rETHInitData));
vm.prank(address(statsFactory));
statsRegistry.register(address(rETHStats));
calculator = new TestBalancerCalculator(systemRegistry, BAL_VAULT);
}
function testConstructorShouldRevertIfBalancerVaultZeroAddress() public {
vm.expectRevert(abi.encodeWithSelector(Errors.ZeroAddress.selector, "_balancerVault"));
new TestBalancerCalculator(systemRegistry, address(0));
}
function testConstructorShouldSetBalVault() public {
assertEq(address(calculator.balancerVault()), BAL_VAULT);
}
function testInitializeRevertIfPoolAddressIsZero() public {
bytes32[] memory depAprIds = new bytes32[](2);
bytes memory initData = getInitData(address(0));
vm.expectRevert(abi.encodeWithSelector(Errors.ZeroAddress.selector, "poolAddress"));
calculator.initialize(depAprIds, initData);
}
function testInitializeRevertIfPoolIdIsEmpty() public {
bytes32[] memory depAprIds = new bytes32[](2);
bytes memory initData = getInitData(RETH_WETH_BAL_POOL);
mockPoolId(RETH_WETH_BAL_POOL, bytes32(0));
vm.expectRevert(
abi.encodeWithSelector(BalancerStablePoolCalculatorBase.InvalidPoolId.selector, RETH_WETH_BAL_POOL)
);
calculator.initialize(depAprIds, initData);
}
function testInitializeRevertIfNumTokensIsZero() public {
bytes32[] memory depAprIds = new bytes32[](2);
bytes memory initData = getInitData(RETH_WETH_BAL_POOL);
address[] memory tokens = new address[](0);
uint256[] memory balances = new uint256[](0);
mockGetPoolTokens(RETH_WETH_POOL_ID, tokens, balances);
vm.expectRevert(
abi.encodeWithSelector(BalancerStablePoolCalculatorBase.InvalidPool.selector, RETH_WETH_BAL_POOL)
);
calculator.initialize(depAprIds, initData);
}
function testInitializeRevertIfNumTokenDependentAprIdsMismatch() public {
bytes32[] memory depAprIds = new bytes32[](2);
bytes memory initData = getInitData(RETH_WETH_BAL_POOL);
address[] memory tokens = new address[](1);
uint256[] memory balances = new uint256[](1);
mockGetPoolTokens(RETH_WETH_POOL_ID, tokens, balances);
vm.expectRevert(
abi.encodeWithSelector(BalancerStablePoolCalculatorBase.DependentAprIdsMismatchTokens.selector, 2, 1)
);
calculator.initialize(depAprIds, initData);
}
function testInitializeRevertIfStatsAddressNotMatch() public {
bytes32[] memory depAprIds = new bytes32[](2);
depAprIds[0] = keccak256(abi.encode(RETH_MAINNET));
bytes memory initData = getInitData(RETH_WETH_BAL_POOL);
mockGetCalculator(depAprIds[0], mockWstethStats); // resolve to the wrong calculator
mockStatsAddress(mockWstethStats, WSTETH_MAINNET);
vm.expectRevert(
abi.encodeWithSelector(Stats.CalculatorAssetMismatch.selector, depAprIds[0], mockWstethStats, RETH_MAINNET)
);
calculator.initialize(depAprIds, initData);
}
function testInitializeSuccessfully() public {
initializeSuccessfully();
assertEq(calculator.numTokens(), 2);
assertEq(address(calculator.lstStats(0)), address(rETHStats));
assertEq(address(calculator.lstStats(1)), address(0));
assertEq(calculator.reserveTokens(0), RETH_MAINNET);
assertEq(calculator.reserveTokens(1), WETH_MAINNET);
assertEq(calculator.poolId(), RETH_WETH_POOL_ID);
assertEq(calculator.getAddressId(), RETH_WETH_BAL_POOL);
assertEq(calculator.getAprId(), Stats.generateBalancerPoolIdentifier(RETH_WETH_BAL_POOL));
assertEq(calculator.lastSnapshotTimestamp(), TARGET_BLOCK_TIMESTAMP);
assertEq(calculator.feeApr(), 0);
assertEq(calculator.lastVirtualPrice(), TARGET_BLOCK_VIRTUAL_PRICE);
assertEq(calculator.lastEthPerShare(0), TARGET_BLOCK_RETH_BACKING);
assertEq(calculator.lastEthPerShare(1), 0);
}
function testShouldNotSnapshotIfNotReady() public {
initializeSuccessfully();
assertFalse(calculator.shouldSnapshot());
vm.expectRevert(abi.encodeWithSelector(IStatsCalculator.NoSnapshotTaken.selector));
calculator.snapshot();
}
function testShouldSnapshot() public {
initializeSuccessfully();
assertFalse(calculator.shouldSnapshot());
uint256 newTimestamp = TARGET_BLOCK_TIMESTAMP + Stats.DEX_FEE_APR_FILTER_INIT_INTERVAL;
vm.warp(newTimestamp);
assertTrue(calculator.shouldSnapshot());
assertEq(calculator.feeApr(), 0);
uint256 newVirtualPrice = TARGET_BLOCK_VIRTUAL_PRICE * 109 / 100; // increase by 9% over 9 days
uint256 newEthPerShare = TARGET_BLOCK_RETH_BACKING * 109 / 100; // increase by 9% over 9 days
mockVirtualPrice(newVirtualPrice);
mockStatsEthPerToken(address(rETHStats), newEthPerShare);
mockTokenPrice(RETH_MAINNET, 1e18);
mockTokenPrice(WETH_MAINNET, 1e18);
vm.expectEmit(true, true, true, false);
emit DexSnapshotTaken(0, 0, 0, 0);
calculator.snapshot();
uint256 totalReserves = TARGET_BLOCK_RESERVE_0 + TARGET_BLOCK_RESERVE_1;
uint256 baseApr = ((1e16 * 365) * TARGET_BLOCK_RESERVE_0) / totalReserves;
uint256 baseAprLessAdmin = baseApr * 5e17 / 1e18; // 50% admin fee
// 5% annualized for virtual price change
uint256 rawFeeApr = 1e16 * 365;
// calculate filtered feeApr with a starting 0
uint256 expectedFeeApr = (rawFeeApr - baseAprLessAdmin);
assertEq(calculator.lastSnapshotTimestamp(), newTimestamp);
assertEq(calculator.lastVirtualPrice(), newVirtualPrice);
assertEq(calculator.lastEthPerShare(0), newEthPerShare); // rETH
assertEq(calculator.lastEthPerShare(1), 0); // weth
assertApproxEqAbs(calculator.feeApr(), expectedFeeApr, 50); // allow for rounding errors
}
function testSnapshotShouldHandleZeroReserves() public {
initializeSuccessfully();
assertFalse(calculator.shouldSnapshot());
uint256 newTimestamp = TARGET_BLOCK_TIMESTAMP + Stats.DEX_FEE_APR_FILTER_INIT_INTERVAL;
vm.warp(newTimestamp);
assertTrue(calculator.shouldSnapshot());
assertEq(calculator.feeApr(), 0);
uint256 newVirtualPrice = TARGET_BLOCK_VIRTUAL_PRICE * 109 / 100; // increase by 9% over 9 days
uint256 newEthPerShare = TARGET_BLOCK_RETH_BACKING * 102 / 100; // increase by 2% over 9 days
mockVirtualPrice(newVirtualPrice);
mockStatsEthPerToken(address(rETHStats), newEthPerShare);
mockTokenPrice(RETH_MAINNET, 1e18);
mockTokenPrice(WETH_MAINNET, 1e18);
address[] memory tokens = new address[](2);
uint256[] memory balances = new uint256[](2); // set balances to zero
mockGetPoolTokens(RETH_WETH_POOL_ID, tokens, balances);
calculator.snapshot();
// NOTE: it isn't possible for virtual price to increase without any reserves
// but testing the edge case
uint256 expectedFeeApr = 9e16 / 9 * 365; // 9% annualized
assertApproxEqAbs(calculator.feeApr(), expectedFeeApr, 50);
}
function testSnapshotShouldClipNegativeFee() public {
initializeSuccessfully();
assertFalse(calculator.shouldSnapshot());
// move past allowed snapshot time
uint256 newTimestamp = TARGET_BLOCK_TIMESTAMP + Stats.DEX_FEE_APR_FILTER_INIT_INTERVAL;
vm.warp(newTimestamp);
assertTrue(calculator.shouldSnapshot());
assertEq(calculator.feeApr(), 0);
// increase virtual price and snapshot so that feeApr isn't 0
uint256 newVirtualPrice = TARGET_BLOCK_VIRTUAL_PRICE * 109 / 100; // increase by 9%
mockVirtualPrice(newVirtualPrice);
mockTokenPrice(RETH_MAINNET, 1e18);
mockTokenPrice(WETH_MAINNET, 1e18);
calculator.snapshot();
uint256 priorFeeApr = calculator.feeApr();
assertGt(priorFeeApr, 0);
newTimestamp += Stats.DEX_FEE_APR_SNAPSHOT_INTERVAL;
vm.warp(newTimestamp);
// increase virtualPrice by 1%
newVirtualPrice = newVirtualPrice * 101 / 100;
// increase rETH backing by 5% to fully offset the virtual price change
// 5% * ~50% reserve balance * 50% admin fee = 1.25%
uint256 newEthPerShare = TARGET_BLOCK_RETH_BACKING * 105 / 100; // increase by 5%
mockVirtualPrice(newVirtualPrice);
mockStatsEthPerToken(address(rETHStats), newEthPerShare);
mockTokenPrice(RETH_MAINNET, 1e18);
mockTokenPrice(WETH_MAINNET, 1e18);
calculator.snapshot();
// add a 0% to the filter
uint256 expectedFeeApr = priorFeeApr * 9e17 / 1e18;
assertEq(calculator.lastSnapshotTimestamp(), newTimestamp);
assertEq(calculator.lastVirtualPrice(), newVirtualPrice);
assertEq(calculator.lastEthPerShare(0), newEthPerShare); // rETH
assertEq(calculator.lastEthPerShare(1), 0); // weth
assertEq(calculator.feeApr(), expectedFeeApr);
}
function testCurrent() public {
initializeSuccessfully();
mockTokenPrice(RETH_MAINNET, 55e16); // set to arbitrary price
mockTokenPrice(WETH_MAINNET, 1e18); // set to 1:1
uint256[] memory emptyArr = new uint256[](0);
mockLSTData(address(rETHStats), 12, emptyArr, emptyArr);
IDexLSTStats.DexLSTStatsData memory current = calculator.current();
uint256 expectedReserve0 = TARGET_BLOCK_RESERVE_0 * 55e16 / 1e18;
assertEq(current.feeApr, 0);
assertEq(current.reservesInEth.length, 2);
assertEq(current.reservesInEth[0], expectedReserve0);
assertEq(current.reservesInEth[1], TARGET_BLOCK_RESERVE_1);
assertEq(current.lstStatsData.length, 2);
assertEq(current.lstStatsData[0].baseApr, 6); // reduced by bal admin fee
assertEq(current.lstStatsData[0].slashingCosts.length, 0);
assertEq(current.lstStatsData[0].slashingTimestamps.length, 0);
assertEq(current.lstStatsData[1].baseApr, 0);
assertEq(current.lstStatsData[1].slashingCosts.length, 0);
assertEq(current.lstStatsData[1].slashingTimestamps.length, 0);
assertEq(current.lastSnapshotTimestamp, TARGET_BLOCK_TIMESTAMP);
}
function testItShouldHandleReserveTokensDecimals() public {
mockTokenDecimals(RETH_MAINNET, 12); // set rETH to be 12 decimals instead of 18
initializeSuccessfully();
mockTokenPrice(RETH_MAINNET, 1e18); // set to 1:1
mockTokenPrice(WETH_MAINNET, 1e18); // set to 1:1
IDexLSTStats.DexLSTStatsData memory current = calculator.current();
assertEq(current.reservesInEth[0], TARGET_BLOCK_RESERVE_0 * 1e6); // pad by 18 vs 12 decimals
assertEq(current.reservesInEth[1], TARGET_BLOCK_RESERVE_1);
}
function initializeSuccessfully() internal {
bytes32[] memory depAprIds = new bytes32[](2);
depAprIds[0] = rETHStats.getAprId();
depAprIds[1] = Stats.NOOP_APR_ID;
bytes memory initData = getInitData(RETH_WETH_BAL_POOL);
calculator.initialize(depAprIds, initData);
}
function getInitData(address poolAddress) internal pure returns (bytes memory) {
return abi.encode(BalancerStablePoolCalculatorBase.InitData({ poolAddress: poolAddress }));
}
function mockPoolId(address pool, bytes32 res) internal {
vm.mockCall(pool, abi.encodeWithSelector(IBalancerPool.getPoolId.selector), abi.encode(res));
}
function mockGetPoolTokens(bytes32 poolId, address[] memory tokens, uint256[] memory balances) internal {
vm.mockCall(
BAL_VAULT, abi.encodeWithSelector(IVault.getPoolTokens.selector, poolId), abi.encode(tokens, balances)
);
}
function mockGetCalculator(bytes32 aprId, address stats) internal {
vm.mockCall(
address(statsRegistry),
abi.encodeWithSelector(IStatsCalculatorRegistry.getCalculator.selector, aprId),
abi.encode(IStatsCalculator(stats))
);
}
function mockStatsAddress(address stats, address res) internal {
vm.mockCall(stats, abi.encodeWithSelector(IStatsCalculator.getAddressId.selector), abi.encode(res));
}
function mockTokenPrice(address token, uint256 price) internal {
vm.mockCall(
address(rootPriceOracle),
abi.encodeWithSelector(IRootPriceOracle.getPriceInEth.selector, token),
abi.encode(price)
);
}
function mockLSTData(
address stats,
uint256 baseApr,
uint256[] memory slashingCosts,
uint256[] memory slashingTimestamps
) internal {
uint24[10] memory discountHistory;
uint40[5] memory discountTimestampByPercent;
ILSTStats.LSTStatsData memory res = ILSTStats.LSTStatsData({
lastSnapshotTimestamp: 0,
baseApr: baseApr,
discount: 0,
discountHistory: discountHistory,
discountTimestampByPercent: discountTimestampByPercent,
slashingCosts: slashingCosts,
slashingTimestamps: slashingTimestamps
});
vm.mockCall(stats, abi.encodeWithSelector(ILSTStats.current.selector), abi.encode(res));
}
function mockTokenDecimals(address token, uint8 decimals) internal {
vm.mockCall(token, abi.encodeWithSelector(IERC20Metadata.decimals.selector), abi.encode(decimals));
}
function mockVirtualPrice(uint256 virtualPrice) internal {
vm.mockCall(
RETH_WETH_BAL_POOL,
abi.encodeWithSelector(IBalancerMetaStablePool.getRate.selector),
abi.encode(virtualPrice)
);
}
function mockStatsEthPerToken(address stats, uint256 value) internal {
vm.mockCall(stats, abi.encodeWithSelector(ILSTStats.calculateEthPerToken.selector), abi.encode(value));
}
}
contract TestBalancerCalculator is BalancerStablePoolCalculatorBase {
constructor(
ISystemRegistry _systemRegistry,
address vault
) BalancerStablePoolCalculatorBase(_systemRegistry, vault) { }
function getVirtualPrice() internal view override returns (uint256) {
// Note: this does not correct for an issue related to balancer not accruing admin fees
return IBalancerMetaStablePool(poolAddress).getRate();
}
function getPoolTokens() internal view override returns (IERC20[] memory tokens, uint256[] memory balances) {
(tokens, balances,) = IVault(balancerVault).getPoolTokens(poolId);
}
} |
import "./userList.css"
import { DataGrid } from "@material-ui/data-grid";
import { DeleteOutline } from "@material-ui/icons";
import { userRows } from '../../dummyData'
import { Link } from 'react-router-dom'
import React, { useState } from 'react'
export default function UserList() {
const [data, setData] = useState(userRows);
const handleDelete = (id) => {
setData(data.filter(item => item.id !== id));
}
const columns = [
{ field: 'id', headerName: 'ID', width: 90 },
{
field: 'user',
headerName: 'User',
width: 200,
renderCell: (params) => {
return (
<div className="userListUser">
<img className="userListImg" src={params.row.avatar} alt="" />
{ params.row.username }
</div>
)
}
},
{
field: 'email',
headerName: 'Email',
type: 'number',
width: 200,
editable: true,
},
{
field: 'status',
headerName: 'Status',
description: 'This column has a value getter and is not sortable.',
sortable: false,
width: 120,
},
{
field: 'transaction',
headerName: 'Transaction',
description: 'This column has a value getter and is not sortable.',
sortable: false,
width: 160,
},
{
field: "action",
headerName: "Action",
width: 150,
renderCell: (params) => {
return (
<>
<Link to={"/user/"+params.row.id}>
<button className="userListEdit">Edit</button>
</Link>
<DeleteOutline className="userListDelete" onClick={()=>handleDelete(params.row.id) } />
</>
)
}
},
];
return (
<div className="userList">
<DataGrid
rows={data}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection
disableSelectionOnClick
/>
</div>
)
} |
<div class="container">
<div class="row text-center">
<span class="display-3">チーム登録</span>
</div>
<div class="row">
<div class="col">
<%= form_with model: [:team ,@team], local: true do |f| %>
<% if @team.errors.any? %>
<div>
<div class="alert alert-danger">
<%= pluralize(@team.errors.count, "個") %>のエラーがあります
</div>
<ul>
<% @team.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.label :account_name, class: 'form-label' %>
<%= f.text_field :account_name, class: 'form-control' %>
<br>
<%= f.label :display_name, class: 'form-label' %>
<%= f.text_field :display_name, class: 'form-control' %>
<br>
<%= f.label :email, class: 'form-label' %>
<%= f.email_field :email, class: 'form-control' %>
<br>
<%= f.label :prefecture_code, class: 'form-label' %>
<%= f.select :prefecture_code, Team.prefecture_codes.keys, {}, class: 'form-control' %>
<br>
<%= f.label :password, class: 'form-label' %>
<%= f.password_field :password, class: 'form-control' %>
<br>
<%= f.label :password_confirmation, class: 'form-label' %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<br>
<%= f.submit "チームアカウント作成", class: "btn btn-primary" %>
<% end %>
</div>
</div>
<div class="row text-center">
<h5>チーム登録済みの方はこちらから → <%= link_to "ログイン", team_login_path, class: "btn btn-secondary" %></h5>
</div>
</div> |
import { Controller, Get, Post, Body } from '@nestjs/common';
import { AppService } from './app.service';
import { RavendbService } from './ravendb/ravendb.service';
import {ConfigService} from "@nestjs/config";
@Controller('app')
export class AppController {
constructor(
private readonly appService: AppService,
private readonly ravenService: RavendbService,
private readonly config: ConfigService) {}
@Get('hello')
getHello(): object {
return {
salutation: this.appService.getHello(),
};
}
@Get('entities')
async getEntities(): Promise<object> {
return await this.ravenService.listDocuments();
}
@Post('entities')
async createEntity(@Body() body: object): Promise<object> {
const created = await this.ravenService.storeDocument(body);
return created;
}
@Get('config')
getConfig() {
const environment = this.config.get<string>('environment');
const names = this.config.get<string[]>('names');
return { environment, names };
}
} |
import { Button, Flex, FormControl, FormLabel, Grid, Input } from "@chakra-ui/react";
import React, { useEffect, useMemo, useState } from "react";
import Datatable from "../../components/data-table/DataTable";
import Layout from "../../components/layout.js/Layout";
import Loader from "../../components/loader/Loader";
import CustomSelect from "../../components/select/CustomSelect";
import Wrapper from "../../components/wrapper/Wrapper";
import { API } from "../../utils/axios/axiosConfig";
import { LEAD_LIST_API } from "../../utils/routes/URLs";
import { COLUMNS } from "./columns";
export default function Leads() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const [statusList, setStatusList] = useState([]);
const [sourceList, setSourceList] = useState([]);
const [isFiltered, setIsFiltered] = useState(false);
const [assigneeList, setAssigneeList] = useState([]);
const [totalRows, setTotalRows] = useState(0);
const [perPage, setPerPage] = useState(10);
//filterState
const [selectedStatus, setSelectedStatus] = useState([]);
const [selectedSource, setSelectedSource] = useState([]);
const [selectedAssignees, setSelectedAssignees] = useState([]);
const [selectedFrom, setSelectedFrom] = useState("");
const [selectedTo, setSelectedTo] = useState("");
const columns = useMemo(() => COLUMNS, []);
const payload = {
search: isFiltered ? "search value" : "",
lead_status_id: selectedStatus?.map((d) => d?.value),
source_id: selectedSource?.map((d) => d?.value),
user_id: selectedAssignees?.map((d) => d?.value),
contacted_date_from: selectedFrom,
contacted_date_to: selectedTo,
};
const getLeadList = (page) => {
setLoading(true);
API.post(LEAD_LIST_API(page), payload)
.then((res) => {
if (res?.data?.code === 200) {
setData(res?.data?.data?.data);
setTotalRows(res?.data?.data?.total);
}
})
.catch((err) => console.log(err))
.finally(() => {
setLoading(false);
});
};
const handlePageChange = (page) => {
getLeadList(page);
};
const handlePerRowsChange = (newPerPage, page) => {
API.post(`/api/admin/lead/list?page=${page}&limit=${newPerPage}`, payload)
.then((res) => {
if (res?.data?.code === 200) {
setPerPage(newPerPage);
setData(res?.data?.data?.data);
}
})
.catch((err) => console.log(err))
.finally(() => {
setLoading(false);
});
};
// Fetch Filter APIs
const fetchStatus = async () => {
setLoading(true);
try {
let res = await API.get("/api/admin/base/lead-status");
if (res?.data?.code === 200) {
let temp = res?.data?.data?.map((d) => ({ label: d?.name, value: d?.id }));
setStatusList(temp);
}
} catch (err) {
console.log(err);
} finally {
setLoading(false);
}
};
const fetchSource = async () => {
setLoading(true);
try {
let res = await API.get("/api/admin/base/source");
if (res?.data?.code === 200) {
let temp = res?.data?.data?.map((d) => ({ label: d?.name, value: d?.id }));
setSourceList(temp);
}
} catch (err) {
console.log(err);
} finally {
setLoading(false);
}
};
const fetchAssignee = async () => {
setLoading(true);
try {
let res = await API.get("/api/admin/base/assignee");
if (res?.data?.code === 200) {
let temp = res?.data?.data?.map((d) => ({ label: d?.name, value: d?.id }));
setAssigneeList(temp);
}
} catch (err) {
console.log(err);
} finally {
setLoading(false);
}
};
useEffect(() => {
getLeadList(1);
fetchStatus();
fetchSource();
fetchAssignee();
}, []);
const Filter = () => {
return (
<Grid templateColumns={"repeat(6, 1fr)"} gap={2} mb="2">
<CustomSelect
isMulti
options={statusList}
placeholder={"Status"}
onChange={(e) => {
setSelectedStatus(e);
}}
value={selectedStatus}
/>
<CustomSelect
isMulti
options={sourceList}
placeholder={"Sources"}
onChange={(e) => {
setSelectedSource(e);
}}
value={selectedSource}
/>
<CustomSelect
isMulti
options={assigneeList}
placeholder={"Assignees"}
onChange={(e) => {
setSelectedAssignees(e);
}}
value={selectedAssignees}
/>
<Input
size="sm"
type="date"
onChange={(e) => {
setSelectedFrom(e.target.value);
}}
value={selectedFrom}
/>
<Input
size="sm"
type="date"
onChange={(e) => {
setSelectedTo(e.target.value);
}}
value={selectedTo}
/>
<Flex gap={2}>
<Button
size="sm"
colorScheme="blue"
onClick={() => {
setIsFiltered(true);
getLeadList(1);
}}
>
Filter
</Button>
<Button
size="sm"
variant="outline"
onClick={() => {
setIsFiltered(false);
setSelectedStatus([]);
setSelectedSource([]);
setSelectedAssignees([]);
setSelectedFrom("");
setSelectedTo("");
getLeadList(1);
}}
>
Reset Filter
</Button>
</Flex>
</Grid>
);
};
const resetFilter = () => {
setIsFiltered(false);
setSelectedStatus([]);
setSelectedSource([]);
setSelectedAssignees([]);
setSelectedFrom("");
setSelectedTo("");
getLeadList(1);
};
return (
<Layout>
{loading && <Loader />}
<Wrapper>
<Filter />
<Datatable
data={data}
columns={columns}
selectableRows
paginationServer
paginationTotalRows={totalRows}
onChangePage={handlePageChange}
onChangeRowsPerPage={handlePerRowsChange}
paginationRowsPerPageOptions={[10, 20, 50]}
/>
</Wrapper>
</Layout>
);
} |
"""Tests for docq.manage_spaces module."""
import json
import logging as log
import sqlite3
import tempfile
from contextlib import closing
from typing import Generator, Optional
from unittest.mock import MagicMock, Mock, patch
import pytest
from docq import manage_spaces
from docq.access_control.main import SpaceAccessor, SpaceAccessType
from docq.config import SpaceType
from docq.domain import SpaceKey
from llama_index.core.schema import Document
TEST_ORG_ID = 1000
@pytest.fixture(scope="session")
def manage_spaces_test_dir() -> Generator:
"""Create a temporary directory for testing."""
from docq.manage_spaces import _init
log.info("Setup manage spaces test.")
with tempfile.TemporaryDirectory() as temp_dir, patch(
"docq.manage_spaces.get_sqlite_shared_system_file"
) as mock_get_sqlite_shared_system_file:
sqlite_system_file = f"{temp_dir}/sql_system.db"
mock_get_sqlite_shared_system_file.return_value = sqlite_system_file
manage_spaces._init()
yield temp_dir, sqlite_system_file, mock_get_sqlite_shared_system_file
log.info("Teardown manage spaces test.")
def insert_test_space(sqlite_system_file: str, name: str, space_type: Optional[str] = None) -> Optional[int]:
"""Insert a test space."""
if space_type is None:
space_type = SpaceType.SHARED.name
with closing(sqlite3.connect(sqlite_system_file)) as connection, closing(connection.cursor()) as cursor:
cursor.execute("INSERT INTO spaces (org_id, name, space_type, summary, datasource_type, datasource_configs) VALUES (?, ?, ?, ?, ?, ?)", (TEST_ORG_ID, name, space_type, "test space description", "test ds_type", json.dumps({"test": "test"})))
space_id = cursor.lastrowid
connection.commit()
return space_id
def test_db_init(manage_spaces_test_dir: tuple) -> None:
"""Test db init."""
with closing(sqlite3.connect(manage_spaces_test_dir[1])) as connection, closing(connection.cursor()) as cursor:
sql_select = "SELECT name FROM sqlite_master WHERE type='table' AND name = ?"
tables = [("spaces",), ("space_access",)]
for table in tables:
cursor.execute(sql_select, table)
result = cursor.fetchone()
assert result is not None, f"Table {table} not found."
# @patch("docq.support.store._get_default_storage_context")
# @patch("docq.model_selection.main._get_service_context")
# def test_create_index(get_service_context: MagicMock, get_default_storage_context: MagicMock) -> None:
# """Test create index."""
# from docq.manage_spaces import _create_vector_index
# with patch("llama_index.core.VectorStoreIndex", Mock(from_documents=MagicMock())):
# documents = [Document(text=f"Document {_}") for _ in range(10)]
# # model_settings_collection = Mock()
# # mocked_model_usage_settings = Mock()
# # mocked_model_usage_settings.additional_args = {"arg1": "value1", "arg2": "value2"}
# model_settings_collection = get_model_settings_collection(
# "azure_openai_latest"
# ) # {ModelCapability.CHAT: mocked_model_usage_settings}
# _create_vector_index(documents, model_settings_collection)
# get_service_context.assert_called_once_with(model_settings_collection)
# get_default_storage_context.assert_called_once()
@patch("docq.manage_spaces._persist_index")
@patch("docq.manage_spaces._create_vector_index")
@patch("docq.manage_spaces.get_saved_model_settings_collection")
@patch("docq.manage_spaces.get_space_data_source")
@patch("docq.manage_spaces.SpaceDataSources")
def test_reindex(
self,
mock_SpaceDataSources,
mock_get_space_data_source,
mock_get_saved_model_settings_collection,
mock_create_vector_index,
mock_persist_index,
):
# Arrange
mock_space = MagicMock(spec=SpaceKey, id_="test_id", org_id="test_org_id")
mock_get_space_data_source.return_value = ("ds_type", "ds_configs")
mock_SpaceDataSources.__getitem__.return_value.value.load.return_value = [
Document(doc_id="testid", text="test", extra_info={"source_uri": "https://example.com"})
]
mock_create_vector_index.return_value = "vector_index"
# Act
manage_spaces.reindex(mock_space)
# Assert
mock_persist_index.assert_called_once_with("vector_index", mock_space)
@patch("docq.manage_indices.get_index_dir")
def test_persist_index(get_index_dir: MagicMock) -> None:
"""Test persist index."""
from docq.manage_indices import _persist_index
def _persist (persist_dir: str) -> None:
with open(persist_dir, "w") as f:
f.write("test")
index = Mock(storage_context=Mock(persist=_persist))
space = Mock()
with tempfile.NamedTemporaryFile() as temp_file:
get_index_dir.return_value = temp_file.name
_persist_index(index, space)
assert temp_file.read() == b"test"
get_index_dir.assert_called_once_with(space)
def test_get_shared_space(manage_spaces_test_dir: tuple) -> None:
"""Test get shared space."""
from docq.manage_spaces import get_shared_space
sqlite_system_file = manage_spaces_test_dir[1]
space_id = insert_test_space(sqlite_system_file, "get_shared_space test")
assert space_id is not None, "Space id not found."
space = get_shared_space(space_id, TEST_ORG_ID)
assert space is not None, "Space not found."
assert space[0] == space_id, "Space id mismatch."
def test_get_shared_spaces(manage_spaces_test_dir: tuple) -> None:
"""Test get shared spaces."""
from docq.manage_spaces import get_shared_spaces
sqlite_system_file = manage_spaces_test_dir[1]
space_id1 = insert_test_space(sqlite_system_file, "get_shared_spaces test 1")
space_id2 = insert_test_space(sqlite_system_file, "get_shared_spaces test 2")
assert space_id1 is not None, "Sample space_id 1 not found."
assert space_id2 is not None, "Sample space_id 2 not found."
spaces = get_shared_spaces([space_id1, space_id2])
assert len(spaces) == 2, f"Expected 2 spaces, got {len(spaces)}."
def test_update_shared_space(manage_spaces_test_dir: tuple) -> None:
"""Test update shared space."""
from docq.manage_spaces import update_shared_space
sqlite_system_file = manage_spaces_test_dir[1]
space_id = insert_test_space(sqlite_system_file, "update_shared_space test")
space_name_updated = "update_shared_space test updated"
assert space_id is not None, "Sample space id not found."
update_space = update_shared_space(
space_id,
TEST_ORG_ID,
name=space_name_updated,
summary="test summary updated",
datasource_type="test ds_type updated",
datasource_configs={"test": "test updated"},
)
assert update_space, "Update failed."
with closing(sqlite3.connect(sqlite_system_file)) as connection, closing(connection.cursor()) as cursor:
cursor.execute("SELECT name FROM spaces WHERE id = ?", (space_id,))
result = cursor.fetchone()
assert result is not None, "Space not found."
assert result[0] == space_name_updated, "Space name mismatch."
def test_create_shared_space(manage_spaces_test_dir: tuple) -> None:
"""Test create shared space."""
from docq.manage_spaces import create_shared_space
sqlite_system_file = manage_spaces_test_dir[1]
space_name = "create_shared_space test"
space_summary = "create_shared_space test summary"
space_datasource_type = "create_shared_space test ds_type"
space_datasource_configs = {"create_shared_space test": "create_shared_space test"}
with patch("docq.manage_spaces.reindex") as reindex:
space = create_shared_space(
TEST_ORG_ID,
space_name,
space_summary,
space_datasource_type,
space_datasource_configs,
)
assert space is not None, "Space not found."
with closing(sqlite3.connect(sqlite_system_file)) as connection, closing(connection.cursor()) as cursor:
cursor.execute("SELECT name, summary, datasource_type, datasource_configs FROM spaces WHERE id = ?", (space.id_,))
result = cursor.fetchone()
assert result is not None, "Space not found."
assert result[0] == space_name, "Space name mismatch."
assert result[1] == space_summary, "Space summary mismatch."
assert result[2] == space_datasource_type, "Space datasource_type mismatch."
assert result[3] == json.dumps(space_datasource_configs), "Space datasource_configs mismatch."
reindex.assert_called_once_with(space)
def test_create_thread_space(manage_spaces_test_dir: tuple) -> None:
"""Test create thread space."""
sqlite_system_file = manage_spaces_test_dir[1]
space_summary = "create_thread_space test summary"
space_datasource_type = "create_thread_space test ds_type"
test_thread_id = 1234
def assert_pattern(thread_id: str, space_summary: str, thread_space_name: str) -> None:
import re
pattern = rf"Thread-{test_thread_id} {space_summary} \d+"
assert (
re.fullmatch(pattern, thread_space_name) is not None
), f"{thread_space_name} does not match pattern {pattern}"
with patch("docq.manage_spaces.reindex") as reindex:
from docq.manage_spaces import create_thread_space
space = create_thread_space(
TEST_ORG_ID,
test_thread_id,
space_summary,
space_datasource_type,
)
assert space is not None, "Space not found."
with closing(sqlite3.connect(sqlite_system_file)) as connection, closing(connection.cursor()) as cursor:
cursor.execute("SELECT name, summary, datasource_type, datasource_configs FROM spaces WHERE id = ?", (space.id_,))
result = cursor.fetchone()
assert result is not None, "Space not found."
# assert result[0] == f"Thread-{test_thread_id} {space_summary}", "Space name mismatch."
assert result[1] == space_summary, "Space summary mismatch."
assert result[2] == space_datasource_type, "Space datasource_type mismatch."
assert_pattern(str(test_thread_id), space_summary, result[0])
reindex.assert_called_once_with(space)
def test_get_thread_space() -> None:
"""Test get thread space."""
space_summary = "get_thread_space test summary"
space_datasource_type = "get_thread_space test ds_type"
test_thread_id = 4321
with patch("docq.manage_spaces.reindex") as reindex:
from docq.manage_spaces import create_thread_space
space = create_thread_space(
TEST_ORG_ID,
test_thread_id,
space_summary,
space_datasource_type,
)
assert space is not None, "Space not found."
reindex.assert_called_once_with(space)
from docq.manage_spaces import get_thread_space
space_result = get_thread_space(TEST_ORG_ID, test_thread_id)
assert space_result is not None, "Space not found."
assert space_result.id_ == space.id_, "Space id mismatch."
def test_list_shared_space(manage_spaces_test_dir: tuple) -> None:
"""Test list shared space."""
from docq.manage_spaces import list_shared_spaces
sqlite_system_file = manage_spaces_test_dir[1]
space_id1 = insert_test_space(sqlite_system_file, "list_shared_space test 1")
space_id2 = insert_test_space(sqlite_system_file, "list_shared_space test 2")
assert space_id1 is not None, "Sample space_id 1 not found."
assert space_id2 is not None, "Sample space_id 2 not found."
spaces = list_shared_spaces(TEST_ORG_ID)
assert len(spaces) >= 2, f"Expected atleast 2 spaces, got {len(spaces)}."
space_ids = [s[0] for s in spaces]
assert space_id1 in space_ids, f"Space id {space_id1} not found."
assert space_id2 in space_ids, f"Space id {space_id2} not found."
def test_list_public_spaces(manage_spaces_test_dir: tuple) -> None:
"""Test list public space."""
from docq.manage_space_groups import _init
from docq.manage_spaces import list_public_spaces
sqlite_system_file = manage_spaces_test_dir[1]
with patch("docq.manage_space_groups.get_sqlite_shared_system_file") as _get_sqlite_shared_system_file:
_get_sqlite_shared_system_file.return_value = sqlite_system_file
_init()
space_id1 = insert_test_space(sqlite_system_file, "list_public_space test 1")
space_id2 = insert_test_space(sqlite_system_file, "list_public_space test 2")
assert space_id1 is not None, "Test list public spaces sample space_id 1 not found."
assert space_id2 is not None, "Test list public spaces sample space_id 2 not found."
with closing(sqlite3.connect(sqlite_system_file)) as connection, closing(connection.cursor()) as cursor:
cursor.execute("INSERT INTO space_groups (org_id, name, summary) VALUES (?, ?, ?)", (TEST_ORG_ID, "test_group_1", "test group summary"))
group_id = cursor.lastrowid
cursor.execute("INSERT INTO space_group_members (group_id, space_id) VALUES (?, ?)", (group_id, space_id1))
cursor.execute("INSERT INTO space_group_members (group_id, space_id) VALUES (?, ?)", (group_id, space_id2))
cursor.execute("INSERT INTO space_access (space_id, access_type, accessor_id) VALUES (?, ?, ?)", (space_id1, SpaceAccessType.PUBLIC.name, group_id))
cursor.execute("INSERT INTO space_access (space_id, access_type, accessor_id) VALUES (?, ?, ?)", (space_id2, SpaceAccessType.PUBLIC.name, group_id))
connection.commit()
assert group_id is not None, "Test list public spaces sample group_id not found."
public_spaces = list_public_spaces(selected_org_id=TEST_ORG_ID, space_group_id=group_id)
space_ids = [s[0] for s in public_spaces]
assert space_id1 in space_ids, f"Space id {space_id1} not found."
assert space_id2 in space_ids, f"Space id {space_id2} not found."
assert len(public_spaces) == 2, f"Expected 2 spaces, got {len(public_spaces)}."
def test_get_shared_space_permissions(manage_spaces_test_dir: tuple) -> None:
"""Test get shared space permissions."""
from docq import manage_user_groups, manage_users
from docq.manage_spaces import get_shared_space_permissions
sqlite_system_file = manage_spaces_test_dir[1]
with patch("docq.manage_users.get_sqlite_shared_system_file") as p1, patch(
"docq.manage_user_groups.get_sqlite_shared_system_file"
) as p2:
p1.return_value = sqlite_system_file
p2.return_value = sqlite_system_file
manage_users._init()
manage_user_groups._init()
space_id = insert_test_space(sqlite_system_file, "get_shared_space_permissions test")
ctrl_space_id = insert_test_space(sqlite_system_file, "get_shared_space_permissions ctrl test")
assert space_id is not None, "Sample space id not found."
assert ctrl_space_id is not None, "Sample ctrl space id not found."
with closing(sqlite3.connect(sqlite_system_file)) as connection, closing(connection.cursor()) as cursor:
cursor.execute("INSERT INTO users (username, password, fullname) VALUES (?, ?, ?)", ("test_user", "test_password", "test user"))
user_id = cursor.lastrowid
assert user_id is not None, "Sample user id not found."
accessor = SpaceAccessor(SpaceAccessType.USER, user_id, "test_user")
cursor.execute("INSERT INTO space_access (space_id, access_type, accessor_id) VALUES (?, ?, ?)", (space_id, accessor.type_.name, accessor.accessor_id))
cursor.execute("INSERT INTO user_groups (org_id, name) VALUES (?, ?)", (TEST_ORG_ID, "test_user_group"))
connection.commit()
shared_space_permissions = get_shared_space_permissions(space_id, TEST_ORG_ID)
assert shared_space_permissions is not None, "Shared space permissions not found."
assert len(shared_space_permissions) == 1, f"Expected 1 space permission, got {len(shared_space_permissions)}."
assert shared_space_permissions[0] == accessor, "Accessor mismatch."
def test_update_shared_space_permissions(manage_spaces_test_dir: tuple) -> None:
"""Test update shared space permissions."""
from docq.manage_spaces import update_shared_space_permissions
sqlite_system_file = manage_spaces_test_dir[1]
space_id = insert_test_space(sqlite_system_file, "update_shared_space_permissions test user")
assert space_id is not None, "Sample user space id not found."
public_accessor = SpaceAccessor(SpaceAccessType.PUBLIC, space_id, "sample_public_accessor")
user_accessor = SpaceAccessor(SpaceAccessType.USER, space_id, "sample_user_accessor")
group_accessor = SpaceAccessor(SpaceAccessType.GROUP, space_id, "sample_group_accessor")
updates = update_shared_space_permissions(space_id, [public_accessor, user_accessor, group_accessor])
assert updates, "Update failed." |
import { useEffect, useMemo, useRef, useState } from "react";
import type WebSocket from "./ws";
import type { Options } from "./ws";
/** When any of the option values are changed, we should reinitialize the socket */
export const getOptionsThatShouldCauseRestartWhenChanged = (
options: Options
) => [
options.startClosed,
options.minUptime,
options.maxRetries,
options.connectionTimeout,
options.maxEnqueuedMessages,
options.maxReconnectionDelay,
options.minReconnectionDelay,
options.reconnectionDelayGrowFactor,
options.debug
];
/**
* Initializes a PartySocket (or WebSocket) and keeps it stable across renders,
* but reconnects and updates the reference when any of the connection args change.
*/
export function useStableSocket<T extends WebSocket, TOpts extends Options>({
options,
createSocket,
createSocketMemoKey: createOptionsMemoKey
}: {
options: TOpts;
createSocket: (options: TOpts) => T;
createSocketMemoKey: (options: TOpts) => string;
}) {
// ensure we only reconnect when necessary
const shouldReconnect = createOptionsMemoKey(options);
const socketOptions = useMemo(() => {
return options;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [shouldReconnect]);
// this is the socket we return
const [socket, setSocket] = useState<T>(() =>
// only connect on first mount
createSocket({ ...socketOptions, startClosed: true })
);
// keep track of the socket we initialized
const socketInitializedRef = useRef<T | null>(null);
// allow changing the socket factory without reconnecting
const createSocketRef = useRef(createSocket);
createSocketRef.current = createSocket;
// finally, initialize the socket
useEffect(() => {
// we haven't yet restarted the socket
if (socketInitializedRef.current === socket) {
// create new socket
const newSocket = createSocketRef.current({
...socketOptions,
// when reconnecting because of options change, we always reconnect
// (startClosed only applies to initial mount)
startClosed: false
});
// update socket reference (this will cause the effect to run again)
setSocket(newSocket);
} else {
// if this is the first time we are running the hook, connect...
if (!socketInitializedRef.current && socketOptions.startClosed !== true) {
socket.reconnect();
}
// track initialized socket so we know not to do it again
socketInitializedRef.current = socket;
// close the old socket the next time the socket changes or we unmount
return () => {
socket.close();
};
}
}, [socket, socketOptions]);
return socket;
} |
import Transaction from '../models/Transaction';
interface CreateTransaction {
title: string;
value: number;
type: 'income' | 'outcome';
}
interface Balance {
income: number;
outcome: number;
total: number;
}
class TransactionsRepository {
private transactions: Transaction[];
constructor() {
this.transactions = [];
}
public all(): Transaction[] {
return this.transactions;
}
public getBalance(): Balance {
const income = this.transactions
.filter(transaction => transaction.type === 'income')
.reduce((startValue, transaction) => startValue + transaction.value, 0);
const outcome = this.transactions
.filter(transaction => transaction.type === 'outcome')
.reduce((startValue, transaction) => startValue + transaction.value, 0);
const total = income - outcome;
const balance = {
income,
outcome,
total,
};
return balance;
}
public create({ title, value, type }: CreateTransaction): Transaction {
const transaction = new Transaction({ title, value, type });
this.transactions.push(transaction);
return transaction;
}
}
export default TransactionsRepository; |
class Matrix:
def __init__(self, size):
self.size = size
self.data = [[0 for _ in range(size)] for _ in range(size)]
def input_matrix(self):
print("Nhập ma trận vuông kích thước", self.size, "x", self.size)
for i in range(self.size):
row = input(f"Nhập hàng thứ {i + 1} (các giá trị cách nhau bằng dấu cách): ")
values = row.split()
if len(values) != self.size:
print("Lỗi: Vui lòng nhập đúng số lượng giá trị cho mỗi hàng.")
return False
try:
self.data[i] = [int(val) for val in values]
except ValueError:
print("Lỗi: Vui lòng chỉ nhập các giá trị số nguyên.")
return False
return True
def is_lower_triangular(self):
for i in range(self.size):
for j in range(i + 1, self.size):
if self.data[i][j] != 0:
return False
return True
def has_duplicate_columns(self):
for i in range(self.size - 1):
for j in range(i + 1, self.size):
if all(self.data[x][i] == self.data[x][j] for x in range(self.size)):
return True
return False
def print_duplicate_column_groups(self):
groups = []
visited = set()
for i in range(self.size - 1):
if i not in visited:
group = [i]
for j in range(i + 1, self.size):
if all(self.data[x][i] == self.data[x][j] for x in range(self.size)):
group.append(j)
visited.add(j)
if len(group) > 1:
groups.append(group)
if not groups:
print("Không có nhóm cột giống nhau.")
return
for group in groups:
print("Nhóm cột giống nhau:", group)
# Ví dụ sử dụng:
size = int(input("Nhập kích thước ma trận vuông: "))
m = Matrix(size)
while not m.input_matrix():
pass # Lặp lại yêu cầu nhập ma trận nếu có lỗi nhập
print("Ma trận vừa nhập:")
for row in m.data:
print(row)
print("Là ma trận tam giác dưới:", m.is_lower_triangular())
print("Có ít nhất hai cột giống nhau:", m.has_duplicate_columns())
m.print_duplicate_column_groups() |
import React, {useCallback, useState} from 'react';
import {useNavigation} from '@react-navigation/native';
import LocationService from '../../../services/location/LocationService';
import {StackNavigationProp} from '@react-navigation/stack';
import {RootStackParamList} from '../../../screens';
import CustomButton from '../../customButton/CustomButton';
import {StyleSheet} from 'react-native';
import {Colors} from '../../../constants';
type NavigationProp = StackNavigationProp<RootStackParamList, 'Weather'>;
function WeatherCurrent() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const navigation = useNavigation<NavigationProp>();
const handleFetchWeather = useCallback(async () => {
try {
setLoading(true);
setError(false);
const position = await LocationService.getCurrentPosition();
navigation.navigate('Weather', {position});
} catch (e) {
setError(true);
} finally {
setLoading(false);
}
}, [navigation]);
return (
<CustomButton
testID="weather-current"
label="Weather at my position"
onPress={handleFetchWeather}
loading={loading}
style={error && style.error}
/>
);
}
const style = StyleSheet.create({
error: {borderColor: Colors.ERROR, borderWidth: 1, borderRadius: 10},
});
export default WeatherCurrent; |
package com.devsimone.appointify.LecturerDash.Adapter
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.devsimone.appointify.LecturerDash.Activity.ViewActivity
import com.devsimone.appointify.Models.Appointment
import com.devsimone.appointify.databinding.BookAppBinding
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class BooksAdapter(
private var bookListLec: MutableList<Appointment>,
private val context: Context
): RecyclerView.Adapter<BooksAdapter.BooksViewHolder>() {
class BooksViewHolder(bookApp: BookAppBinding) :
RecyclerView.ViewHolder(bookApp.root) {
val binding = bookApp
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = BooksViewHolder(
BookAppBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
override fun getItemCount() = bookListLec.size
override fun onBindViewHolder(holder: BooksViewHolder, position: Int) {
val app1 = bookListLec[position]
holder.binding.apply {
val originalChildName = app1.appOwnId
val childName = encodeChildName(originalChildName)
homeAppTime.text = "${app1.appTime} ${app1.appDate}"
homeAppTopic.text = app1.appTopic
var appUsername: String? = null
var appUserdp: String? = null
FirebaseDatabase.getInstance().reference.child("Login")
.child(childName)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
appUsername = dataSnapshot.child("login_username").getValue(String::class.java)
appUserdp = dataSnapshot.child("userDp").value.toString()
Glide.with(context).load(appUserdp)
.into(homeAppDp)
homeAppName.text = appUsername
}
override fun onCancelled(databaseError: DatabaseError) {
// Handle database error
Log.e("Firebase", "Database Error: ${databaseError.message}")
}
})
root.setOnClickListener {
val intent = Intent(context, ViewActivity::class.java)
val bundle = Bundle()
bundle.putString("appId", app1.appId)
bundle.putString("appUsername", appUsername)
bundle.putString("appUserdp", appUserdp)
intent.putExtras(bundle)
root.context.startActivity(intent)
true
}
}
}
private fun encodeChildName(childName: String): String {
return childName.replace("/", "-")
}
} |
import { list } from "../handling/lists.mjs"
import { api } from "../handling/api.mjs"
import { addAttributes } from "../reading/attributes.mjs"
import { cartContentTemplate } from "../templates/cartContent.mjs"
import { compareByValue } from "./general.mjs"
async function getCartProducts(){
const cartItems = await list.get('cart')
let firstIDCheck = []
let newItemList = []
if(cartItems){
cartItems.forEach(element => {
firstIDCheck.push(element[0])
newItemList.push(element)
});
const firstApi = await api.call(100,["include="+firstIDCheck],'cart1')
const orphans = firstApi.reduce((parents, element) => {
const children = addAttributes("child", element, 'test');
if (children.length > 0) {
const orphanGroup = children.filter(child => !cartItems.some(item => item[0] === child));
if (orphanGroup.length > 0) {
orphanGroup.forEach(orphan => {
parents.push([orphan,0,element.id]);
});
}
}
return parents;
}, []);
let secondIDCheck = []
orphans.forEach(element => {
secondIDCheck.push(element[0])
});
const secondApi = await api.call(100,["include="+secondIDCheck],'cart2')
let cartAndOrhpans=[...firstApi, ...secondApi];
const sleeves = cartAndOrhpans.reduce((parents, element) => {
const sleeve = addAttributes("sleeves",element,"value")
if (sleeve.length > 0) {
const sleeveGroup = sleeve.filter(sleeve => !cartItems.some(item => item[0] === sleeve));
if (sleeveGroup.length > 0) {
sleeveGroup.forEach(sleeve => {
parents.push([sleeve[0],0,element.id,sleeve[2]]);
});
}
}
return parents;
}, []);
let thirdIDChech = []
sleeves.forEach(element => {
thirdIDChech.push(element[0])
});
const thirdApi = await api.call(100,["include="+thirdIDChech],'cart3')
let combinedArray = [...firstApi, ...secondApi, ...thirdApi];
list.save('newCart',newItemList)
list.save('tempCartLoad',combinedArray)
list.save('newCartBackup',newItemList)
}
}
async function createListContent(type,target){
let newHtml = ""
let totalPrice = 0
let productCost
let sleevesCollection = []
let accessorieCollection = []
let newList = await list.get('newCart')
let allProducts = await list.get ('tempCartLoad')
if(!newList || !allProducts){
await getCartProducts()
newList = await list.get('newCart')
allProducts = await list.get ('tempCartLoad')
}
allProducts.forEach(product => {
newList.forEach(listContent => {
if(product.id===listContent[0]){
if(listContent[2]){
// is not a main element
if(listContent[3]){
// is sleeves
sleevesCollection.push([product,listContent])
}else{
// is expansion or other accessorie
accessorieCollection.push([product,listContent])
}
}else{
// is a main item
if(listContent[1]>0){
productCost = parseInt(product.regular_price, 10)
totalPrice+=productCost*listContent[1]
}
newHtml+=cartContentTemplate(product,listContent[1])
}
}
});
});
target.innerHTML=newHtml
accessorieCollection=compressAccessories(accessorieCollection)
accessorieCollection.sort(compareByValue)
if(accessorieCollection.length>0){
accessorieCollection.forEach(element => {
totalPrice+=element[0].regular_price*element[1][1]
let addToTarget = target.querySelector(`#productID${element[1][2]}`)
if (addToTarget) {
addToTarget.classList.add('accessorieExpanded')
let container = addToTarget.querySelector(".accessories .container")
if(element[1][1]===0){
container.innerHTML += accessorieContentTemplate(element[0],false)
}else{
container.innerHTML += accessorieContentTemplate(element[0],true)
}
}else{
target.innerHTML+= `<div>${cartContentTemplate(element[0],element[1][1])}</div>`
}
});
}
sleevesCollection.forEach(element => {
let addToTarget = target.querySelector(`#productID${element[1][2]} .sleevesContainer`);
if (addToTarget) {
button = target.querySelector(`#productID${element[1][2]} #sleeveID${element[1][0]}`)
addToTarget.innerHTML += sleeveContentTemplate(element[0], element[1][3] * element[1][1]);
}else{
if(element[1][1]>0){
target.innerHTML+=cartContentTemplate(element[0], Math.ceil(element[1][3] * element[1][1] /55),element[1])
}
}
});
sleevesCollection=compressSleeves(sleevesCollection)
sleevesCollection.forEach(element => {
const price = element[0].regular_price
const sleevesNeeded = element[1][3]
const setsNeeded=Math.ceil(sleevesNeeded/55)
const leftover = setsNeeded*55-sleevesNeeded
let leftoverMessage
totalPrice+=price*setsNeeded
if(leftover>0){
leftoverMessage=leftover+" spare"
}else{
leftoverMessage=leftover+" missing"
}
if(element[1][1]>0){
target.innerHTML+=`
<div id="sleeve-list" class="flex-column">
<span>${element[0].name}</span>
<span> ${sleevesNeeded} sleeves (${leftoverMessage})</span>
<span class="shift-right">
<span>${setsNeeded} x ${price} kr ${setsNeeded*price} kr</span>
</span>
</div>
`
}
});
target.innerHTML+=`
<div class="flex-column shift-right">
<span>Total cost: ${totalPrice}</span>
<a class="checkoutLink" href="checkout.html">Checkout</a>
</div>
`
target.innerHTML+=`
<button id="saveCartID">save new cart!</button>
<button id="resetCartID">Get it back!</button>
`
document.getElementById('saveCartID').addEventListener('click',()=>saveCart())
document.getElementById('resetCartID').addEventListener('click',()=>resetCart());
let finalCartCollection = []
sleevesCollection.forEach(element => {
finalCartCollection.push([element[1][0],element[1][1]])
});
accessorieCollection.forEach(element => {
if(element[1][1]>0){
finalCartCollection.push([element[1][0],element[1][1]])
}
});
}
function compressAccessories(list){
let newList = []
list.forEach(list => {
let inList=false
newList.forEach(newList => {
if(newList[1][0]===list[1][0]){
inList=true
newList[1][1]+=list[1][1]
}
});
if(!inList){
newList.push(list)
}
});
return newList
}
function compressSleeves(list){
let newList = []
list.forEach(list => {
let inList=false
newList.forEach(newList => {
if(newList[1][0]===list[1][0]){
inList=true
newList[1][3]+=list[1][3]*list[1][1]
//newList[1][1]=Math.ceil(newList[1][3]/55)
}
});
if(!inList){
list[1][3]=list[1][3]*list[1][1]
//list[1][1]=Math.ceil(list[1][3]/55)
newList.push(list)
}
});
return newList
}
export{createListContent} |
<?php
/**
* Widget API: WP_Widget_Meta class
*
* @package WordPress
* @subpackage Widgets
* @since 4.4.0
*/
/**
* Core class used to implement a Meta widget.
*
* Displays log in/out, RSS feed links, etc.
*
* @since 2.8.0
*
* @see WP_Widget
*/
class WP_Widget_Meta extends WP_Widget {
/**
* Sets up a new Meta widget instance.
*
* @since 2.8.0
*/
public function __construct() {
$widget_ops = array(
'classname' => 'widget_meta',
'description' => __( 'Login, RSS, & WordPress.org links.' ),
'customize_selective_refresh' => true,
);
parent::__construct( 'meta', __( 'Meta' ), $widget_ops );
}
/**
* Outputs the content for the current Meta widget instance.
*
* @since 2.8.0
*
* @param array $args Display arguments including 'before_title', 'after_title',
* 'before_widget', and 'after_widget'.
* @param array $instance Settings for the current Meta widget instance.
*/
public function widget( $args, $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'Meta' );
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
echo $args['before_widget'];
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
?>
<ul>
<?php wp_register(); ?>
<li><?php wp_loginout(); ?></li>
<li><a href="<?php echo esc_url( get_bloginfo( 'rss2_url' ) ); ?>"><?php _e('Entries <abbr title="Really Simple Syndication">RSS</abbr>'); ?></a></li>
<li><a href="<?php echo esc_url( get_bloginfo( 'comments_rss2_url' ) ); ?>"><?php _e('Comments <abbr title="Really Simple Syndication">RSS</abbr>'); ?></a></li>
<?php
/**
* Filters the "Powered by WordPress" text in the Meta widget.
*
* @since 3.6.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @param string $title_text Default title text for the WordPress.org link.
* @param array $instance Array of settings for the current widget.
*/
echo apply_filters( 'widget_meta_poweredby', sprintf( '<li><a href="%s" title="%s">%s</a></li>',
esc_url( __( 'https://wordpress.org/' ) ),
esc_attr__( 'Powered by WordPress, state-of-the-art semantic personal publishing platform.' ),
_x( 'WordPress.org', 'meta widget link text' )
), $instance );
wp_meta();
?>
</ul>
<?php
echo $args['after_widget'];
}
/**
* Handles updating settings for the current Meta widget instance.
*
* @since 2.8.0
*
* @param array $new_instance New settings for this instance as input by the user via
* WP_Widget::form().
* @param array $old_instance Old settings for this instance.
* @return array Updated settings to save.
*/
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = sanitize_text_field( $new_instance['title'] );
return $instance;
}
/**
* Outputs the settings form for the Meta widget.
*
* @since 2.8.0
*
* @param array $instance Current settings.
*/
public function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = sanitize_text_field( $instance['title'] );
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p>
<?php
}
} |
import 'package:flutter/material.dart';
import 'package:circular_countdown_timer/circular_countdown_timer.dart';
import 'Exercise.dart';
import 'db_helper.dart';
import 'main.dart';
var data = [];
var next = 0;
var exerciseType = "";
var startTime;
class TakeRest extends StatelessWidget {
TakeRest({super.key, required int nextStep, required String type, required time}){
next = nextStep;
exerciseType = type;
startTime = time;
}
@override
Widget build(BuildContext context) {
return Container(
child: Scaffold(
appBar: AppBar(
title: Welcome.lang == "en" ? Text("Take a rest") : Text("TОтдохните"),
centerTitle: true,
),
body: TakeRestBody(),
),
);
}
}
class TakeRestBody extends StatefulWidget {
const TakeRestBody({super.key});
@override
State<TakeRestBody> createState() => _TakeRestBodyState();
}
class _TakeRestBodyState extends State<TakeRestBody> {
var firstExerciseName = "";
Future<void> getData() async {
var db = UserDatabaseProvider();
await db.open();
data = await db.getListType(exerciseType);
setState(() {
});
}
@override
Widget build(BuildContext context) {
getData();
return Container(
margin: EdgeInsets.all(16),
child: Align(
child: Column(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Welcome.lang == "en" ? Text("TAKE A REST",
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.w700,
color: Colors.indigo
),
) : Text("ОТДОХНИТЕ",
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.w700,
color: Colors.indigo
),
),
Container(
child: CircularCountDownTimer(
duration: 10,
initialDuration: 0,
controller: CountDownController(),
width: MediaQuery.of(context).size.width / 6,
height: MediaQuery.of(context).size.height / 6,
ringColor: Colors.white,
ringGradient: null,
fillColor: Colors.white,
fillGradient: null,
backgroundGradient: null,
strokeWidth: 0.0,
strokeCap: StrokeCap.round,
textStyle: TextStyle(
fontSize: 30.0, color: Colors.black, fontWeight: FontWeight.w700),
textFormat: CountdownTextFormat.S,
isReverse: true,
isReverseAnimation: true,
isTimerTextShown: true,
autoStart: true,
onStart: () {
debugPrint('Countdown Started');
},
onComplete: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Exercise(type:workoutType,step:next,fE:data[next]['name'],time: startTime)), // Yönlendirme burada yapılıyor
);
},
onChange: (String timeStamp) {
debugPrint('Countdown Changed $timeStamp');
},
timeFormatterFunction: (defaultFormatterFunction, duration) {
return Function.apply(defaultFormatterFunction, [duration]);
},
),
),
Welcome.lang == "en" ? Text("Next Movement (${next+1}/${data.length})") : Text("Следующая часть (${next+1}/${data.length})"),
SizedBox(height: 10,
),
Text(data[next]["name"].toString(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500
),
)
],
)
),
Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(12),
margin: EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFF1E55A5), // Adjust colors as needed
Color(0xFF14288B),
],
stops: [0, 1],
transform: GradientRotation(274.42 * 3.141592 / 180),
),
borderRadius: BorderRadius.circular(45),
),
child: TextButton(
onPressed: (){
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Exercise(type:workoutType,step:next,fE:data[next]['name'],time: startTime)), // Yönlendirme burada yapılıyor
);
},
child: Welcome.lang == "en" ? Text("Skip rest",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w700
),
) : Text("Пропустить отдых",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w700
),
),
),
),
],
),
),
);
}
} |
<div class="control">
<p class="control-title">Kezelő felület</p>
<mat-tab-group mat-align-tabs="center">
<mat-tab label="Kvízek">
<ng-template matTabContent>
<div class="control-tab-content">
<table mat-table [dataSource]="quizzes" *ngIf="quizzes.length > 0;else quizzesNotAvailable">
<ng-container *ngFor="let tableInfo of quizzesTableInfos" [matColumnDef]="tableInfo.columnDef">
<th mat-header-cell *matHeaderCellDef style="text-align: center; color: aquamarine;">{{tableInfo.header}}</th>
<td mat-cell *matCellDef="let element" style="text-align: center;">{{tableInfo.cell(element)}}</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef style="text-align: center; color: aquamarine;">Műveletek</th>
<td mat-cell *matCellDef="let element" style="text-align: center;">
<button mat-icon-button (click)="editQuiz(element)">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button (click)="deleteQuiz(element)" *ngIf="!element.isDeleted">
<mat-icon>delete</mat-icon>
</button>
<button mat-icon-button (click)="restoreQuiz(element)" *ngIf="element.isDeleted">
<mat-icon>restore_from_trash</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="quizzesTableColumns"></tr>
<tr mat-row *matRowDef="let row; columns: quizzesTableColumns;"></tr>
</table>
<ng-template #quizzesNotAvailable>
Nincs elérhető kvíz
</ng-template>
<div *ngIf="compileQuiz">
<p class="quiz-title">Új kvíz</p>
<form #quizcheck="ngForm" (ngSubmit)="checkQuiz(quizcheck)" [attr.novalidate]="null">
<div class="quiz-item">
<label for="quiz_name">Qvíz neve:</label>
<br>
<input type="text" name="quiz_name" ngModel required style="text-align: center;">
<br>
</div>
<div class="quiz-item">
<label for="quiz_questionids">Kvízben szereplő kérdések:</label>
<br>
<select name="quiz_questionids" ngModel required style="text-align: center;" multiple size="10">
<optgroup *ngFor="let question of questionSortByCategory | keyvalue" label="{{question.key}}">
<option *ngFor="let questionValue of question.value" value="{{questionValue._id}}">{{questionValue.text}}</option>
</optgroup>
</select>
<br>
<i style="font-size: 12px;">(Több kiválasztása: CTRL+CLICK)</i>
</div>
<input type="submit" value="Kvíz mentés" *ngIf="!quizSaved" class="add-button">
</form>
<p class="quiz-error" *ngIf="quizError">{{quizErrorMessage}}</p>
</div>
<button class="add-button" (click)="clickCompileButton()">
{{compileQuiz ? 'Mégse' :'Kvíz összeállítás'}}
</button>
<div *ngIf="quizSaved" class="quiz-saved">
A kvíz elmentve
</div>
</div>
</ng-template>
</mat-tab>
<mat-tab label="Kérdések" class="center-tab-item">
<ng-template matTabContent>
<div class="control-tab-content">
<table mat-table [dataSource]="questions" *ngIf="questions.length > 0;else questionsNotAvailable">
<ng-container *ngFor="let tableInfo of questionsTableInfos" [matColumnDef]="tableInfo.columnDef">
<th mat-header-cell *matHeaderCellDef style="text-align: center; color: aquamarine;">{{tableInfo.header}}</th>
<td mat-cell *matCellDef="let element" style="text-align: center;">{{tableInfo.cell(element)}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="questionsTableColumns"></tr>
<tr mat-row *matRowDef="let row; columns: questionsTableColumns;"></tr>
</table>
<ng-template #questionsNotAvailable>
Nincs elérhető kérdés
</ng-template>
</div>
</ng-template>
</mat-tab>
<mat-tab label="Kategóriák" class="center-tab-item">
<ng-template matTabContent>
<div class="control-tab-content">
<table mat-table [dataSource]="categories" *ngIf="categories.length > 0;else categoriesNotAvailable">
<ng-container *ngFor="let tableInfo of categoriesTableInfos" [matColumnDef]="tableInfo.columnDef">
<th mat-header-cell *matHeaderCellDef style="text-align: center; color: aquamarine;">{{tableInfo.header}}</th>
<td mat-cell *matCellDef="let element" style="text-align: center;">{{tableInfo.cell(element)}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="categoriesTableColumns"></tr>
<tr mat-row *matRowDef="let row; columns: categoriesTableColumns;"></tr>
</table>
<ng-template #categoriesNotAvailable>
Nincs elérhető kategória
</ng-template>
</div>
</ng-template>
</mat-tab>
</mat-tab-group>
</div> |
#
# Window creation example
#
# This example creates a minimal "control" that just fills in its
# window with red. To make your own control, subclass Control and
# write your own OnPaint() method. See PyCWnd.HookMessage for what
# the parameters to OnPaint are.
#
from pywin.mfc import dialog, window
import win32ui
import win32con
import win32api
class Control(window.Wnd):
"""Generic control class"""
def __init__ (self):
window.Wnd.__init__(self, win32ui.CreateWnd ())
def OnPaint (self):
dc, paintStruct = self.BeginPaint()
self.DoPaint(dc)
self.EndPaint(paintStruct)
def DoPaint (self, dc): # Override this!
pass
class RedBox (Control):
def DoPaint (self, dc):
dc.FillSolidRect (self.GetClientRect(), win32api.RGB(255,0,0))
class RedBoxWithPie (RedBox):
def DoPaint (self, dc):
RedBox.DoPaint(self, dc)
r = self.GetClientRect()
dc.Pie(r[0], r[1], r[2], r[3], 0,0,r[2], r[3]//2)
def MakeDlgTemplate():
style = (win32con.DS_MODALFRAME |
win32con.WS_POPUP |
win32con.WS_VISIBLE |
win32con.WS_CAPTION |
win32con.WS_SYSMENU |
win32con.DS_SETFONT)
cs = (win32con.WS_CHILD |
win32con.WS_VISIBLE)
w = 64
h = 64
dlg = [["Red box",
(0, 0, w, h),
style,
None,
(8, "MS Sans Serif")],
]
s = win32con.WS_TABSTOP | cs
dlg.append([128,
"Cancel",
win32con.IDCANCEL,
(7, h - 18, 50, 14), s | win32con.BS_PUSHBUTTON])
return dlg
class TestDialog(dialog.Dialog):
def OnInitDialog(self):
rc = dialog.Dialog.OnInitDialog(self)
self.redbox = RedBox ()
self.redbox.CreateWindow (None, "RedBox",
win32con.WS_CHILD |
win32con.WS_VISIBLE,
(5, 5, 90, 68),
self, 1003)
return rc
class TestPieDialog(dialog.Dialog):
def OnInitDialog(self):
rc = dialog.Dialog.OnInitDialog(self)
self.control = RedBoxWithPie()
self.control.CreateWindow (None, "RedBox with Pie",
win32con.WS_CHILD |
win32con.WS_VISIBLE,
(5, 5, 90, 68),
self, 1003)
def demo(modal=0):
d = TestPieDialog (MakeDlgTemplate())
if modal:
d.DoModal()
else:
d.CreateWindow()
if __name__=='__main__':
demo(1) |
import React from "react";
import {
clearDateValuesWhenStatusChanges,
getCustomTheme,
getEmptyBook,
getPublishingYearRegexPattern,
getTextFieldRegexPattern,
} from "../util/helpers";
import {
Box,
Button,
Form,
FormField,
Grommet,
Select,
Heading,
DateInput,
} from "grommet";
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { Link } from "react-router-dom";
import { getBookById } from "../util/requests";
import {
validateAuthorNameLenght,
validateDescriptionLenght,
validatePublishingYear,
} from "../util/validators";
import { Save } from "grommet-icons";
function BookForm({ editForm, updateBook, submit }) {
const { id } = useParams();
const [value, setValue] = useState({
initialState: getEmptyBook(),
editedState: getEmptyBook(),
});
useEffect(() => {
if (id) {
getBookById(id).then((data) => {
setValue({ initialState: data, editedState: data });
});
}
}, [id]);
const [valid, setValid] = useState(false);
const onChange = (nextValue) => {
nextValue = clearDateValuesWhenStatusChanges(nextValue);
setValue({ ...value, editedState: nextValue });
console.log(value.editedState);
};
const saveBook = () => {
if (editForm) {
updateBook(value.editedState);
} else {
submit(value.editedState);
}
};
return (
<Grommet full theme={getCustomTheme()}>
<Box fill align="center" justify="center" pad="medium">
<Heading level={2}>{id ? "Edit Book: " : "Add a new book: "}</Heading>
<Box width="medium">
<Form
validate="change"
value={value.editedState}
onChange={onChange}
onValidate={(validationResults) => {
setValid(validationResults.valid);
}}
>
<FormField
label="Title*"
name="name"
required
validate={[
{
regexp: getTextFieldRegexPattern(),
message: "Title can contain only letters and digits!",
},
(name) => {
if (validateAuthorNameLenght(name))
return "Title must be between 3 and 32 characters";
return undefined;
},
]}
/>
<FormField
label="Author*"
name="author"
required
validate={[
{ regexp: getTextFieldRegexPattern() },
(author) => {
if (validateAuthorNameLenght(author))
return "Athor's name must be between 3 and 32 characters";
return undefined;
},
]}
/>
<FormField label="Genre*" name="genre" required>
<Select
required
name="genre"
options={[
"Technology",
"Fiction",
"Novel",
"Mystery",
"Horror",
"Adventure",
]}
/>{" "}
</FormField>
<FormField
label="Published*"
name="releaseYear"
required
validate={[
{
regexp: getPublishingYearRegexPattern(),
message: "Year must be numeric and be maximum 4 digits long!",
},
(releaseYear) => {
if (validatePublishingYear(releaseYear))
return "Publishing year can't be greater than current year!";
return undefined;
},
]}
/>
<FormField
label="Description"
name="description"
validate={[
(description) => {
if (validateDescriptionLenght(description))
return "Must be less than 33 characters long!";
return undefined;
},
]}
/>
<FormField
label="Status*"
name="status"
htmlFor="select-size"
required
>
<Select
required
name="status"
id="select-size"
options={["Unread", "In-Progress", "Finished"]}
></Select>
</FormField>
<FormField
label="Started Reading"
name="startReading"
onClick={(e) => console.log(e)}
>
<DateInput
format="dd/mm/yyyy"
name="startReading"
disabled={
value.editedState.status === "Unread" ||
value.editedState.status === ""
? true
: false
}
/>
</FormField>
<FormField label="Finished Reading" name="finishReading">
<DateInput
name="finishReading"
format="dd/mm/yyyy"
disabled={
value.editedState.status === "Unread" ||
value.editedState.status === "In-Progress" ||
value.editedState.status === ""
? true
: false
}
></DateInput>
</FormField>
<FormField label="Rating">
<Select
disabled={value.editedState.status !== "Finished"}
name="grade"
id="select-size"
defaultValue=""
options={["1", "2", "3", "4", "5"]}
/>
</FormField>
<Box
direction="row"
justify="between"
margin={{ top: "medium" }}
pad="medium"
gap="small"
>
<Link to="/">
<Button label="Cancel" />
</Link>
<Button
type="reset"
label="Reset"
onClick={() =>
setValue({ ...value, editedState: value.initialState })
}
/>
<Button
label="Save"
type="submit"
disabled={!valid}
onClick={saveBook}
href={id ? "/?status=edited" : "/?status=added"}
primary
icon={<Save />}
/>
</Box>
</Form>
</Box>
</Box>
</Grommet>
);
}
export default BookForm; |
import { Body, Controller, Get, HttpCode, HttpStatus, Post, Render, Request, Response, UseGuards } from '@nestjs/common';
import { AuthService } from '../services/auth.service';
import { JwtAuthGuard } from '../guard/auth.guard';
import { LocalAuthGuard } from '../guard/local.guard';
import { SocketGateway } from 'src/socket/socket.gateway';
import { ApiTags } from '@nestjs/swagger';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService,
private socket:SocketGateway){}
//localhost:8000/api/auth/login
@HttpCode(HttpStatus.OK)
@ApiTags("API de Login")
@Post("login")
singIn(@Body() singInDTO: Record<string,any>){
return this.authService.signIn(singInDTO.usuario,singInDTO.contraseña)
}
//localhost:8000/api/auth/perfil
@ApiTags("Acceso con jwt")
@UseGuards(JwtAuthGuard)
@Get("perfil")
getPerfil(@Request() req){
return req.usuario
}
//localhost:8000/api/auth/sesion
@Get("sesion")
@Render("index")
getSesion(){}
@Post("sesion")
async postsesion(@Request() req, @Response() res){
const { userT, passT} = req.body;
const validaruser = await this.authService.validateUser(userT, passT)
if(validaruser){
req.session.authenticated = true;
req.session.user = userT;
return res.redirect("menu")
}
return res.status(HttpStatus.UNAUTHORIZED).render
('index', { error: 'Credenciales inválidas' });
}
//localhost:8000/api/auth/menu
@UseGuards(LocalAuthGuard)
@Get("menu")
@Render("menu")
getmenu(@Request()req):{usuario:string}{
const usuario = req.session.user
this.socket.setUsuario(usuario) //Se envia el usuario
return {usuario}
}
} |
/**
* Formats a SIREN number.
*
* @param str The string to format.
* @returns The formatted string or `undefined` if the input is not valid.
*/
export const formatSiren = (str?: string): string | undefined => {
if (!str || str.length !== 9) return str
return `${str.slice(0, 3)} ${str.slice(3, 6)} ${str.slice(6, 9)}`
}
/**
* Formats a SIRET number.
*
* @param str The string to format.
* @returns The formatted string or `undefined` if the input is not valid.
*/
export const formatSiret = (str?: string): string | undefined => {
if (!str || str.length !== 14) return str
return `${str.slice(0, 3)} ${str.slice(3, 6)} ${str.slice(6, 9)} ${str.slice(9, 12)} ${str.slice(12)}`
}
/**
* Generate a version 4 UUID.
* @returns A version 4 UUID.
*/
export function uuid_e4(): string {
const h = '0123456789abcdef';
let u = '';
for (let i = 0; i < 36; i++) {
const c = i === 8 || i === 13 || i === 18 || i === 23 ? '-' : i === 14 ? '4' : 'x';
u += c === '-' || c === '4' ? c : h[Math.floor(Math.random() * 16)];
}
return u;
} |
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _dom = _interopRequireDefault(require("../../shared/dom7"));
var _utils = require("../../shared/utils");
var _class = _interopRequireDefault(require("../../shared/class"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Stepper = /*#__PURE__*/function (_Framework7Class) {
_inheritsLoose(Stepper, _Framework7Class);
function Stepper(app, params) {
var _this;
_this = _Framework7Class.call(this, params, [app]) || this;
var stepper = _assertThisInitialized(_this);
var defaults = {
el: null,
inputEl: null,
valueEl: null,
value: 0,
formatValue: null,
step: 1,
min: 0,
max: 100,
watchInput: true,
autorepeat: false,
autorepeatDynamic: false,
wraps: false,
manualInputMode: false,
decimalPoint: 4,
buttonsEndInputMode: true
}; // Extend defaults with modules params
stepper.useModulesParams(defaults);
stepper.params = (0, _utils.extend)(defaults, params);
if (stepper.params.value < stepper.params.min) {
stepper.params.value = stepper.params.min;
}
if (stepper.params.value > stepper.params.max) {
stepper.params.value = stepper.params.max;
}
var el = stepper.params.el;
if (!el) return stepper || _assertThisInitialized(_this);
var $el = (0, _dom.default)(el);
if ($el.length === 0) return stepper || _assertThisInitialized(_this);
if ($el[0].f7Stepper) return $el[0].f7Stepper || _assertThisInitialized(_this);
var $inputEl;
if (stepper.params.inputEl) {
$inputEl = (0, _dom.default)(stepper.params.inputEl);
} else if ($el.find('.stepper-input-wrap').find('input, textarea').length) {
$inputEl = $el.find('.stepper-input-wrap').find('input, textarea').eq(0);
}
if ($inputEl && $inputEl.length) {
'step min max'.split(' ').forEach(function (paramName) {
if (!params[paramName] && $inputEl.attr(paramName)) {
stepper.params[paramName] = parseFloat($inputEl.attr(paramName));
}
});
var _decimalPoint = parseInt(stepper.params.decimalPoint, 10);
if (Number.isNaN(_decimalPoint)) {
stepper.params.decimalPoint = 0;
} else {
stepper.params.decimalPoint = _decimalPoint;
}
var inputValue = parseFloat($inputEl.val());
if (typeof params.value === 'undefined' && !Number.isNaN(inputValue) && (inputValue || inputValue === 0)) {
stepper.params.value = inputValue;
}
}
var $valueEl;
if (stepper.params.valueEl) {
$valueEl = (0, _dom.default)(stepper.params.valueEl);
} else if ($el.find('.stepper-value').length) {
$valueEl = $el.find('.stepper-value').eq(0);
}
var $buttonPlusEl = $el.find('.stepper-button-plus');
var $buttonMinusEl = $el.find('.stepper-button-minus');
var _stepper$params = stepper.params,
step = _stepper$params.step,
min = _stepper$params.min,
max = _stepper$params.max,
value = _stepper$params.value,
decimalPoint = _stepper$params.decimalPoint;
(0, _utils.extend)(stepper, {
app: app,
$el: $el,
el: $el[0],
$buttonPlusEl: $buttonPlusEl,
buttonPlusEl: $buttonPlusEl[0],
$buttonMinusEl: $buttonMinusEl,
buttonMinusEl: $buttonMinusEl[0],
$inputEl: $inputEl,
inputEl: $inputEl ? $inputEl[0] : undefined,
$valueEl: $valueEl,
valueEl: $valueEl ? $valueEl[0] : undefined,
step: step,
min: min,
max: max,
value: value,
decimalPoint: decimalPoint,
typeModeChanged: false
});
$el[0].f7Stepper = stepper; // Handle Events
var touchesStart = {};
var isTouched;
var isScrolling;
var preventButtonClick;
var intervalId;
var timeoutId;
var autorepeatAction = null;
var autorepeatInAction = false;
var manualInput = false;
function dynamicRepeat(current, progressions, startsIn, progressionStep, repeatEvery, action) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
if (current === 1) {
preventButtonClick = true;
autorepeatInAction = true;
}
clearInterval(intervalId);
action();
intervalId = setInterval(function () {
action();
}, repeatEvery);
if (current < progressions) {
dynamicRepeat(current + 1, progressions, startsIn, progressionStep, repeatEvery / 2, action);
}
}, current === 1 ? startsIn : progressionStep);
}
function onTouchStart(e) {
if (isTouched) return;
if (manualInput) {
return;
}
if ((0, _dom.default)(e.target).closest($buttonPlusEl).length) {
autorepeatAction = 'increment';
} else if ((0, _dom.default)(e.target).closest($buttonMinusEl).length) {
autorepeatAction = 'decrement';
}
if (!autorepeatAction) return;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
isTouched = true;
isScrolling = undefined;
var progressions = stepper.params.autorepeatDynamic ? 4 : 1;
dynamicRepeat(1, progressions, 500, 1000, 300, function () {
stepper[autorepeatAction]();
});
}
function onTouchMove(e) {
if (!isTouched) return;
if (manualInput) {
return;
}
var pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
var pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (typeof isScrolling === 'undefined' && !autorepeatInAction) {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
}
var distance = Math.pow(Math.pow(pageX - touchesStart.x, 2) + Math.pow(pageY - touchesStart.y, 2), 0.5);
if (isScrolling || distance > 20) {
isTouched = false;
clearTimeout(timeoutId);
clearInterval(intervalId);
}
}
function onTouchEnd() {
clearTimeout(timeoutId);
clearInterval(intervalId);
autorepeatAction = null;
autorepeatInAction = false;
isTouched = false;
}
function onMinusClick() {
if (manualInput) {
if (stepper.params.buttonsEndInputMode) {
manualInput = false;
stepper.endTypeMode(true);
}
return;
}
if (preventButtonClick) {
preventButtonClick = false;
return;
}
stepper.decrement(true);
}
function onPlusClick() {
if (manualInput) {
if (stepper.params.buttonsEndInputMode) {
manualInput = false;
stepper.endTypeMode(true);
}
return;
}
if (preventButtonClick) {
preventButtonClick = false;
return;
}
stepper.increment(true);
}
function onInputClick(e) {
if (!e.target.readOnly && stepper.params.manualInputMode) {
manualInput = true;
if (typeof e.target.selectionStart === 'number') {
e.target.selectionStart = e.target.value.length;
e.target.selectionEnd = e.target.value.length;
}
}
}
function onInputKey(e) {
if (e.keyCode === 13 || e.which === 13) {
e.preventDefault();
manualInput = false;
stepper.endTypeMode();
}
}
function onInputBlur() {
manualInput = false;
stepper.endTypeMode(true);
}
function onInput(e) {
if (manualInput) {
stepper.typeValue(e.target.value);
return;
}
if (e.detail && e.detail.sentByF7Stepper) return;
stepper.setValue(e.target.value, true);
}
stepper.attachEvents = function attachEvents() {
$buttonMinusEl.on('click', onMinusClick);
$buttonPlusEl.on('click', onPlusClick);
if (stepper.params.watchInput && $inputEl && $inputEl.length) {
$inputEl.on('input', onInput);
$inputEl.on('click', onInputClick);
$inputEl.on('blur', onInputBlur);
$inputEl.on('keyup', onInputKey);
}
if (stepper.params.autorepeat) {
app.on('touchstart:passive', onTouchStart);
app.on('touchmove:active', onTouchMove);
app.on('touchend:passive', onTouchEnd);
}
};
stepper.detachEvents = function detachEvents() {
$buttonMinusEl.off('click', onMinusClick);
$buttonPlusEl.off('click', onPlusClick);
if (stepper.params.watchInput && $inputEl && $inputEl.length) {
$inputEl.off('input', onInput);
$inputEl.off('click', onInputClick);
$inputEl.off('blur', onInputBlur);
$inputEl.off('keyup', onInputKey);
}
}; // Install Modules
stepper.useModules(); // Init
stepper.init();
return stepper || _assertThisInitialized(_this);
}
var _proto = Stepper.prototype;
_proto.minus = function minus() {
return this.decrement();
};
_proto.plus = function plus() {
return this.increment();
};
_proto.decrement = function decrement() {
var stepper = this;
return stepper.setValue(stepper.value - stepper.step, false, true);
};
_proto.increment = function increment() {
var stepper = this;
return stepper.setValue(stepper.value + stepper.step, false, true);
};
_proto.setValue = function setValue(newValue, forceUpdate, withWraps) {
var stepper = this;
var step = stepper.step,
min = stepper.min,
max = stepper.max;
var oldValue = stepper.value;
var value = Math.round(newValue / step) * step;
if (stepper.params.wraps && withWraps) {
if (value > max) value = min;
if (value < min) value = max;
} else {
value = Math.max(Math.min(value, max), min);
}
if (Number.isNaN(value)) {
value = oldValue;
}
stepper.value = value;
var valueChanged = oldValue !== value; // Events
if (!valueChanged && !forceUpdate) return stepper;
stepper.$el.trigger('stepper:change', stepper.value);
var formattedValue = stepper.formatValue(stepper.value);
if (stepper.$inputEl && stepper.$inputEl.length) {
stepper.$inputEl.val(formattedValue);
stepper.$inputEl.trigger('input change', {
sentByF7Stepper: true
});
}
if (stepper.$valueEl && stepper.$valueEl.length) {
stepper.$valueEl.html(formattedValue);
}
stepper.emit('local::change stepperChange', stepper, stepper.value);
return stepper;
};
_proto.endTypeMode = function endTypeMode(noBlur) {
var stepper = this;
var min = stepper.min,
max = stepper.max;
var value = parseFloat(stepper.value);
if (Number.isNaN(value)) value = 0;
value = Math.max(Math.min(value, max), min);
stepper.value = value;
if (!stepper.typeModeChanged) {
if (stepper.$inputEl && stepper.$inputEl.length && !noBlur) {
stepper.$inputEl.blur();
}
return stepper;
}
stepper.typeModeChanged = false;
stepper.$el.trigger('stepper:change', stepper.value);
var formattedValue = stepper.formatValue(stepper.value);
if (stepper.$inputEl && stepper.$inputEl.length) {
stepper.$inputEl.val(formattedValue);
stepper.$inputEl.trigger('input change', {
sentByF7Stepper: true
});
if (!noBlur) stepper.$inputEl.blur();
}
if (stepper.$valueEl && stepper.$valueEl.length) {
stepper.$valueEl.html(formattedValue);
}
stepper.emit('local::change stepperChange', stepper, stepper.value);
return stepper;
};
_proto.typeValue = function typeValue(value) {
var stepper = this;
stepper.typeModeChanged = true;
var inputTxt = String(value);
if (inputTxt.lastIndexOf('.') + 1 === inputTxt.length || inputTxt.lastIndexOf(',') + 1 === inputTxt.length) {
if (inputTxt.lastIndexOf('.') !== inputTxt.indexOf('.') || inputTxt.lastIndexOf(',') !== inputTxt.indexOf(',')) {
inputTxt = inputTxt.slice(0, -1);
stepper.value = inputTxt;
stepper.$inputEl.val(stepper.value);
return stepper;
}
} else {
var newValue = parseFloat(inputTxt.replace(',', '.'));
if (newValue === 0) {
stepper.value = inputTxt.replace(',', '.');
stepper.$inputEl.val(stepper.value);
return stepper;
}
if (Number.isNaN(newValue)) {
stepper.value = 0;
stepper.$inputEl.val(stepper.value);
return stepper;
}
var powVal = Math.pow(10, stepper.params.decimalPoint);
newValue = Math.round(newValue * powVal).toFixed(stepper.params.decimalPoint + 1) / powVal;
stepper.value = parseFloat(String(newValue).replace(',', '.'));
stepper.$inputEl.val(stepper.value);
return stepper;
}
stepper.value = inputTxt;
stepper.$inputEl.val(inputTxt);
return stepper;
};
_proto.getValue = function getValue() {
return this.value;
};
_proto.formatValue = function formatValue(value) {
var stepper = this;
if (!stepper.params.formatValue) return value;
return stepper.params.formatValue.call(stepper, value);
};
_proto.init = function init() {
var stepper = this;
stepper.attachEvents();
if (stepper.$valueEl && stepper.$valueEl.length) {
var formattedValue = stepper.formatValue(stepper.value);
stepper.$valueEl.html(formattedValue);
}
return stepper;
};
_proto.destroy = function destroy() {
var stepper = this;
stepper.$el.trigger('stepper:beforedestroy');
stepper.emit('local::beforeDestroy stepperBeforeDestroy', stepper);
delete stepper.$el[0].f7Stepper;
stepper.detachEvents();
(0, _utils.deleteProps)(stepper);
stepper = null;
};
return Stepper;
}(_class.default);
var _default = Stepper;
exports.default = _default; |
=== Комбінаторика
*Перестановками* з stem:[n] елементів називаються такі їх сукупності, що відрізняються одна від іншої тільки порядком входження елементів:
[stem,reftext=({counter:eqs})]
++++
P(n)=n!
++++
*Комбінацією (сполученням)* з stem:[n] елементів по stem:[m] називаються такі сукупності m елементів, що відрізняються одна від іншої принаймні одним елементом (stem:[n>=m]):
[stem#cmbn,reftext=({counter:eqs})]
++++
C_n^m=((n),(m))=(n!)/(m!(n-m)!)
++++
.Приклад:
[%collapsible%open]
====
Всі можливі комбінації двох чисел з 1-6 це 15 таких сполучень: 12, 13, 14, 15, 16, 23, 24, 25, 26, 34, 35, 36, 45, 46, 56
====
*Розміщеннями* з stem:[n] елементів по stem:[m] називаються такі сукупності m елементів, що відрізняються одна від іншої принаймні одним елементом або порядком їх входження (stem:[n>=m]):
[stem,reftext=({counter:eqs})]
++++
A_n^m=(n!)/((n-m)!)
++++
.Приклад:
[%collapsible%open]
====
Всі можливі розміщення двох чисел з 1-6 це 30 таких сполучень: 12, 13, 14, 15, 16, 21, 23, 24, 25, 26, 31, 32, 34, 35, 36, 41, 42, 43, 45, 46, 51, 52, 53, 54, 56, 61, 62, 63, 64, 65
==== |
export interface IALTitleInfo {
Media: Media;
}
interface Media {
id: number;
format: string;
status: string;
description: string;
startDate: EndDateClass;
endDate: EndDateClass;
season: string;
seasonYear: number;
episodes: number;
duration: number;
trailer: Trailer;
genres: string[];
averageScore: number;
meanScore: number;
popularity: number;
tags: Tag[];
nextAiringEpisode: NextAiringEpisode;
siteUrl: string;
title: Title;
coverImage: CoverImage;
bannerImage: string;
}
interface CoverImage {
extraLarge: string;
large: string;
medium: string;
color: string;
}
interface EndDateClass {
year: number;
month: number;
day: number;
}
interface NextAiringEpisode {
id: number;
airingAt: number;
episode: number;
}
interface Tag {
id: number;
name: string;
}
interface Title {
english: string;
romaji: string;
}
interface Trailer {
id: string;
site: string;
thumbnail: string;
} |
import { User } from "@/types/user.ts";
interface StorageProxy<T> {
getItem(): T | null;
setItem(value: T | null): void;
removeItem(): void;
}
export class Storage<T> implements StorageProxy<T> {
constructor(private key: string) {}
getItem(): T | null {
const result = localStorage.getItem(this.key);
if (!result) return null;
try {
return JSON.parse(result) as T;
} catch {
return null;
}
}
setItem(value: T | null): void {
const serialized = JSON.stringify(value);
localStorage.setItem(this.key, serialized);
}
removeItem(): void {
localStorage.removeItem(this.key);
}
}
export const USER_STORAGE_KEY = "writtable-user";
export const AUTH_STORAGE_KEY = "writtable-auth";
export const userStorage = new Storage<User>(USER_STORAGE_KEY);
export const authStorage = new Storage<{ jwt: string }>(AUTH_STORAGE_KEY); |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. 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.
""" Finetuning the library models for sequence classification on GLUE."""
# You can also adapt this script on your own text classification task. Pointers for this are left as comments.
from functools import partial
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import List, Optional
import datasets
from datasets.arrow_dataset import concatenate_datasets
import numpy as np
from datasets import load_dataset, load_metric
import datasets
import warnings
import torch
from torch import nn
warnings.filterwarnings("ignore")
import transformers
from transformers import (
AutoConfig,
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
DataCollatorForSeq2Seq,
EvalPrediction,
HfArgumentParser,
PretrainedConfig,
Seq2SeqTrainer,
Trainer,
Seq2SeqTrainingArguments,
default_data_collator,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version
from transformers.utils.versions import require_version
from transformers import T5Tokenizer, T5ForConditionalGeneration
from hfutils.arg_parser import HfArguments
from hfutils.constants import TASK_TO_KEYS, TASK_TO_LABELS
def label2text(task_name, label):
if TASK_TO_LABELS[task_name] is None:
return label
else:
return TASK_TO_LABELS[task_name][label]
def token2label(tokens, label_tokens: List):
return [label_tokens.index(t) for t in tokens]
def get_optimizer_grouped_parameters(args, model):
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
},
{
"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
},
]
return optimizer_grouped_parameters
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
os.environ['TORCH_EXTENSIONS_DIR'] = os.getcwd()
# os.environ['NCCL_DEBUG'] = "INFO"
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
# check_min_version("4.13.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
logger = logging.getLogger(__name__)
from torch.utils.data import DataLoader
from tqdm import tqdm
@dataclass
class DataTrainingArguments:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
Using `HfArgumentParser` we can turn this class
into argparse arguments to be able to specify them on
the command line.
"""
task_name: Optional[str] = field(
default=None,
metadata={"help": "The name of the task to train on: " + ", ".join(TASK_TO_KEYS.keys())},
)
dataset_name: Optional[str] = field(
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
)
max_seq_length: int = field(
default=128,
metadata={
"help": "The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
},
)
overwrite_cache: bool = field(
default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
)
pad_to_max_length: bool = field(
default=True,
metadata={
"help": "Whether to pad all samples to `max_seq_length`. "
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
},
)
max_train_samples: Optional[int] = field(
default=None,
metadata={
"help": "For debugging purposes or quicker training, truncate the number of training examples to this "
"value if set."
},
)
max_eval_samples: Optional[int] = field(
default=None,
metadata={
"help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
"value if set."
},
)
max_predict_samples: Optional[int] = field(
default=None,
metadata={
"help": "For debugging purposes or quicker training, truncate the number of prediction examples to this "
"value if set."
},
)
train_file: Optional[str] = field(
default=None, metadata={"help": "A csv or a json file containing the training data."}
)
validation_file: Optional[str] = field(
default=None, metadata={"help": "A csv or a json file containing the validation data."}
)
test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."})
def __post_init__(self):
if self.task_name is not None:
self.task_name = self.task_name.lower()
# if self.task_name not in TASK_TO_KEYS.keys():
# raise ValueError("Unknown task, you should pick one in " + ",".join(TASK_TO_KEYS.keys()))
elif self.dataset_name is not None:
pass
elif self.train_file is None or self.validation_file is None:
raise ValueError("Need either a GLUE task, a training/validation file or a dataset name.")
else:
train_extension = self.train_file.split(".")[-1]
assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file."
validation_extension = self.validation_file.split(".")[-1]
assert (
validation_extension == train_extension
), "`validation_file` should have the same extension (csv or json) as `train_file`."
@dataclass
class ModelArguments:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
)
config_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
)
tokenizer_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
)
cache_dir: Optional[str] = field(
default=None,
metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
)
use_fast_tokenizer: bool = field(
default=True,
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
)
model_revision: str = field(
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
use_auth_token: bool = field(
default=False,
metadata={
"help": "Will use the token generated when running `transformers-cli login` (necessary to use this script "
"with private models)."
},
)
def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
# Detecting last checkpoint.
last_checkpoint = None
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
raise ValueError(
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
"Use --overwrite_output_dir to overcome."
)
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
# Set seed before initializing model.
set_seed(training_args.seed)
print(data_args.dataset_name, data_args.task_name)
# Labels
is_regression = False
# num_labels = 2
# Load pretrained model and tokenizer
#
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
config = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
# num_labels=num_labels,
finetuning_task=data_args.task_name,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
use_auth_token=True if model_args.use_auth_token else None,
)
tokenizer = T5Tokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
use_auth_token=True if model_args.use_auth_token else None,
)
# print(tokenizer.get_vocab())
# model = AutoModelForSequenceClassification.from_pretrained(
model = T5ForConditionalGeneration.from_pretrained(
model_args.model_name_or_path,
from_tf=bool(".ckpt" in model_args.model_name_or_path),
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
use_auth_token=True if model_args.use_auth_token else None,
)
# if tokenizer.pad_token is None:
# tokenizer.pad_token = tokenizer.eos_token
# model.config.pad_token_id = model.config.eos_token_id
# Padding strategy
if data_args.pad_to_max_length:
padding = "max_length"
else:
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
padding = False
if data_args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
)
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
if data_args.pad_to_max_length:
# data_collator = default_data_collator
data_collator = DataCollatorForSeq2Seq(tokenizer)
elif training_args.fp16:
data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8)
else:
data_collator = None
def preprocess_function(examples, task_name):
# Tokenize the texts
sentence1_key = TASK_TO_KEYS[task_name][0]
sentence2_key = None if len(TASK_TO_KEYS[task_name]) == 1 else TASK_TO_KEYS[task_name][1]
sentence1_examples = examples[sentence1_key]
sentence2_examples = None if sentence2_key is None else examples[sentence2_key]
processed_examples = []
for i in range(len(sentence1_examples)):
elements = [
task_name,
sentence1_key+":",
sentence1_examples[i],
]
if sentence2_examples is not None:
elements += [
sentence2_key+":",
sentence2_examples[i],
]
processed_examples.append(" ".join(elements))
texts = (
(processed_examples,)
)
result = tokenizer(*texts, padding=padding, max_length=max_seq_length, truncation=True, return_tensors="np")
if "label" in examples:
labels = examples["label"]
labels = [label2text(task_name, label) for label in labels]
# Setup the tokenizer for targets
with tokenizer.as_target_tokenizer():
labels = tokenizer(labels, max_length=2, padding=padding, truncation=True, return_tensors="np")
# If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore
# padding in the loss.
if padding == "max_length":
labels["input_ids"] = [
[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]
]
result["labels"] = labels["input_ids"]
# del result['label']
return result
all_acc = []
all_loss = []
for task_key in TASK_TO_LABELS.keys():
loss = nn.CrossEntropyLoss()
dataset = load_dataset(
data_args.dataset_name, task_key, cache_dir=model_args.cache_dir
)
print(data_args.dataset_name, task_key, dataset)
dataset = dataset.map(
partial(preprocess_function, task_name=task_key),
batched=True,
load_from_cache_file=not data_args.overwrite_cache,
desc="Running tokenizer on dataset",
remove_columns=["idx", "label"] + list(TASK_TO_KEYS[task_key])
)
eval_name = "validation_matched" if task_key == "mnli" else "validation"
eval_dataset = dataset[eval_name]
# Log a few random samples from the training set:
for index in random.sample(range(len(eval_dataset)), 3):
logger.info(f"Sample {index} of the training set: {eval_dataset[index]}.")
metric = load_metric("accuracy")
print("eval_dataset", eval_dataset)
eval_dataloader = DataLoader(
eval_dataset,
batch_size=64,
collate_fn=data_collator,
)
label_tokens = [
tokenizer(label, max_length=2).input_ids[0]
for label in TASK_TO_LABELS['mnli']
if label is not None
]
model = model.to("cuda")
logits_list = []
labels_list = []
for batch in tqdm(eval_dataloader, desc=task_key):
input_ids = batch['input_ids'].to("cuda")
attention_mask = batch['attention_mask'].to("cuda")
outputs = model.generate(
input_ids=input_ids,
attention_mask=attention_mask,
do_sample=False, # disable sampling to test if batching affects output
return_dict_in_generate=True,
output_scores=True,
)
logits = outputs.scores[0][:, label_tokens]
predictions = np.argmax(logits.detach().cpu(), axis=-1)
labels = token2label(batch['labels'][:, 0].flatten(), label_tokens)
# print(predictions, labels)
metric.add_batch(
predictions=predictions,
references=labels
)
logits_list.append(logits.detach().cpu())
labels_list += labels
labels = torch.Tensor(labels_list).flatten().long()
logits = torch.cat(logits_list, dim=0)
eval_result = metric.compute()
eval_loss = loss(logits, labels)
print(labels.shape, logits.shape)
print(task_key, eval_result, eval_loss)
all_acc.append(eval_result['accuracy'])
all_loss.append(eval_loss.item())
import scipy.stats as stats
print("accuracy",stats.describe(all_acc))
print("loss",stats.describe(all_loss))
if __name__ == "__main__":
main() |
### NBA-BubblePlayerLevelAnalysisProject
### This is a script for a webscraper to scrape data from Basketball-Reference player pages
### This is version 1.3
# Load libraries
library(rvest)
library(dplyr)
library(tidyr)
library(here)
# Create a blank data frame with 2 empty columns for player names and links to be scraped from the index page.
PlayerTable <- data.frame(Player = "", Links = "")
# Create a loop that progresses through the alphabet.
for (i in 1:26) {
# Indexes on basketball-reference have a seperate page for each letter of the alphabet.
# Keeps track of the current letter, to be used with 'paste0' to construct the correct index address to access.
letCurrent = letters[i]
# The url for the current page is created using the 'paste0' function.
page <- read_html(paste0("https://www.basketball-reference.com/players/", letCurrent, "/"), as.data.frame=T)
# A temporary cache of player links is created. All links from the players table are scraped.
cachePlayerLinks <- page %>% html_nodes(xpath = '//*[@id="players"]') %>% html_nodes("a") %>% html_attr('href')
# Use subset to discard links that are not to players pages, such as college profiles.
# Only links that include "players/./" are kept
cachePlayerLinks <- subset(cachePlayerLinks, grepl("players/./", cachePlayerLinks))
# Scrape the players table to a temporary cached data frame.
cachePlayerTable <- page %>% html_nodes(xpath = '//*[@id="players"]') %>%
.[[1]] %>% html_table(fill = T)
# Add the player page links as a column to the cached player table.
cachePlayerTable$Links <- cachePlayerLinks
# Included in the player table is when players started and ended play in the NBA.
# Filter out all players who do not have 2020 season play in the range of when they played in the NBA.
# This does not necessarily mean that they have data for the targeted 19/20 season. This issue will be resolved
# in the data processing script.
cachePlayerTable <- filter(cachePlayerTable, 2020 >= cachePlayerTable$From, 2020 <= cachePlayerTable$To)
# Once irrelevant players have been dropped, keep only Player and Links columns and use
# 'rbind' to add the temporary cached player table to the overall PlayerTable data frame.
cachePlayerTable <- select(cachePlayerTable, Player, Links)
PlayerTable <- rbind(PlayerTable, cachePlayerTable)
# Sports Reference rules state "Currently we will block users sending requests to...
# our sites more often than twenty requests in a minute."
# Sys.Sleep is used to suspend operation after each request is processed, to avoid making too many requests of the site.
Sys.sleep(3.2)
}
### End of Loop
# Drop the first empty row of the PlayerTable data frame. Also reset the row names to be
# numerically correct.
PlayerTable <- PlayerTable[-1,]
rownames(PlayerTable) <- NULL
# Create a blank frame for the final Advanced player data.
AdvancedLeague <- data.frame()
AdvancedPlayoff <- data.frame()
# A new loop will access each page for each player and extract the 'Advanced' table.
# Set an Increment counter to keep track of where the loop is for certain functions.
aInc <- 1
# Create a loop going through the list of url segments accompaning player name.
for (i in PlayerTable$Links) {
# Set the url using the paste function, pulling the current players' web address from the Links column of PlayerTable.
tryCatch({
url <- paste("https://www.basketball-reference.com", PlayerTable$Links[[aInc]], sep = "")
pageobj <- read_html(url, as.data.frame=T, stringsAsFactors = TRUE)
# The advanced table is scraped using its' ID in the html. This is kept the same across all
# basketball-reference player pages and is known as 'advanced' for league data and 'playoffs_advanced' for playoffs.
# Both league and playoff data is scraped and stored temporarily in a data frame.
tempAdvancedLeague <- pageobj %>%
html_nodes("#advanced") %>%
.[[1]] %>%
html_table(fill=T)
tempAdvancedLeague$LeaguePlayoff <- "League"
tempAdvancedPlayoff <- pageobj %>%
html_nodes("#playoffs_advanced") %>%
.[[1]] %>%
html_table(fill=T)
tempAdvancedPlayoff$LeaguePlayoff <- "Playoff"
}, error = function(e){
e
})
# Add a 'Name' column to the temporary dataset and include the name of the player whose data it is with all entries
# associated with them.
tempAdvancedLeague$Name <- PlayerTable$Player[[aInc]]
tempAdvancedPlayoff$Name <- PlayerTable$Player[[aInc]]
# 'rbind' is used to add the data from the temporary data frame to the overall 'Advanced' frame.
AdvancedLeague <- rbind(AdvancedLeague, tempAdvancedLeague)
AdvancedPlayoff <- rbind(AdvancedPlayoff, tempAdvancedPlayoff)
# At the end of each loop cycle, the counter increments.
aInc <- aInc + 1
# Sports Reference rules state "Currently we will block users sending requests to...
# our sites more often than twenty requests in a minute."
# Sys.Sleep is used to suspend operation after each request is processed, to avoid making too many requests of the site.
Sys.sleep(3.2)
}
#### End of loop
# Use 'rbind' to combine the league and playoff data
Advanced <- rbind(AdvancedLeague, AdvancedPlayoff)
#Save the advanced datasets to the 'Data' folder.
here::here()
save(Advanced, file = file.path("data","Advanced.rda")) |
<?php
/*
* Copyright 2008 Google Inc.
*
* 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.
*/
/**
* Abstract storage class
*
* @author Chris Chabot <chabotc@google.com>
*/
abstract class W3TCG_Google_Cache_Abstract
{
abstract public function __construct(W3TCG_Google_Client $client);
/**
* Retrieves the data for the given key, or false if they
* key is unknown or expired
*
* @param String $key The key who's data to retrieve
* @param boolean|int $expiration Expiration time in seconds
*
*/
abstract public function get($key, $expiration = false);
/**
* Store the key => $value set. The $value is serialized
* by this function so can be of any type
*
* @param string $key Key of the data
* @param string $value data
*/
abstract public function set($key, $value);
/**
* Removes the key/data pair for the given $key
*
* @param String $key
*/
abstract public function delete($key);
} |
from __future__ import annotations
from typing import Any, AnyStr, Callable, Dict, List, Optional, Tuple, Type, TYPE_CHECKING, Union
from quart import Quart
from quart.datastructures import FileStorage
from quart.typing import (
HeadersValue as QuartHeadersValue,
ResponseReturnValue as QuartResponseReturnValue,
ResponseValue as QuartResponseValue,
StatusCode,
)
from quart.wrappers import Response
from werkzeug.datastructures import Headers
try:
from typing import Protocol
except ImportError:
from typing_extensions import Protocol # type: ignore
if TYPE_CHECKING:
from attrs import AttrsInstance
from msgspec import Struct
from pydantic import BaseModel
from pydantic.dataclasses import Dataclass
class DataclassProtocol(Protocol):
__dataclass_fields__: Dict
__dataclass_params__: Dict
__post_init__: Optional[Callable]
ModelTypes = Union["AttrsInstance", "BaseModel", "Dataclass", "DataclassProtocol", "Struct"]
Model = Union[ModelTypes, List[ModelTypes], Dict[str, ModelTypes]]
ResponseValue = Union[QuartResponseValue, Type[Model]]
HeadersValue = Union[QuartHeadersValue, Model]
ResponseReturnValue = Union[
QuartResponseReturnValue,
ResponseValue,
Tuple[ResponseValue, HeadersValue],
Tuple[ResponseValue, StatusCode],
Tuple[ResponseValue, StatusCode, HeadersValue],
]
class WebsocketProtocol(Protocol):
async def receive_json(self) -> dict: ...
async def send_json(self, data: dict) -> None: ...
class TestClientProtocol(Protocol):
app: Quart
async def _make_request(
self,
path: str,
method: str,
headers: Optional[Union[dict, Headers]],
data: Optional[AnyStr],
form: Optional[dict],
files: Optional[Dict[str, FileStorage]],
query_string: Optional[dict],
json: Any,
scheme: str,
root_path: str,
http_version: str,
scope_base: Optional[dict],
) -> Response: ... |
import React, {Component} from "react";
import Profile from "./Profile";
import {connect} from "react-redux";
import {getUserThunk} from "../../redux/profileReducer";
import Preloader from "../Utils/Preloader";
import withAuthRedirect from "../../hoc/withAuthRedirect";
import {compose} from "redux";
import {withRouter} from "react-router-dom";
import {UserType} from "../../types/types";
import {RootState} from "../../redux/store";
type MapStatePropsType = {
profile: UserType;
match: any;
}
type MapDispatchPropsType = {
getUser: (userId: number) => void;
}
type PropsType = MapStatePropsType & MapDispatchPropsType;
class ProfileContainer extends Component<PropsType> {
componentDidMount() {
const {userId} = this.props.match.params;
this.props.getUser(userId);
}
render() {
if (!this.props.profile) {
return <Preloader/>
}
return (
<Profile profile={this.props.profile}/>
);
}
}
const mapStateToProps = (state: RootState) => ({
profile: state.profilePage.profile,
})
export default compose(
connect(mapStateToProps, {getUser: getUserThunk}),
withAuthRedirect,
withRouter,
)(ProfileContainer); |
import { LineString } from "ol/geom";
import { getPoints } from "./api";
import { DistanceMemberPoint, MemberPoint, Point } from "./types";
import { useData } from "./useData";
import { getLength } from "ol/sphere";
import fromPoint from "./map/fromPoint";
import { useMemo } from "react";
const getDistance = (a: Point, b: Point): number =>
getLength(new LineString([fromPoint(a), fromPoint(b)]));
const sortByDistance = (points: MemberPoint[], position?: Point | null) =>
points
.map((p) => ({
...p,
distance: position ? getDistance(p, position) : 0,
}))
.sort((a, b) => a.distance - b.distance);
type PointsState = {
points: DistanceMemberPoint[];
status: "success" | "loading" | "error";
message: string;
};
export const usePoints = (position?: Point | null): PointsState => {
const { data: points, status, message } = useData(getPoints);
const pointsState = useMemo<PointsState>(
() => ({
points: status !== "success" ? [] : sortByDistance(points, position),
status,
message,
}),
[points, position]
);
return pointsState;
}; |
//{ Driver Code Starts
// Initial Template for c++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
bool is_pal(string s, int left, int right)
{
while(left <= right)
{
if(s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
int solve(int index, string str, vector<int> &dp)
{
if(index >= str.length()) return 0;
if(dp[index] != -1) return dp[index];
int mini = 1e9;
for(int i = index; i < str.length(); i++)
{
if(is_pal(str, index, i))
{
int cnt = 1 + solve(i+1, str, dp);
mini = min(mini, cnt);
}
}
return dp[index] = mini;
}
int palindromicPartition(string str)
{
int n = str.length();
vector<int> dp(n+1,-1);
return solve(0, str, dp)-1;
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
string str;
cin>>str;
Solution ob;
cout<<ob.palindromicPartition(str)<<"\n";
}
return 0;
}
// } Driver Code Ends |
import "./App.css";
import { useEffect, useState } from "react";
import axios from "axios";
import { useSelector } from "react-redux/es/hooks/useSelector";
// import Header from "./components/layout/Header/Header";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import WebFont from "webfontloader";
import Footer from "./components/layout/Footer/Footer";
import Home from "./components/Home/Home";
import MetaData from "./components/layout/Header/MetaData";
import ProductDetails from "./components/Product/ProductDetails";
import Products from "./components/Product/Products";
import Search from "./components/Product/Search.js";
import LoginSignup from "./components/User/LoginSignup";
import UserOptions from "./components/layout/Header/UserOptions";
import { loadUser } from "./actions/userActions";
import Profile from "./components/User/Profile";
import UpdateProfile from "./components/User/UpdateProfile";
import UpdatePassword from "./components/User/UpdatePassword";
import ForgotPassword from "./components/User/ForgotPassword";
import ResetPassword from "./components/User/ResetPassword";
import Cart from "./components/Cart/Cart";
import Shipping from "./components/Cart/Shipping";
import ConfirmOrder from "./components/Cart/ConfirmOrder";
import OrderSuccess from "./components/Cart/OrderSuccess";
import MyOrders from "./components/Order/MyOrders";
import Payment from "./components/Cart/Payment";
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import store from "./store";
import OrderDetails from "./components/Order/OrderDetails";
import Dashboard from "./components/Admin/Dashboard";
import ProductsList from "./components/Admin/ProductsList";
import ProtectedRoute from "./components/Route/ProtectedRoute";
import NewProduct from "./components/Admin/NewProduct";
import UpdateProduct from "./components/Admin/UpdateProduct";
import OrdersList from "./components/Admin/OrdersList";
import ProcessOrder from "./components/Admin/ProcessOrder";
import UsersList from "./components/Admin/UsersList";
import UpdateUser from "./components/Admin/UpdateUser";
import ProductReviews from "./components/Admin/ProductReviews";
import Contact from "./components/layout/Contact";
import Layout from "./Layout.js"
import VendorDashboard from "./components/Admin/VendorDashboard"
import AdminProtectedRoute from "./components/Route/AdminProtectedRoute";
function App() {
const { user, isAuthenticated } = useSelector((state) => state.user);
const [stripeApiKey, setStripeApiKey] = useState("");
async function getStripeApiKey() {
const { data } = await axios.get("/api/v1/stripeapikey");
setStripeApiKey(data.stripeApiKey);
}
useEffect(() => {
WebFont.load({
google: {
families: ["Roboto"],
},
});
// Assuming loadUser() and getStripeApiKey() return Promises
const loadUserData = () => store.dispatch(loadUser());
const getStripeApiKeyData = () => getStripeApiKey();
// Function to fetch the stripe key after the user is logged in
const fetchStripeKeyAfterLogin = async () => {
try {
await loadUserData();
await getStripeApiKeyData();
} catch (error) {
// Handle errors here, e.g., display an error message or redirect to login page
console.error("Error loading user data or Stripe API key:", error);
}
};
// Call the function to fetch the data after the user is logged in
fetchStripeKeyAfterLogin();
}, []);
return (
<Router>
<MetaData title="ECOMMERCE" />
{/* <Header /> */}
{isAuthenticated && <UserOptions user={user} />}
<Routes>
<Route element={<Layout/>}>
<Route index element={<Home />} />
<Route path="/product/:id" element={<ProductDetails />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:keyword" element={<Products />} />
<Route path="/search" element={<Search />} />
<Route path="/login" element={<LoginSignup />} />
<Route path="/account" element={<ProtectedRoute>
<Profile />
</ProtectedRoute>} />
<Route
path="/me/update"
element={
<ProtectedRoute>
<UpdateProfile />
</ProtectedRoute>
}
/>
<Route
path="/password/update"
element={
<ProtectedRoute>
<UpdatePassword />
</ProtectedRoute>
}
/>
<Route
path="/password/forgot"
element={
<ProtectedRoute>
<ForgotPassword />
</ProtectedRoute>
}
/>
<Route
path="/password/reset/:token"
element={
<ResetPassword />
}
/>
<Route
path="/cart"
element={
<ProtectedRoute>
<Cart />
</ProtectedRoute>
}
/>
<Route
path="/shipping"
element={
<ProtectedRoute>
<Shipping />
</ProtectedRoute>
}
/>
<Route
path="/order/confirm"
element={
<ProtectedRoute>
<ConfirmOrder />
</ProtectedRoute>
}
/>
<Route
path="/process/payment"
element={
<ProtectedRoute>
<Elements stripe={loadStripe(stripeApiKey)}>
<Payment stripeApiKey={stripeApiKey} />
</Elements>
</ProtectedRoute>
}
/>
<Route
path="/success"
element={
<ProtectedRoute>
<OrderSuccess />
</ProtectedRoute>
}
/>
<Route
path="/orders"
element={
<MyOrders />
}
/>
<Route
path="/order/:id"
element={
<ProtectedRoute>
<OrderDetails />
</ProtectedRoute>
}
/>
<Route
path="/admin/dashboard"
element={
<AdminProtectedRoute isAdmin={true}>
<Dashboard />
</AdminProtectedRoute>
}
/>
{user?.role === 'travelAgency' && (
<Route
path="/travelagency/dashboard"
element={<VendorDashboard />}
/>
)}
<Route
path="/admin/products"
element={
<ProtectedRoute isAdmin={true}>
<ProductsList />
</ProtectedRoute>
}
/>
<Route
path="/admin/product/new"
element={
<ProtectedRoute isAdmin={true}>
<NewProduct/>
</ProtectedRoute>
}
/>
<Route
path="/admin/product/:id"
element={
<ProtectedRoute isAdmin={true}>
<UpdateProduct />
</ProtectedRoute>
}
/>
<Route
path="/admin/orders"
element={
<ProtectedRoute isAdmin={true}>
<OrdersList />
</ProtectedRoute>
}
/>
<Route path="/admin/users" element={
<AdminProtectedRoute isAdmin={true}>
<UsersList/>
</AdminProtectedRoute>
} />
<Route
path="/admin/reviews"
element={
<ProtectedRoute isAdmin={true}>
<ProductReviews />
</ProtectedRoute>
}
/>
<Route
path="/admin/user/:id"
element={
<ProtectedRoute isAdmin={true}>
<UpdateUser />
</ProtectedRoute>
}
/>
<Route
path="/admin/order/:id"
element={
<ProtectedRoute isAdmin={true}>
<ProcessOrder/>
</ProtectedRoute>
}
/>
<Route path="/contact" element={<Contact />} />
</Route>
</Routes>
<Footer />
</Router>
);
}
export default App; |
// Time complexity:
// Space complexity:
// #include <vector>
#include <algorithm>
using namespace std;
int getWays(int n, vector<int> &mem) {
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
if (find(begin(mem), end(mem), n) != end(mem)) {
return mem[n];
}
return mem[n] = getWays(n - 1, mem) + getWays(n - 1, mem);
}
int climbStairs(int A) {
vector<int> mem = {};
return getWays(A, mem);
}
/*
Write a function that does the following task.
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can
you climb to the top?
Mention the time and space complexity of your solution.
Constraints:
2 <= n <= 45
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
*/ |
import { NonexistentSurveyError } from '@/domain/use-cases/survey-result/save-survey-result'
import { LoadSurveySummaryUseCase } from '@/domain/use-cases/survey/load-survey-summary'
import { LoadSurveySummaryController } from '@/presentation/controllers'
import { internalServerError, notFound, ok } from '@/presentation/utils'
import {
createLoadSurveySummaryStub,
fakeSurveySummary,
} from '../../domain/mocks'
describe('LoadSurveySummaryController', () => {
it('should call LoadSurveySummaryUseCase with the survey id', async () => {
const { sut, loadSurveySummaryUseCaseStub } = createSut()
const request = fakeRequest()
await sut.handle(request)
expect(loadSurveySummaryUseCaseStub.load).toHaveBeenCalledWith(
request.surveyId
)
})
it('should return notFoundError if LoadSurveySummaryUseCase throws a SurveyNotFoundError', async () => {
const { sut, loadSurveySummaryUseCaseStub } = createSut()
const request = fakeRequest()
const surveyId = request.surveyId
jest.spyOn(loadSurveySummaryUseCaseStub, 'load').mockRejectedValueOnce(
new NonexistentSurveyError({
surveyId,
})
)
const response = await sut.handle(request)
expect(response).toEqual(
notFound({
cause: expect.any(NonexistentSurveyError),
entityName: 'Survey',
missingId: surveyId,
})
)
})
it('should return internalServerError if LoadSurveySummaryUseCase throws a unexpected error', async () => {
const { sut, loadSurveySummaryUseCaseStub } = createSut()
const request = fakeRequest()
const stubbedError = new Error('Something went wrong')
jest
.spyOn(loadSurveySummaryUseCaseStub, 'load')
.mockRejectedValueOnce(stubbedError)
const response = await sut.handle(request)
expect(response).toEqual(
internalServerError({
message: stubbedError.message,
name: stubbedError.name,
stack: stubbedError.stack,
})
)
})
it('should return a survey summary on success', async () => {
const { sut } = createSut()
const request = fakeRequest()
const response = await sut.handle(request)
expect(response).toEqual(ok(fakeSurveySummary()))
})
})
interface SutFactoryResponse {
sut: LoadSurveySummaryController
loadSurveySummaryUseCaseStub: LoadSurveySummaryUseCase
}
const createSut = (): SutFactoryResponse => {
const loadSurveySummaryUseCaseStub = createLoadSurveySummaryStub()
const sut = new LoadSurveySummaryController(loadSurveySummaryUseCaseStub)
return {
sut,
loadSurveySummaryUseCaseStub,
}
}
const fakeRequest = (): LoadSurveySummaryController.Request => ({
surveyId: 'survey_id',
}) |
<template>
<div>
<h3 class="text-center">
{{ monthName }} {{ year }}
<i class="fa fa-angle-left fa-border previous-month" v-on:click="() => {incrementMonth(-1)}"></i>
<i class="fa fa-angle-right fa-border next-month" v-on:click="() => {incrementMonth(1)}"></i>
</h3>
<div class="container">
<div class="row">
<div class="col">Sunday</div>
<div class="col">Monday</div>
<div class="col">Tuesday</div>
<div class="col">Wednesday</div>
<div class="col">Thursday</div>
<div class="col">Friday</div>
<div class="col">Saturday</div>
</div>
<div class="row" v-for="rowNum in 6" v-bind:key="rowNum">
<div class="col border" v-for="colNum in 7" v-bind:key="colNum" v-bind:class="calcClass(rowNum, colNum)">
<div class="day">
<span v-if="calcDayNum(rowNum, colNum)">{{ calcDayNum(rowNum, colNum) }}</span>
<span class="attendance-indicator">{{ getNotes(rowNum, colNum) }}</span>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
const moment = require('moment')
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
export default {
name: 'Attendance',
data: () => ({
year: moment().year(),
monthIdx: moment().month()
}),
methods: {
incrementMonth: function (increment) {
if (increment < 0 && moment(`${this.year}-${this.monthIdx + 1}`, 'YYYY-M').isBefore(this.calendarData.firstDate)) {
return
}
if (increment > 0 && moment(`${this.year}-${this.monthIdx + 2}`, 'YYYY-M').isAfter(this.calendarData.lastDate)) {
return
}
this.monthIdx += increment
if (this.monthIdx < 0) {
this.year -= 1
}
if (this.monthIdx > 11) {
this.year += 1
}
this.monthIdx = (this.monthIdx + 12) % 12
},
calcDayNum: function (row, col) {
const num = ((row - 1) * 7 + col) - moment(`${this.year}-${this.monthIdx + 1}-1`, 'YYYY-M-D').day()
const thisMonth = moment(`${this.year}-${this.monthIdx + 1}`, 'YYYY-M')
if (num <= 0 || num > thisMonth.daysInMonth()) {
return null
}
return num
},
calcClass: function (row, col) {
const day = this.calcDayNum(row, col)
const month = this.monthIdx + 1
const year = this.year
if (day === null) {
return 'null-day'
}
const date = moment(`${year}-${month}-${day}`, 'YYYY-M-D')
if ([0, 6].indexOf(date.day()) !== -1) {
return 'weekend-day'
}
if (date.isBefore(this.calendarData.firstDate)) {
return 'outside-school-year'
}
if (date.isAfter(this.calendarData.lastDate)) {
return 'outside-school-year'
}
const dateStr = date.format('YYYY-MM-DD')
if (this.calendarData.nonInstructionalDays.indexOf(dateStr) !== -1) {
return 'no-school-day'
}
return 'normal-day'
},
getNotes: function (row, col) {
const day = this.calcDayNum(row, col)
const month = this.monthIdx + 1
const year = this.year
if (day === null) {
return ''
}
const date = moment(`${year}-${month}-${day}`, 'YYYY-M-D')
if ([0, 6].indexOf(date.day()) !== -1) {
return ''
}
const dateStr = date.format('YYYY-MM-DD')
if (this.calendarData.nonInstructionalDays.indexOf(dateStr) !== -1) {
return ''
}
if (dateStr in this.calendarData.daysAbsent) {
const code = this.calendarData.daysAbsent[dateStr]
return code
}
return ''
}
},
computed: {
monthName: function () {
return months[this.monthIdx]
},
calendarData: function () {
return this.$store.state.Student.calendarData
}
}
}
</script>
<style lang="sass" scoped>
.null-day
background-color: white
.outside-school-year
background-color: white
.weekend-day
background-color: white
.no-school-day
background-color: white
.normal-day
background-color: rgb(244, 247, 255)
.attendance-indicator
position: absolute
bottom: 0
right: 0.5em
color: red
.day
height: 4em
.previous-month
position: absolute
left: 30%
.next-month
position: absolute
right: 30%
.next-month:hover, .previous-month:hover
background-color: #fdfdfd
.next-month:active, .previous-month:active
background-color: #f1f1f1
</style> |
/*
Name: Gowtham Prasad
Email: gdprasad@crimson.ua.edu
Course Section: Fall 2023 CS 201
Homework #: 3
Instructions to compile: g++ -std=c++20 hw3.cpp
Instructions to run: ./a.exe <database file> <query file>
*/
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <regex>
#include <chrono>
using namespace std;
int main (int argc, char** argv) {
string line;
unordered_map<string, vector<string>> actorMap, movieMap; // Maps actors to movies and movies to actors
ifstream databaseFile(argv[1]), queryFile(argv[2]);
regex delim("/");
// Check for correct number of arguments
if (argc != 3) {
cout << "Usage: ./a.exe <database file> <query file>" << endl;
exit(1);
}
// Check if files can be opened
if (!databaseFile.is_open() && !queryFile.is_open()) {
cout << "Unable to open files: " << "\"" << argv[1] << "\" and \"" << argv[2] << "\"" << endl;
exit(1);
}
else if (!databaseFile.is_open()) {
cout << "Unable to open file: \"" << argv[1] << "\"" << endl;
exit(1);
}
else if (!queryFile.is_open()) {
cout << "Unable to open file: \"" << argv[2] << "\"" << endl;
exit(1);
}
chrono::time_point<chrono::steady_clock> constructBegin = chrono::steady_clock::now(); // Start timer
while (getline(databaseFile, line)) { // Construct data structure from database file
auto begin = sregex_token_iterator(line.begin(), line.end(), delim, -1);
auto end = sregex_token_iterator();
string name = *(begin++);
for (auto text = begin; text != end; text++) { // Add movie to movieMap
movieMap[name].push_back(*text);
}
for (vector<string>::iterator actor = movieMap[name].begin(); actor != movieMap[name].end(); actor++) { // Add actor to actorMap
actorMap[*actor].push_back(name);
}
}
chrono::time_point<chrono::steady_clock> constructEnd = chrono::steady_clock::now(); // End timer
ofstream outFile(string(argv[1]).substr(0, string(argv[1]).find(".")) + "_output.txt"); // Create output file
chrono::time_point<chrono::steady_clock> printBegin = chrono::steady_clock::now(); // Start timer
while (getline(queryFile, line)) { // Read query file and search data structure
if (actorMap.find(line) != actorMap.end()) { // Check if actor exists in actorMap
outFile << "Movies starring " << line << ":" << endl;
for (vector<string>::iterator movie = actorMap[line].begin(); movie != actorMap[line].end(); movie++) {
outFile << "\t" << *movie << endl;
}
outFile << endl;
}
else if (movieMap.find(line) != movieMap.end()) { // Check if movie exists in movieMap
outFile << "Actors starring in " << line << ":" << endl;
for (vector<string>::iterator actor = movieMap[line].begin(); actor != movieMap[line].end(); actor++) {
outFile << "\t" << *actor << endl;
}
outFile << endl;
}
else { // Actor or movie not found
cout << line << " Not Found" << endl;
}
}
chrono::time_point<chrono::steady_clock> printEnd = chrono::steady_clock::now(); // End timer
chrono::duration<double> constructionTime = constructEnd - constructBegin, printTime = printEnd - printBegin; // Calculate time taken
cout << endl << "Time to construct data structure: " << constructionTime.count() << " seconds" << endl;
cout << "Time to search data structure: " << printTime.count() << " seconds" << endl;
cout << "Total time: " << constructionTime.count() + printTime.count() << " seconds" << endl << endl;
line.clear();
actorMap.clear();
movieMap.clear();
databaseFile.close();
queryFile.close();
outFile.close();
return 0;
} |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAccFormatsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('acc_formats', function (Blueprint $table) {
$table->id();
$table->foreignId('accountability_id')->constrained()->onDelete('cascade');
$table->dateTime('initial_date');
$table->dateTime('final_date');
$table->string('description');
$table->string('type')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('acc_formats');
}
} |
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import src.utils
import src.params
import os
def mod_ax(ax):
"""add vert/horiz lines, specify ticks, and add labels to ax"""
ax.axhline(0, ls="-", c="gray", lw=0.7)
ax.axvline(0, ls="-", c="gray", lw=0.7)
ax.set_xticks(ticks=np.arange(-12, 6, 3))
ax.set_xlim([-13, 3])
ax.set_xlabel("Lag (days)")
return ax
def load_data():
agg_r1 = xr.open_dataset(f"./composite_agg_v850_amj_r1.nc")
agg_r2 = xr.open_dataset(f"{src.params.DATA_PREPPED_FP}/composite_agg_v850_amj.nc")
return agg_r1, agg_r2
def main():
## set plotting style
sns.set()
src.params.set_plot_style()
## Load data
agg_r1, agg_r2 = load_data()
## Make plot
aspect = 3.5
width = src.params.plot_params["max_width"]
height = width / aspect
fig = plt.figure(figsize=(width, height), layout="constrained")
gs = fig.add_gridspec(nrows=1, ncols=5, width_ratios=[1, 0.1, 1, 0.1, 1])
## E and P
ax0 = fig.add_subplot(gs[0])
colors = [sns.color_palette("colorblind")[i] for i in [5, 9]]
masks = ["Total", "Midwest"]
ax0.plot(agg_r1.lag, agg_r1["E_track"].sel(mask="Total"), c=colors[0], ls="--")
ax0.plot(agg_r1.lag, agg_r1["P"].sel(mask="Midwest"), c=colors[1], ls="--")
ax0.plot(
agg_r2.lag,
agg_r2["E_track"].sel(mask="Total"),
c=colors[0],
label="Tracked evap.",
)
ax0.plot(
agg_r2.lag,
agg_r2["P"].sel(mask="Midwest"),
c=colors[1],
label="Midwest precip.",
)
ax0.legend()
ax0 = mod_ax(ax0)
ax0.set_ylabel("Anomaly ($mm$)")
## Oc and La
ax2 = fig.add_subplot(gs[2])
colors = [sns.color_palette()[i] for i in [0, 2, 1]]
masks = ["Ocean", "Land", "Midwest"]
for c, m in zip(colors, masks):
ax2.plot(agg_r2.lag, agg_r2["E_track"].sel(mask=m), c=c, label=f"{m}")
ax2.plot(agg_r1.lag, agg_r1["E_track"].sel(mask=m), c=c, ls="--")
ax2.legend()
ax2 = mod_ax(ax2)
## Atl and Pac
ax4 = fig.add_subplot(gs[4])
colors = [sns.color_palette("mako")[i] for i in [3, 0]]
masks = ["Atlantic", "Pacific"]
for c, m in zip(colors, masks):
ax4.plot(agg_r2.lag, agg_r2["E_track"].sel(mask=m), c=c, label=f"{m}")
ax4.plot(agg_r1.lag, agg_r1["E_track"].sel(mask=m), c=c, ls="--")
ax4.legend()
ax4 = mod_ax(ax4)
## Label subplots
ax0 = src.utils.label_subplot(
ax=ax0, label="a)", posn=(0.1, 0.1), transform=ax0.transAxes
)
ax2 = src.utils.label_subplot(
ax=ax2, label="b)", posn=(0.1, 0.1), transform=ax2.transAxes
)
ax4 = src.utils.label_subplot(
ax=ax4, label="c)", posn=(0.1, 0.1), transform=ax4.transAxes
)
## save
src.utils.save(fig=fig, fname="r2_r1_comp", is_supp=True)
plt.close(fig)
return
if __name__ == "__main__":
src.params.set_plot_style()
main() |
<?php
namespace App\Http\Controllers;
use App\Models\LeaveType;
use App\Models\TeacherLeave;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
class TeacherApproveController extends Controller
{
public function allLeave()
{
if (request()->ajax()) {
$query = TeacherLeave::query();
$userId = auth()->user()->id;
if (auth()->user()->hasRole('admin')) {
$teacherleaves = $query->latest()->get();
} else {
$teacherleaves = $query->where('user_id',$userId)->latest();
}
return DataTables::of($teacherleaves)
->addIndexColumn()
->addColumn('status', function ($row) {
if ($row->status == 0) {
return '<p class="text-dark bg-warning rounded-pill">Pending</p>';
} elseif ($row->status == 1) {
return '<p class="text-white bg-success rounded-pill">Approved</p>';
} elseif ($row->status == 2) {
return '<p class="text-dark bg-danger rounded-pill">Declined</p>';
}
})
->addColumn('file', function ($row) {
return asset('storage/'.$row->file);
})
->addColumn('name', function ($row) {
// return $row->UserName->name??'N/A';
return isset($row->UserName)?$row->UserName->name:'N/A';
})
->addColumn('action', function ($row) {
// Check if the status is 0 (pending)
if ($row->status === 0) {
$approveRoute = route('staff.approveLeave', $row->id);
$declineRoute = route('staff.declineLeave', $row->id);
$buttons = '<form action="' . $approveRoute . '" method="POST">' . csrf_field() .
'<button type="submit" class="btn btn-success">Approve</button></form>';
$buttons .= '<form action="' . $declineRoute . '" method="POST">' . csrf_field() .
'<button type="submit" class="btn btn-danger">Decline</button></form>';
return $buttons;
} else {
// If status is not 0, return an empty string (hide the buttons)
return '';
}
})
->rawColumns(['status', 'file', 'action']) // Declare rawColumns
->make(true);
}
$leave = LeaveType::get();
$teacherleaves = TeacherLeave::get();
return view('backend.staff.approveTeacherLeave', compact('teacherleaves','leave'));
}
// public function approveLeave(Request $request)
// {
// // Validate the incoming request
// $request->validate([
// 'leave_id' => 'required|exists:teacher_leaves,id',
// 'action' => 'required|in:approve,decline',
// ]);
// $leaveId = $request->input('leave_id');
// $action = $request->input('action');
// // Find the leave by ID
// $leave = TeacherLeave::findOrFail($leaveId);
// // Update the status based on the action
// if ($action == 'approve') {
// $leave->status = 1; // Approved
// } elseif ($action == 'decline') {
// $leave->status = 2; // Declined
// }
// // Save the updated leave status
// $leave->save();
// // Redirect back with a success message
// return redirect()->back()->with('success', 'Leave request ' . ucfirst($action) . 'd successfully.');
// }
public function approveLeave(Request $request, $id)
{
$leave = TeacherLeave::findOrFail($id);
$leave->status = 1; // Set status to approved
$leave->save();
return redirect()->back()->with('success', 'Leave request approved successfully.');
}
public function declineLeave(Request $request, $id)
{
$leave = TeacherLeave::findOrFail($id);
$leave->status = 2; // Set status to declined
$leave->save();
return redirect()->back()->with('success', 'Leave request declined successfully.');
}
} |
---
title: "Replication in Parts"
format: html
filters:
- include-code-files
bibliography: inputs/references.bib
---
This is a Quarto [@Allaire_Quarto_2022] Document.
## Includes
### Text
{{< include inputs/_snippet.qmd >}}
### Scripts
We can also include scripts using the [`include-code-files`](https://github.com/quarto-ext/include-code-files) filter extension:
``` {.stata include="inputs/myjob.do" filename="myjob.do"}
```
### Stata `dyndoc`
This content in this section is HTML generated using the `dyndoc` command in Stata as described in this [blog post](https://www.techtips.surveydesign.com.au/post/how-to-create-an-html-webpage-in-stata-using-markdown):
{{< include inputs/dyndoc-example1-html.html >}}
## Exercises
1. Add your own text and code into the `inputs/` folder.
2. Add least one additional text snippet and one script to this document.
3. Add an additional citation.
## References |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Quản Lý Đơn Hàng</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body style="background-color: #ced4da;">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/customers">Khách Hàng </a>
</li>
<li class="nav-item">
<a class="nav-link" href="/donhang">Đơn Hàng</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" th:action="@{/donhang/search}" method = "get">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name = "inputSearch">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Tìm Đơn Hàng</button>
</form>
</div>
</nav>
<h1>Danh Sách Đơn Hàng</h1>
<a href="donhang/new" class="text-decoration-none float-left" >
<button class="btn btn-secondary " id="create-btn-donhang">
Thêm Đơn Hàng
</button>
</a>
<br/><br/><br/>
<div align="center">
<table class="table table-dark">
<thead>
<tr>
<th>ID</th>
<th>Tên Khách Hàng</th>
<th>Tên Mặt Hàng</th>
<th>Số Lượng</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="kh : ${listDonHang}">
<td th:text="${kh.iddonhang}"></td>
<td th:text="${kh.tenkhachhang}"></td>
<td th:text="${kh.tenmathang}"></td>
<td th:text="${kh.soluong}"></td>
<td>
<a th:href="@{'/donhang/edit/' + ${kh.iddonhang}}" th:id="@{'edit-'+${kh.iddonhang}}">Sửa </a>
<a th:href="@{'/donhang/delete/' + ${kh.iddonhang}}" th:id="@{'delete-'+${kh.iddonhang}}">Xóa</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html> |
use tch::{self, IndexOp, Tensor};
use std::path::{Path, PathBuf};
use punkt::{SentenceTokenizer, TrainingData};
use punkt::params::Standard;
use fancy_regex::Regex;
mod treebank_word_tokenizer;
mod phonemizer;
mod text_cleaner;
use treebank_word_tokenizer::TreebankWordTokenizer;
use phonemizer::text_to_phonemes;
use text_cleaner::TextCleaner;
use crate::options::{TTSOptions, TTSDevice};
use super::TextToSpeechBackend;
const MEAN: f64 = -4.0;
const STD: f64 = 4.0;
const STD_TOKEN_COUNT: usize = 60;
const STD_SAMPLE_LENGTH: usize = 72000;
const ALPHA: f64 = 0.3;
const BETA: f64 = 0.9;
const MU: f64 = 0.7;
pub struct StyleTTSBackend {
device: tch::Device,
style_ref: tch::Tensor,
}
impl StyleTTSBackend {
pub fn new(options: TTSOptions) -> anyhow::Result<Self> {
let device = match options.device {
TTSDevice::Cpu => tch::Device::Cpu,
TTSDevice::Cuda => tch::Device::Cuda(0)
};
let style_ref = Tensor::new();
Ok(Self { device, style_ref })
}
}
impl TextToSpeechBackend for StyleTTSBackend {
fn train(
&mut self,
ref_samples: Vec<f32>,
) -> anyhow::Result<()> {
self.style_ref = self.compute_style(ref_samples)?;
Ok(())
}
fn predict(
&mut self,
text: String,
) -> anyhow::Result<Vec<f32>> {
if self.style_ref.size().len() == 1 && self.style_ref.size()[0] == 0 {
panic!("Error: reference style is not initialized! Run train before running predict!");
}
let mut sentences: Vec<String> = self.split_by_any_sep(text);
let mut i: i32 = 0;
while i < sentences.len() as i32 - 1 {
if sentences[i as usize].len() + sentences[i as usize + 1].len() < 51 {
sentences[i as usize] = sentences[i as usize].clone() + " " + &sentences[i as usize + 1];
sentences.remove(i as usize + 1);
i -= 1;
}
i += 1;
}
println!("{:?}", sentences);
let treebank_word_tokenizer = TreebankWordTokenizer::new();
let mut all_out_vecs: Vec<Vec<f32>> = Vec::new();
let mut s_prev: Option<Tensor> = None;
for sent in sentences {
let mut s_ref_1 = tch::Tensor::ones(self.style_ref.size(), (self.style_ref.kind(), self.style_ref.device()));
s_ref_1.copy_(&self.style_ref);
let mut single_text = sent.trim().to_string();
single_text = single_text.replace("\"", "");
let english = TrainingData::english();
let punkt_tokenizer = SentenceTokenizer::<Standard>::new(&single_text, &english);
let mut tokens_vec: Vec<String> = Vec::new();
for sub_s in punkt_tokenizer {
let phonemized_sentence = text_to_phonemes(sub_s, "en-us", None, false, false)?;
let mut phoneme = phonemized_sentence[0].clone();
let single_tokens = treebank_word_tokenizer.tokenize(phoneme, false);
tokens_vec.extend(single_tokens);
}
let merged_tokens = tokens_vec.join(" ");
let text_cleaner = TextCleaner::new();
let mut tokens_from_string = text_cleaner.clean_text(&merged_tokens);
tokens_from_string.insert(0, 0);
if tokens_from_string.len() <= STD_TOKEN_COUNT {
while tokens_from_string.len() < STD_TOKEN_COUNT {
tokens_from_string.push(1 as i64);
}
}
else {
panic!("Error: tokens count should be smaller or equal to 50. The threshold shoul be adjusted. Received: {}", tokens_from_string.len());
}
let tokens = Tensor::of_slice(&tokens_from_string).to_device(self.device).to_kind(tch::Kind::Int64).unsqueeze(0);
let mut tokens_1 = tch::Tensor::ones(&[1, STD_TOKEN_COUNT as i64], (tch::Kind::Int64, self.device));
tokens_1.copy_(&tokens);
let input_lengths = tch::Tensor::of_slice(&[*tokens.size().last().unwrap() as i64]).to(self.device);
let mut input_lengths_1 = tch::Tensor::ones(input_lengths.size(), (input_lengths.kind(), input_lengths.device()));
input_lengths_1.copy_(&input_lengths);
let mut input_lengths_2 = tch::Tensor::ones(input_lengths.size(), (input_lengths.kind(), input_lengths.device()));
input_lengths_2.copy_(&input_lengths);
let text_mask = self.length_to_mask(&input_lengths);
let mut text_mask_1 = tch::Tensor::ones(text_mask.size(), (text_mask.kind(), text_mask.device()));
text_mask_1.copy_(&text_mask);
let attention_mask = tch::Tensor::bitwise_not(&text_mask).to_kind(tch::Kind::Int64);
let text_encoder = tch::CModule::load(self.resolve_path_to_model("text_encoder.pt"))?;
let t_en = text_encoder.forward_ts(&[tokens, input_lengths, text_mask])?;
let bert = tch::CModule::load(self.resolve_path_to_model("bert_dur.pt"))?;
let bert_dur = bert.forward_ts(&[tokens_1, attention_mask])?;
let mut bert_dur_1 = tch::Tensor::ones(bert_dur.size(), (bert_dur.kind(), bert_dur.device()));
bert_dur_1.copy_(&bert_dur);
let bert_encoder = tch::CModule::load(self.resolve_path_to_model("bert_encoder.pt"))?;
let d_en = bert_encoder.forward_ts(&[bert_dur])?.transpose(-1, -2);
let noise = tch::Tensor::randn(&[1, 1, 256], (tch::Kind::Float, self.device));
let sampler_embd = bert_dur_1.i(0).unsqueeze(0);
let sampler = tch::CModule::load(self.resolve_path_to_model("sampler.pt"))?;
let mut s_pred = sampler.forward_ts(&[noise, sampler_embd, s_ref_1])?.squeeze_dim(0);
if s_prev.is_some() {
s_pred = MU * s_prev.unwrap() + (1.0 - MU) * s_pred;
}
let mut s = s_pred.i((.., 128..));
s = BETA * s + (1.0 - BETA) * self.style_ref.i((.., 128..));
let mut s_1 = tch::Tensor::ones(s.size(), (s.kind(), s.device()));
s_1.copy_(&s);
let mut s_vec_1: Vec<tch::Tensor> = Vec::new();
let mut s_vec_2: Vec<tch::Tensor> = Vec::new();
for i in 0..3 {
s_vec_1.push(tch::Tensor::ones(s.size(), (s.kind(), s.device())));
s_vec_1.last_mut().unwrap().copy_(&s);
s_vec_2.push(tch::Tensor::ones(s.size(), (s.kind(), s.device())));
s_vec_2.last_mut().unwrap().copy_(&s);
}
s_vec_1.reverse();
s_vec_2.reverse();
let mut ref_ = s_pred.i((.., ..128));
ref_ = ALPHA * ref_ + (1.0 - ALPHA) * self.style_ref.i((.., ..128));
let mut ref_1 = tch::Tensor::ones(ref_.size(), (ref_.kind(), ref_.device()));
ref_1.copy_(&ref_);
s_pred = Tensor::cat(&[ref_1, s_1], -1);
let predictor_text_encoder = tch::CModule::load(self.resolve_path_to_model("predictor_text_encoder.pt"))?;
let d = predictor_text_encoder.forward_ts(&[d_en, s, input_lengths_1, text_mask_1])?;
let mut d_1 = tch::Tensor::ones(d.size(), (d.kind(), d.device()));
d_1.copy_(&d);
let predictor_lstm = tch::CModule::load(self.resolve_path_to_model("predictor_lstm.pt"))?;
let x = predictor_lstm.forward_ts(&[d])?;
let mut x_1 = tch::Tensor::ones(x.size(), (x.kind(), x.device()));
x_1.copy_(&x);
let predictor_duration_proj = tch::CModule::load(self.resolve_path_to_model("predictor_duration_proj.pt"))?;
let duration = predictor_duration_proj.forward_ts(&[x])?;
let dim: Vec<i64> = vec![-1];
let duration = duration.sigmoid().sum_dim_intlist(dim, false, tch::Kind::Float);
let pred_dur = duration.squeeze().round().clamp_min(1.0);
// let pred_dur = tch::Tensor::concatenate(&[pred_dur.i(..pred_dur.size()[0]-1), pred_dur.i(pred_dur.size()[0]-1..) + 5.0], 0);
let dim0 = input_lengths_2.int64_value(&[0]);
let dim1 = pred_dur.sum_dim_intlist(0, true, pred_dur.kind()).to_kind(tch::Kind::Int64).int64_value(&[0]);
let mut pred_aln_trg = tch::Tensor::zeros(&[dim0, dim1], (tch::Kind::Float, pred_dur.device()));
let mut c_frame = 0;
for i in 0..pred_aln_trg.size()[0] {
let pred_dur_i = pred_dur.i(i..i+1).to_kind(tch::Kind::Int64).int64_value(&[0]);
pred_aln_trg
.get(i)
.slice(0, c_frame, c_frame + pred_dur_i, 1)
.fill_(1.0);
c_frame += pred_dur_i;
}
let mut en = d_1.transpose(-1, -2).matmul(&pred_aln_trg.unsqueeze(0));
en = tch::Tensor::concatenate(&[en.i((.., .., 0..1)), en.i((.., .., 0..en.size()[2]-1))], 2);
let predictor_shared = tch::CModule::load(self.resolve_path_to_model("predictor_shared.pt"))?;
let x_1 = predictor_shared.forward_ts(&[en.transpose_(-1, -2)])?;
let mut F0 = x_1.transpose(-1, -2);
for i in 0..3 {
let F0_block = tch::CModule::load(self.resolve_path_to_model(&format!("F0_block_{}.pt", i)))?;
F0 = F0_block.forward_ts(&[F0, s_vec_1.pop().unwrap()])?;
}
let F0_proj = tch::CModule::load(self.resolve_path_to_model("F0_proj.pt"))?;
F0 = F0_proj.forward_ts(&[F0])?.squeeze_dim(1);
let mut N = x_1.transpose(-1, -2);
for i in 0..3 {
let N_block = tch::CModule::load(self.resolve_path_to_model(&format!("N_block_{}.pt", i)))?;
N = N_block.forward_ts(&[N, s_vec_2.pop().unwrap()])?;
}
let N_proj = tch::CModule::load(self.resolve_path_to_model("N_proj.pt"))?;
N = N_proj.forward_ts(&[N])?.squeeze_dim(1);
let mut asr = t_en.matmul(&pred_aln_trg.unsqueeze(0));
asr = tch::Tensor::concatenate(&[asr.i((.., .., 0..1)), asr.i((.., .., 0..asr.size()[2]-1))], 2);
let decoder = tch::CModule::load(self.resolve_path_to_model("decoder.pt"))?;
let mut out = decoder.forward_ts(&[asr, F0, N, ref_.squeeze().unsqueeze(0)])?.squeeze();
out = out.i(0..out.size()[0]-100);
println!("Output successfully calculated! Output shape: {:?}", out.size());
println!("Output kind: {:?}", out.kind());
let mut out_float_vec: Vec<f32> = Vec::new();
for i in 0..out.size()[0] {
let tensor_slice = out.i(i..i+1).to_kind(tch::Kind::Float).double_value(&[0]) as f32;
out_float_vec.push(tensor_slice);
}
all_out_vecs.push(out_float_vec);
let mut s_prev_tensor = tch::Tensor::ones(s_pred.size(), (s_pred.kind(), s_pred.device()));
s_prev_tensor.copy_(&s_pred);
s_prev = Some(s_prev_tensor);
}
let mut output_samples: Vec<f32> = Vec::new();
for out_float_vec in all_out_vecs {
for sample in out_float_vec {
output_samples.push(sample);
}
}
Ok(output_samples)
}
}
impl StyleTTSBackend {
fn resolve_path_to_model(&mut self, model_filename: &str) -> PathBuf {
self.resolve_path_to_models_folder().join(model_filename)
}
fn resolve_path_to_models_folder(&mut self) -> PathBuf {
match self.device {
tch::Device::Cpu => Path::new("models").join("torch-scripts"),
tch::Device::Cuda(_i) => Path::new("models").join("torch-scripts-cuda"),
_ => panic!("Device not supported!")
}
}
fn compute_style(&mut self, ref_samples: Vec<f32>) -> anyhow::Result<Tensor> {
println!("{:?}", ref_samples.len());
let mut trimmed_ref_samples: Vec<f32> = Vec::new();
if ref_samples.len() >= STD_SAMPLE_LENGTH {
trimmed_ref_samples.extend(ref_samples.iter().take(STD_SAMPLE_LENGTH).cloned().collect::<Vec<f32>>());
}
else {
panic!("Error: reference input audio is too short. Received: {}", ref_samples.len());
}
let mel_tensor = self.preprocess(trimmed_ref_samples)?;
let mut mel_tensor_1 = tch::Tensor::ones(mel_tensor.size(), (mel_tensor.kind(), mel_tensor.device()));
mel_tensor_1.copy_(&mel_tensor);
let style_encoder = tch::CModule::load(self.resolve_path_to_model("style_encoder.pt"))?;
let ref_s = style_encoder.forward_ts(&[mel_tensor.unsqueeze(1)])?;
let predictor_encoder = tch::CModule::load(self.resolve_path_to_model("predictor_encoder.pt"))?;
let ref_p = predictor_encoder.forward_ts(&[mel_tensor_1.unsqueeze(1)])?;
Ok(Tensor::cat(&[ref_s, ref_p], 1))
}
fn preprocess(&mut self, wave: Vec<f32>) -> anyhow::Result<Tensor> {
let wave_tensor = Tensor::of_slice(&wave).to_device(self.device);
let to_mel = tch::CModule::load(self.resolve_path_to_model("to_mel.pt"))?;
let mel_tensor = to_mel.forward_ts(&[wave_tensor])?;
let adjusted_tensor: Tensor = 1e-5 + mel_tensor.unsqueeze(0);
let log_tensor = adjusted_tensor.log();
let normalized_tensor = (log_tensor - MEAN) / STD;
Ok(normalized_tensor)
}
fn split_by_any_sep(&mut self, str_to_split: String) -> Vec<String> {
// Regular expression pattern to split by ',', '.', '!', ';', or '?'
// The capturing group ensures that the delimiters are included in the result
let pattern = r"([,.!?;])";
let re = Regex::new(pattern).unwrap();
// Split the string using the pattern
let mut split_result: Vec<String> = Vec::new();
let mut last_end = 0;
for mat in re.find_iter(&str_to_split) {
if let Ok(m) = mat {
if m.start() != last_end {
split_result.push(str_to_split[last_end..m.start()].to_string());
}
split_result.push(m.as_str().to_string());
last_end = m.end();
}
}
if last_end < str_to_split.len() {
split_result.push(str_to_split[last_end..].to_string());
}
// Combine the substrings and their delimiters
let mut combined_result: Vec<String> = Vec::new();
let mut i = 0;
while i < split_result.len() - 1 {
combined_result.push(format!("{}{}", split_result[i], split_result[i + 1]));
i += 2;
}
if split_result.len() % 2 == 1 {
combined_result.push(split_result[split_result.len() - 1].clone());
}
combined_result
}
fn length_to_mask(&mut self, lengths: &Tensor) -> Tensor {
let max_length = lengths.max().to_kind(tch::Kind::Int64).unsqueeze(0).int64_value(&[0]);
let expand_dim: Vec<i64> = vec![*lengths.size().first().unwrap(), -1];
let mask = Tensor::arange(max_length, (lengths.kind(), lengths.device()))
.unsqueeze(0)
.expand(expand_dim, true);
let mask = mask + 1;
let mask_gt = mask.gt_tensor(&lengths.unsqueeze(1));
mask_gt
}
} |
//
// ViewController.swift
// PictureThis
//
// Created by Harjyot Badh on 3/6/23.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore
class ViewController: UIViewController {
@IBAction func myUnwindAction(unwindSegue: UIStoryboardSegue) {
// @TODO: Add signout stuff here
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print("Error signing out: %@", signOutError)
}
print("Sign out success")
}
@IBOutlet weak var usernameLabel: UITextField!
@IBOutlet weak var passwordLabel: UITextField!
@IBAction func onSignIn(_ sender: Any) {
guard let username = usernameLabel.text,
let password = passwordLabel.text,
!username.isEmpty,
!password.isEmpty
else {
// Alert for unfilled fields.
let alertController = UIAlertController(title: "Alert", message: "Ensure all fields are correctly filled.", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) {
(action: UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
print("Ok button tapped");
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
print("username or pasword is nil!")
return
}
Firebase.Auth.auth().signIn(withEmail: username, password: password) {
result, error in if let e = error{
let alertController = UIAlertController(title: "Alert", message: "Error Logging In. Ensure all fields entered are correct.", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) {
(action: UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
print(e.localizedDescription)
return
}
guard let res = result
else {
let alertController = UIAlertController(title: "Alert", message: "Error Logging In. Ensure all fields entered are correct.", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) {
(action: UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
print("Error occured with logging in ")
return
}
print("Signed in as \(res.user.email)")
self.performSegue(withIdentifier: "loginSegue", sender: nil)
// Clear the fields on login success.
self.usernameLabel.text = ""
self.passwordLabel.text = ""
}
}
@IBOutlet weak var signUpUsernameLabel: UITextField!
@IBOutlet weak var signUpPasswordLabel: UITextField!
@IBOutlet weak var signUpSecondPasswordLabel: UITextField!
@IBOutlet weak var nameField: UITextField!
@IBAction func onSignUp(_ sender: Any) {
guard let username = signUpUsernameLabel.text,
let password = signUpPasswordLabel.text,
let password2 = signUpSecondPasswordLabel.text,
let name = nameField.text,
!username.isEmpty,
!password.isEmpty,
!password2.isEmpty,
!name.isEmpty
else {
// Alert for if all fields are not filled.
let alertController = UIAlertController(title: "Alert", message: "Ensure all fields are correctly filled.", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) {
(action: UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
print("Ok button tapped");
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
print("username or pasword is nil!")
return
}
// Check if both passwords are equal
if (signUpPasswordLabel.text != signUpSecondPasswordLabel.text) {
let alertController = UIAlertController(title: "Alert", message: "Ensure that passwords match!", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) {
(action: UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
print("Ok button tapped");
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
print("passwords do not match!")
return
}
Firebase.Auth.auth().createUser(withEmail: username, password: password) {
result, error in if let e = error{
let alertController = UIAlertController(title: "Alert", message: "Error Signing Up. Ensure all fields entered are correct.", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) {
(action: UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
print("Error occured with signing up")
print(e.localizedDescription)
return
}
guard let res = result else {
let alertController = UIAlertController(title: "Alert", message: "Error Signing Up. Ensure all fields entered are correct.", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) {
(action: UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
print("Error occured with signing up")
return
}
let db = Firestore.firestore()
let userID = Auth.auth().currentUser!.uid
// Add a new document in collection "users"
db.collection("users").document(userID).setData([
"name": self.nameField.text!.uppercased(),
"profilePicURL": "null",
"userID" : userID
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
self.performSegue(withIdentifier: "signUpSegue", sender: nil)
self.signUpUsernameLabel.text = ""
self.signUpPasswordLabel.text = ""
self.signUpSecondPasswordLabel.text = ""
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
let animal = {
eats: true,
walk() {
console.log("Animal walk");
}
};
let rabbit = {
jumps: true,
__proto__: animal
};
let longEar = {
earLength: 10,
__proto__: rabbit
};
// walk взят из цепочки прототипов
longEar.walk(); // Animal walk
console.log(longEar.jumps); // true (из rabbit)
console.log(Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(longEar)))))
</script>
</body>
</html> |
The Modularization of HTMLDefinition in HTML Purifier
WARNING: This document was drafted before the implementation of this
system, and some implementation details may have evolved over time.
HTML Purifier uses the modularization of XHTML
<http://www.w3.org/TR/xhtml-modularization/> to organize the internals
of HTMLDefinition into a more manageable and extensible fashion. Rather
than have one super-object, HTMLDefinition is split into HTMLModules,
each of which are responsible for defining elements, their attributes,
and other properties (for a more indepth coverage, see
/library/HTMLPurifier/HTMLModule.php's docblock comments). These modules
are managed by HTMLModuleManager.
Modules that we don't support but could support are:
* 5.6. Table Modules
o 5.6.1. Basic Tables Module [?]
* 5.8. Client-side Image Map Module [?]
* 5.9. Server-side Image Map Module [?]
* 5.12. Target Module [?]
* 5.21. Name Identification Module [deprecated]
These modules would be implemented as "unsafe":
* 5.2. Core Modules
o 5.2.1. Structure Module
* 5.3. Applet Module
* 5.5. Forms Modules
o 5.5.1. Basic Forms Module
o 5.5.2. Forms Module
* 5.10. Object Module
* 5.11. Frames Module
* 5.13. Iframe Module
* 5.14. Intrinsic Events Module
* 5.15. Metainformation Module
* 5.16. Scripting Module
* 5.17. Style Sheet Module
* 5.19. Link Module
* 5.20. Base Module
We will not be using W3C's XML Schemas or DTDs directly due to the lack
of robust tools for handling them (the main problem is that all the
current parsers are usually PHP 5 only and solely-validating, not
correcting).
This system may be generalized and ported over for CSS.
== General Use-Case ==
The outwards API of HTMLDefinition has been largely preserved, not
only for backwards-compatibility but also by design. Instead,
HTMLDefinition can be retrieved "raw", in which it loads a structure
that closely resembles the modules of XHTML 1.1. This structure is very
dynamic, making it easy to make cascading changes to global content
sets or remove elements in bulk.
However, once HTML Purifier needs the actual definition, it retrieves
a finalized version of HTMLDefinition. The finalized definition involves
processing the modules into a form that it is optimized for multiple
calls. This final version is immutable and, even if editable, would
be extremely hard to change.
So, some code taking advantage of the XHTML modularization may look
like this:
<?php
$config = HTMLPurifier_Config::createDefault();
$def =& $config->getHTMLDefinition(true); // reference to raw
$def->addElement('marquee', 'Block', 'Flow', 'Common');
$purifier = new HTMLPurifier($config);
$purifier->purify($html); // now the definition is finalized
?>
== Inclusions ==
One of the nice features of HTMLDefinition is that piggy-backing off
of global attribute and content sets is extremely easy to do.
=== Attributes ===
HTMLModule->elements[$element]->attr stores attribute information for the
specific attributes of $element. This is quite close to the final
API that HTML Purifier interfaces with, but there's an important
extra feature: attr may also contain a array with a member index zero.
<?php
HTMLModule->elements[$element]->attr[0] = array('AttrSet');
?>
Rather than map the attribute key 0 to an array (which should be
an AttrDef), it defines a number of attribute collections that should
be merged into this elements attribute array.
Furthermore, the value of an attribute key, attribute value pair need
not be a fully fledged AttrDef object. They can also be a string, which
signifies a AttrDef that is looked up from a centralized registry
AttrTypes. This allows more concise attribute definitions that look
more like W3C's declarations, as well as offering a centralized point
for modifying the behavior of one attribute type. And, of course, the
old method of manually instantiating an AttrDef still works.
=== Attribute Collections ===
Attribute collections are stored and processed in the AttrCollections
object, which is responsible for performing the inclusions signified
by the 0 index. These attribute collections, too, are mutable, by
using HTMLModule->attr_collections. You may add new attributes
to a collection or define an entirely new collection for your module's
use. Inclusions can also be cumulative.
Attribute collections allow us to get rid of so called "global attributes"
(which actually aren't so global).
=== Content Models and ChildDef ===
An implementation of the above-mentioned attributes and attribute
collections was applied to the ChildDef system. HTML Purifier uses
a proprietary system called ChildDef for performance and flexibility
reasons, but this does not line up very well with W3C's notion of
regexps for defining the allowed children of an element.
HTMLPurifier->elements[$element]->content_model and
HTMLPurifier->elements[$element]->content_model_type store information
about the final ChildDef that will be stored in
HTMLPurifier->elements[$element]->child (we use a different variable
because the two forms are sufficiently different).
$content_model is an abstract, string representation of the internal
state of ChildDef, while $content_model_type is a string identifier
of which ChildDef subclass to instantiate. $content_model is processed
by substituting all content set identifiers (capitalized element names)
with their contents. It is then parsed and passed into the appropriate
ChildDef class, as defined by the ContentSets->getChildDef() or the
custom fallback HTMLModule->getChildDef() for custom child definitions
not in the core.
You'll need to use these facilities if you plan on referencing a content
set like "Inline" or "Block", and using them is recommended even if you're
not due to their conciseness.
A few notes on $content_model: it's structure can be as complicated
as you want, but the pipe symbol (|) is reserved for defining possible
choices, due to the content sets implementation. For example, a content
model that looks like:
"Inline -> Block -> a"
...when the Inline content set is defined as "span | b" and the Block
content set is defined as "div | blockquote", will expand into:
"span | b -> div | blockquote -> a"
The custom HTMLModule->getChildDef() function will need to be able to
then feed this information to ChildDef in a usable manner.
=== Content Sets ===
Content sets can be altered using HTMLModule->content_sets, an associative
array of content set names to content set contents. If the content set
already exists, your values are appended on to it (great for, say,
registering the font tag as an inline element), otherwise it is
created. They are substituted into content_model.
vim: et sw=4 sts=4 |
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="author" content="Guilherme Domingues Dworakowski">
<meta name="description" content="Portfólio de projetos do desenvolvedor front-end iniciante Guilherme Domingues Dworakowski.">
<meta name="keywords" content="Portfólio, front-end, web design, projetos, desenvolvimento">
<meta name="viewport" content="width=device-width">
<title>Portfólio Web | Guilherme Domingues Dworakowski</title>
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/0cb63d56b5.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="principal">
<header class="header-principal">
<div class="header__logo">g</div>
<div class="header__menu__div">
<div class="menu-toggle">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
<nav class="header__menu">
<ul>
<li><a href="#sobre">Sobre mim</a></li>
<li><a href="#conhecimentos">Conhecimentos</a></li>
<li><a href="#projetos">Projetos</a></li>
</ul>
</nav>
</div>
</header>
<main class="main-principal">
<h1 class="main__title">Guilherme Domingues Dworakowski</h1>
<section class="main__sobre">
<figure class="main__sobre__figure">
<img src="images/img-eu.jpg" alt="Foto do desenvolvedor Guilherme Domingues Dworakowski">
</figure>
<h2 class="main__sobre__title">Quem sou eu?<a name="sobre"></a></h2>
<p class="main__sobre__texto">Olá, me chamo Guilherme, sou estudante de Análise e Desenvolvimento de Sistemas, com foco no desenvolvimento de trabalhos para encantar o cliente, usando das boas práticas de desenvolvimento e design.<br>Atualmente estou estudando Javascript e ferramentas para melhorar a experiência que será entregue ao usuário.<br>Possuo experiência com trabalhos acadêmicos para profissionais de empresas importantes do Brasil e do mundo.<br>No final da página você encontrará meu e-mail para contato.</p>
</section>
<section class="main__conhecimentos">
<h2 class="main__conhecimentos__title title">Habilidades | Conhecimentos<a name="conhecimentos"></a></h2>
<div class="main__conhecimentos__habilidades html">
<div class="main__conhecimentos__habilidades__html main__conhecimentos__habilidades__design-externo">
<span class="main__conhecimentos__habilidades__html__span main__conhecimentos__habilidades__design-interno">90%</span>
</div>
<p class="main__conhecimentos__habilidades__texto upper">html</p>
</div>
<div class="main__conhecimentos__habilidades css">
<div class="main__conhecimentos__habilidades__css main__conhecimentos__habilidades__design-externo">
<span class="main__conhecimentos__habilidades__css__span main__conhecimentos__habilidades__design-interno">80%</span>
</div>
<p class="main__conhecimentos__habilidades__texto upper">css</p>
</div>
<div class="main__conhecimentos__habilidades ux">
<div class="main__conhecimentos__habilidades__ux main__conhecimentos__habilidades__design-externo">
<span class="main__conhecimentos__habilidades__ux__span main__conhecimentos__habilidades__design-interno">60%</span>
</div>
<p class="main__conhecimentos__habilidades__texto upper">ux</p>
</div>
<div class="main__conhecimentos__habilidades js">
<div class="main__conhecimentos__habilidades__js main__conhecimentos__habilidades__design-externo">
<span class="main__conhecimentos__habilidades__js__span main__conhecimentos__habilidades__design-interno">20%</span>
</div>
<p class="main__conhecimentos__habilidades__texto upper">js</p>
</div>
</section>
<section class="main__projetos">
<h2 class="main__projetos__title">Projetos<a name="projetos"></a></h2>
<article class="main__projetos__article main__projetos__fashion">
<img src="images/projeto-fashion.png" alt="Projeto Fashion">
<h3 class="main__projetos__article__title">Fashion</h3>
<p class="main__projetos__article__texto">Primeiro projeto para o curso de desenvolvimento web</p>
</article>
<article class="main__projetos__article main__projetos__landing-page">
<img src="images/projeto-landing-page.png" alt="Projeto Landing Page">
<h3 class="main__projetos__article__title">Landing Page</h3>
<p class="main__projetos__article__texto">Segundo projeto para o curso de desenvolvimento web</p>
</article>
<article class="main__projetos__article main__projetos__article__strata">
<img src="images/projeto-strata.png" alt="Projeto Strata">
<h3 class="main__projetos__article__title">Strata</h3>
<p class="main__projetos__article__texto">Terceiro projeto para o curso de desenvolvimento web</p>
</article>
<article class="main__projetos__article main__projetos__article__range-hotels">
<img src="images/projet-range-hotels.png" alt="Projeto Range Hotels">
<h3 class="main__projetos__article__title">Range Hotels</h3>
<p class="main__projetos__article__texto">Quarto projeto para o curso de desenvolvimento web</p>
</article>
</section>
</main>
<footer class="footer-principal">
<ul class="footer__content">
<li><a href="https://www.linkedin.com/in/guilherme-domingues-dworakowski/" target="_blank"><i class="fab fa-linkedin-in"></i></a></li>
<li><a href="https://www.instagram.com/gui_domin/" target="_blank"><i class="fab fa-instagram"></a></i></li>
<li>| Copyright 2020</li>
</ul>
<address class="footer__email">guilherme.ddworakowski@gmail.com</address>
</footer>
</div>
<script src="javascript/menu.js"></script>
</body>
</html> |
.. _stage_status:
Stage and Status
.. versionchanged:: 8.0 saas-2 state/stage cleaning
Stage
+++++
This revision removed the concept of state on project.issue objects. The ``state``
field has been totally removed and replaced by stages, using ``stage_id``. The
following models are impacted:
- ``project.issue`` now use only stages. However a convention still exists about
'New' stage. An issue is consdered as ``new`` when it has the following
properties:
- ``stage_id and stage_id.sequence = 1``
- ``project.task.type`` do not have any ``state`` field anymore.
- ``project.issue.report`` do not have any ``state`` field anymore.
By default a newly created issue is in a new stage. It means that it will
fetch the stage having ``sequence = 1``. Stage mangement is done using the
kanban view or the clikable statusbar. It is not done using buttons anymore.
Stage analysis
++++++++++++++
Stage analysis can be performed using the newly introduced ``date_last_stage_update``
datetime field. This field is updated everytime ``stage_id`` is updated.
``project.issue.report`` model also uses the ``date_last_stage_update`` field.
This allows to group and analyse the time spend in the various stages.
Open / Assignation date
+++++++++++++++++++++++
The ``date_open`` field meaning has been updated. It is now set when the ``user_id``
(responsible) is set. It is therefore the assignation date.
Subtypes
++++++++
The following subtypes are triggered on ``project.issue``:
- ``mt_issue_new``: new tasks. Condition: ``obj.stage_id and obj.stage_id.sequence == 1``
- ``mt_issue_stage``: stage changed. Condition: ``obj.stage_id and obj.stage_id.sequence != 1``
- ``mt_issue_assigned``: user assigned. condition: ``obj.user_id and obj.user_id.id``
- ``mt_issue_blocked``: kanban state blocked. Condition: ``obj.kanban_state == 'blocked'``
Those subtypes are also available on the ``project.project`` model and are used
for the auto subscription. |
//
// StringExtensions.swift
// Marvel
//
// Created by Albert on 17/2/22.
//
import Foundation
import var CommonCrypto.CC_MD5_DIGEST_LENGTH
import func CommonCrypto.CC_MD5
import typealias CommonCrypto.CC_LONG
extension String {
func from(_ table: String) -> String {
return NSLocalizedString(self, tableName: table, bundle: Bundle.main, comment: String())
}
func md5() -> String {
let length = Int(CC_MD5_DIGEST_LENGTH)
let messageData = self.data(using:.utf8)!
var digestData = Data(count: length)
_ = digestData.withUnsafeMutableBytes { digestBytes -> UInt8 in
messageData.withUnsafeBytes { messageBytes -> UInt8 in
if let messageBytesBaseAddress = messageBytes.baseAddress, let digestBytesBlindMemory = digestBytes.bindMemory(to: UInt8.self).baseAddress {
let messageLength = CC_LONG(messageData.count)
CC_MD5(messageBytesBaseAddress, messageLength, digestBytesBlindMemory)
}
return 0
}
}
return digestData.base64EncodedString()
}
} |
import React, { useEffect, useState } from 'react';
import { useRef } from 'react';
import './LoginSignUp.css';
import Loader from '../layout/Loader/Loader';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import MailOutlineIcon from '@mui/icons-material/MailOutline';
import LockOpenIcon from '@mui/icons-material/LockOpen';
import FaceIcon from '@mui/icons-material/Face';
import { clearErrors, login, register } from '../../actions/userActions';
import { useAlert } from 'react-alert';
const LoginSignUp = () => {
const dispatch = useDispatch();
const alert = useAlert();
const location = useLocation();
const navigate = useNavigate();
const { loading, error, isAuthenticated } = useSelector(
(state) => state.authData
);
const loginTab = useRef(null);
const registerTab = useRef(null);
const switcherTab = useRef(null);
const [loginEmail, setLoginEmail] = useState('');
const [loginPassword, setLoginPassword] = useState('');
const [avatar, setAvatar] = useState();
const [avatarPreview, setAvatarPreview] = useState(
'https://png.pngtree.com/png-clipart/20210915/ourlarge/pngtree-user-avatar-placeholder-black-png-image_3918427.jpg'
);
const [user, setUser] = useState({
name: '',
email: '',
password: ''
});
const { name, email, password } = user;
const loginSubmit = (e) => {
e.preventDefault();
dispatch(login(loginEmail, loginPassword));
};
const registerSubmit = (e) => {
e.preventDefault();
const myForm = new FormData();
myForm.set('name', name);
myForm.set('email', email);
myForm.set('password', password);
myForm.set('avatar', avatar);
console.log(myForm.avatar);
dispatch(register(myForm));
};
useEffect(() => {
const redirectLink = location.search
? location.search.split('=')[1]
: 'account/me';
if (error) {
alert.error(error);
dispatch(clearErrors());
}
if (isAuthenticated) {
navigate(`/${redirectLink}`);
} else {
navigate('/login');
}
}, [dispatch, error, isAuthenticated, navigate, alert, location.search]);
const switchTab = (e, tab) => {
if (tab === 'Login') {
switcherTab.current.classList.add('shiftToNeutral');
switcherTab.current.classList.add('shiftToRight');
registerTab.current.classList.remove('shiftToNeutralForm');
loginTab.current.classList.remove('shiftToLeft');
}
if (tab === 'Register') {
switcherTab.current.classList.add('shiftToRight');
switcherTab.current.classList.remove('shiftToNeutral');
registerTab.current.classList.add('shiftToNeutralForm');
loginTab.current.classList.add('shiftToLeft');
}
};
const registerDataChange = (e) => {
if (e.target.name === 'avatar') {
const reader = new FileReader();
reader.onload = () => {
if (reader.readyState === 2) {
setAvatarPreview(reader.result);
setAvatar(reader.result);
}
};
reader.readAsDataURL(e.target.files[0]);
} else {
setUser({ ...user, [e.target.name]: e.target.value });
}
};
return (
<>
{loading ? (
<Loader />
) : (
<>
<div className="LoginSignUpContainer">
<div className="LoginSignUpBox">
<div>
<div className="login_signUp_toggle">
<p onClick={(e) => switchTab(e, 'Login')}>
LOGIN
</p>
<p
onClick={(e) =>
switchTab(e, 'Register')
}
>
REGISTER
</p>
</div>
<button ref={switcherTab}></button>
</div>
<form
className="loginForm"
ref={loginTab}
onSubmit={loginSubmit}
>
<div className="loginEmail">
<MailOutlineIcon />
<input
type="email"
placeholder="Email"
required
value={loginEmail}
onChange={(e) =>
setLoginEmail(e.target.value)
}
/>
</div>
<div className="loginPassword">
<LockOpenIcon />
<input
type="password"
placeholder="Password"
required
value={loginPassword}
onChange={(e) =>
setLoginPassword(e.target.value)
}
/>
</div>
<Link to="/password/forgot">
{' '}
Forget Password ?
</Link>
<input
type="submit"
value="Login"
className="loginBtn"
/>
</form>
<form
className="signUpForm"
ref={registerTab}
encType="multipart/form-data"
onSubmit={registerSubmit}
>
<div className="signUpName">
<FaceIcon />
<input
type="text"
placeholder="name"
required
name="name"
value={name}
onChange={registerDataChange}
/>
</div>
<div className="signUpEmail">
<MailOutlineIcon />
<input
type="email"
placeholder="email"
required
name="email"
value={email}
onChange={registerDataChange}
/>
</div>
<div className="signUpEmail">
<LockOpenIcon />
<input
type="password"
placeholder="password"
required
name="password"
value={password}
onChange={registerDataChange}
/>
</div>
<div id="registerImage">
<img
className="registerPImage"
src={avatarPreview}
alt="Avatar Preview"
/>
<input
type="file"
name="avatar"
accept="image/*"
onChange={registerDataChange}
/>
</div>
<input
type="submit"
value="Register"
className="signUpBtn"
disabled={loading ? true : false}
/>
</form>
</div>
</div>
</>
)}
</>
);
};
export default LoginSignUp; |
import pool from '../db.js';
const conn = await pool.getConnection();
class poController {
static getData = async (req, user) => {
try {
var user_role = user.user_role !== null && user.user_role !== undefined ? user.user_role : 'User';
var sqlCust = "Select a.customer_id,a.customer_name,a.nick_name,CONCAT(a.city,' ',a.pin_code) as city_pin,b.market_area,a.customer_type" +
" from customers as a, market_area as b " +
" Where a.market_area_id=b.market_area_id and a.status='A'"
if (user_role !== "Admin") {
sqlCust = sqlCust + ` and a.user_id=${user.user_id}`;
}
const [customer_list] = await conn.query(sqlCust);
const [bu_list] = await conn.query("SELECT bu_id, CONCAT(bu_code,' | ',bu_short) as bu_name FROM business_units Where status='A'")
//const [product_list] = await conn.query("SELECT * FROM products as a Where a.status='A'");
return [customer_list, bu_list];
} catch (error) {
console.error(error);
// Handle the error
} finally {
conn.release();
}
}
static getProductList = async (req, res) => {
try {
const { bu_id } = req.query;
const sqlStr = "SELECT a.product_id, a.product_name FROM products as a, products_bu as b" +
" WHERE a.product_id=b.product_id and b.bu_id = ?";
const [productsList] = await conn.query(sqlStr, [bu_id]);
conn.release;
res.json({ products_list: productsList });
} catch (err) {
conn.release;
console.error(err);
res.status(500).send('Internal Server Error');
} finally {
conn.release;
}
}
static viewBlank = async (req, res) => {
//const [customer_list, bu_list] = await this.getData(req, res.locals.user);
const [customer_list, bu_list] = await this.getData(req, res.locals.user);
try {
const [row] = await conn.query("SELECT DATE_FORMAT(CURRENT_DATE(),'%d-%m-%Y') as po_date;")
const data = { po_date: row[0].po_date, po_no: '*****' };
res.render('po/po-create', { customer_list, bu_list, data, conn });
} catch (err) {
conn.release();
console.error(err);
return res.render('po/po-create', { alert: `Internal server error` });
} finally {
conn.release();
}
}
static create = async (req, res) => {
const { customer_id, customer_name, exp_date, bu_id_hdn, bu_name, posted, ftp_date, status, 'sr_no[]': sr_no, 'bu_ids[]': bu_ids, 'bu_names[]': bu_names, 'product_id[]': product_id, 'product_name[]': product_name, 'qty[]': qty, 'rate[]': rate, 'amount[]': amount } = req.body;
const data = req.body //po_date, po_no, po_no_new,
const [customer_list, bu_list] = await this.getData(req, res.locals.user);
var errors = [];
if (!customer_id) {
errors.push({ message: 'Customer name is required' });
}
if (!bu_id_hdn) {
errors.push({ message: 'Select business unit' });
}
if (!exp_date) {
errors.push({ message: 'Select expected date' });
}
// if (isNaN(rate) || rate <= 0) {
// errors.push({ message: 'Price must be a number' });
// }
const [row] = await conn.query("SELECT DATE_FORMAT(CURRENT_DATE(),'%Y-%m-%d') as po_date;")
var sysDate = row[0].po_date;
if (exp_date < sysDate) {
errors.push({ message: 'Expected date should greater than today' });
}
conn.release;
//
if (errors.length) {
res.render('po/po-create', { errors, data, customer_list, bu_list });
return;
}
try {
// Get CURRENT_DATE
const [row] = await conn.query("SELECT DATE_FORMAT(CURRENT_DATE(),'%Y-%m-%d') as po_date;")
const curDate = row[0].po_date;
// Genrate max Customer id
const [rows1] = await conn.query(`SELECT Max(po_no) AS maxNumber FROM po_hd Where po_date='${curDate}'`);
var nextPoNo = rows1[0].maxNumber + 1;
var poNoNew = 'NJ' + curDate.replace(/-/g, '') + nextPoNo.toString().padStart(3, '0');
// Insert new record into database
await conn.beginTransaction();
var status_new = status !== null && status !== undefined ? status : 'A';
var c_by = res.locals.user !== null && res.locals.user !== undefined ? res.locals.user.user_id : 0;
const sqlStr = "INSERT INTO po_hd (po_date,po_no,po_no_new,customer_id,exp_date,bu_id,posted,ftp_date,status,c_at,c_by)" +
" VALUES (?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP( ),?)"
const params = [curDate, nextPoNo, poNoNew, customer_id, exp_date, bu_id_hdn, 'Y', ftp_date, status_new, c_by];
const [result] = await conn.query(sqlStr, params);
//await conn.commit();
// Insert new records into po_dt
// const product_id = req.body['product_id[]'];
// for (let i = 0; i < product_id.length; i++) {
// const sr_no = (i + 1) * 10;
// //const bu_ids = req.body.bu_ids[i];
// const product_id = req.body.product_id[i];
// const qty = req.body.qty[i];
// const rate = req.body.rate[i];
// const amount = qty * rate;
// const sqlStr2 = "INSERT INTO po_dt (po_date, po_no, sr_no, bu_id, product_id, qty, rate, amount)" +
// " VALUES (?,?,?,?,?,?,?,?)"
// const paramsDt = [curDate, nextPoNo, sr_no, bu_id_hdn, product_id, qty, rate, amount];
// await conn.query(sqlStr2, paramsDt); //const [result2] =
// }
// Insert new records into po_dt
for (let i = 0; i < product_id.length; i++) {
const sr_no_val = (i + 1) * 10;
//const bu_ids_val = bu_ids[i];
const product_id_val = product_id[i];
const qty_val = qty[i];
const rate_val = rate[i];
const amount_val = amount[i];
const sqlStr2 = "INSERT INTO po_dt (po_date, po_no, sr_no, bu_id, product_id, qty, rate, amount)" +
" VALUES (?,?,?,?,?,?,?,?)"
const paramsDt = [curDate, nextPoNo, sr_no_val, bu_id_hdn, product_id_val, qty_val, rate_val, amount_val];
await conn.query(sqlStr2, paramsDt); //const [result2] =
}
await conn.commit();
//return res.render('po/po-view', { alert: `Save Customer successfully` });
res.redirect('/po/view');
//res.redirect('/');
} catch (err) {
await conn.rollback();
conn.release();
console.error(err);
return res.render('po/po-view', { alert: `Internal server error` });
} finally {
conn.release();
}
};
static viewAll = async (req, res) => {
//const conn = await pool.getConnection();
// retrieve the alert message from the query parameters
const alert = req.query.alert;
try {//DATE_FORMAT(a.po_date,'%d-%m-%Y') as po_date2, DATE_FORMAT(a.exp_date,'%d-%m-%Y') as exp_date
const sqlStr = "Select a.po_date, a.po_no,a.po_no_new,b.customer_name,a.exp_date,CONCAT(c.bu_code,' | ',c.bu_short) as bu_name,a.posted,a.ftp_date,a.status" +
" FROM po_hd as a, customers as b, business_units as c" +
" Where a.customer_id=b.customer_id and a.bu_id=c.bu_id and a.c_by=?" +
" Order By a.po_date desc, a.po_no desc";
const params = [res.locals.user.user_id];
const [results] = await conn.query(sqlStr, params);
res.render('po/po-view', { po: results, alert });
} catch (error) {
console.error(error);
// Handle the error
} finally {
conn.release();
}
}
static edit = async (req, res) => {
const { po_date, po_no } = req.params;
try {
const [customer_list, bu_list] = await this.getData(req, res.locals.user);
const sqlStr = "Select a.*,b.customer_name,c.bu_name" +
" FROM po_hd as a, customers as b, business_units as c" +
" Where a.customer_id=b.customer_id and a.bu_id=c.bu_id and a.po_date=? and a.po_no=?";
const params = [po_date, po_no];
const [results] = await conn.query(sqlStr, params);
//
const sqlStr2 = "Select a.*,b.product_name" +
" FROM po_dt as a, products as b" +
" Where a.product_id=b.product_id and a.po_date=? and a.po_no=? Order By a.sr_no";
const params2 = [po_date, po_no];
const [results2] = await conn.query(sqlStr2, params2);
//
const sqlStr3 = "SELECT a.product_id, a.product_name FROM products as a, products_bu as b" +
" WHERE a.product_id=b.product_id and b.bu_id =?";
const [productsList] = await conn.query(sqlStr3, results[0].bu_id);
//
res.render('po/po-edit', { data: results[0], data2: results2, customer_list, bu_list, productsList });
} catch (error) {
console.error(error);
// Handle the error
} finally {
conn.release();
}
}
static update = async (req, res) => {
const { po_date, po_no } = req.params;
const { customer_id, customer_name, exp_date, bu_id_hdn, bu_name, posted, ftp_date, status, 'sr_no[]': sr_no, 'bu_ids[]': bu_ids, 'bu_names[]': bu_names, 'product_id[]': product_id, 'product_name[]': product_name, 'qty[]': qty, 'rate[]': rate, 'amount[]': amount } = req.body;
const data = req.body //po_date, po_no, po_no_new,
const [customer_list, bu_list] = await this.getData(req, res.locals.user);
var errors = [];
if (!customer_id) {
errors.push({ message: 'Customer name is required' });
}
if (!bu_id_hdn) {
errors.push({ message: 'Select business unit' });
}
if (!exp_date) {
errors.push({ message: 'Select expected date' });
}
// if (isNaN(rate) || rate <= 0) {
// errors.push({ message: 'Price must be a number' });
// }
// const [rows] = await conn.query('SELECT * FROM po_hd WHERE po_date=? and po_no=? and bu_id=?', [po_date, po_no, bu_id_hdn]);
// if (rows.length === 0) {
// errors.push({ message: 'Business unit can not change' });
// }
const [row] = await conn.query("SELECT DATE_FORMAT(CURRENT_DATE(),'%Y-%m-%d') as po_date;")
var sysDate = row[0].po_date;
if (exp_date < sysDate) {
errors.push({ message: 'Expected date should greater than today' });
}
conn.release;
//
if (errors.length) {
const sqlStr2 = "Select a.*,b.product_name" +
" FROM po_dt as a, products as b" +
" Where a.product_id=b.product_id and a.po_date=? and a.po_no=? Order By a.sr_no";
const params2 = [po_date, po_no];
const [poDetails] = await conn.query(sqlStr2, params2);
//
const sqlStr3 = "SELECT a.product_id, a.product_name FROM products as a, products_bu as b" +
" WHERE a.product_id=b.product_id and b.bu_id =?";
const [productsList] = await conn.query(sqlStr3, bu_id_hdn);
//
res.render('po/po-edit', { errors, data, customer_list, bu_list, data2: poDetails, productsList });
return;
}
try {
// Update record into database using customer_id
await conn.beginTransaction();
var status_new = status !== null && status !== undefined ? status : 'A';
var u_by = res.locals.user !== null && res.locals.user !== undefined ? res.locals.user.user_id : 0;
const sqlStr = "UPDATE po_hd Set customer_id=?,bu_id=?,exp_date=?,status=?,u_at=CURRENT_TIMESTAMP,u_by=?" +
" WHERE po_date=? and po_no=?"
const params = [customer_id, bu_id_hdn, exp_date, status_new, u_by, po_date, po_no];
await conn.query(sqlStr, params);
//
// Delete records from po_dt
const sqlStr3 = "Delete FROM po_dt WHERE po_date=? and po_no=?"
const params3 = [po_date, po_no];
await conn.query(sqlStr3, params3);
//
// Insert new records into po_dt
// const product_id = req.body['product_id[]'];
// for (let i = 0; i < product_id.length; i++) {
// const sr_no = (i + 1) * 10;
// //const bu_ids = req.body.bu_ids[i];
// const product_id = req.body.product_id[i];
// const qty = req.body.qty[i];
// const rate = req.body.rate[i];
// const amount = qty * rate;
// const sqlStr2 = "INSERT INTO po_dt (po_date, po_no, sr_no, bu_id, product_id, qty, rate, amount)" +
// " VALUES (?,?,?,?,?,?,?,?)"
// const paramsDt = [po_date, po_no, sr_no, bu_id_hdn, product_id, qty, rate, amount];
// await conn.query(sqlStr2, paramsDt); //const [result2] =
// }
// Insert new records into po_dt
for (let i = 0; i < product_id.length; i++) {
const sr_no_val = (i + 1) * 10;
//const bu_ids_val = bu_ids[i];
const product_id_val = product_id[i];
const qty_val = qty[i];
const rate_val = rate[i];
const amount_val = amount[i];
const sqlStr2 = "INSERT INTO po_dt (po_date, po_no, sr_no, bu_id, product_id, qty, rate, amount)" +
" VALUES (?,?,?,?,?,?,?,?)"
const paramsDt = [po_date, po_no, sr_no_val, bu_id_hdn, product_id_val, qty_val, rate_val, amount_val];
await conn.query(sqlStr2, paramsDt);
}
await conn.commit();
//res.redirect('/po/view');
res.redirect('/po/view?alert=Update+Order+successfully');
} catch (err) {
await conn.rollback();
conn.release();
console.error(err);
return res.render('po/po-view', { alert: `Internal server error` });
} finally {
conn.release();
}
};
static delete = async (req, res) => {
const { po_date, po_no } = req.params;
try {
var errors = [];
const sqlStr3 = "Select * from po_hd Where po_date=? and po_no=? and posted='Y'"
const params3 = [po_date, po_no];
const [rows] = await conn.query(sqlStr3, params3);
if (rows.length > 0) {
errors.push({ message: "Posted entry can't delete" });
}
conn.release;
//
if (errors.length) {
//res.render('po/po-view', { errors });
res.redirect(`/po/view?${errors.map(error => `alert=${error.message}`).join('&')}`);
return;
}
//
//
const params = [po_date, po_no];
await conn.beginTransaction();
const sqlStr1 = "Delete FROM po_dt WHERE po_date=? and po_no=?"
await conn.query(sqlStr1, params);
//
const sqlStr2 = "Delete FROM po_hd WHERE po_date=? and po_no=?"
await conn.query(sqlStr2, params);
await conn.commit();
//
//res.redirect('/po/view');
res.redirect('/po/view?alert=customer+deleted+successfully');
} catch (err) {
await conn.rollback();
conn.release();
console.error(err);
return res.render('po/po-view', { alert: `Internal server error` });
} finally {
conn.release();
}
};
};
export default poController |
import { motion } from "framer-motion";
// staggerChildren:
// https://www.framer.com/docs/transition/###staggerchildren
const ThreeDotsLoader = ({
width = "2rem",
height = "2rem",
}: {
width?: string;
height?: string;
}) => {
return (
<motion.div
className="flex justify-around"
style={{ width, height }}
initial="start"
animate="end"
variants={{
start: {
transition: {
staggerChildren: 0.2,
},
},
end: {
transition: {
staggerChildren: 0.2,
},
},
}}
>
<Dots />
<Dots />
<Dots />
</motion.div>
);
};
const Dots = () => {
return (
<motion.div
className="w-1/4 h-1/4 bg-chartColor-mainBlue justify-around rounded-full"
variants={{
start: {
y: "80%",
},
end: {
y: "220%",
},
}}
transition={{
duration: 0.5,
repeat: Infinity,
repeatType: "reverse",
ease: "easeInOut",
}}
/>
);
};
export default ThreeDotsLoader; |
"use client";
import useUser from "@/app/hook/useUser";
import { PROTECTED_URLS } from "@/const";
import { createClient } from "@/lib/client";
import AdbIcon from "@mui/icons-material/Adb";
import MenuIcon from "@mui/icons-material/Menu";
import AppBar from "@mui/material/AppBar";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Container from "@mui/material/Container";
import IconButton from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Toolbar from "@mui/material/Toolbar";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import * as React from "react";
const pages = [
{
title: "Mis cursos",
href: "/usuario/curso",
},
{
title: "Horarios",
href: "/usuario/horario",
},
];
export function NavbarUsuario() {
const { data, isFetching } = useUser();
const supabase = createClient();
const query = useQueryClient();
const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(
null
);
const router = useRouter();
const pathname = usePathname();
const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(
null
);
const handleLogout = async () => {
try {
const { error } = await supabase.auth.signOut();
if (error) {
console.error("Error logging out:", error.message);
return;
}
query.clear();
router.refresh();
if (PROTECTED_URLS.includes(pathname)) {
router.replace("/home/auth?next=" + pathname);
}
console.log("Logged out successfully");
} catch (error) {
console.error("Unexpected error:", error);
}
};
if (isFetching) {
return <div>Loading...</div>;
}
const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => {
setAnchorElNav(event.currentTarget);
};
const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
setAnchorElUser(event.currentTarget);
};
const handleCloseNavMenu = () => {
setAnchorElNav(null);
};
const handleCloseUserMenu = () => {
setAnchorElUser(null);
};
return (
<AppBar position="static">
<Container maxWidth="xl">
<Toolbar disableGutters color="primary">
<AdbIcon sx={{ display: { xs: "none", md: "flex" }, mr: 1 }} />
<Typography
variant="h6"
noWrap
component={Link}
href="/usuario"
sx={{
mr: 2,
display: { xs: "none", md: "flex" },
fontFamily: "monospace",
fontWeight: 100,
letterSpacing: ".1rem",
color: "inherit",
textDecoration: "none",
}}
>
HEROES CLUB
</Typography>
<Box sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}>
<IconButton
size="large"
aria-label="account of current user"
aria-controls="menu-appbar"
aria-haspopup="true"
onClick={handleOpenNavMenu}
color="inherit"
>
<MenuIcon />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorElNav}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "left",
}}
open={Boolean(anchorElNav)}
onClose={handleCloseNavMenu}
sx={{
display: { xs: "block", md: "none" },
}}
>
{pages.map((page) => (
<MenuItem key={page.title} onClick={handleCloseNavMenu}>
<Typography textAlign="center">{page.title}</Typography>
</MenuItem>
))}
</Menu>
</Box>
<AdbIcon sx={{ display: { xs: "flex", md: "none" }, mr: 1 }} />
<Typography
variant="h5"
noWrap
component={Link}
href="/usuario"
sx={{
mr: 2,
display: { xs: "flex", md: "none" },
flexGrow: 1,
fontFamily: "monospace",
fontWeight: 700,
letterSpacing: ".3rem",
color: "inherit",
textDecoration: "none",
}}
>
HEROES CLUB
</Typography>
<Box sx={{ flexGrow: 1, display: { xs: "none", md: "flex" } }}>
{pages.map((page) => (
<Button
key={page.title}
onClick={handleCloseNavMenu}
sx={{ my: 2, color: "white", display: "block" }}
>
<Link href={page.href}>{page.title}</Link>
</Button>
))}
</Box>
<Box sx={{ flexGrow: 0 }}>
<Tooltip title="Open settings">
<IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
<Avatar alt="Remy Sharp" src={data?.image_url as string} />
</IconButton>
</Tooltip>
<Menu
sx={{ mt: "45px" }}
id="menu-appbar"
anchorEl={anchorElUser}
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
open={Boolean(anchorElUser)}
onClose={handleCloseUserMenu}
>
<MenuItem onClick={handleCloseUserMenu}>
<Typography textAlign="center">{data?.name}</Typography>
</MenuItem>
<MenuItem onClick={handleCloseUserMenu}>
<Typography textAlign="center">
<Button variant="outlined" onClick={() => handleLogout()}>
cerrar sesión
</Button>
</Typography>
</MenuItem>
</Menu>
</Box>
</Toolbar>
</Container>
</AppBar>
);
} |
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router } from "react-router-dom";
//Redux
import store from "./redux/store";
import { Provider } from "react-redux";
let WithStore = () => (
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
);
ReactDOM.render(<WithStore />, document.getElementById("root"));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister(); |
/* This file is part of the KDE project
*
* SPDX-FileCopyrightText: 2017 Boudewijn Rempt <boud@valdyas.org>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef TEXTNGSHAPECONFIGWIDGET_H
#define TEXTNGSHAPECONFIGWIDGET_H
#include <QWidget>
#include <QTextEdit>
#include <kxmlguiwindow.h>
#include <KoColor.h>
#include <KoSvgText.h>//for the enums
#include <BasicXMLSyntaxHighlighter.h>
#include "ui_WdgSvgTextEditor.h"
#include "ui_WdgSvgTextSettings.h"
class KoSvgTextShape;
class KoDialog;
class SvgTextEditor : public KXmlGuiWindow
{
Q_OBJECT
public:
SvgTextEditor(QWidget *parent = 0, Qt::WindowFlags f = Qt::WindowFlags());
~SvgTextEditor();
//tiny enum to keep track of the tab on which editor something happens while keeping the code readable.
enum Editor {
Richtext, // 0
SVGsource // 1
};
void setInitialShape(KoSvgTextShape *shape);
private Q_SLOTS:
/**
* switch the text editor tab.
*/
void switchTextEditorTab(bool convertData = true);
void slotCloseEditor();
/**
* in rich text, check the current format, and toggle the given buttons.
*/
void checkFormat();
void checkDocumentFormat();
void slotFixUpEmptyTextBlock();
void save();
void undo();
void redo();
void cut();
void copy();
void paste();
void selectAll();
void deselect();
void find();
void findNext();
void findPrev();
void replace();
void zoomOut();
void zoomIn();
#ifndef Q_OS_WIN
void showInsertSpecialCharacterDialog();
void insertCharacter(const QChar &c);
#endif
void setTextBold(QFont::Weight weight = QFont::Bold);
void setTextWeightLight();
void setTextWeightNormal();
void setTextWeightDemi();
void setTextWeightBlack();
void setTextItalic(QFont::Style style = QFont::StyleOblique);
void setTextDecoration(KoSvgText::TextDecoration decor);
void setTextUnderline();
void setTextOverline();
void setTextStrikethrough();
void setTextSubscript();
void setTextSuperScript();
void increaseTextSize();
void decreaseTextSize();
void setLineHeight(double lineHeightPercentage);
void setLetterSpacing(double letterSpacing);
void alignLeft();
void alignRight();
void alignCenter();
void alignJustified();
void setFont(const QString &fontName);
void setFontSize(qreal size);
void setBaseline(KoSvgText::BaselineShiftMode baseline);
void setKerning(bool enable);
void setWrappingLegacy();
void setWrappingPre();
void setWrappingPreWrap();
void setSettings();
void slotToolbarToggled(bool);
void setFontColor(const KoColor &c);
void setBackgroundColor(const KoColor &c);
void setModified(bool modified);
void dialogButtonClicked(QAbstractButton *button);
Q_SIGNALS:
void textUpdated(KoSvgTextShape *shape, const QString &svg, const QString &defs, bool richTextPreferred);
void textEditorClosed();
protected:
void wheelEvent(QWheelEvent *event) override;
bool eventFilter(QObject *watched, QEvent *event) override;
/**
* Selects all if there is no selection
* @returns a copy of the previous cursor.
*/
QTextCursor setTextSelection();
private:
void applySettings();
QAction *createAction(const QString &name,
const char *member);
void createActions();
void enableRichTextActions(bool enable);
void enableSvgTextActions(bool enable);
bool isRichTextEditorTabActive();
bool isSvgSourceEditorTabActive();
Ui_WdgSvgTextEditor m_textEditorWidget;
QTextEdit *m_currentEditor {0};
QWidget *m_page {0};
QList<QAction*> m_richTextActions;
QList<QAction*> m_svgTextActions;
KoSvgTextShape *m_shape {0};
#ifndef Q_OS_WIN
KoDialog *m_charSelectDialog {0};
#endif
BasicXMLSyntaxHighlighter *m_syntaxHighlighter;
QString m_searchKey;
class Private;
QScopedPointer<Private> d;
};
#endif //TEXTNGSHAPECONFIGWIDGET_H |
import React, { useEffect, useState } from "react";
import { fr } from "@codegouvfr/react-dsfr";
import { useStyles } from "tss-react/dsfr";
import { z } from "zod";
import {
cleanStringToHTMLAttribute,
notEqual,
OmitFromExistingKeys,
validateMultipleEmailRegex,
} from "shared";
const componentName = "im-fillable-list";
export const MultipleEmailsInput = (
props: OmitFromExistingKeys<
InputContainerProps,
"onInputChange" | "value"
> & {
initialValue?: string;
valuesInList: string[];
setValues: (values: string[]) => void;
disabled?: boolean;
summaryHintText?: string;
},
) => {
const {
valuesInList,
setValues,
disabled,
summaryHintText,
...addToListProps
} = props;
const { cx } = useStyles();
const getEmailValuesFromString = (stringToParse: string) => {
const matches = stringToParse.match(validateMultipleEmailRegex);
return (matches || []).map((match) => match.trim());
};
const [inputValue, setInputValue] = useState<string>(
addToListProps.initialValue ?? "",
);
const onInputChange: OnInputChange = (event) => {
const { value } = event.target;
const updatedValues = [...new Set([...getEmailValuesFromString(value)])];
setValues(updatedValues);
setInputValue(value);
};
useEffect(() => {
if (!addToListProps.initialValue) return;
setInputValue(addToListProps.initialValue);
}, [addToListProps.initialValue]);
return (
<div className={cx(fr.cx("fr-input-group"), componentName)}>
<InputContainer
{...addToListProps}
value={inputValue}
onInputChange={onInputChange}
disabled={disabled}
/>
{valuesInList.length > 0 && (
<EmailsValuesSummary
values={valuesInList}
disabled={disabled}
onDelete={(valueToDelete) => {
const newEmails = valuesInList.filter(notEqual(valueToDelete));
setValues(newEmails);
setInputValue(newEmails.join(", "));
}}
summaryHintText={summaryHintText}
/>
)}
</div>
);
};
type OnInputChange = (event: React.ChangeEvent<HTMLInputElement>) => void;
type InputContainerProps = {
name: string;
value: string;
onInputChange: OnInputChange;
label?: string;
placeholder?: string;
description?: React.ReactNode;
validationSchema?: z.ZodSchema<unknown>;
disabled?: boolean;
};
const createGetInputError =
(validationSchema?: z.ZodSchema<unknown>) =>
(stringToValidate: string): string | null => {
if (!validationSchema) return null;
try {
validationSchema.parse(stringToValidate);
return null;
} catch (e: any) {
const zodError: z.ZodError = e;
return zodError.errors[0].message;
}
};
const InputContainer = ({
name,
value,
label,
placeholder,
description,
onInputChange,
validationSchema,
disabled,
}: InputContainerProps) => {
const [error, setError] = useState<string | null>(null);
const getInputError = createGetInputError(validationSchema);
useEffect(() => {
if (!value || !error) return;
setError(getInputError(value));
}, [error, value]);
return (
<div
className={`fr-input-group${
error ? " fr-input-group--error" : ""
} ${componentName}__add-to-list-wrapper fr-mb-2w`}
>
<label
className={fr.cx("fr-label")}
htmlFor={cleanStringToHTMLAttribute(name)}
>
{label}
</label>
{description && (
<span className={fr.cx("fr-hint-text")}>{description}</span>
)}
<div className={fr.cx("fr-grid-row")}>
<div className={fr.cx("fr-col")}>
<input
id={cleanStringToHTMLAttribute(name)}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.currentTarget.blur();
}
}}
disabled={disabled}
value={value}
type="text"
name={name}
onChange={onInputChange}
className={fr.cx("fr-input", error ? "fr-input--error" : undefined)}
placeholder={placeholder || ""}
aria-describedby="text-input-error-desc-error"
/>
</div>
</div>
{error && (
<p
id="text-input-email-error-desc-error"
className={fr.cx("fr-error-text")}
>
{error}
</p>
)}
</div>
);
};
type EmailsValuesSummaryProps = {
values: string[];
onDelete: (valueToDelete: string) => void;
disabled?: boolean;
summaryHintText?: string;
};
const EmailsValuesSummary = ({
values,
summaryHintText,
onDelete,
disabled,
}: EmailsValuesSummaryProps) => (
<div className={`${componentName}__list-of-chip`}>
<span className={fr.cx("fr-hint-text")}>
{summaryHintText ??
"Voici les adresses emails qui seront ajoutées en copie :"}
</span>
<ul className={fr.cx("fr-tags-group", "fr-mt-1w")}>
<li>
{values.map((value) => (
<button
className={fr.cx("fr-tag", "fr-tag--dismiss")}
onClick={() => onDelete(value)}
key={value}
aria-label={`Supprimer l'adresse email ${value}`}
disabled={disabled}
>
{value}
</button>
))}
</li>
</ul>
</div>
); |
import mongoose, {Document, model, Schema} from "mongoose";
export interface IUser {
fullName: string;
email: string;
password: string;
contactNumber: string;
images: object;
ageGroup: string;
gender: string;
country: string;
state: string;
city: string;
maritalStatus: string;
occupation: string;
experties: string;
following: number;
followers: number;
point: number;
rewardPoint: number;
}
export interface IUserModel extends IUser, Document {
}
const UserSchema: Schema = new Schema(
{
fullName: {
type: String,
required: true
},
email: {type: String,
required: true,
unique: true
},
contactNumber: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
//select: false
},
images: {
type:Object
},
ageGroup: {
type: String
},
gender: {
type: String
},
country: {
type: String
},
state: {
type: String
},
city: {
type: String
},
maritalStatus: {
type: String
},
occupation: {
type: String
},
experties: {
type: String
},
point: {
type: Number
},
rewardPoint: {
type: Number
},
following: {
type: Number
},
followers: {
type: Number
},
authToken: {
type: String
},
/*
following: [
{
user:{
type: Schema.ObjectId,
ref: 'User'
},
}
],
followers: [
{
user:{
type: Schema.ObjectId,
ref: 'User'
},
}
],
*/
},
{
timestamps: true
}
);
export default mongoose.model<IUserModel>('User', UserSchema) |
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fitbit.research.sensing.common.libraries.camera;
import android.media.Image;
import androidx.camera.core.ImageProxy;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.android.fitbit.research.sensing.common.libraries.flow.DirectProcessor;
import com.google.android.fitbit.research.sensing.common.libraries.flow.RootShared;
import com.google.android.fitbit.research.sensing.common.libraries.flow.Shared;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
/**
* {@link ImageProxy} wrapped with {@link Shared}. See {@link Shared} for more details.
*
* <p>Sample usage:
*
* <pre>{@code
* public class ImageSubscriber implements Subscriber<SharedImageProxy> {
* @Override
* public void onNext(SharedImageProxy shared) {
* try (Shared.Holder<ImageProxy> holder = shared.acquire(this)) {
* ImageProxy imageProxy = holder.get();
* processImage(imageProxy.getImage());
* }
* // Don't manually call ImageProxy.close(); Shared will handle it automatically when all
* // other Subscribers that use the same SharedImageProxy are also finished.
* }
* }
* }</pre>
*/
@CheckReturnValue
public final class SharedImageProxy extends RootShared<ImageProxy> {
private final Shared<Image> image =
new Shared<Image>() {
@Override
public Shared.Holder<Image> acquire(Subscriber<?> key) {
return new ImageHolder(SharedImageProxy.this.acquire(key));
}
@Override
public void release(Subscriber<?> key) {
SharedImageProxy.this.release(key);
}
};
public SharedImageProxy(ImageProxy imageProxy, Publisher<SharedImageProxy> key) {
super(imageProxy, key);
}
/**
* Convenience method for transforming an {@code Publisher<SharedImageProxy>} into a {@code
* Publisher<Shared<Image>>}
*/
public static Publisher<Shared<Image>> asImagePublisher(Publisher<SharedImageProxy> publisher) {
return DirectProcessor.transformPublisher(publisher, SharedImageProxy::asImage);
}
/**
* Returns a shared {@link Image} that uses the same keys as SharedImageProxy.
*
* <p>This serves as bridge between CameraX-based {@link org.reactivestreams.Publisher}s and
* Camera2-based {@link org.reactivestreams.Subscriber}s.
*/
public Shared<Image> asImage() {
return image;
}
private static final class ImageHolder implements Shared.Holder<Image> {
private final Shared.Holder<ImageProxy> delegate;
ImageHolder(Shared.Holder<ImageProxy> delegate) {
this.delegate = delegate;
}
@Override
public Image get() {
return delegate.get().getImage();
}
@Override
public void close() {
delegate.close();
}
}
} |
var GroceryList = (props) => (
<ul>
{props.groceries.map(groceries =>
<GroceryListItem groceries={groceries} />
)}
</ul>
);
class GroceryListItem extends React.Component {
constructor(props) {
super(props);
this.state = {
done: false
}
}
onListItemClick() {
this.setState({
done: !this.state.done
})
}
render() {
var style = {
textDecoration: this.state.done ? 'line-through' : 'none'
};
return (
<li style={style} onClick={this.onListItemClick.bind(this)}>{this.props.groceries}</li>
);
return (
<li>{this.props.groceries}</li>
);
}
};
var App = () => (
<div>
<h2>My Grocery List</h2>
<GroceryList groceries={['Cucumbers', 'Kale', 'cereal', 'oatmeal', 'cha cha beat boi', '!!']} />
</div>
);
ReactDOM.render(<App />, document.getElementById('app')); |
# College Faculty Feedback Automation
## Overview
This Python script automates the process of providing feedback on faculty members for each semester. The project was developed to simplify and streamline the time-consuming task of filling out lengthy feedback forms on the college portal, which typically consists of over 150+ questions.
## Table of Contents
- [Features](#features)
- [Requirements](#requirements)
- [Usage](#usage)
- [Future Improvements](#future-improvements)
- [Contributing](#contributing)
## Features
- **User Inputs**: The script takes the SAP ID, password, and the desired rating as user inputs.
- **Automation**: It automates the entire process of logging in and submitting feedback.
- **Generalized**: The code is generalized to work with different branches and years of engineering students.
## Requirements
- [Python](https://www.python.org/) 3.x
- [Selenium](https://selenium-python.readthedocs.io/) Python library
- [Chrome WebDriver](https://sites.google.com/chromium.org/driver/)
## Usage
1. Clone this repository to your local machine.
```
git clone https://github.com/siddhant-192/NMIMS-Faculty-Feedback-Automation.git
```
2. Install the required Python libraries.
```
pip install selenium
```
3. Download and set up the Chrome WebDriver according to your system specifications.
4. Edit the script with your favorite code editor, providing your SAP ID, password, and the desired rating.
5. Run the script.
```
python feedback_automation.py
```
6. Sit back and watch as the script automates the feedback submission process for you.
## Future Improvements
- **Randomized Ratings**: Add a feature to randomize ratings for more authentic feedback.
- **Specific Feedback**: Allow users to specify particular professors or subjects for different ratings.
- **Improved Error Handling**: Enhance error handling and provide detailed error messages.
- **Data Logging**: Implement a logging system to keep track of feedback provided.
## Contributing
Contributions to the project are welcome! Feel free to submit pull requests, report issues, or suggest new features or improvements. |
#ifndef ZRECTANGLE_H
#define ZRECTANGLE_H
/**
* @package 3dogs
* @file ZRectangle.h
* @brief Unbeleuchtetes Rechteck
* D.h. Licht wird fuer das Objekt
* nicht berechnet !
* @author Rolf Hemmerling <hemmerling@gmx.net>
* @version 1.00,
* Entwicklungswerkzeug "Dev-C ++ 4.9.9.1",
* mit GNU-C/C++ Compiler "MinGW 3.3.1"
* @date 2015-01-01
* @copyright Apache License, Version 2.0
*
* modell/objects/ZRectangle.h -
* Unbeleuchtetes Rechteck
* D.h. Licht wird fuer das Objekt
* nicht berechnet !
*
* Copyright 2004-2015 Rolf Hemmerling
*
* 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.
*
* Haupt-Entwicklungszeit: 2004-03-01 - 2004-06-17
*/
#include "ycube.h"
/**
* @class ZRectangle
* @brief Unbeleuchtetes Rechteck.
* D.h. Licht wird fuer das Objekt nicht berechnet !
*/
class ZRectangle: public YCube
{
public:
/**
* @fn ZRectangle
* @brief Konstruktur
*/
ZRectangle(void);
/**
* @fn ~ZRectangle
* @brief Dekonstruktur
*/
~ZRectangle(void);
/**
* @fn display(OpenGL &aOpenGL)
* @brief Ausfuehren in OpenGL
* @param aOpenGL
*/
virtual void display(OpenGL &aOpenGL);
/**
* @fn getLength
* @brief Laenge holen
* @return GLfloat&
*/
virtual GLfloat &getLength(void);
/**
* @fn setLength(GLfloat length)
* @brief Laenge setzen
* @param length
*/
virtual void setLength(GLfloat length);
/**
* @fn getDefaultLength
* @brief Default-Laenge holen
* @return GLfloat&
*/
virtual GLfloat &getDefaultLength(void);
/**
* @fn setDefaultLength(GLfloat defaultLength)
* @brief Default-Laenge setzen
* @param defaultLength
*/
virtual void setDefaultLength(GLfloat defaultLength);
protected:
/**
* @var length
* @brief Laenge
*/
GLfloat length;
/**
* @var defaultLength
* @brief Default-Laenge
*/
GLfloat defaultLength;
};
#endif // ZRECTANGLE_H |
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "../../utils/cn";
import buttonVariants from "../Button/Button.styles";
import { CalendarProps } from "./Calendar.types";
/**
* The function `Calendar` renders a calendar component using DayPicker with customizable styling and
* navigation icons.
* @param {CalendarProps} - The `Calendar` function takes in the following parameters:
* @param {string} className - The class name for the calendar component.
* @param {Record<string, string>} classNames - The class names for the calendar elements.
* @param {boolean} showOutsideDays - A boolean value to show days outside the current month.
* @param {React.ComponentProps<typeof DayPicker>} props - The props for the DayPicker component.
* @param {SelectSingleEventHandler | SelectMultipleEventHandler | SelectRangeEventHandler} onSelect - The function to set the selected date.
* @returns The `Calendar` function is returning a `DayPicker` component with various props and
* classNames defined for styling purposes. The `DayPicker` component is customized with specific
* classNames for different elements like months, month, caption, nav, table, cell, day, and more. It
* also includes custom components for left and right navigation icons. The `Calendar` function accepts
* props like className, classNames, show
*/
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell:
"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
day: cn(
buttonVariants({ variant: "ghost" }),
"h-9 w-9 p-0 font-normal aria-selected:opacity-100"
),
day_range_end: "day-range-end",
day_selected:
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside:
"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle:
"aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: ({ ...props }) => <ChevronLeft className="h-4 w-4" />,
IconRight: ({ ...props }) => <ChevronRight className="h-4 w-4" />,
}}
{...props}
/>
);
}
Calendar.displayName = "Calendar";
export default Calendar; |
import { InteractionType } from '@/interfaces/content.interface';
import { IsDateString, IsEnum, IsString } from 'class-validator';
export class CreateContentDto {
@IsString()
public title: string;
@IsString()
public story: string;
@IsDateString()
public datePublished: string;
}
export class UpdateContentDto {
@IsString()
public title?: string;
@IsString()
public story?: string;
}
export class TopContentQueryParams {
@IsEnum(InteractionType, { message: 'sortBy must be one of read or like' })
public sortBy?: string;
} |
% Load camera parameters (replace 'cameraParams.mat' with your file)
load('../../Camera_Kalibrierung/calibrationSession_Nina.mat');
% Read the image of the checkerboard
image = imread('./Images/checkerboard_Color.jpg'); % replace with your image file
% Detect the checkerboard corners in the image
[imagePoints, boardSize] = detectCheckerboardPoints(image);
% Define the world coordinates of checkerboard corners
% This depends on the size of your checkerboard and the dimensions of the squares
squareSize = 30; % square size in millimeters
worldPoints = generateCheckerboardPoints(boardSize, squareSize);
% Estimate the pose of the checkerboard
[rotationMatrix, translationVector] = extrinsics(imagePoints, worldPoints, cameraParams);
% Select a corner point to find its position (e.g., first corner)
cornerIndex = 1;
cornerWorldPoint = worldPoints(cornerIndex, :);
% Transform the corner point from world to camera coordinates
cornerCameraPoint = worldToCamera(cameraParams, rotationMatrix, translationVector, cornerWorldPoint);
% Display the result
fprintf('Position of the corner in camera coordinates (in mm):\n X: %f\n Y: %f\n Z: %f\n', cornerCameraPoint); |
# 如何在 Angular 中创建反应式表单
> 原文:<https://dev.to/enniob/how-to-create-a-reactive-form-in-angular-2c1d>
在这篇文章中,我将介绍如何创建一个角度反应形式。我们将制作一个登录表单。我还将演示如何轻松地在表单中添加验证。
**让我们建立我们的项目**
如果您的电脑上没有安装 Angular,请转到 [Angular.io](https://angular.io/) 并按照说明在您的电脑上安装 Angular。你还需要一个编辑。我更喜欢的编辑器是 Visual Studio 代码。
我们来做一个新的角度项目。打开命令提示符并运行以下命令:
```
ng new <name>
```
按照提示上的步骤,一旦完成,你应该有一个新的角度应用。
要测试您的新应用程序,请打开命令提示符并键入`ng serve`;等待几秒钟,然后将网络浏览器指向 [](https://res.cloudinary.com/practicaldev/image/fetch/s--n20CdBGg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://localhost:4200/)
[](https://res.cloudinary.com/practicaldev/image/fetch/s--r-KxLzu---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/260kvhpmz6qog8oqv588.PNG)
**让我们做一些编码**
在您的代码编辑器中,打开`app.component.html`并用以下代码替换所有代码:
```
<div>
<button [routerLink]="['/']">Home</button>
<button [routerLink]="['login']">Login</button>
</div>
```
上面的源代码会添加登录按钮。如果您点击登录按钮,您将得到以下错误:`Error: Cannot match any routes. URL Segment: 'login' Error: Cannot match any routes. URL Segment: 'login'`
要修复这个错误,我们需要制作一个新组件并创建一条新路线。打开命令提示符并输入以下命令:`ng g component /login`以生成登录组件代码。接下来,打开`app-routing.modules.ts`文件,创建一个名为 login 的新路由。你的路线应该是这样的
```
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
const routes: Routes = [
{path: 'login', component: LoginComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
```
键入`ng serve`并打开浏览器。如果您现在单击 login 按钮,您将不会收到错误消息,您应该会在页面上看到一条消息说 login works!
[](https://res.cloudinary.com/practicaldev/image/fetch/s--QWvrIS93--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/jj268cfm1tt2oo1gg0i4.PNG)
现在我们有了路线,让我们做一个角度反应形式。打开 login.component.ts 文件,键入以下代码:
```
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validator, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm = new FormGroup({
userName: new FormControl('', Validators.compose([Validators.required])),
password: new FormControl('', Validators.compose([Validators.required]))
});
constructor() { }
ngOnInit() {
}
}
```
我们现在有一个 FormGroup,它包含两个 FormControls,一个用于用户名输入,另一个用于密码输入。在我们的 login.component.html 中,我们可以使用下面的 HTML 代码在浏览器上显示表单。
```
<form [formGroup]="loginForm" class="myForm">
Username:
<input type="text" formControlName="userName">
Password:
<input type="password" formControlName="password">
<button type="submit">Login</button>
</form>
```
打开浏览器,您应该会在开发人员控制台中看到一条错误消息,指出它无法绑定到“formGroup ”,因为它不是“form”的已知属性。
[](https://res.cloudinary.com/practicaldev/image/fetch/s--m4J5z6LQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/ih6m9000e3uw4j1le67u.PNG)
这是因为我们没有将 ReactiveFormModules 包含到我们的 app.module.ts 中,所以将以下代码添加到您的 app.module.ts 文件中。
```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
如果您返回到浏览器,您应该注意到开发人员控制台中不再有错误。
如果你点击登录按钮,什么都不会发生。我们将需要创建一个函数,并在提交表单时调用它。打开 login.component.ts 并将以下内容添加到 login.component.ts 中的表单标签`(ngSubmit)=”doLogin(loginForm)”`中我们有一个名为 doLogin 的函数,它接受 formGroup 类型的参数。下面是该函数的代码:
**login.component.html**T2】
```
<form [formGroup]="loginForm" (ngSubmit)="doLogin(loginForm)" class="myForm">
Username:
<input type="text" formControlName="userName">
Password:
<input type="password" formControlName="password">
<button type="submit">Login</button>
</form>
```
**login.component.ts**
```
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm = new FormGroup({
userName: new FormControl(''),
password: new FormControl('')
});
constructor() { }
ngOnInit() {
}
doLogin(formData: FormGroup) {
console.log(formData);
}
}
```
确保在浏览器中打开了开发人员控制台,并单击表单上的登录按钮。控制台显示表单组输出。单击左边的箭头展开表单组属性。
[](https://res.cloudinary.com/practicaldev/image/fetch/s--9cP8ux9F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/8wgytm27q21ser5zf806.PNG)
现在我们已经有了登录表单,让我们把它变得更漂亮。我们将使用有棱角的材料,所以我们必须先安装它。欲了解更多关于角状材料的信息,请访问他们的网站 https://material.angular.io 。在命令行中键入以下命令。
```
ng add @angular/material
```
一旦安装完成,我们可以导入我们想要使用的主题。将下面一行添加到您的 styles.scss.
```
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
```
**让我们替换以下文件中的代码:**
Login.component.html
```
<mat-card class="loginCard">
<mat-card-content>
<form [formGroup]="loginForm" (ngSubmit)="doLogin(loginForm)" class="myForm">
<mat-form-field class="fullWidth">
<mat-label>
Username:
</mat-label>
<input matInput type="text" formControlName="userName">
</mat-form-field>
<mat-form-field class="fullWidth">
<mat-label>
Password:
</mat-label>
<input matInput type="password" formControlName="password">
</mat-form-field>
<button mat-button type="submit">Login</button>
</form>
</mat-card-content>
</mat-card>
```
Login.component.scss
```
.loginCard {
width: 400px;
margin-left: auto;
margin-right: auto;
}
.myForm{
min-width: 150px;
max-width: 500px;
width: 100%;
}
.fullWidth {
width: 100%;
}
```
App.component.html
```
<mat-toolbar color="primary">
<mat-toolbar-row>
<button mat-button [routerLink]="['/']">Home</button>
<button mat-button [routerLink]="['login']">Login</button>
</mat-toolbar-row>
</mat-toolbar>
<router-outlet></router-outlet>
```
App.module.ts
```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// MATERIAL
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
BrowserAnimationsModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatToolbarModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
使用`ng serve`构建应用程序,您将看到一个导航标题,登录表单位于页面中央。
现在我们的登录表单看起来更好了,我们可以添加一些表单验证来确保用户输入有效的数据。
将以下代码添加到 login.component.ts.
```
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validator, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm = new FormGroup({
userName: new FormControl('', Validators.compose([Validators.required])),
password: new FormControl('', Validators.compose([Validators.required]))
});
constructor() { }
ngOnInit() {
}
doLogin(formData: FormGroup) {
console.log(formData);
}
}
```
当您返回到登录页面并单击 login 按钮时,您会注意到输入将变成红色,如果您在浏览器中打开控制台窗口,您会发现 FormGroup valid 属性被设置为 invalid。这是因为用户名和密码输入在表单组中被设置为必需的。
返回表单,输入用户名和密码,然后点击登录。您将看到 Formgroup valid 属性现在在控制台中被设置为 true。
结论
你现在知道如何创建反应式表单。如果您愿意,您可以轻松地添加多个验证器,甚至创建您自己的定制验证器。在我的下一篇文章中,我将向您展示如何创建一个使用 Firebase 身份验证的登录表单,我们还将创建一个连接到 Firebase 的注册表单。 |
package com.prac.react.model.dto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
@Configuration
public class AwsConfig {
/**
* Key는 중요정보이기 때문에 properties 파일에 저장한 뒤 가져와 사용하는 방법이 좋습니다.
*/
@Value("${cloud.aws.credentials.accessKey}")
private String iamAccessKey; // IAM Access Key
@Value("${cloud.aws.credentials.secretKey}")
private String iamSecretKey; // IAM Secret Key
@Value("${cloud.aws.region.static}")
private String region; // Bucket Region
//AmazonS3Client를 Bean으로 등록을 해서 사용할수 있도록 한다.
@Bean
public AmazonS3Client amazonS3Client() {
//accessKey와 secretKey를 가지고 Aws credential 객체를 생성한다.
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(iamAccessKey, iamSecretKey);
//그리고 AmazonS3Client를 위에서 만든 Credential 가지고 만들어서 반환한다.
return (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials))
.build();
}
} |
#ifndef TATO_LISTSET_H
#define TATO_LISTSET_H
#include <functional> //hash
#include <string>
#include <unordered_map>
#include "sentence.h"
NAMESPACE_START
struct listset
{
listset() = default;
listset & operator=( listset&& ) = default;
// a list is a group of sentence::id
typedef std::vector< sentence::id > list;
typedef std::vector< list > ctn;
typedef std::vector< list >::size_type offset;
typedef std::hash< std::string >::result_type list_hash;
typedef std::unordered_map< list_hash, offset > offset_list;
/**@brief Checks if a sentence belongs to a list
* @param[in] _id An identifier for the sentence
* @param[in] _listName The name of the list, there should not be any capital letters in.
* @return true if the sentence is part of the list */
bool isSentenceInList( sentence::id _id, const std::string & _listName ) const;
/**@brief Checks if a sentence belongs to a list
* @param[in] _id An identifier for the sentence
* @param[in] _hash The hash of the list
* @return true if the sentence is part of the list */
bool isSentenceInList( sentence::id _id, list_hash _hash ) const;
/**@brief Checks if a list exists
* @param[in] _listName The name of the list */
bool doesListExist( const std::string & _listName ) const;
#ifdef USE_PYTHON_WRAPPER
bool pythonIsSentenceInList( sentence::id _id, const std::string & _listName ) const
{
return isSentenceInList( _id, _listName );
}
#endif
public:
/**@brief Inserts a sentence into a list
* @param[in] _id the sentence id
* @param[in] _listName The name of the list */
void addSentenceToList( sentence::id _id, const std::string & _listName );
/**@brief Computes a hash from the name of a list
* @param[in] _listName the name of the list. There should not be any capital letters in.
* @return An hash corresponding to that name */
static list_hash computeHash( const std::string & _listName );
private:
// returns the offset inside m_lists, or -1 if it cannot be found
offset findOffset( list_hash ) const;
void addNewList( list_hash );
list & getList( const offset & );
const list & getList( const offset & ) const ;
private:
ctn m_lists;
offset_list m_offsets;
};
NAMESPACE_END
#endif //TATO_LISTSET_H |
<!DOCTYPE html>
<html>
<head>
<title>Notifications</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #1e1e1e;
color: #f7f7f7;
padding: 20px;
}
h1 {
text-align: center;
}
button {
padding: 10px 20px;
background-color: #0d47a1;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
margin-right: 10px;
}
.notification {
background-color: #333;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
.notification.success {
background-color: #2ecc71;
}
.notification.error {
background-color: #e74c3c;
}
.notification.info {
background-color: #3498db;
}
.reminder {
background-color: #1e1e1e;
border: 1px solid #333;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
.reminder-time {
font-weight: bold;
margin-bottom: 5px;
}
.reminder-message {
white-space: pre-line;
}
h2 {
margin-top: 20px;
}
form {
margin-top: 10px;
}
label {
display: inline-block;
width: 80px;
}
input[type="text"],
input[type="submit"] {
padding: 5px;
width: 200px;
border-radius: 5px;
border: 1px solid #ccc;
}
input[type="submit"] {
background-color: #0d47a1;
color: #fff;
border: none;
cursor: pointer;
}
</style>
<script>
function createNotification(type, message) {
var notification = document.createElement("div");
notification.className = "notification " + type;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(function() {
document.body.removeChild(notification);
}, 3000);
}
function showLoanApproval() {
var loanType = "Home Loan";
var loanAmount = "$200,000";
var message = "Congratulations! Your " + loanType + " application has been approved for an amount of " + loanAmount + ".";
createNotification("success", message);
createReminder("Tomorrow", "Remember to sign the loan agreement.");
}
function approveNewCard() {
var cardType = "Visa";
var cardNumber = "**** **** **** 1234";
var message = "✅ Your new " + cardType + " card ending in " + cardNumber + " has been approved. It will be delivered to your registered address soon.";
createNotification("success", message);
createReminder("Next week", "Don't forget to activate your new card upon arrival.");
}
function showBankAnnouncement() {
var announcementTitle = "New Branch Opening";
var announcementContent = "We are excited to announce the opening of our new branch in downtown. Visit us for exclusive offers!";
var message = "📢 " + announcementTitle + " 📢\n\n" + announcementContent;
createNotification("info", message);
}
var reminderId = 1; // Unique identifier for each reminder
function createReminder(time, message) {
var reminder = document.createElement("div");
reminder.className = "reminder";
reminder.id = "reminder-" + reminderId; // Assign a unique ID to the reminder element
reminder.innerHTML = "<div class='reminder-time'>" + time + "</div><div class='reminder-message'>" + message + "</div>";
document.getElementById("reminders-container").appendChild(reminder);
showNotification(time, message); // Show the notification when creating the reminder
reminderId++; // Increment the reminder ID for the next reminder
}
function setReminder() {
var timeInput = document.getElementById("time");
var messageInput = document.getElementById("message");
var time = timeInput.value;
var message = messageInput.value;
if (time === "" || message === "") {
alert("Please provide all the required information.");
return;
}
createReminder(time, message);
timeInput.value = "";
messageInput.value = "";
}
function showNotification(time, message) {
if (Notification.permission === "granted") {
var notification = new Notification("Reminder", {
body: message,
icon: "notification-icon.png"
});
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then(function (permission) {
if (permission === "granted") {
var notification = new Notification("Reminder", {
body: message,
icon: "notification-icon.png"
});
}
});
}
}
function handleIssue() {
var issueType = "Payment Error";
var issueMessage = "There was an error processing your payment. Please contact our support team for assistance.";
var message = "⚠️ " + issueType + " ⚠️\n\n" + issueMessage;
createNotification("error", message);
}
function receiveReminder(time, message) {
createNotification("info", "Reminder: " + time + "\n\n" + message);
}
</script>
</head>
<body>
<h1>Bank Notifications</h1>
<button onclick="showLoanApproval()">Show Loan Approval</button>
<button onclick="showBankAnnouncement()">Show Bank Announcement</button>
<button onclick="handleIssue()">Handle Issue</button>
<button onclick="approveNewCard()">Approve New Card</button>
<h1>Reminders</h1>
<div id="reminders-container"></div>
<h2>Create Reminder</h2>
<form onsubmit="event.preventDefault(); setReminder();">
<p>
<label for="time">Time:</label>
<input type="text" id="time" name="time" required>
</p>
<p>
<label for="message">Message:</label>
<input type="text" id="message" name="message" required>
</p>
<button type="submit">Set Reminder</button>
</form>
</form>
<button type="submit" onclick="window.location.href='ClientDashBoard.html';">Back</button>
</body>
</html> |
import React from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as courseActions from "../../redux/actions/courseActions";
import * as authorActions from "../../redux/actions/authorActions";
import propTypes from "prop-types";
import CourseList from "./CourseList";
import { Redirect } from "react-router-dom";
import Spinner from "../common/Spinner";
import { toast } from "react-toastify";
class CoursesPage extends React.Component {
state = {
redirectToAddCoursePage: false
};
componentDidMount() {
const { courses, authors, actions } = this.props;
if (courses.length === 0) {
actions.loadCourses().catch(error => {
alert("Loading courses failed " + error);
});
}
if (authors.length === 0) {
actions.loadAuthors().catch(error => {
alert("Loading authors failed " + error);
});
}
}
/**
* async and await are used here as an example of an alternaive way of handling asynhronous interactions
*/
handleDeleteCourse = async course => {
toast.success("Course deleted");
try {
await this.props.actions.deleteCourse(course);
} catch (error) {
toast.error("Delete failed. " + error.message, { autoClose: false });
}
};
render() {
return (
<>
{this.state.redirectToAddCoursePage && <Redirect to="/course" />}
<h2>Courses</h2>
{this.props.loading ?
<Spinner /> : (
<>
<button
style={{ marginBottom: 20 }}
className="btn btn-primary add-course"
onClick={() => this.setState({ redirectToAddCoursePage: true })}
>
Add Course
</button>
<CourseList onDeleteClick={this.handleDeleteCourse} courses={this.props.courses} />
</>
)
}
</>
);
}
}
CoursesPage.propTypes = {
courses: propTypes.array.isRequired,
authors: propTypes.array.isRequired,
actions: propTypes.object.isRequired,
loading: propTypes.bool.isRequired
};
//this injects the state used/supported by this container component into the props, to be passed down to the view
function mapStateToProps(state) {
return {
//this verifies is authors list has been returned so they can be weaved in the "merged result"
courses: state.authors.length === 0 ? []
: state.courses.map(course => {
return {
...course,
authorName: state.authors.find(a => a.id === course.authorId).name
}
}),
authors: state.authors,
loading: state.apiCallsInProgress > 0
}
}
//this injects dispatch actions to be supported by this container component into the props.dispatch,
//to be passed down to the view
function mapDispatchToProps(dispatch) {
return {
actions: {
loadCourses: bindActionCreators(courseActions.loadCourses, dispatch),
loadAuthors: bindActionCreators(authorActions.loadAuthors, dispatch),
deleteCourse: bindActionCreators(courseActions.deleteCourse, dispatch)
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage); |
import { useState } from "react";
import Gameboard from "./Components/Gameboard";
import Players from "./Components/Players";
import Log from "./Components/Log";
function App() {
const [gamerTurn, setGameturn] = useState([]);
const [activeplayer, setactiveplayer] = useState("X");
const handleSelectsquare = () => {
setactiveplayer((prevalue) => (prevalue === "X" ? "O" : "X"));
setGameturn((prevalue) => {
let currentPlayer = "x";
if (prevalue.length > 0 && prevalue[0].player === "X") {
currentPlayer = "O";
}
const updateTurns = [
{
square: {
row: rowIndex,
col: colIndex,
},
player: currentPlayer,
},
...prevalue,
];
return updateTurns;
});
};
return (
<main>
<div id="game-container">
<ol id="players" className="highlight-player">
<Players name="Player 1" symbol="X" isActive={activeplayer === "X"} />
<Players name="Player 2" symbol="O" isActive={activeplayer === "O"} />
</ol>
{/* GameBoard old attribute = activeSymbolOnBoard={activeplayer} */}
<Gameboard onSelectExecute={handleSelectsquare} turns={gamerTurn} />
</div>
<Log turns={gamerTurn} />
</main>
);
}
export default App; |
const express = require("express"),
bodyParser = require("body-parser"),
ejs = require("ejs"),
_ = require('lodash');
const app = express();
const port = 3000;
let homeText = "Lorem ipsum dolor sit amet, officia excepteur ex fugiat reprehenderit enim labore culpa sint ad nisi Lorem pariatur mollit ex esse exercitation amet. Nisi anim cupidatat excepteur officia. Reprehenderit nostrud nostrud ipsum Lorem est aliquip amet voluptate voluptate dolor minim nulla est proident. Nostrud officia pariatur ut officia. Sit irure elit esse ea nulla sunt ex occaecat reprehenderit commodo officia dolor Lorem duis laboris cupidatat officia voluptate. Culpa proident adipisicing id nulla nisi laboris ex in Lorem sunt duis officia eiusmod. Aliqua reprehenderit commodo ex non excepteur duis sunt velit enim. Voluptate laboris sint cupidatat ullamco ut ea consectetur et est culpa et culpa duis."
let contactText = "Lorem ipsum dolor sit amet, officia excepteur ex fugiat reprehenderit enim labore culpa sint ad nisi Lorem pariatur mollit ex esse exercitation amet. Nisi anim cupidatat excepteur officia. Reprehenderit nostrud nostrud ipsum Lorem est aliquip amet voluptate voluptate dolor minim nulla est proident. Nostrud officia pariatur ut officia. Sit irure elit esse ea nulla sunt ex occaecat reprehenderit commodo officia dolor Lorem duis laboris cupidatat officia voluptate. Culpa proident adipisicing id nulla nisi laboris ex in Lorem sunt duis officia eiusmod. Aliqua reprehenderit commodo ex non excepteur duis sunt velit enim. Voluptate laboris sint cupidatat ullamco ut ea consectetur et est culpa et culpa duis."
let aboutText = "Lorem ipsum dolor sit amet, officia excepteur ex fugiat reprehenderit enim labore culpa sint ad nisi Lorem pariatur mollit ex esse exercitation amet. Nisi anim cupidatat excepteur officia. Reprehenderit nostrud nostrud ipsum Lorem est aliquip amet voluptate voluptate dolor minim nulla est proident. Nostrud officia pariatur ut officia. Sit irure elit esse ea nulla sunt ex occaecat reprehenderit commodo officia dolor Lorem duis laboris cupidatat officia voluptate. Culpa proident adipisicing id nulla nisi laboris ex in Lorem sunt duis officia eiusmod. Aliqua reprehenderit commodo ex non excepteur duis sunt velit enim. Voluptate laboris sint cupidatat ullamco ut ea consectetur et est culpa et culpa duis."
let postList = [];
let post1Object = {title: "Day 1", content: "Lorem ipsum dolor sit amet, qui minim labore adipisicing minim sint cillum sint consectetur cupidatat."}
let post2Object = {title: "Day 2", content: "Lorem ipsum dolor sit amet, qui minim labore adipisicing minim sint cillum sint consectetur cupidatat."}
postList.push(post1Object)
postList.push(post2Object)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static("public"))
app.set('view engine', 'ejs');
app.get("/", (req, res)=>{
res.render("home", {title: "Home", content: homeText, postList: postList})
})
app.get("/contact", (req, res)=>{
res.render("contact", {title:"Contact", content: contactText})
})
app.get("/about", (req, res)=>{
res.render("about" ,{title: "About", content: aboutText})
})
app.get("/compose", (req, res)=>{
res.render("compose", {title: "About", content: aboutText})
})
app.post("/post", (req, res)=>{
let postObject = {title: _.capitalize(req.body.title), content: req.body.content}
postList.push(postObject)
res.redirect("/")
})
app.get("/posts/:post_name", (req, res)=>{
postList.forEach( post => {
if (post.title.toLowerCase() == req.params.post_name.toLowerCase()){
res.render("post", {title: post.title, content: post.content})
}
});
})
app.listen(port, ()=>{
console.log("Server ready on port " + port)
}) |
/// Geometry Interfaces Module Level 1
///
/// https://drafts.fxtf.org/geometry/
// ignore_for_file: unused_import
@JS('self')
@staticInterop
library geometry_1;
import 'dart:js_util' as js_util;
import 'package:js/js.dart';
import 'package:meta/meta.dart';
import 'dart:typed_data';
import 'package:js_bindings/js_bindings.dart';
/// The interface specifies the coordinate and perspective fields
/// used by [DOMPoint] to define a 2D or 3D point in a coordinate
/// system.
/// Note: This feature is available in Web Workers
///
/// There are two ways to create a new instance. First, you can use
/// its constructor, passing in the values of the parameters for each
/// dimension and, optionally, the perspective:
/// [/* 2D */
/// const point = new DOMPointReadOnly(50, 50);
///
/// /* 3D */
/// const point = new DOMPointReadOnly(50, 50, 25);
///
/// /* 3D with perspective */
/// const point = new DOMPointReadOnly(100, 100, 100, 1.0);
/// ]
/// The other option is to use the static
/// [DOMPointReadOnly.fromPoint()] method:
/// [const point = DOMPointReadOnly.fromPoint({x: 100, y: 100, z:
/// 50; w: 1.0});
/// ]
@JS()
@staticInterop
class DOMPointReadOnly {
external factory DOMPointReadOnly._(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic z = 0,
/* double | NaN */ dynamic w = 1]);
factory DOMPointReadOnly(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic z = 0,
/* double | NaN */ dynamic w = 1]) =>
DOMPointReadOnly._(x ?? 0, y ?? 0, z ?? 0, w ?? 1);
external static dynamic fromPoint([DOMPointInit? other]);
}
extension PropsDOMPointReadOnly on DOMPointReadOnly {
/* double | NaN */ dynamic get x => js_util.getProperty(this, 'x');
/* double | NaN */ dynamic get y => js_util.getProperty(this, 'y');
/* double | NaN */ dynamic get z => js_util.getProperty(this, 'z');
/* double | NaN */ dynamic get w => js_util.getProperty(this, 'w');
DOMPoint matrixTransform([DOMMatrixInit? matrix]) =>
js_util.callMethod(this, 'matrixTransform', [matrix]);
dynamic toJSON() => js_util.callMethod(this, 'toJSON', []);
}
/// A object represents a 2D or 3D point in a coordinate system; it
/// includes values for the coordinates in up to three dimensions, as
/// well as an optional perspective value. is based on
/// [DOMPointReadOnly] but allows its properties' values to be
/// changed.
/// In general, a positive [x] component represents a position to
/// the right of the origin, a positive [y] component is downward
/// from the origin, and a positive [z] component extends outward
/// from the screen (in other words, toward the user).
///
///
///
/// DOMPointReadOnly
///
///
///
///
///
/// DOMPoint
///
///
@JS()
@staticInterop
class DOMPoint implements DOMPointReadOnly {
external factory DOMPoint._(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic z = 0,
/* double | NaN */ dynamic w = 1]);
factory DOMPoint(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic z = 0,
/* double | NaN */ dynamic w = 1]) =>
DOMPoint._(x ?? 0, y ?? 0, z ?? 0, w ?? 1);
external static DOMPoint fromPoint([DOMPointInit? other]);
}
extension PropsDOMPoint on DOMPoint {
/* double | NaN */ dynamic get x => js_util.getProperty(this, 'x');
set x(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'x', newValue);
}
/* double | NaN */ dynamic get y => js_util.getProperty(this, 'y');
set y(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'y', newValue);
}
/* double | NaN */ dynamic get z => js_util.getProperty(this, 'z');
set z(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'z', newValue);
}
/* double | NaN */ dynamic get w => js_util.getProperty(this, 'w');
set w(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'w', newValue);
}
}
@anonymous
@JS()
@staticInterop
class DOMPointInit {
external factory DOMPointInit._(
{/* double | NaN */ dynamic x,
/* double | NaN */ dynamic y,
/* double | NaN */ dynamic z,
/* double | NaN */ dynamic w});
factory DOMPointInit(
{/* double | NaN */ dynamic x,
/* double | NaN */ dynamic y,
/* double | NaN */ dynamic z,
/* double | NaN */ dynamic w}) =>
DOMPointInit._(x: x ?? 0, y: y ?? 0, z: z ?? 0, w: w ?? 1);
}
extension PropsDOMPointInit on DOMPointInit {
/* double | NaN */ dynamic get x => js_util.getProperty(this, 'x');
set x(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'x', newValue);
}
/* double | NaN */ dynamic get y => js_util.getProperty(this, 'y');
set y(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'y', newValue);
}
/* double | NaN */ dynamic get z => js_util.getProperty(this, 'z');
set z(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'z', newValue);
}
/* double | NaN */ dynamic get w => js_util.getProperty(this, 'w');
set w(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'w', newValue);
}
}
/// The interface specifies the standard properties used by
/// [DOMRect] to define a rectangle whose properties are immutable.
@JS()
@staticInterop
class DOMRectReadOnly {
external factory DOMRectReadOnly._(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic width = 0,
/* double | NaN */ dynamic height = 0]);
factory DOMRectReadOnly(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic width = 0,
/* double | NaN */ dynamic height = 0]) =>
DOMRectReadOnly._(x ?? 0, y ?? 0, width ?? 0, height ?? 0);
external static dynamic fromRect([DOMRectInit? other]);
}
extension PropsDOMRectReadOnly on DOMRectReadOnly {
/* double | NaN */ dynamic get x => js_util.getProperty(this, 'x');
/* double | NaN */ dynamic get y => js_util.getProperty(this, 'y');
/* double | NaN */ dynamic get width => js_util.getProperty(this, 'width');
/* double | NaN */ dynamic get height => js_util.getProperty(this, 'height');
/* double | NaN */ dynamic get top => js_util.getProperty(this, 'top');
/* double | NaN */ dynamic get right => js_util.getProperty(this, 'right');
/* double | NaN */ dynamic get bottom => js_util.getProperty(this, 'bottom');
/* double | NaN */ dynamic get left => js_util.getProperty(this, 'left');
dynamic toJSON() => js_util.callMethod(this, 'toJSON', []);
}
/// A describes the size and position of a rectangle.
/// The type of box represented by the is specified by the method or
/// property that returned it. For example,
/// [VREyeParameters.renderRect] from the WebVR API specifies the
/// viewport of a canvas into which visuals for one eye of a head
/// mounted display should be rendered.
/// It inherits from its parent, [DOMRectReadOnly].
///
///
///
/// DOMRectReadOnly
///
///
///
///
///
/// DOMRect
///
///
@JS()
@staticInterop
class DOMRect implements DOMRectReadOnly {
external factory DOMRect._(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic width = 0,
/* double | NaN */ dynamic height = 0]);
factory DOMRect(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic width = 0,
/* double | NaN */ dynamic height = 0]) =>
DOMRect._(x ?? 0, y ?? 0, width ?? 0, height ?? 0);
external static DOMRect fromRect([DOMRectInit? other]);
}
extension PropsDOMRect on DOMRect {
/* double | NaN */ dynamic get x => js_util.getProperty(this, 'x');
set x(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'x', newValue);
}
/* double | NaN */ dynamic get y => js_util.getProperty(this, 'y');
set y(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'y', newValue);
}
/* double | NaN */ dynamic get width => js_util.getProperty(this, 'width');
set width(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'width', newValue);
}
/* double | NaN */ dynamic get height => js_util.getProperty(this, 'height');
set height(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'height', newValue);
}
}
@anonymous
@JS()
@staticInterop
class DOMRectInit {
external factory DOMRectInit._(
{/* double | NaN */ dynamic x,
/* double | NaN */ dynamic y,
/* double | NaN */ dynamic width,
/* double | NaN */ dynamic height});
factory DOMRectInit(
{/* double | NaN */ dynamic x,
/* double | NaN */ dynamic y,
/* double | NaN */ dynamic width,
/* double | NaN */ dynamic height}) =>
DOMRectInit._(
x: x ?? 0, y: y ?? 0, width: width ?? 0, height: height ?? 0);
}
extension PropsDOMRectInit on DOMRectInit {
/* double | NaN */ dynamic get x => js_util.getProperty(this, 'x');
set x(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'x', newValue);
}
/* double | NaN */ dynamic get y => js_util.getProperty(this, 'y');
set y(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'y', newValue);
}
/* double | NaN */ dynamic get width => js_util.getProperty(this, 'width');
set width(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'width', newValue);
}
/* double | NaN */ dynamic get height => js_util.getProperty(this, 'height');
set height(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'height', newValue);
}
}
@JS()
@staticInterop
class DOMRectList {
external factory DOMRectList();
}
extension PropsDOMRectList on DOMRectList {
int get length => js_util.getProperty(this, 'length');
DOMRect? item(int index) => js_util.callMethod(this, 'item', [index]);
}
/// Experimental: This is an experimental technologyCheck the
/// Browser compatibility table carefully before using this in
/// production.
/// A is a collection of four [DOMPoint]s defining the corners of an
/// arbitrary quadrilateral. Returning s lets [getBoxQuads()] return
/// accurate information even when arbitrary 2D or 3D transforms are
/// present. It has a handy [bounds] attribute returning a
/// [DOMRectReadOnly] for those cases where you just want an
/// axis-aligned bounding rectangle.
@experimental
@JS()
@staticInterop
class DOMQuad {
external factory DOMQuad._(
[DOMPointInit? p1, DOMPointInit? p2, DOMPointInit? p3, DOMPointInit? p4]);
factory DOMQuad(
[DOMPointInit? p1,
DOMPointInit? p2,
DOMPointInit? p3,
DOMPointInit? p4]) =>
DOMQuad._(
p1 ?? undefined, p2 ?? undefined, p3 ?? undefined, p4 ?? undefined);
external static DOMQuad fromRect([DOMRectInit? other]);
external static DOMQuad fromQuad([DOMQuadInit? other]);
}
extension PropsDOMQuad on DOMQuad {
DOMPoint get p1 => js_util.getProperty(this, 'p1');
DOMPoint get p2 => js_util.getProperty(this, 'p2');
DOMPoint get p3 => js_util.getProperty(this, 'p3');
DOMPoint get p4 => js_util.getProperty(this, 'p4');
DOMRect getBounds() => js_util.callMethod(this, 'getBounds', []);
dynamic toJSON() => js_util.callMethod(this, 'toJSON', []);
}
@anonymous
@JS()
@staticInterop
class DOMQuadInit {
external factory DOMQuadInit(
{DOMPointInit? p1, DOMPointInit? p2, DOMPointInit? p3, DOMPointInit? p4});
}
extension PropsDOMQuadInit on DOMQuadInit {
DOMPointInit get p1 => js_util.getProperty(this, 'p1');
set p1(DOMPointInit newValue) {
js_util.setProperty(this, 'p1', newValue);
}
DOMPointInit get p2 => js_util.getProperty(this, 'p2');
set p2(DOMPointInit newValue) {
js_util.setProperty(this, 'p2', newValue);
}
DOMPointInit get p3 => js_util.getProperty(this, 'p3');
set p3(DOMPointInit newValue) {
js_util.setProperty(this, 'p3', newValue);
}
DOMPointInit get p4 => js_util.getProperty(this, 'p4');
set p4(DOMPointInit newValue) {
js_util.setProperty(this, 'p4', newValue);
}
}
/// The interface represents a read-only 4×4 matrix, suitable for 2D
/// and 3D operations. The [DOMMatrix] interface — which is based
/// upon —adds mutability, allowing you to alter the matrix after
/// creating it.
/// This interface should be available inside web workers, though
/// some implementations doesn't allow it yet.
@JS()
@staticInterop
class DOMMatrixReadOnly {
external factory DOMMatrixReadOnly._([dynamic init]);
factory DOMMatrixReadOnly([dynamic init]) =>
DOMMatrixReadOnly._(init ?? undefined);
external static dynamic fromMatrix([DOMMatrixInit? other]);
external static dynamic fromFloat32Array(Float32List array32);
external static dynamic fromFloat64Array(Float64List array64);
}
extension PropsDOMMatrixReadOnly on DOMMatrixReadOnly {
/* double | NaN */ dynamic get a => js_util.getProperty(this, 'a');
/* double | NaN */ dynamic get b => js_util.getProperty(this, 'b');
/* double | NaN */ dynamic get c => js_util.getProperty(this, 'c');
/* double | NaN */ dynamic get d => js_util.getProperty(this, 'd');
/* double | NaN */ dynamic get e => js_util.getProperty(this, 'e');
/* double | NaN */ dynamic get f => js_util.getProperty(this, 'f');
/* double | NaN */ dynamic get m11 => js_util.getProperty(this, 'm11');
/* double | NaN */ dynamic get m12 => js_util.getProperty(this, 'm12');
/* double | NaN */ dynamic get m13 => js_util.getProperty(this, 'm13');
/* double | NaN */ dynamic get m14 => js_util.getProperty(this, 'm14');
/* double | NaN */ dynamic get m21 => js_util.getProperty(this, 'm21');
/* double | NaN */ dynamic get m22 => js_util.getProperty(this, 'm22');
/* double | NaN */ dynamic get m23 => js_util.getProperty(this, 'm23');
/* double | NaN */ dynamic get m24 => js_util.getProperty(this, 'm24');
/* double | NaN */ dynamic get m31 => js_util.getProperty(this, 'm31');
/* double | NaN */ dynamic get m32 => js_util.getProperty(this, 'm32');
/* double | NaN */ dynamic get m33 => js_util.getProperty(this, 'm33');
/* double | NaN */ dynamic get m34 => js_util.getProperty(this, 'm34');
/* double | NaN */ dynamic get m41 => js_util.getProperty(this, 'm41');
/* double | NaN */ dynamic get m42 => js_util.getProperty(this, 'm42');
/* double | NaN */ dynamic get m43 => js_util.getProperty(this, 'm43');
/* double | NaN */ dynamic get m44 => js_util.getProperty(this, 'm44');
bool get is2D => js_util.getProperty(this, 'is2D');
bool get isIdentity => js_util.getProperty(this, 'isIdentity');
DOMMatrix translate(
[/* double | NaN */ dynamic tx = 0,
/* double | NaN */ dynamic ty = 0,
/* double | NaN */ dynamic tz = 0]) =>
js_util.callMethod(this, 'translate', [tx, ty, tz]);
DOMMatrix scale(
[/* double | NaN */ dynamic scaleX = 1,
/* double | NaN */ dynamic scaleY,
/* double | NaN */ dynamic scaleZ = 1,
/* double | NaN */ dynamic originX = 0,
/* double | NaN */ dynamic originY = 0,
/* double | NaN */ dynamic originZ = 0]) =>
js_util.callMethod(
this, 'scale', [scaleX, scaleY, scaleZ, originX, originY, originZ]);
DOMMatrix scaleNonUniform(
[/* double | NaN */ dynamic scaleX = 1,
/* double | NaN */ dynamic scaleY = 1]) =>
js_util.callMethod(this, 'scaleNonUniform', [scaleX, scaleY]);
DOMMatrix scale3d(
[/* double | NaN */ dynamic scale = 1,
/* double | NaN */ dynamic originX = 0,
/* double | NaN */ dynamic originY = 0,
/* double | NaN */ dynamic originZ = 0]) =>
js_util.callMethod(this, 'scale3d', [scale, originX, originY, originZ]);
DOMMatrix rotate(
[/* double | NaN */ dynamic rotX = 0,
/* double | NaN */ dynamic rotY,
/* double | NaN */ dynamic rotZ]) =>
js_util.callMethod(this, 'rotate', [rotX, rotY, rotZ]);
DOMMatrix rotateFromVector(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0]) =>
js_util.callMethod(this, 'rotateFromVector', [x, y]);
DOMMatrix rotateAxisAngle(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic z = 0,
/* double | NaN */ dynamic angle = 0]) =>
js_util.callMethod(this, 'rotateAxisAngle', [x, y, z, angle]);
DOMMatrix skewX([/* double | NaN */ dynamic sx = 0]) =>
js_util.callMethod(this, 'skewX', [sx]);
DOMMatrix skewY([/* double | NaN */ dynamic sy = 0]) =>
js_util.callMethod(this, 'skewY', [sy]);
DOMMatrix multiply([DOMMatrixInit? other]) =>
js_util.callMethod(this, 'multiply', [other]);
DOMMatrix flipX() => js_util.callMethod(this, 'flipX', []);
DOMMatrix flipY() => js_util.callMethod(this, 'flipY', []);
DOMMatrix inverse() => js_util.callMethod(this, 'inverse', []);
DOMPoint transformPoint([DOMPointInit? point]) =>
js_util.callMethod(this, 'transformPoint', [point]);
Float32List toFloat32Array() =>
js_util.callMethod(this, 'toFloat32Array', []);
Float64List toFloat64Array() =>
js_util.callMethod(this, 'toFloat64Array', []);
String mToString() => js_util.callMethod(this, 'toString', []);
dynamic toJSON() => js_util.callMethod(this, 'toJSON', []);
}
/// The interface represents 4×4 matrices, suitable for 2D and 3D
/// operations including rotation and translation. It is a mutable
/// version of the [DOMMatrixReadOnly] interface.
/// [WebKitCSSMatrix] is an alias to .
/// This interface should be available inside web workers, though
/// some implementations don't allow it yet.
///
///
///
/// DOMMatrixReadOnly
///
///
///
///
///
/// DOMMatrix
///
///
@experimental
@JS()
@staticInterop
class DOMMatrix implements DOMMatrixReadOnly {
external factory DOMMatrix._([dynamic init]);
factory DOMMatrix([dynamic init]) => DOMMatrix._(init ?? undefined);
external static DOMMatrix fromMatrix([DOMMatrixInit? other]);
external static DOMMatrix fromFloat32Array(Float32List array32);
external static DOMMatrix fromFloat64Array(Float64List array64);
}
extension PropsDOMMatrix on DOMMatrix {
/* double | NaN */ dynamic get a => js_util.getProperty(this, 'a');
set a(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'a', newValue);
}
/* double | NaN */ dynamic get b => js_util.getProperty(this, 'b');
set b(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'b', newValue);
}
/* double | NaN */ dynamic get c => js_util.getProperty(this, 'c');
set c(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'c', newValue);
}
/* double | NaN */ dynamic get d => js_util.getProperty(this, 'd');
set d(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'd', newValue);
}
/* double | NaN */ dynamic get e => js_util.getProperty(this, 'e');
set e(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'e', newValue);
}
/* double | NaN */ dynamic get f => js_util.getProperty(this, 'f');
set f(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'f', newValue);
}
/* double | NaN */ dynamic get m11 => js_util.getProperty(this, 'm11');
set m11(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm11', newValue);
}
/* double | NaN */ dynamic get m12 => js_util.getProperty(this, 'm12');
set m12(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm12', newValue);
}
/* double | NaN */ dynamic get m13 => js_util.getProperty(this, 'm13');
set m13(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm13', newValue);
}
/* double | NaN */ dynamic get m14 => js_util.getProperty(this, 'm14');
set m14(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm14', newValue);
}
/* double | NaN */ dynamic get m21 => js_util.getProperty(this, 'm21');
set m21(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm21', newValue);
}
/* double | NaN */ dynamic get m22 => js_util.getProperty(this, 'm22');
set m22(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm22', newValue);
}
/* double | NaN */ dynamic get m23 => js_util.getProperty(this, 'm23');
set m23(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm23', newValue);
}
/* double | NaN */ dynamic get m24 => js_util.getProperty(this, 'm24');
set m24(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm24', newValue);
}
/* double | NaN */ dynamic get m31 => js_util.getProperty(this, 'm31');
set m31(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm31', newValue);
}
/* double | NaN */ dynamic get m32 => js_util.getProperty(this, 'm32');
set m32(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm32', newValue);
}
/* double | NaN */ dynamic get m33 => js_util.getProperty(this, 'm33');
set m33(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm33', newValue);
}
/* double | NaN */ dynamic get m34 => js_util.getProperty(this, 'm34');
set m34(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm34', newValue);
}
/* double | NaN */ dynamic get m41 => js_util.getProperty(this, 'm41');
set m41(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm41', newValue);
}
/* double | NaN */ dynamic get m42 => js_util.getProperty(this, 'm42');
set m42(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm42', newValue);
}
/* double | NaN */ dynamic get m43 => js_util.getProperty(this, 'm43');
set m43(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm43', newValue);
}
/* double | NaN */ dynamic get m44 => js_util.getProperty(this, 'm44');
set m44(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm44', newValue);
}
DOMMatrix multiplySelf([DOMMatrixInit? other]) =>
js_util.callMethod(this, 'multiplySelf', [other]);
DOMMatrix preMultiplySelf([DOMMatrixInit? other]) =>
js_util.callMethod(this, 'preMultiplySelf', [other]);
DOMMatrix translateSelf(
[/* double | NaN */ dynamic tx = 0,
/* double | NaN */ dynamic ty = 0,
/* double | NaN */ dynamic tz = 0]) =>
js_util.callMethod(this, 'translateSelf', [tx, ty, tz]);
DOMMatrix scaleSelf(
[/* double | NaN */ dynamic scaleX = 1,
/* double | NaN */ dynamic scaleY,
/* double | NaN */ dynamic scaleZ = 1,
/* double | NaN */ dynamic originX = 0,
/* double | NaN */ dynamic originY = 0,
/* double | NaN */ dynamic originZ = 0]) =>
js_util.callMethod(this, 'scaleSelf',
[scaleX, scaleY, scaleZ, originX, originY, originZ]);
DOMMatrix scale3dSelf(
[/* double | NaN */ dynamic scale = 1,
/* double | NaN */ dynamic originX = 0,
/* double | NaN */ dynamic originY = 0,
/* double | NaN */ dynamic originZ = 0]) =>
js_util
.callMethod(this, 'scale3dSelf', [scale, originX, originY, originZ]);
DOMMatrix rotateSelf(
[/* double | NaN */ dynamic rotX = 0,
/* double | NaN */ dynamic rotY,
/* double | NaN */ dynamic rotZ]) =>
js_util.callMethod(this, 'rotateSelf', [rotX, rotY, rotZ]);
DOMMatrix rotateFromVectorSelf(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0]) =>
js_util.callMethod(this, 'rotateFromVectorSelf', [x, y]);
DOMMatrix rotateAxisAngleSelf(
[/* double | NaN */ dynamic x = 0,
/* double | NaN */ dynamic y = 0,
/* double | NaN */ dynamic z = 0,
/* double | NaN */ dynamic angle = 0]) =>
js_util.callMethod(this, 'rotateAxisAngleSelf', [x, y, z, angle]);
DOMMatrix skewXSelf([/* double | NaN */ dynamic sx = 0]) =>
js_util.callMethod(this, 'skewXSelf', [sx]);
DOMMatrix skewYSelf([/* double | NaN */ dynamic sy = 0]) =>
js_util.callMethod(this, 'skewYSelf', [sy]);
DOMMatrix invertSelf() => js_util.callMethod(this, 'invertSelf', []);
DOMMatrix setMatrixValue(String transformList) =>
js_util.callMethod(this, 'setMatrixValue', [transformList]);
}
@anonymous
@JS()
@staticInterop
class DOMMatrix2DInit {
external factory DOMMatrix2DInit(
{/* double | NaN */ dynamic a,
/* double | NaN */ dynamic b,
/* double | NaN */ dynamic c,
/* double | NaN */ dynamic d,
/* double | NaN */ dynamic e,
/* double | NaN */ dynamic f,
/* double | NaN */ dynamic m11,
/* double | NaN */ dynamic m12,
/* double | NaN */ dynamic m21,
/* double | NaN */ dynamic m22,
/* double | NaN */ dynamic m41,
/* double | NaN */ dynamic m42});
}
extension PropsDOMMatrix2DInit on DOMMatrix2DInit {
/* double | NaN */ dynamic get a => js_util.getProperty(this, 'a');
set a(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'a', newValue);
}
/* double | NaN */ dynamic get b => js_util.getProperty(this, 'b');
set b(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'b', newValue);
}
/* double | NaN */ dynamic get c => js_util.getProperty(this, 'c');
set c(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'c', newValue);
}
/* double | NaN */ dynamic get d => js_util.getProperty(this, 'd');
set d(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'd', newValue);
}
/* double | NaN */ dynamic get e => js_util.getProperty(this, 'e');
set e(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'e', newValue);
}
/* double | NaN */ dynamic get f => js_util.getProperty(this, 'f');
set f(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'f', newValue);
}
/* double | NaN */ dynamic get m11 => js_util.getProperty(this, 'm11');
set m11(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm11', newValue);
}
/* double | NaN */ dynamic get m12 => js_util.getProperty(this, 'm12');
set m12(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm12', newValue);
}
/* double | NaN */ dynamic get m21 => js_util.getProperty(this, 'm21');
set m21(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm21', newValue);
}
/* double | NaN */ dynamic get m22 => js_util.getProperty(this, 'm22');
set m22(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm22', newValue);
}
/* double | NaN */ dynamic get m41 => js_util.getProperty(this, 'm41');
set m41(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm41', newValue);
}
/* double | NaN */ dynamic get m42 => js_util.getProperty(this, 'm42');
set m42(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm42', newValue);
}
}
@anonymous
@JS()
@staticInterop
class DOMMatrixInit implements DOMMatrix2DInit {
external factory DOMMatrixInit._(
{/* double | NaN */ dynamic m13,
/* double | NaN */ dynamic m14,
/* double | NaN */ dynamic m23,
/* double | NaN */ dynamic m24,
/* double | NaN */ dynamic m31,
/* double | NaN */ dynamic m32,
/* double | NaN */ dynamic m33,
/* double | NaN */ dynamic m34,
/* double | NaN */ dynamic m43,
/* double | NaN */ dynamic m44,
bool? is2D});
factory DOMMatrixInit(
{/* double | NaN */ dynamic m13,
/* double | NaN */ dynamic m14,
/* double | NaN */ dynamic m23,
/* double | NaN */ dynamic m24,
/* double | NaN */ dynamic m31,
/* double | NaN */ dynamic m32,
/* double | NaN */ dynamic m33,
/* double | NaN */ dynamic m34,
/* double | NaN */ dynamic m43,
/* double | NaN */ dynamic m44,
bool? is2D}) =>
DOMMatrixInit._(
m13: m13 ?? 0,
m14: m14 ?? 0,
m23: m23 ?? 0,
m24: m24 ?? 0,
m31: m31 ?? 0,
m32: m32 ?? 0,
m33: m33 ?? 1,
m34: m34 ?? 0,
m43: m43 ?? 0,
m44: m44 ?? 1,
is2D: is2D ?? undefined);
}
extension PropsDOMMatrixInit on DOMMatrixInit {
/* double | NaN */ dynamic get m13 => js_util.getProperty(this, 'm13');
set m13(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm13', newValue);
}
/* double | NaN */ dynamic get m14 => js_util.getProperty(this, 'm14');
set m14(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm14', newValue);
}
/* double | NaN */ dynamic get m23 => js_util.getProperty(this, 'm23');
set m23(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm23', newValue);
}
/* double | NaN */ dynamic get m24 => js_util.getProperty(this, 'm24');
set m24(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm24', newValue);
}
/* double | NaN */ dynamic get m31 => js_util.getProperty(this, 'm31');
set m31(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm31', newValue);
}
/* double | NaN */ dynamic get m32 => js_util.getProperty(this, 'm32');
set m32(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm32', newValue);
}
/* double | NaN */ dynamic get m33 => js_util.getProperty(this, 'm33');
set m33(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm33', newValue);
}
/* double | NaN */ dynamic get m34 => js_util.getProperty(this, 'm34');
set m34(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm34', newValue);
}
/* double | NaN */ dynamic get m43 => js_util.getProperty(this, 'm43');
set m43(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm43', newValue);
}
/* double | NaN */ dynamic get m44 => js_util.getProperty(this, 'm44');
set m44(/* double | NaN */ dynamic newValue) {
js_util.setProperty(this, 'm44', newValue);
}
bool get is2D => js_util.getProperty(this, 'is2D');
set is2D(bool newValue) {
js_util.setProperty(this, 'is2D', newValue);
}
} |
//
// EditorStatusView.swift
// MarkEditMac
//
// Created by cyan on 1/16/23.
//
import AppKit
import AppKitControls
import MarkEditKit
/**
To indicate the current line, column and length of selection.
*/
final class EditorStatusView: NSView, BackgroundTheming {
private let button = TitleOnlyButton(fontSize: 11)
init(handler: @escaping () -> Void) {
super.init(frame: .zero)
self.toolTip = Localized.Document.gotoLineLabel
button.addAction(handler)
addSubview(button)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
button.frame = bounds
}
override func updateLayer() {
layer?.borderWidth = 1
layer?.cornerRadius = 3
layer?.cornerCurve = .continuous
layer?.borderColor = NSColor.plainButtonBorder.cgColor
}
func updateLineColumn(_ info: LineColumnInfo) {
let title = {
// Don't localize the labels
let lineColumn = "Ln \(info.lineNumber), Col \(info.columnText.count + 1)"
if info.selectionText.isEmpty {
return lineColumn
} else {
return "\(lineColumn) (\(info.selectionText.count))"
}
}()
let label = button.labelView
label.stringValue = title
label.sizeToFit()
self.frame = label.bounds.insetBy(dx: -4, dy: -2)
self.needsLayout = true
}
}
// MARK: - Accessibility
extension EditorStatusView {
override func isAccessibilityElement() -> Bool {
true
}
override func accessibilityRole() -> NSAccessibility.Role? {
.button
}
override func accessibilityLabel() -> String? {
button.labelView.stringValue
}
override func accessibilityPerformPress() -> Bool {
button.performClick(nil)
return true
}
} |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strjoin.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fmoreira <fmoreira@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/17 13:28:59 by fmoreira #+# #+# */
/* Updated: 2021/06/17 14:39:08 by fmoreira ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strjoin(char const *s1, char const *s2)
{
size_t i;
size_t j;
char *ns;
if (!s1 || !s2)
return (0);
ns = ft_calloc(ft_strlen(s1) + ft_strlen(s2) + 1, 1);
if (ns)
{
i = 0;
j = 0;
while (s1[i])
{
ns[i] = s1[i];
i++;
}
while (s2[j])
{
ns[i + j] = s2[j];
j++;
}
}
return (ns);
} |
<!doctype html>
<!--
Mozilla AI Guide |
We need your help to make OSS AI best-in-class!
Reach out to ai-guide@mozilla.com to contribute!
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<html lang="en" data-theme="moz_ai_guide_base">
<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>Mozilla AI Guide</title>
<meta name="description" content="Mozilla AI Guide" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Mozilla" />
<meta property="og:image" content="/img/mozilla-256.jpg" />
<meta property="og:title" content="Mozilla AI Guide" />
<meta property="og:description" content="Mozilla AI Guide" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@mozilla" />
<meta name="twitter:domain" content="future.mozilla.org" />
<link rel="stylesheet" href="/css/ai.e9ce9d34.css" />
<script
type="text/javascript"
src="/scripts/dark_mode.ce5d9712.js"
></script>
</head>
<body>
<div class="drawer lg:drawer-open">
<input id="my-drawer-2" type="checkbox" class="drawer-toggle" />
<!-- <div class="drawer-content flex flex-col items-center justify-center relative"> -->
<div class="drawer-content">
<div id="mobile_banner">
<label id="hamburger-btn" class="" for="my-drawer-2">
<svg
viewBox="0 0 100 80"
width="20"
height="20"
fill="currentColor"
>
<rect width="100" height="10" rx="8"></rect>
<rect y="30" width="80" height="10" rx="8"></rect>
<rect y="60" width="60" height="10" rx="8"></rect>
</svg>
</label>
<div id="header-bg">
<div id="header-content">
<a href="/ai/home">
<h1 id="header-title">AI Guide</h1>
</a>
</div>
</div>
</div>
<main id="content" class="">
<h2 id="ai-basics" tabindex="-1">AI Basics</h2>
<h3 id="what-is-ai-in-2023" tabindex="-1">What is AI in 2023?</h3>
<p>
Artificial intelligence (AI), machine learning (ML), large language
models (LLMs) and related technologies and techniques have crossed
the chasm from science fiction and niche research domains into
widespread awareness and widely adopted products, services, and
systems in 2023.
</p>
<p>
Although the history of AI research reaches back to the 1950s, the
current widespread awareness of AI can be traced to a recent set of
products and services using generative AI such as ChatGPT, Stable
Diffusion, and the like. In particular, OpenAI’s ChatGPT captured
the imagination of many by removing many technical barriers to
interacting with AI through “natural language” text conversations.
As such, ChatGPT allowed individuals to see the power, promise, and
pitfalls of such systems, and many heralded the moment as a new
epoch in the history of computing.
</p>
<p>
The rapid popularity of ChatGPT and other systems meant new
attention and investment in the domain. Almost overnight, new
applications and companies emerged that sought to make use of these
technologies in new ways and new domains. As a result, a myriad of
industries are finding new ways to use this technology for better
decision-making, automation, and innovation.
</p>
<p>
Alongside this expansion in interest and development is the need for
individuals in a variety of roles to quickly ramp up their
understanding of AI. However, with the increasing complexity of
these models, the substantial amount of new things to learn and the
extensive list of new libraries being added every single day,
onboarding into the state-of-the-art AI world has become challenging
for new engineers. While resources exist, many of these resources
(and increasingly so) depend on proprietary technologies. Moreover,
the state of knowledge is rapidly changing, and existing resources
are quickly out-of-date.
</p>
<h3 id="why-are-people-excited-about-llms" tabindex="-1">
Why are people excited about LLMs?
</h3>
<p>
Large Language Models (LLMs) are AI models that use deep learning
techniques to process and understand natural language text. These
models have millions or even billions of parameters that allow them
to generate human-like language output, making them ideal for tasks
such as language translation, natural-sounding chatbots, document
and code generation, and more. LLMs have been trained on massive
amounts of data, allowing them to identify patterns in language that
were previously difficult for computers to comprehend. This has led
to breakthroughs in natural language processing, generated output
and improved communication between humans and machines.
</p>
<h3 id="why-are-people-concerned-about-llms" tabindex="-1">
Why are people concerned about LLMs?
</h3>
<p>
LLMs are currently used to power chatbots and a wide variety of
content tools that can generate text, images, video, and even code.
But the very traits that make LLMs so powerful and useful also
present important questions that technologists need to consider when
developing and deploying them.
</p>
<p>
By mimicking human language and creativity, LLMs have the potential
to transform or even automate certain tasks or jobs. The mass
harvesting of data to train these systems presents largely
unresolved challenges to the principles of copyright, fair use, and
fair compensation. The tendency of users to view LLM-powered tools
as “officious oracles” can lead humans to make flawed or harmful
decisions based on the biases and misinformation these systems can
produce.
</p>
<p>
At Mozilla, we believe that developers should take these risks
seriously and cultivate both an understanding and awareness of how
their chosen AI technologies behave and impact the world. By their
very nature, open source LLMs offer a greater chance to achieve
those goals.
</p>
<h3 id="what-exactly-is-an-llm" tabindex="-1">
What exactly is an LLM?
</h3>
<p>
At its heart, a Transformer-based Large Language Model (LLM) is
essentially a computer program designed to generate text that
resembles human-written content. It leverages machine learning
techniques, specifically a type of neural network called a
Transformer. At a high-level, a Transformer encodes linguistic
patterns in the form of statistical relationships between words, and
then uses those patterns to generate text. Transformers encode these
semantic patterns by ingesting examples of existing text. Now let’s
dig a little deeper.
</p>
<p><strong>Here’s how it works:</strong></p>
<div class="whitespace-nowrap overflow-x-scroll flex py-6">
<div
id="item1"
class="card card-compact bg-neutral w-72 shrink-0 grow-0 ml-6 first:ml-0"
>
<figure class="card-figure !mt-0 !mb-0">
<img
src="/img/ai/carousels/how-llm-works/tokenization.png"
alt="Tokenization Visualization"
/>
</figure>
<div class="card-body text-neutral-content whitespace-normal">
<div class="font-semibold mb-0">Tokenization</div>
<p>
The LLM starts by breaking down the input text, or
'prompt', into smaller pieces known as tokens. These
could be as small as one character or as large as one word
</p>
</div>
</div>
</div>
<div class="whitespace-nowrap overflow-x-scroll flex py-6">
<div
id="item1"
class="card card-compact bg-neutral w-72 shrink-0 grow-0 ml-6 first:ml-0"
>
<figure class="card-figure !mt-0 !mb-0">
<img
src="/img/ai/carousels/how-llm-works/tokenization.png"
alt="Tokenization Visualization"
/>
</figure>
<div class="card-body text-neutral-content whitespace-normal">
<div class="font-semibold mb-0">Tokenization</div>
<p>
The LLM starts by breaking down the input text, or
'prompt', into smaller pieces known as tokens.
</p>
</div>
</div>
<div
id="item2"
class="card card-compact bg-neutral w-72 shrink-0 grow-0 ml-6 first:ml-0"
>
<figure class="card-figure !mt-0 !mb-0">
<img
src="/img/ai/carousels/how-llm-works/embedding.png"
alt="Embedding Visualization"
/>
</figure>
<div class="card-body text-neutral-content whitespace-normal">
<div class="font-semibold mb-0">Embedding</div>
<p>
Next, each token is converted into a numerical representation
through a process called embedding.
</p>
</div>
</div>
<div
id="item3"
class="card card-compact bg-neutral w-72 shrink-0 grow-0 ml-6 first:ml-0"
>
<figure class="card-figure !mt-0 !mb-0">
<img
src="/img/ai/carousels/how-llm-works/self-attention.png"
alt="Self-attention Visualization"
/>
</figure>
<div class="card-body text-neutral-content whitespace-normal">
<div class="font-semibold mb-0">Self-attention</div>
<p>
The model then adds additional information to these vectors to
account for the order of words in the input. Self attention
mechanisms allow the model to create context-aware
representations of each word.
</p>
</div>
</div>
<div
id="item4"
class="card card-compact bg-neutral w-72 shrink-0 grow-0 ml-6 first:ml-0"
>
<figure class="card-figure !mt-0 !mb-0">
<img
src="/img/ai/carousels/how-llm-works/decoding.png"
alt="Decoding Visualization"
/>
</figure>
<div class="card-body text-neutral-content whitespace-normal">
<div class="font-semibold mb-0">Decoding</div>
<p>
The LLM Decoder will take the output and use it to predict the
next token in the sequence.
</p>
</div>
</div>
<div
id="item5"
class="card card-compact bg-neutral w-72 shrink-0 grow-0 ml-6 first:ml-0"
>
<figure class="card-figure !mt-0 !mb-0">
<img
src="/img/ai/carousels/how-llm-works/output.png"
alt="Output Visualization"
/>
</figure>
<div class="card-body text-neutral-content whitespace-normal">
<div class="font-semibold mb-0">Output</div>
<p>Finally, the model generates a response.</p>
</div>
</div>
</div>
<p>
The LLM starts by breaking down the input text, or “prompt,” into
smaller pieces known as tokens. These could be as small as one
character or as large as one word.
</p>
<p>
Next, each token is converted into a numerical representation
through a process called embedding. This transformation turns each
word into a high-dimensional vector in order to capture the semantic
relationship of words.
</p>
<p>
The model then adds additional information to these vectors to
account for the order of words in the input. This is crucial because
the meaning of a sentence can change dramatically based on word
order.
</p>
<p>
Now comes the real magic of the Transformer architecture:
self-attention mechanisms. These allow the model to weigh the
importance of different words when predicting the next word in the
sentence. This way, the model can create context-aware
representations of each word.
</p>
<p>
If the LLM includes a decoder component, it will take the output
from the encoder and use it, along with the previously generated
tokens, to predict the next token in the sequence.
</p>
<p>
Finally, the model generates a response, one token at a time, until
it reaches a certain length or produces a termination token.
</p>
<p>
All these steps involve complex mathematical operations and
transformations. But fundamentally, what the model is doing is
learning patterns in the data it was trained on, and using those
patterns to generate new text that fits within the same patterns.
</p>
<p>
So, in essence, a Transformer-based LLM is a cleverly designed
pattern recognition system that uses learned associations between
words to generate human-like text. It’s like having a scribe who has
read everything ever written and can produce text on any topic in a
style that mirrors the content it was trained on.
</p>
<h3 id="what-are-the-pros-and-cons-of-using-an-llm" tabindex="-1">
What are the pros & cons of using an LLM?
</h3>
<p>
Although LLMs have made it possible for computers to process human
language ways that have been previously difficult, if not
impossible, they are not without trade-offs:
</p>
<ul>
<li>
Pros
<ul>
<li>
<strong>Improved Accuracy</strong>: LLMs are trained on large
amounts of human-readable data (e.g. written text, code, and
audio) and rely on state-of-the-art techniques to determine
patterns within those data. The size and pattern recognition
techniques (e.g. Transformers) improve the accuracy of
predictions over previous systems.
</li>
<li>
<strong>Efficiency</strong>: With LLMs, tasks such as language
translation and chatbots can be automated, freeing up time for
humans to focus on more complex tasks.
</li>
<li>
<strong>Language Generation</strong>: LLMs can generate
human-like language output, making them applicable for tasks
such as content creation and copywriting.
</li>
</ul>
</li>
<li>
Cons
<ul>
<li>
<strong>Computational Power Requirements</strong>: Training an
LLM requires significant computational power, which can be
expensive and time-consuming.
</li>
<li>
<strong>Data Bias</strong>: Because LLMs are trained on
massive amounts of data, they can perpetuate biases that exist
in the training data.
</li>
<li>
<strong>Lack of Transparency</strong>: The inner workings of
an LLM can be difficult to understand, which makes it
challenging to identify how it arrived at a particular
decision or prediction.
</li>
<li>
<strong>LLM hallucinations</strong>: One of the most
interesting and controversial aspects of LLMs is their ability
to generate realistic language output that they have never
been trained on. This phenomenon is known as LLM
hallucination, and it has raised concerns about the potential
misuse of these models.
</li>
</ul>
</li>
</ul>
<h3 id="what-new-behaviors-do-llms-unlock" tabindex="-1">
What new behaviors do LLMs unlock?
</h3>
<p>
Large Language Models (LLMs) have unlocked a plethora of new
behaviors that were previously impossible for computers to achieve.
For example, LLMs can now generate highly convincing human-like
text, which has led to the development of more advanced chatbots and
virtual assistants. Additionally, LLMs have revolutionized the field
of natural language processing by enabling machines to understand
and interpret complex human language in ways that were previously
impossible. This has opened up new possibilities for automated
language translation, content creation, code generation, and even
sentiment analysis. With continued advancements in LLM technology,
we can expect to see even more exciting developments in the near
future.
</p>
<h3
id="what-are-the-components-of-transformer-based-pre-trained-llms"
tabindex="-1"
>
What are the components of Transformer-based, pre-trained LLMs?
</h3>
<ul>
<li>
<strong>Tokenizer</strong>: This is the first step in processing
text data. The tokenizer converts raw text into chunks known as
‘tokens’. These tokens can represent words, subwords, or even
characters depending on the granularity of the tokenization
process. For instance, a word-level tokenizer will convert the
sentence “I love coding” into ‘I’, ‘love’, ‘coding’.
</li>
<li>
<strong>Embedding Layer</strong>: Once the text is tokenized,
these tokens are transformed into dense vectors of fixed size in a
high-dimensional space through the embedding layer. These
embeddings capture semantic information about the words. For
example, in this space, ‘king’ and ‘queen’ would be closer to each
other than ‘king’ and ‘apple’.
</li>
<li>
<strong>Encoder</strong>: The encoder processes the input sequence
into a context-dependent representation that captures the meaning
of the text. It uses a Transformer architecture which allows it to
pay varying levels of ‘attention’ to different parts of the input
sequence at each step of the encoding process. The output of the
encoder is a series of hidden states.
</li>
<li>
<strong>Decoder</strong>: The decoder generates output text word
by word based on the hidden states from the encoder. In some
models like GPT-3, the decoder is essentially the entire model. It
also uses a Transformer architecture and attention mechanism to
focus on the relevant parts of the input.
</li>
<li>
<strong>Attention Mechanism</strong>: This is a key part of both
the encoder and decoder in a Transformer. It helps the model
dynamically focus on different parts of the input sequence as it
processes the data. It computes a weighted sum of input values (or
‘query’) based on their relevance (or ‘attention scores’) to the
current ‘key’ value.
</li>
<li>
<strong>Pre-training and Fine-tuning</strong>: LLMs often start
with a pre-trained language model, which have been trained on vast
amounts of text data. These models are then fine-tuned for
specific tasks. During fine-tuning, the model learns task-specific
patterns on top of the general language understanding it gained
during pre-training.
</li>
</ul>
<h3
id="when-i-send-a-transformer-based-llm-a-prompt-what-happens-internally-in-more-technical-terms"
tabindex="-1"
>
When I send a Transformer-based LLM a “prompt”, what happens
internally in more technical terms?
</h3>
<ol>
<li>
<strong>Tokenization</strong>: The prompt is first converted into
tokens (smaller units of text) using a process called
tokenization. This could be as small as words, or even subwords in
some cases.
</li>
<li>
<strong>Embedding</strong>: Each token is then mapped to a
high-dimensional vector using a pre-trained embedding layer. This
representation, known as a word vector, captures semantic
information about the token in its dimensions.
</li>
<li>
<strong>Positional Encoding</strong>: Since transformer models do
not inherently understand the order of tokens, positional encoding
is added to give sequence information to the model. This involves
adding a vector to the embedding which represents the position of
each token within the sequence.
</li>
<li>
<strong>Encoder</strong>: The encoded input is passed through
several layers (the exact number depends on the model
architecture). Each layer consists of self-attention mechanisms
and feed-forward neural networks. These layers allow the model to
consider all parts of the input when generating each part of the
output.
</li>
<li>
<strong>Decoder (if applicable)</strong>: Some transformer models,
like BERT, are ‘encoder-only’, while others, like T5, also include
a decoder component. The decoder takes the output of the encoder
and generates the final output text. It also uses the attention
mechanism, but in a slightly different way that allows it to
consider previously generated output tokens.
</li>
<li>
<strong>Output Generation</strong>: Finally, the model generates
the output text. This is done one token at a time, with the model
deciding on the most likely next token based on the current state.
The process continues until the model generates a termination
token or reaches a preset maximum length.
</li>
</ol>
<p>
Each step in this process involves complex mathematical operations
and transformations. But at a high-level, the goal is to convert
text into a form that the model can understand, let the model
process and generate a response, and then convert that response back
into human-readable text.
</p>
<div class="text-right">
<a class="button-next-page" href="/ai/content/llms-101/"
>LLMs 101 →</a
>
</div>
</main>
<footer id="footer" class="mzp-c-footer">
<div class="mzp-l-content">
<nav class="mzp-c-footer-secondary">
<div class="container">
<ul class="mzp-c-footer-terms">
<li>
<a
href="https://www.mozilla.org/privacy/websites/"
data-link-type="footer"
data-link-name="Privacy"
>Website Privacy Notice</a
>
</li>
<li>
<a
href="https://www.mozilla.org/privacy/websites/#user-choices"
data-link-type="footer"
data-link-name="Cookies"
>Cookies</a
>
</li>
<li>
<a
href="https://www.mozilla.org/about/legal/"
data-link-type="footer"
data-link-name="Legal"
>Legal</a
>
</li>
<li>
<a
href="https://www.mozilla.org/about/governance/policies/participation/"
data-link-type="footer"
data-link-name="Community Participation Guidelines"
>Community Participation Guidelines</a
>
</li>
<li>
<a
href="https://www.mozilla.org/about/this-site/"
data-link-type="footer"
data-link-name="About this site"
>About this site</a
>
</li>
</ul>
</div>
<div class="container">
<div class="mzp-c-footer-license leading-6" rel="license">
Visit
<a href="https://www.mozilla.org/" class="underline"
>Mozilla Corporation’s</a
>
not-for-profit parent, the
<a
href="https://foundation.mozilla.org/?utm_source=www.mozilla.org&utm_medium=referral&utm_campaign=footer"
class="underline"
rel="external noopener"
>Mozilla Foundation</a
>. Portions of this content are ©1998–2023 by individual
mozilla.org contributors. Content available under a
<a
rel="license"
href="https://www.mozilla.org/foundation/licensing/website-content/"
>Creative Commons license</a
>.
</div>
</div>
</nav>
</div>
</footer>
</div>
<div class="drawer-side">
<label for="my-drawer-2" class="drawer-overlay"></label>
<!-- <button id="sidebar-close-btn" class="drawer-button">X</button> -->
<ul class="menu">
<li>
<a href="/ai/home"
><img
alt="Mozilla logo"
class="dark:[filter:invert(1)]"
id="sidebar-logo"
src="/img/mozilla-only.c3f76b0f.png"
/></a>
</li>
<li>
<details closed="">
<summary>
<a href="/ai/content/introduction/">Introduction</a>
</summary>
<ul class="sub_menu">
<li>
<a href="/ai/content/introduction/#why-this-guide"
>Why this guide?</a
>
</li>
<li>
<a href="/ai/content/introduction/#why-mozilla"
>Why Mozilla?</a
>
</li>
</ul>
</details>
</li>
<li>
<details closed="">
<summary>
<a href="/ai/content/ai-basics/">AI Basics</a>
</summary>
<ul class="sub_menu">
<li>
<a href="/ai/content/ai-basics/#what-is-ai-in-2023"
>What is AI in 2023?</a
>
</li>
<li>
<a
href="/ai/content/ai-basics/#why-are-people-excited-about-llms"
>Why are people excited about LLMs?</a
>
</li>
<li>
<a
href="/ai/content/ai-basics/#why-are-people-concerned-about-llms"
>Why are people concerned about LLMs?</a
>
</li>
<li>
<a href="/ai/content/ai-basics/#what-exactly-is-an-llm"
>What exactly is an LLM?</a
>
</li>
<li>
<a
href="/ai/content/ai-basics/#what-are-the-pros-cons-of-using-an-llm"
>What are the pros & cons of using an LLM?</a
>
</li>
<li>
<a
href="/ai/content/ai-basics/#what-new-behaviors-do-llms-unlock"
>What new behaviors do LLMs unlock?</a
>
</li>
<li>
<a
href="/ai/content/ai-basics/#what-are-the-components-of-transformer-based-pre-trained-llms"
>What are the components of Transformer-based, pre-trained
LLMs?</a
>
</li>
<li>
<a
href="/ai/content/ai-basics/#when-i-send-a-transformer-based-llm-a-prompt-what-happens-internally-in-more-technical-terms"
>When I send a Transformer-based LLM a “prompt”, what
happens internally in more technical terms?</a
>
</li>
</ul>
</details>
</li>
<li>
<details closed="">
<summary>
<a href="/ai/content/llms-101/">LLMs 101</a>
</summary>
<ul class="sub_menu">
<li>
<a
href="/ai/content/llms-101/#what-do-these-numbers-mean-in-the-names-of-models"
>What do these numbers mean in the names of models?</a
>
</li>
<li>
<a href="/ai/content/llms-101/#what-is-a-parameter"
>What is a parameter?</a
>
</li>
<li>
<a href="/ai/content/llms-101/#what-does-training-an-llm-mean"
>What does “training” an LLM mean?</a
>
</li>
<li>
<a
href="/ai/content/llms-101/#how-does-a-typical-training-run-work"
>How does a typical training run work?</a
>
</li>
<li>
<a href="/ai/content/llms-101/#what-is-backpropagation"
>What is backpropagation?</a
>
</li>
<li>
<a
href="/ai/content/llms-101/#what-does-fine-tuning-an-llm-mean"
>What does “fine-tuning” an LLM mean?</a
>
</li>
<li>
<a href="/ai/content/llms-101/#human-in-the-loop-approach"
>“Human in the loop” approach</a
>
</li>
<li>
<a href="/ai/content/llms-101/#what-does-inference-mean"
>What does "inference" mean?</a
>
</li>
<li>
<a
href="/ai/content/llms-101/#is-inference-computationally-expensive"
>Is inference computationally expensive?</a
>
</li>
<li>
<a href="/ai/content/llms-101/#what-is-a-vector"
>What is a vector?</a
>
</li>
<li>
<a href="/ai/content/llms-101/#what-is-beam-search"
>What is beam search?</a
>
</li>
<li>
<a href="/ai/content/llms-101/#what-is-sampling"
>What is sampling?</a
>
</li>
<li>
<a href="/ai/content/llms-101/#what-is-temperature"
>What is temperature?</a
>
</li>
</ul>
</details>
</li>
<li class="upcoming">
<a disabled="">
<div class="badge">Up Next</div>
Choosing ML models</a
>
</li>
<li class="upcoming">
<a disabled="">
<div class="badge">Up Next</div>
Fine-tuning</a
>
</li>
<li class="upcoming">
<a disabled="">
<div class="badge">Up Next</div>
LLMs from scratch</a
>
</li>
<li class="upcoming">
<a disabled="">
<div class="badge">Up Next</div>
Images, Audio & Video</a
>
</li>
</ul>
</div>
<script type="text/javascript">
const sidebarDrawer = document.getElementById("my-drawer-2");
document.querySelectorAll("ul.menu li a").forEach(function (item) {
item.addEventListener("click", function () {
sidebarDrawer.checked = false;
return true;
});
});
</script>
</div>
</body>
</html> |
<template>
<div>
<main id="main">
<section id="breadcrumbs" class="breadcrumbs">
<div class="container">
<ol>
<li><router-link :to="{name: 'home'}" active-class="active">Home</router-link></li>
<li>Edit Post</li>
</ol>
<h2>Edit Post ({{ this.$route.params.slug }})</h2>
</div>
</section>
<section class="blog">
<div class="container" data-aos="fade-up">
<div class="row">
<div class="col-lg-12 entries">
<div class="blog-comments">
<div class="reply-form">
<h4>Edit post</h4>
<form v-on:submit.prevent="submitForm" method="post">
<div class="row">
<div class="col form-group">
<input v-model="post.title" @input="changeSlug" type="text" class="form-control" placeholder="Post Title*">
<label v-if="errors.title">{{ errors.title.toString() }}</label>
</div>
</div>
<div class="row">
<div class="col form-group">
<textarea class="form-control" v-model="post.content"></textarea>
<label v-if="errors.content">{{ errors.content.toString() }}</label>
</div>
</div>
<div class="row">
<div class="col form-group">
<input v-model="post.tags" type="text" class="form-control" placeholder="Post Tags">
<label v-if="errors.tags">{{ errors.tags.toString() }}</label>
</div>
</div>
<div class="row">
<div class="col form-group">
<select v-model="post.category_id">
<option v-for="category in categories" :key="category.id" :value="category.id">{{ category.name }}</option>
</select>
<label v-if="errors.category_id">{{ errors.category_id.toString() }}</label>
</div>
</div>
<div class="row">
<div class="col form-group">
<input v-model="post.slug" type="text" class="form-control" placeholder="Slug*">
<label v-if="errors.slug">{{ errors.slug.toString() }}</label>
</div>
</div>
<div class="row">
<div class="col form-group">
<input v-model="post.meta_title" type="text" class="form-control" placeholder="Meta Title">
<label v-if="errors.meta_title">{{ errors.meta_title.toString() }}</label>
</div>
</div>
<div class="row">
<div class="col form-group">
<input v-model="post.meta_description" type="text" class="form-control" placeholder="Meta Description">
<label v-if="errors.meta_description">{{ errors.meta_description.toString() }}</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div><!-- End blog comments -->
</div><!-- End blog entries list -->
</div>
</div>
</section>
</main>
</div>
</template>
<script>
import axios from 'axios'
import router from '../../../router.js'
export default {
name: "Update",
data() {
return {
post: {
title: '',
content: '',
tags: '',
category_id: '',
slug: '',
meta_title: '',
meta_description: '',
},
categories: {},
errors: {}
}
},
methods: {
async submitForm() {
axios.create({
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + this.$store.getters['0/user'].token
},
}).patch(this.appConfig.BASE_URL +'/api/post/' + this.$route.params.id, this.post).then(({data}) => {
this.$toaster.success(data.message)
router.push({name: 'admin.posts'})
}).catch((error) => {
if(error.response.status === 422)
this.errors = error.response.data.errors
this.$toaster.error(error.response.statusText)
})
},
async loadCategories() {
await axios.get(this.appConfig.BASE_URL +'/api/category').then(({data}) => {
this.categories = data.data;
}).catch((error) => {
this.$toaster.error(error.response.statusText)
})
},
changeSlug() {
this.post.slug = this.post.name.toLowerCase().split(' ').join('-')
}
},
mounted() {
axios.get(this.appConfig.BASE_URL +'/api/post/' + this.$route.params.slug).then(({data}) => {
this.post = data
}).catch((error) => {
this.$toaster.error(error.response.statusText)
router.push({name: 'admin.posts'})
})
this.loadCategories()
},
}
</script> |
<?php
declare(strict_types=1);
namespace Impexta\Client\Presentation\Controller\CRM;
use Impexta\Client\Domain\Factory\ClientFactory;
use Impexta\Client\Infrastructure\Repository\ClientRepository;
use Impexta\Client\Infrastructure\Service\UploadedFileService;
use Impexta\Client\Presentation\Form\Model\ClientModel;
use Impexta\Client\Presentation\Form\Type\ClientType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
final class CreateClientController extends AbstractController
{
private ClientRepository $clientRepository;
private ClientFactory $clientFactory;
private UploadedFileService $uploadedFileService;
public function __construct(
ClientRepository $clientRepository,
ClientFactory $clientFactory,
UploadedFileService $uploadedFileService
) {
$this->clientRepository = $clientRepository;
$this->clientFactory = $clientFactory;
$this->uploadedFileService = $uploadedFileService;
}
/**
* @Route("zakaznik/vytvorit", name="client_crm_client_create")
*/
public function __invoke(Request $request): Response
{
$clientModel = ClientModel::createEmpty();
$form = $this->createForm(ClientType::class, $clientModel);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$client = $this->clientFactory->createClient($clientModel);
if ($clientModel->logo) {
$this->uploadedFileService->uploadLogo($form, $client);
}
$this->clientRepository->save($client);
$this->addFlash('success', 'Zákazník byl vytvořen.');
return $this->redirectToRoute('client_crm_client_detail', [
'id' => $client->getId(),
]);
}
return $this->render('@client/CRM/client_create.html.twig', [
'form' => $form->createView(),
'smartform_instances' => [ClientType::BILLING_ADDRESS, ClientType::SHIPPING_ADDRESS],
]);
}
} |
const User = require('../models/User')
const Note = require('../models/Note')
const asyncHandler = require('express-async-handler')
const bcrypt = require('bcrypt')
//@desc Get all users
//@route GET /users
//@access Private
const getAllUsers = asyncHandler(async (req, res) => {
const users = await User.find().select('-password').lean()
if (!users?.length) {
return res.status(400).json({message: 'No users found'})
}
res.json(users)
})
//@desc Create new user
//@route POST /users
//@access Private
const createNewUser = asyncHandler(async (req, res) => {
const {username, password, roles} = req.body
//Confirm data
if (!username || !password || !Array.isArray(roles) || !roles.length) {
res.status(400).json({ message: "All fields are required"})
}
//Check for duplicate
const duplicate = await User.findOne({username}).lean().exec()
if (duplicate) {
return res.status(409).json({message: 'Duplicate username'})
}
//Hash the password
const hashedPwd =await bcrypt.hash(password, 10) // salt rounds
const userObject = {username, "password": hashedPwd, roles}
//Create and store new user
const user = await User.create(userObject)
if (user) {
res.status(201).json({message: `New user ${username} created`})
} else {
res.status(400).json({message: 'Invalid user data received'})
}
})
//@desc Update user
//@route PATCH /users
//@access Private
const updateUser = asyncHandler(async (req, res) => {
const {id, username, roles, active, password} = req.body
//Confirm data
if(!id || !username || !Array.isArray(roles) || !roles.length || typeof active !== 'boolean') {
return res.status(400).json({message: 'All fields are required'})
}
const user = await User.findById(id).exec()
if (!user) {
return res.status(400).json({message: 'user not found'})
}
//Check for duplicate
const duplicate = await User.findOne({username}).lean().exec()
//Allow updates to the original user
if (duplicate && duplicate?._id.toString() !== id) {
return res.status(409).json({message: 'Duplicate username'})
}
user.username = username
user.roles = roles
user.active = active
if (password) {
//hash password
user.password = await bcrypt.hash(password, 10)
}
const updatedUser = await user.save()
res.json({message: `${updatedUser.username} updated`})
})
//@desc Delete a user
//@route DELETE /users
//@access Private
const deleteUser = asyncHandler(async (req, res) => {
const {id} = req.body
if (!id) {
return res.status(400).json({message: 'User ID reqiured'})
}
const note = await Note.findOne({user: id}).lean().exec()
if (note) {
return res.status(400).json({message: 'User has assigned notes'})
}
const user = await User.findById(id).exec()
if (!user) {
return res.status(400).json({message: 'User not found'})
}
const result = await user.deleteOne()
const reply = `Username ${result.username} with ID ${result.id} deleted`
res.json(reply)
})
module.exports = {
getAllUsers,
createNewUser,
updateUser,
deleteUser
} |
import React from "react"
import { useDispatch } from "react-redux";
import { removeSingleFavoriteProduct } from "../store/favoriteSlice";
import { Link } from "react-router-dom";
import "../styles/favorite.scss";
const SingleFavoriteProduct = ( { product } ) => {
const dispatch = useDispatch( )
return(
<div className="favorite-product-container">
<span className="close" onClick={ ( ) => dispatch( removeSingleFavoriteProduct( product._id ) ) }>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
<path strokeLinecap="round" strokeLinejoin="round" d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</span>
<div className="product-image">
<img src={ product.img } alt="" />
</div>
<div className="product-info wishlist-product">
<div className="product-left">
<h3 className="product-title">{ product.title }</h3>
<p className="product-price">$ { product.price }</p>
<Link to={`/product/${ product._id }`} style={ { color: "black", marginTop: "1rem" } }>Go to product</Link>
</div>
<div className="product-filter">
<div className="product-color-filter">
{ product.color.map( color => (
<span style={{ backgroundColor: `${ color }` }} className="color" key={ color }></span>
))}
</div>
<div className="product-size-filter">
<span>Size</span>
<div className="product-size-filter-container" >
{ product.size.map( size => (
<span className="size" key={ size }>{ size }</span>
) ) }
</div>
</div>
</div>
</div>
</div>
)
}
export default SingleFavoriteProduct |
Use Case: LibMesh is a framework for numerical simulations using finite element methods. You can use it for solving partial differential equations on serial and parallel architectures. The input files are generally cpp files containing problem assumptions, boundary conditions and solver details.
Code details and examples:
Code:
```c++
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh.h"
#include "libmesh/linear_implicit_system.h"
#include "libmesh/equation_systems.h"
#include "libmesh/dof_map.h"
#include "libmesh/quadrature_gauss.h"
using namespace libMesh;
int main(int argc, char** argv){
// Initialize libmesh library
LibMeshInit init(argc, argv);
// Check if we're in 2D or 3D
const unsigned int dim = 2;
// Create Mesh object, square or cube
Mesh mesh(init.comm());
// Generate square or cube
if(dim == 2)
MeshTools::Generation::build_square(mesh, 32, 32, -1., 1., -1., 1., QUAD9);
else
MeshTools::Generation::build_cube(mesh, 16, 16, 16, -1., 1., -1., 1., -1., 1., HEX27);
// Create an equation systems object
EquationSystems equation_systems(mesh);
// Declaring system of type "BASIC"
LinearImplicitSystem& system = equation_systems.add_system<LinearImplicitSystem> ("Basic");
// Adding variable "u" to the system
system.add_variable("u", THIRD, L2_LAGRANGE);
// Initialize the system
system.init();
}
```
Command to run:
If the file is named main.cpp, compile with:
```
mpicxx main.cpp -o main -l libmesh
```
And run with:
```
mpirun -np 4 ./main
``` |
import React from "react";
import { useFormik } from "formik";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { addJobItem } from "../../../features/Job/JobSlice";
const AddJob = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
const initialValues = {
JOBPOSITIONID: "",
Technology: "",
NUMBER_OF_OPENINGS: "",
PUBLISHEDON: "",
APPLICATIONFROMDATE: "",
APPLICATIONEXPIRYDATE: "",
JOBPOSTINGSTATUS: "",
};
const { values, handleBlur, handleChange, handleSubmit, errors, touched } =
useFormik({
initialValues,
//validationSchema: Yupschema,
onSubmit: (values) => {
console.log(values);
dispatch(addJobItem(values));
navigate("/Job/JobPosting");
},
});
return (
<>
<form
action=""
onSubmit={handleSubmit}
className="flex py-5 px-1 w-full gap-4"
>
<div className="w-[60%] flex flex-col gap-4">
<div className="grid md:grid-cols-2 md:gap-6">
<div className="relative z-0 w-full mb-6 group">
<input
type="number"
name="JOBPOSITIONID"
className="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
placeholder=" "
value={values.JOBPOSITIONID}
onChange={handleChange}
onBlur={handleBlur}
required
/>
<label
htmlFor="floating_last_name"
className="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6"
>
JOBPOSITIONID
</label>
</div>
<div className="relative z-0 w-full mb-6 group">
<input
type="text"
name="Technology"
className="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
placeholder=" "
value={values.Technology}
onChange={handleChange}
onBlur={handleBlur}
required
/>
<label
htmlFor="floating_last_name"
className="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6"
>
Technology
</label>
</div>
</div>
<div className="grid md:grid-cols-2 md:gap-6">
<div className="relative z-0 w-full mb-6 group">
<input
type="number"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
name="NUMBER_OF_OPENINGS"
className="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
placeholder=" "
value={values.NUMBER_OF_OPENINGS}
onChange={handleChange}
onBlur={handleBlur}
required
/>
<label
htmlFor="floating_phone"
className="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6"
>
NUMBER OF OPENINGS
</label>
</div>
<div className="relative z-0 w-full mb-6 group">
<input
type="date"
name="PUBLISHEDON"
className="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
placeholder=" "
value={values.PUBLISHEDON}
onChange={handleChange}
onBlur={handleBlur}
required
/>
<label
htmlFor="floating_city"
className="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6"
>
PUBLISHEDON
</label>
</div>
</div>
<div className="grid md:grid-cols-2 md:gap-6">
<div className="relative z-0 w-full mb-6 group">
<input
type="date"
name="APPLICATIONFROMDATE"
id="floating_first_name"
className="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
placeholder=" "
value={values.APPLICATIONFROMDATE}
onChange={handleChange}
onBlur={handleBlur}
required
/>
<label
htmlFor="floating_first_name"
className="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6"
>
APPLICATIONFROMDATE
</label>
</div>
<div className="relative z-0 w-full mb-6 group">
<input
type="date"
name="APPLICATIONEXPIRYDATE"
className="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
placeholder=" "
value={values.APPLICATIONEXPIRYDATE}
onChange={handleChange}
onBlur={handleBlur}
required
/>
<label
htmlFor="floating_email"
className="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6"
>
APPLICATIONEXPIRYDATE
</label>
</div>
</div>
<div className="relative z-0 w-full mb-6 group">
<label
htmlFor="floating_repeat_password"
className="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-1 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6"
>
JOBPOSTINGSTATUS
</label>
<select
name="JOBPOSTINGSTATUS"
value={values.JOBPOSTINGSTATUS}
onChange={handleChange}
onBlur={handleBlur}
className="block w-full px-4 py-3 text-base rounded-lg text-gray-900 bg-transparentborder-0 border-b-2 border-gray-300 dark:border-gray-600"
>
<option value="IsActive">IsActive</option>
<option value="NonActive">NonActive</option>
</select>
</div>
<button
type="submit"
className="w-44 h-12 mt-5 bg-transparent hover:bg-blue-500 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded"
>
Submit
</button>
</div>
</form>
</>
);
};
export default AddJob; |
import type { MLElement } from './element.js';
import type { MLASTNode } from '@markuplint/ml-ast';
import type { PlainData, RuleConfigValue } from '@markuplint/ml-config';
import { MLNode } from './node.js';
export declare abstract class MLCharacterData<T extends RuleConfigValue, O extends PlainData = undefined, A extends MLASTNode = MLASTNode> extends MLNode<T, O, A> implements CharacterData {
/**
* @implements DOM API: `CharacterData`
* @see https://dom.spec.whatwg.org/#dom-characterdata-data
*/
get data(): string;
/**
* **IT THROWS AN ERROR WHEN CALLING THIS.**
*
* @unsupported
* @implements DOM API: `CharacterData`
* @see https://dom.spec.whatwg.org/#dom-characterdata-length
*/
get length(): number;
/**
* The element immediately following the specified one in its parent's children list.
*
* @readonly
* @implements DOM API: `CharacterData`
* @see https://dom.spec.whatwg.org/#ref-for-dom-nondocumenttypechildnode-nextelementsibling%E2%91%A1
*/
get nextElementSibling(): MLElement<T, O> | null;
get nodeValue(): string | null;
/**
* The element immediately prior the specified one in its parent's children list.
*
* @readonly
* @implements DOM API: `CharacterData`
* @see https://dom.spec.whatwg.org/#ref-for-dom-nondocumenttypechildnode-previouselementsibling%E2%91%A1
*/
get previousElementSibling(): MLElement<T, O> | null;
/**
* @implements DOM API: `CharacterData`
*/
after(...nodes: (string | MLElement<any, any>)[]): void;
appendData(data: string): void;
/**
* @implements DOM API: `CharacterData`
*/
before(...nodes: (string | MLElement<any, any>)[]): void;
deleteData(offset: number, count: number): void;
insertData(offset: number, data: string): void;
/**
* @implements DOM API: `CharacterData`
*/
remove(): void;
replaceData(offset: number, count: number, data: string): void;
/**
* @implements DOM API: `CharacterData`
*/
replaceWith(...nodes: (string | MLElement<any, any>)[]): void;
substringData(offset: number, count: number): string;
} |
import { useContext } from 'react'
import { cartContext } from '../../contexts/cart.context'
import { ReactComponent as ShoppingIcon} from '../../assets/shopping-cart.svg'
import './cart-icon.styles.scss'
const CartIcon = () => {
const { isCartOpen, setIsCartOpen, cartCount } = useContext(cartContext)
const toggleIsCartOpen = () => setIsCartOpen(!isCartOpen);
return (
<div className="cart-icon-container" onClick={toggleIsCartOpen}>
<ShoppingIcon className="shopping-icon"/>
{cartCount ?
(
<div className='count-container'>
<span className="item-count">{cartCount}</span>
</div>
)
: null
}
</div>
)
}
export default CartIcon; |
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { assert } from 'chai';
import * as sinon from 'sinon';
import {
AudioDeviceModule,
getAudioDeviceModule,
} from '../../calling/audioDeviceModule';
describe('audio device module', () => {
describe('getAudioDeviceModule', () => {
let sandbox: sinon.SinonSandbox;
beforeEach(() => {
sandbox = sinon.createSandbox();
});
afterEach(() => {
sandbox.restore();
});
it('returns ADM2 on Windows', () => {
sandbox.stub(process, 'platform').get(() => 'win32');
assert.strictEqual(getAudioDeviceModule(), AudioDeviceModule.WindowsAdm2);
});
it('returns the default module on macOS', () => {
sandbox.stub(process, 'platform').get(() => 'darwin');
assert.strictEqual(getAudioDeviceModule(), AudioDeviceModule.Default);
});
it('returns the default module on Linux', () => {
sandbox.stub(process, 'platform').get(() => 'linux');
assert.strictEqual(getAudioDeviceModule(), AudioDeviceModule.Default);
});
});
}); |
const ObjectId = require('mongoose').Types.ObjectId
const { Router } = require("express");
const {
getAllGyms,
postGyms,
saveGyms,
getGymById,
getGymByName
} = require("../../controlers/gyms");
const Gyms = require("../../models/Gyms");
const Users = require("../../models/User");
const Partner = require("../../models/Partner");
const router = Router();
// Para solicitar info de todos los gyms
router.get("/allgyms", async (req, res) => {
try {
const response = await getAllGyms();
res.status(200).send(response);
} catch (error) {
res.status(404).send({ error: error.message });
}
});
// router.get("/mygyms/:userId", async (req, res) => {
// let { userId } = req.params;
// // console.log(userId)
// let partnerId = userId;
// try {
// let infoPartner = await Users.findById(partnerId)
// if (infoPartner.partner){
// let idInfoPartner = infoPartner.partner;
// allGymPartner = await Partner.findById(idInfoPartner)
// .populate({path: "gyms", populate:{path: "services"}})
// }
// res.status(200).json(allGymPartner);
// } catch (error) {
// console.log(error)
// res.status(404).send({ error: error.message });
// }
// });
// Para solicitar info de un gym por su id
// router.get("/:id", async (req, res) => {
// ---> Tiene conficto con la anterior porque espera un id
router.get("/gymbyid/:id", async (req, res) => {
try {
const { id } = req.params;
const response = await getGymById(id);
res.status(200).send(response);
} catch (error) {
res.status(404).send({ error: error.message });
}
});
// Para solicitar info de un gym con su name
router.get('/gymbyname', async (req, res) => {
try {
const { name } = req.query;
const response = await getGymByName(name);
res.status(200).send(response);
} catch (error) {
res.status(404).send({ error: error.message });
}
});
// Para actualizar un gym
router.put('/gymupdate', async (req, res) => {
try {
const { id, data } = req.body
const response = await saveGyms(id, data);
res.status(200).send(response);
} catch (error) {
console.error(error)
res.status(404).send({ error: error.message });
}
});
// Para crear gym
router.post('/gymcreate/:idUser', async (req, res) => {
const { idUser } = req.params;
try {
console.log("llega a la ruta post gymcreate")
const response = await postGyms(idUser, req.body);
res.status(200).send(response);
} catch (error) {
res.status(404).send({ error: error.message });
}
});
//----------------------------------------------------------------------------
// Trae los gimnasios de un usuario partner
//----------------------------------------------------------------------------
// http:/localhost:3001/api/partner/gyms/mygyms/:userId
router.get("/mygyms/:userId", async (req, res) => {
let { userId } = req.params;
// console.log(userId)
let partnerId = userId;
try {
let infoPartner = await Users.findById(partnerId)
if (infoPartner.partner) {
let idInfoPartner = infoPartner.partner;
allGymPartner = await Partner.findById(idInfoPartner)
.populate({ path: "gyms", populate: { path: "services" } })
}
res.status(200).json(allGymPartner);
} catch (error) {
console.log(error)
res.status(404).send({ error: error.message });
}
});
//----------------------------------------------------------------------------
// Para crear un solo gym - envío el id del user y la info para crear el gym
//----------------------------------------------------------------------------
// http://localhost:3001/api/partner/gyms/createOneGym
router.post('/createOneGym/', async (req, res) => {
console.log(req.body, 'create One Gym 1')
const { userId, dataNewGym } = req.body;
let partnerId = userId.userId;
// console.log(partnerId, 'partener id');
try {
let addNewGym;
let infoPartner = await Users.findById(partnerId)
console.log(infoPartner, ' info del partner')
const newGym = new Gyms(dataNewGym);
await newGym.save();
if (infoPartner.partner) {
let idInfoPartner = infoPartner.partner;
addNewGym = await Partner.findByIdAndUpdate(idInfoPartner,
{ $push: { gyms: newGym._id } },
{ new: true });
// console.log(addNewGym, 'estoy en el if newGym');
}
if (addNewGym) {
return res.status(200).json({ message: 'Gimasio creado' });
}
} catch (error) {
console.log(error, 'create One Gym');
res.status(404).send({ error: error.message });
}
})
// pasos para crear el gym y vincularlo al user
// 1 crear el gym
// 2 guardarlo
// 3 buscar el partner (userId) y actualizarlo
// 1 - En el modelo User cuando es partner
// partner: {
// type: Array,
// of: mongoose.SchemaTypes.ObjectId,
// ref: "Partner" --------------------> hay una referencia al modelo Partner
// },
// 2 - En el modelo Partner
// gyms: {
// type: Array,
// of: mongoose.SchemaTypes.ObjectId,
// ref: "Gyms", --------------------> hay una referencia al modelo Gyms
// },
// 3 - En el modelo Gym
// services: {
// type: Array,
// of: mongoose.SchemaTypes.ObjectId,
// ref: "Services", ----------------> Hay una referencia al modelo Services
// },
// 4 - Y finalmente está services en el último lugar
//----------------------------------------------------------------------------
// Para editar un solo gym - envío el id del gym y la nueva info para editar
// el gym
//----------------------------------------------------------------------------
// http://localhost:3001/api/partner/gyms/editOneGym
router.put('/editOneGym/', async (req, res) => {
console.log(req.body, 'edite One Gym')
const { gymId, newDataGym } = req.body;
let idGym = gymId.gymId;
let editeGym;
console.log(req.body, ' la data del gym a editar')
try {
editeGym = await Gyms.findByIdAndUpdate(idGym,
newDataGym, { new: true })
console.log(editeGym, 'luego del update')
res.status(200).json({ message: 'Gimnasio actualizado' });
} catch (error) {
console.log(error);
res.status(404).send({ error: error.message });
}
})
module.exports = router; |
package rating
import (
"os"
"path/filepath"
"gopkg.in/yaml.v3"
)
// Config is a structure containing data from the config.yaml file
type Config struct {
Lichess struct {
URL string `yaml:"url"`
DefaultUser string `yaml:"defaultUser"`
} `yaml:"lichess"`
USCF struct {
URL string `yaml:"url"`
DefaultUser string `yaml:"defaultUser"`
DefaultState string `yaml:"defaultState"`
} `yaml:"USCF"`
}
var (
DEFAULT_DATA_GETTER = ReadConfigFile
// Override this for unit tests
DATA_GETTER = DEFAULT_DATA_GETTER
)
// LoadsConfig reads the configuration YAML file and returns a
// configuration object.
//
// The configuration data can be mocked for unit testing by
// setting DATA_GETTER to a function that returns ([]byte, error)
func LoadConfig() (*Config, error) {
var config Config
body, err := DATA_GETTER()
defer func() {
DATA_GETTER = DEFAULT_DATA_GETTER
}()
if err != nil {
return nil, err
}
err = yaml.Unmarshal(body, &config)
if err != nil {
return nil, err
}
return &config, nil
}
// ReadConfigFile reads $HOME/.config/rating/config.yaml and returns
// its contents
func ReadConfigFile() ([]byte, error) {
configDir, _ := os.UserConfigDir()
filename := filepath.Join(configDir, "chess-rating", "config.yaml")
body, err := os.ReadFile(filename)
return body, err
} |
<template>
<!-- Search BTN -->
<button class="btn btn-primary position-fixed" style="bottom: 20px; right: 20px; z-index: 1050;"
data-bs-toggle="modal" aria-label="IP Check" data-bs-target="#IPCheck" @click="openQueryIP"
v-tooltip="$t('Tooltips.QueryIP')"><i class="bi bi-search"></i></button>
<!-- Search Modal -->
<div class="modal fade" id="IPCheck" tabindex="-1" aria-labelledby="IPCheck" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content" :class="{ 'dark-mode dark-mode-border': isDarkMode }">
<div class="modal-header" :class="{ 'dark-mode-border': isDarkMode }">
<h5 class="modal-title" id="IPCheckTitle">{{ $t('ipcheck.Title') }}</h5>
<button type="button" class="btn-close" :class="{ 'dark-mode-close-button': isDarkMode }"
data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" :class="{ 'dark-mode': isDarkMode }">
<input type="text" class="form-control mb-2" :class="{ 'dark-mode': isDarkMode }"
:placeholder="$t('ipcheck.Placeholder')" v-model="inputIP" @keyup.enter="submitQuery"
name="inputIP" id="inputIP">
<div v-if="modalQueryError" class="text-danger">{{ modalQueryError }}</div>
<div v-if="modalQueryResult" class="mt-2">
<div class="card-body">
<ul class="list-group list-group-flush">
<li class="list-group-item jn-list-group-item" :class="{ 'dark-mode': isDarkMode }">
<span class="jn-text col-auto">
<i class="bi bi-pc-display-horizontal"></i> {{ $t('ipInfos.Country')
}}</span> :
<span class="col-10 ">{{ modalQueryResult.country_name }}
<span v-if="modalQueryResult.country_code"
:class="'jn-fl fi fi-' + modalQueryResult.country_code.toLowerCase()"></span>
</span>
</li>
<li class="list-group-item jn-list-group-item" :class="{ 'dark-mode': isDarkMode }">
<span class="jn-text col-auto"><i class="bi bi-houses"></i> {{ $t('ipInfos.Region')
}}</span> :
<span class="col-10 ">
{{ modalQueryResult.region }}
</span>
</li>
<li class="list-group-item jn-list-group-item" :class="{ 'dark-mode': isDarkMode }">
<span class="jn-text col-auto"><i class="bi bi-sign-turn-right"></i> {{
$t('ipInfos.City')
}}</span> :
<span class="col-10 ">
{{ modalQueryResult.city }}
</span>
</li>
<li class="list-group-item jn-list-group-item" :class="{ 'dark-mode': isDarkMode }">
<span class="jn-text col-auto"><i class="bi bi-ethernet"></i> {{ $t('ipInfos.ISP')
}}</span> :
<span class="col-10 ">
{{ modalQueryResult.isp }}
</span>
</li>
<li v-if="ipGeoSource === 0 && modalQueryResult.type !== $t('ipInfos.proxyDetect.type.unknownType')"
class="list-group-item jn-list-group-item" :class="{ 'dark-mode': isDarkMode }">
<span class="jn-text col-auto">
<i class="bi bi-reception-4"></i> {{ $t('ipInfos.type')
}}</span> :
<span class="col-10 ">
{{ modalQueryResult.type }}
<span v-if="modalQueryResult.proxyOperator !== 'unknown'">
( {{ modalQueryResult.proxyOperator }} )
</span>
</span>
</li>
<li v-if="ipGeoSource === 0 && modalQueryResult.isProxy !== $t('ipInfos.proxyDetect.unknownProxyType')"
class="list-group-item jn-list-group-item" :class="{ 'dark-mode': isDarkMode }">
<span class="jn-text col-auto">
<i class="bi bi-shield-fill-check"></i>
{{ $t('ipInfos.isProxy') }}</span> :
<span class="col-10 ">
{{ modalQueryResult.isProxy }}
<span
v-if="modalQueryResult.proxyProtocol !== $t('ipInfos.proxyDetect.unknownProtocol')">
( {{ modalQueryResult.proxyProtocol }} )
</span>
</span>
</li>
<li class="list-group-item jn-list-group-item" :class="{ 'dark-mode': isDarkMode }">
<span class="jn-text col-auto">
<i class="bi bi-buildings"></i> {{ $t('ipInfos.ASN') }}</span> :
<span class="col-10 ">
<a v-if="modalQueryResult.asnlink" :href="modalQueryResult.asnlink"
target="_blank"
class="link-underline-opacity-50 link-underline-opacity-100-hover"
:class="[isDarkMode ? 'link-light' : 'link-dark']">{{ modalQueryResult.asn
}}</a>
</span>
</li>
</ul>
</div>
</div>
</div>
<div class="modal-footer" :class="{ 'dark-mode-border': isDarkMode }">
<button id="sumitQueryButton" type="button" class="btn btn-primary"
:class="{ 'btn-secondary': !isValidIP(inputIP), 'btn-primary': isValidIP(inputIP) }"
@click="submitQuery" :disabled="!isValidIP(inputIP) || reCaptchaStatus === false || isChecking === 'running'
">{{
$t('ipcheck.Button') }}</button>
<span v-if="configs.recaptcha" class="text-secondary" style="font-size:10px">
This site is protected by reCAPTCHA and the Google
<a href="https://policies.google.com/privacy">Privacy Policy</a> and
<a href="https://policies.google.com/terms">Terms of Service</a> apply.
</span>
</div>
</div>
</div>
</div>
</template>
<script>
import { ref, computed, watch } from 'vue';
import { useStore } from 'vuex';
import { Modal } from 'bootstrap';
export default {
name: 'QueryIP',
// 引入 Store
setup() {
const store = useStore();
const isDarkMode = computed(() => store.state.isDarkMode);
const isMobile = computed(() => store.state.isMobile);
const ipGeoSource = computed(() => store.state.ipGeoSource);
const configs = computed(() => store.state.configs);
return {
isDarkMode,
isMobile,
ipGeoSource,
configs,
};
},
data() {
return {
inputIP: '',
modalQueryResult: null,
modalQueryError: "",
reCaptchaStatus: true,
reCaptchaLoaded: false,
isChecking: "idle",
}
},
methods: {
// 查询 IP 信息
async submitQuery() {
// 首先检查输入的 IP 是否有效
if (this.isValidIP(this.inputIP)) {
this.modalQueryError = "";
this.modalQueryResult = null;
this.isChecking = "running";
// 如果 reCAPTCHA 已启用,验证令牌
switch (this.configs.recaptcha) {
case true:
// 执行 reCAPTCHA 验证
grecaptcha.ready(async () => {
grecaptcha.execute(import.meta.env.VITE_RECAPTCHA_SITE_KEY, { action: 'submit' }).then(async (token) => {
let recaptchaSuccess = await this.verifyRecaptchaToken(token);
if (recaptchaSuccess) {
this.reCaptchaStatus = true;
await this.fetchIPForModal(this.inputIP);
} else {
this.reCaptchaStatus = false;
this.modalQueryError = this.$t('ipcheck.recaptchaError');
this.isChecking = "idle";
}
});
});
break;
case false:
await this.fetchIPForModal(this.inputIP);
break;
}
} else {
// 如果 IP 无效,设置错误信息
this.modalQueryError = this.$t('ipcheck.Error');
this.modalQueryResult = null;
this.isChecking = "idle";
}
},
// 加载 reCAPTCHA 脚本
loadRecaptchaScript() {
if (this.configs.recaptcha === false || this.reCaptchaLoaded === true) {
return;
}
// 创建一个 script 元素
const script = document.createElement('script');
script.src = `https://www.google.com/recaptcha/api.js?render=${import.meta.env.VITE_RECAPTCHA_SITE_KEY}`;
script.async = true;
script.defer = true;
document.head.appendChild(script);
// 获取加载完成的状态
script.onload = () => {
this.reCaptchaLoaded = true;
};
},
// 验证 reCAPTCHA 令牌
async verifyRecaptchaToken(token) {
const response = await fetch(`/api/recaptcha?token=${token}`, {
method: 'GET',
});
const data = await response.json();
return data.success;
},
// 打开查询 IP 的模态框
openQueryIP() {
// 如果 reCAPTCHA 脚本尚未加载,加载它
if (!window.grecaptcha && this.configs.recaptcha) {
this.loadRecaptchaScript();
}
this.$trackEvent('SideButtons', 'ToggleClick', 'QueryIP');
},
// 重置 modalQueryResult
setupModalEventListener() {
const modalElement = document.getElementById("IPCheck");
modalElement.addEventListener("hidden.bs.modal", this.resetModalData);
},
// 验证 IP 地址合法性
isValidIP(ip) {
const ipv4Pattern =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
const ipv6Pattern =
/^(([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4})|(([0-9a-fA-F]{1,4}:){0,6}([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:){0,6}([0-9a-fA-F]{1,4})?))$/;
return ipv4Pattern.test(ip) || ipv6Pattern.test(ip);
},
// 格式化 IP 数据
transformDataFromIPapi(data) {
if (data.error) {
throw new Error(data.reason);
}
const baseData = {
country_name: data.country_name || "",
country_code: data.country || "",
region: data.region || "",
city: data.city || "",
latitude: data.latitude || "",
longitude: data.longitude || "",
isp: data.org || "",
asn: data.asn || "",
asnlink: data.asn ? `https://radar.cloudflare.com/${data.asn}` : false,
mapUrl: data.latitude && data.longitude ? `/api/map?latitude=${data.latitude}&longitude=${data.longitude}&language=${this.bingMapLanguage}&CanvasMode=CanvasLight` : "",
mapUrl_dark: data.latitude && data.longitude ? `/api/map?latitude=${data.latitude}&longitude=${data.longitude}&language=${this.bingMapLanguage}&CanvasMode=RoadDark` : ""
};
if (this.ipGeoSource === 0) {
const proxyDetails = this.extractProxyDetails(data.proxyDetect);
return {
...baseData,
...proxyDetails,
};
}
return baseData;
},
// 提取代理信息
extractProxyDetails(proxyDetect = {}) {
const isProxy = proxyDetect.proxy === 'yes' ? this.$t('ipInfos.proxyDetect.yes') :
proxyDetect.proxy === 'no' ? this.$t('ipInfos.proxyDetect.no') :
this.$t('ipInfos.proxyDetect.unknownProxyType');
const type = proxyDetect.type === 'Business' ? this.$t('ipInfos.proxyDetect.type.Business') :
proxyDetect.type === 'Residential' ? this.$t('ipInfos.proxyDetect.type.Residential') :
proxyDetect.type === 'Wireless' ? this.$t('ipInfos.proxyDetect.type.Wireless') :
proxyDetect.type === 'Hosting' ? this.$t('ipInfos.proxyDetect.type.Hosting') :
proxyDetect.type ? proxyDetect.type : this.$t('ipInfos.proxyDetect.type.unknownType');
const proxyProtocol = proxyDetect.protocol === 'unknown' ? this.$t('ipInfos.proxyDetect.unknownProtocol') :
proxyDetect.protocol ? proxyDetect.protocol : this.$t('ipInfos.proxyDetect.unknownProtocol');
const proxyOperator = proxyDetect.operator ? proxyDetect.operator : "";
return { isProxy, type, proxyProtocol, proxyOperator };
},
// 获取 IP 信息
async fetchIPForModal(ip, sourceID = null) {
if (this.reCaptchaStatus === false) {
this.modalQueryError = this.$t('ipcheck.recaptchaError');
return;
}
let lang = this.$Lang;
if (lang === 'zh') {
lang = 'zh-CN';
};
sourceID = this.ipGeoSource;
const sources = [
{ id: 0, url: `/api/ipchecking?ip=${ip}&lang=${lang}`, transform: this.transformDataFromIPapi },
{ id: 1, url: `/api/ipinfo?ip=${ip}`, transform: this.transformDataFromIPapi },
{ id: 2, url: `/api/ipapicom?ip=${ip}&lang=${lang}`, transform: this.transformDataFromIPapi },
{ id: 3, url: `https://ipapi.co/${ip}/json/`, transform: this.transformDataFromIPapi },
{ id: 4, url: `/api/keycdn?ip=${ip}`, transform: this.transformDataFromIPapi },
{ id: 5, url: `/api/ipsb?ip=${ip}`, transform: this.transformDataFromIPapi },
];
// 根据指定的源获取数据
for (const source of sources) {
if (sourceID && source.id !== sourceID) {
continue;
}
try {
const response = await fetch(source.url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(data.reason || "IP lookup failed");
}
// 使用对应的转换函数更新 modalQueryResult
this.modalQueryResult = source.transform(data);
this.isChecking = "idle";
break;
} catch (error) {
console.error("Error fetching IP details:", error);
}
}
},
},
}
</script>
<style scoped></style> |
from urllib.request import Request,urlopen
import re
from bs4 import BeautifulSoup
import requests
class Crawler():
def __init__(self, info_dict: dict = {}, url : str = ''):
self.url = url
self.info_dict = info_dict
self.movie_name_list = []
self.movie_eng_name_list = []
self.movie_time_list = []
self.movie_score_list = []
# 请求网页,获取网页内容
def obtain_url_info(self):
request = requests.get(self.url)
html = request.content.decode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
# 获取电影中英名称
movie_titles = soup.find_all('h2', class_='m-b-sm')
for title in movie_titles:
movie_name = title.text.split('-')[0] # movie_name为list
movie_eng_name = title.text.split('-')[1]
self.movie_name_list.append(movie_name)
self.movie_eng_name_list.append(movie_eng_name)
# 获取电影时长
info_div = soup.find_all('div', class_='m-v-sm info')
for info in info_div:
movie_info = info.text # 获取文本数据
pattern1 = r"(\d+) 分钟" # 使用正则表达式查找”分钟“前的数字
movie_times = re.search(pattern1, movie_info)
if movie_times:
movie_time = movie_times.group(1)
self.movie_time_list.append(movie_time)
# 获取电影评分
score_info = soup.find_all('p',class_='score m-t-md m-b-n-sm')
for score in score_info:
movie_score = score.text
pattern2 = r'\d+.\d+'
movie_scores = re.findall(pattern2, movie_score)
result = ','.join(movie_scores) # 将列表转换为字符串
self.movie_score_list.append(result)
# 精髓
for i in range(len(self.movie_name_list)): # 每个列表的长度一样
movie_name = self.movie_name_list[i]
movie_eng_name = self.movie_eng_name_list[i]
movie_time = self.movie_time_list[i]
movie_score = self.movie_score_list[i]
self.info_dict[i] = {'movie_name': movie_name, 'movie_eng_name': movie_eng_name, 'movie_time': movie_time,'movie_score': movie_score}
print(str(self.info_dict))
with open('result.txt', 'a', encoding='UTF-8') as f:
f.write(str(self.info_dict))
if __name__ == '__main__':
# 搜索所有相关的网页
for i in range(1, 11):
url = 'https://ssr1.scrape.center/page/{}'.format(i)
crawler = Crawler(url = url)
crawler.obtain_url_info()
#print(crawler.obtain_url_info()) |
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
class LoginController extends Controller
{
//
public function index(){
return view('auth.login');
}
public function login_proses(Request $request){
$request->validate([
'username' => 'required',
'password' => 'required'
]);
$data = [
'username' => $request->username,
'password' =>$request->password
];
if(Auth::attempt($data)){
return redirect()->route('admin.dashboard');
} else {
return redirect()->route('login')->with('failed', 'Username atau Password Salah');
}
}
public function logout(){
Auth::logout();
return redirect()->route('login')->with('success', 'Kamu berhasil logout');
}
public function register(){
return view('auth.register');
}
public function register_proses(Request $request){
$request->validate([
// 'photo' => 'required|mimes:png,jpg,jpeg,|max:2048',
'nama' => 'required',
'username' => 'required|unique:users,username',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6'
]);
//Menambahkan foto ke lokal
// $photo = $request->file('photo');
// $filename = date('Y-m-d').$photo->getClientOriginalName();
// $path = 'photo-user/'.$filename;
// Storage::disk('public')->put($path,file_get_contents($photo));
$data['name'] = $request->nama;
$data['username'] = $request->username;
$data['email'] = $request->email;
$data['password'] = Hash::make($request->password);
$data['level'] = $request->level;
// $data['image'] = $filename;
User::create($data);
$login = [
'username' => $request->username,
'password' => $request->password
];
if(Auth::attempt($login)){
return redirect()->route('admin.dashboard');
} else {
return redirect()->route('register')->with('failed', 'Email atau Password Salah');
}
}
} |
import './globals.css'
import type { Metadata } from 'next'
import { Poppins } from 'next/font/google'
import {ClerkProvider} from '@clerk/nextjs'
import ModalProvider from '@/providers/modal-provider'
import { ToastProvider } from '@/providers/toast-provider'
import { ThemeProvider } from '@/providers/theme-provider'
const poppins = Poppins({
weight: '400',
subsets: ['latin'],
})
export const metadata: Metadata = {
title: 'Admin Dashboard',
description: 'Admin Dashboard',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<ClerkProvider>
<html lang="en">
<body className={poppins.className}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<ToastProvider />
<ModalProvider />
{children}
</ThemeProvider>
</body>
</html>
</ClerkProvider>
)
} |
import { Injectable } from "@angular/core";
import { Movie } from "./movie.model";
import { Repository } from "./repository";
@Injectable()
export class Cart {
// ---------Properties----------------
selections: MovieSelection[] = [];
itemCount: number = 0;
totalPrice: number = 0;
// ---------Constructor---------------
constructor(private repo: Repository) {
repo.getSessionData("cart").subscribe((cartData) => {
if (cartData != null) {
cartData
.map(
(item) =>
new MovieSelection(
this,
item.movieId,
item.name,
item.price,
item.quantity
)
)
.forEach((item) => this.selections.push(item));
this.update(false);
}
});
}
// ---------Methods-------------------
addMovie(movie: Movie) {
let selection = this.selections.find((ms) => ms.movieId == movie.movieId);
if (selection) {
selection.quantity++;
} else {
this.selections.push(
new MovieSelection(this, movie.movieId, movie.name, movie.price, 1)
);
}
this.update();
}
updateQuantity(movieId: number, quantity: number) {
if (quantity > 0) {
let selection = this.selections.find((ms) => ms.movieId == movieId);
if (selection) {
selection.quantity = quantity;
}
} else {
let index = this.selections.findIndex((ms) => ms.movieId == movieId);
if (index != -1) {
this.selections.splice(index, 1);
}
this.update();
}
}
clear() {
this.selections = [];
this.update();
}
update(storeData: boolean = true) {
this.itemCount = this.selections
.map((ms) => ms.quantity)
.reduce((prev, curr) => prev + curr, 0);
this.totalPrice = this.selections
.map((ms) => ms.price * ms.quantity)
.reduce((prev, curr) => prev + curr, 0);
if (storeData) {
this.repo.storeSessionData(
"cart",
this.selections.map(ms => {
return {
movieId: ms.movieId,
name: ms.name,
price: ms.price,
quantity: ms.quantity,
}
})
);
}
}
}
// ----------Class MovieSelection--------
export class MovieSelection {
constructor(
public cart: Cart,
public movieId?: number,
public name?: string,
public price?: number,
private quantityValue?: number
) {}
get quantity() {
return this.quantityValue;
}
set quantity(newQuantity: number) {
this.quantityValue = newQuantity;
this.cart.update();
}
} |
#ifndef MQTT_SBC_H
#define MQTT_SBC_H
#include "display.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <MQTTClient.h>
// Configuracoes mqtt
#define CLIENTID "sbc"
//#define BROKER "mqtt://broker.emqx.io:1883"
#define BROKER "tcp://10.0.0.101:1883"
#define USERNAME "aluno"
#define PASSWORD "@luno*123"
// Topicos a serem publicados
#define SBC_ESP "sbc/esp"
#define SBC_IHM "sbc/ihm"
// Topicos a se inscrever
#define SENSORES_D "esp/sensores_digitais"
#define SENSORES_A "esp/sensores_analogicos"
#define SENSOR_ANALOG "esp/analog_sensor"
#define SENSOR_DIGITAL "esp/digital_sensor"
#define STATUS "esp/status"
#define LED "esp/led"
#define IHM_TIME "ihm/tempo"
// variaveis que armazenam os historicos de atualizacao
int dig_history1[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int dig_history2[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int dig_history3[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int dig_history4[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int dig_history5[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int dig_history6[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int dig_history7[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int dig_history8[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int anag_history[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// variavel cliente MQTT
MQTTClient client;
void publish(MQTTClient client, char* topic, char* payload);
int on_message(void *context, char *topicName, int topicLen, MQTTClient_message *message);
/**
* Publica uma mensagem em um dado topico
* @param topic - Topico da mensagem a ser publicada
* @param payload - Mensagem a ser enviada
*/
void publicar(char* topic, char* payload){
publish(client, topic, payload);
}
void atualiza_historico(int *historico, int valor){
for(int i = 0; i < 10; i++){
historico[i] = historico[i + 1];
}
historico[0] = valor;
}
void atualiza_digitais(int valor[]){
atualiza_historico(dig_history1, valor[0]);
atualiza_historico(dig_history2, valor[1]);
atualiza_historico(dig_history3, valor[2]);
atualiza_historico(dig_history4, valor[3]);
atualiza_historico(dig_history5, valor[4]);
atualiza_historico(dig_history6, valor[5]);
atualiza_historico(dig_history7, valor[6]);
atualiza_historico(dig_history8, valor[7]);
}
int stringToInt(char *string){
int number = 0;
for(int i = 0; i<strlen(string); i++){
number = number * 10 + (string[i] - '0');
}
return number;
}
void publicar_historico(int *historico, char* sensor){
for(int i = 0; i < strlen(sensor); i++){
char d[15];
sprintf(d, "%d", historico[i]);
char *a = d;
char newTopic[30];
sprintf(newTopic, "%s/%s", SBC_IHM, sensor);
publicar(newTopic, a);
}
}
void publicar_digitais(){
publicar_historico(dig_history1, "D/1");
publicar_historico(dig_history2, "D/2");
publicar_historico(dig_history3, "D/3");
publicar_historico(dig_history4, "D/4");
publicar_historico(dig_history5, "D/5");
publicar_historico(dig_history6, "D/6");
publicar_historico(dig_history7, "D/7");
publicar_historico(dig_history8, "D/8");
}
/**
* Recebe as mensagens dos topicos inscritos
* @param context -
* @param topicName - Nome do topico que mando a mensagem
* @param topicLen - Tamamnho do nome do topico
* @param mensagem - Mensagem recebida
*/
int on_message(void *context, char *topicName, int topicLen, MQTTClient_message *message) {
char* payload = message->payload;
printf("\n\nMensagem recebida! \n\rTopico: %s Mensagem: %s\n\n\n", topicName, payload);
if(strcmp(topicName, LED) == 0){
if(strcmp(payload, "1") == 0){
write_textLCD(" MQTT ", "LED: ON");
}
else if(strcmp(payload, "0") == 0){
write_textLCD(" MQTT ", "LED: OFF");
}
}
else if(strcmp(topicName, STATUS) == 0){
if(strcmp(payload, "00") == 0){
write_textLCD(" MQTT ", "Status:OK");
}
else if(strcmp(payload, "1F") == 0){
write_textLCD(" MQTT ", "Status: ERROR");
}
}
else if(strcmp(topicName, SENSOR_ANALOG) == 0){
char texto[30];
sprintf(texto, "A1: %s", payload);
write_textLCD("Leitura Analogica", texto);
}
else if(strcmp(topicName, SENSOR_DIGITAL) == 0){
char texto[30];
sprintf(texto, "D%c: %c", payload[0], payload[1]);
write_textLCD("Leitura Digital", texto);
}
else if(strcmp(topicName, SENSORES_A) == 0){
int valor = stringToInt(payload);
atualiza_historico(anag_history, valor);
publicar_historico(anag_history, "A/1");
}
else if(strcmp(topicName, SENSORES_D) == 0){
int valor[8];
for(int i = 0; i < 8; i++){
valor[i] = payload[0] - '0';
}
atualiza_digitais(valor);
publicar_digitais(); // envia o comando e o sensor indicado
}
else if(strcmp(topicName, IHM_TIME) == 0){
publicar(SBC_ESP, payload); // envia o tempo recebido para nodemcu
}
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
/**
* Realiza as configurações iniciais para a comunicacao mqtt
*/
void mqtt_config(){
while(!MQTTClient_isConnected(client)){
int rc;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
conn_opts.username = USERNAME;
conn_opts.password = PASSWORD;
//Inicializacao do MQTT (conexao & subscribe)
MQTTClient_create(&client, BROKER, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
// Adiciona msgs
MQTTClient_setCallbacks(client, NULL, mqtt_config, on_message, NULL);
// Verifica se o cliente mqtt esta conectado
rc = MQTTClient_connect(client, &conn_opts);
if (rc != MQTTCLIENT_SUCCESS) {
printf("\n\rFalha na conexao ao broker MQTT. Erro: %d\n", rc);
exit(-1);
}
}
}
/**
* Publica uma mensagem num dado topico
* @param cliente - cliente MQTT que publicara o topico
* @param topico - topico MQTT a ser publicado
* @param payload - conteudo da mensagem
*/
void publish(MQTTClient client, char* topic, char* payload) {
MQTTClient_message pubmsg = MQTTClient_message_initializer;
pubmsg.payload = payload;
pubmsg.payloadlen = strlen(pubmsg.payload);
pubmsg.qos = 2;
pubmsg.retained = 0;
MQTTClient_deliveryToken token;
MQTTClient_publishMessage(client, topic, &pubmsg, &token);
MQTTClient_waitForCompletion(client, token, 1000L);
}
/**
* Inscreve-se em um topico mqtt
* @param topic - topico que deseja se inscrever
*/
void increver(char* topic){
MQTTClient_subscribe(client, topic, 0);
}
#endif |
const URL = require('../models/modelUrl');
/**
* Handles the GET request for retrieving IDs.
*
* @param {Object} req - The request object.
* @param {Object} res - The response object.
* @return {Promise} The redirect response.
*/
async function handleGetIds(req, res) {
// Extract the shortId from the URL
const shortId = req.params.shortId
if (shortId == null) {
return res.status(400).json({ error: 'shortId is required' })
}
// Record the new Visit to the URL
const newVisit = await URL.findOneAndUpdate(
{ shortUrl: shortId },
{
$push: {
visitHistory: { time: Date.now() }
}
})
//Redirect to the original URL
res.redirect(newVisit.originalUrl)
}
module.exports = { handleGetIds } |
import React, { SetStateAction } from "react";
import {
BackGroundContainer,
ImageContainer,
ModalContainer,
TitleContainer,
} from "./modalImageStyle";
interface ModaImageProps {
img: string | null;
setShowImage: React.Dispatch<SetStateAction<string | null>>;
setShowModalImage: React.Dispatch<SetStateAction<boolean>>;
}
const ModalImage: React.FC<ModaImageProps> = ({
img,
setShowImage,
setShowModalImage,
}) => {
const closeModal = () => {
setShowImage(null);
setShowModalImage(false);
};
return img ? (
<BackGroundContainer>
<ModalContainer>
<TitleContainer>
<h2>Imagem do carro</h2>
<button onClick={() => closeModal()}>X</button>
</TitleContainer>
<ImageContainer>
<img src={img} alt="" />
</ImageContainer>
</ModalContainer>
</BackGroundContainer>
) : (
<h2>Sem imagem</h2>
);
};
export default ModalImage; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.