text
stringlengths
184
4.48M
import React, { useState, useEffect } from "react"; import Input from "./Input"; const Tasks = ({ list, deleteTask, saveUpdatedTask }) => { const [taskList, setTaskList] = useState([]); useEffect(() => { setTaskList(list); }, [list]); const updateSelectedTask = (index, value) => { const updatedTaskList = taskList.map((item, i) => { if (i === index) { return { ...item, task: value }; } return item; }); setTaskList(updatedTaskList); }; const saveSelectedTask = async (index, event) => { if (event.key === "Enter" && taskList[index].task.trim() !== "") { await saveUpdatedTask(taskList[index]); event.target.blur(); } }; const revertChanges = () => { setTaskList(list); }; const renderTasks = () => { if (taskList && taskList.length > 0) { return taskList.map((item, index) => { return ( <div key={index} className="task-item"> <Input type={"text"} value={item.task} onBlur={() => revertChanges()} onChange={(e) => updateSelectedTask(index, e.target.value)} onKeyPress={(e) => saveSelectedTask(index, e)} /> <div className="delete-button" onClick={() => deleteTask(item.id)}> <span className="delete-icon">X</span> </div> </div> ); }); } else { return ( <> <div className="no-task-message"> <div>{":("}</div> <div>{"There is no task yet!"}</div> </div> </> ); } }; return ( <> <div>{renderTasks()}</div> </> ); }; export default Tasks;
package map; import java.util.Comparator; import list.ArrayList; public class SortedArrayMap<K,V> implements Map<K,V> { private static class Entry<K,V> { private K k; private V v; public Entry(K key, V value) { k = key; v = value; } public K getKey() { return k; } public V getValue() { return v; } public V setValue(V value) { V old = v; v = value; return old; } public String toString() { return "<" + k + ", " + v + ">"; } } private Comparator<K> comp; private ArrayList<Entry<K,V>> data = new ArrayList<>(); public SortedArrayMap(Comparator<K> c) { comp = c; } public SortedArrayMap() { this(new DefaultComparator<K>()); } public int size() { return data.size(); } public boolean isEmpty() { return size() == 0; } private boolean checkKey(K key) { try { return (comp.compare(key,key) == 0); } catch (ClassCastException e) { throw new IllegalArgumentException("Incompatible key"); } } private int findIndex(K key) { return findIndex(key, 0, data.size() - 1); } private int findIndex(K key, int low, int high) { if (high < low) return high + 1; int mid = (low + high) / 2; int result = comp.compare(key, data.get(mid).getKey()); if (result == 0) return mid; else if (result < 0) return findIndex(key, low, mid - 1); else return findIndex(key, mid + 1, high); } public V get(K key) { checkKey(key); int j = findIndex(key); if (j == size() || comp.compare(key, data.get(j).getKey()) != 0) return null; return data.get(j).getValue(); } public V put(K key, V value) { checkKey(key); int j = findIndex(key); if (j < size() && comp.compare(key, data.get(j).getKey()) == 0) return data.get(j).setValue(value); data.add(j, new Entry<K,V>(key,value)); return null; } public V remove(K key) { checkKey(key); int j = findIndex(key); if (j == size() || comp.compare(key, data.get(j).getKey()) != 0) return null; return data.remove(j).getValue(); } public String toString() { return data.toString(); } }
import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import { Modal, Header, Button, Icon } from 'semantic-ui-react'; import { addTrackToAlbum, addTrackToAlbumAndReport, } from '../../../store/track/actions'; import { setNotification } from '../../../store/notification/actions'; import { AddNewTrackToAlbumFormValuesType } from '../../../store/track/types'; import { Album } from '../../../store/album/types'; import { ReportState } from '../../../store/report/types'; import AddTrackToAlbumForm from './AddTrackToAlbumForm'; interface Props { currentAlbum: Album; report: ReportState; } const AddTrackToAlbum: React.FC<Props> = ({ currentAlbum, report }) => { const dispatch = useDispatch(); console.log('album at album details', currentAlbum); console.log('report at album details', report); const [modalOpen, setModalOpen] = useState(false); const handleOpen = () => { setModalOpen(true); }; const handleClose = () => { setModalOpen(false); }; const handleAddToAlbumClick = (values: AddNewTrackToAlbumFormValuesType) => { const length = Number(values.minutes) * 60 + Number(values.seconds); let regexPeople; if (values.people) { regexPeople = `| ${values.people.replace(/\n/g, ' | ')} |`; } else { regexPeople = null; } console.log(values); const trackToAdd = { track_title: values.track_title, artist_name: currentAlbum.artist_name, album_name: currentAlbum.album_name, album_id: currentAlbum.album_id, artist_id: currentAlbum.artist_id, length, country: values.country, cat_id: currentAlbum.cat_id, label: currentAlbum.label, year: currentAlbum.year, record_country: values.record_country, people: regexPeople, disc_no: Number(values.disc_no), track_no: Number(values.track_no), isrc: values.isrc, comment: values.comment, }; console.log(trackToAdd); dispatch(addTrackToAlbum(trackToAdd)); dispatch( setNotification( `${values.track_title} added to ${currentAlbum.album_name}`, 'success' ) ); handleClose(); }; const handleAddToAlbumAndReportClick = ( values: AddNewTrackToAlbumFormValuesType ) => { const length = Number(values.minutes) * 60 + Number(values.seconds); let regexPeople; if (values.people) { regexPeople = `| ${values.people.replace(/\n/g, ' | ')} |`; } else { regexPeople = null; } console.log(values); const trackToAdd = { track_title: values.track_title, artist_name: currentAlbum.artist_name, album_name: currentAlbum.album_name, album_id: currentAlbum.album_id, artist_id: currentAlbum.artist_id, length, country: values.country, cat_id: currentAlbum.cat_id, label: currentAlbum.label, year: currentAlbum.year, record_country: values.record_country, people: regexPeople, disc_no: Number(values.disc_no), track_no: Number(values.track_no), isrc: values.isrc, comment: values.comment, report_id: report.reportDetails?.id, sortable_rank: report.report.length + 1, }; console.log('add to album and', trackToAdd); dispatch(addTrackToAlbumAndReport(trackToAdd)); dispatch( setNotification( `${values.track_title} added to ${currentAlbum.album_name} and to ${report.reportDetails?.program_name} ${report.reportDetails?.program_date}`, 'success' ) ); handleClose(); }; return ( <Modal trigger={ <Button style={{ marginBottom: '0.5rem' }} onClick={handleOpen} floated='right' color='green' > <Icon name='add' /> Add a track to the album </Button> } closeIcon open={modalOpen} onClose={handleClose} > <Modal.Content> <Header content={`Add a track to album ${currentAlbum.album_name}`} /> <AddTrackToAlbumForm onClose={handleClose} onSubmit={handleAddToAlbumClick} reportDetails={report.reportDetails} currentAlbum={currentAlbum} addToAlbumAndReport={handleAddToAlbumAndReportClick} /> </Modal.Content> </Modal> ); }; export default AddTrackToAlbum;
import { LockOutlined, UserOutlined } from "@ant-design/icons"; import { Button, Checkbox, Form, Input } from "antd"; import { useNavigate } from "react-router-dom"; import { useState } from "react"; import { login } from "../store/action/actionCreator"; import { useDispatch } from "react-redux"; import { toast } from "react-toastify"; const LoginView = () => { const navigate = useNavigate(); const dispatch = useDispatch(); const [loginForm, setLoginForm] = useState({ email: "", password: "", }); const handleChange = (e) => { const { name, value } = e.target; setLoginForm((prevState) => ({ ...prevState, [name]: value, })); // console.log(loginForm); }; let onFinish = async () => { try { await dispatch(login(loginForm)); navigate("/"); } catch (err) { toast.error(err); } }; return ( <div className="w-[400px] rounded-lg text-center bg-gray-100 modal-custom translate-y-2/4 p-10 border "> <h1 className="text-3xl font-bold mb-10 ">Login</h1> <Form name="normal_login" className="login-form " onFinish={onFinish} initialValues={loginForm} > <Form.Item name="email" rules={[ { required: true, message: "Please input your Email!", }, ]} > <Input className="border border-black" prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Email" name="email" onChange={handleChange} /> </Form.Item> <Form.Item name="password" rules={[ { required: true, message: "Please input your Password!", }, ]} > <Input className="border border-black" prefix={<LockOutlined className="site-form-item-icon" />} type="password" placeholder="Password" name="password" onChange={handleChange} /> </Form.Item> <Form.Item> <Form.Item name="remember" valuePropName="checked" noStyle> <Checkbox>Remember me</Checkbox> </Form.Item> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit" className="bg-blue-500"> Log in </Button> </Form.Item> </Form> </div> ); }; export default LoginView;
import { NavigationContainer } from "@react-navigation/native"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; import { Provider } from "react-redux"; import store from "./redux"; import { LoginScreen } from "./screens/LoginScreen"; import { HomeScreen } from "./screens/HomeScreen"; import { SyncScreen } from "./screens/SyncScreen"; import { RegisteredFarmerScreen } from "./screens/buyCoffee/RegisteredFarmerScreen"; import { FarmerScreen } from "./screens/buyCoffee/FarmerScreen"; import { UnRegisteredFarmerScreen } from "./screens/buyCoffee/UnregisteredFarmerScreen"; import { ScJournal } from "./screens/scJournal/ScDailyJournal"; import { ScJournalsSummary } from "./screens/scJournal/ScJournalsSummary"; import { EditTransactionScreen } from "./screens/scJournal/EditTransactionScreen"; import { ChooseInspectionScreen } from "./screens/inspection/ChooseInspectionScreen"; import { InspectionFarmerScreen } from "./screens/inspection/InspectionFarmerScreen"; import { InspectionQuestionsScreen } from "./screens/inspection/InspectionQuestionsScreen"; import { InspectionCoursesScreen } from "./screens/inspection/InspectionCoursesScreen"; import { InspectionsScreen } from "./screens/inspection/InspectionsScreen"; import { HistoryScreen } from "./screens/history/HistoryScreen"; import { HistoryDetails } from "./screens/history/HistoryDetails"; import { TrainingCourses } from "./screens/training/TrainingCourses"; import { TrainingFarmers } from "./screens/training/TrainingFarmers"; import { TrainingScreen } from "./screens/training/TrainingScreen"; import { FarmerRegistrationScreen } from "./screens/farmer/FarmerRegistrationScreen"; import { FarmerUpdateHome } from "./screens/farmer/FarmerUpdateHome"; import { FarmerUpdateScreen } from "./screens/farmer/FarmerUpdateScreen"; import { FarmUpdateScreen } from "./screens/farmer/FarmUpdateScreen"; import { ChooseFarmerScreen } from "./screens/farmer/ChooseFarmerScreen"; import { SelectFarmersScreen } from "./screens/farmer/SelectFarmersScreen"; import { PendingRegistrationsScreen } from "./screens/farmer/PendingRegistrationsScreen"; import { FarmerEditScreen } from "./screens/farmer/FarmerEditScreen"; import { FarmerNewHHmember } from "./screens/farmer/FarmerNewHHmember"; import { PendingDeletionScreen } from "./screens/farmer/PendingDeletionScreen"; const Stack = createNativeStackNavigator(); export default function App() { return ( <Provider store={store}> <NavigationContainer> <Stack.Navigator initialRouteName="Login" screenOptions={{ headerShown: false }} > <Stack.Screen name="Login" options={{ unmountOnBlur: true }} component={LoginScreen} /> <Stack.Screen name="Homepage" options={{ unmountOnBlur: true }} component={HomeScreen} /> <Stack.Screen name="Sync" options={{ unmountOnBlur: true }} component={SyncScreen} /> {/* coffee purchase */} <Stack.Screen name="Registered_ATP_Farmer" options={{ unmountOnBlur: true }} component={RegisteredFarmerScreen} /> <Stack.Screen name="Unregistered_ATP_Farmer" options={{ unmountOnBlur: true }} component={UnRegisteredFarmerScreen} /> <Stack.Screen name="FarmerScreen" options={{ unmountOnBlur: true }} component={FarmerScreen} /> <Stack.Screen name="ScDailyJournal" options={{ unmountOnBlur: true }} component={ScJournal} /> <Stack.Screen name="ScDailySummary" options={{ unmountOnBlur: true }} component={ScJournalsSummary} /> <Stack.Screen name="EditTransaction" options={{ unmountOnBlur: true }} component={EditTransactionScreen} /> {/* inspection */} <Stack.Screen name="chooseInspection" options={{ unmountOnBlur: true }} component={ChooseInspectionScreen} /> <Stack.Screen name="inspectionFarmer" options={{ unmountOnBlur: true }} component={InspectionFarmerScreen} /> <Stack.Screen name="inspectionQuestions" options={{ unmountOnBlur: true }} component={InspectionQuestionsScreen} /> <Stack.Screen name="inspectionCourses" options={{ unmountOnBlur: true }} component={InspectionCoursesScreen} /> <Stack.Screen name="InspectionsScreen" options={{ unmountOnBlur: true }} component={InspectionsScreen} /> {/* history */} <Stack.Screen name="HistoryScreen" options={{ unmountOnBlur: true }} component={HistoryScreen} /> <Stack.Screen name="HistoryDetails" options={{ unmountOnBlur: true }} component={HistoryDetails} /> {/* training */} <Stack.Screen name="TrainingCourses" options={{ unmountOnBlur: true }} component={TrainingCourses} /> <Stack.Screen name="TrainingFarmers" options={{ unmountOnBlur: true }} component={TrainingFarmers} /> <Stack.Screen name="TrainingScreen" options={{ unmountOnBlur: true }} component={TrainingScreen} /> {/* farmer management */} <Stack.Screen name="FarmerRegistration" options={{ unmountOnBlur: true }} component={FarmerRegistrationScreen} /> <Stack.Screen name="FarmerUpdateHome" options={{ unmountOnBlur: true }} component={FarmerUpdateHome} /> <Stack.Screen name="FarmerUpdateScreen" options={{ unmountOnBlur: true }} component={FarmerUpdateScreen} /> <Stack.Screen name="FarmUpdateScreen" options={{ unmountOnBlur: true }} component={FarmUpdateScreen} /> <Stack.Screen name="ChooseFarmerUpdateScreen" options={{ unmountOnBlur: true }} component={ChooseFarmerScreen} /> <Stack.Screen name="SelectFarmerDeleteScreen" options={{ unmountOnBlur: true }} component={SelectFarmersScreen} /> <Stack.Screen name="PendingRegistrationScreen" options={{ unmountOnBlur: true }} component={PendingRegistrationsScreen} /> <Stack.Screen name="PendingFarmerEditScreen" options={{ unmountOnBlur: true }} component={FarmerEditScreen} /> <Stack.Screen name="FarmerNewHHmember" options={{ unmountOnBlur: true }} component={FarmerNewHHmember} /> <Stack.Screen name="FarmerDeletedScreen" options={{ unmountOnBlur: true }} component={PendingDeletionScreen} /> </Stack.Navigator> </NavigationContainer> </Provider> ); }
<template> <div> <div v-if="showPage" class="signup"> <h1>Página cadastro</h1> <div></div> <form> <div> <label for="name" >Nome:</label> <input tabindex="1" type="text" id="name" v-model="user.name"> </div> <div> <label for="email" >Email:</label> <input tabindex="2" type="email" id="email" v-model="user.email"> </div> <div> <label for="password" >Senha:</label> <input tabindex="3" type="password" id="password" v-model="user.password"> </div> <div> <label for="confirm_password" >Confirmação:</label> <input tabindex="4" type="password" id="confirm_password" v-model="user.confirm_password"> </div> <button type="submit" tabindex="5" class="btn" @click.prevent="signup">Cadastrar</button> </form> </div> <div v-else> <PageLoading /> </div> </div> </template> <script> import { beforeEach } from '../utils/loginRouteUtils' export default { name: "Signup", data () { return { user : { name: 'luisgustavo', email: 'luisgustavo@gmail.com', password: '123456@Gustavo', confirm_password: '123456@Gustavo' }, btnClicked: false } }, computed: { showPage () { return this.$store.state.screencontrol.showPage } }, methods: { async signup (event) { this.efeitoEntrar(event.target, true) this.$store.commit('screencontrol/CHANGE_SHOW_PAGE', false) // console.log(this.$store.state.screencontrol.showPage) this.$store.dispatch('login/signup', this.user) .then( (response) => { if (response.status === 201) { alert(response.data.messages) this.user = {} this.$router.push( {name: 'login'}) } }) .catch ( (err) => { if (err.response) { alert(err.response.data.errors) this.$store.commit('screencontrol/CHANGE_SHOW_PAGE', true) } else { alert("O servidor está fora!!!") } }) // Limpe os campos no final }, // Método repetivo. Tem que ir para algum lugar em comum efeitoEntrar(target, ativar) { if (ativar) { target.disabled = true target.classList.add("btn-disabled") this.btnClicked = true } else { target.disabled = false target.classList.remove("btn-disabled") this.btnClicked = false } } }, beforeRouteEnter (to, from, next) { // console.log("beforeRouteEnter: LOGIN") next(vm => { beforeEach(to, from, next, vm.$store, vm.$router) }) } } </script> <style scoped> .signup { display: grid; grid-template-columns: 2fr 4fr 2fr; width: 90%; margin: 0 auto; padding: 0 20px; } .signup h1 { grid-column: 1 / 4; } .signup form { width: 100%; min-width: 50%; } .signup label { display: block; margin-bottom: 10px; } .signup input { margin-bottom: 10px; width: 100%; } .signup button { display: block; margin: 20px auto; width: 100%; } .btn-disabled { background: gray; } </style>
import { InjectModel } from '@nestjs/mongoose'; import { Project } from './schemas/project.schema'; import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { Query } from 'express-serve-static-core'; import * as mongoose from 'mongoose'; @Injectable() export class ProjectService { constructor( @InjectModel(Project.name) private projectModel: mongoose.Model<Project>, ) {} async findAll(query: Query): Promise<Project[]> { const resPerPage = 2; const currentPage = Number(query.page) || 1; const skip = resPerPage * (currentPage - 1); const keyword = query.keyword ? { title: { $regex: query.keyword, $options: 'i', }, } : {}; const projects = await this.projectModel .find({ ...keyword }) .limit(resPerPage) .skip(skip); return projects; } async create(project: Project): Promise<Project> { const data = Object.assign(project); const res = await this.projectModel.create(data); return res; } async findById(id: string): Promise<Project> { const isValidId = mongoose.isValidObjectId(id); if (!isValidId) { throw new BadRequestException('Please enter correct id.'); } const project = await this.projectModel.findById(id); if (!project) { throw new NotFoundException('Project not found.'); } return project; } async updateById(id: string, project: Project): Promise<Project> { const existProject = await this.projectModel.findByIdAndUpdate(id, project, { new: true, runValidators: true, }); if (!existProject) { throw new NotFoundException(`Student #${id} not found`); } return existProject; } async deleteById(id: string): Promise<Project> { const project = await this.projectModel.findByIdAndDelete(id); if (!project) { throw new NotFoundException(`Student #${id} not found`); } return project; } }
# fig_algae_boot # written by: sean Kinard # last edit: 2023-05-19 #---------------------------------------------------------------------------- # Setup #---------------------------------------------------------------------------- source('Rcal/00_setup_packages.R') algae_boot <- read_csv('Rout/algae_boot.csv') library(ggdark) #---------------------------------------------------------------------------- # Figure #---------------------------------------------------------------------------- plot_algae_boot <- algae_boot %>% mutate(treatment = str_replace_all(treatment, 'Open', 'Control')) %>% mutate( site=fct_relevel(site, c('Sub-Humid', 'Transition', 'Semi-Arid'))) %>% ggplot(aes(x=site, y=mu, color=treatment, fill=treatment, shape=treatment)) + #geom_line(linetype = 9, aes(group = treatment)) + geom_errorbar(aes(ymin=lower, ymax=upper), position = position_dodge(width=0.2), width=.18) + geom_point(size = 4, color='black', position = position_dodge(width=0.2)) + dark_theme_grey(base_size=18) + scale_y_log10() + scale_fill_manual(values=c('red', 'cyan')) + scale_color_manual(values=c('red', 'cyan')) + scale_shape_manual(values=c(21, 23)) + xlab(element_blank())+ ylab(expression(paste('Total Algae ( ', mu, 'g/cm)'))) + theme(legend.position = c(0.2, 0.82)) + theme(legend.background = element_rect(colour = 'grey50', fill = 'black', linetype='solid')) + theme(legend.title = element_blank()) #---------------------------------------------------------------------------- # Table #---------------------------------------------------------------------------- table_algae_boot <- algae_boot %>% mutate(Tre.Sig = ifelse(is.na(Tre.Sig), '', Tre.Sig)) %>% mutate(Algae=tormat(mu, 2), CI.95=paste('(', tormat(lower, 2), ', ', tormat(upper, 2), ')', sep='' )) %>% select(site, treatment, Algae, CI.95, Sit.Sig, Tre.Sig) %>% rename(Site=site, Treatment=treatment) write_csv(table_algae_boot, 'Rfig/table_algae_boot.csv') #---------------------------------------------------------------------------- # End fig_algae_boot
// import { useCallback } from 'react'; import { Button } from 'antd'; import { getNameByLang } from '../../../helpers/lang'; import { v4 } from 'uuid'; export const getBtnFunc = ({ childComps, updateState, defaultChildData, setChildComps, style }) => { const addOrDelete = payload => setChildComps(state => { const { type, data } = payload; if (type === 'add') { return [...state, defaultChildData(v4())]; } else { return state.filter(v => v.childId !== data); } }); const onAddClicked = id => { addOrDelete({ data: id, type: 'add' }); }; const onDeleteClicked = id => { addOrDelete({ data: id, type: 'delete' }); }; const { MAX_COUNT = 5, addContent = '添加', addContentEn = 'Add', deleteContent = '删除', deleteContentEn = 'Delete', addType = 'default', deleteType = 'default', lang, } = style; console.log(style); const addBtn = id => ( <Button onClick={onAddClicked} type={addType} style={{ ...style }} disabled={childComps.length >= MAX_COUNT} > {getNameByLang(lang, addContent, addContentEn)} </Button> ); const deleteBtn = id => ( <Button onClick={onDeleteClicked.bind(this, id)} type={deleteType} style={{ ...style }}> {getNameByLang(lang, deleteContent, deleteContentEn)} </Button> ); return { onAddClicked, onDeleteClicked, addBtn, deleteBtn }; };
function importTotalCasesR15 % This can run under MATLAB R2015a (added by Sherwood Samn) % This is the function for automating the download of the data % on the total COVID-19 cases from <ourworldindata.org>. % % The download part is added by Igor Podlubny (igor.podlubny@tuke.sk). % The code for parsing the data is the original code by Milan Batista, % the author of the package fitVirusCV19. % % Comment: the original Milan Batista's file 'ImportData' is a script; % this modification has the form of a function without arguments, % in order to keep all names of variables within this function; % they are not needed outside it. % write the results of parsing into the 'data' directory (MB 20/04/23) oldFolder = cd('data'); pwd %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% STEP 1: download the data and convert the file format %%% %%% added by Igor Podlubny, (igor.podlubny@tuke.sk) %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get the current date in YYYYMMDD format currentDateYYYYMMDD = strrep(datestr(date, 26), '/', ''); % set the filenames fileCSV = ['totalcases', currentDateYYYYMMDD, '.csv']; fileXLSX = ['totalcases', currentDateYYYYMMDD, '.xlsx']; % import data from <https://ourworldindata.org/coronavirus-source-data> % download the 'totalcase/csv' file tcFileCSV = websave(fileCSV,'https://covid.ourworldindata.org/data/ecdc/total_cases.csv'); % read the CSV file, and then save it to XLSX format TMPFILE = readtable(fileCSV); writetable(TMPFILE,fileXLSX); % we will write the results of parsing into the current directory; % in order to use the original Milan Batista's code, we put: path = pwd; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% STEP 2: Split the data for individual countries %%% %%% Milan Batista's original code for parsing %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Amin = 5; % data les than Amin will be deleted from file begining % get table T = readtable(fileXLSX); % get data A = T{:,2:end}; [nrow,ncol] = size(A); % table column names % The next 2 lines were commented out %name = string(T.Properties.VariableNames); %name = name(2:end)'; % and replaced by name =T.Properties.VariableNames; % start date date0 = datenum(T{1,1}); %datenum(txt{2,1},'dd.mm.yyyy'); %datenum('2019/12/31'); % end date %date1 = date0 + nrow - 1; %functions names % The next line was commented out % ffname = strings(ncol,1); % and replaced by ffname = cell(ncol,1); nn = 0; for n = 1:ncol % The next line was commented out % nname = name{n}; % and replaced by nname = name{n+1}; if strcmp('',nname) continue end nn = nn + 1; nname = strrep(nname,' ','_'); nname = strrep(nname,'-','_'); nname = strrep(nname,'''','_'); nname = strrep(nname,'(','_'); nname = strrep(nname,')','_'); fname = sprintf('getData%s.m',nname); fid = fopen(fullfile(path,fname),'w'); if fid < 0 fprintf('***Fail to open %s\n',fname); continue end fprintf('%d/%d country %s ...\n',ncol,n,nname); % The next line was commented out % ffname(nn) = nname; % and replaced by ffname{nn} = nname; fprintf(fid,'function [country,C,date0] = getData%s()\n',nname); fprintf(fid,'%%GETDATA%s Coronavirus data for %s\n',upper(nname),nname); fprintf(fid,'%% as reported by One World in Data\n'); fprintf(fid,'%% https://ourworldindata.org/coronavirus-source-data\n'); % The next line was commented out %fprintf(fid,'country = ''%s'';\n',strrep(name(n),' ','_')); % and replaced it by fprintf(fid,'country = ''%s'';\n',strrep(name{n+1},' ','_')); fprintf(fid,'C = [\n'); found = false; nday = 0; for m = 1:nrow if ~found && (isnan(A(m,n)) || A(m,n) == 0 || A(m,n) < Amin) nday = nday + 1; continue else found = true; end fprintf(fid,' %9d %% %s\n',A(m,n),datestr(date0 + m - 1)); end fprintf(fid,'%%<-------------- add new data here\n'); fprintf(fid,']'';\n'); % start date fprintf(fid,'date0=datenum(''%s'');\n',datestr(date0 + nday)); fprintf(fid,'end\n'); fclose(fid); %generete driver rutine fname = 'runAll.m'; fid = fopen(fullfile(path,fname),'w'); if fid < 0 fprintf('***Fail to open %s\n',fname); continue end fprintf(fid,'prn = ''off'';\n'); fprintf(fid,'plt = ''on'';\n'); for n = 1:nn fprintf(fid,'try\n'); % The next two lines were commented out % fprintf(fid,' fitVirusCV19(@getData%s,''prn'',prn,''jpg'',plt)\n',... % ffname(n)); % and replaced them by fprintf(fid,' fitVirusCV19(@getData%s,''prn'',prn,''jpg'',plt)\n',... ffname{n}); fprintf(fid,'end\n'); end fclose(fid); cd(oldFolder) end % function names = getCountryNames() % names = [ % "date" % "World" % "Afghanistan" % "Albania" % "Algeria" % "Andorra" % "Angola" % "Antigua and Barbuda" % "Argentina" % "Aruba" % "Armenia" % "Australia" % "Austria" % "Azerbaijan" % "Bahamas" % "Bahrain" % "Bangladesh" % "Barbados" % "Belarus" % "Belgium" % "Belize" % "Benin" % "Bermuda" % "Bhutan" % "Bolivia" % "Bosnia and Herzegovina" % "Brazil" % "Brunei" % "Bulgaria" % "Burkina Faso" % "Cambodia" % "Cameroon" % "Canada" % "Cape Verde" % "Cayman Islands" % "Central African Republic" % "Chad" % "Chile" % "China" % "Colombia" % "Congo" % "Costa Rica" % "Cote d'Ivoire" % "Croatia" % "Cuba" % "Cyprus" % "Czech Republic" % "Democratic Republic of Congo" % "Denmark" % "Djibouti" % "Dominica" % "Dominican Republic" % "Ecuador" % "Egypt" % "El Salvador" % "Equatorial Guinea" % "Eritrea" % "Estonia" % "Ethiopia" % "Faeroe Islands" % "Fiji" % "Finland" % "France" % "French Polynesia" % "Gabon" % "Gambia" % "Georgia" % "Germany" % "Ghana" % "Gibraltar" % "Greece" % "Greenland" % "Grenada" % "Guam" % "Guatemala" % "Guernsey" % "Guinea" % "Guyana" % "Haiti" % "Honduras" % "Hungary" % "Iceland" % "India" % "Indonesia" % "International" % "Iran" % "Iraq" % "Ireland" % "Isle of Man" % "Israel" % "Italy" % "Jamaica" % "Japan" % "Jersey" % "Jordan" % "Kazakhstan" % "Kenya" % "Kosovo" % "Kuwait" % "Kyrgyzstan" % "Laos" % "Latvia" % "Lebanon" % "Liberia" % "Libya" % "Liechtenstein" % "Lithuania" % "Luxembourg" % "Macedonia" % "Madagascar" % "Malaysia" % "Maldives" % "Malta" % "Mauritania" % "Mauritius" % "Mexico" % "Moldova" % "Monaco" % "Mongolia" % "Montenegro" % "Montserrat" % "Morocco" % "Mozambique" % "Myanmar" % "Namibia" % "Nepal" % "Netherlands" % "Netherlands Antilles" % "New Caledonia" % "New Zealand" % "Nicaragua" % "Niger" % "Nigeria" % "Norway" % "Oman" % "Pakistan" % "Palestine" % "Panama" % "Papua New Guinea" % "Paraguay" % "Peru" % "Philippines" % "Poland" % "Portugal" % "Qatar" % "Romania" % "Russia" % "Rwanda" % "Saint Lucia" % "Saint Vincent and the Grenadines" % "San Marino" % "Saudi Arabia" % "Senegal" % "Serbia" % "Seychelles" % "Singapore" % "Slovakia" % "Slovenia" % "Somalia" % "South Africa" % "South Korea" % "Spain" % "Sri Lanka" % "Sudan" % "Suriname" % "Swaziland" % "Sweden" % "Switzerland" % "Syria" % "Taiwan" % "Tanzania" % "Thailand" % "Timor" % "Togo" % "Trinidad and Tobago" % "Tunisia" % "Turkey" % "Turks and Caicos Islands" % "Uganda" % "Ukraine" % "United Arab Emirates" % "United Kingdom" % "United States" % "United States Virgin Islands" % "Uruguay" % "Uzbekistan" % "Vatican" % "Venezuela" % "Vietnam" % "Zambia" % "Zimbabwe" % ]; % end %
package org.sigmah.offline.handler; /* * #%L * Sigmah * %% * Copyright (C) 2010 - 2016 URD * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.sigmah.client.dispatch.DispatchListener; import org.sigmah.offline.dao.ValueAsyncDAO; import org.sigmah.offline.dispatch.AsyncCommandHandler; import org.sigmah.offline.dispatch.OfflineExecutionContext; import org.sigmah.shared.command.GetValue; import org.sigmah.shared.command.result.ValueResult; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.Inject; import com.google.inject.Singleton; import org.sigmah.shared.command.result.Authentication; /** * JavaScript implementation of {@link org.sigmah.server.handler.GetValueHandler}. * Used when the user is offline. * * @author Raphaël Calabro (rcalabro@ideia.fr) */ @Singleton public class GetValueAsyncHandler implements AsyncCommandHandler<GetValue, ValueResult>, DispatchListener<GetValue, ValueResult> { private final ValueAsyncDAO valueAsyncDAO; @Inject public GetValueAsyncHandler(ValueAsyncDAO valueAsyncDAO) { this.valueAsyncDAO = valueAsyncDAO; } @Override public void execute(GetValue command, OfflineExecutionContext executionContext, AsyncCallback<ValueResult> callback) { valueAsyncDAO.get(command, callback); } @Override public void onSuccess(GetValue command, ValueResult result, Authentication authentication) { if(result != null) { valueAsyncDAO.saveOrUpdate(command, result); } } }
/* Copyright 2023 DSTestRunner Contributors * * 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 utils import action.ActionResult import action.ActionStatus import action.ScreenData import config.Localization import config.MainConfig import config.ScreenshotConfig import pazone.ashot.Screenshot import pazone.ashot.comparison.ImageDiffer import java.awt.Graphics import java.awt.image.BufferedImage import java.io.File import java.nio.file.Files import java.nio.file.Paths import javax.imageio.ImageIO import javax.swing.GrayFilter class ImageUtils { fun compare(stepId: String, testId: String, parentId: String, screenData: ScreenData): Pair<ActionResult, ScreenData> { try { val currentScreenshotDir = ScreenshotConfig.currentScreenshotDir val templateScreenshotDir = ScreenshotConfig.templateScreenshotDir if (currentScreenshotDir.isEmpty() || templateScreenshotDir.isEmpty()) return Pair(ActionResult(ActionStatus.BROKEN, Localization.get("ScreenshotCompare.ScreenshotPathsNotSpecified")), screenData) val fileName = "${parentId.replace(".", "_")}_${stepId}" val templateImageRelativePath = Paths.get(testId, "${fileName}.png") val currentImageRelativePath = Paths.get(MainConfig.sessionId, testId, "${fileName}.png") val markedImageRelativePath = Paths.get(MainConfig.sessionId, testId, "${fileName}_marked.png") val currentImageFile = Paths.get(currentScreenshotDir, currentImageRelativePath.toString()).toFile() val templateImageFile = Paths.get(templateScreenshotDir, templateImageRelativePath.toString()).toFile() val currentImage = screenData.getCurrentImage() markIgnoredAreas(currentImage) saveImage(currentImage.image, currentImageFile) screenData.currentImagePath = currentImageRelativePath.toString() if (templateImageFile.exists()) { val templateImage = Screenshot(readImage(templateImageFile)) templateImage.coordsToCompare = currentImage.coordsToCompare templateImage.ignoredAreas = currentImage.ignoredAreas val imageDiff = ImageDiffer().makeDiff(currentImage, templateImage) if (imageDiff.hasDiff() && imageDiff.diffSize > ScreenshotConfig.allowableDifference) { screenData.templateImage = templateImage.image screenData.templateImagePath = templateImageRelativePath.toString() val markedImage = imageDiff.markedImage val markedImageFile = Paths.get(currentScreenshotDir, markedImageRelativePath.toString()).toFile() saveImage(markedImage, markedImageFile) screenData.markedImage = markedImage screenData.markedImagePath = markedImageRelativePath.toString() return Pair(ActionResult(ActionStatus.BROKEN, Localization.get("ScreenshotCompare.CurrentScreenshotNotMatchReference")), screenData) } } else { if (ScreenshotConfig.saveTemplateIfMissing) { saveImage(currentImage.image, templateImageFile) screenData.templateImagePath = templateImageRelativePath.toString() return Pair(ActionResult(ActionStatus.BROKEN, Localization.get("ScreenshotCompare.ReferenceScreenshotMissingWithSave")), screenData) } return Pair(ActionResult(ActionStatus.BROKEN, Localization.get("ScreenshotCompare.ReferenceScreenshotMissing")), screenData) } return Pair(ActionResult(ActionStatus.PASSED, null), screenData) } catch (e: Exception) { return Pair(ActionResult(ActionStatus.BROKEN, Localization.get("ScreenshotCompare.GeneralError", e.message), e.stackTraceToString()), screenData) } } fun saveImage(bufferedImage: BufferedImage, output: File) { Files.createDirectories(output.toPath()) ImageIO.write(bufferedImage, "png", output) } private fun readImage(input: File): BufferedImage { return ImageIO.read(input) } private fun markIgnoredAreas(screenshot: Screenshot) { if (screenshot.ignoredAreas.isEmpty()) return val graphics: Graphics = screenshot.image.createGraphics() screenshot.ignoredAreas.forEach { area -> try { val ignoredImage = screenshot.image.getSubimage(area.x, area.y, area.width, area.height) graphics.drawImage(GrayFilter.createDisabledImage(ignoredImage), area.x, area.y, null) } catch (e: Exception) { e.printStackTrace() } } graphics.dispose() } }
import { Directive, Input } from '@angular/core'; import { AbstractControl, FormGroup, NG_VALIDATORS, ValidationErrors } from '@angular/forms'; @Directive({ selector: '[appMatchPassword]', providers: [{provide: NG_VALIDATORS, useExisting: ValidMatchpasswordDirective, multi: true}] }) export class ValidMatchpasswordDirective { @Input('appMatchPassword') matchPassword: string[] = []; validate(formGroup: FormGroup): ValidationErrors | null { return this.match(this.matchPassword[0], this.matchPassword[1])(formGroup); } match(controlName: string, checkControlName: string) { return (formGroup: FormGroup) => { const control = formGroup.controls[controlName]; const checkControl = formGroup.controls[checkControlName]; if (checkControl?.errors && !checkControl.errors['matching']) { return null; } if (control?.value !== checkControl?.value) { checkControl?.setErrors({ 'matching': true }); return { 'matching': true }; } else { checkControl?.setErrors(null); return null; } }; } }
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class StoreProgramRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ 'title'=>'required|unique:programs,title|string', 'slogan'=>'required|unique:programs,slogan|string', 'price'=>'numeric|required|min:0', 'discount'=>'numeric|required|min:0|max:100', 'duration'=>'numeric|required|min:0|max:12', 'limit'=>'numeric|required|min:1|max:100', ]; } public function attributes() { return [ 'title'=>__("keywords.title"), 'slogan'=>__("keywords.slogan"), 'price'=>__("keywords.price"), 'discount'=>__("keywords.discount"), 'duration'=>__("keywords.durationInMonth"), 'limit'=>__("keywords.limit"), ]; } }
/* * Project: openMDX, http://www.openmdx.org/ * Description: Interaction Specs * Owner: the original authors. * * This software is published under the BSD license as listed below. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the openMDX team nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ------------------ * * This product includes software developed by other organizations as * listed in the NOTICE file. */ package org.openmdx.base.resource; import java.io.ObjectStreamException; import javax.resource.cci.InteractionSpec; import org.openmdx.base.resource.cci.RestFunction; import org.openmdx.base.resource.spi.MethodInvocationSpec; import org.openmdx.base.resource.spi.RestInteractionSpec; /** * Interaction Specs */ public class InteractionSpecs { /** * Constructor * * @param retainValues CREATE and PUT return updates if {@code retainValues} is {@code true} */ private InteractionSpecs( boolean retainValues ){ this.CREATE = new RestInteractionSpec( RestFunction.POST, retainValues ? InteractionSpec.SYNC_SEND_RECEIVE : InteractionSpec.SYNC_SEND ); this.INVOKE = new RestInteractionSpec( RestFunction.POST, InteractionSpec.SYNC_SEND_RECEIVE ); this.GET = new RestInteractionSpec( RestFunction.GET, InteractionSpec.SYNC_SEND_RECEIVE ); this.VERIFY = new RestInteractionSpec( RestFunction.GET, InteractionSpec.SYNC_SEND ); this.UPDATE = new RestInteractionSpec( RestFunction.PUT, retainValues ? InteractionSpec.SYNC_SEND_RECEIVE : InteractionSpec.SYNC_SEND ); this.MOVE = new RestInteractionSpec( RestFunction.PUT, InteractionSpec.SYNC_SEND_RECEIVE ); this.DELETE = new RestInteractionSpec( RestFunction.DELETE, InteractionSpec.SYNC_SEND ); } /** * A {@link RestFunction#POST} Object Creation Interaction Specification */ public final RestInteractionSpec CREATE; /** * A {@link RestFunction#POST} Method Invocation Interaction Specification */ public final RestInteractionSpec INVOKE; /** * A {@link RestFunction#GET} Object Retrieval Interaction Specification */ public final RestInteractionSpec GET; /** * A {@link RestFunction#GET} Object Verification Interaction Specification */ public final RestInteractionSpec VERIFY; /** * A {@link RestFunction#PUT} Object Update Interaction Specification */ public final RestInteractionSpec UPDATE; /** * A {@link RestFunction#PUT} Object Update Interaction Specification */ public final RestInteractionSpec MOVE; /** * A {@link RestFunction#DELETE} Object Removal Interaction Specification */ public final RestInteractionSpec DELETE; /** * CREATE and PUT return updates */ private static final InteractionSpecs RETAINING_VALUES = new InteractionSpecs(true); /** * CREATE and PUT return nothing */ private static final InteractionSpecs NOT_RETAINING_VALUES = new InteractionSpecs(false); /** * REST {@code InteractionSpecs} factory method. * * @param retainValues CREATE and PUT return updates if {@code retainValues} is {@code true} * * @return an {@code InteractionSpecs} instance */ public static InteractionSpecs getRestInteractionSpecs( boolean retainValues ){ return retainValues ? RETAINING_VALUES : NOT_RETAINING_VALUES; } /** * Method invocation specification factory method. * * @param methodName the name of the method to be invoked * @param query the execute method waits for the reply if query is {@code true} * * @return a new {@code InteractionSpec} instance */ public static InteractionSpec newMethodInvocationSpec( String methodName, int interactionVerb ){ return new MethodInvocationSpec( methodName, interactionVerb ); } /** * Test whether the {@code InteractionSpec} is logically {@code null} * * @param interactionSpec the {@code InteractionSpec} to be tested * * @return {@code true} if the {@code InteractionSpec} is logically {@code null} */ public static boolean isNull( InteractionSpec interactionSpec ){ return interactionSpec == null || interactionSpec == NULL; } //---------------------------------------------------------------------------------- // Class NULL-InteractionSpec //---------------------------------------------------------------------------------- /** * The {@code NULL} interaction spec */ public static final InteractionSpec NULL = new InteractionSpec(){ /** * Implements {@code Serializable} */ private static final long serialVersionUID = -6765662708933344857L; /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "NULL"; } private Object readResolve( ) throws ObjectStreamException { return NULL; } }; }
import { zip } from 'lodash'; import path from 'path'; import { sortFiles, SortOptions } from './cmd.sort'; import { traverseDirectory } from "./directory"; import { batchNewName, getNewName, RenameOptions, safeRename } from './rename'; export async function commandRename(dir: string, options: RenameOptions) { const { files } = await traverseDirectory(dir, options.recursive); await Promise.all(files.map(file => { const newPath = path.join(path.dirname(file), getNewName(file, options)); if (file === newPath) return Promise.resolve(); if (options.dryRun) { console.log(`Would rename: ${file} to ${newPath}`); return Promise.resolve(); } else { return safeRename(file, newPath) .then(() => console.log(`Renamed: ${file} to ${newPath}`)) .catch(err => console.error(`Error processing file ${file}: ${err}`)); } })); } export async function commandRenameWithRule(batchRule: string, dir: string, options: SortOptions & RenameOptions) { const { files } = await traverseDirectory(dir, options.recursive); const filesWithStats = await sortFiles(files, options); const oldPaths = filesWithStats.map(f => f.file); const newNames = batchNewName(oldPaths, batchRule); const pathsMapping = zip(oldPaths, newNames); for (let [oldPath, newName] of pathsMapping) { let newPath = path.join(path.dirname(oldPath), newName); if (oldPath === newPath) continue; if (options.dryRun) { console.log(`Would rename: ${oldPath} to ${newPath}`); } else { safeRename(oldPath, newPath) .then(() => console.log(`Renamed: ${oldPath} to ${newPath}`)) .catch(err => console.error(`Error processing file ${oldPath}: ${err}`)); } } }
//Project UID db1f506d06d84ab787baf250c265e24e #include <iostream> #include <string> #include <cassert> #include <utility> #include <cmath> #include <map> #include <set> #include "csvstream.h" using namespace std; class Classifier{ private: int total_posts = 0; //done int total_unique_words; //done string train_file; string test_file; map<string, double> posts_with_word; //done map<string, double> posts_with_label; //done map<pair<string, string>, double> label_with_word; map<string, double> log_priors; // done map<pair<string, string>, double> log_likelihoods; public: set<string> unique_words(const string &str); void determine_log_likelihood(); void determine_log_prior(); void read_in(); void train_classifier(const string &train_file_in); void test_classifier(const string &test_file_in); int get_total_posts(); int get_unique_words(); void print_debug_output(); }; int Classifier::get_total_posts(){ return total_posts; } int Classifier::get_unique_words(){ return total_unique_words; } set<string> Classifier::unique_words(const string &str){ // Fancy modern C++ and STL way to do it istringstream source{str}; return {istream_iterator<string>{source}, istream_iterator<string>{}}; } void Classifier::determine_log_likelihood(){ double log_likelihood_curr; for (auto &node:label_with_word){ log_likelihood_curr = log(node.second / posts_with_label.find((node.first).first)->second); log_likelihoods[node.first] = log_likelihood_curr; } } void Classifier::determine_log_prior(){ double current_prior = 0; for (auto &label:posts_with_label){ current_prior = log(double(label.second) / total_posts); log_priors[label.first] = current_prior; } } void Classifier::read_in(){ csvstream train_in(train_file); map<string, string> row; pair<string, string> label_word; while (train_in >> row){ label_word.first = row["tag"]; posts_with_label[row["tag"]] += 1; for (auto &word:unique_words(row["content"])){ posts_with_word[word] += 1; total_unique_words++; label_word.second = word; label_with_word[label_word] += 1; } total_posts++; } } void Classifier::train_classifier(const string &train_file_in){ train_file = train_file_in; read_in(); determine_log_prior(); determine_log_likelihood(); } void Classifier::test_classifier(const string &test_file_in){ test_file = test_file_in; csvstream test_in(test_file); map<string, string> row; cout << "test data:" << endl; while(test_in >> row){ //creating map of each label's log probability for a particular post map<string, double> log_probabilities; for(auto &label:posts_with_label){ double likelihood_sum = 0; double log_probabilty = 0; for(auto &word:unique_words(row["content"])){ pair<string, string> label_word; label_word.first = label.first; label_word.second = word; if (log_likelihoods[label_word] != 0){ likelihood_sum += log_likelihoods[label_word]; } else if (posts_with_word[word] != 0){ likelihood_sum += log(posts_with_word[word] / total_posts); } else{ likelihood_sum += log(1.0 / total_posts); } } log_probabilty = log_priors[label.first] + likelihood_sum; log_probabilities[label.first] = log_probabilty; } double current_max_lp = log_probabilities.begin()->second; string current_key = log_probabilities.begin()->first; for(auto &lp:log_probabilities){ if (lp.second > current_max_lp){ current_key = lp.first; current_max_lp = lp.second; } } cout << " correct = " << row["tag"] << ", predicted = " << current_key << ", log-probability score = " << log_probabilities[current_key] << endl; cout << " content = " << row["content"] << endl << endl; } } void Classifier::print_debug_output(){ csvstream train_in(train_file); map<string, string> row; cout << "training data:" << endl; while (train_in >> row){ cout << " label = " << row["tag"] << ", "; cout << "content = " << row["content"] << endl; } cout << "trained on " << total_posts << " examples" << endl; cout << "vocabulary size = " << posts_with_word.size() << endl << endl; cout << "classes:" << endl; for (auto &element:log_priors){ cout << " " << element.first << ", " << posts_with_label[element.first] << " examples, log-prior = " << element.second << endl; } cout << "classifier parameters:" << endl; for(auto &element:label_with_word){ cout << " " << element.first.first << ":" << element.first.second << ", count = " << element.second << ", log-likelihood = " << log_likelihoods[element.first] << endl; } cout << endl; } //end classifier class functions int main(int argc, char* argv[]){ const string train_file = argv[1]; const string test_file = argv[2]; string debug = ""; //Used to cast debug argument cout.precision(3); //checking arguments if (argc == 4){ debug = argv[3]; if (debug == "--debug"){ assert(true); } else{ cout << "Usage: main.exe TRAIN_FILE TEST_FILE [--debug]" << endl; return -1; } } else if(argc == 3){ assert(true); } else{ cout << "Usage: main.exe TRAIN_FILE TEST_FILE [--debug]" << endl; return -1; } Classifier c1; c1.train_classifier(train_file); if(debug == "--debug"){ c1.print_debug_output(); } else{ cout << "trained on " << c1.get_total_posts() << " examples" << endl << endl; } c1.test_classifier(test_file); return 0; }
const asyncHandler = require("express-async-handler"); const bcrypt = require("bcryptjs"); const User = require("../models/userModel"); // @desc register new user const registerUser = asyncHandler(async (req, res) => { console.log(req.body); const { name, email, password } = req.body; if (!email || !password || !name) { res.status(400); throw new Error("Please include all field"); } // find user already exist const userExist = await User.findOne({ email, }); if (userExist) { res.status(400); throw new Error("user already exist"); } // hash password const salt = await bcrypt.genSalt(10); const hashPassword = await bcrypt.hash(password, salt); // create user const user = await User.create({ name, email, password: hashPassword, }); if (user) { res.status(201).json({ _id: user._id, name: user.name, email: user.email, }); } else { res.status(400); throw new Error("Invalid user data"); } }); const loginUser = asyncHandler(async (req, res) => { const { email, password } = req.body; const user = await User.findOne({ email }); // compare password with entered and stored if (user && (await bcrypt.compare(password, user.password))) { } res.send("login route"); }); module.exports = { registerUser, loginUser, };
import React from "react"; import styles from "./SingleApplication.module.css"; import { formatDate, formatCurrency } from "./utils"; const SingleApplication = ({ application }) => { return ( <div className={styles.SingleApplication} data-testid="application"> <div className={styles.cell}> <sub>Company</sub> {application.company} </div> <div className={styles.cell}> <sub>Name</sub> {application.first_name} {application.last_name} </div> <div className={styles.cell}> <sub>Email</sub> {application.email} </div> <div className={styles.cell}> <sub>Loan Amount</sub> {formatCurrency(application.loan_amount)} </div> <div className={styles.cell}> <sub>Application Date</sub> {formatDate(application.date_created)} </div> <div className={styles.cell}> <sub>Expiry date</sub> {formatDate(application.expiry_date)} </div> </div> ); }; export default SingleApplication;
package com.cjh.scanlogin.config; import com.cjh.scanlogin.service.JwtTokenService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Objects; /** * Token 校验过滤器 * * @author Guoqing */ public class AuthenticationTokenFilter extends OncePerRequestFilter { @Autowired private JwtTokenService jwtTokenService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest httpRequest = (HttpServletRequest) request; String authToken = httpRequest.getHeader("Authorization"); if (Objects.isNull(authToken)) { chain.doFilter(request, response); return; } String username = StringUtils.isNotBlank(authToken) ? jwtTokenService.getUsernameFromToken(authToken) : null; if (username != null && SecurityContextHolder.getContext().getAuthentication() == null && !jwtTokenService.isTokenExpired(authToken)) { UserDetails userDetails = jwtTokenService.getUserDetails(authToken); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest)); SecurityContextHolder.getContext().setAuthentication(authentication); } chain.doFilter(request, response); } }
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-3"> <div class="card"> <div class="card-header"> home page main setting </div> @include('layouts.side-card') </div> </div> <div class="col-md-9"> <div class="card"> <div class="card-header">home page setting</div> <div class="card-body"> <form action="{{ route('home.store') }}" method="POST" enctype="multipart/form-data"> @csrf <div class="form-group mt-3" > <label for="">title</label> <input type="text" class="form-control" value="{{ old('title')}}" name="title"> @error('title') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group mt-3"> <label for="">subject</label> <input type="text" class="form-control" value="{{ old('subject')}}" name="subject"> @error('subject') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group mt-3"> <label for="">position</label> <input type="text" class="form-control" value="{{ old('job')}}" name="job"> @error('job') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group mt-3"> <label for="">description</label> <textarea type="text" class="form-control" value="{{ old('description')}}" name="description"></textarea> @error('description') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group mt-3"> <label for="">link</label> <input type="text" class="form-control" value="{{ old('link')}}" name="link"> @error('link') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group mt-3"> <label for="">pictrue</label> <input type="file" class="form-control" name="image"> @error('image') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group mt-3"> <button type="submit" class="btn btn-save px-5">save</button> </div> </form> </div> </div> </div> </div> </div> @endsection @section('js') {{-- <script> function destroyUser(event,id){ event.preventDefault(); document.querySelector('#userdelete-'+id).submit(); } </script> --}} @endsection
import { useState, useEffect } from 'react'; import { getTrandingMovie } from 'components/Api/api'; import { useLocation } from 'react-router-dom'; import { MoviesWrapper, MoviesItem, MoviesNavLink, } from '../Movies/Movies.styled'; const MoviesList = () => { const [movies, setMovies] = useState([]); const location = useLocation(); useEffect(() => { getTrandingMovie().then(setMovies); }, []); if (!movies) { return <MoviesWrapper>Sorry. Don't found this films</MoviesWrapper>; } return ( <> {' '} <MoviesWrapper> {movies.map(movie => { return ( <MoviesItem key={movie.id}> <MoviesNavLink to={`/movies/${movie.id}`} state={{ from: location }} > {movie.title || movie.name} </MoviesNavLink> </MoviesItem> ); })} </MoviesWrapper> </> ); }; export default MoviesList; // import { getTrandingMovie } from 'components/Api/api'; // import { useState, useEffect } from 'react'; // import { useLocation } from 'react-router-dom'; // import { // MoviesWrapper, // MoviesItem, // MoviesNavLink, // } from '../Movies/Movies.styled'; // const MoviesList = () => { // const [movies, setMovies] = useState([]); // const location = useLocation(); // getTrandingMovie().then(response => { // const result = response.data.results; // console.log(result); // setMovies([...result]); // }); // console.log('hi'); // // useEffect(() => { // // getTrandingMovie().then(response => { // // const result = response.data.results; // // console.log(result); // // setMovies([...result]); // // }); // // }, []); // // console.log('movies:', movies); // // if (movies === []) { // // return; // // } // return ( // ); // }; // export default MoviesList; // <MoviesWrapper> // {movies.map(movie => ( // <MoviesItem key={movie.id}> // <NavLink to={`/movies/${movie.id}`} state={{ from: location }}> // {movie.name || movie.title} // </NavLink> // </MoviesItem> // ))} // </MoviesWrapper>;
# MIT License # Copyright (c) 2022 I. Ahmad # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, Optional from pspl.parser.errors import PSPLParserError, IdentifierAlreadyDefined from pspl.parser import generator from pspl import lexer import rply if TYPE_CHECKING: from rply.lexer import Lexer from rply.parser import LRParser from rply.token import SourcePosition __all__ = ( 'RuntimeState', ) class RuntimeState: """Internal state for PSPL runtime. This class acts as a state for passing important runtime data into parser production rules. This class is not meant to be used in normal cases and is initialized and used internally. Attributes ---------- source: :class:`str` The source code or file name. file: :class:`bool` Whether :attr:`source` is a file name. """ def __init__( self, *, source: str, file: bool = False, ) -> None: self.source = source self.file = file self.type_defs: Dict[str, Any] = {} self.defs: Dict[str, Any] = {} self.constant_defs: Dict[str, Any] = {} @property def filename(self) -> Optional[str]: """Optional[:class:`str`]: The name of file from which the code is being red. None is returned if the source is not a file and is the raw source code. """ return self.source if self.file else None def add_type_def(self, ident: str, tp: Any) -> None: self.type_defs[ident] = tp def get_type_def(self, ident: str) -> Any: return self.type_defs[ident] def remove_type_def(self, ident: str) -> Any: return self.type_defs.pop(ident) def add_def( self, ident: str, val: Any, *, constant: bool = False, source_pos: Optional[SourcePosition] = None, ) -> None: if ident in self.constant_defs: raise IdentifierAlreadyDefined(source_pos, ident) if constant: self.constant_defs[ident] = val else: self.defs[ident] = val def get_def(self, ident: str) -> Any: if ident in self.constant_defs: return self.constant_defs[ident] return self.defs[ident] def remove_def(self, ident: str) -> Any: return self.defs.pop(ident) def _get_lexer(self) -> Lexer: lg = rply.LexerGenerator() for token, pattern in lexer.TOKENS.items(): lg.add(token, pattern) for pattern in lexer.IGNORED_TOKENS: lg.ignore(pattern) return lg.build() def _get_parser(self) -> LRParser: gen = generator.get() return gen.build() def log_error( self, error_type: str, error_message: str, source_pos: Optional[SourcePosition] = None, ) -> None: if source_pos: print(f'At line {source_pos.lineno}, column {source_pos.colno}, index {source_pos.idx}:') print(f'{error_type}: {error_message}') def exec(self) -> None: """Start the execution process.""" src = self.source if self.file: with open(src, 'r') as f: src = f.read() lexer = self._get_lexer() parser = self._get_parser() tokens = lexer.lex(src) try: parser.parse(tokens, state=self).eval() # type: ignore except (rply.LexingError, PSPLParserError) as err: if isinstance(err, rply.LexingError): self.log_error( error_type='SyntaxError', error_message='Invalid syntax', source_pos=err.source_pos, ) else: self.log_error( error_type=err.__class__.__name__, error_message=err.message, source_pos=err.source_pos, )
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[cfg(test)] mod mock; #[cfg(test)] mod tests; // #[cfg(feature = "runtime-benchmarks")] // mod benchmarking; #[frame_support::pallet] pub mod pallet { use frame_support::{ dispatch::DispatchResultWithPostInfo, pallet_prelude::*, traits::Get }; use frame_system::pallet_prelude::*; use sp_std::vec::Vec; /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] pub trait Config: frame_system::Config { type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; type StringLimit: Get<u32>; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet<T>(_); #[pallet::storage] #[pallet::getter(fn proofs)] pub type Proofs<T: Config> = StorageMap<_, Blake2_128Concat, Vec<u8>, (T::AccountId, T::BlockNumber)>; #[pallet::event] #[pallet::metadata(T::AccountId = "AccountId")] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { ClaimCreated(T::AccountId, Vec<u8>), ClaimRevoked(T::AccountId, Vec<u8>), ClaimTransfered(T::AccountId, Vec<u8>), } // Errors inform users that something went wrong. #[pallet::error] pub enum Error<T> { ProofAlreadyExist, ClaimNotExist, NotClaimOwner, BadClaimLength, } #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {} // Dispatchable functions allows users to interact with the pallet and invoke state changes. // These functions materialize as "extrinsics", which are often compared to transactions. // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl<T: Config> Pallet<T> { #[pallet::weight(0)] pub fn create_claim( origin: OriginFor<T>, claim: Vec<u8> ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ensure!(claim.len() <= T::StringLimit::get() as usize, Error::<T>::BadClaimLength); ensure!(!Proofs::<T>::contains_key(&claim), Error::<T>::ProofAlreadyExist); Proofs::<T>::insert( &claim, (sender.clone(), frame_system::Pallet::<T>::block_number()) ); Self::deposit_event(Event::ClaimCreated(sender, claim)); Ok(().into()) } } }
"use client"; import type { z } from "zod"; import React, { useEffect, useState, useTransition } from "react"; import { notFound, useParams } from "next/navigation"; import { zodResolver } from "@hookform/resolvers/zod"; import { ClipboardList, PlusIcon, SaveIcon, Trash } from "lucide-react"; import { useForm } from "react-hook-form"; import { ActionEnum, EntityEnum } from "types/permissions"; import { Button, Input } from "@acme/ui"; import { productCategoryFormSchema } from "@acme/validators"; import { AlertModal } from "~/components/modals/alert-modal"; import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "~/components/ui/form"; import { Heading } from "~/components/ui/heading"; import { useMutation } from "~/hooks/use-mutation"; import { useHasPermissions } from "~/lib/utils"; import { api } from "~/trpc/react"; type ProductCategoryFormValues = z.infer<typeof productCategoryFormSchema>; const ProductCategoryDetailPage = () => { const { productCategoryId } = useParams(); const isDetails = !!(productCategoryId && productCategoryId !== "new"); const [isDeleting, setIsDeleting] = useState(false); const [loading, startTransition] = useTransition(); const [canCreate, canDelete, canUpdate] = useHasPermissions( [EntityEnum.PRODUCTCATEGORY, ActionEnum.CREATE], [EntityEnum.PRODUCTCATEGORY, ActionEnum.DELETE], [EntityEnum.PRODUCTCATEGORY, ActionEnum.UPDATE], ); const deleteProductCategory = useMutation( EntityEnum.PRODUCTCATEGORY, "delete", "/product-categories", ); const updateProductCategory = useMutation( EntityEnum.PRODUCTCATEGORY, "update", ); const createProductCategory = useMutation( EntityEnum.PRODUCTCATEGORY, "create", "/product-categories", ); const { data: productCategory, isLoading } = api.productCategory.byId.useQuery({ id: isDetails ? +productCategoryId : 0, }); if (isDetails && !isLoading && !productCategory) notFound(); const action = isDetails ? "Opslaan" : "Toevoegen"; const form = useForm<ProductCategoryFormValues>({ resolver: zodResolver(productCategoryFormSchema), defaultValues: { title: "", }, }); useEffect(() => { if (productCategory) { form.reset(productCategory); } }, [productCategory, form]); const onSubmit = async (data: ProductCategoryFormValues) => { startTransition(async () => { if (isDetails && canUpdate) { await updateProductCategory({ ...data, id: +productCategoryId }); } else if (canCreate) { await createProductCategory(data); } }); }; const title = form.watch("title"); useEffect(() => { form.setValue("slug", title.toLocaleLowerCase().replaceAll(" ", "-")); }, [title, form]); return ( <> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="w-full space-y-4" > <Heading title={ isDetails ? "Productcategorie aanpassen" : "Productcategorie toevoegen" } description={ isDetails ? "Bekijk productcategorie gegevens en pas eventueel aan" : "Voeg een nieuw productcategorie toe" } > <div className="flex space-x-2"> {canDelete && ( <Button variant="outline" disabled={isLoading || loading} type="button" onClick={() => setIsDeleting(true)} > <Trash className="mr-1 w-4" /> <span className="max-md:hidden">Verwijderen</span> </Button> )} <Button disabled={isLoading || loading}> {isDetails ? ( <SaveIcon className="mr-1 w-4" /> ) : ( <PlusIcon className="mr-1 w-4" /> )} <span className="max-md:hidden">{action}</span> </Button> </div> </Heading> <div className="grid grid-cols-1 gap-4"> <Card> <CardHeader> <CardTitle className="flex items-center"> <ClipboardList className="mr-2 w-5" /> Algemene informatie </CardTitle> </CardHeader> <CardContent className="grid grid-cols-1 gap-4 md:grid-cols-2"> <FormField control={form.control} name="title" render={({ field }) => ( <FormItem> <FormLabel>Titel</FormLabel> <FormControl> <Input disabled={loading} placeholder="Titel" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="slug" render={({ field }) => ( <FormItem> <FormLabel>Slug</FormLabel> <FormControl> <Input disabled={loading} placeholder="Item slug" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> </CardContent> </Card> </div> </form> </Form> <AlertModal isOpen={isDeleting} onClose={() => setIsDeleting(false)} onConfirm={() => deleteProductCategory(+productCategoryId)} loading={false} /> </> ); }; export default ProductCategoryDetailPage;
package factory.store; import factory.pizza.Pizza; import factory.pizza.nystyle.*; /** * Modeled a store that sells pizza with the NY style */ public class NYPizzaStore extends PizzaStore{ @Override protected Pizza createPizza(String type) { return switch (type) { case "cheese" -> new NYStyleCheesePizza(); case "pepperoni" -> new NYStylePepperoniPizza(); case "veggie" -> new NyStyleVeggiePizza(); default -> null; }; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract validator { using SafeMath for uint256; ERC20 protonToken = ERC20(0x29794fCC95837D24b89906EB202F3408C39826bC); struct site { address nominee; string comment; uint256 yesVotes; uint256 noVotes; mapping(address => bool) votedYes; mapping(address => bool) votedNo; } mapping(string => site) public sitelist; event siteAdded(address indexed _nominee, string indexed _url, string indexed _comment); event voted(address indexed _validator, bool indexed _isScam); function addSite(string memory _url, string memory _comment) public { site storage s = sitelist[_url]; require(bytes(s.comment).length == 0,"Site Already Added"); require(protonToken.balanceOf(msg.sender) >= 1, "Token Balance too low. Required minimum of 1 Proton"); s.nominee = msg.sender; s.comment = _comment; emit siteAdded(msg.sender, _url, _comment); } function castVote(string memory _url, bool _isScam) public onlyValidator { site storage s = sitelist[_url]; require(!s.votedYes[msg.sender] && !s.votedNo[msg.sender], "Already Voted"); if(_isScam){ s.yesVotes += protonToken.balanceOf(msg.sender); s.votedYes[msg.sender] = true; } else { s.noVotes += protonToken.balanceOf(msg.sender); s.votedNo[msg.sender] = true; } emit voted(msg.sender, _isScam); } function getVoteStatus(string memory _url) public view returns (uint, bool) { site storage s = sitelist[_url]; require(s.yesVotes > 0 || s.noVotes > 0, "No Votes Registered Yet"); uint256 totalVotes = s.yesVotes.add(s.noVotes); uint256 votePercent = s.yesVotes.mul(10 ** 2).div(totalVotes); //uint256 votePercent = SafeMath.mul(SafeMath.div(s.yesVotes, SafeMath.add(s.yesVotes, s.noVotes)), 100); bool voteStatus; if(votePercent > 50){ voteStatus = true; }else{ voteStatus = false; } return (votePercent, voteStatus); } // function executePenalise() public { // } // function executeReward() public { // } modifier onlyValidator { require(protonToken.balanceOf(msg.sender) >= 25, "Token Balance too low. Required minimum of 25 Protons"); _; } }
import { useTranslation } from 'react-i18next'; import { Article } from '../../model/types/article'; import cls from './ArticleList.module.scss'; import { classNames } from '@/shared/lib/classNames/classNames'; import { ArticleListItem } from '../ArticleListItem/ArticleListItem'; import { ArticleListItemSkeleton } from '../ArticleListItem/ArticleListItemSkeleton'; import { Text, TextSize } from '@/shared/ui/Text'; import { FC, HTMLAttributeAnchorTarget, memo, useEffect, useRef, useState } from 'react'; import { Virtuoso, VirtuosoGrid, VirtuosoGridHandle } from 'react-virtuoso'; import { ARTICLE_LIST_ITEM_LOCALSTORAGE_ID } from '@/shared/const/localStorage'; import { Page } from '@/widgets/Page/ui/Page/Page'; import { ArticleView } from '../../model/consts/consts'; interface ArticleListProps { className?: string; articles: Article[]; isLoading?: boolean; view?: ArticleView; target?: HTMLAttributeAnchorTarget; onLoadNextPart?: () => void; } // const getSkeletons = () => { // return new Array(3) // .fill(0) // .map((_, index) => ( // <ArticleListItemSkeleton className={cls.card} key={index} view={ArticleView.BIG}/> // )) // } const getSkeletons = (view: ArticleView) => { return new Array(view === ArticleView.SMALL ? 9 : 3) .fill(0) .map((item, index) => ( <ArticleListItemSkeleton className={cls.card} key={index} view={view} /> )) } export const ArticleList = (props: ArticleListProps) => { const { className, articles, isLoading, view = ArticleView.SMALL, target, onLoadNextPart } = props; const { t } = useTranslation(); const [selectedArticleId, setSelectedArticleId] = useState(1); const VirtuosoGridRef = useRef<VirtuosoGridHandle>(null); useEffect(() => { const paged = sessionStorage.getItem(ARTICLE_LIST_ITEM_LOCALSTORAGE_ID) || 1; setSelectedArticleId(+paged) }, []) useEffect(() => { let timeoutId: NodeJS.Timeout; if (view === 'SMALL') { timeoutId = setTimeout(() => { if (VirtuosoGridRef.current) { VirtuosoGridRef.current.scrollToIndex(selectedArticleId); } }, 100) } return () => clearTimeout(timeoutId); }, [selectedArticleId, view]) // const renderArticle = (index: number, article: Article) => ( // <ArticleListItem // article={article} // view={view} // className={cls.card} // key={article.id} // target={target} // index={index} // /> // ); const renderArticle = (article: Article) => ( <ArticleListItem article={article} view={view} className={cls.card} key={article.id} target={target} /> ); // const Footer = memo(() => { // if(isLoading){ // return ( // <div className={cls.skeleton}> // {getSkeletons()} // </div> // ) // } // return null; // }) if (!isLoading && !articles.length) { return ( <div className={classNames(cls.ArticleList, {}, [className, cls[view]])}> <Text size={TextSize.L} title={t('Статьи не найдены')} /> </div> ) } const ItemContainerComp: FC<{ height: number, width: number; index: number }> = ({ height, width, index }) => { return ( <div className={cls.ItemContainer}> <ArticleListItemSkeleton key={index} view={view} className={cls.card} /> </div> ) } console.log(view) return ( <div className={classNames(cls.ArticleList, {}, [className, cls[view]])}> {articles.length > 0 ? articles.map(renderArticle) : null} {isLoading && getSkeletons(view)} {/* { view === 'BIG' ? ( <Virtuoso style={{ height: '100%' }} data={articles} itemContent={renderArticle} endReached={onLoadNextPart} initialTopMostItemIndex={selectedArticleId} components={{ Header, Footer, }} /> ) : ( <VirtuosoGrid ref={VirtuosoGridRef} totalCount={articles.length} components={{ Header, ScrollSeekPlaceholder: ItemContainerComp, }} style={{ height: '100%' }} endReached={onLoadNextPart} data={articles} itemContent={renderArticle} listClassName={cls.itemsWrapper} scrollSeekConfiguration={{ enter: (velocity) => Math.abs(velocity) > 200, exit: (velocity) => Math.abs(velocity) < 30 }} /> )} */} </div> ); };
# coding: utf-8 from model.serializable import SwaggerSerializable class NmiBankSettings(SwaggerSerializable): swagger_types = { 'allow_multicurrency': 'bool', 'base_currency': 'str', 'supported_currencies': 'list[str]', 'allow_moto': 'bool', 'allow_internet': 'bool', 'allow_recurring': 'bool', 'bank_merchant_id': 'str', 'bank_merchant_password': 'str', 'default_cardholder_email': 'str', 'enable_automatic_settle': 'bool', 'batch_time': 'str', 'display_name': 'str', 'allow_edit_display_name': 'bool', 'force_unique_order_id': 'bool' } attribute_map = { 'allow_multicurrency': 'allowMulticurrency', 'base_currency': 'baseCurrency', 'supported_currencies': 'supportedCurrencies', 'allow_moto': 'allowMoto', 'allow_internet': 'allowInternet', 'allow_recurring': 'allowRecurring', 'bank_merchant_id': 'bankMerchantId', 'bank_merchant_password': 'bankMerchantPassword', 'default_cardholder_email': 'defaultCardholderEmail', 'enable_automatic_settle': 'enableAutomaticSettle', 'batch_time': 'batchTime', 'display_name': 'displayName', 'allow_edit_display_name': 'allowEditDisplayName', 'force_unique_order_id': 'forceUniqueOrderId' } def __init__(self, allow_multicurrency=False, base_currency=None, supported_currencies=None, allow_moto=True, allow_internet=False, allow_recurring=True, bank_merchant_id=None, bank_merchant_password=None, default_cardholder_email=None, enable_automatic_settle=True, batch_time=None, display_name=None, allow_edit_display_name=False, force_unique_order_id=True): # noqa: E501 """NmiBankSettings - a model defined in Swagger""" # noqa: E501 self._allow_multicurrency = None self._base_currency = None self._supported_currencies = None self._allow_moto = None self._allow_internet = None self._allow_recurring = None self._bank_merchant_id = None self._bank_merchant_password = None self._default_cardholder_email = None self._enable_automatic_settle = None self._batch_time = None self._display_name = None self._allow_edit_display_name = None self._force_unique_order_id = None self.discriminator = None if allow_multicurrency is not None: self.allow_multicurrency = allow_multicurrency if base_currency is not None: self.base_currency = base_currency if supported_currencies is not None: self.supported_currencies = supported_currencies if allow_moto is not None: self.allow_moto = allow_moto if allow_internet is not None: self.allow_internet = allow_internet if allow_recurring is not None: self.allow_recurring = allow_recurring self.bank_merchant_id = bank_merchant_id self.bank_merchant_password = bank_merchant_password if default_cardholder_email is not None: self.default_cardholder_email = default_cardholder_email if enable_automatic_settle is not None: self.enable_automatic_settle = enable_automatic_settle if batch_time is not None: self.batch_time = batch_time if display_name is not None: self.display_name = display_name if allow_edit_display_name is not None: self.allow_edit_display_name = allow_edit_display_name if force_unique_order_id is not None: self.force_unique_order_id = force_unique_order_id @property def allow_multicurrency(self): """Gets the allow_multicurrency of this NmiBankSettings. # noqa: E501 :return: The allow_multicurrency of this NmiBankSettings. # noqa: E501 :rtype: bool """ return self._allow_multicurrency @allow_multicurrency.setter def allow_multicurrency(self, allow_multicurrency): """Sets the allow_multicurrency of this NmiBankSettings. :param allow_multicurrency: The allow_multicurrency of this NmiBankSettings. # noqa: E501 :type: bool """ self._allow_multicurrency = allow_multicurrency @property def base_currency(self): """Gets the base_currency of this NmiBankSettings. # noqa: E501 :return: The base_currency of this NmiBankSettings. # noqa: E501 :rtype: str """ return self._base_currency @base_currency.setter def base_currency(self, base_currency): """Sets the base_currency of this NmiBankSettings. :param base_currency: The base_currency of this NmiBankSettings. # noqa: E501 :type: str """ allowed_values = ["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LVL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MRU", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "USN", "USS", "UYI", "UYU", "UZS", "VEF", "VES", "VND", "VUV", "WST", "XAF", "XCD", "XOF", "XPF", "YER", "ZAR", "ZMW", "ZWL"] # noqa: E501 if base_currency not in allowed_values: raise ValueError( "Invalid value for `base_currency` ({0}), must be one of {1}" # noqa: E501 .format(base_currency, allowed_values) ) self._base_currency = base_currency @property def supported_currencies(self): """Gets the supported_currencies of this NmiBankSettings. # noqa: E501 :return: The supported_currencies of this NmiBankSettings. # noqa: E501 :rtype: list[str] """ return self._supported_currencies @supported_currencies.setter def supported_currencies(self, supported_currencies): """Sets the supported_currencies of this NmiBankSettings. :param supported_currencies: The supported_currencies of this NmiBankSettings. # noqa: E501 :type: list[str] """ allowed_values = ["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LVL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MRU", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "USN", "USS", "UYI", "UYU", "UZS", "VEF", "VES", "VND", "VUV", "WST", "XAF", "XCD", "XOF", "XPF", "YER", "ZAR", "ZMW", "ZWL"] # noqa: E501 if not set(supported_currencies).issubset(set(allowed_values)): raise ValueError( "Invalid values for `supported_currencies` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(supported_currencies) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._supported_currencies = supported_currencies @property def allow_moto(self): """Gets the allow_moto of this NmiBankSettings. # noqa: E501 :return: The allow_moto of this NmiBankSettings. # noqa: E501 :rtype: bool """ return self._allow_moto @allow_moto.setter def allow_moto(self, allow_moto): """Sets the allow_moto of this NmiBankSettings. :param allow_moto: The allow_moto of this NmiBankSettings. # noqa: E501 :type: bool """ self._allow_moto = allow_moto @property def allow_internet(self): """Gets the allow_internet of this NmiBankSettings. # noqa: E501 :return: The allow_internet of this NmiBankSettings. # noqa: E501 :rtype: bool """ return self._allow_internet @allow_internet.setter def allow_internet(self, allow_internet): """Sets the allow_internet of this NmiBankSettings. :param allow_internet: The allow_internet of this NmiBankSettings. # noqa: E501 :type: bool """ self._allow_internet = allow_internet @property def allow_recurring(self): """Gets the allow_recurring of this NmiBankSettings. # noqa: E501 :return: The allow_recurring of this NmiBankSettings. # noqa: E501 :rtype: bool """ return self._allow_recurring @allow_recurring.setter def allow_recurring(self, allow_recurring): """Sets the allow_recurring of this NmiBankSettings. :param allow_recurring: The allow_recurring of this NmiBankSettings. # noqa: E501 :type: bool """ self._allow_recurring = allow_recurring @property def bank_merchant_id(self): """Gets the bank_merchant_id of this NmiBankSettings. # noqa: E501 :return: The bank_merchant_id of this NmiBankSettings. # noqa: E501 :rtype: str """ return self._bank_merchant_id @bank_merchant_id.setter def bank_merchant_id(self, bank_merchant_id): """Sets the bank_merchant_id of this NmiBankSettings. :param bank_merchant_id: The bank_merchant_id of this NmiBankSettings. # noqa: E501 :type: str """ if bank_merchant_id is None: raise ValueError("Invalid value for `bank_merchant_id`, must not be `None`") # noqa: E501 self._bank_merchant_id = bank_merchant_id @property def bank_merchant_password(self): """Gets the bank_merchant_password of this NmiBankSettings. # noqa: E501 :return: The bank_merchant_password of this NmiBankSettings. # noqa: E501 :rtype: str """ return self._bank_merchant_password @bank_merchant_password.setter def bank_merchant_password(self, bank_merchant_password): """Sets the bank_merchant_password of this NmiBankSettings. :param bank_merchant_password: The bank_merchant_password of this NmiBankSettings. # noqa: E501 :type: str """ if bank_merchant_password is None: raise ValueError("Invalid value for `bank_merchant_password`, must not be `None`") # noqa: E501 self._bank_merchant_password = bank_merchant_password @property def default_cardholder_email(self): """Gets the default_cardholder_email of this NmiBankSettings. # noqa: E501 :return: The default_cardholder_email of this NmiBankSettings. # noqa: E501 :rtype: str """ return self._default_cardholder_email @default_cardholder_email.setter def default_cardholder_email(self, default_cardholder_email): """Sets the default_cardholder_email of this NmiBankSettings. :param default_cardholder_email: The default_cardholder_email of this NmiBankSettings. # noqa: E501 :type: str """ self._default_cardholder_email = default_cardholder_email @property def enable_automatic_settle(self): """Gets the enable_automatic_settle of this NmiBankSettings. # noqa: E501 :return: The enable_automatic_settle of this NmiBankSettings. # noqa: E501 :rtype: bool """ return self._enable_automatic_settle @enable_automatic_settle.setter def enable_automatic_settle(self, enable_automatic_settle): """Sets the enable_automatic_settle of this NmiBankSettings. :param enable_automatic_settle: The enable_automatic_settle of this NmiBankSettings. # noqa: E501 :type: bool """ self._enable_automatic_settle = enable_automatic_settle @property def batch_time(self): """Gets the batch_time of this NmiBankSettings. # noqa: E501 :return: The batch_time of this NmiBankSettings. # noqa: E501 :rtype: str """ return self._batch_time @batch_time.setter def batch_time(self, batch_time): """Sets the batch_time of this NmiBankSettings. :param batch_time: The batch_time of this NmiBankSettings. # noqa: E501 :type: str """ self._batch_time = batch_time @property def display_name(self): """Gets the display_name of this NmiBankSettings. # noqa: E501 :return: The display_name of this NmiBankSettings. # noqa: E501 :rtype: str """ return self._display_name @display_name.setter def display_name(self, display_name): """Sets the display_name of this NmiBankSettings. :param display_name: The display_name of this NmiBankSettings. # noqa: E501 :type: str """ self._display_name = display_name @property def allow_edit_display_name(self): """Gets the allow_edit_display_name of this NmiBankSettings. # noqa: E501 :return: The allow_edit_display_name of this NmiBankSettings. # noqa: E501 :rtype: bool """ return self._allow_edit_display_name @allow_edit_display_name.setter def allow_edit_display_name(self, allow_edit_display_name): """Sets the allow_edit_display_name of this NmiBankSettings. :param allow_edit_display_name: The allow_edit_display_name of this NmiBankSettings. # noqa: E501 :type: bool """ self._allow_edit_display_name = allow_edit_display_name @property def force_unique_order_id(self): """Gets the force_unique_order_id of this NmiBankSettings. # noqa: E501 :return: The force_unique_order_id of this NmiBankSettings. # noqa: E501 :rtype: bool """ return self._force_unique_order_id @force_unique_order_id.setter def force_unique_order_id(self, force_unique_order_id): """Sets the force_unique_order_id of this NmiBankSettings. :param force_unique_order_id: The force_unique_order_id of this NmiBankSettings. # noqa: E501 :type: bool """ self._force_unique_order_id = force_unique_order_id
<script setup> defineProps(["person"]); </script> <template> <div> <div class="px-4 sm:px-0"> <h3 class="text-base font-semibold leading-7 text-gray-900"> Applicant Information </h3> <p class="mt-1 max-w-2xl text-sm leading-6 text-gray-500"> Personal details and application. </p> </div> <div class="mt-6 border-t border-gray-100"> <dl class="divide-y divide-gray-100"> <div class="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> <dt class="text-sm font-medium leading-6 text-gray-900">Full name</dt> <dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0" > {{ person.name }} </dd> </div> <div class="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> <dt class="text-sm font-medium leading-6 text-gray-900"> Application for </dt> <dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0" > {{ person.position }} </dd> </div> <div class="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> <dt class="text-sm font-medium leading-6 text-gray-900"> Email address </dt> <dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0" > {{ person.email }} </dd> </div> <div class="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> <dt class="text-sm font-medium leading-6 text-gray-900"> Salary expectation </dt> <dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0" > {{ person.salary }} </dd> </div> <div class="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> <dt class="text-sm font-medium leading-6 text-gray-900">About</dt> <dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0" > {{ person.about }} </dd> </div> <div class="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> <dt class="text-sm font-medium leading-6 text-gray-900"> Attachments </dt> <dd class="mt-2 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <ul role="list" class="divide-y divide-gray-100 rounded-md border border-gray-200" > <li class="flex items-center justify-between py-4 pl-4 pr-5 text-sm leading-6" v-for="(att, index) in person.attachments" :key="index" > <div class="flex w-0 flex-1 items-center"> <svg class="h-5 w-5 flex-shrink-0 text-gray-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" > <path fill-rule="evenodd" d="M15.621 4.379a3 3 0 00-4.242 0l-7 7a3 3 0 004.241 4.243h.001l.497-.5a.75.75 0 011.064 1.057l-.498.501-.002.002a4.5 4.5 0 01-6.364-6.364l7-7a4.5 4.5 0 016.368 6.36l-3.455 3.553A2.625 2.625 0 119.52 9.52l3.45-3.451a.75.75 0 111.061 1.06l-3.45 3.451a1.125 1.125 0 001.587 1.595l3.454-3.553a3 3 0 000-4.242z" clip-rule="evenodd" /> </svg> <div class="ml-4 flex min-w-0 flex-1 gap-2"> <span class="truncate font-medium">{{ att.name }}</span> <span class="flex-shrink-0 text-gray-400">{{ att.size }}</span> </div> </div> <div class="ml-4 flex-shrink-0"> <a href="#" class="font-medium text-indigo-600 hover:text-indigo-500" >Download</a > </div> </li> </ul> </dd> </div> </dl> </div> </div> </template> <style></style>
public class Main { public static void main(String[] args) { String[] columns = new String[]{"StudentId", "Name", "Surname"}; Table student = new Table("Student", columns); //Add some records Record rec1 = new Record(3); rec1.setColumn(1, Integer.valueOf(16230943)); rec1.setColumn(2, new String("Lerato")); rec1.setColumn(3, new String("Molefe")); student.insert(rec1); Record rec2 = new Record(3); rec2.setColumn(1, Integer.valueOf(17248830)); rec2.setColumn(2, new String("Isabel")); rec2.setColumn(3, new String("Muller")); student.insert(rec2); Record rec3 = new Record(3); rec3.setColumn(1, Integer.valueOf(16094340)); rec3.setColumn(2, new String("John")); rec3.setColumn(3, new String("Botha")); student.insert(rec3); Record rec4 = new Record(3); rec4.setColumn(1, Integer.valueOf(17012340)); rec4.setColumn(2, new String("Michael")); rec4.setColumn(3, new String("Evans")); student.insert(rec4); //Select All - No indexes student.select(null, null, null); //Select All Ordered By - No indexes student.select(null, null, "StudentId"); student.createIndex("PrimKey", "StudentId"); student.createIndex("SecKey", "Surname"); student.printIndex("PrimKey"); student.printIndex("SecKey"); //Select All Ordered By - Use index student.select(null, null, "StudentId"); student.select(null, null, "Name"); student.select(null, null, "Surname"); //Select All Where Specific - Use index if available student.select("StudentId", 17248830, null); student.select("StudentId", 17123456, null); student.select("Name", "Michael", null); student.select("Name", "Mike", null); student.select("Surname", "Botha", null); student.select("Surname", "Oldfield", null); //Delete All Where Specific - Use index if available student.delete("StudentId", 17248830); student.delete("Surname", "Evans"); //Updated indexes student.printIndex("PrimKey"); student.printIndex("SecKey"); //Select All student.select(null, null, null); //Delete All student.delete(null, null); //Updated indexes student.printIndex("PrimKey"); student.printIndex("SecKey"); //Select All student.select(null, null, null); /* Expected Output: 16230943,Lerato,Molefe 17248830,Isabel,Muller 16094340,John,Botha 17012340,Michael,Evans No indexes found Level 1 [ 17012340] Level 2 [ 16094340 16230943] Level 2 [ 17012340 17248830] Level 1 [ Molefe] Level 2 [ Botha Evans] Level 2 [ Molefe Muller] 16094340,John,Botha 16230943,Lerato,Molefe 17012340,Michael,Evans 17248830,Isabel,Muller No suitable index found 16094340,John,Botha 17012340,Michael,Evans 16230943,Lerato,Molefe 17248830,Isabel,Muller 17248830,Isabel,Muller Record(s) not found 17012340,Michael,Evans Record(s) not found 16094340,John,Botha Record(s) not found Level 1 [ 16230943] Level 2 [ 16094340] Level 2 [ 16230943] Level 1 [ Molefe] Level 2 [ Botha] Level 2 [ Molefe] 16230943,Lerato,Molefe 16094340,John,Botha Level 1 [] Level 1 [] No records found */ } }
import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import Shop from "./Pages/Shop"; import ShopCategory from "./Pages/ShopCategory"; import Product from "./Pages/Product"; import Cart from "./Pages/Cart"; import LoginSignUp from "./Pages/LoginSignUp"; import reportWebVitals from "./reportWebVitals"; import menBanner from "./Components/assets/Assets/banner_mens.png"; import womenBanner from "./Components/assets/Assets/banner_women.png"; import kidsBanner from "./Components/assets/Assets/banner_kids.png"; import { BrowserRouter, RouterProvider, createBrowserRouter, } from "react-router-dom"; import ShopContextProvider from "./Context/ShopContext"; const appRouter = createBrowserRouter([ { path: "/", element: <App />, children: [ { path: "/", element: <Shop />, }, { path: "/mens", element: <ShopCategory banner={menBanner} category="men" />, }, { path: "/womens", element: <ShopCategory banner={womenBanner} category="women" />, }, { path: "/kids", element: <ShopCategory banner={kidsBanner} category="kid" />, }, { path: "/product", element: <Product />, children: [ { path: ":productId", element: <Product />, }, ], }, { path: "/cart", element: <Cart />, }, { path: "/login", element: <LoginSignUp />, }, ], }, ]); const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <RouterProvider router={appRouter} /> </React.StrictMode> );
#!/usr/bin/env python3 """ Route module for the API """ from os import getenv from api.v1.views import app_views from flask import Flask, jsonify, abort, request from flask_cors import (CORS, cross_origin) import os # Create a Flask application and configure CORS settings app = Flask(__name__) app.register_blueprint(app_views) CORS(app, resources={r"/api/v1/*": {"origins": "*"}}) # Initialize a variable based on the environment variable AUTH_TYPE auth = None auth_type = getenv('AUTH_TYPE') # Instantiate the appropriate authentication class based on AUTH_TYPE if auth_type == 'basic_auth': from api.v1.auth.basic_auth import BasicAuth auth = BasicAuth() else: from api.v1.auth.auth import Auth auth = Auth() # Define a list of paths that don't need authentication excluded_paths = [ '/api/v1/status/', '/api/v1/unauthorized/', '/api/v1/forbidden/'] @app.before_request def before_request(): """Filter and authenticate incoming API requests. """ if auth is None: pass current_path = request.path if auth.require_auth(current_path, excluded_paths): authorization_header = auth.authorization_header(request) current_user = auth.current_user(request) if authorization_header is None: abort(401, description="Unauthorized") if current_user is None: abort(403, description="Forbidden") @app.errorhandler(404) def not_found(error) -> str: """ Not found handler """ return jsonify({"error": "Not found"}), 404 @app.errorhandler(401) def unauthorized_error(e) -> str: """Custom Unauthorized error handler """ return jsonify({"error": "Unauthorized"}), 401 @app.errorhandler(403) def forbidden_error(e) -> str: """Custom Forbidden error handler """ return jsonify({"error": "Forbidden"}), 403 if __name__ == "__main__": host = getenv("API_HOST", "0.0.0.0") port = getenv("API_PORT", "5000") app.run(host=host, port=port)
import React, { useState } from 'react' import { Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, TextField, Button, } from '@mui/material' import useAddUser from '../../graphql/user/hooks/useAddUser' import {useTranslation} from "react-i18next"; const NewUserForm = ({ setOpen, open }) => { const [addUser] = useAddUser() const [name, setName] = useState('') const {t, i18n} = useTranslation('common'); const handleChange = (event) => { setName(event.target.value) } const projectId = window.localStorage.getItem('projectId') const handleClose = () => { setOpen(false) } const handleSave = () => { addUser({ variables: { userName: name, projectId: projectId, }, }) setName('') setOpen(false) } const handleEventKey = (e) => { if(e.key === 'Enter' && name !== '') {handleSave()} } return ( <div> <Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title"> <DialogTitle id="form-dialog-title"> {t('newUserForm.newuser')}</DialogTitle> <DialogContent> <DialogContentText> {t('newUserForm.usercredentials')} </DialogContentText> <TextField variant="standard" autoComplete="off" autoFocus margin="dense" name="name" label= {t('newUserForm.name')} type="text" fullWidth onChange={(event) => handleChange(event)} onKeyPress = {handleEventKey} /> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> {t('newUserForm.cancel')} </Button> <Button disabled={!name.length} onClick={handleSave} color="primary" id="addUser"> {t('newUserForm.add')} </Button> </DialogActions> </Dialog> </div> ) } export default NewUserForm
import React, { useContext, useState } from "react"; import { BiLogoWhatsapp, BiLogoGmail } from "react-icons/bi"; import { Navigate } from "react-router-dom"; import { Context, server } from "../main"; import toast from "react-hot-toast"; import axios from "axios"; import Loading from "../components/Loading"; const Home = () => { const [medicationName, setMedicationName] = useState(""); const [remindhr, setRemindhr] = useState(""); const [remindmin, setRemindmin] = useState("false"); const [email, setEmail] = useState("false"); const [whatsapp, setWhatsapp] = useState("false"); const { isAuthenticated, loading, setLoading } = useContext(Context); const submitHandler = async (e) => { e.preventDefault(); try { setLoading(true); const { data } = await axios.post( `${server}/reminder/create`, { medicationName, remindhr, remindmin, email, whatsapp, }, { withCredentials: true, headers: { "Content-Type": "application/json", }, } ); toast.success(data.message); setLoading(false); setMedicationName(""); setRemindhr(""); setRemindmin(""); setEmail("false"); setWhatsapp("false"); } catch (error) { toast.error(error.response.data.message); setLoading(false); console.error("Error:", error); } }; const handleEmailCheckboxChange = (e) => { setEmail(e.target.checked ? "true" : "false"); }; const handlewhatsappCheckboxChange = (e) => { setWhatsapp(e.target.checked ? "true" : "false"); }; if (!isAuthenticated) return <Navigate to={"/login"} />; return loading ? ( <Loading /> ) : ( <> <div className="intrdoction py-12 md:w-4/5 lg:w-4/6 p-8 text-center mx-auto"> <h1 className="text-4xl md:text-5xl text-gray-800 font-bold mb-5 mt-20 "> Welcome to Notify </h1>{" "} <br /> <p className="text-lg text-gray-600 leading-7"> At Notify, we believe that taking control of your time should be simple and stress-free. Getting a reminder notification plays a vital role in our busy lives. In today's fast-paced world, where we juggle multiple tasks and responsibilities, it's easy for things to slip through the cracks. A reminder notification acts as a gentle nudge, ensuring that we stay on top of our commitments. Whether it's a project deadline, a doctor's appointment, or even a simple daily task, these reminders help us prioritize and stay organized. </p> </div> <div className="min-h-screen flex items-center justify-center"> <div className="max-w-screen-xl mx-auto p-12"> <div className="md:flex justify-center"> <div className="md:mr-7 text-center md:w-2/3 md:p-4 mb-16 md:mt-28 "> <h1 className="text-4xl md:text-5xl text-gray-800 font-bold"> Did you know? </h1>{" "} <br /> <p className="text-lg text-gray-600 leading-7"> reminder notifications help reduce stress and anxiety by freeing up mental space and allowing us to focus on other important aspects of our live </p> </div> <div className=" md:ml-7 bg-green-300 rounded-lg p-7 shadow-md w-full md:w-1/2 mb-16"> <h2 className="text-3xl md:text-4xl text-center text-gray-800 font-bold"> Set a Reminder </h2> <br /> <form onSubmit={submitHandler}> <div className="mb-4"> <label className="block font-bold text-gray-800"> Notification: </label> <input name="medicationname" value={medicationName} required type="text" className="w-full border border-gray-300 rounded-md py-2 px-3" onChange={(e) => setMedicationName(e.target.value)} /> </div> <div className="mb-4"> <label className="block font-bold text-gray-800"> Set time : </label> <div className="flex items-center"> <input name="remindhr" type="number" min="0" max="23" className="w-1/2 border border-gray-300 rounded-md py-2 px-3" value={remindhr} required // onChange={(e) => setRemindhr(e.target.value)} onInput={(e) => { const value = e.target.value; const intValue = parseInt(value, 10); if (isNaN(intValue) || intValue < 0) { e.target.value = ""; } else if (intValue > 23) { e.target.value = "23"; } setRemindhr(e.target.value); }} placeholder="24hr format" /> <span className="mx-2">:</span> <input name="remindmin" type="number" min="0" max="59" className="w-1/2 border border-gray-300 rounded-md py-2 px-3" required value={remindmin} // onChange={(e) => setRemindmin(e.target.value)} onInput={(e) => { const value = e.target.value; const intValue = parseInt(value, 10); if (isNaN(intValue) || intValue < 0) { e.target.value = ""; } else if (intValue > 59) { e.target.value = "59"; } setRemindmin(e.target.value); }} placeholder="60min format" /> </div> <br /> <div className="mb-4"> <label className="block font-bold text-gray-800 mb-2"> Notification Method : </label> <div className=" sm:w-4/5 md:w-full lg:w-4/5 mx-auto"> <div className="flex items-center justify-between"> <label className="flex items-center "> <input type="checkbox" name="whatsapp" checked={whatsapp === "true"} // Bind the checked status of the checkbox to the email state onChange={handlewhatsappCheckboxChange} /> <span className="ml-2 text-lg"> <BiLogoWhatsapp className=" inline text-3xl text-gray-600" /> WhatsApp </span> </label> <label className="flex items-center"> <input type="checkbox" name="mail" checked={email === "true"} // Bind the checked status of the checkbox to the email state onChange={handleEmailCheckboxChange} /> <span className="ml-2 text-lg"> <BiLogoGmail className=" inline text-3xl text-gray-600" />{" "} Mail&nbsp;&nbsp;&nbsp; </span> </label> </div> <div className="flex items-center justify-between"></div> </div> </div> </div> <button type="submit" className="bg-blue-500 text-white font-bold py-2 px-4 rounded-md hover:bg-blue-600 w-full" onClick={submitHandler} > Submit </button> </form> </div> </div> <div className="mt-8 text-center pb-7"> <h1 className="text-2xl md:text-3xl text-gray-800 font-bold"> Note: To enable WhatsApp </h1> <p className="text-gray-600"> Please scan the given QR code and hit the send button </p> < br /> <img src="/qr.PNG" alt="QR code" className="h-32 mx-auto mt-2" />< br /> <p className="text-gray-600"> Or, on WhatsApp, text "join solar-brown" to the number +14155238886 </p> </div> </div> </div> </> ); }; export default Home;
#include <iostream> #include <fstream> #include <sstream> #include <filesystem> #include <GL/glew.h> #include <GLFW/glfw3.h> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "imgui/imgui.h" #include "imgui/imgui_impl_glfw.h" #include "imgui/imgui_impl_opengl3.h" #include "renderer/Shader.h" #include "renderer/Renderer.h" #include "renderer/models/baseModels/Cube.h" #include "renderer/models/baseModels/Sphere.h" #include "universe/Body.h" #include "common/Camera.h" #include "universe/Universe.h" #define STB_IMAGE_IMPLEMENTATION #include "stb/stb_image.h" #define width 1920 #define height 1080 void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); unsigned int loadCubemap(std::vector<std::string> faces); std::vector<float> skyboxVertices = { // positions -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }; std::vector<std::string> faces { "res/textures/skybox/right.jpg", "res/textures/skybox/left.jpg", "res/textures/skybox/top.jpg", "res/textures/skybox/bottom.jpg", "res/textures/skybox/front.jpg", "res/textures/skybox/back.jpg" }; int main(void) { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; /* Set GLFW error callback */ glfwSetErrorCallback([](int error, const char* description) { std::cerr << "GLFW Error: " << description << std::endl; }); /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(width, height, "Gravity simulation", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); /* Initialize GLEW */ GLenum err = glewInit(); if (err != GLEW_OK) { std::cerr << "GLEW Error: " << glewGetErrorString(err) << std::endl; return -1; } glfwSetScrollCallback(window, scroll_callback); /* Enable OpenGL debug output */ glEnable(GL_DEBUG_OUTPUT); // Setup ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); // Second param install_callback=true will install GLFW callbacks and chain to existing ones. ImGui_ImplOpenGL3_Init(); unsigned int cubemapTexture = loadCubemap(faces); unsigned int skyboxVAO, skyboxVBO; glGenVertexArrays(1, &skyboxVAO); glGenBuffers(1, &skyboxVBO); glBindVertexArray(skyboxVAO); glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO); glBufferData(GL_ARRAY_BUFFER, skyboxVertices.size() * sizeof(float), &skyboxVertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); // Create cube Cube cube; Sphere sphere(1.0f, 20); // Projection matrix glm::mat4 Projection = glm::perspective(glm::radians(30.0f), (float)width / (float)height, 0.1f, 500.0f); // Create renderer Renderer renderer(Projection); // Create bodies with a sphere as model Body body1(glm::vec3(20.0f, 0.0f, 0.0f), sphere, glm::vec4(0.0f, 0.5f, 0.5f, 1.0f), glm::vec3(0.0f, 0.0f, 0.055f), 15.0f, 0.4f, 0.5f); Body body2(glm::vec3(30.0f, 0.0f, 0.0f), sphere, glm::vec4(0.5f, 0.0f, 0.5f, 1.0f), glm::vec3(0.0f, 0.0f, 0.055f), 10.0f, 0.5f, 0.35f); Body star(glm::vec3(0.0f, 0.0f, 0.0f), sphere, glm::vec4(0.5f, 0.5f, 0.0f, 1.0f), glm::vec3(0.0f, 0.00f, 0.0f), 1000.0f, 100.0f,2.0f); body1.SetName("Planet 1"); body2.SetName("Planet 2"); star.SetName("Star"); // Create Camera Camera camera(window, Projection, glm::vec3(0, 0, 50), star.GetPosition(), width, height); glfwSetWindowUserPointer(window, &camera); // Create universe and add bodies Universe universe; universe.AddBody(&body1); universe.AddBody(&body2); universe.SetEmissiveBody(&star); // Create, compile and bind shader Shader starShader("res/shaders/star/VertexShader.glsl", "res/shaders/star/FragmentShader.glsl"); Shader defaultShader("res/shaders/default/VertexShader.glsl", "res/shaders/default/FragmentShader.glsl"); Shader skyboxShader("res/shaders/skybox/VertexShader.glsl", "res/shaders/skybox/FragmentShader.glsl"); // Check for OpenGL errors after shader creation GLenum shaderErr = glGetError(); if (shaderErr != GL_NO_ERROR) { std::cerr << "Shader Creation Error: " << shaderErr << std::endl; return -1; } // Set shaders uniforms defaultShader.Bind(); defaultShader.SetUniform4f("u_LightColor", star.GetColor().x, star.GetColor().y, star.GetColor().z, star.GetColor().w); defaultShader.SetUniform4f("u_LightPosition",star.GetPosition().x, star.GetPosition().y, star.GetPosition().z, 1.0f); skyboxShader.Bind(); skyboxShader.SetUniform1i("u_Skybox", 0); // Enable depth glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { renderer.Clear(); // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Begin("Focus"); ImGui::Text("Select the body to focus on:"); // Loop to create checkboxes for each body in the universe for (unsigned int i = 0; i < universe.bodies.size(); i++) { // Create a unique label for each checkbox std::string checkboxLabel = universe.bodies[i]->GetName(); // Check if the checkbox is checked bool checked = (universe.GetFocusedBodyId() == i); // Create the checkbox and set its state if (ImGui::Checkbox(checkboxLabel.c_str(), &checked)) { // If the checkbox state changed, update the focused body if (checked) { universe.SetFocusedBody(i); } } } ImGui::End(); // Update universe's bodies universe.Update(); // Test if mouse pressed if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); camera.RotateCamera(glm::vec2(xpos, ypos)); } else { camera.ResetDrag(); } Body* focusedBody = universe.bodies[universe.GetFocusedBodyId()]; // Look at focused body camera.SetLookAt(focusedBody->GetPosition()); camera.m_position = focusedBody->GetPosition() + camera.m_distance * glm::normalize(focusedBody->GetPosition() - camera.GetOrbitPosition()); // Draw bodies for (unsigned int i = 0; i < universe.bodies.size(); i++) { if (i == universe.GetEmissiveBodyId()) { renderer.Draw(universe.bodies[i], camera.GetViewMatrix(), starShader); } else { defaultShader.Bind(); glm::mat4 modelMat = glm::translate(glm::mat4(1.0f), universe.bodies[i]->GetPosition()); defaultShader.SetUniformMat4f("u_M", modelMat); renderer.Draw(universe.bodies[i], camera.GetViewMatrix(), defaultShader); } } // Render skybox glDepthFunc(GL_LEQUAL); skyboxShader.Bind(); skyboxShader.SetUniformMat4f("u_View", glm::mat4(glm::mat3(camera.GetViewMatrix()))); skyboxShader.SetUniformMat4f("u_Projection", camera.GetProjectionMatrix()); glBindVertexArray(skyboxVAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glDepthFunc(GL_LESS); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); // Check for OpenGL errors after each frame GLenum frameErr = glGetError(); if (frameErr != GL_NO_ERROR) { std::cerr << "OpenGL Error: " << frameErr << std::endl; return -1; } } glfwTerminate(); ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); return 0; } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { Camera* camera = (Camera*)glfwGetWindowUserPointer(window); if (camera->m_distance - yoffset > 1.0f) { camera->m_distance -= yoffset; } } unsigned int loadCubemap(std::vector<std::string> faces) { unsigned int textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); int w, h, nrChannels; for (unsigned int i = 0; i < faces.size(); i++) { unsigned char* data = stbi_load(faces[i].c_str(), &w, &h, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data ); stbi_image_free(data); } else { std::cerr << "Cubemap texture failed to load at path: " << faces[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return textureID; }
/* Axelou Olympia, 2161 * Tsitsopoulou Eirini, 2203 * * This program simulates a roller coaster. * Every new ride begins when train is full. * * Implemented with conditions and mutexes * * The program never terminates because the train never stops. */ #define _GNU_SOURCE #include "mtx_cond.h" #include <errno.h> pthread_mutex_t mtx; pthread_cond_t wait_to_fill; pthread_cond_t train_start; pthread_cond_t wait_to_empty; pthread_cond_t pas_entering; pthread_cond_t pas_exiting; volatile int waiting, onboard; volatile int trainCapacity; volatile int train_w_fill, train_w_start, train_w_empty; #define RIDE_DURATION 2 /* Controls when a passenger enters. * * If there are enough pasengers for the train to start, they notify the train * and then the train allows them to enter. * * The first passenger that unblocks, unblocks the others behind him. * * The last passenger that enters notifies the train to begin the ride. */ void train_enter(){ mtx_lock(&mtx, __LINE__); waiting++; // enough passengers to notify the train to start taking passengers // and train is actually waiting if(waiting == trainCapacity && train_w_fill == 1){ train_w_fill = 0; cond_signal(&wait_to_fill, __LINE__); } cond_wait(&pas_entering, &mtx, __LINE__); //waiting for train to allow them to get in // printf("woke up and onboard = %d\n", onboard); waiting--; onboard++; if(onboard < trainCapacity){ //unblock one passenger behind him cond_signal(&pas_entering, __LINE__); } else if(onboard == trainCapacity){ printf("\t"ANSI_COLOR_CYAN"Train full. Going to Start."ANSI_COLOR_RESET"\n"); if(train_w_start){ train_w_start = 0; cond_signal(&train_start, __LINE__); //notify the train to start } } mtx_unlock(&mtx, __LINE__); } /* This function is called when a passenger exits the train. * Every passenger notifies the next one to exit. * The last one notifies the train that it has emptied. */ void train_exit(){ mtx_lock(&mtx, __LINE__); cond_wait(&pas_exiting, &mtx, __LINE__); // printf("going to exit with onboard = %d\n", onboard); if(onboard > 0){ //unblock one behind them onboard--; cond_signal(&pas_exiting, __LINE__); } else if(onboard == 0 && train_w_empty == 1){ //last passenger notifies train it has emptied train_w_empty = 0; cond_signal(&wait_to_empty, __LINE__); } mtx_unlock(&mtx, __LINE__); } /* Thread function which implements a passenger. * First, it calls train_enter function, * then stays on the train for the duration of the ride (controlled by the train) * and then calls train_exit function * * Doesn't return anything. */ void *passenger(void *args){ train_enter(); // on ride train_exit(); return NULL; } /* Thread function which implements the train. * * Blocks until enough passengers have arrived. Then notifies passengers to start entering * Waits until last passenger has entered. * When ride is over, notifies passangers to exit. Waits for the last passanger to exit before next ride * * Doesn't terminate. */ void *train(void *args){ while(1){ printf("\t"ANSI_COLOR_GREEN"* * * * * * * * Ready for a new ride * * * * * * * *"ANSI_COLOR_RESET"\n"); mtx_lock(&mtx, __LINE__); if(waiting < trainCapacity){ train_w_fill = 1; cond_wait(&wait_to_fill, &mtx, __LINE__); // waits until enough passengers have arrived } // onboard++; waiting--; // printf("train. going to wake up first passanger with onboard = %d\n", onboard); cond_signal(&pas_entering, __LINE__); // notify passengers to enter // printf("train after signa: onboard = %d\n", onboard); if (onboard < trainCapacity){ train_w_start = 1; cond_wait(&train_start, &mtx, __LINE__); // waits until last passenger has got in } sleep(RIDE_DURATION); onboard--; cond_signal(&pas_exiting, __LINE__); // notifies one passenger to exit if (onboard > 0){ train_w_empty = 1; cond_wait(&wait_to_empty, &mtx, __LINE__); // waits for the last passenger to exit // printf("just woke up train. everybode gone\n"); } mtx_unlock(&mtx, __LINE__); } } /* DEBUGGING FUNCTION * This function prints every second the values of waiting passengers and passengers onboard */ void *print_time_screenshot(void *arg){ int i = 0; printf("time: 0 onboard = %d, waiting = %d\n", onboard, waiting); usleep(800000); // head start so that it prints the values in the middle of the second while(1){ i++; printf("time: %3d onboard = %d, waiting = %d\n", i, onboard, waiting); sleep(1); } return NULL; } void init_mtx_cond(){ mtx_init(&mtx, __LINE__); cond_init(&wait_to_fill, __LINE__); cond_init(&wait_to_empty, __LINE__); cond_init(&pas_entering, __LINE__); cond_init(&pas_exiting, __LINE__); cond_init(&train_start, __LINE__); waiting = onboard = train_w_start = 0; train_w_fill = train_w_empty = 0; } void destroy_mtx_cond(){ mtx_destroy(&mtx, __LINE__); cond_destroy(&wait_to_fill, __LINE__); cond_destroy(&wait_to_empty, __LINE__); cond_destroy(&pas_entering, __LINE__); cond_destroy(&pas_exiting, __LINE__); cond_destroy(&train_start, __LINE__); } int main(int argc, char *argv[]) { int nofpassegers = 0, i, waiting_time; pthread_t *passenger_threads; pthread_t roller_coaster_thread, print_time_thread; // retrieving arguments: train capacity if(argc != 2){ printf("Wrong number of arguments. Terminating.\n"); exit(1); } trainCapacity = atoi(argv[1]); if(trainCapacity == 0){ printf("Not a valid argument for train capacity. Terminating.\n"); exit(1); } printf("trainCapacity = %d\n", trainCapacity);sleep(1); init_mtx_cond(); if (pthread_create(&roller_coaster_thread, NULL, train, NULL)){ printf("problem in creating roller_coaster_thread\n"); return 1; } if (pthread_create(&print_time_thread, NULL, print_time_screenshot, NULL)){ printf("problem in creating print_time_thread\n"); return 1; } scanf("%d", &nofpassegers); passenger_threads = (pthread_t *)malloc(sizeof(pthread_t)*nofpassegers); for (i = 0; i < nofpassegers; i++){ scanf("%d", &waiting_time); if (pthread_create(&passenger_threads[i], NULL, passenger, NULL)){ printf("problem in creating thread %d\n", i); return 1; } sleep(waiting_time); } if(pthread_join(roller_coaster_thread, NULL)){ printf("problem with join\n"); return 1; } /* never reach this point; for cosmetic reasons */ destroy_mtx_cond(); printf("If you are watching this, something is wrong\n"); return 0; }
from typing import List, Dict, Set, Any from aicore.component.DetectedObject import DetectedObject from aicore.component.Line import Line from aicore.component.Point import Point from aicore.component.Trajectory import Trajectory from aicore.logic_shape_filter.logic_shape_filter import LogicShapeFilter class LineFilter(LogicShapeFilter): def __init__(self, name: str, id: int, location: Line, created_at: int, updated_at: int, attribute: List[str], direction: int): """ Initialize the LineFilter object. Args: name (str): The name of the filter. id (int): The ID of the filter. location (Line): The line object representing the filtering area. created_at (int): The timestamp when the filter was created. updated_at (int): The timestamp when the filter was last updated. attribute (List[str]): The attributes associated with the filter. direction (int): The direction of the crossing line. """ super().__init__(name, id, location, created_at, updated_at) self.attr = attribute self.direction = direction def make_filtering(self, source_filter: Dict[Any, DetectedObject], current_frame=None) -> Dict[Any, DetectedObject]: """ Perform filtering based on line crossing. Args: source_filter (Dict[Any, DetectedObject]): A dictionary containing DetectedObject instances. current_frame: Optional argument for the current frame. Returns: Dict[Any, DetectedObject]: A dictionary containing filtered DetectedObject instances. """ output = dict() for track_id, detectedObject in source_filter.items(): trajectory_list = detectedObject.get_trajectories() output_set = set() if self._check_crossing_line(trajectory_list, output_set): iterator = iter(output_set) first_traj = next(iterator) second_traj = next(iterator) if self.direction == 0: output[detectedObject.get_track_id()] = detectedObject elif self.direction == self._check_crossing_direction(first_traj, second_traj): output[detectedObject.get_track_id()] = detectedObject else: pass return output def _check_crossing_line(self, list_track: List[Trajectory], output: Set[Trajectory]) -> bool: """ Check if any trajectory crosses the line. Args: list_track (List[Trajectory]): List of trajectory objects. output (Set[Trajectory]): Set to store trajectories that cross the line. Returns: bool: True if any trajectory crosses the line, False otherwise. """ tmp = None for trajectory in list_track: if tmp is None: tmp = trajectory continue if self._is_line_cross(tmp.get_position(), trajectory.get_position()): output.add(tmp) output.add(trajectory) return True tmp = trajectory return False def _is_line_cross(self, point1: Point, point2: Point) -> bool: """ Check if the line defined by two points crosses the filter line. Args: point1 (Point): First point. point2 (Point): Second point. Returns: bool: True if the line crosses the filter line, False otherwise. """ line_start_point = self.location.get_start_point() line_end_point = self.location.get_end_point() check1 = (point1.get_y() - point2.get_y()) * (line_start_point.get_x() - point1.get_x()) - (line_start_point.get_y() - point1.get_y()) * ( point1.get_x() - point2.get_x()) check2 = (point1.get_y() - point2.get_y()) * (line_end_point.get_x() - point1.get_x()) - (line_end_point.get_y() - point1.get_y()) * ( point1.get_x() - point2.get_x()) check3 = (line_start_point.get_y() - line_end_point.get_y()) * (point1.get_x() - line_start_point.get_x()) - ( point1.get_y() - line_start_point.get_y()) * (line_start_point.get_x() - line_end_point.get_x()) check4 = (line_start_point.get_y() - line_end_point.get_y()) * (point2.get_x() - line_start_point.get_x()) - ( point2.get_y() - line_start_point.get_y()) * (line_start_point.get_x() - line_end_point.get_x()) return check1 * check2 <= 0 and check3 * check4 <= 0 def _check_crossing_direction(self, first_trajectory: Trajectory, second_trajectory: Trajectory) -> int: """ Check the direction of line crossing. Args: first_trajectory (Trajectory): First trajectory object. second_trajectory (Trajectory): Second trajectory object. Returns: int: 1 if the orientation is positive, -1 otherwise. """ line_start_point = self.location.get_start_point() orient = (first_trajectory.get_position().get_y()- second_trajectory.get_position().get_y()) * ( line_start_point.get_x() - first_trajectory.get_position().get_x()) - ( line_start_point.get_y() - first_trajectory.get_position().get_y()) * ( first_trajectory.get_position().get_x() - second_trajectory.get_position().get_x()) return 1 if orient >= 0 else -1
#ifndef SERVER_TEMPLATE_TCP_TCP_SERVER_TEMPLATE_H_ #define SERVER_TEMPLATE_TCP_TCP_SERVER_TEMPLATE_H_ #include "tcp_ns.h" #include "../base/server_base.h" #include "../util/uuid.h" #include "tcp_connection_handler.h" #include <assert.h> SERVER_TEMPLATE_TCP_NAMESPACE_BEGIN #ifdef _WIN32 #define HANDLE_PIPE_NAME_PREFIX "\\\\?\\pipe\\hp-" #else #define HANDLE_PIPE_NAME_PREFIX "/tmp/hp-" #endif template <typename Protocol> class TCPServerTemplate : public uv_tcp_t, public base::ServerBase { public: virtual ~TCPServerTemplate() {} virtual void run(uv_loop_t *loop) override { this->loadConfig(); this->loop = loop; assert(this->loop != NULL); // parse address sockaddr_storage addr; if (this->ipAddress.parseAddress(&addr) < 0) { abort(); } auto r = uv_tcp_init(this->loop, this); if (r != 0) { abort(); } r = uv_tcp_bind(this, (sockaddr *)&addr, 0); if (r != 0) { abort(); } assert(this->maxConnectionCount > 0); // Start listen auto tcpHandle = (uv_tcp_s *)this; tcpHandle->data = this; r = uv_listen((uv_stream_t *)tcpHandle, this->maxConnectionCount, [](uv_stream_t *server, int status) { if (status < 0) { return; } ((TCPServerTemplate<Protocol> *)server->data)->onConnection(); }); if (r != 0) { abort(); } } virtual void useIpAddress(const util::IpAddress &ipAddress) override { this->ipAddress = ipAddress; } virtual void setMaxConnectionCount(uint32_t value) override { this->maxConnectionCount = value; } void onConnection() { log("on connection"); // Accept connection auto *client = new uv_tcp_t; auto r = uv_tcp_init(this->loop, client); if (r != 0) { uv_close((uv_handle_t *)client, [](uv_handle_t *handle) { delete handle; }); return; } auto tcpHandle = (uv_tcp_s *)this; r = uv_accept((uv_stream_t *)tcpHandle, (uv_stream_t *)client); if (r == 0) { // create a pipe to send client handle auto pipe = new uv_pipe_t; // random pipe name auto pipeName = std::string(HANDLE_PIPE_NAME_PREFIX).append(util::UUID::generate(20)).append(std::to_string((size_t)pipe)); // start a new thread to read auto connHandler = new TCPConnectionHandler(pipe, pipeName, this->config, this->protocolFactory, client); client->data = connHandler; pipe->data = client; auto workReq = new uv_work_t; workReq->data = connHandler; uv_queue_work( this->loop, workReq, [](uv_work_t *req) { auto handler = (TCPConnectionHandler *)(req->data); handler->start(); delete handler; }, [](uv_work_t *req, int status) { delete req; }); } else { printf("error accpet\n"); uv_close((uv_handle_t *)client, [](uv_handle_t *handle) { delete handle; }); } } private: void loadConfig() { assert(this->config != NULL); this->config->configServer(this); } util::IpAddress ipAddress; uint32_t maxConnectionCount = 512; TCPBasedProtocol::ProtocolFactory protocolFactory = [](base::ConfigurationBase *config, ConnectionHandlerBase *connHandler) { auto protocol = dynamic_cast<TCPBasedProtocol *>(new Protocol()); protocol->setConnectionHandler(connHandler); protocol->useConfig(config); return protocol; }; }; SERVER_TEMPLATE_TCP_NAMESPACE_END #endif // !SERVER_TEMPLATE_TCP_TCP_SERVER_TEMPLATE_H_
import os # Check and create files: def check_directory(filename: str): if filename not in os.listdir(): with open(filename, 'w', encoding='utf-8') as data: data.write("") # Option 1: def read_all(filename: str) -> str: with open(filename, 'r', encoding='utf-8') as data: result = data.read() return result # Option 2: def add_new_user(name: str, phone: str, filename: str): with open(filename, 'a+', encoding='utf-8') as data: data.seek(0) lines_count = len(data.readlines()) data.write(f"{lines_count + 1};{name};{phone}\n") # Option 3: def search_user(data: str, filename: str) -> str: with open(filename, 'r', encoding='utf-8') as file: lines = file.readlines() res_list = [line for line in lines if data in line.lower()] if res_list: return ''.join(res_list) else: return "Нет подходящих записей" # Option 4: def copy_line(line_num: str, filename: str, copy_filename: str): with open(filename, 'r', encoding='utf-8') as og_file: og_lines = og_file.readlines() if len(og_lines) < int(line_num) or int(line_num) <= 0: print("Нет такой строки") return for line in og_lines: if line.startswith(line_num + ';'): line_to_copy = line break with open(copy_filename, 'a+', encoding='utf-8') as copy_file: copy_file.seek(0) lines_count = len(copy_file.readlines()) copy_file.write(f"{lines_count + 1};{line_to_copy.split(';', 1)[1]}") INFO_STRING = """ Выберите режим работы: 1 - Вывести все данные 2 - Добавление нового пользователя 3 - Поиск 4 - Копирование строки """ DATASOURCE = "phone.txt" DATACOPY = "phone-copy.txt" check_directory(DATASOURCE) check_directory(DATACOPY) while True: mode = int(input(INFO_STRING)) if mode == 1: print(read_all(DATASOURCE)) elif mode == 2: user = input("Имя: ") phone = input("Номер телефона: ") add_new_user(user, phone, DATASOURCE) elif mode == 3: search = input("Введите строку для поиска: ") print(search_user(search, DATASOURCE)) elif mode == 4: line_num = input("Введите номер копируемой строки: ") copy_line(line_num, DATASOURCE, DATACOPY)
import {Button, Dropdown, Input} from "semantic-ui-react"; import QRCode from "react-qr-code"; import React, {useEffect, useState} from "react"; type assignmentOptions = { allTeams:number[], teamsWithoutPhotos:number[], teamsWithOldPhotos:number[], setQRDimmerActive:(val:boolean) => void } const options = [ {key: 'all', text:"Assign every team at the event", value: 'all'}, {key: 'old', text:"Assign only teams with old images", value: 'old'}, {key: 'new', text:"Assign only teams with no image", value: 'new'}, ] export default function PhotoAssignment({allTeams, teamsWithoutPhotos, teamsWithOldPhotos, setQRDimmerActive}: assignmentOptions) { const [numPitScouters, setNumPitScouters] = useState(1) console.log(teamsWithoutPhotos.length) const [teams, setTeams] = useState(allTeams) const [currentTeamOption, setCurrentTeamOption] = useState("all") let [pitScoutSchedules, setPitScoutSchedules] = useState<String[]>([]) let [currentPitScout, setCurrentPitScout] = useState(0) useEffect(() => { switch (currentTeamOption) { case "all": setTeams(allTeams) break; case "new": setTeams(teamsWithoutPhotos) break; case "old": setTeams(teamsWithOldPhotos) break; } console.log("did a thing") }, [currentTeamOption, allTeams, teamsWithoutPhotos, teamsWithOldPhotos]); useEffect(() => { console.log("regenerating") let pitScoutArray:String[]= Array(numPitScouters).fill("") let index = 0; teams.forEach(e => { pitScoutArray[index] += `${e},` index = index < pitScoutArray.length-1 ? index+1 : 0 }) let shortenedArray =pitScoutArray.map(e => e.substring(0, e.length-1)) setPitScoutSchedules(shortenedArray) }, [numPitScouters, teams]); return( <div className={"config-qr-code-window"}> <div className={"qr-code-header"}> <h1 className={"config-qr-code-header-text"}>Team Photo QR Code</h1> <Button className={"qr-code-close-button"} icon={"close"} onClick={() => setQRDimmerActive(false)}> </Button> </div> <div className={"inline-input"}> <div className={"input-text-container"}> <h3 className={"input-text"}>Number of Pit Scouters</h3> </div> <Input value={numPitScouters} onChange={(event) => { let result = parseInt(event.target.value) if(result && result < teams.length) { setNumPitScouters(parseInt(event.target.value)) } else if (event.target.value === "") { setNumPitScouters(0); } } }/> </div> <Dropdown options={options} selection defaultValue={"all"} onChange={(event, data) => { setCurrentTeamOption(data.value as string) }} /> <br/> <br/> <QRCode value={`pho:${pitScoutSchedules[currentPitScout]}`}/> <div className={"inline-arrows"}> <Button icon={"arrow left"} onClick={() => { if(currentPitScout > 0) { setCurrentPitScout(currentPitScout-1) } }}/> <h3>{currentPitScout+1} of {numPitScouters}</h3> <Button icon={"arrow right"} onClick={() => { if(currentPitScout < numPitScouters-1) { setCurrentPitScout(currentPitScout+1) } }}/> </div> </div> ) }
// // TodaysTasksHome.swift // MoteNoteApp // // Created by Bernie Graves on 1/25/23. // import SwiftUI struct TodaysTasksHome: View { @EnvironmentObject var profileViewModel: ProfileViewModel @State private var todaysTasks: [Task] = [] @State private var weeksTasks: [Date:[Task]] = [:] @State private var selectedDate: Date? = Date() @State private var showingDailyView = false @State private var showingWeeklySnapshot = false let calendar = Calendar.current let now = Date() var body: some View { ZStack { RoundedRectangle(cornerRadius: 25) .fill(.orange) .frame(width: 350, height: showingWeeklySnapshot ? 750 : 200) .layoutPriority(1) VStack(spacing: 0) { HStack{ Text(showingWeeklySnapshot ? "Weekly Snapshot" : "Daily Snapshot") .padding([.top, .leading], 10.0) .font(.headline) Spacer() Button(action: { withAnimation(.easeInOut) { self.showingWeeklySnapshot.toggle() } }, label: { Label("Graph", systemImage: "chevron.down.circle") .labelStyle(.iconOnly) .imageScale(.large) .scaleEffect(showingWeeklySnapshot ? 1.25 : 1) .padding([.top, .bottom, .trailing], 10.0) }) } .padding(.top, 0) Divider() if showingWeeklySnapshot { WeeklySnapshot() .frame(width: 325) .scaleEffect(0.95) .environmentObject(profileViewModel) } else { DailySnapshot(date: now) .scaleEffect(0.9) .onTapGesture { self.showingDailyView.toggle() } .sheet(isPresented: $showingDailyView) { DailyCalendarView(selectedDate: $selectedDate, coordinator: CalendarCoordinator(selectedDate: $selectedDate, profileViewModel: profileViewModel)) } } } // .onAppear{ // self.todaysTasks = CalendarCoordinator(selectedDate: Binding<Date?>(.constant(Date())), profileViewModel: profileViewModel).getDatesTasks(date: Date()) // // for date in getDatesForCurrentWeek() { // weeksTasks[date] = CalendarCoordinator(selectedDate: Binding<Date?>(.constant(Date())), profileViewModel: profileViewModel).getDatesTasks(date: date) // } // } } } func getDatesForCurrentWeek() -> [Date] { var dates: [Date] = [] // Get the start of the current week let startOfWeek = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: now))! // Loop through the days of the week, adding each to the array of dates for day in 0...6 { let date = calendar.date(byAdding: .day, value: day, to: startOfWeek)! dates.append(date) } return dates } } struct TodaysTasksHome_Previews: PreviewProvider { static var previews: some View { TodaysTasksHome() .environmentObject(ProfileViewModel()) } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Nutrio</title> <link rel="stylesheet" href="styles/style.css"> <link href="https://fonts.googleapis.com/css?family=Work+Sans&display=swap" rel="stylesheet"> <!-- Place your kit's code here --> <script src="https://kit.fontawesome.com/3453b874c7.js" crossorigin="anonymous"></script> </head> <body> <nav id="navbar"> <div class="logo"> <a href="#"> <h4><i class="fas fa-utensils"></i> Nutrio</h4> </a> </div> <ul class="nav-links"> <li><a href="#"><i class="fas fa-home"></i> Home</a></li> <li><a href="https://www.bbcgoodfood.com/recipes/collection/student" target="_blank"><i class="fab fa-pagelines"></i> Cooking Together</a></li> <li><a href="https://fitt.co/toronto/articles/healthy-restaurants-toronto" target="_blank"><i class="fas fa-glass-cheers"></i> Local Eating</a></li> <li><a href="https://food-guide.canada.ca/en/" target="_blank"><i class="fas fa-map-signs"></i> Food Guide</a></li> <li><a href="#contact"><i class="fas fa-envelope"></i> Contact</a></li> </ul> <div class="burger"> <div class="line1"></div> <div class="line2"></div> <div class="line3"></div> </div> </nav> <!-- HERO IMAGE --> <section id="welcome-section"> <div class="hero-image"> <div class="hero-text"> <h1>Nutrio</h1> <p> Because Healthy Eating is Delicious!</p> <a href="#content"><button class="btn"><i class="fas fa-rocket"></i> Learn More</button></a> </div> </div> </section> <!-- Content --> <section id="content"> <div class="content-image"> <div class="content-text"> <h2 style="font-size: 32px;"><i class="fas fa-seedling"></i></h2> <!-- <img src="https://avatars3.githubusercontent.com/u/40644553?s=460&v=4" alt=""> --> <h1 class="center-text">Why eat healthy?</h1> <p style="font-size:22px;line-height:1.5em;max-width:100%;">Choosing to eat healthy and fresh food is beneficial to your overall health. Healthy food has healthy nutrients and offers a great alternative to some of the nutrients unhealthy food provides. Visiting this site itself was the first step in the road to eating and staying healthy. Our site offers various resources such as food guides to help improve eating habits and recipes to adjust your needs. </p> <div class="gain-wrapper"> <div class="gain-box"> <h4><i class="fas fa-dumbbell"></i></h4> <h4>Weight loss</h4> </div> <div class="gain-box"> <h4><i class="fas fa-border-none"></i></i></i></h4> <h4>Reduced cancer risk</h4> </div> <div class="gain-box"> <h4><i class="far fa-smile"></i></h4> <h4>Diabetes management</h4> </div> <div class="gain-box"> <h4><i class="fas fa-heart"></i></h4> <h4>Heart health </h4> </div> <div class="gain-box"> <h4><i class="fas fa-brain"></i></h4> <h4>stroke prevention</h4> </div> <div class="gain-box"> <h4><i class="fas fa-fist-raised"></i></i></h4> <h4>Strong bones and teeth</h4> </div> <div class="gain-box"> <h4><i class="fas fa-bolt"></i></h4> <h4>Improved memory</h4> </div> </div> <h1 style="margin-top:2em;" class="center-text">Some recipes you can try at home</h1> <div class="food-wrapper"> <div class="food-box"> <img class="food-img" src="https://www.bbcgoodfood.com/sites/default/files/styles/recipe/public/recipe_images/mexican-pulled-chicken-beans.jpg?itok=oNTaSAI6" alt=""> <h4> Mexican pulled chicken & beans</h4> </div> <div class="food-box"> <img class="food-img" src="https://www.bbcgoodfood.com/sites/default/files/styles/recipe/public/recipe/recipe-image/2017/05/halloumi-flatbreads.jpg?itok=4vzR1iC1" alt=""> <h4>Halloumi flatbreads</h4> </div> <div class="food-box"> <img class="food-img" src="https://www.bbcgoodfood.com/sites/default/files/styles/recipe/public/recipe/recipe-image/2018/01/super-quick-sesame-ramen.jpg?itok=LRVc0y1S" alt=""> <h4>Super quick sesame ramen</h4> </div> <div class="food-box"> <img class="food-img" src="https://images.unsplash.com/photo-1466637574441-749b8f19452f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80" alt=""> <h4>Check out Cooking Together for more!</h4> </div> </div> <h1 style="margin-top: 3em;"class="center-text">Connect with us on Social Media</h1> <div class="social-wrapper"> <div class="social-links"> <a id="profile-link" href="https://www.facebook.com/pages/category/Government-Organization/Public-Health-Agency-of-Canada-10860597051/" target="_blank"> <div class="social-box facebook"> <h2><i class="fab fa-facebook-square"></i></h2> <h2>Facebook</h2> </div> </a> <a href="https://www.instagram.com/canada/?hl=en" target="_blank"> <div class="social-box instagram"> <h2><i class="fab fa-instagram"></i></h2> <h2>Instagram</h2> </div> </a> <a href="https://twitter.com/phac_gc?lang=en" target="_blank"> <div class="social-box twitter"> <h2><i class="fab fa-twitter"></i></h2> <h2>Twitter</h2> </div> </a> </div> </div> <!-- CONTACT BUTTON --> <h1 style="margin-top: 3em;"class="center-text">Want to contact us or give feedback?</h1> <p style="font-size:20px;">Press the button below to contact or send us a feedback! We love what we do and messages or feedbacks are greatly appreciated! <a style="text-decoration:none;"href="#content"><button class="btn" style="display:block;margin: 34px auto;"><i class="fas fa-envelope"></i> Contact </button></a> </p> </div> </div> </section> <!-- CONTACT --> <section id="contact"> <div class="contact-image"> <div class="contact-text"> <h1>Send us a message</h1> <p style="margin:2em auto;">We love listening to your messages and feedbacks! Please fill in the blanks below</p> <form style ="margin-top:4em;" method="POST" action="https://formspree.io/email"> <label for="name">Full Name: </label> <input type="text" name="name" placeholder="Name" required> <label for="email address">Email Address: </label> <input type="email" name="email" placeholder="Email Address" required> <label for="message">Message: </label> <textarea name="message" placeholder="Message" required></textarea> <button class="btn" type="submit"><i class="fas fa-envelope"></i> Send</button> </form> </section> <footer> <h4>Nutrio is a website made for the web design skills competition. by Aryan. Copyright 2020</h4> <h5>Made with HTML5/CSS3 and Javascript</h5> <ul class="footer-links"> <li><a href="#"><i class="fas fa-home"></i> Home</a></li> <li><a href="https://www.bbcgoodfood.com/recipes/collection/student" target="_blank"><i class="fab fa-pagelines"></i> Cooking Together</a></li> <li><a href="https://fitt.co/toronto/articles/healthy-restaurants-toronto" target="_blank"><i class="fas fa-glass-cheers"></i> Local Eating</a></li> <li><a href="https://food-guide.canada.ca/en/" target="_blank"><i class="fas fa-map-signs"></i> Food Guide</a></li> <li><a href="#contact"><i class="fas fa-envelope"></i> Contact</a></li> </ul> </footer> <script src="scripts/app.js"></script> </body> </html>
import React, { CSSProperties, ReactNode } from 'react'; import { closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'; import { SortableContext, arrayMove, sortableKeyboardCoordinates, verticalListSortingStrategy, } from '@dnd-kit/sortable'; import { findIndex, get } from 'lodash'; import FaSortItem from './FaSortItem'; import {Empty} from "antd"; export interface FaSortListProps<T> { list: T[]; rowKey?: string; // T对象的ID属性,默认值:id renderItem: (item: T) => ReactNode; onSortEnd?: (list: T[]) => void; handle?: boolean; // 是否使用拖动把手 handleNode?: ReactNode; itemStyle?: CSSProperties; handleStyle?: CSSProperties; vertical?: boolean; } /** * 封装的排序列表 * @author xu.pengfei * @date 2022/12/3 9:57 */ export default function FaSortList<T>({ list, rowKey = 'id', renderItem, onSortEnd, handle, handleNode, itemStyle, handleStyle, vertical, }: FaSortListProps<T>) { const sensors = useSensors( useSensor(PointerSensor), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, }), ); function handleDragEnd(event: any) { const { active, over } = event; if (active.id !== over.id) { const oldIndex = findIndex(list, (i) => getRowKey(i) === active.id); const newIndex = findIndex(list, (i) => getRowKey(i) === over.id); const newList = arrayMove(list, oldIndex, newIndex); if (onSortEnd) onSortEnd(newList); } } function getRowKey(item: T) { return get(item, rowKey!); } if (list === undefined || list === null || list.length === 0) { return <Empty /> } return ( <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}> <SortableContext items={list.map((i) => getRowKey(i))} strategy={verticalListSortingStrategy}> {list.map((i) => ( <FaSortItem key={getRowKey(i)} id={getRowKey(i)} handle={handle} handleNode={handleNode} vertical={vertical} style={itemStyle} handleStyle={handleStyle} > {renderItem(i)} </FaSortItem> ))} </SortableContext> </DndContext> ); }
package com.wastehub.user.presentation.ui.transaction.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.wastehub.user.R import com.wastehub.user.common.dummy_data.model.pickup_order.PickupOrder import com.wastehub.user.databinding.ItemTransactionBinding import java.text.SimpleDateFormat class PickupOrderAdapter(private val context: Context, private val records: List<PickupOrder>) : RecyclerView.Adapter<PickupOrderAdapter.PickupOrderViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PickupOrderViewHolder { val binding = ItemTransactionBinding.inflate(LayoutInflater.from(parent.context), parent, false) return PickupOrderViewHolder(binding) } override fun getItemCount(): Int = records.size override fun onBindViewHolder(holder: PickupOrderViewHolder, position: Int) { holder.bind(records[position]) } inner class PickupOrderViewHolder(private val binding: ItemTransactionBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(record: PickupOrder) { // Parse the original date string val originalFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") val date = originalFormat.parse(record.updatedAt) // Define the desired format for the output val outputFormat = SimpleDateFormat("dd/MM/yyyy") // Format the date into the desired format val formattedDate = outputFormat.format(date) // Set the formatted date to the TextView binding.date.text = formattedDate setStatePickupStatus(record.status) // binding.wasteVolume.text = record.wasteVolume.name binding.personName.text = record.picker.name binding.amount.text = String.format("$%,.2f", record.wasteVolume.pickupFee) } private fun setStatePickupStatus(status: String) { when (status) { "requested" -> { binding.status.text = "Pickup is requested" binding.status.setTextColor(ContextCompat.getColor(context, R.color.yellow_500)) binding.status.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_status_requested, 0, 0, 0) } "confirmed" -> { binding.status.text = "Pickup has been confirmed" binding.status.setTextColor(ContextCompat.getColor(context, R.color.yellow_500)) binding.status.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_status_confirmed, 0, 0, 0) } "in progress" -> { binding.status.text = "Pickup is in progress" binding.status.setTextColor(ContextCompat.getColor(context, R.color.blue_300)) binding.status.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_status_in_progress, 0, 0, 0) } "completed" -> { binding.status.text = "Pickup is completed" binding.status.setTextColor(ContextCompat.getColor(context, R.color.green_500)) binding.status.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_status_completed, 0, 0, 0) } "cancelled" -> { binding.status.text = "Pickup is cancelled" binding.status.setTextColor(ContextCompat.getColor(context, R.color.red_300)) binding.status.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_status_cancelled, 0, 0, 0) } "failed" -> { binding.status.text = "Pickup has failed" binding.status.setTextColor(ContextCompat.getColor(context, R.color.red_300)) binding.status.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_status_cancelled, 0, 0, 0) } } } } }
control 'WOAD-3X-000116' do title 'The Workspace ONE Access vPostgres instance must log all connection attempts.' desc "For completeness of forensic analysis, it is necessary to track successful and failed attempts to log on to VMware Postgres. Setting 'log_connections' to 'on' will cause each attempted connection to the server to be logged, as well as successful completion of client authentication." desc 'rationale', '' desc 'check', " At the command prompt, execute the following command: # /opt/vmware/vpostgres/9.6/bin/psql -U postgres -A -t -c \"SHOW log_connections\" Expected result: on If the output does not match the expected result, this is a finding. Note: For a non-clustered vRSLCM deployed instance you may be prompted for the postgres users password which is available at /usr/local/horizon/conf/db.pwd. " desc 'fix', " At the command prompt, execute the following command(s): # /opt/vmware/vpostgres/9.6/bin/psql -U postgres -c \"ALTER SYSTEM SET log_connections TO 'on';\" # /opt/vmware/vpostgres/9.6/bin/psql -U postgres -c \"SELECT pg_reload_conf();\" Note: For a non-clustered vRSLCM deployed instance you may be prompted for the postgres users password which is available at /usr/local/horizon/conf/db.pwd. " impact 0.5 tag severity: 'medium' tag gtitle: 'SRG-APP-000503-DB-000350' tag satisfies: ['SRG-APP-000503-DB-000351', 'SRG-APP-000506-DB-000353'] tag gid: 'V-WOAD-3X-000116' tag rid: 'SV-WOAD-3X-000116' tag stig_id: 'WOAD-3X-000116' tag cci: ['CCI-000172'] tag nist: ['AU-12 c'] clustered = input('clustered') if clustered describe command('/opt/vmware/vpostgres/9.6/bin/psql -U postgres -A -t -c "SHOW log_connections;"') do its('stdout.strip') { should cmp 'on' } end else sqlpw = file("#{input('postgres_pw_file')}").content.strip sql = postgres_session("#{input('postgres_user')}", sqlpw, "#{input('postgres_host')}") sqlquery = 'SHOW log_connections;' describe sql.query(sqlquery) do its('output') { should cmp 'on' } end end end
package com.jz.led.message; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.util.Log; import androidx.annotation.NonNull; /** * Copyright (C) * FileName: MessengerClient * Author: JZ * Date: 2022/5/9 17:03 * Description: MessengerClient */ public class MessengerClient { private static final String TAG = "MessengerClient"; private Context mContext = null; private Messenger mMessengerService = null; private Messenger mMessengerClient = new Messenger(new ClientHandler()); private static MessengerClient mInstance = null; private MessengerClient() { } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d(TAG, "onServiceConnected"); mMessengerService = new Messenger(service); Message obtain = Message.obtain(null, CommonParams.MSG_REC_REGISTER_CLIENT); Bundle bundle = new Bundle(); bundle.putString("msg", "message from client packageName:" + mContext.getPackageName()); obtain.setData(bundle); sendMsgToMessengerService(obtain); } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "onServiceDisconnected"); mMessengerService = null; } }; public static MessengerClient getInstance() { if (null == mInstance) { synchronized (MessengerClient.class) { if (null == mInstance) { mInstance = new MessengerClient(); } } } return mInstance; } public void init(Context context) { Log.d(TAG, "init"); mContext = context; bindMessengerService(); } public void uninit() { Log.d(TAG, "uninit"); try { unbindMessengerService(); } catch (Exception e) { e.printStackTrace(); } } private void bindMessengerService() { Log.d(TAG, "bind MessengerService"); Intent bindIntent = new Intent(); bindIntent.setAction("com.jz.server.MessengerService"); bindIntent.setPackage("com.jz.server"); mContext.bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE); } private void unbindMessengerService() { Log.d(TAG, "unbind MessengerService"); mContext.unbindService(mConnection); Message msg = Message.obtain(null, CommonParams.MSG_REC_UNREGISTER_CLIENT); sendMsgToMessengerService(msg); } public class ClientHandler extends Handler { @Override public void handleMessage(@NonNull Message msg) { Log.d(TAG, "ClientHandler handleMessage " + msg.what); switch (msg.what) { case CommonParams.MSG_REC_HELLO_SERVER: Log.d(TAG, msg.getData().getString("msg")); break; default: MsgHandlerCenter.dispatchMessage(msg); break; } } } public boolean sendMsgToMessengerService(Message msg) { if (mMessengerService == null) { Log.d(TAG, "mMessengerService is null"); return false; } try { msg.replyTo = mMessengerClient; mMessengerService.send(msg); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
'use client'; import { toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import { useState } from "react"; import axios from "axios"; import api from "@/app/services/api"; export default function ModalCreate({ isVisible, onClose, validatePost }: any) { const [nome, setNome] = useState(''); const [origem, setOrigem] = useState(''); const [destino, setDestino] = useState(''); const [status, setStatus] = useState('PedidoEfetuado'); const token = typeof window !== 'undefined' ? localStorage.getItem('token') : ''; const authorization = { headers: { Authorization: `Bearer ${token}` } } async function save(event: any) { event.preventDefault(); const data = { nome, origem, destino, status } if (!data.nome || !data.origem || !data.destino || !data.status) { toast.error("Informe todos os campos!") } else { try { console.log(data); await api.post('api/Pedido', data, authorization) .then(response => { toast.success("Pedido criado com sucesso."); validatePost(true); onClose(); setOrigem(''); setDestino(''); }) } catch (error) { alert(error); } } } function handleChangeOrigem(event: any) { const cep = event.target.value; if (cep.length == 9) { axios.get(`https://viacep.com.br/ws/${cep}/json/`) .then(response => { setOrigem(`${response.data.localidade} - ${response.data.uf}`); }).catch((error) => { console.log('Whoops! Houve um erro.', error.message || error) }); } } function handleChangeDestino(event: any) { const cep = event.target.value; axios.get(`https://viacep.com.br/ws/${cep}/json/`) .then(response => { setDestino(`${response.data.localidade} - ${response.data.uf}`); }).catch((error) => { console.log('Whoops! Houve um erro.', error.message || error) });; } if (!isVisible) return null; return ( <div id="popup-modal" tabIndex={-1} className="fixed w-full top-0 left-0 sm:left-1/3 sm:top-0 z-50 backdrop-blur-sm p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full" > <div id="authentication-modal" tabIndex={-1} aria-hidden="true" className="relative w-full max-w-md max-h-full top-0 left-0 sm:left-1/3" > <div className="relative w-full max-w-md max-h-full"> {/* Modal content */} <div className="relative bg-white rounded-lg shadow dark:bg-gray-700"> <button type="button" className="absolute top-3 right-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-800 dark:hover:text-white" data-modal-hide="authentication-modal" onClick={()=>{onClose(); setDestino(''); setOrigem('');}} > <svg aria-hidden="true" className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" > <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" /> </svg> <span className="sr-only">Close modal</span> </button> <div className="px-6 py-6 lg:px-8"> <h3 className="mb-4 text-xl font-medium text-gray-900 dark:text-white"> Criar Pedido </h3> <form className="space-y-6" action="#" onSubmit={(e) => { save(e); }}> <div> <label htmlFor="email" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Nome </label> <input name="name" id="name" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white" placeholder="Oder" onChange={e => setNome(e.target.value)} /> </div> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Origem </label> <a className="text-white" href="https://buscacepinter.correios.com.br/app/endereco/index.php" > Não sabe seu CEP? </a> <input name="origem" id="origem" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white" placeholder="Digite seu Cep..." onChange={handleChangeOrigem} /> <p className="text-white">{origem}</p> </div> <div> <label htmlFor="destino" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Destino </label> <input name="destino" id="destino" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white" placeholder="Digite seu Cep..." onChange={handleChangeDestino} /> <p className="text-white">{destino}</p> </div> <div> <label htmlFor="password" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Status </label> <select onChange={(e) => setStatus(e.target.value)} value={status} className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"> <option value="PedidoEfetuado">Pedido Efetuado</option> <option value="Enviado">Enviado</option> <option value="Transito">Transito</option> <option value="Despachado">Despachado</option> <option value="Retirado">Retirado</option> </select> </div> <div className="flex justify-between"> </div> <button type="submit" className="w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" > Criar </button> </form> </div> </div> </div> </div> </div> ) }
// Copyright 2022-2023, Offchain Labs, Inc. // For license information, see https://github.com/nitro/blob/master/LICENSE use crate::{ arbcompress, gostack::GoRuntimeState, runtime, socket, syscall, user, wavmio, wavmio::Bytes32, Opts, }; use arbutil::Color; use eyre::{bail, ErrReport, Result, WrapErr}; use go_js::JsState; use sha3::{Digest, Keccak256}; use thiserror::Error; use wasmer::{ imports, CompilerConfig, Function, FunctionEnv, FunctionEnvMut, Instance, Memory, Module, RuntimeError, Store, TypedFunction, }; use wasmer_compiler_cranelift::Cranelift; use std::{ collections::{BTreeMap, HashMap}, fs::File, io::{self, Write}, io::{BufReader, BufWriter, ErrorKind, Read}, net::TcpStream, sync::Arc, time::{Duration, Instant}, }; pub fn create(opts: &Opts, env: WasmEnv) -> (Instance, FunctionEnv<WasmEnv>, Store) { let file = &opts.binary; let wasm = match std::fs::read(file) { Ok(wasm) => wasm, Err(err) => panic!("failed to read {}: {err}", file.to_string_lossy()), }; let mut store = match opts.cranelift { true => { let mut compiler = Cranelift::new(); compiler.canonicalize_nans(true); compiler.enable_verifier(); Store::new(compiler) } false => { #[cfg(not(feature = "llvm"))] panic!("Please rebuild with the \"llvm\" feature for LLVM support"); #[cfg(feature = "llvm")] { let mut compiler = wasmer_compiler_llvm::LLVM::new(); compiler.canonicalize_nans(true); compiler.opt_level(wasmer_compiler_llvm::LLVMOptLevel::Aggressive); compiler.enable_verifier(); Store::new(compiler) } } }; let module = match Module::new(&store, wasm) { Ok(module) => module, Err(err) => panic!("{}", err), }; let func_env = FunctionEnv::new(&mut store, env); macro_rules! native { ($func:expr) => { Function::new_typed(&mut store, $func) }; } macro_rules! func { ($func:expr) => { Function::new_typed_with_env(&mut store, &func_env, $func) }; } macro_rules! github { ($name:expr) => { concat!("github.com/offchainlabs/nitro/", $name) }; } let imports = imports! { "go" => { "debug" => native!(runtime::go_debug), "runtime.resetMemoryDataView" => native!(runtime::reset_memory_data_view), "runtime.wasmExit" => func!(runtime::wasm_exit), "runtime.wasmWrite" => func!(runtime::wasm_write), "runtime.nanotime1" => func!(runtime::nanotime1), "runtime.walltime" => func!(runtime::walltime), "runtime.walltime1" => func!(runtime::walltime1), "runtime.scheduleTimeoutEvent" => func!(runtime::schedule_timeout_event), "runtime.clearTimeoutEvent" => func!(runtime::clear_timeout_event), "runtime.getRandomData" => func!(runtime::get_random_data), "syscall/js.finalizeRef" => func!(syscall::js_finalize_ref), "syscall/js.stringVal" => func!(syscall::js_string_val), "syscall/js.valueGet" => func!(syscall::js_value_get), "syscall/js.valueSet" => func!(syscall::js_value_set), "syscall/js.valueDelete" => func!(syscall::js_value_delete), "syscall/js.valueIndex" => func!(syscall::js_value_index), "syscall/js.valueSetIndex" => func!(syscall::js_value_set_index), "syscall/js.valueCall" => func!(syscall::js_value_call), "syscall/js.valueInvoke" => func!(syscall::js_value_invoke), "syscall/js.valueNew" => func!(syscall::js_value_new), "syscall/js.valueLength" => func!(syscall::js_value_length), "syscall/js.valuePrepareString" => func!(syscall::js_value_prepare_string), "syscall/js.valueLoadString" => func!(syscall::js_value_load_string), "syscall/js.valueInstanceOf" => func!(syscall::js_value_instance_of), "syscall/js.copyBytesToGo" => func!(syscall::js_copy_bytes_to_go), "syscall/js.copyBytesToJS" => func!(syscall::js_copy_bytes_to_js), "go-js-test/syscall.debugPoolHash" => func!(syscall::debug_pool_hash), github!("wavmio.getGlobalStateBytes32") => func!(wavmio::get_global_state_bytes32), github!("wavmio.setGlobalStateBytes32") => func!(wavmio::set_global_state_bytes32), github!("wavmio.getGlobalStateU64") => func!(wavmio::get_global_state_u64), github!("wavmio.setGlobalStateU64") => func!(wavmio::set_global_state_u64), github!("wavmio.readInboxMessage") => func!(wavmio::read_inbox_message), github!("wavmio.readDelayedInboxMessage") => func!(wavmio::read_delayed_inbox_message), github!("wavmio.resolvePreImage") => func!(wavmio::resolve_preimage), github!("arbos/programs.activateProgramRustImpl") => func!(user::stylus_activate), github!("arbos/programs.callProgramRustImpl") => func!(user::stylus_call), github!("arbos/programs.readRustVecLenImpl") => func!(user::read_rust_vec_len), github!("arbos/programs.rustVecIntoSliceImpl") => func!(user::rust_vec_into_slice), github!("arbos/programs.rustConfigImpl") => func!(user::rust_config_impl), github!("arbos/programs.rustEvmDataImpl") => func!(user::evm_data_impl), github!("arbcompress.brotliCompress") => func!(arbcompress::brotli_compress), github!("arbcompress.brotliDecompress") => func!(arbcompress::brotli_decompress), }, }; let instance = match Instance::new(&mut store, &module, &imports) { Ok(instance) => instance, Err(err) => panic!("Failed to create instance: {}", err.red()), }; let memory = match instance.exports.get_memory("mem") { Ok(memory) => memory.clone(), Err(err) => panic!("Failed to get memory: {}", err.red()), }; let resume = match instance.exports.get_typed_function(&store, "resume") { Ok(resume) => resume, Err(err) => panic!("Failed to get the {} func: {}", "resume".red(), err.red()), }; let getsp = match instance.exports.get_typed_function(&store, "getsp") { Ok(getsp) => getsp, Err(err) => panic!("Failed to get the {} func: {}", "getsp".red(), err.red()), }; let env = func_env.as_mut(&mut store); env.memory = Some(memory); env.exports.resume = Some(resume); env.exports.get_stack_pointer = Some(getsp); (instance, func_env, store) } #[derive(Error, Debug)] pub enum Escape { #[error("program exited with status code `{0}`")] Exit(u32), #[error("jit failed with `{0}`")] Failure(String), #[error("hostio failed with `{0}`")] HostIO(String), #[error("comms with child instance failed with `{0}`")] Child(ErrReport), #[error("hostio socket failed with `{0}`")] SocketError(#[from] io::Error), } pub type MaybeEscape = Result<(), Escape>; impl Escape { pub fn exit(code: u32) -> MaybeEscape { Err(Self::Exit(code)) } pub fn hostio<S: std::convert::AsRef<str>>(message: S) -> MaybeEscape { Err(Self::HostIO(message.as_ref().to_string())) } pub fn failure<T, S: std::convert::AsRef<str>>(message: S) -> Result<T, Escape> { Err(Self::Failure(message.as_ref().to_string())) } } impl From<RuntimeError> for Escape { fn from(outcome: RuntimeError) -> Self { match outcome.downcast() { Ok(escape) => escape, Err(outcome) => Escape::Failure(format!("unknown runtime error: {outcome}")), } } } pub type WasmEnvMut<'a> = FunctionEnvMut<'a, WasmEnv>; pub type Inbox = BTreeMap<u64, Vec<u8>>; pub type Oracle = BTreeMap<Bytes32, Vec<u8>>; pub type ModuleAsm = Arc<[u8]>; #[derive(Default)] pub struct WasmEnv { /// Mechanism for reading and writing the module's memory pub memory: Option<Memory>, /// Go's general runtime state pub go_state: GoRuntimeState, /// The state of Go's js runtime pub js_state: JsState, /// An ordered list of the 8-byte globals pub small_globals: [u64; 2], /// An ordered list of the 32-byte globals pub large_globals: [Bytes32; 2], /// An oracle allowing the prover to reverse keccak256 pub preimages: Oracle, /// A collection of programs called during the course of execution pub module_asms: HashMap<Bytes32, ModuleAsm>, /// The sequencer inbox's messages pub sequencer_messages: Inbox, /// The delayed inbox's messages pub delayed_messages: Inbox, /// The purpose and connections of this process pub process: ProcessEnv, /// The exported funcs callable in hostio pub exports: WasmEnvFuncs, } impl WasmEnv { pub fn cli(opts: &Opts) -> Result<Self> { let mut env = WasmEnv::default(); env.process.forks = opts.forks; env.process.debug = opts.debug; let mut inbox_position = opts.inbox_position; let mut delayed_position = opts.delayed_inbox_position; for path in &opts.inbox { let mut msg = vec![]; File::open(path)?.read_to_end(&mut msg)?; env.sequencer_messages.insert(inbox_position, msg); inbox_position += 1; } for path in &opts.delayed_inbox { let mut msg = vec![]; File::open(path)?.read_to_end(&mut msg)?; env.delayed_messages.insert(delayed_position, msg); delayed_position += 1; } if let Some(path) = &opts.preimages { let mut file = BufReader::new(File::open(path)?); let mut preimages = Vec::new(); let filename = path.to_string_lossy(); loop { let mut size_buf = [0u8; 8]; match file.read_exact(&mut size_buf) { Ok(()) => {} Err(err) if err.kind() == ErrorKind::UnexpectedEof => break, Err(err) => bail!("Failed to parse {filename}: {}", err), } let size = u64::from_le_bytes(size_buf) as usize; let mut buf = vec![0u8; size]; file.read_exact(&mut buf)?; preimages.push(buf); } for preimage in preimages { let mut hasher = Keccak256::new(); hasher.update(&preimage); let hash = hasher.finalize().into(); env.preimages.insert(hash, preimage); } } fn parse_hex(arg: &Option<String>, name: &str) -> Result<Bytes32> { match arg { Some(arg) => { let mut arg = arg.as_str(); if arg.starts_with("0x") { arg = &arg[2..]; } let mut bytes32 = Bytes32::default(); hex::decode_to_slice(arg, &mut bytes32) .wrap_err_with(|| format!("failed to parse {} contents", name))?; Ok(bytes32) } None => Ok(Bytes32::default()), } } let last_block_hash = parse_hex(&opts.last_block_hash, "--last-block-hash")?; let last_send_root = parse_hex(&opts.last_send_root, "--last-send-root")?; env.small_globals = [opts.inbox_position, opts.position_within_message]; env.large_globals = [last_block_hash, last_send_root]; Ok(env) } pub fn send_results(&mut self, error: Option<String>) { let writer = match &mut self.process.socket { Some((writer, _)) => writer, None => return, }; macro_rules! check { ($expr:expr) => {{ if let Err(comms_error) = $expr { eprintln!("Failed to send results to Go: {comms_error}"); panic!("Communication failure"); } }}; } if let Some(error) = error { check!(socket::write_u8(writer, socket::FAILURE)); check!(socket::write_bytes(writer, &error.into_bytes())); check!(writer.flush()); return; } check!(socket::write_u8(writer, socket::SUCCESS)); check!(socket::write_u64(writer, self.small_globals[0])); check!(socket::write_u64(writer, self.small_globals[1])); check!(socket::write_bytes32(writer, &self.large_globals[0])); check!(socket::write_bytes32(writer, &self.large_globals[1])); check!(writer.flush()); } } pub struct ProcessEnv { /// Whether to create child processes to handle execution pub forks: bool, /// Whether to print debugging info pub debug: bool, /// Mechanism for asking for preimages and returning results pub socket: Option<(BufWriter<TcpStream>, BufReader<TcpStream>)>, /// The last preimage received over the socket pub last_preimage: Option<([u8; 32], Vec<u8>)>, /// A timestamp that helps with printing at various moments pub timestamp: Instant, /// How long to wait on any child threads to compute a result pub child_timeout: Duration, /// Whether the machine has reached the first wavmio instruction pub reached_wavmio: bool, } impl Default for ProcessEnv { fn default() -> Self { Self { forks: false, debug: false, socket: None, last_preimage: None, timestamp: Instant::now(), child_timeout: Duration::from_secs(15), reached_wavmio: false, } } } #[derive(Default)] pub struct WasmEnvFuncs { /// Calls `resume` from the go runtime pub resume: Option<TypedFunction<(), ()>>, /// Calls `getsp` from the go runtime pub get_stack_pointer: Option<TypedFunction<(), i32>>, }
interface DialogProps { open: boolean; actionClose: () => void; actionConfirm: () => void; title: string; content: string; labelConfirm?: string; } export default function Dialog({ open, actionClose, title, content, labelConfirm, actionConfirm, }: DialogProps) { if (!open) { return ""; } return ( <div className="relative z-10" aria-labelledby="modal-title" role="dialog" aria-modal="true" > <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div> <div className="fixed inset-0 z-10 w-screen overflow-y-auto"> <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0"> <div className="relative transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg"> <div className="bg-white px-4 pb-4 pt-5 sm:p-6 sm:pb-4"> <div className="sm:flex sm:items-start"> <div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left"> <h3 className="text-base font-semibold leading-6 text-gray-900" id="modal-title" > {title} </h3> <div className="mt-2"> <p className="text-sm text-gray-500">{content}</p> </div> </div> </div> </div> <div className="bg-gray-50 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6"> <button onClick={actionConfirm} type="button" className="inline-flex w-full justify-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-500 sm:ml-3 sm:w-auto" > {labelConfirm || "Confirmar"} </button> <button onClick={actionClose} type="button" className="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:mt-0 sm:w-auto" > Cancelar </button> </div> </div> </div> </div> </div> ); }
%% Extract XY coordinates and plot % This program extracts XY coordinates from u-track and saves and plots % them for each track. Note you need to use Matlab 2013b or later. % Matt Akamatsu, Drubin lab, December 2015 % modified 10/2016 to incorporate a second track rejection step from Josh % Ferguson (OSU, Kural lab). This step removes tracks that have erratic intensity jumps between timepoints. % Select TrackFeatures file function extractXYcoordinates_useCellMask(data) disp('running extractXYcoords'); %clear; %% second track rejection step from Josh Ferguson (OSU, Kural lab). % This step removes tracks that have erratic intensity jumps between timepoints. rejectErraticTracks = true; %% set "makefigs" to false if you don't want those figures makefigs = false; saveallgraphs = false; % number of tracks to plot, for track positions (fig 1) and track durations (fig 5). set to -1 if you want to plot all tracks. % Plots of lifetime distributions do not change based on this number. nbTracksToPlot = 500; %-1 %% Choose cutoff for lifetime distribution. % The program will discard lifetimes less than this value (in seconds) if "cutLifetimes = true". cutLifetimes = true; lifetimesCutoffSeconds = 3 % If you ran cmeAnalysis and chose a region of the movie (cell mask), turn % this on to keep only the tracks within the mask. useCellMask = true; % Later this program could scan through pre-defined folder structures... %% Ask for file name if ~exist('data', 'var') curfilename = input('What do you want to call this file? ', 's'); pixel_size = input('What was the pixel size of the camera in nm? '); frame_time = input('How many seconds between each frame? '); load('previous_file.mat') [utrack_file, utrack_folder_name] = uigetfile('*.mat','Select the tracking_result.mat or trackedFeatures.mat file.', previous_file); if isdir(utrack_folder_name) previous_file = fullfile(utrack_folder_name, utrack_file); save('previous_file', 'previous_file') else disp('You did not pick a folder.') return end else curfilename = data.curfilename; pixel_size = data.pixelSize * (1e9)/data.M; frame_time = data.framerate; utrack_file = 'trackedFeatures.mat'; utrack_folder_name = strcat(data.source, 'Tracking/'); end lifetimesCutoffFrames = ceil(lifetimesCutoffSeconds/frame_time) utrack_full = fullfile(utrack_folder_name, utrack_file); uTrackParent = open(utrack_full); uTracks = uTrackParent.tracksFinal; if useCellMask load('previous_file.mat') if (exist('data', 'var')) cellmask_file = 'cellmask.tif'; cellmask_folder_name = strcat(data.source, 'Detection/'); else [cellmask_file, cellmask_folder_name] = uigetfile('*.tif','Select the cellmask file.', previous_file); end if isdir(cellmask_folder_name) previous_file = fullfile(cellmask_folder_name, cellmask_file); save('previous_file', 'previous_file') else display('You did not pick a folder.') return end cellmask_full = fullfile(cellmask_folder_name, cellmask_file); cellmask = readtiff(cellmask_full); %or imread % % flip Y % cellmaskUnflipped = cellmask; % % cellmask = flipud(cellmask); % % % % separatorsMask = utrack_folder_name==pathsep; % [~, ] % % curCellMask = utrack_folder_name end % if isdir(ref_img_folder_name) % previous_file = fullfile(ref_img_folder_name, ref_img_file); % save('previous_file', 'previous_file') % else % display('You did not pick a folder.') % return % end alltracks = {}; alltracksNoCutoff = {}; trackLengths = []; trackLengthsNoCutoff = []; % n is the current track number. % calculate number of tracks (no cutoff) nbTracksNoCutoff = length(uTracks); % Identify the number of XY data points for each track % NOTE will fail currently f you have splitting and merging tracks. it % assumes you only have nomerging tracks. % Find the x and y values for the first time point of each track, and save % as xs and ys % Keep ONLY if the first time point of the track is within the cell mask. nn = 1; for n = 1:nbTracksNoCutoff trackLengthsNoCutoff(n) = length(uTracks(n).tracksCoordAmpCG(1,:))/8; xs = []; ys = []; Is = []; Istd = []; for m = 1:trackLengthsNoCutoff(n) curIndex = (m-1)*8+1; %Find where X and Y are (indecies) % Just for the primary track. ignores track splits and merges. xs(m,1) = uTracks(n).tracksCoordAmpCG(1, curIndex); ys(m,1) = uTracks(n).tracksCoordAmpCG(1, curIndex+1); Is(m,1) = uTracks(n).tracksCoordAmpCG(1, curIndex+3); Istd(m,1) = uTracks(n).tracksCoordAmpCG(1, curIndex+7); end % This treatment of tracks ignores merging and splitting events. This % might cause problems later. trackend = uTracks(n).seqOfEvents(end,1); trackbeg = uTracks(n).seqOfEvents(1,1); firstX = round(xs(1)); firstY = round(ys(1)); firstTimePoint = [round(xs(1)), round(ys(1))]; firstTimePoints(n,:) = firstTimePoint; curMaskState(n) = sum(cellmask(firstTimePoint)); timepointsAndMask(n,:) = [firstTimePoints(n) curMaskState(n)]; %disp(cellmask(firstTimePoint)); if useCellMask % if cellmask(firstTimePoint) if cellmask(firstY, firstX) trackduration = transpose(trackbeg:trackend); alltracksNoCutoff(nn).xs = xs; alltracksNoCutoff(nn).ys = ys; alltracksNoCutoff(nn).Is = Is; alltracksNoCutoff(nn).Istd = Istd; alltracksNoCutoff(nn).trackduration = trackduration; alltracksNoCutoff(nn).tracklength = trackLengthsNoCutoff(n); alltracksNoCutoff(nn).lifetime = alltracksNoCutoff(nn).tracklength * frame_time; nn = nn+1; end else trackduration = transpose(trackbeg:trackend); alltracksNoCutoff(n).xs = xs; alltracksNoCutoff(n).ys = ys; alltracksNoCutoff(n).Is = Is; alltracksNoCutoff(n).Istd = Istd; alltracksNoCutoff(n).trackduration = trackduration; alltracksNoCutoff(n).tracklength = trackLengthsNoCutoff(n); alltracksNoCutoff(n).lifetime = alltracksNoCutoff(n).tracklength * frame_time; end end % disp('halfway there'); %% Added by Josh Ferguson, Kural Group, The Ohio State University, Sep 21 2016. Modified by Matt Akamatsu if rejectErraticTracks % record number of original tracks lengthAlltracksIncludingErratic = length(alltracksNoCutoff); disp('Rejecting erratic tracks...') % remove "erratic" tracks (ones that don't follow a linear progression % of intensity change over a, say, 4 frame window) alltracksNoCutoff = trace_rejection_function(alltracksNoCutoff, lifetimesCutoffFrames); lengthAllTracks = length(alltracksNoCutoff); % display how many tracks you rejected. % fprintf('%d erratic tracks rejected. \n', lengthAlltracksIncludingErratic - lengthAllTracks) end if cutLifetimes nn = 1; for n = 1:length(alltracksNoCutoff) % Remove tracks with lifetimes < cutoff value listed at top of program if alltracksNoCutoff(n).lifetime >= lifetimesCutoffSeconds trackLengths(nn) = alltracksNoCutoff(n).tracklength; alltracks(nn).xs = alltracksNoCutoff(n).xs; alltracks(nn).ys = alltracksNoCutoff(n).ys; alltracks(nn).Is = alltracksNoCutoff(n).Is; alltracks(nn).Istd = alltracksNoCutoff(n).Istd; alltracks(nn).trackduration = alltracksNoCutoff(n).trackduration; alltracks(nn).tracklength = alltracksNoCutoff(n).tracklength; alltracks(nn).lifetime = alltracksNoCutoff(n).lifetime; nn = nn + 1; end end else alltracks = alltracksNoCutoff; nn = 1; for n = 1:length(alltracksNoCutoff) trackLengths(nn) = alltracksNoCutoff(n).tracklength; nn = nn+1; end end nbTracks = length(alltracks); % If nbTracksToPlot is -1, then nbTracksToPlot becomes same value as nbTracks % And if nbTracksToPlot is > nbTracks then set it to nbTracks if nbTracksToPlot == -1 nbTracksToPlot = nbTracks; elseif nbTracksToPlot > nbTracks nbTracksToPlot = nbTracks; end LifetimesNoCutoff = (trackLengthsNoCutoff*frame_time)'; Lifetimes = (trackLengths*frame_time)'; %% Make a csv file for Associate_tracks program % Format is parent, time, x, y assocarray = []; for n = 1:nbTracks nLarge = n+10^9; % Format Imaris gives for track number. % curassocfile = [repmat(nLarge, trackLength(n), 1) alltracks(n).trackduration alltracks(n).xs alltracks(n).ys]; % Edited 12/21/15 by Julian to convert pixels to nm for input into % 'Associate_tracks.m' curassocarray = [alltracks(n).xs*pixel_size, alltracks(n).ys*pixel_size, NaN(trackLengths(n), 1), NaN(trackLengths(n), 1), NaN(trackLengths(n), 1), alltracks(n).trackduration, repmat(nLarge, trackLengths(n), 1), NaN(trackLengths(n), 1)]; % Edited 12/21/15 by Julian to avoid adding NaNs from tracking to the % output file which breaks 'Associate_tracks.m' % MA edit further to remove just tracks with NaN in first or last % element % if ~isnan(alltracks(n).xs) if isnan(alltracks(n).xs(1))||isnan(alltracks(n).xs(end)) nanTrackNumbers(n) = 1; % list of tracks that start or end with NaN (probably due to track splitting) % nanTracks{n} = curassocarray; else assocarray = [assocarray; curassocarray]; end end % convert to table assoctable = array2table(assocarray, 'VariableNames', {'PositionX', 'PositionY', 'Unit', 'Category', 'Collection', 'Time', 'TrackID', 'ID'}); % Rearrange by time not track assoctablesort = sortrows(assoctable, 'Time'); % Save as csv file assocfilename = fullfile(utrack_folder_name, [curfilename '_utrack_Position.csv']); %writetable(assoctablesort, 'utrack_Positions.csv') writetable(assoctablesort, assocfilename); % Save a csv file with raw lifetimes of tracks lifetimeTable = array2table(Lifetimes); lifetimeFilename = fullfile(utrack_folder_name, [curfilename '_utrack_Lifetimes.csv']); writetable(lifetimeTable, lifetimeFilename); meanLifetime = mean(Lifetimes); stdLifetime = std(Lifetimes); %% Plot track durations trackdurations = {}; for n = 1:nbTracks trackdurations{n} = alltracks(n).trackduration; end if makefigs trackPlottingOrder = randperm(nbTracks, nbTracksToPlot); figure(1); clf; for n = trackPlottingOrder xs = alltracks(n).xs; ys = alltracks(n).ys; xsNoNan = xs(~isnan(xs)); ysNoNan = ys(~isnan(ys)); plot(xsNoNan,-ysNoNan), hold all; end title(sprintf('%2.f tracks', nbTracksToPlot)); xlabel('x'); ylabel('y'); figure(4); clf; colormap('jet'); for n = trackPlottingOrder % plot(tracksall{n}, n:length(tracksall{n}):n, '.'); hold all; scatter(trackdurations{n}*frame_time, repmat(n,length(trackdurations{n}),1)', [], repmat(Lifetimes(n),length(trackdurations{n}),1),'.'); hold all; end title(sprintf('Track durations for %2.f tracks', nbTracksToPlot)); xlabel('Time (seconds)'); ylabel('Track number'); set(gca, 'box', 'on'); h = colorbar; h.Label.String = 'Lifetime(s)'; figure(2); clf; for i = 1:20 subplot(5,4,i); figure(2); errorbar(alltracks(i).Is, alltracks(i).Istd); hold on; xlabel('Time (frames)'); ylabel('Intensity'); end title('Intensity vs frames for 20 tracks'); figure(3); clf; histogram(Lifetimes); xlabel('Lifetime (seconds)'); title(sprintf('Lifetimes \n %2.f � %2.f s', meanLifetime, stdLifetime)); %% Plot cumulative distribution of lifetimes [yy, xx] = ecdf(Lifetimes); t50mask = yy<0.55&yy>0.45; t50 = mean(xx(t50mask)); figure(5); clf; ecdf(Lifetimes); title(sprintf('Track lifetimes cumulative distribution \n t50 = %2.f � %2.f s', t50, stdLifetime)); xlabel('Lifetime (s)'); ylabel('Proportion of population'); end %% Save all variables % this is off for now. comment out to save all the data. %save(fullfile(utrack_folder_name, curfilename)) fprintf('saved %s \n in %s \n', [curfilename '_utrack_Position.csv'], utrack_folder_name) %% Save graphs % if saveallgraphs % % saveCurGraphsInLocation([curfilename '_utrack'], utrack_folder_name, 1:5); % % end
package org.university; import lombok.EqualsAndHashCode; import lombok.Getter; import java.util.ArrayList; import java.util.List; @Getter @EqualsAndHashCode public class Library implements IManageable { private final List<Item> items = new ArrayList<>(); private final List<Patron> patrons = new ArrayList<>(); public void registerPatron(Patron patron){ patrons.add(patron); } public void lendItem(Patron patron, Item item){ if(!patrons.contains(patron)){ System.err.println("Patron is not registered!"); } else if(!items.contains(item)){ System.err.println("No a such book in a library!"); } else { patron.borrow(item); } } public void returnItem(Patron patron, Item item){ if(!patrons.contains(patron)){ System.err.println("Patron is not registered!"); } else if(!items.contains(item)){ System.err.println("No a such book in a library!"); } else { patron.returnItem(item); } } public void add(Item item){ if(items.contains(item)){ System.err.println("This book already exist"); } else{ items.add(item); System.out.println("Item was successfully added"); } } public void remove(Item item){ if(!items.contains(item)){ System.err.println("No a such book in a library!"); } else{ items.remove(item); System.out.println("Item was successfully removed"); } } public void listAvailable(){ items.stream() .filter(item -> !item.isBorrowed) .forEach(System.out::println); } public void listBorrowed(){ items.stream() .filter(item -> item.isBorrowed) .forEach(System.out::println); } }
<!-- create 4 divs, one for each color, and assign a number from 0 - 3 create a start button random integer selector (MDN "random integer") - which color to light up function getRandomIntInclusive(0, 3) { return Math.floor(Math.random() * (max - min + 1)) + min random number makes color flash (change opacity) // convert random number into a color and flash - use data-id for number/color? // flash: color is 50% opacity unless random number = color id number, then it is 100% figure out how to track the order of numbers/colors/flashes and compare to user's input (Konami Code): Simon: randomOrder, randomPattern, randomSequence, simonSequence Player: playerResponse, playerSequence add a tone to the flash: E-note (blue, lower right); C♯-note (yellow, lower left); A-note (red, upper right). E-note (green, upper left, an octave lower than blue); Justin's Konami Code: "use strict"; var konamiCode = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13]; var keysCorrect = []; $(document).keyup(function(event){ console.log(event.keyCode); keysCorrect.push(event.keyCode); ***comparing just the last number rather than the entire array*** if (keysCorrect[keysCorrect.length-1] != konamiCode[keysCorrect.length-1]) { keysCorrect = []; } if (keysCorrect.length == konamiCode.length) { $("body").css("background-image", "url(/img/up1.jpeg"); alert("You have added 30 lives!"); } }); add the random number to an array <!how to add another number if user's input is correct or stop game if not correct --> <!-- how to slowly increase speed as array gets longer --> <!doctype> <html> <head> <title>Simple Simon Game</title> <link rel="stylesheet" href="index.css"> </head> <body> <button id="start">Start</button> <div class="container"> <div class="game-button" id="green"></div> <div class="game-button" id="red"></div> <div class="game-button" id="blue"></div> <div class="game-button" id="yellow"></div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> // ******1- generate random number and flash - math.random // ******2- user inputs a number, lights up - // ******3- compare simon and user numbers // ******4- if numbers are the same, push to arrays; if not, game over // ******5- continue to next random number or end game "use strict"; var simonSequence = []; var playerSequence = []; var colors = ["#green","#red","#blue","#yellow"]; function getRandomColor() { var randomNumber = Math.floor(Math.random() * 4); return colors[randomNumber]; } function simonTurn() { var randomColor = getRandomColor(); var duration = 1000; simonSequence.push(randomColor); simonSequence.forEach(function(game_button, index) { setTimeout(function() { console.log(game_button); $(game_button).animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); }, (duration*(index+1))); }); // console.log(randomNumber); // if (randomNumber == 0) { // $("#green").animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); // simonSequence.push("#green") // } // if (randomNumber == 1) { // $("#red").animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); // simonSequence.push("#red") // } // if (randomNumber == 2) { // $("#blue").animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); // simonSequence.push("#blue") // } // if (randomNumber == 3) { // $("#yellow").animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); // simonSequence.push("#yellow") // } // console.log(simonSequence); } function userTurn() { $(".game-button").click(function() { $(this).animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); var id = $(this).attr("id"); // console.log(playerSequence); playerSequence.push("#" + id); if (simonSequence.length == playerSequence.length){ // console.log("it matches length"); console.log(playerSequence.join(",")); console.log(simonSequence.join(",")); if (playerSequence.join(",") == simonSequence.join(",")){ console.log("it matches value"); playerSequence = []; // playerSequence.join(",") console.log(playerSequence); simonTurn(); } } }); } // $(".game-button").prop("disabled",true) // $("#start").prop("disabled",true); // var randomNumber = getRandomIntInclusive(0, 3); // if (randomNumber == 0) { // simonSequence.push("green") // $("#green").animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); // } if (randomNumber == 1) { // simonSequence.push("red") // $("#red").animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); // } if (randomNumber == 2) { // simonSequence.push("blue") // $("#blue").animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); // } if (randomNumber == 3) { // simonSequence.push("yellow") // $("#yellow").animate({opacity: 1}, 500).animate({opacity: 0.6}, 500); // } // console.log(randomNumber); // } // *******2- user inputs a number, lights up - // function allowUserInput(){ // if (playerSequence[playerSequence.length-1] == simonSequence[playerSequence.length-1]) { // $(".game-button").prop("disabled",false) // } // } // for (var i = 0; i < 10; i++) { // simonSequence.push(randomNumber); // } // console.log(simonSequence); // ********3- compare simon and user numbers // function compareTurn() { // if (simonSequence[simonSequence.length-1] != playerSequence[simonSequence.length-1]) { // alert("game over"); // } // if (simonSequence[simonSequence.length-1] == playerSequence[simonSequence.length-1]) { // } simonTurn(); // } // if simon's number randomNumber = player's number, then run simon turn again with another random number // function compareTurn() { // if (playerSequence.join(",") != simonSequence.join(",")) { // alert("GAME OVER!") // simonSequence = [] // playerSequence = [] // roundNumber = 0 // $("#start").prop("disabled",false); // }else if (simonSequence.length == playerSequence.length) { // alert("Congratulations!") // $("#start").prop("disabled",false); // playerSequence = [] // } // } // function animateButtons() { // simonSequence.forEach(function(color, index, simonSequence) { // setTimeout(function() { // $('#' + color).animate({ // opacity: 1 // }, 500).animate({ // opacity: 0.5 // }, 1000, function() { // $(this).css('opacity', ''); // }); // }, (index * 1000)+1) // }) // } $("#start").click(function() { simonTurn(); userTurn(); }); // ************4- if numbers are the same, push to arrays; if not, game over // $("#start").click(function(){ // simonTurn(); // }); // $(document).click(function(event){ // console.log(event.clickSequence); // playerSequence.push(event.clickSequence); // if (playerSequence[playerSequence.length-1] != simonSequence[playerSequence.length-1]) { // playerSequence = []; // } // }) // console.log(playerSequence); // 5- continue to next random number or end game // $(document).keyup(function(event){ // var userEnteredKey = event.keyCode; // console.log(userEnteredKey); // if (userEnteredKey == code[index]) { // index++; // } else { // index = 0; // console.log("You entered the wrong button, restarting."); // } // if (index == code.length) { // index = 0; // alert("You have 30 lives!") // } // }); </script> </body> </html>
package hello.springmvc.basic; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @Slf4j public class LogTestcontroller { // 롬복(@Slf4j) 사용하면 생략 가능 // private final Logger log = LoggerFactory.getLogger(getClass()); //클래스 지정 @RequestMapping("/log-test") public String logTest() { String name = "Spring"; //로그 찍을 때 어떤 상태의 레벨인지 지정 가능 //디폴트로 운영서버는 info부터(info, warn, error) 출력 log.trace("trace log = {}", name); log.debug("debug log = {}", name); // 디버그 할 때 봄(개발서버 같은 곳에서) log.info("info log = {}", name); // 중요한 정보야 (비즈니스 로직이나 OS에서도 봐야하거나) log.warn("warn log = {}", name); // 경고 log.error("error log = {}", name); // 에러 return "ok"; } }
import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { InterviewerSkill } from 'src/app/model/interviewerSkill'; import { InterviewerSkillService } from 'src/app/service/interviewer-skill.service'; import { RestDataSource } from 'src/app/service/restdataSource'; import { InterviewerSkillFormComponent } from '../interviewer-skill-form/interviewer-skill-form.component'; import { Router } from '@angular/router'; @Component({ selector: 'app-interviewer-skill-view', templateUrl: './interviewer-skill-view.component.html', styleUrls: ['./interviewer-skill-view.component.css'], }) export class InterviewerSkillViewComponent implements OnInit, AfterViewInit { interviewerSkills!: InterviewerSkill[]; displayedColumns: string[] = [ 'interviewerSkillId', 'interviewerSkillName', 'action', ]; dataSource!: MatTableDataSource<InterviewerSkill>; @ViewChild(MatPaginator) paginator!: MatPaginator; @ViewChild(MatSort) sort!: MatSort; constructor( private interviewerSkillService: InterviewerSkillService, private dialog: MatDialog, private restData: RestDataSource ) { this.dataSource = new MatTableDataSource(); this.getInterviewerSkills(); } ngAfterViewInit() { this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } ngOnInit(): void {} applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } getInterviewerSkills() { this.restData.getInterviewerSkills().subscribe({ next: (resp) => { console.log(resp); this.interviewerSkills = resp; this.dataSource.data = resp; }, }); } addSkill() { this.dialog.open(InterviewerSkillFormComponent); } deleteSkill(interviewerSkill: InterviewerSkill) { this.restData .deleteInterviewerSkillById(interviewerSkill.interviewerSkillId) .subscribe({ next: (res) => { this.getInterviewerSkills(); }, error: (err) => console.log(err), }); } editSkill(interviewerSkill: InterviewerSkill) { console.log(interviewerSkill); this.dialog.open(InterviewerSkillFormComponent, { data: interviewerSkill, }); } }
import React from 'react' import useSpotify from '../hooks/useSpotify' import { msToMins } from '../lib/time' import { useRecoilState } from 'recoil' import { currentTrackIdState, isPlayingState } from '../atoms/song-atom' const Song = ({ order, song }: any) => { const spotifyApi = useSpotify() const [currentTrackId, setCurrentTrackId] = useRecoilState(currentTrackIdState) const [isPlaying, setIsPlaying] = useRecoilState(isPlayingState) const playSong = () => { setCurrentTrackId(song.track.id) setIsPlaying(true) spotifyApi .play({ uris: [song.track.uri], }) .catch((err) => { console.warn(err.message) alert("Sorry, this app only works for 'premium' accounts") }) } return ( <div className="grid grid-cols-2 text-gray-500 py-4 px-5 hover:bg-gray-900 rounded-lg cursor-pointer" onClick={playSong} > <div className="flex items-center space-x-4"> <p>{order + 1}</p> <img className="h-10 w-10" src={song.track.album.images[0].url} alt="" /> <div> <p className="w-36 lg:w-64 truncate text-white"> {song.track.name} </p> <p className="w-40">{song.track.artists[0].name}</p> </div> </div> <div className="w-50 flex items-center justify-between ml-auto md:ml-0"> <p className="hidden md:inline">{song.track.album.name}</p> <p>{msToMins(song.track.duration_ms)}</p> </div> </div> ) } export default Song
import React,{useState,useEffect} from 'react' import './Stopwatch.css'; import Footer from './Footer.js' function Stopwatch() { const [time, setTime] = useState(0); const [running, setRunning] = useState(false); useEffect(() => { let interval; if (running) { interval = setInterval(() => { setTime((prevTime) => prevTime + 10); }, 10); } else if (!running) { clearInterval(interval); } return () => clearInterval(interval); }, [running]); return ( <div className="stopwatch"> <div className="numbers"> <span>{("0" + Math.floor((time / 60000) % 60)).slice(-2)}:</span> <span>{("0" + Math.floor((time / 1000) % 60)).slice(-2)}:</span> <span>{("0" + ((time / 10) % 100)).slice(-2)}</span> </div> <div > <button className="buttons" onClick={() => setRunning(true)}>Start</button> <button className="buttons" onClick={() => setRunning(false)}>Stop</button> <button className="buttons" onClick={() => setTime(0)}>Reset</button> </div> <Footer/> </div> ); } export default Stopwatch
// Copyright 2023-2024 Buf Technologies, 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. package vanguard import ( "bytes" "encoding/binary" "errors" "fmt" "io" "net/http" "net/textproto" "strconv" "strings" "time" "connectrpc.com/connect" "google.golang.org/genproto/googleapis/rpc/status" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" ) // grpcClientProtocol implements the gRPC protocol for // processing RPCs received from the client. type grpcClientProtocol struct{} var _ clientProtocolHandler = grpcClientProtocol{} var _ envelopedProtocolHandler = grpcClientProtocol{} func (g grpcClientProtocol) protocol() Protocol { return ProtocolGRPC } func (g grpcClientProtocol) acceptsStreamType(_ *operation, _ connect.StreamType) bool { return true } func (g grpcClientProtocol) extractProtocolRequestHeaders(_ *operation, headers http.Header) (requestMeta, error) { headers.Del("Te") // no need to propagate "te: trailers" to requests in different protocols return grpcExtractRequestMeta("application/grpc", "application/grpc+", headers) } func (g grpcClientProtocol) addProtocolResponseHeaders(meta responseMeta, headers http.Header) int { statusCode := grpcAddResponseMeta("application/grpc+", meta, headers) if len(meta.pendingTrailers) > 0 { if meta.pendingTrailerKeys == nil { meta.pendingTrailerKeys = make(headerKeys, len(meta.pendingTrailers)) } for k := range meta.pendingTrailers { meta.pendingTrailerKeys.add(k) } } for k := range meta.pendingTrailerKeys { headers.Add("Trailer", textproto.CanonicalMIMEHeaderKey(k)) } if !meta.pendingTrailerKeys.contains("Grpc-Status") { headers.Add("Trailer", "Grpc-Status") } if !meta.pendingTrailerKeys.contains("Grpc-Message") { headers.Add("Trailer", "Grpc-Message") } return statusCode } func (g grpcClientProtocol) encodeEnd(_ *operation, end *responseEnd, _ io.Writer, wasInHeaders bool) http.Header { if wasInHeaders { // already recorded this in call to addProtocolResponseHeaders return nil } trailers := make(http.Header, len(end.trailers)+3) grpcWriteEndToTrailers(end, trailers) return trailers } func (g grpcClientProtocol) decodeEnvelope(bytes envelopeBytes) (envelope, error) { return grpcServerProtocol{}.decodeEnvelope(bytes) } func (g grpcClientProtocol) encodeEnvelope(env envelope) envelopeBytes { return grpcServerProtocol{}.encodeEnvelope(env) } func (g grpcClientProtocol) String() string { return g.protocol().String() } // grpcServerProtocol implements the gRPC protocol for // sending RPCs to the server handler. type grpcServerProtocol struct{} var _ serverProtocolHandler = grpcServerProtocol{} var _ serverEnvelopedProtocolHandler = grpcServerProtocol{} func (g grpcServerProtocol) protocol() Protocol { return ProtocolGRPC } func (g grpcServerProtocol) addProtocolRequestHeaders(meta requestMeta, headers http.Header) { grpcAddRequestMeta("application/grpc+", meta, headers) headers.Set("Te", "trailers") } func (g grpcServerProtocol) extractProtocolResponseHeaders(statusCode int, headers http.Header) (responseMeta, responseEndUnmarshaller, error) { return grpcExtractResponseMeta("application/grpc", "application/grpc+", statusCode, headers), nil, nil } func (g grpcServerProtocol) extractEndFromTrailers(_ *operation, trailers http.Header) (responseEnd, error) { return responseEnd{ err: grpcExtractErrorFromTrailer(trailers), trailers: trailers, }, nil } func (g grpcServerProtocol) decodeEnvelope(envBytes envelopeBytes) (envelope, error) { flags := envBytes[0] if flags != 0 && flags != 1 { return envelope{}, fmt.Errorf("invalid compression flag: must be 0 or 1; instead got %d", flags) } return envelope{ compressed: flags == 1, length: binary.BigEndian.Uint32(envBytes[1:]), }, nil } func (g grpcServerProtocol) encodeEnvelope(env envelope) envelopeBytes { var envBytes envelopeBytes if env.compressed { envBytes[0] = 1 } binary.BigEndian.PutUint32(envBytes[1:], env.length) return envBytes } func (g grpcServerProtocol) decodeEndFromMessage(_ *operation, _ *bytes.Buffer) (responseEnd, error) { return responseEnd{}, errors.New("gRPC protocol does not allow embedding result/trailers in body") } func (g grpcServerProtocol) String() string { return g.protocol().String() } // grpcClientProtocol implements the gRPC protocol for // processing RPCs received from the client. type grpcWebClientProtocol struct{} var _ clientProtocolHandler = grpcWebClientProtocol{} var _ envelopedProtocolHandler = grpcWebClientProtocol{} func (g grpcWebClientProtocol) protocol() Protocol { return ProtocolGRPCWeb } func (g grpcWebClientProtocol) acceptsStreamType(_ *operation, _ connect.StreamType) bool { return true } func (g grpcWebClientProtocol) extractProtocolRequestHeaders(_ *operation, headers http.Header) (requestMeta, error) { return grpcExtractRequestMeta("application/grpc-web", "application/grpc-web+", headers) } func (g grpcWebClientProtocol) addProtocolResponseHeaders(meta responseMeta, headers http.Header) int { return grpcAddResponseMeta("application/grpc-web+", meta, headers) } func (g grpcWebClientProtocol) encodeEnd(op *operation, end *responseEnd, writer io.Writer, wasInHeaders bool) http.Header { if wasInHeaders { // already recorded this in call to addProtocolResponseHeaders return nil } trailers := make(http.Header, len(end.trailers)+3) grpcWriteEndToTrailers(end, trailers) buffer := op.bufferPool.Get() defer op.bufferPool.Put(buffer) _ = trailers.Write(buffer) // TODO: Send envelope compressed if possible. env := envelope{trailer: true, length: uint32(buffer.Len())} envBytes := g.encodeEnvelope(env) _, _ = writer.Write(envBytes[:]) _, _ = buffer.WriteTo(writer) return nil } func (g grpcWebClientProtocol) decodeEnvelope(bytes envelopeBytes) (envelope, error) { return grpcServerProtocol{}.decodeEnvelope(bytes) } func (g grpcWebClientProtocol) encodeEnvelope(env envelope) envelopeBytes { var envBytes envelopeBytes if env.compressed { envBytes[0] = 1 } if env.trailer { envBytes[0] |= 0x80 } binary.BigEndian.PutUint32(envBytes[1:], env.length) return envBytes } func (g grpcWebClientProtocol) String() string { return g.protocol().String() } // grpcServerProtocol implements the gRPC-Web protocol for // sending RPCs to the server handler. type grpcWebServerProtocol struct{} var _ serverProtocolHandler = grpcWebServerProtocol{} var _ serverEnvelopedProtocolHandler = grpcWebServerProtocol{} func (g grpcWebServerProtocol) protocol() Protocol { return ProtocolGRPCWeb } func (g grpcWebServerProtocol) addProtocolRequestHeaders(meta requestMeta, headers http.Header) { grpcAddRequestMeta("application/grpc-web+", meta, headers) } func (g grpcWebServerProtocol) extractProtocolResponseHeaders(statusCode int, headers http.Header) (responseMeta, responseEndUnmarshaller, error) { return grpcExtractResponseMeta("application/grpc-web", "application/grpc-web+", statusCode, headers), nil, nil } func (g grpcWebServerProtocol) extractEndFromTrailers(_ *operation, _ http.Header) (responseEnd, error) { return responseEnd{}, errors.New("gRPC-Web protocol does not use HTTP trailers") } func (g grpcWebServerProtocol) decodeEnvelope(envBytes envelopeBytes) (envelope, error) { flags := envBytes[0] if flags&0b0111_1110 != 0 { // invalid bits are set return envelope{}, fmt.Errorf("invalid frame flags: only highest and lowest bits may be set; instead got %d", flags) } return envelope{ compressed: flags&1 != 0, trailer: flags&0x80 != 0, length: binary.BigEndian.Uint32(envBytes[1:]), }, nil } func (g grpcWebServerProtocol) encodeEnvelope(env envelope) envelopeBytes { // Request streams don't have trailers, so we can re-use the gRPC implementation // without worrying about gRPC-Web's in-body trailers. return grpcServerProtocol{}.encodeEnvelope(env) } func (g grpcWebServerProtocol) decodeEndFromMessage(_ *operation, buffer *bytes.Buffer) (responseEnd, error) { headerLines := bytes.Split(buffer.Bytes(), []byte{'\r', '\n'}) trailers := make(http.Header, len(headerLines)) for i, headerLine := range headerLines { // may have trailing newline, so ignore resulting trailing empty line if len(headerLine) == 0 { continue } pos := bytes.IndexByte(headerLine, ':') if pos == -1 { return responseEnd{}, fmt.Errorf("response body included malformed trailer at line %d", i+1) } trailers.Add(string(headerLine[:pos]), strings.TrimSpace(string(headerLine[pos+1:]))) } return responseEnd{ err: grpcExtractErrorFromTrailer(trailers), trailers: trailers, }, nil } func (g grpcWebServerProtocol) String() string { return g.protocol().String() } func grpcExtractRequestMeta(contentTypeShort, contentTypePrefix string, headers http.Header) (requestMeta, error) { var reqMeta requestMeta if err := grpcExtractTimeoutFromHeaders(headers, &reqMeta); err != nil { return reqMeta, err } contentType := headers.Get("Content-Type") if contentType == contentTypeShort { reqMeta.codec = CodecProto } else { reqMeta.codec = strings.TrimPrefix(contentType, contentTypePrefix) } headers.Del("Content-Type") reqMeta.compression = headers.Get("Grpc-Encoding") headers.Del("Grpc-Encoding") reqMeta.acceptCompression = parseMultiHeader(headers.Values("Grpc-Accept-Encoding")) headers.Del("Grpc-Accept-Encoding") return reqMeta, nil } func grpcExtractResponseMeta(contentTypeShort, contentTypePrefix string, statusCode int, headers http.Header) responseMeta { var respMeta responseMeta contentType := headers.Get("Content-Type") switch { case contentType == contentTypeShort: respMeta.codec = CodecProto case strings.HasPrefix(contentType, contentTypePrefix): respMeta.codec = strings.TrimPrefix(contentType, contentTypePrefix) default: respMeta.codec = contentType + "?" } headers.Del("Content-Type") respMeta.compression = headers.Get("Grpc-Encoding") headers.Del("Grpc-Encoding") respMeta.acceptCompression = parseMultiHeader(headers.Values("Grpc-Accept-Encoding")) headers.Del("Grpc-Accept-Encoding") // See if RPC is already over (unexpected HTTP error or trailers-only response) if len(headers.Values("Grpc-Status")) > 0 { connErr := grpcExtractErrorFromTrailer(headers) respMeta.end = &responseEnd{ err: connErr, httpCode: statusCode, } headers.Del("Grpc-Status") headers.Del("Grpc-Message") headers.Del("Grpc-Status-Details-Bin") if contentType == "" { // no need to report "?" codec if no content-type on a trailers-only response respMeta.codec = "" } } if statusCode != http.StatusOK { if respMeta.end == nil { respMeta.end = &responseEnd{} } if respMeta.end.err == nil { code := httpStatusCodeToRPC(statusCode) respMeta.end.err = connect.NewError(code, fmt.Errorf("unexpected HTTP error: %d %s", statusCode, http.StatusText(statusCode))) } } return respMeta } func grpcAddRequestMeta(contentTypePrefix string, meta requestMeta, headers http.Header) { headers.Set("Content-Type", contentTypePrefix+meta.codec) if meta.compression != "" { headers.Set("Grpc-Encoding", meta.compression) } if len(meta.acceptCompression) > 0 { headers.Set("Grpc-Accept-Encoding", strings.Join(meta.acceptCompression, ", ")) } if meta.hasTimeout { timeoutStr := grpcEncodeTimeout(meta.timeout) headers.Set("Grpc-Timeout", timeoutStr) } } func grpcAddResponseMeta(contentTypePrefix string, meta responseMeta, headers http.Header) int { if meta.end != nil { headers.Set("Content-Type", contentTypePrefix+meta.codec) grpcWriteEndToTrailers(meta.end, headers) return http.StatusOK } headers.Set("Content-Type", contentTypePrefix+meta.codec) if meta.compression != "" { headers.Set("Grpc-Encoding", meta.compression) } if len(meta.acceptCompression) > 0 { headers.Set("Grpc-Accept-Encoding", strings.Join(meta.acceptCompression, ", ")) } return http.StatusOK } func grpcWriteEndToTrailers(respEnd *responseEnd, trailers http.Header) { for k, v := range respEnd.trailers { trailers[k] = v } if respEnd.err == nil { trailers.Set("Grpc-Status", "0") trailers.Set("Grpc-Message", "") } else { trailers.Set("Grpc-Status", strconv.Itoa(int(respEnd.err.Code()))) trailers.Set("Grpc-Message", grpcPercentEncode(respEnd.err.Message())) if len(respEnd.err.Details()) == 0 { return } stat := grpcStatusFromError(respEnd.err) bin, err := proto.Marshal(stat) if err == nil { trailers.Set("Grpc-Status-Details-Bin", connect.EncodeBinaryHeader(bin)) } } } func grpcStatusFromError(err *connect.Error) *status.Status { stat := &status.Status{ Code: int32(err.Code()), Message: err.Message(), } if details := err.Details(); len(details) > 0 { stat.Details = make([]*anypb.Any, len(details)) for i, detail := range details { stat.Details[i] = &anypb.Any{ TypeUrl: "type.googleapis.com/" + detail.Type(), Value: detail.Bytes(), } } } return stat } // grpcPercentEncode follows RFC 3986 Section 2.1 and the gRPC HTTP/2 spec. // It's a variant of URL-encoding with fewer reserved characters. It's intended // to take UTF-8 encoded text and escape non-ASCII bytes so that they're valid // HTTP/1 headers, while still maximizing readability of the data on the wire. // // The grpc-message trailer (used for human-readable error messages) should be // percent-encoded. // // References: // // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses // https://datatracker.ietf.org/doc/html/rfc3986#section-2.1 func grpcPercentEncode(msg string) string { var hexCount int for i := 0; i < len(msg); i++ { if grpcShouldEscape(msg[i]) { hexCount++ } } if hexCount == 0 { return msg } // We need to escape some characters, so we'll need to allocate a new string. var out strings.Builder out.Grow(len(msg) + 2*hexCount) for i := 0; i < len(msg); i++ { switch char := msg[i]; { case grpcShouldEscape(char): out.WriteByte('%') out.WriteByte(upperhex[char>>4]) out.WriteByte(upperhex[char&15]) default: out.WriteByte(char) } } return out.String() } func grpcPercentDecode(input string) (string, error) { percentCount := 0 for i := 0; i < len(input); { switch input[i] { case '%': percentCount++ if err := validateHex(input[i:]); err != nil { return "", err } i += 3 default: i++ } } if percentCount == 0 { return input, nil } // We need to unescape some characters, so we'll need to allocate a new string. var out strings.Builder out.Grow(len(input) - 2*percentCount) for i := 0; i < len(input); i++ { switch input[i] { case '%': out.WriteByte(unhex(input[i+1])<<4 | unhex(input[i+2])) i += 2 default: out.WriteByte(input[i]) } } return out.String(), nil } // Characters that need to be escaped are defined in gRPC's HTTP/2 spec. // They're different from the generic set defined in RFC 3986. func grpcShouldEscape(char byte) bool { return char < ' ' || char > '~' || char == '%' } // The gRPC wire protocol specifies that errors should be serialized using the // binary Protobuf format, even if the messages in the request/response stream // use a different codec. Consequently, this function needs a Protobuf codec to // unmarshal error information in the headers. func grpcExtractErrorFromTrailer(trailers http.Header) *connect.Error { grpcStatus := trailers.Get("Grpc-Status") grpcMsg := trailers.Get("Grpc-Message") grpcDetails := trailers.Get("Grpc-Status-Details-Bin") trailers.Del("Grpc-Status") trailers.Del("Grpc-Message") trailers.Del("Grpc-Status-Details-Bin") codeHeader := grpcStatus if codeHeader == "" { return connect.NewError( connect.CodeInternal, protocolError("missing trailer header %q", "Grpc-Status"), ) } if codeHeader == "0" { return nil } code, err := strconv.ParseUint(codeHeader, 10 /* base */, 32 /* bitsize */) if err != nil { return connect.NewError( connect.CodeInternal, protocolError("invalid error code %q: %w", codeHeader, err), ) } if code == 0 { return nil } if len(grpcDetails) == 0 { message, err := grpcPercentDecode(grpcMsg) if err != nil { return connect.NewError( connect.CodeInternal, protocolError("invalid grpc-message trailer: %w", err), ) } return connect.NewWireError(connect.Code(code), errors.New(message)) } // Prefer the Protobuf-encoded data to the headers (grpc-go does this too). detailsBinary, err := connect.DecodeBinaryHeader(grpcDetails) if err != nil { return connect.NewError( connect.CodeInternal, protocolError("invalid grpc-status-details-bin trailer: %w", err), ) } var stat status.Status if err := proto.Unmarshal(detailsBinary, &stat); err != nil { return connect.NewError( connect.CodeInternal, protocolError("invalid protobuf for error details: %w", err), ) } trailerErr := connect.NewWireError(connect.Code(stat.GetCode()), errors.New(stat.GetMessage())) for _, msg := range stat.GetDetails() { errDetail, err := connect.NewErrorDetail(msg) if err != nil { // shouldn't happen since msg is an Any and doesn't need to be marshalled continue } trailerErr.AddDetail(errDetail) } return trailerErr } func grpcExtractTimeoutFromHeaders(headers http.Header, meta *requestMeta) error { timeoutStr := headers.Get("Grpc-Timeout") headers.Del("Grpc-Timeout") if timeoutStr == "" { return nil } timeout, err := grpcDecodeTimeout(timeoutStr) if err != nil { return err } meta.timeout = timeout meta.hasTimeout = true return nil } func grpcDecodeTimeout(timeout string) (time.Duration, error) { if timeout == "" { return 0, errNoTimeout } unit := grpcTimeoutUnitLookup(timeout[len(timeout)-1]) if unit == 0 { return 0, protocolError("timeout %q has invalid unit", timeout) } num, err := strconv.ParseInt(timeout[:len(timeout)-1], 10 /* base */, 64 /* bitsize */) if err != nil || num < 0 { return 0, protocolError("invalid timeout %q", timeout) } if num > 99999999 { // timeout must be ASCII string of at most 8 digits return 0, protocolError("timeout %q is too long", timeout) } const grpcTimeoutMaxHours = 8 if unit == time.Hour && num > grpcTimeoutMaxHours { // Timeout is effectively unbounded, so ignore it. The grpc-go // implementation does the same thing. return 0, errNoTimeout } return time.Duration(num) * unit, nil } func grpcEncodeTimeout(timeout time.Duration) string { if timeout <= 0 { return "0n" } const grpcTimeoutMaxValue = 1e8 var ( size time.Duration unit byte ) switch { case timeout < time.Nanosecond*grpcTimeoutMaxValue: size, unit = time.Nanosecond, 'n' case timeout < time.Microsecond*grpcTimeoutMaxValue: size, unit = time.Microsecond, 'u' case timeout < time.Millisecond*grpcTimeoutMaxValue: size, unit = time.Millisecond, 'm' case timeout < time.Second*grpcTimeoutMaxValue: size, unit = time.Second, 'S' case timeout < time.Minute*grpcTimeoutMaxValue: size, unit = time.Minute, 'M' default: size, unit = time.Hour, 'H' } value := timeout / size return strconv.FormatInt(int64(value), 10 /* base */) + string(unit) } func grpcTimeoutUnitLookup(unit byte) time.Duration { switch unit { case 'n': return time.Nanosecond case 'u': return time.Microsecond case 'm': return time.Millisecond case 'S': return time.Second case 'M': return time.Minute case 'H': return time.Hour default: return 0 } }
from transformers import AutoModelForSequenceClassification, AutoTokenizer import torch import numpy as np import pandas as pd from datasets import Dataset import math global TOKENIZER global DEVICE global MODEL TOKENIZER = AutoTokenizer.from_pretrained('alex-miller/ODABert', model_max_length=512) DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" MODEL = AutoModelForSequenceClassification.from_pretrained("alex-miller/cdp-multi-classifier-weighted") MODEL = MODEL.to(DEVICE) SUB_MODEL = AutoModelForSequenceClassification.from_pretrained("alex-miller/cdp-multi-classifier-sub-classes-weighted") SUB_MODEL = SUB_MODEL.to(DEVICE) YEAR = 2022 def sigmoid(x): return 1/(1 + np.exp(-x)) def chunk_by_tokens(input_text, model_max_size=512): chunks = list() tokens = TOKENIZER.encode(input_text) token_length = len(tokens) if token_length <= model_max_size: return [input_text] desired_number_of_chunks = math.ceil(token_length / model_max_size) calculated_chunk_size = math.ceil(token_length / desired_number_of_chunks) for i in range(0, token_length, calculated_chunk_size): chunks.append(TOKENIZER.decode(tokens[i:i + calculated_chunk_size])) return chunks def inference(model, inputs): predictions = model(**inputs) logits = predictions.logits.cpu().detach().numpy()[0] predicted_confidences = sigmoid(logits) predicted_classes = (predicted_confidences > 0.5) return predicted_classes, predicted_confidences def map_columns(example): textual_data_list = [ example['project_title'], example['short_description'], example['long_description'] ] textual_data_list = [str(textual_data) for textual_data in textual_data_list if textual_data is not None] text = " ".join(textual_data_list) predictions = { 'Crisis finance': [False, 0], 'PAF': [False, 0], 'AA': [False, 0], 'Direct': [False, 0], 'Indirect': [False, 0], 'Part': [False, 0], } text_chunks = chunk_by_tokens(text) for text_chunk in text_chunks: inputs = TOKENIZER(text_chunk, return_tensors="pt", truncation=True).to(DEVICE) model_pred, model_conf = inference(MODEL, inputs) predictions['Crisis finance'][0] = predictions['Crisis finance'][0] or model_pred[0] predictions['Crisis finance'][1] = max(predictions['Crisis finance'][1], model_conf[0]) predictions['PAF'][0] = predictions['PAF'][0] or model_pred[1] predictions['PAF'][1] = max(predictions['PAF'][1], model_conf[1]) predictions['AA'][0] = predictions['AA'][0] or model_pred[2] predictions['AA'][1] = max(predictions['AA'][1], model_conf[2]) # Apply sub-model sub_model_pred, sub_model_conf = inference(SUB_MODEL, inputs) predictions['Direct'][0] = predictions['Direct'][0] or sub_model_pred[0] predictions['Direct'][1] = max(predictions['Direct'][1], sub_model_conf[0]) predictions['Indirect'][0] = predictions['Indirect'][0] or sub_model_pred[1] predictions['Indirect'][1] = max(predictions['Indirect'][1], sub_model_conf[1]) predictions['Part'][0] = predictions['Part'][0] or sub_model_pred[2] predictions['Part'][1] = max(predictions['Part'][1], sub_model_conf[2]) example['Crisis finance predicted'] = predictions['Crisis finance'][0] example['Crisis finance confidence'] = predictions['Crisis finance'][1] example['PAF predicted'] = predictions['PAF'][0] example['PAF confidence'] = predictions['PAF'][1] example['AA predicted'] = predictions['AA'][0] example['AA confidence'] = predictions['AA'][1] example['Direct predicted'] = predictions['Direct'][0] example['Direct confidence'] = predictions['Direct'][1] example['Indirect predicted'] = predictions['Indirect'][0] example['Indirect confidence'] = predictions['Indirect'][1] example['Part predicted'] = predictions['Part'][0] example['Part confidence'] = predictions['Part'][1] return example def main(): text_cols = ['project_title', 'short_description', 'long_description'] dataset = pd.read_csv("large_data/crs_{}.csv".format(YEAR)) dataset_text = dataset[text_cols] dataset_text = Dataset.from_pandas(dataset_text) dataset_text = dataset_text.map(map_columns, remove_columns=text_cols) dataset_text = pd.DataFrame(dataset_text) dataset = pd.concat([dataset.reset_index(drop=True), dataset_text.reset_index(drop=True)], axis=1) dataset.to_csv('output/crs_{}_predictions.csv'.format(YEAR), index=False) if __name__ == '__main__': main()
using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using sip.Documents.Renderers.Handlebars; namespace sip.Documents.Renderers.Word; public class MsWordRenderer(HandlebarsService handlebarsRenderer) : IDocRenderer { public async Task<MimePart> Render(MimePart tsource, object context) { if (!SupportsType(tsource.ContentType)) { throw new FormatException($"{nameof(MsWordRenderer)}: Unsupported source {tsource}"); } var result = new MemoryStream(); await tsource.Content.DecodeToAsync(result); result.Position = 0; using var doc = WordprocessingDocument.Open(result, true); // Fix the document structure so it is prepared for handlebars rendering MergeRuns('{', '}', doc.MainDocumentPart!.Document.Body!.Descendants<Run>()); doc.Save(); // Write the fixed shit to text, so we can pass it to handlebars string contents; using (var contentStreamReader = new StreamReader(doc.MainDocumentPart!.GetStream())) { contents = await contentStreamReader.ReadToEndAsync(); } // Now lets actually use the handlebars renderer, but first do some replacements contents = contents.Replace("{", "{{"); contents = contents.Replace("}", "}}"); var newContents = handlebarsRenderer.Render(contents, context); await using var contentStreamWriter = new StreamWriter(doc.MainDocumentPart.GetStream(FileMode.Create)); await contentStreamWriter.WriteAsync(newContents); var resultMp = new MimePart(tsource.ContentType) { Content = new MimeContent(result) }; return resultMp; } public bool SupportsType(ContentType contentType) => contentType.IsMsWord(); public void MergeRuns(char startDelimiter, char endDelimiter, IEnumerable<Run> runs) { var runsList = runs.ToList(); // Search for start pattern var index = 0; while (index < runsList.Count) { var currentRun = runsList[index]; // Does this run open merge? var text = string.Join("", currentRun.Descendants<Text>().Select(t => t.Text)); if (text.Contains(startDelimiter)) { var mergCount = MergeRunsUntil(runsList.Skip(index), endDelimiter); index += mergCount; } index++; } } /// <summary> /// Merge multiple runs into the first run in the enumerable /// Only first run with one text is preserved, all texts are merged to the first and /// everything further gets deleted. /// </summary> /// <param name="runs"></param> /// <param name="untilChar"></param> /// <exception cref="InvalidOperationException"></exception> public int MergeRunsUntil(IEnumerable<Run> runs, char untilChar) { var mergedCount = 0; var runsList = runs.ToList(); var targetRun = runsList.First(); var targetTexts= targetRun.Descendants<Text>().ToList(); var targetText = targetTexts.First(); if (targetText is null) throw new InvalidOperationException("Text element is missing in Run element"); // Handle addition text elements in the run we are merging to foreach (var text in targetTexts.Skip(1)) { targetText.Text += text; text.Remove(); } // Now merge texts of remaining runs foreach (var mergeRun in runsList.Skip(1)) { var text = string.Join("", mergeRun.Descendants<Text>().Select(t => t.Text)); targetText.Text += text; mergeRun.Remove(); mergedCount++; if (text.Contains(untilChar)) return mergedCount; } return mergedCount; } }
'use strict'; function convertHTML(str) { const entitiesHTML = { "&": '&amp;', "<": '&lt;', ">": '&gt;', '"': '&quot;', "'": '&apos;' } const newStr = str.split('') .map(symb => { return (symb in entitiesHTML)? symb.replace(symb, entitiesHTML[symb]) : symb; }).join(''); return newStr; } console.log(convertHTML("<>")); /** * Convert HTML Entities Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities. */
import * as React from "react" import Navbar from "../Componentss/Navbar" import { Typography } from "@mui/material" import { ProductHeroLayout } from "../Componentss/ProductHeroLayout" import { styled } from "@mui/material/styles" import Button from "@mui/material/Button" import AppBar from "@mui/material/AppBar" import Grid from "@mui/material/Grid" import ButtonGroup from "@mui/material/ButtonGroup" import Box from "@mui/material/Box" import { createTheme, ThemeProvider } from "@mui/material/styles" import { pathLogin, pathRegister, pathSearch } from "../Paths" import { getBuyerId, getIsGuest } from "../services/SessionService" const cards = [1, 2, 3] const backgroundImage = "https://images.unsplash.com/photo-1471193945509-9ad0617afabf" const createButton = (name: string, path: string) => { return ( <Button href={path} style={{ height: 100, width: 500 }} key="name" variant="contained" size="large" color="primary" sx={{ m: 1, "&:hover": { borderRadius: 5, }, }} > {name} </Button> ) // <Button // color="secondary" // variant="contained" // size="large" // component="a" // href="/store" // sx={{ minWidth: 200 }} // > } const buttons = [ createButton("Continue To Website", pathSearch), createButton("Create An Account", pathRegister), createButton("Log In To Your Account", pathLogin), ] const theme = createTheme({ palette: { mode: "light", }, typography: { fontFamily: [ "-apple-system", "BlinkMacSystemFont", '"Segoe UI"', "Roboto", '"Helvetica Neue"', "Arial", "sans-serif", '"Apple Color Emoji"', '"Segoe UI Emoji"', '"Segoe UI Symbol"', ].join(","), }, }) export default function Home() { return ( <ThemeProvider theme={theme}> {/* {!getIsGuest() && <Navbar/> } */} <main> <ProductHeroLayout sxBackground={{ backgroundImage: `url(${backgroundImage})`, backgroundSize: "cover", backgroundPosition: "center", height: "100vh", outerHeight: "150vh", }} > {/* Increase the network loading priority of the background image. */} {/* <img style={{ display: "none" }} src={backgroundImage} alt="increase priority" /> */} <img style={{ display: "none" }} src={backgroundImage} alt="increase priority" /> <Typography color="primary" align="center" variant="h2"> Buy smart and cheap </Typography> <Typography color="inherit" align="center" variant="h5" sx={{ mb: 4, mt: { sx: 4, sm: 2 } }} > Enjoy a variety of products, and mostly the suffering of 6 naive students </Typography> <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", }} > <ButtonGroup orientation="vertical" aria-label="vertical contained button group" variant="text" > {buttons} </ButtonGroup> </Box> </ProductHeroLayout> </main> </ThemeProvider> ) }
import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { ApiService } from './api.service'; import { HttpClient } from '@angular/common/http'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AuthService { public isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); public isAuthenticated$: Observable<boolean> = this.isAuthenticatedSubject.asObservable(); public userRoleSubject: BehaviorSubject<string> = new BehaviorSubject<string>(''); public userRole$: Observable<string> = this.userRoleSubject.asObservable(); public loggedInUser: BehaviorSubject<string> = new BehaviorSubject<string>(''); private baseUrl = 'http://localhost:8000'; constructor(private apiService: ApiService,private http: HttpClient, private router: Router) {} setAuthenticated(status: boolean) { this.isAuthenticatedSubject.next(status); } isAuthenticatedUser(): Observable<boolean> { return this.isAuthenticated$; } setUserRole(role: string) { this.userRoleSubject.next(role); } getUserRole(): Observable<string> { return this.userRole$; } setLoggedInUser(username: string) { this.loggedInUser.next(username); } getLoggedInUser(): Observable<string> { return this.loggedInUser.asObservable(); } login(username: string, password: string, remember: boolean): Observable<any> { return this.apiService.login(username, password, remember); } logout() { this.apiService.logout().subscribe(() => { // Perform any additional logic or redirection after logout console.log("refreshing.....................") window.location.reload(); // Refresh the page }); } }
import { createSlice } from '@reduxjs/toolkit'; import { getOrders, makeOrder } from './actions'; import { State } from './types'; const initialState: State = { orders: [], last_seen: undefined, hasMore: false, }; const ordersSlice = createSlice({ name: 'orders', initialState, reducers: { resetMessage: state => { state.message = undefined; }, }, extraReducers: builder => { builder.addCase(getOrders.fulfilled, (state, action) => { const len = action.payload.length; state.orders = action.payload; if (len) { state.hasMore = true; state.last_seen = action.payload[len - 1]._id; } }); builder.addCase(makeOrder.fulfilled, (state, action) => { state.message = action.payload; }); }, }); export const orderActions = ordersSlice.actions; export default ordersSlice.reducer;
import { ApiPromise, WsProvider } from '@polkadot/api'; import {GenericExtrinsicPayload, GenericSignerPayload} from "@polkadot/types"; import {SubmittableExtrinsic} from "@polkadot/api/promise/types"; import {blake2AsU8a} from "@polkadot/util-crypto"; export type ApiOptions = { url?:string, isMain?:string } export type ChainType = "ethereum" | "substrate" export type SigType= "ECDSA" const MAINNET_URL= "wss://mainnet.polkadex.trade" const TESTNET_URL= "wss://blockchain.polkadex.trade" export default class PolkadexApi{ api:ApiPromise constructor(options: ApiOptions) { let provider; if(options.url){ provider = new WsProvider(options.url,2000) } else if(options.isMain){ provider = new WsProvider(MAINNET_URL) } else{ provider= new WsProvider(TESTNET_URL) } this.api= new ApiPromise({provider}) } public Api(): ApiPromise{ return this.api } public async createExtrinsicPayload(tx: string, address:string):Promise<GenericExtrinsicPayload>{ const nonce = await this.getAccountNonce(address) const signingPayload = this.api.createType('SignerPayload', { method: tx, nonce: nonce, genesisHash: this.api.genesisHash, blockHash: this.api.genesisHash, runtimeVersion: this.api.runtimeVersion, version: this.api.extrinsicVersion }) return this.api.createType('ExtrinsicPayload', signingPayload.toPayload(), { version: this.api.extrinsicVersion }) } public getHashedExtrinsicPayload(extrinsicPayload: GenericExtrinsicPayload, network: ChainType):Uint8Array{ const u8a = extrinsicPayload.toU8a({ method: true }) if(network==="ethereum"){ const encoded = u8a.length > 256 ? blake2AsU8a(u8a) : u8a; return blake2AsU8a(encoded) } else{ throw new Error("unknown network type") } } public getTransactionSender(tx: SubmittableExtrinsic, address:string, signature: Uint8Array, extrinsicPayload: GenericSignerPayload, sigType:SigType="ECDSA"){ let multiSignature; if(sigType === "ECDSA"){ //update the recovery bit if signed by eth compatible wallets if(signature[signature.length-1] > 3){ signature[signature.length-1]-=27 } multiSignature = this.api.createType("MultiSignature", {ecdsa: signature}) } else{ throw new Error("unknown signature type") } tx.addSignature(address, multiSignature.toHex(), extrinsicPayload.toPayload()) return tx.send } async getAccountNonce (address:string){ const {nonce} = (await this.api.query.system.account(address)).toJSON() as any return Number(nonce) + 1; } }
package lv2.day9; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; public class 다리를_지나는_트럭 { /* * https://school.programmers.co.kr/learn/courses/30/lessons/42583 * */ public static int solution(int bridge_length, int weight, int[] truck_weights) { Queue<Integer> q = new LinkedList<>(); int answer = 0; int sum = 0; for (int i = 0; i < truck_weights.length; i++) { int truck = truck_weights[i]; while (true) { System.out.println("q = " + q); System.out.println("sum = " + sum); System.out.println("answer = " + answer); if (q.isEmpty()) { // 7 q.offer(truck); sum += truck; // 7 answer++; // 1 break; } else { if (q.size() == bridge_length) { sum -= q.poll(); // } else if (sum + truck > weight) { q.offer(0); // 7, 0 answer++; // 2 } else { q.offer(truck); sum += truck; answer++; break; } } } } return answer + bridge_length; } public static void main(String[] args) { System.out.println(solution(2, 10, new int[]{7, 4, 5, 6})); } }
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> </head> <body> <!-- 타입 --> 기본타입 - 숫자(number) - 문자열(string) - 불리언(boolean) - 심볼(symbol) # ECMAScript 6부터 제공 - undefined 객체타입 - 객체(object) <script> //숫자타입은 정수와 실수를 따로 구분하지 않음 var number1 = 10; var number2 = 10.1; //큰수 작은수 표현은 e표기법 var number3 = 10e6; // 10000000 var number4 = 10e-6; // 0.00001 //문자열 var num = 1234; var str = "Hongtaehwa" document.write(num + str); // 1234Hongtaehwa //심볼 : 심볼은 유일하고 변경할 수 없는 타입으로 // 객체의 프로퍼티를 위한 식별자로 사용 var test1 = Symbol("taehwa"); //심볼 타입 var test2 = Object(test); //오브젝트 타입 //null과 undefined // null : object 타입이며, 아직 [값]이 정해지지 않은 것을 의미한다 // undefined : null과는 다르게 [타입]이 정해지지 않은 것을 의미한다 // undefined는 초기화되지 않은 변수나 존재하지 않는 값에 접근할 때 반환 var numTest; // 초기화하지 않았으므로 undefined var strTest = null; // object 타입의 nul typeof numTest2; // 정의되지 않은 변수는 undefined // 동등 연산자(==)와 일치 연산자(===)로 비교시 결과가 다름 // null과 undefined는 타입을 제외하면 같은 의미지만 타입이 다르므로 일치하지 않는다 null == undefined; // true null === undefined; // false </script> <!-- 타입의 변환 --> 타입이 정해져있지 않고 같은 변수에 다른타입의 값을 다시 대입가능 <script> var test = 10; test = "테스트"; var test; //재선언은 무시됨 // 묵시적 타입 변환 10 + "문자"; //문자열로 변환 "10" * "10"; //곱셉연산을 위해 두 문자열이 숫자로 변환 100 - "문자"; //NaN : 자동으로 타입변환이 불가능함 // 명시적 타입 변환을 위한 함수 Number("10"); String(555); Boolean(0); //false Boolean(1); //true var pInt = parseInt("10"); var pFloat = parseFloat("10.1"); document.write(pInt); document.write(pFloat); </script> </body> </html>
using Domain.API; using System.Security.Cryptography; using System.Text; namespace DomainShared.Extentions.Utility { public static class Extentions { /// <summary> /// Hashes string With SHA256 /// </summary> /// <param name="source">String that will hash</param> /// <returns></returns> public static string HashData(this string source) { SHA256 hasher = SHA256.Create(); byte[] bytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(source)); var Result = ""; foreach (byte b in bytes) { Result += b.ToString("x2"); } return Result; } public static ServiceResult<object> ToObjectiveServiceResult<T>(this ServiceResult<T> serviceResult) { if (serviceResult.Failure) return new ServiceResult<object>(serviceResult.Messages); var result = new ServiceResult<object>(serviceResult.Result); result.Messages = new(); result.Messages.AddRange(serviceResult.Messages); return result; } /// <summary> /// Formats LongNumber in 1000 base /// </summary> /// <param name="num"></param> /// <returns></returns> public static string FormatCount(this long num) { if (num < 1000) return num.ToString(); string result = ((double)num / 1000).ToString("0.0") + "K"; return result; } /// <summary> /// Formats Int Number in 1000 base /// </summary> /// <param name="num"></param> /// <returns></returns> public static string FormatCount(this int num) { if (num < 1000) return num.ToString(); string result = ((double)num / 1000).ToString("0.0") + "K"; return result; } public static string FormatLength(this string src, int length) { var isLong = false; var res = ""; char[] srcArray = src.ToArray(); if (srcArray.Length > length) { isLong = true; } else { length = srcArray.Length; } for (var i = 0; i < length; i++) { res += srcArray[i].ToString(); } if (isLong) { res += " ..."; } return res; } } }
import React, { useState } from 'react'; const CreateBlogForm = ({ addNewBlog }) => { const [title, setTitle] = useState(''); const [author, setAuthor] = useState(''); const [url, setUrl] = useState(''); const createBlog = async (event) => { event.preventDefault(); await addNewBlog({ title, author, url }); setTitle(''); setAuthor(''); setUrl(''); }; return ( <form onSubmit={createBlog}> <div> title: <input id="title-input" value={title} onChange={({ target }) => setTitle(target.value)}> </input> </div> <div> author: <input id="author-input" value={author} onChange={({ target }) => setAuthor(target.value)}> </input> </div> <div> url: <input id="url-input" value={url} onChange={({ target }) => setUrl(target.value)}> </input> </div> <button type="submit">create</button> </form> ); }; export default CreateBlogForm;
import { Asset, Model, Field, Document, DocumentStatus, FieldListItemsModelProps, FieldListItemsObjectProps, FieldListModel, } from '@stackbit/types'; import { Entry } from '@contentstack/management/types/stack/contentType/entry'; import { ExtendedAsset } from './types'; type ImageField = { uid?: string; }; type Item = Record<string, any>; export function transformDocument( document: Entry, model: Model, models: Record<string, Model>, options: { apiKey: string }, ): Document { const { uid, created_at, updated_at } = document; const baseData: Omit<Document, 'fields'> = { type: 'document', id: uid, manageUrl: `https://app.contentstack.com/#!/stack/${options.apiKey}/content-type/${model.name}/en-us/entry/${uid}/edit`, modelName: model.name, status: getStatus(document), createdAt: created_at as string, updatedAt: updated_at as string, context: {}, }; const fieldsData = (model?.fields ?? []).reduce((acc: Record<string, any>, curr) => { acc[curr.name] = transformField(curr, model, models)(document); return acc; }, {}); const result = { ...baseData, fields: fieldsData, }; return result; } export function transformAsset<T>(asset: ExtendedAsset, options: { apiKey: string }): Asset<T> { const { uid: id, filename, url, content_type: contentType, file_size: size } = asset; const title = (asset as { title?: string }).title || filename; return { type: 'asset', id, manageUrl: `https://app.contentstack.com/#!/stack/${options.apiKey}/assets/${id}`, status: 'published', createdAt: asset.created_at as string, updatedAt: asset.updated_at as string, fields: { title: { type: 'string', localized: false, value: title, }, file: { type: 'assetFile', url, fileName: filename, contentType, size: Number(size), dimensions: {}, }, }, context: {} as T, }; } function isBlockField(field: FieldListModel, modelName: string) { return field.items.models?.some((fieldModel) => fieldModel.includes(`BLOCK_${modelName}__`)); } function transformField( field: Field, model: Pick<Model, 'name' | 'type' | 'fields'>, models: Record<string, Model>, isNested = false ): Function { switch (field.type) { case 'boolean': case 'string': case 'enum': case 'number': case 'markdown': case 'text': case 'slug': case 'color': return (item: Item) => { return { type: field.type, value: (!isNested && field.group ? item[field.group] : item)[field.name], }; }; case 'date': case 'datetime': return (item: Item) => item[field.name] ? { type: field.type, value: item[field.name], } : null; case 'json': return (item: Item) => { const fieldGroup = field.group; const fieldData = (fieldGroup ? item[fieldGroup] : item)[field.name]; return { type: field.type, value: fieldData, }; }; case 'image': return (item: Item) => { const fieldGroup = field.group; const fieldData = (fieldGroup ? item[fieldGroup] : item)[field.name] as ImageField; return fieldData ? { type: 'reference', refType: 'asset', refId: fieldData?.uid, } : null; }; case 'reference': return (item: Item) => { const fieldGroup = field.group; const fieldData = (fieldGroup ? item[fieldGroup] : item)[field.name]; return fieldData?.length > 0 ? { type: 'reference', refType: 'document', refId: fieldData[0].uid, } : null; }; case 'object': { return (item: Item) => { const fieldGroup = field.group; const fieldData = (fieldGroup ? item[fieldGroup] : item)[field.name]; return fieldData ? { type: 'object', fields: (field.fields || []).reduce((acc: Record<string, any>, curr) => { acc[curr.name] = transformField( curr, { name: `ContentStackObject-${field.name}`, type: 'object', fields: field.fields }, models )(fieldData); return acc; }, {}), } : null; }; } case 'model': return (item: Item) => { const fieldGroup = field.group; const fieldData = (fieldGroup ? item[fieldGroup] : item)[field.name]; const nestedModel = models[field.models[0] as string] as Model; return fieldData ? { type: 'model', modelName: nestedModel.name, fields: (nestedModel?.fields || []).reduce((acc: Record<string, any>, curr) => { acc[curr.name] = transformField(curr, nestedModel as Model, models)(fieldData); return acc; }, {}), } : null; }; case 'list': switch (field.items.type) { case 'model': return (item: Item) => { const fieldGroup = field.group; const fieldData = (fieldGroup ? item[fieldGroup] : item)[field.name]; const blockField = isBlockField(field as FieldListModel, model.name); return { type: 'list', items: ((fieldData || []) as any[]) .map((listItem) => { const itemTypeId: string = blockField ? (Object.keys(listItem)[0] as string) : ((field as FieldListItemsModelProps).items.models[0] as string); const nestedModel = models[blockField ? `BLOCK_${model.name}__${itemTypeId}` : itemTypeId]; return { type: 'model', modelName: nestedModel?.name, fields: (nestedModel?.fields || []).reduce((acc: Record<string, any>, curr) => { acc[curr.name] = transformField( curr, nestedModel as Model, models )(blockField ? listItem[itemTypeId] : listItem); return acc; }, {}), }; }) .filter(Boolean), }; }; case 'reference': return (item: Item) => ({ type: 'list', items: (item[field.name] || []).map((listItem: Record<'uid', string>) => { return { type: 'reference', refType: 'document', refId: listItem.uid, }; }), }); case 'image': return (item: Item) => ({ type: 'list', items: (item[field.name] || []).map((listItem: Record<'uid', string>) => { return { type: 'reference', refType: 'asset', refId: listItem.uid, }; }), }); case 'object': { return (item: Item) => { const items = (field.group ? item[field.group] : item[field.name]) || []; const objectFields = (field as FieldListItemsObjectProps).items.fields || []; return { type: 'list', items: items.map((currentItem: Record<string, any>) => ({ type: 'object', fields: objectFields.reduce((acc: Record<string, any>, currentField) => { acc[currentField.name] = transformField( currentField, { name: 'ContentStackObject', type: 'object', fields: objectFields }, models, true )(currentItem); return acc; }, {}), })), }; }; } default: return (item: Item) => ({ type: 'list', items: ((item[field.name] || []) as any[]).map((listItem) => { return { type: field.items.type || 'string', value: listItem, }; }), }); } default: return (item: Item) => {}; } } function getStatus(document: Entry): DocumentStatus { if (Array.isArray(document.publish_details) && document.publish_details.length > 0) { return document.publish_details.slice(-1)[0]?.time < (document.updated_at as string) ? 'modified' : 'published'; } return 'added'; }
import React, { memo } from "react"; import styled from "styled-components"; import ErrorLogItem, { getLogItemProps } from "./ErrorLogItem"; import { BlankState } from "../helpers"; import { createMessage, NO_ERRORS } from "@appsmith/constants/messages"; import { thinScrollbar } from "constants/DefaultTheme"; import { Log } from "entities/AppsmithConsole"; const ContainerWrapper = styled.div` overflow: hidden; height: 100%; `; const ListWrapper = styled.div` overflow: auto; ${thinScrollbar}; height: 100%; padding-bottom: 25px; `; // This component is used to render the error logs in the debugger. function ErrorLog(props: { errors: Record<string, Log>; hasShortCut?: boolean; }) { // returns array of log items for each error in the error log. const getLogItem = (error: Log, index: number) => { const logItemProps = getLogItemProps(error); const messages = error.messages || []; const logItems = []; if (messages.length) { messages.forEach((message) => { logItemProps.messages = [message]; logItems.push( <ErrorLogItem key={`debugger-${index}`} {...logItemProps} />, ); }); } else { logItems.push( <ErrorLogItem key={`debugger-${index}`} {...logItemProps} />, ); } return logItems; }; return ( <ContainerWrapper> <ListWrapper className="debugger-list"> {!Object.values(props.errors).length ? ( <BlankState hasShortCut={props.hasShortCut} placeholderText={createMessage(NO_ERRORS)} /> ) : ( Object.values(props.errors).map((error, index) => { return getLogItem(error, index); }) )} </ListWrapper> </ContainerWrapper> ); } // Memoizing the component to avoid unnecessary re-renders export default memo(ErrorLog);
'use client'; import { FormErrorMessage, FormLabel, FormControl, Input, Text, } from '@chakra-ui/react'; import { InputTextProps } from './InputText.interface'; export const InputText = <TFormValues extends Record<string, unknown>>({ name, label, rules, type, defaultValue, register, errors, description, ...rest }: InputTextProps<TFormValues>) => ( <FormControl isInvalid={!!errors?.[name]?.message} isRequired={!!rules?.required} > {label && <FormLabel htmlFor={name}>{label}</FormLabel>} {description && ( <Text fontSize="sm" color="gray.500" mb={2}> {description} </Text> )} <Input id={name} name={name} type={type} autoComplete="off" defaultValue={defaultValue} {...(register && register(name, rules))} {...rest} /> {errors?.[name]?.message && ( <FormErrorMessage role="alert"> {errors?.[name]?.message?.toString()} </FormErrorMessage> )} </FormControl> );
"use client"; import { PlayIcon } from "lucide-react"; import { useWindowSize } from "usehooks-ts"; import { useModal } from "@/components/Modal"; import { YouTubeVideo } from "@/components/YouTubeVideo"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; export function OnboardingModal({ title, description, videoId, }: { title: string; description: React.ReactNode; videoId: string; }) { const { isModalOpen, openModal, setIsModalOpen } = useModal(); return ( <> <Button onClick={openModal} size="sm"> <PlayIcon className="mr-2 h-4 w-4" /> Watch Video </Button> <OnboardingModalDialog isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} title={title} description={description} videoId={videoId} /> </> ); } export function OnboardingModalDialog({ isModalOpen, setIsModalOpen, title, description, videoId, }: { isModalOpen: boolean; setIsModalOpen: (open: boolean) => void; title: string; description: React.ReactNode; videoId: string; }) { const { width } = useWindowSize(); const videoWidth = Math.min(width * 0.75, 1200); const videoHeight = videoWidth * (675 / 1200); return ( <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}> <DialogContent className="min-w-[350px] sm:min-w-[600px] md:min-w-[750px] lg:min-w-[880px] xl:min-w-[1280px]"> <DialogHeader> <DialogTitle>{title}</DialogTitle> <DialogDescription>{description}</DialogDescription> </DialogHeader> <YouTubeVideo videoId={videoId} iframeClassName="mx-auto" opts={{ height: `${videoHeight}`, width: `${videoWidth}`, playerVars: { // https://developers.google.com/youtube/player_parameters autoplay: 1, }, }} /> </DialogContent> </Dialog> ); }
package fr.racomach.zigbelote.android.ui.camera import android.util.Log import android.view.View import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.widget.LinearLayout import androidx.camera.core.CameraSelector import androidx.camera.core.ExperimentalGetImage import androidx.camera.core.ImageAnalysis import androidx.camera.view.LifecycleCameraController import androidx.camera.view.PreviewView import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.LifecycleOwner import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.PermissionState import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.shouldShowRationale import com.google.mediapipe.tasks.vision.core.RunningMode import com.google.mediapipe.tasks.vision.objectdetector.ObjectDetectorResult import fr.racomach.zigbelote.android.ObjectDetectorHelper import fr.racomach.zigbelote.android.ObjectDetectorHelper.DetectorListener import java.util.concurrent.Executors @OptIn(ExperimentalPermissionsApi::class) @Composable fun CameraScreen( modifier: Modifier = Modifier, onNewDetection: (result: ObjectDetectorResult) -> Unit ) { val cameraPermissionState: PermissionState = rememberPermissionState(android.Manifest.permission.CAMERA) LaunchedEffect(key1 = Unit) { if (!cameraPermissionState.status.isGranted && !cameraPermissionState.status.shouldShowRationale) { cameraPermissionState.launchPermissionRequest() } } if (cameraPermissionState.status.isGranted) { CameraPreview(modifier, onNewDetection) } else { // In this screen you should notify the user that the permission // is required and maybe offer a button to start another // camera perission request NoCameraPermissionScreen( cameraPermissionState = cameraPermissionState ) } } @androidx.annotation.OptIn(ExperimentalGetImage::class) @Composable private fun CameraPreview( modifier: Modifier = Modifier, onNewDetection: (result: ObjectDetectorResult) -> Unit ) { val context = LocalContext.current val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current val cameraController: LifecycleCameraController = remember { LifecycleCameraController(context) } val executor = remember { Executors.newSingleThreadExecutor() } val objectDetectorHelper: ObjectDetectorHelper = remember { ObjectDetectorHelper( runningMode = RunningMode.LIVE_STREAM, context = context, objectDetectorListener = object : DetectorListener { override fun onError(error: String, errorCode: Int) { Log.e("MMA-DEBUG", "Error : $error ($errorCode)") } override fun onResults(resultBundle: ObjectDetectorHelper.ResultBundle) { val result = resultBundle.results.firstOrNull() if (result != null) { onNewDetection(result) } } }) } val imageAnalyzer: ImageAnalysis.Analyzer = remember { ImageAnalysis.Analyzer { imageProxy -> objectDetectorHelper.detectLivestreamFrame(imageProxy) imageProxy.close() } } KeepScreenOn() Scaffold(modifier = modifier) { innerPadding: PaddingValues -> AndroidView( modifier = Modifier .fillMaxSize() .padding(innerPadding), factory = { context -> PreviewView(context).apply { setBackgroundColor(Color.White.toArgb()) layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT) scaleType = PreviewView.ScaleType.FILL_START implementationMode = PreviewView.ImplementationMode.COMPATIBLE }.also { previewView -> objectDetectorHelper.setupObjectDetector() previewView.controller = cameraController cameraController.bindToLifecycle(lifecycleOwner) cameraController.cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA cameraController.setImageAnalysisAnalyzer(executor, imageAnalyzer) } }, onRelease = { cameraController.unbind() } ) } } @Composable fun KeepScreenOn() = AndroidView({ View(it).apply { keepScreenOn = true } }) @OptIn(ExperimentalPermissionsApi::class) @Composable private fun NoCameraPermissionScreen(cameraPermissionState: PermissionState) { Text(text = "Il manque la permission pour la caméra : ${cameraPermissionState.status}") }
import jwt, { VerifyErrors } from 'jsonwebtoken'; import { User } from '../controllers/member2_controller'; const secretKey = process.env.JWT_SECRET_KEY; const expiresIn = '1h'; export const generateToken = (userInfo: User): string => { const payload = { email: userInfo.email, name: userInfo.name, generation: userInfo.generation, isAdmin: userInfo.isAdmin, }; if (!secretKey) { throw new Error('JWT secret key is not configured'); } return jwt.sign(payload, secretKey, { expiresIn }); }; export const verifyToken = (token: string): User | null => { try { if (!secretKey) { throw new Error('JWT secret key is not configured'); } const decoded = jwt.verify(token, secretKey) as User; return decoded; } catch (error) { console.error('Error verifying token:', error); return null; } }; export const refreshToken = (token: string): string | null => { try { const decoded = verifyToken(token); if (decoded) { return generateToken(decoded); } else { return null; } } catch (error) { console.error('Error refreshing token:', error); return null; } };
const Cart = require("../models/Cart"); const Order = require("../models/Order"); const order = require("../models/Order"); const Shoe = require("../models/Shoe"); require("dotenv").config(); const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); let getAllOrderByidUser = async (req, res) => { //lay tat ca order theo idUser try { const userId = req.params.idUser; const result = await order.find({ userId: userId, }); res .status(200) .json({ message: "Get All by User success", result: result }); } catch (err) { console.log(err); res.status(500).json({ message: "Get fail" }); } }; let makeOrderbyiduser = async (req, res) => { try { let idUser = req.params.idUser; const { shoes, methodPay, name, address, phone } = req.body; const result = new order({ userId: idUser, shoes: shoes, methodPay: methodPay, name: name, address: address, phone: phone, }); await result.save(); const PullCart = await Cart.findOneAndUpdate( { userId: idUser }, { $pull: { shoes: {} }, }, { new: true, } ); await descShoeCountWithSize(shoes); res.status(200).json({ message: "make order success", result: result }); } catch (err) { console.log(err); res.status(500).json({ message: "make order fail" }); } }; let makePaymentOnline = async (req, res) => { try { const { shoes, name, address, phone, methodPay, idUser } = req.metadata; const rawDataBuffer = Buffer.from(shoes); // Dữ liệu dưới dạng Buffer const rawDataString = rawDataBuffer.toString(); // Chuyển đổi từ Buffer thành chuỗi const jsonShoes = JSON.parse(rawDataString); // Chuyển đổi thành đối tượng JSON const ShoeList = await querryToMakeOrder(jsonShoes); const result = new order({ userId: idUser, shoes: ShoeList, methodPay: methodPay, name: name, address: address, phone: phone, }); await result.save(); await descShoeCountWithSize(ShoeList); await Cart.findOneAndUpdate( { userId: idUser }, { $pull: { shoes: {} }, }, { new: true, } ); } catch (err) { console.log(err); } }; const querryToMakeOrder = async (shoeList) => { const shoeListMax = await Promise.all( shoeList.map(async (shoe, index) => { let shoeItem = await Shoe.findById(shoe._id); return { ...shoe, price: shoeItem.price, img: shoeItem.img, desc: shoeItem.desc, color: shoeItem.color, type: shoeItem.type, name: shoeItem.name, }; }) ); return shoeListMax; }; let descShoeCountWithSize = (shoes) => { try { shoes.map(async (shoe) => { await Shoe.findOneAndUpdate( { _id: shoe._id, "size.ss": shoe.size, }, { $inc: { "size.$.cs": -shoe.quantity }, } ); }); } catch (err) { console.log(err); } }; let changeStatusByIdOrder = async (req, res) => { try { const { textStatus } = req.body; const result = await order.findOneAndUpdate( { _id: req.params.orderId, }, { $set: { status: textStatus, }, }, { new: true, } ); res .status(200) .json({ message: "Change Status order success", result: result }); } catch (err) { console.log(err); res.status(500).json({ message: "change status order fail" }); } }; let getAllOrders = async (req, res) => { const { idOrder } = req.query; if (idOrder) { try { const order = await Order.findById(idOrder); if (!order) return res .status(204) .json({ success: true, message: "Cannot find any order" }); return res .status(200) .json({ success: true, message: "Happy hacking", data: order }); } catch (error) { console.log(error); res .status(500) .json({ success: false, message: "Internal Server Error", error: err }); } } try { const orders = await Order.find(); if (!orders) return res .status(204) .json({ success: true, message: "Cannot find any orders" }); res.status(200).json({ success: true, message: "Happy time", orders }); } catch (err) { res .status(500) .json({ success: false, message: "Internal Server Error", error: err }); } }; let deleteOrder = async (req, res) => { try { const orderId = req.params.orderId; const shoeList = req.body.shoes; IncrShoeBydeleteOrder(shoeList); const orderDelete = await Order.findByIdAndDelete( { _id: orderId }, { new: true } ); res.status(200).json({ message: "delete order success" }); } catch (err) { res.status(500).json(err); } }; let IncrShoeBydeleteOrder = (shoes) => { try { shoes.map(async (shoe) => { await Shoe.findOneAndUpdate( { _id: shoe._id, "size.ss": shoe.size, }, { $inc: { "size.$.cs": shoe.quantity }, } ); }); } catch (err) { console.log(err); } }; let SearchOrder = async (req, res) => { try { const { name, phone, day, status } = req.body; const querry = {}; if (name) { querry.name = name; } if (phone) { querry.phone = phone; } if (day) { const SearchDate = new Date(`${day}T00:00:00.000Z`); querry.createdAt = { $gte: SearchDate, $lte: new Date(SearchDate.getTime() + 24 * 60 * 60 * 1000), }; } if (status) { querry.status = status; } console.log(querry); const orders = await Order.find(querry); res.status(200).json({ message: "success Search", orders }); } catch (err) { console.log(err); } }; const getStatAllOrder = async (req, res) => { const date = new Date(); const lastYear = new Date(date.setFullYear(date.getFullYear() - 1)); try { const data = await Order.aggregate([ { $match: { createdAt: { $gte: lastYear } }, }, { $project: { month: { $month: "$createdAt" }, }, }, { $group: { _id: "$month", total: { $sum: 1 }, }, }, ]); res.status(200).json({ success: true, message: "Happing Stat", data }); } catch (error) {} }; module.exports = { getAllOrderByidUser, changeStatusByIdOrder, makeOrderbyiduser, makePaymentOnline, getAllOrders, deleteOrder, getStatAllOrder, SearchOrder, };
package com.example.service.impl; import com.example.dto.StudentDto; import com.example.entity.Student; import com.example.exception.EmailAlreadyExistsException; import com.example.exception.ResourceNotFoundException; import com.example.mapper.StudentMapper; import com.example.repository.StudentRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class StudentServiceImplTest { @Mock private StudentRepository repository; @Mock private StudentMapper mapper; @InjectMocks private StudentServiceImpl service; /* @Test void testCreateStudent_Successful() { StudentDto inputDto = new StudentDto(1L, "Name1", "Surname1", "email1@example.com"); Student inputStudent = StudentMapper.mapToStudent(inputDto); Student savedStudent = new Student(1L, "Name1", "Surname1", "email1@example.com"); StudentDto expectedDto = new StudentDto(1L, "Name1", "Surname1", "email1@example.com"); when(repository.findByEmail(inputDto.getEmail())).thenReturn(Optional.empty()); when(repository.save(inputStudent)).thenReturn(savedStudent); when(mapper.mapToStudentDto(savedStudent)).thenReturn(expectedDto); StudentDto resultDto = service.createStudent(inputDto); assertEquals(expectedDto, resultDto); verify(repository, times(1)).findByEmail(inputDto.getEmail()); verify(repository, times(1)).save(inputStudent); verify(mapper, times(1)).mapToStudentDto(savedStudent); }*/ @Test void testCreateStudent_EmailAlreadyExists() { StudentDto inputDto = new StudentDto(); Student existingStudent = new Student(); when(repository.findByEmail(inputDto.getEmail())).thenReturn(Optional.of(existingStudent)); assertThrows(EmailAlreadyExistsException.class, () -> service.createStudent(inputDto)); verify(repository, times(1)).findByEmail(inputDto.getEmail()); verifyNoMoreInteractions(repository, mapper); } /*@Test void testGetStudentById_Successful() { Long studentId = 1L; Student student = new Student(1L, "Name1", "Surname1", "email1@example.com"); StudentDto expectedDto = new StudentDto(1L, "Name1", "Surname1", "email1@example.com"); when(repository.findById(studentId)).thenReturn(Optional.of(student)); when(mapper.mapToStudentDto(student)).thenReturn(expectedDto); StudentDto resultDto = service.getStudentById(studentId); assertEquals(expectedDto, resultDto); verify(repository, times(1)).findById(studentId); verify(mapper, times(1)).mapToStudentDto(student); }*/ @Test void testGetStudentById_NotFound() { Long studentId = 99L; when(repository.findById(studentId)).thenReturn(Optional.empty()); assertThrows(ResourceNotFoundException.class, () -> service.getStudentById(studentId)); verify(repository, times(1)).findById(studentId); verifyNoMoreInteractions(repository, mapper); } @Test void testGetAllStudents_Successful() { List<Student> mockStudents = Arrays.asList( new Student(1L, "Name1", "Surname1", "email1@example.com"), new Student(2L, "Name2", "Surname2", "email2@example.com"), new Student(3L, "Name3", "Surname3", "email3@example.com")); when(repository.findAll()).thenReturn(mockStudents); List<StudentDto> list = service.getAllStudents(); assertEquals(3, list.size()); verify(repository, times(1)).findAll(); } @Test void testGetAllStudents_WhenEmpty() { when(repository.findAll()).thenReturn(Collections.emptyList()); List<StudentDto> result = service.getAllStudents(); assertTrue(result.isEmpty()); verify(repository, times(1)).findAll(); } /*@Test void testUpdateStudent_Successful() { StudentDto inputDto = new StudentDto(1L, "Name1", "Surname1", "email1@example.com"); Student existingStudent = new Student(1L, "Name1", "Surname1", "email1@example.com"); Student updatedStudent = new Student(1L, "Name1", "Surname1", "email1@example.com"); StudentDto expectedDto = new StudentDto(1L, "Name1", "Surname1", "email1@example.com"); when(repository.findById(inputDto.getId())).thenReturn(Optional.of(existingStudent)); when(repository.save(existingStudent)).thenReturn(updatedStudent); when(mapper.mapToStudentDto(updatedStudent)).thenReturn(expectedDto); StudentDto resultDto = service.updateStudent(inputDto); assertEquals(expectedDto, resultDto); verify(repository, times(1)).findById(inputDto.getId()); verify(repository, times(1)).save(existingStudent); verify(mapper, times(1)).mapToStudentDto(updatedStudent); }*/ @Test void testUpdateStudent_NotFound() { StudentDto inputDto = new StudentDto(); when(repository.findById(inputDto.getId())).thenReturn(Optional.empty()); assertThrows(ResourceNotFoundException.class, () -> service.updateStudent(inputDto)); verify(repository, times(1)).findById(inputDto.getId()); verifyNoMoreInteractions(repository, mapper); } @Test void testDeleteStudent_Successful() { Long studentId = 1L; Student existingStudent = new Student(1L, "Name1", "Surname1", "email1@example.com"); when(repository.findById(studentId)).thenReturn(Optional.of(existingStudent)); service.deleteStudent(studentId); verify(repository, times(1)).findById(studentId); verify(repository, times(1)).deleteById(studentId); } @Test void testDeleteStudent_NotFound() { Long studentId = 99L; when(repository.findById(studentId)).thenReturn(Optional.empty()); assertThrows(ResourceNotFoundException.class, () -> service.deleteStudent(studentId)); verify(repository, times(1)).findById(studentId); verifyNoMoreInteractions(repository); } }
import React, { useState } from 'react' import { FormControl, FormLabel,useToast, VStack,Input, InputGroup, InputRightElement, Button } from '@chakra-ui/react' import {useNavigate} from 'react-router-dom'; import axios from 'axios'; axios.defaults.baseURL=process.env.REACT_APP_SERVER_DOMAIN; export default function Signup() { const navigate=useNavigate(); const [show,setshow]=useState(false); const [name,setName]=useState(''); const [email,setEmail]=useState(''); const [password,setPassword]=useState(''); const [confirmpassword,setConfirmpassword]=useState(''); const [pic,setPic]=useState(''); const [loading,setloading]=useState(false); const toast=useToast(); const handleClick=()=>setshow(!show); const postdetails=(pics)=>{ setloading(true); if(pics===undefined){ toast({ title: 'Please select an Image!', status: 'warning', duration: 5000, isClosable: true, position: "bottom" }); return; } if(pics.type==="image/jpeg" || pics.type==="image/png"){ const data=new FormData(); data.append("file",pics); data.append("upload_preset","ChitChat"); data.append("cloud_name","dzhvjtoot"); fetch("https://api.cloudinary.com/v1_1/dzhvjtoot/image/upload",{ method:"post", body:data }).then((res)=>res.json()).then(data=>{ setPic(data.url.toString()); console.log(data); setloading(false); }).catch((err)=>{ console.log(err); setloading(false); }); }else{ toast({ title: 'Please select an Image!', status: 'warning', duration: 5000, isClosable: true, position: "bottom" }); setloading(false); return; } } const submitHandler=async()=>{ setloading(true); if(!name || !email || !password || !confirmpassword){ toast({ title: 'Please Fill all the Fields', status: 'warning', duration: 5000, isClosable: true, position: "bottom" }); setloading(false); return; } if(password!==confirmpassword){ toast({ title: 'Password Do Not Match', status: 'warning', duration: 5000, isClosable: true, position: "bottom" }); return; } try{ const config={ headers:{ "Content-type":"application/json", } }; const {data}=await axios.post( "/api/user", {name,email,password,pic}, config); toast({ title:"Registration successful", status:"success", duration:5000, isClosable:true, position:'bottom', }); localStorage.setItem("userinfo",JSON.stringify(data)); setloading(false); navigate('/'); } catch(err){ toast({ title:'Error Occured!', description:err.response.data.message, status:'error', duration:5000, isClosable:true, position:'bottom' }); setloading(false); } }; return ( <VStack spacing='5px' color='black'> <FormControl id='first-name' isRequired> <FormLabel>Name</FormLabel> <Input placeholder='Enter your Name' onChange={(e)=>setName(e.target.value)}></Input> </FormControl> <FormControl id='email' isRequired> <FormLabel>Email</FormLabel> <Input placeholder='Enter your Email' onChange={(e)=>setEmail(e.target.value)}></Input> </FormControl> <FormControl id='password' isRequired> <FormLabel>Password</FormLabel> <InputGroup> <Input placeholder='Enter Password' type={show ? "text": "password"} onChange={(e)=>setPassword(e.target.value)}></Input> <InputRightElement width="4.5rem"> <Button h="1.75rem" mr={"2px"} sm="sm" onClick={handleClick}> {show ? "Hide":"Show"} </Button> </InputRightElement> </InputGroup> </FormControl> <FormControl id='confirmpassword' isRequired> <FormLabel>Confirm Password</FormLabel> <InputGroup> <Input placeholder='Enter Confirm Password' type={show ? "text": "password"} onChange={(e)=>setConfirmpassword(e.target.value)}></Input> <InputRightElement width="4.5rem"> <Button h="1.75rem" mr={"2px"} sm="sm" onClick={handleClick}> {show ? "Hide":"Show"} </Button> </InputRightElement> </InputGroup> </FormControl> <FormControl id='pic' isRequired> <FormLabel>Upload your Picture</FormLabel> <Input type='file' p={1.5} accept='image/*' onChange={(e)=>postdetails(e.target.files[0])}></Input> </FormControl> <Button colorScheme='purple' width="100%" style={{marginTop:15}} onClick={submitHandler} isLoading={loading}>Sign Up</Button> </VStack> ) }
# SpringLobbyServer (Perl module) # # Extensible SpringRTS engine lobby server based on AnyEvent. # Only the network protocol/logic is implemented, all database related # operations (persistency, authentications etc.) must be implemented through # callbacks. # # Copyright (C) 2024 Yann Riou <yaribzh@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # SPDX-License-Identifier: AGPL-3.0-or-later # ######################################## # Customization callbacks # ######################################## # onNewClientConnection: # --------------------- # Parameters: # $r_connInfo,$hdl # Return value: # $denyMsg (undef if allowed) # Processing: # should update $r_connInfo "country" field ######################################## # onAdditionalInGameTime: # --------------------- # Parameters: # $r_connInfo,$login,$r_userInfo,$additionalInGameTime # Return balue (async only): # $mustBroadcastUserStatus # Processing: # can update $r_userInfo->{status}{rank} in case of in-game time based ranks ######################################## # onChannelJoin: # ------------- # Parameters: # $r_connInfo,$login,$r_userInfo,$channel # Return value: # $denyMsg (undef if allowed) ######################################## # onChannelMsg: # ------------ # Parameters: # $r_connInfo,$login,$r_userInfo,$channel,$r_msg,$isExMsg # Return values: # $denyMsg (undef if allowed, empty string if silently denied) # Processing: # update $r_msg in place to modify the message ######################################## # onBattleJoin: # ------------ # Parameters: # $r_connInfo,$login,$r_userInfo,$battleFounderName,$r_battleFounderUserInfo,$battleId # Return value: # $denyMsg (undef if allowed) ######################################## # onBattleMsg: # ----------- # Parameters: # $r_connInfo,$login,$r_userInfo,$battleFounderName,$r_battleFounderUserInfo,$battleId,$r_msg,$isExMsg # Return values: # $denyMsg (undef if allowed, empty string if silently denied) # Processing: # update $r_msg in place to modify the message ######################################## # onPrivateMsg: # ------------ # Parameters: # $r_connInfo,$login,$r_userInfo,$recipient,$r_recipientUserInfo,$r_msg,$isExMsg,$isBattleMsg # Return values: # $denyMsg (undef if allowed, empty string if silently denied) # Processing: # update $r_msg in place to modify the message ######################################## # onChannelTopic(Async): # --------------------- # Parameters: # ($r_callback,)$r_connInfo,$login,$r_userInfo,$channel,$r_topic # Return values: # $denyMsg (undef if allowed, empty string if silently denied) # Processing: # update $r_topic in place to modify the new channel topic ######################################## # registrationSvc: # --------------- # Parameters: # Register mode: # $r_connInfo,$userName,$password,$email ($email = '' if not provided) # Agreement/email confirm mode: # $r_connInfo,$userName,$emailVerificationCode ($emailVerifCode = '' if not provided) # Return value: # $deniedReason (undef if allowed) ######################################## # authenticationSvc: # ----------------- # Parameters: # $r_connInfo,$userName,$password,$r_userInfo # Return value: # $deniedReason (undef if allowed) # Processing: # should update $r_userInfo fields such as: # status/{rank,access,bot} # accountId # pendingAgreement (if an agreement must be confirmed by user and/or email validated with code) # accessLevel # bypassMaxClients # inGameTime # emailAddress # registrationTs # lastLoginTs # ignoredAccounts ( { <accountId> => {userName => $userName[, reason => $reason] } } ) # friendAccounts ( { <accountId> => <userName> } ) # friendRequestsIn ( { <accountId> => {userName => $userName[, msg => $msg] } } ) # friendRequestsOut ( { <accountId> => {userName => $userName[, msg => $msg] } } ) ######################################## # accountManagementSvc{$command}: # ------------------------------ # Parameters: # $r_callback,$r_connInfo,<lobby cmd params...> # RESETPASSWORDREQUEST $email # RESETPASSWORD $email,$verificationCode # $r_callback,$r_connInfo,$login,$r_userInfo,<lobby cmd params...> # RESENDVERIFICATION $email # CHANGEEMAILREQUEST $newEmail # CHANGEEMAIL $newEmail[,$verificationCode] # RENAMEACCOUNT $newUserName # CHANGEPASSWORD $oldPassword,$newPassword # GETUSERINFO $userName # SETBOTMODE $botName,$botMode # CREATEBOTACCOUNT $botName,$ownerName # BAN $userName,$duration,$reason # UNBAN $userName # LISTBANS # SETACCESS $userName,$accessMode # DELETEACCOUNT $userName (must also remove references from ban, ignore and friend data) # Return values (callback parameters): # CHANGEEMAIL,CHANGEPASSWORD, SETBOTMODE, BAN, SETACCESS, DELETEACCOUNT # $failedReason,$accountId # GETUSERINFO # $failedReason,$r_userInfo # {accountId, registrationTs, emailAddress, inGameTime, lastLoginTs, lobbyClient, macAddressHash, systemHash, accessLevel, country, lastIpAddr} # LISTBANS # $failedReason,$r_bans # _OTHERS_ # $failedReason (undef if OK) ######################################## # ignoreSvc{$command}: # -------------------- # Parameters: # $r_callback,$r_connInfo,$login,$r_userInfo,<lobby cmd params...> # IGNORE $userName[,$reason] # UNIGNORE $userName # IGNORELIST (useful to show correct names of offline users who renamed after ignoring user logged in, so ignoring user can unignore them) # Return values (callback parameters): # IGNORE, UNIGNORE # $failedReason,$accountId # IGNORELIST # $r_ignoreList [{userName => $ignoredUserName[, reason => $ignoreReason][, accountId => $ignoredAccountId]},...] ######################################## # friendSvc{$command}: # -------------------- # Parameters: # $r_callback,$r_connInfo,$login,$r_userInfo,<lobby cmd params...> # FRIENDREQUEST $userName[,$msg] (must ignore duplicate requests and ignored accounts, i.e. set $failedReason to "", and check nb friends and nb requests against maxFriendsByAccount) # ACCEPTFRIENDREQUEST $userName # DECLINEFRIENDREQUEST $userName # UNFRIEND $userName # FRIENDREQUESTLIST $isOutReq (useful to show correct names of offline users who renamed after target user logged in, so he can accept/decline them) # FRIENDLIST (useful to show correct names of offline users who renamed after friends logged in, so they can unfriend them) # Return values (callback parameters): # FRIENDREQUEST, ACCEPTFRIENDREQUEST, DECLINEFRIENDREQUEST, UNFRIEND # $failedReason,$friendAccountId # FRIENDREQUESTLIST # $r_friendRequestList [{userName => $friendName[, msg => $msg][, accountId => $friendAccountId,]},...] # FRIENDLIST # $r_friendList [{userName => $friendName[, accountId => $friendAccountId]}] ######################################## # serverBots{$botName}{onPrivateMsg}: # ---------------------------------- # Parameters: $r_callback,$r_connInfo,$login,$r_userInfo,$privateMsg,$isExMsg ($r_connInfo = undef => msg from another server bot) # Return values: $r_responsePrivateMsgs (undef => no response) ######################################## # serverBots{$botName}{onChannelMsg}: # ---------------------------------- # Parameters: $r_callback,$r_connInfo,$login,$r_userInfo,$channel,$chanMsg,$isExMsg ($r_connInfo = undef => msg from another server bot) # Return values: ($r_responseChannelMsgs,$r_responsePrivateMsgs) (undef => no response) ######################################## # channelBots{$channel}{$botName}: # ------------------------------- # Parameters: $r_callback,$r_connInfo,$login,$r_userInfo,$channel,$chanMsg,$isExMsg ($r_connInfo = undef => msg from another server bot) # Return values: ($r_responseChannelMsgs,$r_responsePrivateMsgs) (undef => no response) ######################################## package SpringLobbyServer; use warnings; use strict; use AnyEvent::Handle; use AnyEvent::Socket; use Carp 'croak'; use JSON::PP (); use List::Util qw'all any none first reduce'; use Scalar::Util 'weaken'; use Socket qw'unpack_sockaddr_in inet_ntoa'; use RsaCertPem 'getPemCertificate'; use SpringLobbyProtocol qw':server :regex :int32'; our $VERSION='0.10'; use constant { IP_ADDR_LOOPBACK => 0, IP_ADDR_LAN => 1, IP_ADDR_WAN => 2, SRV_MODE_NORMAL => 0, SRV_MODE_LAN => 1, CNT_CHECK_ONLY => 1, CNT_INCR_ONLY => 2, }; my @LOG_LEVELS=('[ CRITICAL ]','[ ERROR ]','[ WARNING ]','[ NOTICE ]','[ INFO ]','[ DEBUG ]'); my %DEFAULT_PARAMS=( listenAddress => '0.0.0.0', # ('0' IPv4 wildcard, '::' IPv6 wildcard) listenPort => 8200, serverBannerCommand => 'TASSERVER', protocolVersion => '0.37', engineVersion => '*', natHelperPort => '8201', # (unimplemented) serverMode => SRV_MODE_LAN, accessFlagLevel => 100, # access level required to get lobby moderator/admin access flag (0: disable automatic lobby access flag based on access level) defaultCountryCode => '??', readTimeout => 45, writeTimeout => 60, maxReadQueue => 2048, # (maximum length of one lobby command) maxWriteQueue => 524288, # (maximum data queued for one connection, when client does not read the socket) autoCork => 0, # (0: try to write message instantly, 1: wait one event loop) noDelay => 1, # (0: enable Nagle algorithm, 1: disable Nagle algorithm) pemKeyFile => 'spring-lobby-server-key.pem', pemCertFile => 'spring-lobby-server-cert.pem', wanAddress => undef, logger => sub { my ($m,$l)=@_; my @time = localtime(); $time[4]++; @time = map(sprintf('%02d',$_),@time); my $timestamp = ($time[5]+1900).$time[4].$time[3].$time[2].$time[1].$time[0]; my $level = $LOG_LEVELS[$l]; print "$timestamp $level $m\n"; }, debug => 0, motd => [ 'Welcome, {USERNAME}!', 'There are currently {CLIENTS} clients connected.', 'The server is hosting {CHANNELS} chat channels and {BATTLES} battles.', 'Server uptime is {UPTIME}.', ], onNewClientConnection => undef, onNewClientConnectionAsync => undef, onAdditionalInGameTime => undef, onAdditionalInGameTimeAsync => undef, onChannelJoin => undef, onChannelMsg => undef, onBattleJoin => undef, onBattleMsg => undef, onPrivateMsg => undef, onChannelTopic => undef, onChannelTopicAsync => undef, registrationSvc => undef, registrationSvcAsync => undef, authenticationSvc => undef, authenticationSvcAsync => undef, accountManagementSvc => {}, ignoreSvc => {}, friendSvc => {}, channelTopics => {}, # ($channelName => { topic => $topic, author => $author }) countersCleaningInterval => 60, maxChatMsgLength => 1024, # maximum length of messages sent with SAY(EX)/SAYPRIVATE(EX)/SAYBATTLE(EX)/SAYBATTLEPRIVATE(EX) commands (in number of UTF8 characters) maxBattleScriptTags => 512, # maximum number of script tags that can be set in a battle lobby maxConnFailedLogin => 3, # maximum number of failed login attempts before automatically closing the connection (0 = disabled) unauthentConnTimeout => 10, # maximum time in seconds a connection can stay up without successfully logging in (0 = disabled) maxIgnoresByAccount => 100, # maximum number of ignored users by account (0 = disabled) maxFriendsByAccount => 100, # maximum number of friends by account (0 = disabled) maxUnauthentByHost => 8, # maximum number of simultaneous unauthenticated client connections by host (0 = disabled) maxClientsByHost => 4, # maximum number of simultaneous unprivileged client connections by host (not counting accounts with bot or access flag, 0 = disabled) maxInputRateByUnauthent => [[1,4,1024],[10,16,4096]], # maximum rate of input commands/data on unauthenticated connection maxInputRateByClient => [[1,50,4096],[10,200,20480]], # maximum rate of input commands/data by non-bot connection maxInputRateByBot => [[1,1000,262144],[10,4000,524288]], # maximum rate of input commands/data by bot connection maxInducedTrafficRateByClient => [[1,4000,131072],[10,16000,262144]], # maximum rate of commands/data induced by non-bot connection maxInducedTrafficRateByBot => [[1,8000,262144],[10,32000,524288]], # maximum rate of commands/data induced by bot connection maxDbCmdRateByClient => [[1,3],[10,6]], # maximum rate of input commands triggering access to database by non-bot connection maxDbCmdRateByBot => [[1,6],[10,12]], # maximum rate of input commands triggering access to database by bot connection maxLoginRateByAccount => [[10,3],[60,6]], # maximum rate of successful login operations by account maxRenameRateByAccount => [[86400,4]], # maximum rate of successful renaming operations by account maxFailedLoginRateByHost => [[10,3],[60,6]], # maximum rate of failed login attempt by host maxRegisterRateByHost => [[86400,4]], # maximum rate of account registration by host maxFailedAgreementRateByHost => [[10,2]], # maximum rate of failed agreement confirmation by host ); my %DEFAULT_PARAMS_LAN_MODE=( maxConnFailedLogin => 0, unauthentConnTimeout => 0, maxIgnoresByAccount => 0, maxFriendsByAccount => 0, maxUnauthentByHost => 0, maxClientsByHost => 0, maxInputRateByUnauthent => [], maxInputRateByClient => [], maxInputRateByBot => [], maxInducedTrafficRateByClient => [], maxInducedTrafficRateByBot => [], maxDbCmdRateByClient => [], maxDbCmdRateByBot => [], maxLoginRateByAccount => [], maxRenameRateByAccount => [], maxFailedLoginRateByHost => [], maxRegisterRateByHost => [], maxFailedAgreementRateByHost => [], ); # REGISTER, LOGIN, CONFIRMAGREEMENT, RESETPASSWORDREQUEST, RESETPASSWORD, RESENDVERIFICATION can only be used when not logged in and therefore are not useful for DB commands flood protection. # However, they are kept here for completness. our %DATABASE_ACCESS_COMMANDS = map {$_ => 1} ( qw' REGISTER LOGIN CONFIRMAGREEMENT RESETPASSWORDREQUEST RESETPASSWORD RESENDVERIFICATION CHANGEEMAILREQUEST CHANGEEMAIL CHANNELTOPIC RENAMEACCOUNT CHANGEPASSWORD GETUSERINFO SETBOTMODE CREATEBOTACCOUNT BAN UNBAN LISTBANS SETACCESS DELETEACCOUNT IGNORE UNIGNORE IGNORELIST FRIENDREQUEST ACCEPTFRIENDREQUEST DECLINEFRIENDREQUEST UNFRIEND FRIENDREQUESTLIST FRIENDLIST '); our %CMDS=( PING => [0,\&hPing], EXIT => [0,\&hExit], LISTCOMPFLAGS => [0,\&hListCompFlags], STLS => [0,\&hStls], REGISTER => [0,\&hRegister], LOGIN => [0,\&hLogin], CONFIRMAGREEMENT => [0,\&hConfirmAgreement], RESETPASSWORDREQUEST => [0,\&hResetPasswordRequest], RESETPASSWORD => [0,\&hResetPassword], RESENDVERIFICATION => [0,\&hResendVerification], CHANGEEMAILREQUEST => [0,\&hChangeEmailRequest], CHANGEEMAIL => [0,\&hChangeEmail], RENAMEACCOUNT => [1,\&hRenameAccount], CHANGEPASSWORD => [1,\&hChangePassword], MYSTATUS => [1,\&hMyStatus], CHANNELS => [1,\&hChannels], JOIN => [1,\&hJoin], LEAVE => [1,\&hLeave], SAY => [1,\&hSay], SAYEX => [1,\&hSay], SAYPRIVATE => [1,\&hSayPrivate], SAYPRIVATEEX => [1,\&hSayPrivate], OPENBATTLE => [1,\&hOpenBattle], JOINBATTLE => [1,\&hJoinBattle], JOINBATTLEACCEPT => [1,\&hJoinBattleAccept], JOINBATTLEDENY => [1,\&hJoinBattleDeny], LEAVEBATTLE => [1,\&hLeaveBattle], KICKFROMBATTLE => [1,\&hKickFromBattle], MYBATTLESTATUS => [1,\&hMyBattleStatus], ADDBOT => [1,\&hAddBot], REMOVEBOT => [1,\&hRemoveBot], UPDATEBOT => [1,\&hUpdateBot], FORCESPECTATORMODE => [1,\&hForceSpectatorMode], FORCETEAMNO => [1,\&hForceTeamNo], FORCEALLYNO => [1,\&hForceAllyNo], HANDICAP => [1,\&hHandicap], FORCETEAMCOLOR => [1,\&hForceTeamColor], SETSCRIPTTAGS => [1,\&hSetScriptTags], REMOVESCRIPTTAGS => [1,\&hRemoveSCriptTags], DISABLEUNITS => [1,\&hDisableUnits], ENABLEUNITS => [1,\&hEnableUnits], ENABLEALLUNITS => [1,\&hEnableAllUnits], UPDATEBATTLEINFO => [1,\&hUpdateBattleInfo], ADDSTARTRECT => [1,\&hAddStartRect], REMOVESTARTRECT => [1,\&hRemoveStartRect], SAYBATTLE => [1,\&hSayBattle], SAYBATTLEEX => [1,\&hSayBattle], SAYBATTLEPRIVATE => [1,\&hSayBattlePrivate], SAYBATTLEPRIVATEEX => [1,\&hSayBattlePrivate], RING => [1,\&hRing], GETUSERINFO => [1,\&hGetUserInfo], IGNORE => [1,\&hIgnore], UNIGNORE => [1,\&hUnignore], IGNORELIST => [1,\&hIgnoreList], FRIENDREQUEST => [1,\&hFriendRequest], ACCEPTFRIENDREQUEST => [1,\&hAcceptFriendRequest], DECLINEFRIENDREQUEST => [1,\&hDeclineFriendRequest], UNFRIEND => [1,\&hUnfriend], FRIENDREQUESTLIST => [1,\&hFriendRequestList], FRIENDLIST => [1,\&hFriendList], CHANNELTOPIC => [100,\&hChannelTopic], FORCELEAVECHANNEL => [100,\&hForceLeaveChannel], KICK => [100,\&hKick], SETBOTMODE => [100,\&hSetBotMode], CREATEBOTACCOUNT => [100,\&hCreateBotAccount], BAN => [100,\&hBan], UNBAN => [100,\&hUnban], LISTBANS => [100,\&hListBans], SETACCESS => [200,\&hSetAccess], DELETEACCOUNT => [200,\&hDeleteAccount], ); our %IGNORED_CMDS; map {$IGNORED_CMDS{$_}=1} (qw' GETCHANNELMESSAGES c.user.list_relationships c.telemetry.update_client_property c.telemetry.log_client_event c.telemetry.upload_infolog'); my %DEFAULT_SRVBOT_INFO=(country => undef, cpu => 0, accountId => 0, lobbyClient => 'ServerBot'); my %DEFAULT_SRVBOT_STATUS=(inGame => 0, rank => 0, away => 0, access => 1, bot => 1); my $SRVMSG_LOBBY_PROTOCOL_EXTENSIONS = '@PROTOCOL_EXTENSIONS@ '.JSON::PP::encode_json( { 'sayBattlePrivate:multicast' => 1, } ); sub new { my ($this,%params)=@_; my $class = ref($this) || $this; my $self={}; my @invalidParams; foreach my $param (keys %params) { if(exists $DEFAULT_PARAMS{$param}) { $self->{$param}=$params{$param}; }else{ push(@invalidParams,$param); } } croak 'Invalid contructor parameter'.(@invalidParams>1?'s':'').': '.join(', ',@invalidParams) if(@invalidParams); my %defaultParams=%DEFAULT_PARAMS; map {$defaultParams{$_}=$DEFAULT_PARAMS_LAN_MODE{$_}} (keys %DEFAULT_PARAMS_LAN_MODE) if(($self->{serverMode}//$DEFAULT_PARAMS{serverMode}) == SRV_MODE_LAN); map {$self->{$_}//=$defaultParams{$_}} (keys %defaultParams); croak 'Inconsistent server parameters: serverMode is NOT set to LAN mode, but there is NO registration service function defined' if($self->{serverMode} != SRV_MODE_LAN && ! defined $self->{registrationSvc} && ! defined $self->{registrationSvcAsync}); $self->{banner} = join(' ',@{$self}{qw'serverBannerCommand protocolVersion engineVersion natHelperPort serverMode'})."\cJ"; @{$self}{qw'privateKeyPem certPem'}=getPemCertificate(@{$self}{qw'pemKeyFile pemCertFile'}); @{$self}{qw'connections connQueues users lcUsers accounts channels battles serverBots lcServerBots channelBots'}=({},{},{},{},{},{},{},{},{},{}); $self->{nextBattleId}=1; $self->{startTime}=time; map {$self->{$_}={}} (qw'nbUnauthentByHost authentConnByHost'); $self->{accountCounters}={login => {}, rename => {}}; $self->{hostCounters}={FailedLogin => {}, Register => {}, FailedAgreement => {}}; my $weakSelf=$self; weaken($weakSelf); my $anyEventModel=AnyEvent::detect(); $self->{logger}("Running SpringLobbyServer v$VERSION with AnyEvent v$AnyEvent::VERSION (event model: $anyEventModel)",4); $self->{countersCleaner}=AE::timer($self->{countersCleaningInterval},$self->{countersCleaningInterval},sub {cleanPersistentCounters($weakSelf)}); if(! defined $self->{wanAddress}) { AnyEvent::DNS::a('resolver1.opendns.com', sub { my $openDnsResolverAddr=$_[0]; if(defined $openDnsResolverAddr) { AnyEvent::DNS->new(server => [AnyEvent::Socket::parse_address($openDnsResolverAddr)])->resolve( 'myip.opendns.com','a',sub { return unless(defined $weakSelf); if(defined $_[0] && @{$_[0]}) { my $wanIpAddr=$_[0][4]; if($wanIpAddr =~ REGEX_IPV4) { $weakSelf->{logger}("WAN IP address: $wanIpAddr (auto-detected)",3); $weakSelf->{wanAddress}=$wanIpAddr; }else{ $weakSelf->{logger}("Failed to auto-detect WAN IP address (invalid IPv4 address \"$wanIpAddr\")",2); } }else{ $weakSelf->{logger}('Failed to auto-detect WAN IP address (invalid response from resolver)',2); } }); }else{ $weakSelf->{logger}('Failed to auto-detect WAN IP address (unable to contact resolver)',2); } }); } $self->{tcpServer}=tcp_server($self->{listenAddress},$self->{listenPort},sub {onNewClientConnection($weakSelf,@_)}); $self->{logger}("Spring lobby server listening on $self->{listenAddress}:$self->{listenPort}",3); bless($self,$class); return $self; } sub cleanPersistentCounters { my $self=shift; return unless(defined $self); my $currentTime=time(); my $loginAccCountersPruneTime=$currentTime - reduce {$a > $b->[0] ? $a : $b->[0]} (0,@{$self->{maxLoginRateByAccount}}); my $r_accountLoginCounters=$self->{accountCounters}{login}; map {delete $r_accountLoginCounters->{$_} unless($r_accountLoginCounters->{$_}[1] > $loginAccCountersPruneTime)} (keys %{$r_accountLoginCounters}); my $renameAccCountersPruneTime=$currentTime - reduce {$a > $b->[0] ? $a : $b->[0]} (0,@{$self->{maxRenameRateByAccount}}); my $r_accountRenameCounters=$self->{accountCounters}{rename}; map {delete $r_accountRenameCounters->{$_} unless($r_accountRenameCounters->{$_}[1] > $renameAccCountersPruneTime)} (keys %{$r_accountRenameCounters}); foreach my $hostCounterType (qw'FailedLogin Register FailedAgreement') { my $hostCountersPruneTime=$currentTime - reduce {$a > $b->[0] ? $a : $b->[0]} (0,@{$self->{'max'.$hostCounterType.'RateByHost'}}); my $r_countersByHost=$self->{hostCounters}{$hostCounterType}; map {delete $r_countersByHost->{$_} unless($r_countersByHost->{$_}[1] > $hostCountersPruneTime)} (keys %{$r_countersByHost}); } } sub onNewClientConnection { my ($self,$fh,$host,$port)=@_; $self->{debug} && $self->{logger}("New client connection request from [$host:$port]",5); if($self->{maxUnauthentByHost} && exists $self->{nbUnauthentByHost}{$host} && $self->{nbUnauthentByHost}{$host} >= $self->{maxUnauthentByHost}) { close($fh); $self->{debug} && $self->{logger}("Denying client connection from [$host:$port] (too many simultaneous unauthenticated connections)",5); return; } my $r_connInfo={host => $host, port => $port, country => $self->{defaultCountryCode}, connectTime => time}; if(defined $self->{onNewClientConnection}) { my $denyMsg=$self->{onNewClientConnection}($r_connInfo,$fh); if(defined $denyMsg) { close($fh); $self->{debug} && $self->{logger}("Denying client connection from [$host:$port] ($denyMsg)",5); return; } } $self->{nbUnauthentByHost}{$host}++; if(defined $self->{onNewClientConnectionAsync}) { $self->{onNewClientConnectionAsync}( sub { my $denyMsg=shift; if(defined $denyMsg) { close($fh); $self->{debug} && $self->{logger}("Denying client connection from [$host:$port] ($denyMsg)",5); delete $self->{nbUnauthentByHost}{$host} unless(--$self->{nbUnauthentByHost}{$host} > 0); }else{ allowedNewClientConnection($self,$fh,$r_connInfo), } }, $r_connInfo,$fh, ); }else{ allowedNewClientConnection($self,$fh,$r_connInfo); } } sub allowedNewClientConnection { my ($self,$fh,$r_connInfo)=@_; my $connIdx=fileno($fh); my $weakSelf=$self; weaken($weakSelf); my $hdl; $hdl=AnyEvent::Handle->new( connIdx => $connIdx, fh => $fh, rtimeout => $self->{readTimeout}, wtimeout => $self->{writeTimeout}, rbuf_max => $self->{maxReadQueue}, wbuf_max => $self->{maxWriteQueue}, autocork => $self->{autoCork}, no_delay => $self->{noDelay}, on_starttls => sub { my ($tlsHdl,$success,$tlsError)=@_; if($success) { $tlsHdl->push_write($weakSelf->{banner}); }else{ closeClientConnection($weakSelf,$tlsHdl,'TLS handshake error',$tlsError,1); } }, on_error => sub { my ($errorHdl,$isFatal,$errorMsg)=@_; my ($networkError,$errorDetails); if($! == Errno::ECONNRESET) { $networkError='connection reset by peer'; }elsif($! == Errno::ENOSPC) { if(defined $errorHdl->{rbuf_max} && $errorHdl->{rbuf_max} < length($errorHdl->{rbuf})) { $networkError='maximum lobby command size exceeded'; }elsif(defined $errorHdl->{wbuf_max} && $errorHdl->{wbuf_max} < length($errorHdl->{wbuf})) { $networkError='write queue overflow' }else{ $networkError='network error'; $errorDetails=$errorMsg; } }else{ $networkError='network error'; $errorDetails=$errorMsg; } closeClientConnection($weakSelf,$errorHdl,$networkError,$errorDetails,1); }, on_eof => sub {closeClientConnection($weakSelf,$_[0],'connection closed by peer',undef,1)}, on_rtimeout => sub {closeClientConnection($weakSelf,$_[0],'socket read timeout',undef,1)}, on_wtimeout => sub {closeClientConnection($weakSelf,$_[0],'socket write timeout',undef,1)}, on_read => sub {$_[0]->push_read(line => qr'\cM?\cJ+', sub {handleLobbyCmdFromClient($weakSelf,@_)})}, #skylobby puts several LF after STLS, TASClient puts CR before LF... ); if($hdl) { $self->{debug} && $self->{logger}("Allowing client connection from [$r_connInfo->{host}:$r_connInfo->{port}]",5); $r_connInfo->{hdl}=$hdl; $r_connInfo->{ipAddrType}=getIpAddrType($r_connInfo->{host}); $r_connInfo->{localIpAddr}=inet_ntoa((unpack_sockaddr_in(getsockname($fh)))[1]) if($r_connInfo->{ipAddrType} == IP_ADDR_LAN); $r_connInfo->{loginTimeout}=AE::timer($self->{unauthentConnTimeout},0,sub {return if($hdl->destroyed()); closeClientConnection($weakSelf,$hdl,'login timeout',undef,1)}) if($self->{unauthentConnTimeout}); $r_connInfo->{inputRateCounters}=[undef,undef]; $self->{connections}{$connIdx}=$r_connInfo; $hdl->push_write($self->{banner}); }else{ $self->{logger}("Failed to accept client connection from [$r_connInfo->{host}:$r_connInfo->{port}]: $!",1); } } sub closeClientConnection { my ($self,$hdl,$reason,$details,$skipQueueDrain)=@_; return if(exists $self->{closeClientConnectionInProgress}); # avoid recursive call to closeClientConnection (may happen when draining queue below) my $connIdx=$hdl->{connIdx}; my $r_connInfo = delete $self->{connections}{$connIdx}; my $host=$r_connInfo->{host}; my $login=$r_connInfo->{login}; if($self->{debug}) { my $detailsStr = defined $details ? ' ('.$details.')' : ''; $self->{logger}('Removing connection of client'.(defined $login ? " \"$login\"" : '')." [$host:$r_connInfo->{port}]: $reason$detailsStr",5); } if(defined $login) { my $r_userInfo = delete $self->{users}{$login}; my $accountId=$r_userInfo->{accountId}; delete $self->{accounts}{$accountId} if($accountId); delete $self->{lcUsers}{lc($login)}; my $r_channels=$self->{channels}; my $channelLeftReason; if($reason eq 'quit') { $channelLeftReason='Quit: '; $channelLeftReason.=$details if(defined $details); }else{ $channelLeftReason=$reason; } map {delete $r_channels->{$_}{$login}; %{$r_channels->{$_}} ? broadcastChannel($self,$_,'LEFT',$_,$login,$channelLeftReason) : delete $r_channels->{$_}} (keys %{$r_userInfo->{channels}}); my $bId=$r_userInfo->{battle}; if(defined $bId) { my $r_b=$self->{battles}{$bId}; delete $r_b->{users}{$login}; if($r_b->{founder} eq $login) { map {undef $self->{users}{$_}{battle}} (keys %{$r_b->{users}}); delete $self->{battles}{$bId}; broadcast($self,'BATTLECLOSED',$bId); }else{ map {delete $r_b->{bots}{$_}; broadcastBattle($self,$bId,'REMOVEBOT',$bId,$_)} (grep {$r_b->{bots}{$_}{owner} eq $login} (keys %{$r_b->{bots}})); broadcast($self,'LEFTBATTLE',$bId,$login); } } broadcast($self,'REMOVEUSER',$login); my $r_hostConns=$self->{authentConnByHost}{$host}; delete $r_hostConns->{$connIdx}; delete $self->{authentConnByHost}{$host} unless(%{$r_hostConns}); }else{ delete $self->{nbUnauthentByHost}{$host} unless(--$self->{nbUnauthentByHost}{$host} > 0); } my $r_queuedMsgs=delete $self->{connQueues}{$connIdx}; if(defined $r_queuedMsgs && ! $skipQueueDrain) { $self->{closeClientConnectionInProgress}=1; if($#{$r_queuedMsgs} == 0) { $hdl->push_write(${$r_queuedMsgs->[0]}); }else{ my $queueBuffer; $queueBuffer.=$$_ for (@{$r_queuedMsgs}); $hdl->push_write($queueBuffer); } delete $self->{closeClientConnectionInProgress}; } $hdl->destroy(); return; # explicitely return undef to skip checkInducedTrafficFlood() call when using "return closeClientConnection()" idiom } sub getIpAddrType { my $ipAddr=shift; return IP_ADDR_LOOPBACK if(substr($ipAddr,0,4) eq '127.'); return IP_ADDR_LAN if(substr($ipAddr,0,3) eq '10.' || substr($ipAddr,0,8) eq '192.168.' || ($ipAddr =~ /^172\.(\d+)\./ && $1 > 15 && $1 < 32)); return IP_ADDR_WAN; } sub handleLobbyCmdFromClient { my ($self,$hdl,$line)=@_; if(! exists $self->{netMsgRcvTime}) { delete $self->{scheduledDispatcher}; $self->{netMsgRcvTime}=time(); AE::postpone { delete $self->{netMsgRcvTime}; dispatchMessages($self); }; } my $r_connInfo=$self->{connections}{$hdl->{connIdx}}; my $login=$r_connInfo->{login}; $self->{debug} && $self->{logger}('Received from'.(defined $login ? " \"$login\"" : '')." [$r_connInfo->{host}:$r_connInfo->{port}]: \"$line\"",5); return closeClientConnection($self,$hdl,'input flood') if(defined checkInputFlood($self,$r_connInfo,length($line))); my ($r_cmd,$cmdId) = eval { unmarshallClientCommand($line) }; do { chomp($@); return closeClientConnection($self,$hdl,'protocol error',$@) } unless(defined $r_cmd); my $cmd=$r_cmd->[0]; return closeClientConnection($self,$hdl,'protocol error','empty command') unless(defined $cmd); if(exists $CMDS{$cmd}) { if(defined $login) { my $r_userInfo=$self->{users}{$login}; if($r_userInfo->{accessLevel} < $CMDS{$cmd}[0]) { $self->{logger}("Client \"$login\" [$r_connInfo->{host}:$r_connInfo->{port}] tried to call command \"$cmd\" with insuficient privileges",3); }else{ return closeClientConnection($self,$hdl,'database access command flood') if(exists $DATABASE_ACCESS_COMMANDS{$cmd} && defined checkDbCmdFlood($self,$r_userInfo)); my @inducedTraffic=$CMDS{$cmd}[1]->($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId); return if($hdl->destroyed()); return closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); } }else{ if($CMDS{$cmd}[0]) { closeClientConnection($self,$hdl,'protocol error','command requires authentication first'); }else{ $CMDS{$cmd}[1]->($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId); } } }elsif($IGNORED_CMDS{$cmd}) { $self->{debug} && $self->{logger}("Ignored command received from".(defined $login ? " \"$login\"" : '')." [$r_connInfo->{host}:$r_connInfo->{port}]: \"$cmd\"",5); }else{ $self->{logger}("Unsupported command received from".(defined $login ? " \"$login\"" : '')." [$r_connInfo->{host}:$r_connInfo->{port}]: \"$cmd\"",3); closeClientConnection($self,$hdl,'protocol error','unknown command on unauthenticated connection') unless(defined $login); } } sub checkInputFlood { my ($self,$r_connInfo,$length)=@_; my $login=$r_connInfo->{login}; my $r_thresholds; if(defined $login) { my $r_userStatus=$self->{users}{$login}{status}; return undef if($r_userStatus->{access}); $r_thresholds = $self->{$r_userStatus->{bot} ? 'maxInputRateByBot' : 'maxInputRateByClient'}; }else{ $r_thresholds=$self->{maxInputRateByUnauthent}; } my $r_rlData=$r_connInfo->{inputRateCounters}; my $idxThresh=checkDataRateLimits($r_thresholds,$r_rlData,$self->{netMsgRcvTime},$length); return $idxThresh unless(defined $idxThresh && $self->{debug}); my ($period,$maxCmds,$maxDataSize)=@{$r_thresholds->[$idxThresh]}; my ($nbCmds,$dataSize)=@{$r_rlData->[0][$idxThresh][0]}[1,2]; $self->{logger}('Input flood from'.(defined $login ? " \"$login\"" : '')." [$r_connInfo->{host}:$r_connInfo->{port}]: period=${period}s., cmd=$nbCmds/$maxCmds, data=$dataSize/$maxDataSize",5); return $idxThresh; } sub checkInducedTrafficFlood { my ($self,$r_userInfo,$nbEvents,$sumData)=@_; my $r_userStatus=$r_userInfo->{status}; return undef if($r_userStatus->{access}); my $r_thresholds = $self->{$r_userStatus->{bot} ? 'maxInducedTrafficRateByBot' : 'maxInducedTrafficRateByClient'}; my $idxThresh=checkDataRateLimitsMulti($r_thresholds,$r_userInfo->{inducedTrafficRateCounters},$self->{netMsgRcvTime}//time(),$nbEvents,$sumData); return $idxThresh unless(defined $idxThresh && $self->{debug}); my ($period,$maxCmds,$maxDataSize)=@{$r_thresholds->[$idxThresh]}; my ($nbCmds,$dataSize)=@{$r_userInfo->{inducedTrafficRateCounters}[0][$idxThresh][0]}[1,2]; my $r_connInfo=$self->{connections}{$r_userInfo->{connIdx}}; $self->{logger}("Induced traffic flood from \"$r_connInfo->{login}\" [$r_connInfo->{host}:$r_connInfo->{port}]: period=${period}s., cmd=$nbCmds/$maxCmds, data=$dataSize/$maxDataSize",5); return $idxThresh; } sub addInducedTraffic { my ($r_inducedTraffic,$nbEvents,$sumData)=@_; return unless($nbEvents); $r_inducedTraffic->[0]+=$nbEvents; $r_inducedTraffic->[1]+=$sumData; } sub checkDbCmdFlood { my ($self,$r_userInfo)=@_; my $r_userStatus=$r_userInfo->{status}; return undef if($r_userStatus->{access}); my $r_thresholds = $self->{$r_userStatus->{bot} ? 'maxDbCmdRateByBot' : 'maxDbCmdRateByClient'}; my $idxThresh=checkRateLimits($r_thresholds,$r_userInfo->{dbCmdCounters},$self->{netMsgRcvTime}); return $idxThresh unless(defined $idxThresh && $self->{debug}); my ($period,$maxCmds)=@{$r_thresholds->[$idxThresh]}; my $nbCmds=$r_userInfo->{dbCmdCounters}[0][$idxThresh][0][1]; my $r_connInfo=$self->{connections}{$r_userInfo->{connIdx}}; $self->{logger}("Database access command flood from \"$r_connInfo->{login}\" [$r_connInfo->{host}:$r_connInfo->{port}]: period=${period}s., cmd=$nbCmds/$maxCmds",5); return $idxThresh; } sub checkAccountLoginFlood { my ($self,$r_userInfo,$login)=@_; return undef if($r_userInfo->{status}{access}); my $accountIdOrLogin=$r_userInfo->{accountId} || $login; $self->{accountCounters}{login}{$accountIdOrLogin}//=[undef,undef]; my $r_accLoginCounters=$self->{accountCounters}{login}{$accountIdOrLogin}; my $idxThresh=checkRateLimits($self->{maxLoginRateByAccount},$r_accLoginCounters,$r_userInfo->{loginTime}); return $idxThresh unless(defined $idxThresh && $self->{debug}); my ($period,$maxLogins)=@{$self->{maxLoginRateByAccount}[$idxThresh]}; my $nbLogins=$r_accLoginCounters->[0][$idxThresh][0][1]; my $r_connInfo=$self->{connections}{$r_userInfo->{connIdx}}; $self->{logger}("Login flood from \"$login\" [$r_connInfo->{host}:$r_connInfo->{port}]: period=${period}s., login=$nbLogins/$maxLogins",5); return $idxThresh; } sub checkAccountRenameFlood { my ($self,$r_userInfo,$currentTime,$partialMode)=@_; return undef if($r_userInfo->{status}{access}); my $r_connInfo=$self->{connections}{$r_userInfo->{connIdx}}; my $accountIdOrLogin=$r_userInfo->{accountId} || $r_connInfo->{login}; if(! exists $self->{accountCounters}{rename}{$accountIdOrLogin}) { return if($partialMode == CNT_CHECK_ONLY); $self->{accountCounters}{rename}{$accountIdOrLogin}=[undef,undef]; } my $r_accRenameCounters=$self->{accountCounters}{rename}{$accountIdOrLogin}; my $idxThresh=checkRateLimits($self->{maxRenameRateByAccount},$r_accRenameCounters,$currentTime,$partialMode); return $idxThresh unless(defined $idxThresh && $self->{debug}); my ($period,$maxRenames)=@{$self->{maxRenameRateByAccount}[$idxThresh]}; my $nbRenames=$r_accRenameCounters->[0][$idxThresh][0][1]; $self->{logger}("Rename flood from \"$r_connInfo->{login}\" [$r_connInfo->{host}:$r_connInfo->{port}]: period=${period}s., rename=$nbRenames/$maxRenames",5); return $idxThresh; } sub checkHostFlood { my ($self,$checkType,$host,$currentTime,$partialMode)=@_; my $r_countersByHost=$self->{hostCounters}{$checkType}; if(! exists $r_countersByHost->{$host}) { return if($partialMode == CNT_CHECK_ONLY); $r_countersByHost->{$host}=[undef,undef]; } my $r_hostCounters=$r_countersByHost->{$host}; my $r_thresholds=$self->{'max'.$checkType.'RateByHost'}; my $idxThresh=checkRateLimits($r_thresholds,$r_hostCounters,$currentTime,$partialMode); return $idxThresh unless(defined $idxThresh && $self->{debug}); my ($period,$max)=@{$r_thresholds->[$idxThresh]}; my $current=$r_hostCounters->[0][$idxThresh][0][1]; $self->{logger}($checkType." flood from host \"$host\": $current/$max (period=${period}s.)",5); return $idxThresh; } ###################################################################### # This function checks the counters before incrementing: it does NOT increment any counter if any threshold is reached. # # Rate limiter structures: # # $r_thresholds=[ # [$period1,$maxEvents1], # [$period2,$maxEvents2], # ... # ]; # # $r_rlData: # 0] $r_counters=[ # [[$nextPeriodStart1,$currentNbEvents1],[$currentPeriodStart1,$oldNbEvents1]], # [[$nextPeriodStart2,$currentNbEvents2],[$currentPeriodStart2,$oldNbEvents2]], # ... # ]; # # 1] $timestampLastUpdate ###################################################################### sub checkRateLimits { my ($r_thresholds,$r_rlData,$currentTime,$partialMode)=@_; my ($r_counters,$timestampLastUpdate)=@{$r_rlData}; if(defined $timestampLastUpdate) { if($currentTime == $timestampLastUpdate) { if(! defined $partialMode || $partialMode == CNT_CHECK_ONLY) { my $firstMatchingThresh=first {$r_counters->[$_][0][1] >= $r_thresholds->[$_][1]} (0..$#{$r_thresholds}); return $firstMatchingThresh if(defined $firstMatchingThresh); return undef if(defined $partialMode); } map {$_->[0][1]++} @{$r_counters}; }else{ if(! defined $partialMode || $partialMode == CNT_CHECK_ONLY) { my $firstMatchingThresh=first {$currentTime < $r_counters->[$_][0][0] && $r_counters->[$_][0][1] >= $r_thresholds->[$_][1]} (0..$#{$r_thresholds}); return $firstMatchingThresh if(defined $firstMatchingThresh); return undef if(defined $partialMode); } for my $threshIdx (0..$#{$r_counters}) { my $r_counterData=$r_counters->[$threshIdx]; if($currentTime < $r_counterData->[0][0]) { $r_counterData->[0][1]++; }else{ pop(@{$r_counterData}); unshift(@{$r_counterData},[$currentTime+$r_thresholds->[$threshIdx][0],1]); } } } }else{ return undef if(defined $partialMode && $partialMode == CNT_CHECK_ONLY); $r_rlData->[0]=[map {[[$currentTime+$_->[0],1],[$currentTime,0]]} @{$r_thresholds}]; } $r_rlData->[1]=$currentTime; return undef; } ###################################################################### # This function checks the counters after incrementing: it always increments the counters. # Data rate limiter structures: # # $r_thresholds=[ # [$period1,$maxEvents1,$maxData1], # [$period2,$maxEvents2,$maxData2], # ... # ]; # $period1 < $period2 # # $r_rlData: # 0] $r_counters=[ # [[$nextPeriodStart1,$currentNbEvents1,$currentDataSize1],[$currentPeriodStart1,$oldNbEvents1,$oldDataSize1]], # [[$nextPeriodStart2,$currentNbEvents2,$currentDataSize2],[$currentPeriodStart2,$oldNbEvents2,$oldDataSize2]], # ... # ]; # # 1] $timestampLastUpdate ###################################################################### sub checkDataRateLimits { my ($r_thresholds,$r_rlData,$currentTime,$newData)=@_; my ($r_counters,$timestampLastUpdate)=@{$r_rlData}; $r_rlData->[1]=$currentTime; if(defined $timestampLastUpdate) { if($currentTime == $timestampLastUpdate) { map {$_->[0][1]++; $_->[0][2]+=$newData} @{$r_counters}; }else{ for my $threshIdx (0..$#{$r_counters}) { my $r_counterData=$r_counters->[$threshIdx]; if($currentTime < $r_counterData->[0][0]) { $r_counterData->[0][1]++; $r_counterData->[0][2]+=$newData; }else{ pop(@{$r_counterData}); unshift(@{$r_counterData},[$currentTime+$r_thresholds->[$threshIdx][0],1,$newData]); } } } return first {$r_counters->[$_][0][1] > $r_thresholds->[$_][1] || $r_counters->[$_][0][2] > $r_thresholds->[$_][2]} (0..$#{$r_thresholds}); }else{ $r_rlData->[0]=[map {[[$currentTime+$_->[0],1,$newData],[$currentTime,0,0]]} @{$r_thresholds}]; return first {$newData > $r_thresholds->[$_][2]} (0..$#{$r_thresholds}); } } sub checkDataRateLimitsMulti { my ($r_thresholds,$r_rlData,$currentTime,$nbEvents,$sumData)=@_; my ($r_counters,$timestampLastUpdate)=@{$r_rlData}; $r_rlData->[1]=$currentTime; if(defined $timestampLastUpdate) { if($currentTime == $timestampLastUpdate) { map {$_->[0][1]+=$nbEvents; $_->[0][2]+=$sumData} @{$r_counters}; }else{ for my $threshIdx (0..$#{$r_counters}) { my $r_counterData=$r_counters->[$threshIdx]; if($currentTime < $r_counterData->[0][0]) { $r_counterData->[0][1]+=$nbEvents; $r_counterData->[0][2]+=$sumData; }else{ pop(@{$r_counterData}); unshift(@{$r_counterData},[$currentTime+$r_thresholds->[$threshIdx][0],$nbEvents,$sumData]); } } } return first {$r_counters->[$_][0][1] > $r_thresholds->[$_][1] || $r_counters->[$_][0][2] > $r_thresholds->[$_][2]} (0..$#{$r_thresholds}); }else{ $r_rlData->[0]=[map {[[$currentTime+$_->[0],$nbEvents,$sumData],[$currentTime,0,0]]} @{$r_thresholds}]; return first {$nbEvents > $r_thresholds->[$_][1] || $sumData > $r_thresholds->[$_][2]} (0..$#{$r_thresholds}); } } sub dispatchMessages { my $self=shift; while(my @queuedConns = keys %{$self->{connQueues}}) { foreach my $queuedConn (@queuedConns) { my $r_queuedMsgs=delete $self->{connQueues}{$queuedConn}; if($#{$r_queuedMsgs} == 0) { $self->{connections}{$queuedConn}{hdl}->push_write(${$r_queuedMsgs->[0]}); }else{ my $queueBuffer; $queueBuffer.=$$_ for (@{$r_queuedMsgs}); $self->{connections}{$queuedConn}{hdl}->push_write($queueBuffer); } } } $self->{scheduledDispatcher}=AE::timer(0.1,0,sub {dispatchMessages($self)}); } # sendClient($self,$hdl,$r_aCmd[,$cmdId]) sub sendClient { return sendClientByIdx($_[0],$_[1]->{connIdx},$_[2],$_[3]) } # sendClientByIdx($self,$connIdx,$r_aCmd[,$cmdId]) # called by: sendClient, sendUser, hJoinBattleDeny sub sendClientByIdx { my $mCmd=marshallServerCommand($_[2],$_[3]); sendClientMarshalled($_[0],$_[1],\$mCmd); return (1,length($mCmd)); } # sendClientMulti($self,$hdl,$r_aCmds[,$cmdId]) sub sendClientMulti { return sendClientMultiByIdx($_[0],$_[1]->{connIdx},$_[2],$_[3]) } # sendClientMultiByIdx($self,$connIdx,$r_aCmds[,$cmdId]) sub sendClientMultiByIdx { my $mCmd; $mCmd.=$_ for (map {marshallServerCommand($_,$_[3])} @{$_[2]}); sendClientMarshalled($_[0],$_[1],\$mCmd); return (1,length($mCmd)); # merged commands count as one network command (no network I/O overhead) } # sendClientMarshalled($self,$conndIdx,$r_sCmd) # called by: sendClientByIdx, sendClientMulti, sendUserMarshalled sub sendClientMarshalled { my ($self,$connIdx,$r_msg)=@_; if($self->{debug}) { my $r_connInfo=$self->{connections}{$connIdx}; $self->{logger}('Sending to'.(defined $r_connInfo->{login} ? " \"$r_connInfo->{login}\"" : '')." [$r_connInfo->{host}:$r_connInfo->{port}]: \"".substr(${$r_msg},0,-1).'"',5); } push(@{$self->{connQueues}{$connIdx}},$r_msg); } # sendUser($self,$user,$r_aCmd[,$cmdId]) sub sendUser { return sendClientByIdx($_[0],$_[0]->{users}{$_[1]}{connIdx},$_[2],$_[3]) } # sendUserMarshalled($self,$user,$r_sCmd) # called by: broadcast, broadcastLegacy, broadcastChannel, broadcastChannelLegacy, broadcastBattle, broadcastBattleUFlag sub sendUserMarshalled { sendClientMarshalled($_[0],$_[0]->{users}{$_[1]}{connIdx},$_[2]) } sub broadcast { my $self=shift; my $mCmd=marshallServerCommand(\@_); map {sendUserMarshalled($self,$_,\$mCmd)} (keys %{$self->{users}}); my $nbCmdsSent=keys %{$self->{users}}; return ($nbCmdsSent,length($mCmd) * $nbCmdsSent); } sub broadcastLegacy { my $self=shift; my ($mCmd,$mCmdLegacy)=(marshallServerCommand($_[0]),marshallServerCommand($_[1])); my ($nbCmds,$nbCmdsLegacy)=(0,0); foreach my $userName (keys %{$self->{users}}) { if($self->{users}{$userName}{isLegacyClient}) { sendUserMarshalled($self,$userName,\$mCmdLegacy); ++$nbCmdsLegacy; }else{ sendUserMarshalled($self,$userName,\$mCmd); ++$nbCmds; } } return ($nbCmds+$nbCmdsLegacy , $nbCmds*length($mCmd) + $nbCmdsLegacy*length($mCmdLegacy)); } sub broadcastChannel { my ($self,$chan)=(shift,shift); if(exists $self->{channels}{$chan}) { my $mCmd=marshallServerCommand(\@_); map {sendUserMarshalled($self,$_,\$mCmd)} (keys %{$self->{channels}{$chan}}); my $nbCmdsSent=keys %{$self->{channels}{$chan}}; return ($nbCmdsSent,$nbCmdsSent*length($mCmd)); }else{ return (0,0); } } sub broadcastChannelLegacy { my ($self,$chan)=(shift,shift); if(exists $self->{channels}{$chan}) { my ($mCmd,$mCmdLegacy)=(marshallServerCommand($_[0]),marshallServerCommand($_[1])); my ($nbCmds,$nbCmdsLegacy)=(0,0); foreach my $userName (keys %{$self->{channels}{$chan}}) { if($self->{users}{$userName}{isLegacyClient}) { sendUserMarshalled($self,$userName,\$mCmdLegacy); ++$nbCmdsLegacy; }else{ sendUserMarshalled($self,$userName,\$mCmd); ++$nbCmds; } } return ($nbCmds+$nbCmdsLegacy , $nbCmds*length($mCmd) + $nbCmdsLegacy*length($mCmdLegacy)); }else{ return (0,0); } } sub broadcastBattle { my ($self,$bId)=(shift,shift); my $mCmd=marshallServerCommand(\@_); map {sendUserMarshalled($self,$_,\$mCmd)} (keys %{$self->{battles}{$bId}{users}}); my $nbCmdsSent=keys %{$self->{battles}{$bId}{users}}; return ($nbCmdsSent,$nbCmdsSent*length($mCmd)); } sub broadcastBattleUFlag { my ($self,$bId)=(shift,shift); my ($mCmdUFlag,$mCmd)=(marshallServerCommand($_[0]),marshallServerCommand($_[1])); my ($nbCmdsUFlag,$nbCmds)=(0,0); foreach my $userName (keys %{$self->{battles}{$bId}{users}}) { if($self->{users}{$userName}{compFlags}{u}) { sendUserMarshalled($self,$userName,\$mCmdUFlag); ++$nbCmdsUFlag; }else{ sendUserMarshalled($self,$userName,\$mCmd); ++$nbCmds; } } return ($nbCmdsUFlag+$nbCmds,$nbCmdsUFlag*length($mCmdUFlag)+$nbCmds*length($mCmd)); } sub broadcastChannelMsgToSrvBots { my ($self,$r_connInfo,$userName,$r_userInfo,$chan,$msg,$isExMsg)=@_; return unless(exists $self->{channelBots}{$chan}); my $accountId=$r_userInfo->{accountId}; foreach my $srvBot (keys %{$self->{channelBots}{$chan}}) { my $r_onSpecificChannelMsg=$self->{channelBots}{$chan}{$srvBot}; my $r_onChannelMsg=$self->{serverBots}{$srvBot}{onChannelMsg}; return unless(defined $r_onSpecificChannelMsg || defined $r_onChannelMsg); my $srvBotAccountId=$self->{serverBots}{$srvBot}{accountId}; my $r_onChanMsgCb = sub { my ($r_chanMsgs,$r_pvMsgs)=@_; my $r_srvBotInfo=$self->{serverBots}{$srvBot}; return unless(defined $r_srvBotInfo); AE::postpone { if(defined $r_chanMsgs && @{$r_chanMsgs} && exists $r_srvBotInfo->{channels}{$chan}) { foreach my $response (@{$r_chanMsgs}) { my ($responseMsg,$saidCmd,$useExMsg); if(ref $response eq '') { ($responseMsg,$saidCmd,$useExMsg)=($response,'SAID',0); }else{ ($responseMsg,$saidCmd,$useExMsg)=($response->[0],'SAIDEX',1); } broadcastChannel($self,$chan,$saidCmd,$chan,$srvBot,$responseMsg); broadcastChannelMsgToSrvBots($self,undef,$srvBot,$r_srvBotInfo,$chan,$responseMsg,$useExMsg); } } if(defined $r_pvMsgs && @{$r_pvMsgs}) { my $recipient=getOnlineClientName($self,$accountId,$userName); if(defined $recipient) { return if($srvBotAccountId && exists $self->{users}{$recipient}{ignoredAccounts}{$srvBotAccountId}); foreach my $response (@{$r_pvMsgs}) { my ($responseMsg,$saidPrivateCmd); if(ref $response eq '') { ($responseMsg,$saidPrivateCmd)=($response,'SAIDPRIVATE'); }else{ ($responseMsg,$saidPrivateCmd)=($response->[0],'SAIDPRIVATEEX'); } sendUser($self,$recipient,[$saidPrivateCmd,$srvBot,$responseMsg]); } }elsif(exists $self->{serverBots}{$userName}) { foreach my $response (@{$r_pvMsgs}) { my ($responseMsg,$useExMsg); if(ref $response eq '') { ($responseMsg,$useExMsg)=($response,0); }else{ ($responseMsg,$useExMsg)=($response->[0],1); } sendPrivateMsgToSrvBot($self,undef,$srvBot,$r_srvBotInfo,$userName,$responseMsg,$useExMsg); } } } }; }; $r_onSpecificChannelMsg->($r_onChanMsgCb,$r_connInfo,$userName,$r_userInfo,$chan,$msg,$isExMsg) if(defined $r_onSpecificChannelMsg); $r_onChannelMsg->($r_onChanMsgCb,$r_connInfo,$userName,$r_userInfo,$chan,$msg,$isExMsg) if(defined $r_onChannelMsg); } } sub sendPrivateMsgToSrvBot { my ($self,$r_connInfo,$userName,$r_userInfo,$srvBot,$msg,$isExMsg)=@_; return unless(exists $self->{serverBots}{$srvBot} && defined $self->{serverBots}{$srvBot}{onPrivateMsg}); my $srvBotAccountId=$self->{serverBots}{$srvBot}{accountId}; my $accountId=$r_userInfo->{accountId}; $self->{serverBots}{$srvBot}{onPrivateMsg}( sub { my $r_pvMsgs=shift; return unless(defined $r_pvMsgs && @{$r_pvMsgs}); my $r_srvBotInfo=$self->{serverBots}{$srvBot}; return unless(defined $r_srvBotInfo); my $recipient; if($accountId) { $recipient=$self->{accounts}{$accountId}; }elsif(exists $self->{users}{$userName}) { $recipient=$userName; } if(defined $recipient) { return if($srvBotAccountId && exists $self->{users}{$recipient}{ignoredAccounts}{$srvBotAccountId}); foreach my $response (@{$r_pvMsgs}) { my ($responseMsg,$saidPrivateCmd); if(ref $response eq '') { ($responseMsg,$saidPrivateCmd)=($response,'SAIDPRIVATE'); }else{ ($responseMsg,$saidPrivateCmd)=($response->[0],'SAIDPRIVATEEX'); } sendUser($self,$recipient,[$saidPrivateCmd,$srvBot,$responseMsg]); } }elsif(exists $self->{serverBots}{$userName}) { foreach my $response (@{$r_pvMsgs}) { my ($responseMsg,$useExMsg); if(ref $response eq '') { ($responseMsg,$useExMsg)=($response,0); }else{ ($responseMsg,$useExMsg)=($response->[0],1); } sendPrivateMsgToSrvBot($self,undef,$srvBot,$r_srvBotInfo,$userName,$responseMsg,$useExMsg); } } }, $r_connInfo,$userName,$r_userInfo,$msg,$isExMsg, ); } # Following functions are called for each online user when a new battle is opened # $hostLanIpAddr is only provided if != '*' # $selfWanIpAddr is only provided if != '' (i.e. manual or successfully auto-detected WAN IP address) sub getLoopbackBattleAddrForUser { my ($r_userConnInfo,$hostIpAddr,$hostLanIpAddr,$selfWanIpAddr)=@_; return $hostIpAddr if($r_userConnInfo->{ipAddrType} == IP_ADDR_LOOPBACK); return $r_userConnInfo->{localIpAddr} if($r_userConnInfo->{ipAddrType} == IP_ADDR_LAN); return $selfWanIpAddr // $hostLanIpAddr // $hostIpAddr; } sub getLanBattleAddrForUser { my ($r_userConnInfo,$hostIpAddr,undef,$selfWanIpAddr)=@_; return $hostIpAddr if($r_userConnInfo->{ipAddrType} == IP_ADDR_LOOPBACK || $r_userConnInfo->{ipAddrType} == IP_ADDR_LAN); return $selfWanIpAddr // $hostIpAddr; } sub getWanBattleAddrForUser { my ($r_userConnInfo,$hostIpAddr,$hostLanIpAddr)=@_; return $hostIpAddr if($r_userConnInfo->{ipAddrType} == IP_ADDR_LOOPBACK || $r_userConnInfo->{ipAddrType} == IP_ADDR_LAN); return $hostLanIpAddr if(defined $hostLanIpAddr && $r_userConnInfo->{host} eq $hostIpAddr); return $hostIpAddr; } # Following functions are called for each open battle when a new user logs in # $hostLanIpAddr is always provided (must be compared to '*' before use) # $selfWanIpAddr is only provided if != '' (i.e. manual or successfully auto-detected WAN IP address) sub getBattleAddrForLoopbackUser { return $_[1] } sub getBattleAddrForLanUser { my ($r_userConnInfo,$hostIpAddr,$hostIpAddrType)=@_; return $r_userConnInfo->{localIpAddr} if($hostIpAddrType == IP_ADDR_LOOPBACK); return $hostIpAddr; } sub getBattleAddrForWanUser { my ($r_userConnInfo,$hostIpAddr,$hostIpAddrType,$hostLanIpAddr,$selfWanIpAddr)=@_; if($hostIpAddrType == IP_ADDR_LOOPBACK) { return $selfWanIpAddr if(defined $selfWanIpAddr); return $hostLanIpAddr unless($hostLanIpAddr eq '*'); return $hostIpAddr; } return $selfWanIpAddr // $hostIpAddr if($hostIpAddrType == IP_ADDR_LAN); return $hostLanIpAddr if($hostLanIpAddr ne '*' && $r_userConnInfo->{host} eq $hostIpAddr); return $hostIpAddr; } sub hPing { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; return sendClient($self,$hdl,['PONG'],$cmdId); } sub hExit { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; return closeClientConnection($self,$hdl,'quit',$r_cmd->[1],1); } sub hListCompFlags { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; return sendClient($self,$hdl,['COMPFLAGS','sp','b','u'],$cmdId); } sub hStls { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; return closeClientConnection($self,$hdl,'protocol error','duplicate STLS command') if($hdl->{tls}); sendClient($self,$hdl,['OK','cmd=STLS'],$cmdId); my $r_queuedMsgs=delete $self->{connQueues}{$hdl->{connIdx}}; if(defined $r_queuedMsgs) { if($#{$r_queuedMsgs} == 0) { $hdl->push_write(${$r_queuedMsgs->[0]}); }else{ my $queueBuffer; $queueBuffer.=$$_ for (@{$r_queuedMsgs}); $hdl->push_write($queueBuffer); } } return if($hdl->destroyed()); $hdl->starttls('accept',{cert => $self->{certPem}, key => $self->{privateKeyPem}}); return; # no induced traffic check (command can only be used once) } sub hRegister { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; my (undef,$userName,$password,$email)=@{$r_cmd}; $email//=''; return closeClientConnection($self,$hdl,'protocol error','cannot register while already logged in') if(exists $r_connInfo->{login}); return closeClientConnection($self,$hdl,'protocol error','invalid REGISTER parameter') unless( $userName =~ REGEX_USERNAME && length($password) < 50 && ($email eq '' || ($email =~ REGEX_EMAIL && length($email) < 255))); return closeClientConnection($self,$hdl,'protocol error','duplicate REGISTER command') if(exists $r_connInfo->{asyncRegistrationInProgress}); my $lcUserName=lc($userName); my $denyString = exists $self->{lcUsers}{$lcUserName} ? 'already in use.' : exists $self->{lcServerBots}{$lcUserName} ? 'reserved for internal use.' : undef; return sendClient($self,$hdl,['REGISTRATIONDENIED','Username is '.$denyString],$cmdId) if(defined $denyString); my $currentTime=$self->{netMsgRcvTime}; if(defined checkHostFlood($self,'Register',$r_connInfo->{host},$currentTime,CNT_CHECK_ONLY)) { sendClient($self,$hdl,['REGISTRATIONDENIED','Too many registrations from this host, please try again later'],$cmdId); return closeClientConnection($self,$hdl,'too many registrations from this host'); } if(defined $self->{registrationSvc}) { my $deniedReason=$self->{registrationSvc}($r_connInfo,$userName,$password,$email); return sendClient($self,$hdl,['REGISTRATIONDENIED',$deniedReason],$cmdId) if(defined $deniedReason); } if(defined $self->{registrationSvcAsync}) { $r_connInfo->{asyncRegistrationInProgress}=1; $self->{registrationSvcAsync}( sub { my $deniedReason=shift; if($hdl->destroyed()) { checkHostFlood($self,'Register',$r_connInfo->{host},$currentTime,CNT_INCR_ONLY) unless(defined $deniedReason); return; } delete $r_connInfo->{asyncRegistrationInProgress}; if(defined $deniedReason) { sendClient($self,$hdl,['REGISTRATIONDENIED',$deniedReason],$cmdId); }else{ checkHostFlood($self,'Register',$r_connInfo->{host},$currentTime,CNT_INCR_ONLY); sendClient($self,$hdl,['REGISTRATIONACCEPTED'],$cmdId); } }, $r_connInfo,$userName,$password,$email, ); }else{ checkHostFlood($self,'Register',$r_connInfo->{host},$currentTime,CNT_INCR_ONLY); sendClient($self,$hdl,['REGISTRATIONACCEPTED'],$cmdId); } } sub hLogin { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; return closeClientConnection($self,$hdl,'protocol error','duplicate LOGIN command') if(exists $r_connInfo->{login} || exists $r_connInfo->{asyncAuthentInProgress} || exists $r_connInfo->{pendingLoginData}); my (undef,$userName,$password,$cpu,$lanIpAddr,$lobbyClient,$hostHashes,$compFlags)=@{$r_cmd}; $compFlags//=''; my ($macAddressHash,$systemHash); return closeClientConnection($self,$hdl,'protocol error','invalid LOGIN parameter') unless( $userName =~ REGEX_USERNAME && length($password) < 50 && $cpu =~ /^\d{1,9}$/ && ($lanIpAddr eq '*' || $lanIpAddr =~ REGEX_IPV4) && length($lobbyClient) < 50 && $hostHashes =~ REGEX_HOSTHASHES && do {$macAddressHash=$1; $systemHash=$2; 1} && $compFlags =~ REGEX_COMPFLAGS); my $lcUserName=lc($userName); my $denyReason = exists $self->{lcUsers}{$lcUserName} ? 'Already logged in' : exists $self->{lcServerBots}{$lcUserName} ? 'Username reserved for internal use' : undef; if(defined $denyReason) { sendClient($self,$hdl,['DENIED',$denyReason],$cmdId); closeClientConnection($self,$hdl,'too many failed login attempts from this connection') if(++$r_connInfo->{nbDeniedLogin} >= $self->{maxConnFailedLogin} && $self->{maxConnFailedLogin}); return; } if(defined checkHostFlood($self,'FailedLogin',$r_connInfo->{host},$self->{netMsgRcvTime},CNT_CHECK_ONLY)) { sendClient($self,$hdl,['DENIED','Too many failed login attemps from this host, please try again later'],$cmdId); return closeClientConnection($self,$hdl,'too many failed login attempts from this host'); } my %compFlagsHash; map {$compFlagsHash{$_}=1} split(/ /,$compFlags); my $connIdx=$hdl->{connIdx}; my %userInfo=( country => $r_connInfo->{country}, connIdx => $connIdx, password => $password, cpu => $cpu, lanIpAddr => $lanIpAddr, lobbyClient => $lobbyClient, macAddressHash => $macAddressHash, systemHash => $systemHash, compFlags => \%compFlagsHash, channels => {}, battle => undef, status => { inGame => 0, rank => 0, away => 0, access => 0, bot => 0, }, accountId => 0, pendingAgreement => [], accessLevel => 1, inGameTime => 0, emailAddress => undef, registrationTs => undef, lastLoginTs => time, ignoredAccounts => {}, friendAccounts => {}, friendRequestsIn => {}, friendRequestsOut => {}, isLegacyClient => substr($lobbyClient,0,9) eq 'TASClient', inducedTrafficRateCounters => [undef,undef], dbCmdCounters => [undef,undef], loginTime => $self->{netMsgRcvTime}, ); if(defined $self->{authenticationSvc}) { my $deniedReason=$self->{authenticationSvc}($r_connInfo,$userName,$password,\%userInfo); if(defined $deniedReason) { checkHostFlood($self,'FailedLogin',$r_connInfo->{host},$self->{netMsgRcvTime},CNT_INCR_ONLY); sendClient($self,$hdl,['DENIED',$deniedReason],$cmdId); closeClientConnection($self,$hdl,'too many failed login attempts from this connection') if(++$r_connInfo->{nbDeniedLogin} >= $self->{maxConnFailedLogin} && $self->{maxConnFailedLogin}); return; } } if(defined $self->{authenticationSvcAsync}) { $r_connInfo->{asyncAuthentInProgress}=1; $self->{authenticationSvcAsync}( sub { return if($hdl->destroyed()); delete $r_connInfo->{asyncAuthentInProgress}; my $deniedReason=shift; if(defined $deniedReason) { checkHostFlood($self,'FailedLogin',$r_connInfo->{host},$userInfo{loginTime},CNT_INCR_ONLY); sendClient($self,$hdl,['DENIED',$deniedReason],$cmdId); closeClientConnection($self,$hdl,'too many failed login attempts from this connection') if(++$r_connInfo->{nbDeniedLogin} >= $self->{maxConnFailedLogin} && $self->{maxConnFailedLogin}); }elsif(@{$userInfo{pendingAgreement}}) { if(defined checkHostFlood($self,'FailedAgreement',$r_connInfo->{host},$userInfo{loginTime},CNT_CHECK_ONLY)) { sendClient($self,$hdl,['DENIED','Too many failed agreement confirmations from this host, please try again later'],$cmdId); return closeClientConnection($self,$hdl,'too many failed agreement confirmations from this host'); } delete $r_connInfo->{loginTimeout}; sendClientMultiByIdx($self,$connIdx,[(map {['AGREEMENT',$_]} @{$userInfo{pendingAgreement}}),['AGREEMENTEND']]); $userInfo{pendingAgreement}=[]; $r_connInfo->{pendingLoginData}={userName => $userName, userInfo => \%userInfo, lcUserName => $lcUserName}; }else{ delete $r_connInfo->{loginTimeout}; hLogin_allowed($self,$hdl,$r_connInfo,$userName,\%userInfo,$lcUserName,$cmdId,1); } }, $r_connInfo,$userName,$password,\%userInfo, ); }elsif(@{$userInfo{pendingAgreement}}) { if(defined checkHostFlood($self,'FailedAgreement',$r_connInfo->{host},$self->{netMsgRcvTime},CNT_CHECK_ONLY)) { sendClient($self,$hdl,['DENIED','Too many failed agreement confirmations from this host, please try again later'],$cmdId); return closeClientConnection($self,$hdl,'too many failed agreement confirmations from this host'); } delete $r_connInfo->{loginTimeout}; sendClientMultiByIdx($self,$connIdx,[(map {['AGREEMENT',$_]} @{$userInfo{pendingAgreement}}),['AGREEMENTEND']]); $userInfo{pendingAgreement}=[]; $r_connInfo->{pendingLoginData}={userName => $userName, userInfo => \%userInfo, lcUserName => $lcUserName}; }else{ delete $r_connInfo->{loginTimeout}; hLogin_allowed($self,$hdl,$r_connInfo,$userName,\%userInfo,$lcUserName,$cmdId); } } sub hConfirmAgreement { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; my $verificationCode=$r_cmd->[1]//''; return closeClientConnection($self,$hdl,'protocol error','unexpected CONFIRMAGREEMENT command') unless(exists $r_connInfo->{pendingLoginData}); return closeClientConnection($self,$hdl,'protocol error','invalid CONFIRMAGREEMENT parameter') unless($verificationCode =~ REGEX_VERIFICATIONCODE); my ($userName,$r_userInfo,$lcUserName)=@{$r_connInfo->{pendingLoginData}}{qw'userName userInfo lcUserName'}; my $currentTime=$self->{netMsgRcvTime}; if(defined $self->{registrationSvc}) { my $deniedReason=$self->{registrationSvc}($r_connInfo,$userName,$verificationCode); if(defined $deniedReason) { checkHostFlood($self,'FailedAgreement',$r_connInfo->{host},$currentTime,CNT_INCR_ONLY); sendClient($self,$hdl,['DENIED',$deniedReason],$cmdId); closeClientConnection($self,$hdl,'too many failed login attempts from this connection') if(++$r_connInfo->{nbDeniedLogin} >= $self->{maxConnFailedLogin} && $self->{maxConnFailedLogin}); return; } } if(defined $self->{registrationSvcAsync}) { $self->{registrationSvcAsync}( sub { return if($hdl->destroyed()); my $deniedReason=shift; if(defined $deniedReason) { checkHostFlood($self,'FailedAgreement',$r_connInfo->{host},$currentTime,CNT_INCR_ONLY); sendClient($self,$hdl,['DENIED',$deniedReason],$cmdId); closeClientConnection($self,$hdl,'too many failed login attempts from this connection') if(++$r_connInfo->{nbDeniedLogin} >= $self->{maxConnFailedLogin} && $self->{maxConnFailedLogin}); }else{ delete $r_connInfo->{pendingLoginData}; hLogin_allowed($self,$hdl,$r_connInfo,$userName,$r_userInfo,$lcUserName,$cmdId,1) unless($r_userInfo->{isLegacyClient}); } }, $r_connInfo,$userName,$verificationCode, ); }else{ delete $r_connInfo->{pendingLoginData}; hLogin_allowed($self,$hdl,$r_connInfo,$userName,$r_userInfo,$lcUserName,$cmdId,1) unless($r_userInfo->{isLegacyClient}); } } sub hLogin_allowed { my ($self,$hdl,$r_connInfo,$userName,$r_userInfo,$lcUserName,$cmdId,$recheckDuplicates)=@_; return if($hdl->destroyed()); delete $r_connInfo->{nbDeniedLogin}; if($recheckDuplicates) { my $deniedReason = exists $self->{lcUsers}{$lcUserName} ? 'Already logged in' : exists $self->{lcServerBots}{$lcUserName} ? 'Username reserved for internal use' : undef; if(defined $deniedReason) { sendClient($self,$hdl,['DENIED',$deniedReason],$cmdId); return closeClientConnection($self,$hdl,'login denied',$deniedReason); } } my $r_userStatus=$r_userInfo->{status}; $r_userStatus->{access}=1 if($self->{accessFlagLevel} && $r_userInfo->{accessLevel} >= $self->{accessFlagLevel}); my $host=$r_connInfo->{host}; if(exists $self->{authentConnByHost}{$host} && ! $r_userInfo->{bypassMaxClients} && ! $r_userStatus->{access} && ! $r_userStatus->{bot}) { my $nbHostClients=0; foreach my $connIdx (keys %{$self->{authentConnByHost}{$host}}) { my $connUser=$self->{connections}{$connIdx}{login}; # always defined for authenticated connections my $r_connUserInfo=$self->{users}{$connUser}; next if($r_connUserInfo->{bypassMaxClients}); my $r_connUserStatus=$r_connUserInfo->{status}; next if($r_connUserStatus->{access} || $r_connUserStatus->{bot}); $nbHostClients++; } if($self->{maxClientsByHost} && $nbHostClients >= $self->{maxClientsByHost}) { my $deniedReason='Too many simultaneous client connections originating from this host'; sendClient($self,$hdl,['DENIED',$deniedReason],$cmdId); return closeClientConnection($self,$hdl,'login denied',$deniedReason); } } if(defined checkAccountLoginFlood($self,$r_userInfo,$userName)) { my $deniedReason='Account login flood'; sendClient($self,$hdl,['DENIED',$deniedReason],$cmdId); return closeClientConnection($self,$hdl,'login denied',$deniedReason); } sendClient($self,$hdl,['ACCEPTED',$userName],$cmdId); my @legacyAddUserFields=(qw'country cpu'); push(@legacyAddUserFields,'accountId') unless($self->{serverMode} == SRV_MODE_LAN); broadcastLegacy($self,['ADDUSER',$userName,@{$r_userInfo}{qw'country accountId lobbyClient'}],['ADDUSER',$userName,@{$r_userInfo}{@legacyAddUserFields}]); $r_userInfo->{marshalledStatus}=marshallClientStatus($r_userStatus); broadcast($self,'CLIENTSTATUS',$userName,$r_userInfo->{marshalledStatus}) if($r_userInfo->{marshalledStatus}); $r_connInfo->{login}=$userName; $r_connInfo->{inputRateCounters}=[undef,undef]; # authenticated connections may use different check periods for input flood protection delete $self->{nbUnauthentByHost}{$host} unless(--$self->{nbUnauthentByHost}{$host} > 0); my $connIdx=$hdl->{connIdx}; $self->{authentConnByHost}{$host}{$connIdx}=1; $self->{users}{$userName}=$r_userInfo; my $accountId=$r_userInfo->{accountId}; $self->{accounts}{$accountId}=$userName if($accountId); $self->{lcUsers}{$lcUserName}=$userName; my @loginInfoCmds; push(@loginInfoCmds,['SERVERMSG',$SRVMSG_LOBBY_PROTOCOL_EXTENSIONS]) if(length($r_userInfo->{lobbyClient}) > 6 && substr($r_userInfo->{lobbyClient},0,7) eq 'SPADS v'); if(defined $self->{motd}) { my %motdPlaceholders=( USERNAME => $userName, CLIENTS => scalar keys %{$self->{connections}}, CHANNELS => scalar keys %{$self->{channels}}, BATTLES => scalar keys %{$self->{battles}}, UPTIME => secToTime(time-$self->{startTime}), ); my @motd=@{$self->{motd}}; foreach my $motdString (@motd) { map {$motdString =~ s/\{$_\}/$motdPlaceholders{$_}/g} (keys %motdPlaceholders); } push(@loginInfoCmds,(map {['MOTD',$_]} @motd)); } if($r_userInfo->{isLegacyClient}) { map {push(@loginInfoCmds,['ADDUSER',$_,@{$self->{serverBots}{$_}}{@legacyAddUserFields}])} (keys %{$self->{serverBots}}); map {push(@loginInfoCmds,['ADDUSER',$_,@{$self->{users}{$_}}{@legacyAddUserFields}])} (keys %{$self->{users}}); }else{ map {push(@loginInfoCmds,['ADDUSER',$_,@{$self->{serverBots}{$_}}{qw'country accountId lobbyClient'}])} (keys %{$self->{serverBots}}); map {push(@loginInfoCmds,['ADDUSER',$_,@{$self->{users}{$_}}{qw'country accountId lobbyClient'}])} (keys %{$self->{users}}); } my $r_funcGetBattleAddrForUser = $r_connInfo->{ipAddrType} == IP_ADDR_LOOPBACK ? \&getBattleAddrForLoopbackUser : $r_connInfo->{ipAddrType} == IP_ADDR_LAN ? \&getBattleAddrForLanUser : \&getBattleAddrForWanUser; my $selfWanIpAddr = (defined $self->{wanAddress} && $self->{wanAddress} ne '') ? $self->{wanAddress} : undef; foreach my $bId (keys %{$self->{battles}}) { my $r_b=$self->{battles}{$bId}; push(@loginInfoCmds,['BATTLEOPENED',$bId,@{$r_b}{qw'type natType founder'}, $r_funcGetBattleAddrForUser->($r_connInfo,@{$r_b}{qw'ipAddr ipAddrType lanIpAddr'},$selfWanIpAddr), @{$r_b}{qw'port maxPlayers'},$r_b->{password} eq '' ? 0 : 1, @{$r_b}{qw'rankLimit mapHash engineName engineVersion mapName title gameName'}, $r_userInfo->{compFlags}{u} ? '__battle__'.$bId : ()]); push(@loginInfoCmds,['UPDATEBATTLEINFO',$bId,@{$r_b}{qw'nbSpec locked mapHash mapName'}]); map {push(@loginInfoCmds,['JOINEDBATTLE',$bId,$_]) unless($_ eq $r_b->{founder})} (keys %{$r_b->{users}}); } map {push(@loginInfoCmds,['CLIENTSTATUS',$_,$self->{serverBots}{$_}{marshalledStatus}]) if($self->{serverBots}{$_}{marshalledStatus})} (keys %{$self->{serverBots}}); map {push(@loginInfoCmds,['CLIENTSTATUS',$_,$self->{users}{$_}{marshalledStatus}]) if($self->{users}{$_}{marshalledStatus})} (keys %{$self->{users}}); push(@loginInfoCmds,['LOGININFOEND']); sendClientMultiByIdx($self,$connIdx,\@loginInfoCmds); } sub secToTime { my $sec=shift; my @units=qw'year day hour minute second'; my @amounts=(gmtime $sec)[5,7,2,1,0]; $amounts[0]-=70; my @strings; for my $i (0..$#units) { if($amounts[$i] == 1) { push(@strings,"1 $units[$i]"); }elsif($amounts[$i] > 1) { push(@strings,"$amounts[$i] $units[$i]s"); } } @strings=("0 second") unless(@strings); return $strings[0] if($#strings == 0); my $endString=pop(@strings); my $startString=join(", ",@strings); return "$startString and $endString"; } sub hResetPasswordRequest { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; my $email=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid RESETPASSWORDREQUEST parameter') unless($email =~ REGEX_EMAIL && length($email) < 255); return closeClientConnection($self,$hdl,'protocol error','unexpected RESETPASSWORDREQUEST, already logged in') if(exists $r_connInfo->{login} || exists $r_connInfo->{pendingLoginData}); return sendClient($self,$hdl,['RESETPASSWORDREQUESTDENIED','Feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{RESETPASSWORDREQUEST}); $self->{accountManagementSvc}{RESETPASSWORDREQUEST}( sub { return if($hdl->destroyed()); my $deniedReason=shift; if(defined $deniedReason) { sendClient($self,$hdl,['RESETPASSWORDREQUESTDENIED',$deniedReason],$cmdId); }else{ sendClient($self,$hdl,['RESETPASSWORDREQUESTACCEPTED'],$cmdId); } }, $r_connInfo,$email, ); } sub hResetPassword { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; my (undef,$email,$verificationCode)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid RESETPASSWORD parameter') unless($email =~ REGEX_EMAIL && length($email) < 255 && $verificationCode =~ REGEX_VERIFICATIONCODE); return closeClientConnection($self,$hdl,'protocol error','unexpected RESETPASSWORD, already logged in') if(exists $r_connInfo->{login} || exists $r_connInfo->{pendingLoginData}); return sendClient($self,$hdl,['RESETPASSWORDDENIED','Feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{RESETPASSWORD}); $self->{accountManagementSvc}{RESETPASSWORD}( sub { return if($hdl->destroyed()); my $deniedReason=shift; if(defined $deniedReason) { sendClient($self,$hdl,['RESETPASSWORDDENIED',$deniedReason],$cmdId); }else{ sendClient($self,$hdl,['RESETPASSWORDACCEPTED'],$cmdId); } }, $r_connInfo,$email,$verificationCode, ); } sub hResendVerification { my ($self,$hdl,$r_connInfo,undef,undef,$r_cmd,$cmdId)=@_; my $email=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid RESENDVERIFICATION parameter') unless($email =~ REGEX_EMAIL && length($email) < 255); return closeClientConnection($self,$hdl,'protocol error','unexpected RESENDVERIFICATION, agreement already accepted') if(exists $r_connInfo->{login}); return closeClientConnection($self,$hdl,'protocol error','unexpected RESENDVERIFICATION, not logged in') unless(exists $r_connInfo->{pendingLoginData}); return sendClient($self,$hdl,['RESENDVERIFICATIONDENIED','Feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{RESENDVERIFICATION}); my ($login,$r_userInfo)=@{$r_connInfo->{pendingLoginData}}{qw'userName userInfo'}; $self->{accountManagementSvc}{RESENDVERIFICATION}( sub { return if($hdl->destroyed()); my $deniedReason=shift; if(defined $deniedReason) { sendClient($self,$hdl,['RESENDVERIFICATIONDENIED',$deniedReason],$cmdId); }else{ sendClient($self,$hdl,['RESENDVERIFICATIONACCEPTED'],$cmdId); } }, $r_connInfo,$login,$r_userInfo,$email, ); } sub hChangeEmailRequest { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $email=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid CHANGEEMAILREQUEST parameter') unless($email =~ REGEX_EMAIL && length($email) < 255); if(exists $r_connInfo->{pendingLoginData}) { ($login,$r_userInfo)=@{$r_connInfo->{pendingLoginData}}{qw'userName userInfo'}; }elsif(! defined $login) { return closeClientConnection($self,$hdl,'protocol error','unexpected CHANGEEMAILREQUEST, not logged in'); } return sendClient($self,$hdl,['CHANGEEMAILREQUESTDENIED','Feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{CHANGEEMAILREQUEST}); $self->{accountManagementSvc}{CHANGEEMAILREQUEST}( sub { return if($hdl->destroyed()); my $deniedReason=shift; sendClient($self,$hdl,defined $deniedReason ? ['CHANGEEMAILREQUESTDENIED',$deniedReason] : ['CHANGEEMAILREQUESTACCEPTED'],$cmdId); }, $r_connInfo,$login,$r_userInfo,$email, ); return; # no induced traffic check (command is already limited by maxDbCmdRate) } sub hChangeEmail { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$email,$verificationCode)=@{$r_cmd}; $verificationCode//=''; return closeClientConnection($self,$hdl,'protocol error','invalid CHANGEEMAIL parameter') unless($email =~ REGEX_EMAIL && length($email) < 255 && $verificationCode =~ REGEX_VERIFICATIONCODE); if(exists $r_connInfo->{pendingLoginData}) { ($login,$r_userInfo)=@{$r_connInfo->{pendingLoginData}}{qw'userName userInfo'}; }elsif(! defined $login) { return closeClientConnection($self,$hdl,'protocol error','unexpected CHANGEEMAIL, not logged in'); } return sendClient($self,$hdl,['CHANGEEMAILDENIED','Feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{CHANGEEMAIL}); $self->{accountManagementSvc}{CHANGEEMAIL}( sub { my ($deniedReason,$updatedAccountId)=@_; if(defined $deniedReason) { return if($hdl->destroyed()); sendClient($self,$hdl,['CHANGEEMAILDENIED',$deniedReason],$cmdId); }else{ # client may have disconnected, reconnected and even renamed during async processing... my (undef,$r_currentInfo)=getOnlineClientData($self,$updatedAccountId,$login); $r_currentInfo->{emailAddress}=$email if(defined $r_currentInfo); return if($hdl->destroyed()); sendClientMulti($self,$hdl,[['CHANGEEMAILACCEPTED'],['SERVERMSG','Your email address has been changed to '.$email]],$cmdId); } }, $r_connInfo,$login,$r_userInfo,$email,$verificationCode, ); return; # no induced traffic check (command is already limited by maxDbCmdRate) } sub hRenameAccount { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $userName=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid RENAMEACCOUNT parameter') unless($userName =~ REGEX_USERNAME); return sendClient($self,$hdl,['SERVERMSG','Cannot rename account, feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{RENAMEACCOUNT}); return sendClient($self,$hdl,['SERVERMSG','Failed to rename to '.$userName.': You already have that username.'],$cmdId) if($userName eq $login); my $lcUserName=lc($userName); my $denyReason = (exists $self->{lcUsers}{$lcUserName} && $lcUserName ne lc($login)) ? 'name is already taken by an online client' : exists $self->{lcServerBots}{$lcUserName} ? 'name is reserved for internal use' : undef; my $currentTime=$self->{netMsgRcvTime}; return sendClient($self,$hdl,['SERVERMSG','Rename denied: too many renames for this account'],$cmdId) if(defined checkAccountRenameFlood($self,$r_userInfo,$currentTime,CNT_CHECK_ONLY)); $self->{accountManagementSvc}{RENAMEACCOUNT}( sub { return if($hdl->destroyed()); my $failedReason=shift; if(defined $failedReason) { sendClient($self,$hdl,['SERVERMSG','Failed to rename to '.$userName.': '.$failedReason],$cmdId); }else{ checkAccountRenameFlood($self,$r_userInfo,$currentTime,CNT_INCR_ONLY); sendClient($self,$hdl,['SERVERMSG','Your account has been renamed to '.$userName.'. Reconnect with the new username (you will now be automatically disconnected).'],$cmdId); closeClientConnection($self,$hdl,'renaming'); } }, $r_connInfo,$login,$r_userInfo,$userName, ); return; # no induced traffic check (command is already limited by maxDbCmdRate) } sub hChangePassword { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$oldPassword,$newPassword)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid CHANGEPASSWORD parameter') unless(length($oldPassword) < 50 && length($newPassword) < 50); return sendClient($self,$hdl,['SERVERMSG','Cannot change password, feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{CHANGEPASSWORD}); return sendClient($self,$hdl,['SERVERMSG','Failed to change password: new password must be different to current password.'],$cmdId) if($oldPassword eq $newPassword); return sendClient($self,$hdl,['SERVERMSG','Failed to change password: invalid password.'],$cmdId) unless($oldPassword eq $r_userInfo->{password}); $self->{accountManagementSvc}{CHANGEPASSWORD}( sub { my ($failedReason,$updatedAccountId)=@_; if(defined $failedReason) { return if($hdl->destroyed()); sendClient($self,$hdl,['SERVERMSG','Failed to change password: '.$failedReason],$cmdId); }else{ # client may have disconnected, reconnected and even renamed during async processing... my (undef,$r_currentInfo)=getOnlineClientData($self,$updatedAccountId,$login); $r_currentInfo->{password}=$newPassword if(defined $r_currentInfo); return if($hdl->destroyed()); sendClient($self,$hdl,['SERVERMSG','Password changed successfully.'],$cmdId); } }, $r_connInfo,$login,$r_userInfo,$oldPassword,$newPassword, ); return; # no induced traffic check (command is already limited by maxDbCmdRate) } sub getOnlineClientName { my ($self,$accountId,$userName)=@_; return $self->{accounts}{$accountId} if($accountId); return $userName if(exists $self->{users}{$userName}); return undef; } sub getOnlineClientData { my ($self,$accountId,$userName)=@_; if($accountId) { my $onlineName=$self->{accounts}{$accountId}; return defined $onlineName ? ($onlineName,$self->{users}{$onlineName}) : (undef,undef); } # if server is not using account IDs we have to rely on $userName directly, hoping no race conditions occured during async processing... my $r_onlineInfo=$self->{users}{$userName}; return defined $r_onlineInfo ? ($userName,$r_onlineInfo) : (undef,undef); } sub hMyStatus { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $marshalledStatus=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid MYSTATUS parameter') unless($marshalledStatus =~ REGEX_INT32 && $marshalledStatus >= INT32_MIN && $marshalledStatus <= INT32_MAX); my $r_u=unmarshallClientStatus($marshalledStatus); return unless(any {$r_userInfo->{status}{$_} != $r_u->{$_}} (qw'inGame away')); my $gameDuration; if($r_u->{inGame} && ! $r_userInfo->{status}{inGame}) { $r_userInfo->{gameStartTimestamp}=time(); }elsif(! $r_u->{inGame} && $r_userInfo->{status}{inGame} && defined $r_userInfo->{gameStartTimestamp}) { $gameDuration = time() - delete $r_userInfo->{gameStartTimestamp}; $gameDuration=5400 if($gameDuration > 5400); $r_userInfo->{inGameTime}+=$gameDuration; } map {$r_userInfo->{status}{$_}=$r_u->{$_}} (qw'inGame away'); if($gameDuration) { $self->{onAdditionalInGameTime}($r_connInfo,$login,$r_userInfo,$gameDuration) if(defined $self->{onAdditionalInGameTime}); if(defined $self->{onAdditionalInGameTimeAsync}) { my $statusAlreadyBroadcasted; $self->{onAdditionalInGameTimeAsync}( sub { return if($hdl->destroyed() || ! shift); $r_userInfo->{marshalledStatus}=marshallClientStatus($r_userInfo->{status}); my @inducedTraffic=broadcast($self,'CLIENTSTATUS',$login,$r_userInfo->{marshalledStatus}); $statusAlreadyBroadcasted=1; closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$gameDuration, ); return if($statusAlreadyBroadcasted); } } $r_userInfo->{marshalledStatus}=marshallClientStatus($r_userInfo->{status}); return broadcast($self,'CLIENTSTATUS',$login,$r_userInfo->{marshalledStatus}); } sub hChannels { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my @channelCmds=map {['CHANNEL',$_,scalar(keys %{$self->{channels}{$_}}),exists $self->{channelTopics}{$_} ? $self->{channelTopics}{$_}{topic} : ()]} (keys %{$self->{channels}}); push(@channelCmds,['ENDOFCHANNELS']); return sendClientMulti($self,$hdl,\@channelCmds,$cmdId); } sub hJoin { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $chan=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid JOIN parameter') unless($chan =~ REGEX_CHANNEL); return if(exists $r_userInfo->{channels}{$chan}); return sendClient($self,$hdl,['JOINFAILED',$chan,'invalid channel name'],$cmdId) if(substr($chan,0,2) eq '__'); if(defined $self->{onChannelJoin}) { my $denyMsg=$self->{onChannelJoin}($r_connInfo,$login,$r_userInfo,$chan); return sendClient($self,$hdl,['JOINFAILED',$chan,$denyMsg],$cmdId) if(defined $denyMsg); } my @inducedTraffic=sendClient($self,$hdl,['JOIN',$chan],$cmdId); addInducedTraffic(\@inducedTraffic,broadcastChannel($self,$chan,'JOINED',$chan,$login)); $r_userInfo->{channels}{$chan}=1; $self->{channels}{$chan}{$login}=1; my @joinCmds; my ($topic,$topicAuthor) = exists $self->{channelTopics}{$chan} ? @{$self->{channelTopics}{$chan}}{qw'topic author'} : ('','<null>'); if($r_userInfo->{isLegacyClient}) { @joinCmds=(['CHANNELTOPIC',$chan,$topicAuthor,$self->{startTime}*1000,$topic]) unless($topic eq ''); }else{ @joinCmds=(['JOINED',$chan,$login],['CHANNELTOPIC',$chan,$topicAuthor,$topic]); } push(@joinCmds,['CLIENTS',$chan,join(' ',keys %{$self->{channelBots}{$chan}},keys %{$self->{channels}{$chan}})]); addInducedTraffic(\@inducedTraffic,sendClientMulti($self,$hdl,\@joinCmds)); return @inducedTraffic; } sub hLeave { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $chan=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid LEAVE parameter') unless($chan =~ REGEX_CHANNEL); return removeUserFromChannel($self,$login,$chan); } # $kickAuthor must be defined if and only if the user didn't request to leave the channel (to trigger FORCELEAVECHANNEL for legacy clients) # $kickAuthor can be set to "" to avoid the automatic "Kicked by ..." prefix sub removeUserFromChannel { my ($self,$removedUser,$chan,$reason,$kickAuthor)=@_; my $r_userInfo=$self->{users}{$removedUser}; return unless(defined $r_userInfo && exists $r_userInfo->{channels}{$chan}); my @inducedTraffic; my @leftCmd=('LEFT',$chan,$removedUser); if($r_userInfo->{isLegacyClient}) { if(defined $kickAuthor) { my @forceLeaveCmd=('FORCELEAVECHANNEL',$chan); if($kickAuthor eq '') { push(@forceLeaveCmd,'*server*'); if(defined $reason) { push(@forceLeaveCmd,$reason); push(@leftCmd,$reason); } }else{ push(@forceLeaveCmd,$kickAuthor); push(@leftCmd,'Kicked by '.$kickAuthor); if(defined $reason) { push(@forceLeaveCmd,$reason); $leftCmd[-1].=': '.$reason; } } @inducedTraffic=sendUser($self,$removedUser,\@forceLeaveCmd); }elsif(defined $reason) { push(@leftCmd,$reason); } delete $self->{channels}{$chan}{$removedUser}; addInducedTraffic(\@inducedTraffic,broadcastChannel($self,$chan,@leftCmd)); }else{ if(defined $kickAuthor && $kickAuthor ne '') { push(@leftCmd,'Kicked by '.$kickAuthor.(defined $reason ? ': '.$reason : '')); }elsif(defined $reason) { push(@leftCmd,$reason); } @inducedTraffic=broadcastChannel($self,$chan,@leftCmd); delete $self->{channels}{$chan}{$removedUser}; } delete $self->{channels}{$chan} unless(%{$self->{channels}{$chan}}); delete $r_userInfo->{channels}{$chan}; return @inducedTraffic; } sub hSay { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my ($cmd,$chan,$msg)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error',"invalid $cmd parameter") unless($chan =~ REGEX_CHANNEL && length($msg) <= $self->{maxChatMsgLength}); return hSayBattle($self,$hdl,$r_connInfo,$login,$r_userInfo,[$cmd eq 'SAY' ? 'SAYBATTLE' : 'SAYBATTLEEX',$msg],$cmdId) if($chan =~ /^__battle__(\d+)$/ && defined $r_userInfo->{battle} && $1 == $r_userInfo->{battle}); return sendClient($self,$hdl,['SERVERMSG',"Cannot send message to channel \"$chan\": not in channel!"],$cmdId) unless(exists $r_userInfo->{channels}{$chan}); my ($saidCmd,$isExMsg); if($cmd eq 'SAY') { ($saidCmd,$isExMsg)=('SAID',0); }else{ ($saidCmd,$isExMsg)=('SAIDEX',1); } if(defined $self->{onChannelMsg}) { my $denyMsg=$self->{onChannelMsg}($r_connInfo,$login,$r_userInfo,$chan,\$msg,$isExMsg); if(defined $denyMsg) { return if($denyMsg eq ''); return sendClient($self,$hdl,['SERVERMSG',"Failed to send message to channel \"$chan\": $denyMsg"],$cmdId); } } my @inducedTraffic=broadcastChannel($self,$chan,$saidCmd,$chan,$login,$msg); broadcastChannelMsgToSrvBots($self,$r_connInfo,$login,$r_userInfo,$chan,$msg,$isExMsg); return @inducedTraffic; } sub hSayPrivate { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my ($cmd,$recipient,$msg)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error',"invalid $cmd parameter") unless($recipient =~ REGEX_USERNAME && length($msg) <= $self->{maxChatMsgLength}); my $isExMsg = $cmd eq 'SAYPRIVATEEX'; if(exists $self->{users}{$recipient}) { my $r_recipientUserInfo=$self->{users}{$recipient}; if(defined $self->{onPrivateMsg}) { my $denyMsg=$self->{onPrivateMsg}($r_connInfo,$login,$r_userInfo,$recipient,$r_recipientUserInfo,\$msg,$isExMsg,0); if(defined $denyMsg) { return if($denyMsg eq ''); return sendClient($self,$hdl,['SERVERMSG',"Failed to send private message to $recipient: $denyMsg"],$cmdId); } } my @inducedTraffic=sendClient($self,$hdl,$r_cmd,$cmdId); my $accountId=$r_userInfo->{accountId}; addInducedTraffic(\@inducedTraffic,sendUser($self,$recipient,[$isExMsg ? 'SAIDPRIVATEEX' : 'SAIDPRIVATE',$login,$msg])) unless($accountId && exists $r_recipientUserInfo->{ignoredAccounts}{$accountId}); return @inducedTraffic; }elsif(exists $self->{serverBots}{$recipient}) { my @inducedTraffic=sendClient($self,$hdl,$r_cmd,$cmdId); sendPrivateMsgToSrvBot($self,$r_connInfo,$login,$r_userInfo,$recipient,$msg,$isExMsg); return @inducedTraffic; }else{ $self->{debug} && $self->{logger}("\"$login\" tried to send private message to offline client \"$recipient\"",5); return; } } sub hOpenBattle { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$type,$natType,$password,$port,$maxPlayers,$gameHash,$rankLimit,$mapHash,$engineName,$engineVersion,$mapName,$title,$gameName)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid OPENBATTLE parameter') unless( $type =~ REGEX_BOOL && $natType =~ REGEX_ENUM2 && length($password) < 50 && $port =~ REGEX_PORT && $maxPlayers =~ REGEX_MAXPLAYERS && $gameHash =~ REGEX_INT32 && $gameHash >= INT32_MIN && $gameHash <= INT32_MAX && $rankLimit =~ REGEX_RANK && $mapHash =~ REGEX_INT32 && $mapHash >= INT32_MIN && $mapHash <= INT32_MAX && length($engineName) && length($engineName) < 100 && length($engineVersion) && length($engineVersion) < 100 && length($mapName) && length($mapName) < 100 && length($title) && length($title) < 100 && length($gameName) && length($gameName) < 100); return sendClient($self,$hdl,['OPENBATTLEFAILED','already in a battle'],$cmdId) if(defined $r_userInfo->{battle}); $password='' if($password eq '*'); my $bId=$self->{nextBattleId}++; $r_userInfo->{battle}=$bId; map {$_+=0} ($gameHash,$mapHash); $self->{battles}{$bId}={ type => $type, natType => $natType, founder => $login, password => $password, ipAddr => $r_connInfo->{host}, ipAddrType => $r_connInfo->{ipAddrType}, lanIpAddr => $r_userInfo->{lanIpAddr}, port => $port, maxPlayers => $maxPlayers, gameHash => $gameHash, rankLimit => $rankLimit, mapHash => $mapHash, engineName => $engineName, engineVersion => $engineVersion, mapName => $mapName, title => $title, gameName => $gameName, nbSpec => 0, locked => 0, users => { $login => { battleStatus => { side => 0, sync => 0, bonus => 0, mode => 0, team => 0, id => 0, ready => 0, }, marshalledBattleStatus => 0, color => { red => 0, green => 0, blue => 0, }, marshalledColor => 0, }, }, bots => {}, disabledUnits => {}, startRects => {}, scriptTags => {}, }; my $r_funcGetBattleAddrForUser = $r_connInfo->{ipAddrType} == IP_ADDR_LOOPBACK ? \&getLoopbackBattleAddrForUser : $r_connInfo->{ipAddrType} == IP_ADDR_LAN ? \&getLanBattleAddrForUser : \&getWanBattleAddrForUser; my $hostLanIpAddr = $r_userInfo->{lanIpAddr} eq '*' ? undef : $r_userInfo->{lanIpAddr}; my $selfWanIpAddr = (defined $self->{wanAddress} && $self->{wanAddress} ne '') ? $self->{wanAddress} : undef; my $isPassworded = $password eq '' ? 0 : 1; my @inducedTraffic; map { addInducedTraffic( \@inducedTraffic, sendUser($self,$_,['BATTLEOPENED',$bId,$type,$natType,$login, $r_funcGetBattleAddrForUser->($self->{connections}{$self->{users}{$_}{connIdx}},$r_connInfo->{host},$hostLanIpAddr,$selfWanIpAddr), $port,$maxPlayers,$isPassworded,$rankLimit,$mapHash,$engineName,$engineVersion,$mapName,$title,$gameName, $self->{users}{$_}{compFlags}{u} ? '__battle__'.$bId : ()])) } (keys %{$self->{users}}); addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['OPENBATTLE',$bId],$cmdId)); my @openBattleResCmds; push(@openBattleResCmds,['JOINBATTLE',$bId,$gameHash,$r_userInfo->{compFlags}{u} ? '__battle__'.$bId : ()]) unless($r_userInfo->{isLegacyClient}); push(@openBattleResCmds,['REQUESTBATTLESTATUS']); addInducedTraffic(\@inducedTraffic,sendClientMulti($self,$hdl,\@openBattleResCmds)); return @inducedTraffic; } sub hJoinBattle { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$bId,$password,$scriptPassword)=@{$r_cmd}; $password='' unless(defined $password && $password ne '*'); $scriptPassword//=''; return closeClientConnection($self,$hdl,'protocol error','invalid JOINBATTLE parameter') unless( $bId =~ REGEX_BATTLEID && length($password) < 50 && $scriptPassword =~ REGEX_SCRIPTPASSWD); return sendClient($self,$hdl,['JOINBATTLEFAILED','invalid battle ID'],$cmdId) unless(exists $self->{battles}{$bId}); return sendClient($self,$hdl,['JOINBATTLEFAILED','battle is locked'],$cmdId) if($self->{battles}{$bId}{locked}); if($self->{battles}{$bId}{password} ne '') { return sendClient($self,$hdl,['JOINBATTLEFAILED','battle is password protected'],$cmdId) if($password eq ''); return sendClient($self,$hdl,['JOINBATTLEFAILED','invalid password'],$cmdId) if($password ne $self->{battles}{$bId}{password}); } return sendClient($self,$hdl,['JOINBATTLEFAILED','already in a battle'],$cmdId) if(defined $r_userInfo->{battle}); my $battleFounder=$self->{battles}{$bId}{founder}; if(defined $self->{onBattleJoin}) { my $denyMsg=$self->{onBattleJoin}($r_connInfo,$login,$r_userInfo,$battleFounder,$self->{users}{$battleFounder},$bId); return sendClient($self,$hdl,['JOINBATTLEFAILED',$denyMsg],$cmdId) if(defined $denyMsg); } $r_userInfo->{pendingBattleJoin}=[$bId,$scriptPassword]; return sendUser($self,$battleFounder,['JOINBATTLEREQUEST',$login,$r_connInfo->{host}]); } sub hJoinBattleAccept { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $joiningUser=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid JOINBATTLEACCEPT parameter') unless($joiningUser =~ REGEX_USERNAME); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login && exists $self->{users}{$joiningUser} && ! defined $self->{users}{$joiningUser}{battle}); my $r_joiningUserInfo=$self->{users}{$joiningUser}; my $r_pendingJoinData=$r_joiningUserInfo->{pendingBattleJoin}; return unless(defined $r_pendingJoinData && $r_pendingJoinData->[0] eq $bId); my $joiningUserConnIdx=$r_joiningUserInfo->{connIdx}; my @inducedTraffic=sendClientMultiByIdx($self,$joiningUserConnIdx,[ ['JOINBATTLE',$bId,$r_b->{gameHash},$r_joiningUserInfo->{compFlags}{u} ? '__battle__'.$bId : ()], ['JOINEDBATTLE',$bId,$joiningUser,$r_pendingJoinData->[1]] ]); addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['JOINEDBATTLE',$bId,$joiningUser,$r_pendingJoinData->[1]],$cmdId)); map {addInducedTraffic(\@inducedTraffic,sendUser($self,$_,['JOINEDBATTLE',$bId,$joiningUser])) unless($_ eq $login || $_ eq $joiningUser)} (keys %{$self->{users}}); delete $r_joiningUserInfo->{pendingBattleJoin}; $r_joiningUserInfo->{battle}=$bId; $r_b->{users}{$joiningUser} = { battleStatus => { side => 0, sync => 0, bonus => 0, mode => 0, team => 0, id => 0, ready => 0, }, marshalledBattleStatus => 0, color => { red => 0, green => 0, blue => 0, }, marshalledColor => 0, }; my @joinResCmds=(['SETSCRIPTTAGS',map {$_.'='.$r_b->{scriptTags}{$_}} (keys %{$r_b->{scriptTags}})]); push(@joinResCmds,['DISABLEDUNITS',keys %{$r_b->{disabledUnits}}]) if(%{$r_b->{disabledUnits}}); map { push(@joinResCmds,['CLIENTBATTLESTATUS',$_,$r_b->{users}{$_}{marshalledBattleStatus},$r_b->{users}{$_}{marshalledColor}]) if($r_b->{users}{$_}{marshalledBattleStatus} || $r_b->{users}{$_}{marshalledColor}) } (keys %{$r_b->{users}}); map {push(@joinResCmds,['ADDBOT',$bId,$_,$r_b->{bots}{$_}{owner},$r_b->{bots}{$_}{marshalledBattleStatus},$r_b->{bots}{$_}{marshalledColor},$r_b->{bots}{$_}{aiDll}])} (keys %{$r_b->{bots}}); map {push(@joinResCmds,['ADDSTARTRECT',$_,@{$r_b->{startRects}{$_}}{qw'left top right bottom'}])} (sort {$a <=> $b} keys %{$r_b->{startRects}}); push(@joinResCmds,['REQUESTBATTLESTATUS']); addInducedTraffic(\@inducedTraffic,sendClientMultiByIdx($self,$joiningUserConnIdx,\@joinResCmds)); closeClientConnection($self,$self->{connections}{$joiningUserConnIdx}{hdl},'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_joiningUserInfo,@inducedTraffic)); return; } sub hJoinBattleDeny { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$joiningUser,$reason)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid JOINBATTLEDENY parameter') unless($joiningUser =~ REGEX_USERNAME); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login); my $r_joiningUserInfo=$self->{users}{$joiningUser}; return unless(defined $r_joiningUserInfo && ! defined $r_joiningUserInfo->{battle}); my $r_pendingJoinData=$r_joiningUserInfo->{pendingBattleJoin}; return unless(defined $r_pendingJoinData && $r_pendingJoinData->[0] eq $bId); delete $r_joiningUserInfo->{pendingBattleJoin}; my $joiningUserConnIdx=$r_joiningUserInfo->{connIdx}; $reason='access denied by host'.(defined $reason ? ' - '.$reason : ''); my @inducedTraffic=sendClientByIdx($self,$joiningUserConnIdx,['JOINBATTLEFAILED',$reason]); closeClientConnection($self,$self->{connections}{$joiningUserConnIdx}{hdl},'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_joiningUserInfo,@inducedTraffic)); return; } sub hLeaveBattle { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $bId=$r_userInfo->{battle}; return unless(defined $bId); return removeUserFromBattle($self,$login,$bId); } sub hKickFromBattle { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $kickedUser=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid KICKFROMBATTLE parameter') unless($kickedUser =~ REGEX_USERNAME); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login && exists $r_b->{users}{$kickedUser}); my @inducedTraffic=sendUser($self,$kickedUser,['FORCEQUITBATTLE']); addInducedTraffic(\@inducedTraffic,removeUserFromBattle($self,$kickedUser,$bId)); return @inducedTraffic; } sub removeUserFromBattle { my ($self,$user,$bId)=@_; my $r_b=$self->{battles}{$bId}; if($user eq $r_b->{founder}) { map {undef $self->{users}{$_}{battle}} (keys %{$r_b->{users}}); delete $self->{battles}{$bId}; return broadcast($self,'BATTLECLOSED',$bId); }else{ undef $self->{users}{$user}{battle}; delete $r_b->{users}{$user}; my @inducedTraffic; map {delete $r_b->{bots}{$_}; addInducedTraffic(\@inducedTraffic,broadcastBattle($self,$bId,'REMOVEBOT',$bId,$_))} (grep {$r_b->{bots}{$_}{owner} eq $user} (keys %{$r_b->{bots}})); addInducedTraffic(\@inducedTraffic,broadcast($self,'LEFTBATTLE',$bId,$user)); return @inducedTraffic; } } sub hMyBattleStatus { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$marshalledBattleStatus,$marshalledColor)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid MYBATTLESTATUS parameter') unless(all {$_ =~ REGEX_INT32 && $_ >= INT32_MIN && $_ <= INT32_MAX} ($marshalledBattleStatus,$marshalledColor)); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; my $r_bu=$r_b->{users}{$login}; my $r_bs=unmarshallBattleStatus($marshalledBattleStatus); $r_bs->{mode}=0 if($r_bs->{mode} && ! $r_bu->{battleStatus}{mode} && scalar(grep {$r_b->{users}{$_}{battleStatus}{mode}} (keys %{$r_b->{users}})) >= $r_b->{maxPlayers}); my $commandIsEffective; if(any {$_ ne 'bonus' && $r_bs->{$_} != $r_bu->{battleStatus}{$_}} (keys %{$r_bs})) { $commandIsEffective=1; $r_bs->{bonus}=$r_bu->{battleStatus}{bonus}; $r_bu->{battleStatus}=$r_bs; $r_bu->{marshalledBattleStatus}=marshallBattleStatus($r_bs); # always remarshall to enforce unused bits = 0 } my $r_c=unmarshallColor($marshalledColor); if(any {$r_c->{$_} != $r_bu->{color}{$_}} (keys %{$r_c})) { $commandIsEffective=1; $r_bu->{color}=$r_c; $r_bu->{marshalledColor}=marshallColor($r_c); # always remarshall to enforce unused bits = 0 } return broadcastBattle($self,$bId,'CLIENTBATTLESTATUS',$login,$r_bu->{marshalledBattleStatus},$r_bu->{marshalledColor}) if($commandIsEffective); return; } sub hAddBot { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$botName,$marshalledBattleStatus,$marshalledColor,$aiDll)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid ADDBOT parameter') unless($botName =~ REGEX_USERNAME && (all {$_ =~ REGEX_INT32 && $_ >= INT32_MIN && $_ <= INT32_MAX} ($marshalledBattleStatus,$marshalledColor)) && length($aiDll) && length($aiDll) < 50); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return if(exists $r_b->{bots}{$botName}); my $r_bs=unmarshallBattleStatus($marshalledBattleStatus); my $r_c=unmarshallColor($marshalledColor); $r_b->{bots}{$botName}={ owner => $login, battleStatus => $r_bs, marshalledBattleStatus => marshallBattleStatus($r_bs), color => $r_c, marshalledColor => marshallColor($r_c), aiDll => $aiDll, }; return broadcastBattle($self,$bId,'ADDBOT',$bId,$botName,$login,$r_b->{bots}{$botName}{marshalledBattleStatus},$r_b->{bots}{$botName}{marshalledColor},$aiDll); } sub hRemoveBot { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $botName=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid REMOVEBOT parameter') unless($botName =~ REGEX_USERNAME); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless(exists $r_b->{bots}{$botName} && $r_b->{bots}{$botName}{owner} eq $login || $r_b->{founder} eq $login); delete $r_b->{bots}{$botName}; return broadcastBattle($self,$bId,'REMOVEBOT',$bId,$botName); } sub hUpdateBot { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$botName,$marshalledBattleStatus,$marshalledColor)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid UPDATEBOT parameter') unless($botName =~ REGEX_USERNAME && (all {$_ =~ REGEX_INT32 && $_ >= INT32_MIN && $_ <= INT32_MAX} ($marshalledBattleStatus,$marshalledColor))); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_bb=$self->{battles}{$bId}{bots}{$botName}; return unless(defined $r_bb && $r_bb->{owner} eq $login || $self->{battles}{$bId}{founder} eq $login); my $r_bs=unmarshallBattleStatus($marshalledBattleStatus); my $commandIsEffective; if(any {$r_bs->{$_} != $r_bb->{battleStatus}{$_}} (keys %{$r_bs})) { $commandIsEffective=1; $r_bb->{battleStatus}=$r_bs; $r_bb->{marshalledBattleStatus}=marshallBattleStatus($r_bs); # always remarshall to enforce unused bits = 0 } my $r_c=unmarshallColor($marshalledColor); if(any {$r_c->{$_} != $r_bb->{color}{$_}} (keys %{$r_c})) { $commandIsEffective=1; $r_bb->{color}=$r_c; $r_bb->{marshalledColor}=marshallColor($r_c); # always remarshall to enforce unused bits = 0 } return broadcastBattle($self,$bId,'UPDATEBOT',$bId,$botName,$r_bb->{marshalledBattleStatus},$r_bb->{marshalledColor}) if($commandIsEffective); return; } sub hForceSpectatorMode { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $forcedUser=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid FORCESPECTATORMODE parameter') unless($forcedUser =~ REGEX_USERNAME); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; my $r_bu=$r_b->{users}{$forcedUser}; return unless($r_b->{founder} eq $login && defined $r_bu && $r_bu->{battleStatus}{mode}); $r_bu->{battleStatus}{mode}=0; $r_bu->{marshalledBattleStatus}=marshallBattleStatus($r_bu->{battleStatus}); return broadcastBattle($self,$bId,'CLIENTBATTLESTATUS',$forcedUser,$r_bu->{marshalledBattleStatus},$r_bu->{marshalledColor}); } sub hForceTeamNo { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$forcedUser,$teamNb)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid FORCETEAMNO parameter') unless($forcedUser =~ REGEX_USERNAME && $teamNb =~ REGEX_TEAMID); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; my $r_bu=$r_b->{users}{$forcedUser}; return unless($r_b->{founder} eq $login && defined $r_bu && $r_bu->{battleStatus}{id} != $teamNb); $r_bu->{battleStatus}{id}=$teamNb; $r_bu->{marshalledBattleStatus}=marshallBattleStatus($r_bu->{battleStatus}); return broadcastBattle($self,$bId,'CLIENTBATTLESTATUS',$forcedUser,$r_bu->{marshalledBattleStatus},$r_bu->{marshalledColor}); } sub hForceAllyNo { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$forcedUser,$teamNb)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid FORCEALLYNO parameter') unless($forcedUser =~ REGEX_USERNAME && $teamNb =~ REGEX_TEAMID); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; my $r_bu=$r_b->{users}{$forcedUser}; return unless($r_b->{founder} eq $login && defined $r_bu && $r_bu->{battleStatus}{team} != $teamNb); $r_bu->{battleStatus}{team}=$teamNb; $r_bu->{marshalledBattleStatus}=marshallBattleStatus($r_bu->{battleStatus}); return broadcastBattle($self,$bId,'CLIENTBATTLESTATUS',$forcedUser,$r_bu->{marshalledBattleStatus},$r_bu->{marshalledColor}); } sub hHandicap { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$forcedUser,$bonus)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid HANDICAP parameter') unless($forcedUser =~ REGEX_USERNAME && $bonus =~ REGEX_TEAMID); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; my $r_bu=$r_b->{users}{$forcedUser}; return unless($r_b->{founder} eq $login && defined $r_bu && $r_bu->{battleStatus}{bonus} != $bonus); $r_bu->{battleStatus}{bonus}=$bonus; $r_bu->{marshalledBattleStatus}=marshallBattleStatus($r_bu->{battleStatus}); return broadcastBattle($self,$bId,'CLIENTBATTLESTATUS',$forcedUser,$r_bu->{marshalledBattleStatus},$r_bu->{marshalledColor}); } sub hForceTeamColor { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$forcedUser,$marshalledColor)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid FORCETEAMCOLOR parameter') unless($forcedUser =~ REGEX_USERNAME && $marshalledColor =~ REGEX_INT32 && $marshalledColor >= INT32_MIN && $marshalledColor <= INT32_MAX); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; my $r_bu=$r_b->{users}{$forcedUser}; return unless($r_b->{founder} eq $login && defined $r_bu); my $r_c=unmarshallColor($marshalledColor); if(any {$r_c->{$_} != $r_bu->{color}{$_}} (keys %{$r_c})) { $r_bu->{color}=$r_c; $r_bu->{marshalledColor}=marshallColor($r_c); # always remarshall to enforce unused bits = 0 return broadcastBattle($self,$bId,'CLIENTBATTLESTATUS',$forcedUser,$r_bu->{marshalledBattleStatus},$r_bu->{marshalledColor}); } return; } sub hSetScriptTags { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@scriptTagDefs)=@{$r_cmd}; pop(@scriptTagDefs) if(@scriptTagDefs && $scriptTagDefs[-1] eq ''); # springlobby sometimes puts an empty string at the end... my %scriptTags; foreach my $scriptTagDef (@scriptTagDefs) { if($scriptTagDef =~ REGEX_SCRIPTTAGDEF) { $scriptTags{lc($1)}=$2; }else{ return closeClientConnection($self,$hdl,'protocol error','invalid SETSCRIPTTAGS parameter'); } } my $bId=$r_userInfo->{battle}; return unless(defined $bId && $self->{battles}{$bId}{founder} eq $login); my $r_battleScriptTags=$self->{battles}{$bId}{scriptTags}; my @changedScriptTags; my $nbNewScriptTags; foreach my $scriptTag (keys %scriptTags) { if(exists $r_battleScriptTags->{$scriptTag}) { push(@changedScriptTags,$scriptTag) if($r_battleScriptTags->{$scriptTag} ne $scriptTags{$scriptTag}); }else{ push(@changedScriptTags,$scriptTag); $nbNewScriptTags++; } } return unless(@changedScriptTags); return closeClientConnection($self,$hdl,'too many script tags in battle') if($nbNewScriptTags && keys(%{$r_battleScriptTags}) + $nbNewScriptTags > $self->{maxBattleScriptTags}); map {$r_battleScriptTags->{$_}=$scriptTags{$_}} @changedScriptTags; return broadcastBattle($self,$bId,'SETSCRIPTTAGS',map {$_.'='.$scriptTags{$_}} @changedScriptTags); } sub hRemoveSCriptTags { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@scriptTags)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid REMOVESCRIPTTAGS parameter') unless(all {$_ =~ REGEX_SCRIPTTAG} @scriptTags); my $bId=$r_userInfo->{battle}; return unless(defined $bId && $self->{battles}{$bId}{founder} eq $login); my @scriptTagsToDelete=grep {exists $self->{battles}{$bId}{scriptTags}{$_}} @scriptTags; return unless(@scriptTagsToDelete); delete @{$self->{battles}{$bId}{scriptTags}}{@scriptTagsToDelete}; return broadcastBattle($self,$bId,'REMOVESCRIPTTAGS',@scriptTagsToDelete); } sub hDisableUnits { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@units)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid DISABLEUNITS parameter') unless(all {$_ =~ REGEX_UNIT} @units); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login); my @unitsToDisable=grep {! exists $r_b->{disabledUnits}{$_}} @units; return unless(@unitsToDisable); map {$r_b->{disabledUnits}{$_}=1} @unitsToDisable; return broadcastBattle($self,$bId,'DISABLEUNITS',@unitsToDisable); } sub hEnableUnits { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@units)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid ENABLEUNITS parameter') unless(all {$_ =~ REGEX_UNIT} @units); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login); my @unitsToEnable=grep {exists $r_b->{disabledUnits}{$_}} @units; return unless(@unitsToEnable); map {delete $r_b->{disabledUnits}{$_}} @unitsToEnable; return broadcastBattle($self,$bId,'ENABLEUNITS',@unitsToEnable); } sub hEnableAllUnits { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login && %{$r_b->{disabledUnits}}); $r_b->{disabledUnits}={}; return broadcastBattle($self,$bId,'ENABLEALLUNITS'); } sub hUpdateBattleInfo { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$nbSpec,$locked,$mapHash,$mapName)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid UPDATEBATTLEINFO parameter') unless($nbSpec =~ REGEX_NBSPEC && $locked =~ REGEX_BOOL && $mapHash =~ REGEX_INT32 && $mapHash >= INT32_MIN && $mapHash <= INT32_MAX && length($mapName) && length($mapName) < 100); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login); return if($r_b->{nbSpec} == $nbSpec && $r_b->{locked} == $locked && $r_b->{mapHash} == $mapHash && $r_b->{mapName} eq $mapName); $mapHash+=0; $r_b->{nbSpec}=$nbSpec; $r_b->{locked}=$locked; $r_b->{mapHash}=$mapHash; $r_b->{mapName}=$mapName; return broadcast($self,'UPDATEBATTLEINFO',$bId,$nbSpec,$locked,$mapHash,$mapName); } sub hAddStartRect { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$team,$left,$top,$right,$bottom)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid ADDSTARTRECT parameter') unless($team =~ REGEX_TEAMID && (all {$_ =~ REGEX_STARTRECT} ($left,$top,$right,$bottom))); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login); return if(exists $r_b->{startRects}{$team} && $r_b->{startRects}{$team}{left} == $left && $r_b->{startRects}{$team}{top} == $top && $r_b->{startRects}{$team}{right} == $right && $r_b->{startRects}{$team}{bottom} == $bottom); $r_b->{startRects}{$team}={left => $left, top => $top, right => $right, bottom => $bottom}; return broadcastBattle($self,$bId,'ADDSTARTRECT',$team,$left,$top,$right,$bottom); } sub hRemoveStartRect { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $team=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error','invalid REMOVESTARTRECT parameter') unless($team =~ REGEX_TEAMID); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login && exists $r_b->{startRects}{$team}); delete $r_b->{startRects}{$team}; return broadcastBattle($self,$bId,'REMOVESTARTRECT',$team); } sub hSayBattle { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my ($cmd,$msg)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error',"invalid $cmd parameter") unless(length($msg) <= $self->{maxChatMsgLength}); my $bId=$r_userInfo->{battle}; return sendClient($self,$hdl,['SERVERMSG','Cannot send message in battle lobby: not in a battle!'],$cmdId) unless(defined $bId); my $battleFounder=$self->{battles}{$bId}{founder}; my $isExMsg = $cmd eq 'SAYBATTLEEX'; if(defined $self->{onBattleMsg}) { my $denyMsg=$self->{onBattleMsg}($r_connInfo,$login,$r_userInfo,$battleFounder,$self->{users}{$battleFounder},$bId,\$msg,$isExMsg); if(defined $denyMsg) { return sendClient($self,$hdl,['SERVERMSG',"Failed to send message in battle lobby: $denyMsg"],$cmdId) unless($denyMsg eq ''); return; } } return broadcastBattleUFlag($self,$bId,[$isExMsg ? 'SAIDEX' : 'SAID','__battle__'.$bId,$login,$msg],[$isExMsg ? 'SAIDBATTLEEX' : 'SAIDBATTLE',$login,$msg]); } sub hSayBattlePrivate { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my ($cmd,$recipientsStr,$msg)=@{$r_cmd}; my @recipients=split(',',$recipientsStr); return closeClientConnection($self,$hdl,'protocol error',"invalid $cmd parameter") unless((all {$_ =~ REGEX_USERNAME} @recipients) && length($msg) <= $self->{maxChatMsgLength}); my $bId=$r_userInfo->{battle}; return sendClient($self,$hdl,['SERVERMSG',"Cannot send private message to $recipientsStr in battle lobby: not in a battle!"],$cmdId) unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login); @recipients=grep {exists $r_b->{users}{$_}} @recipients; return unless(@recipients); my $isExMsg = $cmd eq 'SAYBATTLEPRIVATEEX'; my @inducedTraffic; foreach my $recipient (@recipients) { if(defined $self->{onPrivateMsg}) { my $denyMsg=$self->{onPrivateMsg}($r_connInfo,$login,$r_userInfo,$recipient,$self->{users}{$recipient},\$msg,$isExMsg,1); if(defined $denyMsg) { addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['SERVERMSG',"Failed to send private message to $recipient in battle lobby: $denyMsg"],$cmdId)) unless($denyMsg eq ''); next; } } if($self->{users}{$recipient}{compFlags}{u}) { addInducedTraffic(\@inducedTraffic,sendUser($self,$recipient,[$isExMsg ? 'SAIDEX' : 'SAID','__battle__'.$bId,$login,$msg])); }else{ addInducedTraffic(\@inducedTraffic,sendUser($self,$recipient,[$isExMsg ? 'SAIDBATTLEEX' : 'SAIDBATTLE',$login,$msg])); } } return @inducedTraffic; } sub hRing { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $recipient=$r_cmd->[1]; return closeClientConnection($self,$hdl,'protocol error',"invalid RING parameter") unless($recipient =~ REGEX_USERNAME); my $bId=$r_userInfo->{battle}; return unless(defined $bId); my $r_b=$self->{battles}{$bId}; return unless($r_b->{founder} eq $login && exists $r_b->{users}{$recipient}); my $accountId=$r_userInfo->{accountId}; return if($accountId && exists $self->{users}{$recipient}{ignoredAccounts}{$accountId}); return sendUser($self,$recipient,['RING',$login]); } sub hGetUserInfo { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $userName=$r_cmd->[1]; if(defined $userName && $userName ne $login) { return sendClient($self,$hdl,['SERVERMSG','Your are not allowed to retrieve user information of other accounts']) unless($r_userInfo->{status}{access}); return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid GETUSERINFO parameter'],$cmdId) unless($userName =~ REGEX_USERNAME); my $r_onlineUserInfo=$self->{users}{$userName}; if(defined $r_onlineUserInfo) { return sendUserInfoAsServerMsg($self,$hdl,$userName,$r_onlineUserInfo,$cmdId,1); }elsif(exists $self->{accountManagementSvc}{GETUSERINFO}) { $self->{accountManagementSvc}{GETUSERINFO}( sub { return if($hdl->destroyed()); my ($failedReason,$r_offlineUserInfo)=@_; if(defined $failedReason) { sendClient($self,$hdl,['SERVERMSG','Failed to retrieve user information for '.$userName.': '.$failedReason],$cmdId); }else{ sendUserInfoAsServerMsg($self,$hdl,$userName,$r_offlineUserInfo,$cmdId,1); } }, $r_connInfo,$login,$r_userInfo,$userName, ); return; }else{ return sendClient($self,$hdl,['SERVERMSG','Cannot retrieve user information of offline user, feature is not supported by this server'],$cmdId); } }else{ return sendUserInfoAsServerMsg($self,$hdl,$login,$r_userInfo,$cmdId,$r_userInfo->{status}{access}); } } sub sendUserInfoAsServerMsg { my ($self,$hdl,$userName,$r_userInfo,$cmdId,$fullAccess)=@_; my $userIsOnline; my @userInfoMsgs; if($fullAccess) { $userIsOnline=exists $r_userInfo->{connIdx}; push(@userInfoMsgs,$userName.' is '.($userIsOnline ? 'online' : 'offline')); my $accountId=$r_userInfo->{accountId}; push(@userInfoMsgs,'Account ID: '.$accountId) if($accountId); } push(@userInfoMsgs,'Registration date: '.timestampToGmTime($r_userInfo->{registrationTs})) if(defined $r_userInfo->{registrationTs}); push(@userInfoMsgs,'Email address: '.$r_userInfo->{emailAddress}) if(defined $r_userInfo->{emailAddress}); push(@userInfoMsgs,'Ingame time: '.secToTime($r_userInfo->{inGameTime})) if(defined $r_userInfo->{inGameTime}); if($fullAccess) { push(@userInfoMsgs,'Last login: '.timestampToGmTime($r_userInfo->{lastLoginTs})) if(defined $r_userInfo->{lastLoginTs}); push(@userInfoMsgs,'Lobby client: '.$r_userInfo->{lobbyClient}) if(defined $r_userInfo->{lobbyClient}); push(@userInfoMsgs,'MAC address hash: '.$r_userInfo->{macAddressHash}) if(defined $r_userInfo->{macAddressHash}); push(@userInfoMsgs,'System hash: '.$r_userInfo->{systemHash}) if(defined $r_userInfo->{systemHash}); push(@userInfoMsgs,'Access level: '.$r_userInfo->{accessLevel}) if(defined $r_userInfo->{accessLevel}); push(@userInfoMsgs,'Country: '.$r_userInfo->{country}) if(defined $r_userInfo->{country}); if($userIsOnline) { my $r_connInfo=$self->{connections}{$r_userInfo->{connIdx}}; push(@userInfoMsgs,'Connection time: '.secToTime(time-$r_connInfo->{connectTime})); push(@userInfoMsgs,'Lobby status: '.join(', ',map {$_.':'.$r_userInfo->{status}{$_}} (sort keys %{$r_userInfo->{status}}))); push(@userInfoMsgs,'IP address: '.$r_connInfo->{host}); }else{ push(@userInfoMsgs,'Last IP address: '.$r_userInfo->{lastIpAddr}) if(defined $r_userInfo->{lastIpAddr}); } } return sendClientMulti($self,$hdl,[map {['SERVERMSG',$_]} @userInfoMsgs],$cmdId); } sub timestampToGmTime { my @gmtime=gmtime(shift); $gmtime[4]++; @gmtime = map {sprintf('%02d',$_)} @gmtime; return ($gmtime[5]+1900).'-'.$gmtime[4].'-'.$gmtime[3].' '.$gmtime[2].':'.$gmtime[1].':'.$gmtime[0].' GMT'; } sub hForceLeaveChannel { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$chan,$kickedUser,$reason)=@{$r_cmd}; undef $reason if(defined $reason && $reason eq ''); return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid FORCELEAVECHANNEL parameter'],$cmdId) unless($chan =~ REGEX_CHANNEL && $kickedUser =~ REGEX_USERNAME && (! defined $reason || length($reason) < 255)); return removeUserFromChannel($self,$kickedUser,$chan,$reason,$login); } sub hKick { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$kickedUser,$reason)=@{$r_cmd}; undef $reason if(defined $reason && $reason eq ''); return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid KICK parameter'],$cmdId) unless($kickedUser =~ REGEX_USERNAME && (! defined $reason || length($reason) < 255)); return sendClient($self,$hdl,['SERVERMSG','Cannot kick '.$kickedUser.', user not found online'],$cmdId) unless(exists $self->{users}{$kickedUser}); my @inducedTraffic=kickUserFromServer($self,$kickedUser,$login,$reason); addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['SERVERMSG','Kicked '.$kickedUser.' from the server'],$cmdId)); return @inducedTraffic; } sub kickUserFromServer { my ($self,$kickedUser,$login,$reason,$isBanned)=@_; my $kickedOrBanned=$isBanned?'banned':'kicked'; my $r_kickedUserInfo=$self->{users}{$kickedUser}; my $bId=$r_kickedUserInfo->{battle}; my @inducedTraffic; @inducedTraffic=sendUser($self,$self->{battles}{$bId}{founder},['KICKFROMBATTLE',$bId,$kickedUser]) if(defined $bId); addInducedTraffic(\@inducedTraffic,sendUser($self,$kickedUser,['SERVERMSGBOX','You were '.$kickedOrBanned.' from the server by '.$login.(defined $reason ? " ($reason)" : '')])); closeClientConnection($self,$self->{connections}{$r_kickedUserInfo->{connIdx}}{hdl},$kickedOrBanned.' from server by '.$login,$reason); return @inducedTraffic; } sub hSetBotMode { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$botName,$botMode)=@{$r_cmd}; return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid SETBOTMODE parameter (botName)'],$cmdId) unless($botName =~ REGEX_USERNAME); my $lcBotMode=lc($botMode); if(any {$lcBotMode eq $_} (qw'0 false no disabled')) { $botMode=0; }elsif(any {$lcBotMode eq $_} (qw'1 true yes enabled')) { $botMode=1; }else{ return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid SETBOTMODE parameter (botMode)'],$cmdId); } my $r_botInfo=$self->{users}{$botName}; return sendClient($self,$hdl,['SERVERMSG','Failed to set bot mode for '.$botName.': bot mode is already set to '.$botMode],$cmdId) if(defined $r_botInfo && $r_botInfo->{status}{bot} == $botMode); if(exists $self->{accountManagementSvc}{SETBOTMODE}) { $self->{accountManagementSvc}{SETBOTMODE}( sub { my ($failedReason,$updatedAccountId)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to set bot mode for '.$botName.': '.$failedReason],$cmdId); }else{ # updated client may have disconnected, reconnected and even renamed during async processing... my ($currentBotName,$r_currentBotInfo)=getOnlineClientData($self,$updatedAccountId,$botName); if(defined $r_currentBotInfo && $r_currentBotInfo->{status}{bot} != $botMode) { $r_currentBotInfo->{status}{bot}=$botMode; $r_currentBotInfo->{marshalledStatus}=marshallClientStatus($r_currentBotInfo->{status}); @inducedTraffic=broadcast($self,'CLIENTSTATUS',$currentBotName,$r_currentBotInfo->{marshalledStatus}); } return if($hdl->destroyed()); addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['SERVERMSG','Bot mode for '.$botName.' successfully set to '.$botMode],$cmdId)); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$botName,$botMode, ); return; }elsif(defined $r_botInfo) { $r_botInfo->{status}{bot}=$botMode; $r_botInfo->{marshalledStatus}=marshallClientStatus($r_botInfo->{status}); my @inducedTraffic=broadcast($self,'CLIENTSTATUS',$botName,$r_botInfo->{marshalledStatus}); addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['SERVERMSG','Bot mode for '.$botName.' successfully set to '.$botMode],$cmdId)); return @inducedTraffic; }else{ return sendClient($self,$hdl,['SERVERMSG','Cannot set bot mode of offline client, feature is not supported by this server'],$cmdId); } } sub hCreateBotAccount { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$botName,$ownerName)=@{$r_cmd}; return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid CREATEBOTACCOUNT parameter'],$cmdId) unless($botName =~ REGEX_USERNAME && $ownerName =~ REGEX_USERNAME); return sendClient($self,$hdl,['SERVERMSG','Cannot create bot account, feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{CREATEBOTACCOUNT}); my $lcBotName=lc($botName); my $denyReason = exists $self->{lcUsers}{$lcBotName} ? 'account already exists' : exists $self->{lcServerBots}{$lcBotName} ? 'name is reserved for internal use' : undef; return sendClient($self,$hdl,['SERVERMSG','Failed to create bot account '.$botName.': '.$denyReason],$cmdId) if(defined $denyReason); $self->{accountManagementSvc}{CREATEBOTACCOUNT}( sub { return if($hdl->destroyed()); my $failedReason=shift; my @inducedTraffic; if(defined $failedReason) { @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to create bot account '.$botName.': '.$failedReason],$cmdId); }else{ @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','A new bot account '.$botName.' has been created, with the same password as '.$ownerName],$cmdId); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$botName,$ownerName, ); return; } sub hBan { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$userName,$duration,$reason)=@{$r_cmd}; undef $reason if(defined $reason && $reason eq ''); if(defined $duration) { $duration=0 if($duration eq ''); }else{ $duration=0; } return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid BAN parameter'],$cmdId) unless($userName =~ REGEX_USERNAME && $duration =~ REGEX_BANDURATION && (! defined $reason || length($reason) < 255)); return sendClient($self,$hdl,['SERVERMSG','Cannot ban account, feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{BAN}); my %DURATION_SUFFIXES=( y => 525600, m => 43200, w => 10080, d => 1440, h => 60, ); foreach my $durationSuffix (keys %DURATION_SUFFIXES) { if($duration =~ /^(\d+)$durationSuffix$/) { $duration = $1 * $DURATION_SUFFIXES{$durationSuffix}; last; } } $self->{accountManagementSvc}{BAN}( sub { my ($failedReason,$bannedAccountId)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to ban '.$userName.': '.$failedReason],$cmdId); }else{ # banned user may have disconnected, reconnected and even renamed during async processing... my $currentBannedUserName=getOnlineClientName($self,$bannedAccountId,$userName); @inducedTraffic=kickUserFromServer($self,$currentBannedUserName,$login,$reason,1) if(defined $currentBannedUserName); return if($hdl->destroyed()); addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['SERVERMSG','Banned '.$userName.' from the server'],$cmdId)); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName,$duration,$reason, ); return; } sub hUnban { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $userName=$r_cmd->[1]; return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid UNBAN parameter'],$cmdId) unless($userName =~ REGEX_USERNAME); return sendClient($self,$hdl,['SERVERMSG','Cannot unban account, feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{UNBAN}); $self->{accountManagementSvc}{UNBAN}( sub { return if($hdl->destroyed()); my $failedReason=shift; my @inducedTraffic; if(defined $failedReason) { @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to unban '.$userName.': '.$failedReason],$cmdId); }else{ @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Unbanned '.$userName.' from the server'],$cmdId); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName, ); return; } sub hListBans { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; return sendClient($self,$hdl,['SERVERMSG','Cannot list bans, feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{LISTBANS}); $self->{accountManagementSvc}{LISTBANS}( sub { return if($hdl->destroyed()); my ($failedReason,$r_bans)=@_; my @inducedTraffic; if(defined $failedReason) { @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to list bans: '.$failedReason],$cmdId); }else{ if(defined $r_bans && @{$r_bans}) { my @serverMsgs=('-- Banlist --'); foreach my $r_ban (@{$r_bans}) { push(@serverMsgs,'. '.join(', ',map {$_.':'.$r_ban->{$_}} (sort keys %{$r_ban}))); } push(@serverMsgs,'-- End Banlist --'); @inducedTraffic=sendClientMulti($self,$hdl,[map {['SERVERMSG',$_]} @serverMsgs],$cmdId); }else{ @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Banlist is empty'],$cmdId); } } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo ); return; } sub hSetAccess { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$userName,$accessLevel)=@{$r_cmd}; return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid SETACCESS parameter (userName)'],$cmdId) unless($userName =~ REGEX_USERNAME); my $lcAccessLevel=lc($accessLevel); my %ACCESS_MODES=( user => 1, mod => 100, admin => 200, ); if(exists $ACCESS_MODES{$lcAccessLevel}) { $accessLevel=$ACCESS_MODES{$lcAccessLevel}; }elsif($accessLevel !~ /^\d{1,6}$/) { return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid SETACCESS parameter (accessLevel)'],$cmdId) } my $r_updatedUserInfo=$self->{users}{$userName}; return sendClient($self,$hdl,['SERVERMSG','Failed to set access level for '.$userName.': access is already set to '.$accessLevel],$cmdId) if(defined $r_updatedUserInfo && $r_updatedUserInfo->{accessLevel} == $accessLevel); my $newAccessFlag; if($self->{accessFlagLevel}) { $newAccessFlag = $accessLevel >= $self->{accessFlagLevel} ? 1 : 0; } if(exists $self->{accountManagementSvc}{SETACCESS}) { $self->{accountManagementSvc}{SETACCESS}( sub { my ($failedReason,$updatedAccountId)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to set access level for '.$userName.': '.$failedReason],$cmdId); }else{ # updated client may have disconnected, reconnected and even renamed during async processing... my ($currentUserName,$r_currentUserInfo)=getOnlineClientData($self,$updatedAccountId,$userName); if(defined $r_currentUserInfo) { $r_currentUserInfo->{accessLevel}=$accessLevel; if(defined $newAccessFlag && $r_currentUserInfo->{status}{access} != $newAccessFlag) { $r_currentUserInfo->{status}{access}=$newAccessFlag; $r_currentUserInfo->{marshalledStatus}=marshallClientStatus($r_currentUserInfo->{status}); @inducedTraffic=broadcast($self,'CLIENTSTATUS',$currentUserName,$r_currentUserInfo->{marshalledStatus}); } } return if($hdl->destroyed()); addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['SERVERMSG','Access level for '.$userName.' successfully set to '.$accessLevel],$cmdId)); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName,$accessLevel, ); return; }elsif(defined $r_updatedUserInfo) { my @inducedTraffic; $r_updatedUserInfo->{accessLevel}=$accessLevel; if(defined $newAccessFlag && $r_updatedUserInfo->{status}{access} != $newAccessFlag) { $r_updatedUserInfo->{status}{access} = $newAccessFlag; $r_updatedUserInfo->{marshalledStatus}=marshallClientStatus($r_updatedUserInfo->{status}); @inducedTraffic=broadcast($self,'CLIENTSTATUS',$userName,$r_updatedUserInfo->{marshalledStatus}); } addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['SERVERMSG','Access level for '.$userName.' successfully set to '.$accessLevel],$cmdId)); return @inducedTraffic; }else{ return sendClient($self,$hdl,['SERVERMSG','Cannot set access level of offline client, feature is not supported by this server'],$cmdId); } } sub hDeleteAccount { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my $userName=$r_cmd->[1]; return sendClient($self,$hdl,['SERVERMSG','Protocol error: invalid DELETEACCOUNT parameter'],$cmdId) unless($userName =~ REGEX_USERNAME); return sendClient($self,$hdl,['SERVERMSG','Cannot delete account, feature is not supported by this server'],$cmdId) unless(exists $self->{accountManagementSvc}{DELETEACCOUNT}); $self->{accountManagementSvc}{DELETEACCOUNT}( sub { my ($failedReason,$deletedAccountId)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to delete account of '.$userName.': '.$failedReason],$cmdId); }else{ # client may have disconnected, reconnected and even renamed during async processing... my $currentDeletedUserName=getOnlineClientName($self,$deletedAccountId,$userName); @inducedTraffic=kickUserFromServer($self,$currentDeletedUserName,$login,'account deleted') if(defined $currentDeletedUserName); return if($hdl->destroyed()); addInducedTraffic(\@inducedTraffic,sendClient($self,$hdl,['SERVERMSG','Deleted account of '.$userName],$cmdId)); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName, ); return; } sub hIgnore { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@tagParamDefs)=@{$r_cmd}; my ($r_tagParams,$paramError)=parseTagParamDefs(\@tagParamDefs,['userName','reason']); return closeClientConnection($self,$hdl,'protocol error','invalid IGNORE parameter: '.$paramError) if(defined $paramError); my ($userName,$reason)=@{$r_tagParams}{qw'userName reason'}; return closeClientConnection($self,$hdl,'protocol error','missing IGNORE parameter: userName') unless(defined $userName); return closeClientConnection($self,$hdl,'protocol error','invalid IGNORE parameter') unless($userName =~ REGEX_USERNAME && (! defined $reason || length($reason) < 255)); my $accountId=$r_userInfo->{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot ignore account, feature requires accountId feature which is not supported by this server'],$cmdId) unless($accountId); my $ignoredAccountId; if(exists $self->{users}{$userName}) { $ignoredAccountId=$self->{users}{$userName}{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot ignore account, feature requires accountId feature which is not fully supported by this server'],$cmdId) unless($ignoredAccountId); return sendClient($self,$hdl,['SERVERMSG','Failed to ignore '.$userName.': account is already ignored'],$cmdId) if(exists $r_userInfo->{ignoredAccounts}{$ignoredAccountId}); } return sendClient($self,$hdl,['SERVERMSG','Cannot ignore more accounts: maximum number of ignored accounts reached'],$cmdId) if($self->{maxIgnoresByAccount} && keys %{$r_userInfo->{ignoredAccounts}} >= $self->{maxIgnoresByAccount}); if(exists $self->{ignoreSvc}{IGNORE}) { $self->{ignoreSvc}{IGNORE}( sub { my ($failedReason,$ignoredAccountIdFromDb)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to ignore '.$userName.': '.$failedReason],$cmdId); }else{ # client may have disconnected, reconnected and even renamed during async processing... my (undef,$r_currentUserInfo)=getOnlineClientData($self,$accountId); return unless(defined $r_currentUserInfo && ! exists $r_currentUserInfo->{ignoredAccounts}{$ignoredAccountIdFromDb}); $r_currentUserInfo->{ignoredAccounts}{$ignoredAccountIdFromDb}=$r_tagParams; return if($hdl->destroyed()); # do not send command ack if user reconnected @inducedTraffic=sendClient($self,$hdl,$r_cmd,$cmdId); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName,$reason, ); return; }elsif(defined $ignoredAccountId) { $r_userInfo->{ignoredAccounts}{$ignoredAccountId}=$r_tagParams; return sendClient($self,$hdl,$r_cmd,$cmdId); }else{ return sendClient($self,$hdl,['SERVERMSG','Cannot ignore offline account, feature is not supported by this server'],$cmdId); } } sub parseTagParamDefs { my ($r_tagParamDefs,$r_allowedTags)=@_; my $r_tagParams={}; foreach my $tagParamDef (@{$r_tagParamDefs}) { if($tagParamDef =~ REGEX_TAGPARAM) { my ($paramName,$paramVal)=($1,$2); return (undef,'duplicate tag parameter') if(exists $r_tagParams->{$paramName}); return (undef,'wrong tag parameter name') if(none {$paramName eq $_} @{$r_allowedTags}); $r_tagParams->{$paramName}=$paramVal; }else{ return (undef,'wrong tag parameter syntax'); } } return ($r_tagParams); } sub hUnignore { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@tagParamDefs)=@{$r_cmd}; my ($r_tagParams,$paramError)=parseTagParamDefs(\@tagParamDefs,['userName']); return closeClientConnection($self,$hdl,'protocol error','invalid UNIGNORE parameter: '.$paramError) if(defined $paramError); my $userName=$r_tagParams->{userName}; return closeClientConnection($self,$hdl,'protocol error','missing UNIGNORE parameter: userName') unless(defined $userName); return closeClientConnection($self,$hdl,'protocol error','invalid UNIGNORE parameter') unless($userName =~ REGEX_USERNAME); my $accountId=$r_userInfo->{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot unignore account, feature requires accountId feature which is not supported by this server'],$cmdId) unless($accountId); my $ignoredAccountId; if(exists $self->{users}{$userName}) { $ignoredAccountId=$self->{users}{$userName}{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot unignore account, feature requires accountId feature which is not fully supported by this server'],$cmdId) unless($ignoredAccountId); return sendClient($self,$hdl,['SERVERMSG','Failed to unignore '.$userName.': account is not ignored'],$cmdId) unless(exists $r_userInfo->{ignoredAccounts}{$ignoredAccountId}); } if(exists $self->{ignoreSvc}{UNIGNORE}) { $self->{ignoreSvc}{UNIGNORE}( sub { my ($failedReason,$ignoredAccountIdFromDb)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to unignore '.$userName.': '.$failedReason],$cmdId); }else{ # client may have disconnected, reconnected and even renamed during async processing... my (undef,$r_currentUserInfo)=getOnlineClientData($self,$accountId); return unless(defined $r_currentUserInfo && exists $r_currentUserInfo->{ignoredAccounts}{$ignoredAccountIdFromDb}); delete $r_currentUserInfo->{ignoredAccounts}{$ignoredAccountIdFromDb}; return if($hdl->destroyed()); # do not send command ack if user reconnected @inducedTraffic=sendClient($self,$hdl,$r_cmd,$cmdId); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName, ); return; }elsif(defined $ignoredAccountId) { delete $r_userInfo->{ignoredAccounts}{$ignoredAccountId}; return sendClient($self,$hdl,$r_cmd,$cmdId); }else{ my $unignoredAccounts=0; foreach my $ignoredId (keys %{$r_userInfo->{ignoredAccounts}}) { if($r_userInfo->{ignoredAccounts}{$ignoredId}{userName} eq $userName) { delete $r_userInfo->{ignoredAccounts}{$ignoredId}; $unignoredAccounts++; } } if($unignoredAccounts) { return sendClient($self,$hdl,$r_cmd,$cmdId); }else{ return sendClient($self,$hdl,['SERVERMSG','Failed to unignore '.$userName.': user is not ignored'],$cmdId) } } } sub hIgnoreList { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; if(exists $self->{ignoreSvc}{IGNORELIST}) { $self->{ignoreSvc}{IGNORELIST}( sub { return if($hdl->destroyed()); my $r_ignoreList=shift; my @ignoreListCmds=(['IGNORELISTBEGIN']); if(defined $r_ignoreList) { foreach my $r_ignoreData (@{$r_ignoreList}) { my @tagParams=('userName='.$r_ignoreData->{userName}); push(@tagParams,'reason='.$r_ignoreData->{reason}) if(defined $r_ignoreData->{reason}); push(@tagParams,'accountId='.$r_ignoreData->{accountId}) if(defined $r_ignoreData->{accountId}); push(@ignoreListCmds,['IGNORELIST',@tagParams]); } } push(@ignoreListCmds,['IGNORELISTEND']); my @inducedTraffic=sendClientMulti($self,$hdl,\@ignoreListCmds,$cmdId); closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo); return; }else{ my @ignoreListCmds=(['IGNORELISTBEGIN']); foreach my $ignoredId (sort keys %{$r_userInfo->{ignoredAccounts}}) { my $r_ignoreData=$r_userInfo->{ignoredAccounts}{$ignoredId}; my @tagParams=('userName='.($self->{accounts}{$ignoredId}//$r_ignoreData->{userName})); my $reason=$r_ignoreData->{reason}; push(@tagParams,'reason='.$reason) if(defined $reason); push(@tagParams,'accountId='.$ignoredId); push(@ignoreListCmds,['IGNORELIST',@tagParams]); } push(@ignoreListCmds,['IGNORELISTEND']); return sendClientMulti($self,$hdl,\@ignoreListCmds,$cmdId); } } sub hFriendRequest { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@tagParamDefs)=@{$r_cmd}; my ($r_tagParams,$paramError)=parseTagParamDefs(\@tagParamDefs,['userName','msg']); return closeClientConnection($self,$hdl,'protocol error','invalid FRIENDREQUEST parameter: '.$paramError) if(defined $paramError); my ($userName,$msg)=@{$r_tagParams}{qw'userName msg'}; return closeClientConnection($self,$hdl,'protocol error','missing FRIENDREQUEST parameter: userName') unless(defined $userName); return closeClientConnection($self,$hdl,'protocol error','invalid FRIENDREQUEST parameter') unless($userName =~ REGEX_USERNAME && (! defined $msg || length($msg) < 255)); return sendClient($self,$hdl,['SERVERMSG','Cannot send friend request, feature is not supported by this server'],$cmdId) unless(exists $self->{friendSvc}{FRIENDREQUEST}); return sendClient($self,$hdl,['SERVERMSG','Cannot send friend request to yourself'],$cmdId) if($login eq $userName); my $accountId=$r_userInfo->{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot send friend request, feature requires accountId feature which is not supported by this server'],$cmdId) unless($accountId); if(exists $self->{users}{$userName}) { my $r_friendUserInfo=$self->{users}{$userName}; my $friendAccountId=$r_friendUserInfo->{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot send friend request, feature requires accountId feature which is not fully supported by this server'],$cmdId) unless($friendAccountId); return sendClient($self,$hdl,['SERVERMSG','Failed to send friend request to '.$userName.': already friend'],$cmdId) if(exists $r_userInfo->{friendAccounts}{$friendAccountId}); return sendClient($self,$hdl,['SERVERMSG','Failed to send friend request to '.$userName.': you already have an incoming friend request from this user, use ACCEPTFRIENDREQUEST instead'],$cmdId) if(exists $r_userInfo->{friendRequestsIn}{$friendAccountId}); return if(exists $r_friendUserInfo->{friendRequestsIn}{$accountId} || exists $r_friendUserInfo->{ignoredAccounts}{$accountId}); return sendClient($self,$hdl,['SERVERMSG','Failed to send friend request to '.$userName.': user has reached maximum number of friends and friend requests'],$cmdId) if($self->{maxFriendsByAccount} && keys(%{$r_friendUserInfo->{friendAccounts}}) + keys(%{$r_friendUserInfo->{friendRequestsIn}}) + keys(%{$r_friendUserInfo->{friendRequestsOut}}) >= $self->{maxFriendsByAccount}); } return sendClient($self,$hdl,['SERVERMSG','Cannot send friend request: maximum number of friends and friend requests reached'],$cmdId) if($self->{maxFriendsByAccount} && keys(%{$r_userInfo->{friendAccounts}}) + keys(%{$r_userInfo->{friendRequestsIn}}) + keys(%{$r_userInfo->{friendRequestsOut}}) >= $self->{maxFriendsByAccount}); $self->{friendSvc}{FRIENDREQUEST}( sub { my ($failedReason,$friendAccountId)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to send friend request to '.$userName.': '.$failedReason],$cmdId) unless($failedReason eq ''); }else{ # clients may have disconnected, reconnected and even renamed during async processing... my ($friendUserName,$r_friendUserInfo)=getOnlineClientData($self,$friendAccountId); $friendUserName//=$userName; my ($currentLogin,$r_currentUserInfo)=getOnlineClientData($self,$accountId); $currentLogin//=$login; # we don't check ignoredAccounts here to keep consistency with DB (avoid race conditions) if(defined $r_currentUserInfo && ! exists $r_currentUserInfo->{friendAccounts}{$friendAccountId} && ! exists $r_currentUserInfo->{friendRequestsOut}{$friendAccountId} && ! exists $r_currentUserInfo->{friendRequestsIn}{$friendAccountId}) { my %friendData=(userName => $friendUserName); $friendData{msg}=$msg if(defined $msg); $r_currentUserInfo->{friendRequestsOut}{$friendAccountId}=\%friendData; } if(defined $r_friendUserInfo && ! exists $r_friendUserInfo->{friendAccounts}{$accountId} && ! exists $r_friendUserInfo->{friendRequestsOut}{$accountId} && ! exists $r_friendUserInfo->{friendRequestsIn}{$accountId}) { my %friendData=(userName => $currentLogin); $friendData{msg}=$msg if(defined $msg); $r_friendUserInfo->{friendRequestsIn}{$accountId}=\%friendData; my @tagParams=('userName='.$currentLogin); push(@tagParams,'msg='.$msg) if(defined $msg); push(@tagParams,'accountId='.$accountId); @inducedTraffic=sendUser($self,$friendUserName,['FRIENDREQUEST',@tagParams]); } return if($hdl->destroyed()); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName,$msg, ); return; } sub hAcceptFriendRequest { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@tagParamDefs)=@{$r_cmd}; my ($r_tagParams,$paramError)=parseTagParamDefs(\@tagParamDefs,['userName']); return closeClientConnection($self,$hdl,'protocol error','invalid ACCEPTFRIENDREQUEST parameter: '.$paramError) if(defined $paramError); my $userName=$r_tagParams->{userName}; return closeClientConnection($self,$hdl,'protocol error','missing ACCEPTFRIENDREQUEST parameter: userName') unless(defined $userName); return closeClientConnection($self,$hdl,'protocol error','invalid ACCEPTFRIENDREQUEST parameter') unless($userName =~ REGEX_USERNAME); return sendClient($self,$hdl,['SERVERMSG','Cannot accept friend request, feature is not supported by this server'],$cmdId) unless(exists $self->{friendSvc}{ACCEPTFRIENDREQUEST}); my $accountId=$r_userInfo->{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot accept friend request, feature requires accountId feature which is not supported by this server'],$cmdId) unless($accountId); if(exists $self->{users}{$userName}) { my $friendAccountId=$self->{users}{$userName}{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot accept friend request, feature requires accountId feature which is not fully supported by this server'],$cmdId) unless($friendAccountId); return sendClient($self,$hdl,['SERVERMSG','Failed to accept friend request, no pending request from '.$userName],$cmdId) unless(exists $r_userInfo->{friendRequestsIn}{$friendAccountId}); if(exists $r_userInfo->{friendAccounts}{$friendAccountId}) { delete $r_userInfo->{friendRequestsIn}{$friendAccountId}; return; } } $self->{friendSvc}{ACCEPTFRIENDREQUEST}( sub { my ($failedReason,$friendAccountId)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to accept friend request from '.$userName.': '.$failedReason],$cmdId); }else{ # clients may have disconnected, reconnected and even renamed during async processing... my ($friendUserName,$r_friendUserInfo)=getOnlineClientData($self,$friendAccountId); $friendUserName//=$userName; my ($currentLogin,$r_currentUserInfo)=getOnlineClientData($self,$accountId); $currentLogin//=$login; if(defined $r_currentUserInfo) { delete $r_currentUserInfo->{friendRequestsIn}{$friendAccountId}; if(! exists $r_currentUserInfo->{friendAccounts}{$friendAccountId}) { $r_currentUserInfo->{friendAccounts}{$friendAccountId}=$friendUserName; @inducedTraffic=sendUser($self,$currentLogin,['FRIEND','userName='.$friendUserName,'accountId='.$friendAccountId]); } } if(defined $r_friendUserInfo) { delete $r_friendUserInfo->{friendRequestsOut}{$accountId}; if(! exists $r_friendUserInfo->{friendAccounts}{$accountId}) { $r_friendUserInfo->{friendAccounts}{$accountId}=$currentLogin; addInducedTraffic(\@inducedTraffic,sendUser($self,$friendUserName,['FRIEND','userName='.$currentLogin,'accountId='.$accountId])); } } return if($hdl->destroyed()); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName, ); return; } sub hDeclineFriendRequest { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@tagParamDefs)=@{$r_cmd}; my ($r_tagParams,$paramError)=parseTagParamDefs(\@tagParamDefs,['userName']); return closeClientConnection($self,$hdl,'protocol error','invalid DECLINEFRIENDREQUEST parameter: '.$paramError) if(defined $paramError); my $userName=$r_tagParams->{userName}; return closeClientConnection($self,$hdl,'protocol error','missing DECLINEFRIENDREQUEST parameter: userName') unless(defined $userName); return closeClientConnection($self,$hdl,'protocol error','invalid DECLINEFRIENDREQUEST parameter') unless($userName =~ REGEX_USERNAME); return sendClient($self,$hdl,['SERVERMSG','Cannot decline friend request, feature is not supported by this server'],$cmdId) unless(exists $self->{friendSvc}{DECLINEFRIENDREQUEST}); my $accountId=$r_userInfo->{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot decline friend request, feature requires accountId feature which is not supported by this server'],$cmdId) unless($accountId); if(exists $self->{users}{$userName}) { my $friendAccountId=$self->{users}{$userName}{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot decline friend request, feature requires accountId feature which is not fully supported by this server'],$cmdId) unless($friendAccountId); return sendClient($self,$hdl,['SERVERMSG','Failed to decline friend request, no pending request from '.$userName],$cmdId) unless(exists $r_userInfo->{friendRequestsIn}{$friendAccountId}); if(exists $r_userInfo->{friendAccounts}{$friendAccountId}) { delete $r_userInfo->{friendRequestsIn}{$friendAccountId}; return; } } $self->{friendSvc}{DECLINEFRIENDREQUEST}( sub { my ($failedReason,$friendAccountId)=@_; if(defined $failedReason) { return if($hdl->destroyed()); my @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to decline friend request from '.$userName.': '.$failedReason],$cmdId); closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }else{ # clients may have disconnected, reconnected and even renamed during async processing... my (undef,$r_friendUserInfo)=getOnlineClientData($self,$friendAccountId); delete $r_friendUserInfo->{friendRequestsOut}{$accountId} if(defined $r_friendUserInfo); my (undef,$r_currentUserInfo)=getOnlineClientData($self,$accountId); delete $r_currentUserInfo->{friendRequestsIn}{$friendAccountId} if(defined $r_currentUserInfo); } }, $r_connInfo,$login,$r_userInfo,$userName, ); return; } sub hUnfriend { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@tagParamDefs)=@{$r_cmd}; my ($r_tagParams,$paramError)=parseTagParamDefs(\@tagParamDefs,['userName']); return closeClientConnection($self,$hdl,'protocol error','invalid UNFRIEND parameter: '.$paramError) if(defined $paramError); my $userName=$r_tagParams->{userName}; return closeClientConnection($self,$hdl,'protocol error','missing UNFRIEND parameter: userName') unless(defined $userName); return closeClientConnection($self,$hdl,'protocol error','invalid UNFRIEND parameter') unless($userName =~ REGEX_USERNAME); return sendClient($self,$hdl,['SERVERMSG','Cannot unfriend, feature is not supported by this server'],$cmdId) unless(exists $self->{friendSvc}{UNFRIEND}); my $accountId=$r_userInfo->{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot unfriend, feature requires accountId feature which is not supported by this server'],$cmdId) unless($accountId); if(exists $self->{users}{$userName}) { my $friendAccountId=$self->{users}{$userName}{accountId}; return sendClient($self,$hdl,['SERVERMSG','Cannot unfriend, feature requires accountId feature which is not fully supported by this server'],$cmdId) unless($friendAccountId); return sendClient($self,$hdl,['SERVERMSG','Failed to unfriend, not friend with '.$userName],$cmdId) unless(exists $r_userInfo->{friendAccounts}{$friendAccountId}); } $self->{friendSvc}{UNFRIEND}( sub { my ($failedReason,$friendAccountId)=@_; my @inducedTraffic; if(defined $failedReason) { return if($hdl->destroyed()); @inducedTraffic=sendClient($self,$hdl,['SERVERMSG','Failed to unfriend with '.$userName.': '.$failedReason],$cmdId); }else{ # clients may have disconnected, reconnected and even renamed during async processing... my ($friendUserName,$r_friendUserInfo)=getOnlineClientData($self,$friendAccountId); $friendUserName//=$userName; my ($currentLogin,$r_currentUserInfo)=getOnlineClientData($self,$accountId); $currentLogin//=$login; if(defined $r_currentUserInfo && exists $r_currentUserInfo->{friendAccounts}{$friendAccountId}) { delete $r_currentUserInfo->{friendAccounts}{$friendAccountId}; @inducedTraffic=sendUser($self,$currentLogin,['UNFRIEND','userName='.$friendUserName,'accountId='.$friendAccountId]); } if(defined $r_friendUserInfo && exists $r_friendUserInfo->{friendAccounts}{$accountId}) { delete $r_friendUserInfo->{friendAccounts}{$accountId}; addInducedTraffic(\@inducedTraffic,sendUser($self,$friendUserName,['UNFRIEND','userName='.$currentLogin,'accountId='.$accountId])); } return if($hdl->destroyed()); } closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$userName, ); return; } sub hFriendRequestList { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,@tagParamDefs)=@{$r_cmd}; my ($r_tagParams,$paramError)=parseTagParamDefs(\@tagParamDefs,['type']); return closeClientConnection($self,$hdl,'protocol error','invalid FRIENDREQUESTLIST parameter: '.$paramError) if(defined $paramError); my $isOutgoingRequests; my $type=$r_tagParams->{type}; if(defined $type) { if(lc($type) eq 'in') { $type='in'; }elsif(lc($type) eq 'out') { $isOutgoingRequests=1; $type='out'; }else{ closeClientConnection($self,$hdl,'protocol error','invalid FRIENDREQUESTLIST parameter: type'); } } if(exists $self->{friendSvc}{FRIENDREQUESTLIST}) { $self->{friendSvc}{FRIENDREQUESTLIST}( sub { return if($hdl->destroyed()); my $r_friendRequestList=shift; my @friendCmds=(['FRIENDREQUESTLISTBEGIN']); if(defined $r_friendRequestList) { foreach my $r_friendData (@{$r_friendRequestList}) { my @tagParams=('userName='.$r_friendData->{userName}); map {push(@tagParams,$_.'='.$r_friendData->{$_}) if(defined $r_friendData->{$_})} (qw'msg accountId type'); push(@friendCmds,['FRIENDREQUESTLIST',@tagParams]); } } push(@friendCmds,['FRIENDREQUESTLISTEND']); my @inducedTraffic=sendClientMulti($self,$hdl,\@friendCmds,$cmdId); closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$isOutgoingRequests); return; }else{ my $friendRequestsField = $isOutgoingRequests ? 'friendRequestsOut' : 'friendRequestsIn'; my @friendCmds=(['FRIENDREQUESTLISTBEGIN']); foreach my $friendAccountId (sort keys %{$r_userInfo->{$friendRequestsField}}) { my $r_friendData=$r_userInfo->{$friendRequestsField}{$friendAccountId}; my @tagParams=('userName='.$r_friendData->{userName}); push(@tagParams,'msg='.$r_friendData->{msg}) if(defined $r_friendData->{msg}); push(@tagParams,'accountId='.$friendAccountId); push(@tagParams,'type='.$type) if(defined $type); push(@friendCmds,['FRIENDREQUESTLIST',@tagParams]); } push(@friendCmds,['FRIENDREQUESTLISTEND']); return sendClientMulti($self,$hdl,\@friendCmds,$cmdId); } } sub hFriendList { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; if(exists $self->{friendSvc}{FRIENDLIST}) { $self->{friendSvc}{FRIENDLIST}( sub { return if($hdl->destroyed()); my $r_friendList=shift; my @friendCmds=(['FRIENDLISTBEGIN']); if(defined $r_friendList) { foreach my $r_friendData (@{$r_friendList}) { my @tagParams=('userName='.$r_friendData->{userName}); push(@tagParams,'accountId='.$r_friendData->{accountId}) if(defined $r_friendData->{accountId}); push(@friendCmds,['FRIENDLIST',@tagParams]); } } push(@friendCmds,['FRIENDLISTEND']); my @inducedTraffic=sendClientMulti($self,$hdl,\@friendCmds,$cmdId); closeClientConnection($self,$hdl,'induced traffic flood') if($inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo); return; }else{ my @friendCmds=(['FRIENDLISTBEGIN']); map {push(@friendCmds,['FRIENDLIST','userName='.$r_userInfo->{friendAccounts}{$_},'accountId='.$_])} (sort keys %{$r_userInfo->{friendAccounts}}); push(@friendCmds,['FRIENDLISTEND']); return sendClientMulti($self,$hdl,\@friendCmds,$cmdId); } } sub hChannelTopic { my ($self,$hdl,$r_connInfo,$login,$r_userInfo,$r_cmd,$cmdId)=@_; my (undef,$chan,$topic)=@{$r_cmd}; return closeClientConnection($self,$hdl,'protocol error','invalid CHANNELTOPIC parameter') unless($chan =~ REGEX_CHANNEL && length($topic) <= $self->{maxChatMsgLength}); $topic='' if($topic eq '*'); if(defined $self->{onChannelTopic}) { my $denyMsg=$self->{onChannelTopic}($r_connInfo,$login,$r_userInfo,$chan,\$topic); if(defined $denyMsg) { return if($denyMsg eq ''); return sendClient($self,$hdl,['SERVERMSG',"Failed to set channel topic for channel \"$chan\": $denyMsg"],$cmdId); } } if(defined $self->{onChannelTopicAsync}) { $self->{onChannelTopicAsync}->( sub { my $denyMsg=shift; if(defined $denyMsg) { return if($hdl->destroyed() || $denyMsg eq ''); return sendClient($self,$hdl,['SERVERMSG',"Failed to set channel topic for channel \"$chan\": $denyMsg"],$cmdId); } my @inducedTraffic=updateChannelTopic($self,$chan,$topic,$login); closeClientConnection($self,$hdl,'induced traffic flood') if(! $hdl->destroyed() && $inducedTraffic[0] && defined checkInducedTrafficFlood($self,$r_userInfo,@inducedTraffic)); }, $r_connInfo,$login,$r_userInfo,$chan,\$topic); }else{ return updateChannelTopic($self,$chan,$topic,$login); } } sub updateChannelTopic { my ($self,$chan,$topic,$author)=@_; if(exists $self->{channelTopics}{$chan}) { return if($self->{channelTopics}{$chan}{topic} eq $topic); if($topic eq '') { delete $self->{channelTopics}{$chan}; }else{ $self->{channelTopics}{$chan}={topic => $topic, author => $author}; } }else{ return if($topic eq ''); $self->{channelTopics}{$chan}={topic => $topic, author => $author}; } my @inducedTraffic=broadcastChannelLegacy($self,$chan,['CHANNELTOPIC',$chan,$author,$topic],['CHANNELTOPIC',$chan,$author,time()*1000,$topic eq '' ? '<null>' : $topic]); addInducedTraffic(\@inducedTraffic,broadcastChannel($self,$chan,'CHANNELMESSAGE',$chan,$topic eq '' ? 'Topic removed.' : 'Topic changed.')); return @inducedTraffic } sub srvBotAdd { my ($self,$srvBot,$r_onPrivateMsg,$r_onChannelMsg,$r_srvBotInfo,$r_srvBotStatus)=@_; my $lcBotName=lc($srvBot); croak "invalid srvBotAdd call: duplicate server bot \"$srvBot\"" if(exists $self->{lcServerBots}{$lcBotName}); croak "invalid srvBotAdd call: username conflict for server bot \"$srvBot\"" if(exists $self->{lcUsers}{$lcBotName}); my %srvBotInfo; if(defined $r_srvBotInfo) { map {$srvBotInfo{$_}=$r_srvBotInfo->{$_}//$DEFAULT_SRVBOT_INFO{$_}} (keys %DEFAULT_SRVBOT_INFO); $srvBotInfo{country}//=$self->{defaultCountryCode}; }else{ %srvBotInfo=%DEFAULT_SRVBOT_INFO; $srvBotInfo{country}=$self->{defaultCountryCode}; } my %srvBotStatus; if(defined $r_srvBotStatus) { map {$srvBotStatus{$_}=$r_srvBotStatus->{$_}//$DEFAULT_SRVBOT_STATUS{$_}} (keys %DEFAULT_SRVBOT_STATUS); }else{ %srvBotStatus=%DEFAULT_SRVBOT_STATUS; } my $marshalledBotStatus=marshallClientStatus(\%srvBotStatus); @srvBotInfo{qw'status marshalledStatus channels onPrivateMsg onChannelMsg'}=(\%srvBotStatus,$marshalledBotStatus,{},$r_onPrivateMsg,$r_onChannelMsg); $self->{serverBots}{$srvBot}=\%srvBotInfo; $self->{lcServerBots}{$lcBotName}=$srvBot; my @legacyAddUserFields=(qw'country cpu'); push(@legacyAddUserFields,'accountId') unless($self->{serverMode} == SRV_MODE_LAN); broadcastLegacy($self,['ADDUSER',$srvBot,@srvBotInfo{qw'country accountId lobbyClient'}],['ADDUSER',$srvBot,@srvBotInfo{@legacyAddUserFields}]); broadcast($self,'CLIENTSTATUS',$srvBot,$marshalledBotStatus) if($marshalledBotStatus); } sub srvBotRemove { my ($self,$srvBot,$reason)=@_; croak "invalid srvBotRemove call: unknown server bot \"$srvBot\"" unless(exists $self->{serverBots}{$srvBot}); map {delete $self->{channelBots}{$_}{$srvBot}; broadcastChannel($self,$_,'LEFT',$_,$srvBot,defined $reason ? $reason : ())} (keys %{$self->{serverBots}{$srvBot}{channels}}); delete $self->{serverBots}{$srvBot}; delete $self->{lcServerBots}{lc($srvBot)}; broadcast($self,'REMOVEUSER',$srvBot); } sub srvBotUpdateStatus { my ($self,$srvBot,$r_statusUpdates)=@_; croak "invalid srvBotUpdateStatus call: unknown server bot \"$srvBot\"" unless(exists $self->{serverBots}{$srvBot}); my $r_srvBotStatus=$self->{serverBots}{$srvBot}{status}; my $statusUpdated; foreach my $field (keys %{$r_statusUpdates}) { croak "invalid srvBotUpdateStatus call: unknown status field \"$field\"" unless(exists $r_srvBotStatus->{$field}); next if($r_srvBotStatus->{$field} == $r_statusUpdates->{$field}); $r_srvBotStatus->{$field}=$r_statusUpdates->{$field}; $statusUpdated=1; } return unless($statusUpdated); my $marshalledStatus=marshallClientStatus($r_srvBotStatus); $self->{serverBots}{$srvBot}{marshalledStatus}=$marshalledStatus; broadcast($self,'CLIENTSTATUS',$srvBot,$marshalledStatus); } sub srvBotJoinChannel { my ($self,$srvBot,$chan,$r_onChanMsg)=@_; croak "invalid srvBotJoinChannel call: unknown server bot \"$srvBot\"" unless(exists $self->{serverBots}{$srvBot}); croak "invalid srvBotJoinChannel call: server bot \"$srvBot\" is already in channel \"$chan\"" if(exists $self->{channelBots}{$chan}{$srvBot}); $self->{channelBots}{$chan}{$srvBot}=$r_onChanMsg; $self->{serverBots}{$srvBot}{channels}{$chan}=1; broadcastChannel($self,$chan,'JOINED',$chan,$srvBot); } sub srvBotLeaveChannel { my ($self,$srvBot,$chan,$reason)=@_; croak "invalid srvBotLeaveChannel call: unknown server bot \"$srvBot\"" unless(exists $self->{serverBots}{$srvBot}); croak "invalid srvBotLeaveChannel call: server bot \"$srvBot\" is not in channel \"$chan\"" unless(exists $self->{channelBots}{$chan}{$srvBot}); delete $self->{channelBots}{$chan}{$srvBot}; delete $self->{serverBots}{$srvBot}{channels}{$chan}; broadcastChannel($self,$chan,'LEFT',$chan,$srvBot,defined $reason ? $reason : ()); } sub srvBotSay { my ($self,$srvBot,$chan,$r_msgs,$isExMsg)=@_; return unless(defined $r_msgs && @{$r_msgs}); my $r_srvBotInfo=$self->{serverBots}{$srvBot}; return unless(defined $r_srvBotInfo && exists $r_srvBotInfo->{channels}{$chan}); my $saidCmd=$isExMsg?'SAIDEX':'SAID'; map {broadcastChannel($self,$chan,$saidCmd,$chan,$srvBot,$_);broadcastChannelMsgToSrvBots($self,undef,$srvBot,$r_srvBotInfo,$chan,$_,$isExMsg)} @{$r_msgs}; } sub srvBotSayPrivate { my ($self,$srvBot,$userName,$r_msgs,$isExMsg)=@_; return unless(defined $r_msgs && @{$r_msgs}); my $r_srvBotInfo=$self->{serverBots}{$srvBot}; return unless(defined $r_srvBotInfo); my $accountId; ($accountId,$userName) = @{$userName} if(ref $userName ne ''); my $recipient=getOnlineClientName($self,$accountId,$userName); if(defined $recipient) { my $srvBotAccountId=$r_srvBotInfo->{accountId}; return if($srvBotAccountId && exists $self->{users}{$recipient}{ignoredAccounts}{$srvBotAccountId}); my $saidCmd=$isExMsg?'SAIDPRIVATEEX':'SAIDPRIVATE'; map {sendUser($self,$recipient,[$saidCmd,$srvBot,$_])} @{$r_msgs}; }elsif(exists $self->{serverBots}{$userName}) { map {sendPrivateMsgToSrvBot($self,undef,$srvBot,$r_srvBotInfo,$userName,$_,$isExMsg)} @{$r_msgs}; } } package SpringLobbyServer::ServerBot; use Scalar::Util 'weaken'; sub new { my ($this,$springLobbyServer,$srvBot,@addBotParams)=@_; my $class = ref($this) || $this; $springLobbyServer->srvBotAdd($srvBot,@addBotParams); my $weakSpringLobbyServer=$springLobbyServer; weaken($weakSpringLobbyServer); my $self=[$weakSpringLobbyServer,$srvBot]; bless($self,$class); return $self; } sub remove { my $self=shift; return unless(defined $self->[0]); $self->[0]->srvBotRemove($self->[1],@_); undef $self->[0]; } sub updateStatus { my $self=shift; return unless(defined $self->[0]); $self->[0]->srvBotUpdateStatus($self->[1],@_); } sub joinChannel { my $self=shift; return unless(defined $self->[0]); $self->[0]->srvBotJoinChannel($self->[1],@_); } sub leaveChannel { my $self=shift; return unless(defined $self->[0]); $self->[0]->srvBotLeaveChannel($self->[1],@_); } sub say { my $self=shift; return unless(defined $self->[0]); $self->[0]->srvBotSay($self->[1],@_); } sub sayPrivate { my $self=shift; return unless(defined $self->[0]); $self->[0]->srvBotSayPrivate($self->[1],@_); } sub DESTROY { my $self=shift; return unless(defined $self->[0]); $self->[0]->srvBotRemove($self->[1]); }
import { useState } from "react"; import { Routes, Route, BrowserRouter } from "react-router-dom"; import Login from "./views/auth/Login"; import Register from "./views/auth/Register"; import Dashboard from "./views/auth/Dashboard"; import Logout from "./views/auth/Logout"; import ForgotPassword from "./views/auth/ForgotPassword"; import CreatePassword from "./views/auth/CreatePassword"; import StoreHeader from "./views/base/StoreHeader"; import StoreFooter from "./views/base/StoreFooter"; import Products from "./views/store/Products"; import ProductDetail from "./views/store/ProductDetail"; import Cart from "./views/store/Cart"; import Checkout from "./views/store/Checkout"; import PaymentSuccess from "./views/store/PaymentSuccess"; // import MainWrapper from "./layout/MainWrapper" function App() { const [count, setCount] = useState(0); return ( <BrowserRouter> <StoreHeader/> <Routes> <Route path="/login" element={<Login />} /> <Route path="/register" element={<Register />} /> <Route path="/logout" element={<Logout />} /> <Route path="/forgot-password" element={<ForgotPassword />} /> <Route path="/create-new-password" element={<CreatePassword />} /> <Route path="/dashboard" element={<Dashboard />} /> {/* STORE COMPONENTS */} <Route path='/' element={<Products />} /> <Route path='/detail/:slug/' element={<ProductDetail />} /> <Route path='/cart/' element={<Cart />} /> <Route path='/checkout/:order_oid/' element={<Checkout />} /> <Route path='/payment-success/:order_oid/' element={<PaymentSuccess />} /> </Routes> <StoreFooter/> </BrowserRouter> ); } export default App;
import { createSlice } from '@reduxjs/toolkit' import { getStoreLocal } from '@/utils/local-storage/localStorage' import { logout, signin, signup } from './user.actions' import { IUserInitialState } from '@/shared/types/user.types' const initialState: IUserInitialState = { user: getStoreLocal('user'), isLoading: false, } export const userSlice = createSlice({ name: 'user', initialState, reducers: {}, extraReducers: (builder) => { builder .addCase(signup.pending, (state) => { state.isLoading = true }) .addCase(signup.fulfilled, (state, { payload }) => { state.isLoading = false state.user = payload.user }) .addCase(signup.rejected, (state) => { state.isLoading = false state.user = null }) .addCase(signin.pending, (state) => { state.isLoading = true }) .addCase(signin.fulfilled, (state, { payload }) => { state.isLoading = false state.user = payload.user }) .addCase(signin.rejected, (state) => { state.isLoading = false state.user = null }) .addCase(logout.fulfilled, (state) => { state.isLoading = false state.user = null }) }, }) export const { reducer } = userSlice
from datetime import datetime import uuid from sqlalchemy import Column, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from core.db import Base class Incident(Base): __tablename__ = "incident" id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4())) type = Column(String, nullable=False) description = Column(String(255), nullable=False) detail = Column(String(255), nullable=False) address = Column(String, nullable=False) evidence = Column(String, nullable=False) creation_date = Column(DateTime, default=datetime.now) state = Column(String, nullable=False) user_username = Column(String, ForeignKey('users.username')) user = relationship("UserInDB", back_populates="incidents")
using Karkathamizha.API.IService; using Karkathamizha.API.Model; using Karkathamizha.API.Service.Service; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; namespace Karkathamizha.API.Controllers { [Route("api/[controller]")] [ApiController] public class BookController : ControllerBase { private readonly IBookService _bookService; public BookController(IBookService bookService) { _bookService = bookService; } #region Add Books [HttpPost()] [Route("AddBook")] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task<ActionResult<Book>> AddBook(Book book, int id) { if (book is null) { Log.Error("Book sent from client is null."); return BadRequest("Book object is null"); } if (!ModelState.IsValid) { Log.Error("Invalid Book object sent from client."); return BadRequest("Invalid model object"); } int bookId = await _bookService.AddUpdateBook(book); if (bookId == -2) return Ok($"Book = {book.BookName} already exists."); if (bookId >= 0) return Ok($"Book Id = {bookId} updated successfullly."); else return Ok($"New Book Id = {id} Created successfullly."); } #endregion #region Delete Books [HttpDelete("{id:int}")] public async Task<ActionResult<string>> DeleteBook(int id) { var book = await _bookService.GetBookById(id); if (book == null) return NotFound($"User Id = {id} doesn't exist."); var result = await _bookService.DeleteBook(id); return Ok(result); } #endregion #region Get All Books [HttpGet()] [Route("GetAllBooks")] public async Task<IEnumerable<Book>> GetAllBooks() { return await _bookService.GetAllBooks(); } #endregion #region Get Book By Id [HttpGet()] [Route("GetBookById")] [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Book))] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult<Book>> GetBookById(int id) { var book = await _bookService.GetBookById(id); if (book == null) return NotFound($"Book Id = {id} doesn't exist."); return Ok(book); } #endregion #region Get All Books [HttpGet()] [Route("GetAllBooksWithAuthor")] public async Task<IEnumerable<Book>> GetAllBooksWithAuthor() { return await _bookService.GetAllBooksWithAuthor(); } #endregion } }
<script setup lang="ts"> import { computed, onMounted, ref } from 'vue'; import { Utils } from '@youcan/ui-core'; import TagItem from './TagItem.vue'; import type { TagItemType, TagItemValue } from './types'; const props = withDefaults(defineProps<{ modelValue: TagItemValue[] type?: TagItemType max?: number placeholder?: string disabled?: boolean error?: boolean }>(), { type: 'text', placeholder: 'Add tag', disabled: false, error: false, }); const emit = defineEmits(['update:modelValue']); const tagInput = ref<HTMLInputElement>(); const tagsContainer = ref<HTMLDivElement>(); const newTagLabel = ref(''); const model = computed({ get: () => props.modelValue, set: (value: TagItemValue[]) => emit('update:modelValue', value), }); const updateTag = (index: number, value: TagItemValue) => { if (props.disabled) { return; } model.value = Utils.updateArray(model.value, index, value); }; const removeTag = (index: number) => { if (props.disabled) { return; } model.value = Utils.removeFromArray(model.value, index); }; onMounted(() => { tagInput.value?.addEventListener('keydown', (event: KeyboardEvent) => { if (event.key === 'Enter') { event.preventDefault(); if (!newTagLabel.value || (typeof props.max === 'number' && model.value.length >= props.max)) { return; } model.value = model.value.concat({ label: newTagLabel.value, }); newTagLabel.value = ''; } if (event.key === 'Backspace' && !newTagLabel.value) { removeTag(model.value.length - 1); } }); tagsContainer.value?.addEventListener('click', (event: MouseEvent) => { if (event.target === tagsContainer.value) { tagInput.value?.focus(); } }); }); </script> <template> <div ref="tagsContainer" class="tag" tabindex="0" :disabled="disabled" :error="error"> <TagItem v-for="(tag, index) in model" :key="`${tag.label}-${index}`" :model-value="model[index]" :type="type" @update:model-value="(value) => updateTag(index, value)" @remove="removeTag(index)" /> <input v-show="typeof max === 'undefined' || model.length < max" ref="tagInput" v-model="newTagLabel" type="text" class="tag-input" :placeholder="placeholder" > </div> </template> <style scoped> .tag { --width: 460px; --border: 1px solid var(--gray-200); --shadow: var(--shadow-xs-gray); --background-color: var(--base-white); display: flex; box-sizing: border-box; flex-wrap: wrap; align-items: center; width: var(--width); max-width: 100%; padding: 6px; border: var(--border); border-radius: 8px; outline: none; background-color: var(--background-color); box-shadow: var(--shadow); gap: 6px; } .tag:hover { --border: 1px solid var(--gray-300); } .tag[disabled="false"][error="false"]:focus, .tag[disabled="false"][error="false"]:focus-within { --border: 1px solid var(--brand-500); --shadow: var(--focus-shadow-xs-brand); } .tag[disabled="false"][error="true"] { --border: 1px solid var(--red-500); } .tag[disabled="false"][error="true"]:focus, .tag[disabled="false"][error="true"]:focus-within { --border: 1px solid var(--red-500); --shadow: var(--focus-shadow-xs-red); } .tag[disabled="true"] { --text-color: var(--gray-300); --background-color: var(--gray-50); } .tag .tag-input { flex: 1; min-width: 146px; border: none; outline: none; background-color: var(--base-white); color: var(--gray-900); font: var(--text-sm-regular); } .tag[disabled="true"] .tag-input { background-color: var(--gray-50); pointer-events: none; } .tag .tag-input::placeholder { color: var(--gray-300); } </style>
<?php /** * Script custom import function * * @return void */ function custom_scripts() { // Splide slider wp_enqueue_script('Splide-script', get_theme_file_uri('/asset/splide/splide.min.js'), array('jquery'), '1.0', true); // Index.js wp_enqueue_script('home-script', get_theme_file_uri('/dist/js/index.js'), array('jquery'), '1.0', true); } /** * Add script action */ add_action('after_setup_theme', 'custom_scripts'); /** * Css custom import function * * @return void */ function enqueue_custom_styles() { // Main css wp_enqueue_style('main-style', get_theme_file_uri('/dist/css/style.css'), array(), '1.0', 'all'); // Font-awesome css wp_enqueue_style('font-awesome', get_theme_file_uri('/asset/font-awesome/css/all.min.css'), array(), '1.0', 'all'); // Splide css wp_enqueue_style('splide-slide', get_theme_file_uri('/asset/splide/splide.min.css'), array(), '1.0', 'all'); } /** * Add Css action */ add_action('after_setup_theme', 'enqueue_custom_styles'); /** * Add more field function * * @return void */ function add_field() { add_theme_support('post-thumbnails'); } /** * Add Field action */ add_action('after_setup_theme', 'add_field'); /** * Custom post type function * * @return void */ function custom_post_types() { // Partner register_post_type('partner', array ( 'has_archive' => true, 'rewrite' => array('slug' => 'partners'), 'public' => true, 'labels' => array( 'name' => 'Partners', ), 'menu_icon' => 'dashicons-businessman', 'supports' => array('title', 'excerpt', 'editor') )); // Invest register_post_type('investment', array ( 'has_archive' => false, 'public' => true, 'labels' => array( 'name' => 'investments', ), 'menu_icon' => 'dashicons-chart-line', 'supports' => array('title', 'editor') )); } /** * Custom post type action */ add_action( 'init', 'custom_post_types' ); ?>
// // TabBarPageView.dart // flutter_templet_project // // Created by shang on 10/22/21 5:03 PM. // Copyright © 10/22/21 shang. All rights reserved. // import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:tuple/tuple.dart'; /// TabBar + PageView class NTabPageView extends StatefulWidget { const NTabPageView({ Key? key, required this.items, this.labelColor, this.labelStyle, this.pageController, this.tabBgColor = Colors.white, this.tabController, this.initialIndex = 0, required this.onPageChanged, this.canPageChanged, this.isTabBottom = false, }) : super(key: key); final List<Tuple2<String, Widget>> items; /// tab背景颜色 final Color? tabBgColor; /// 标题和指示器颜色 final Color? labelColor; /// 字体样式 final TextStyle? labelStyle; /// PageView 控制器 final PageController? pageController; /// Tab 控制器 final TabController? tabController; /// 初始索引 final int initialIndex; /// 左右滑动回调 final ValueChanged<int> onPageChanged; /// 范围 false 时,锁定不在滚动 final bool Function(int)? canPageChanged; /// tab 位置底部 false 顶部, true 底部 final bool isTabBottom; @override _NTabPageViewState createState() => _NTabPageViewState(); } class _NTabPageViewState extends State<NTabPageView> with SingleTickerProviderStateMixin { late final _tabController = widget.tabController ?? TabController( initialIndex: widget.initialIndex, length: widget.items.length, vsync: this); late final _pageController = widget.pageController ?? PageController( initialPage: widget.initialIndex, keepPage: true); ///是否允许滚动 bool get canScrollable { final disable = (widget.canPageChanged?.call(_tabController.index) == false); return !disable; } @override void initState() { // _tabController = widget.tabController ?? TabController(length: widget.items.length, vsync: this); // _pageController = widget.pageController ?? PageController(initialPage: 0, keepPage: true); // ..addListener(() { // ddlog(_pageController.page); // }); super.initState(); } @override void dispose() { _tabController.dispose(); _pageController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var list = [ _buildTabBar(), _buildPageView(), ]; if (widget.isTabBottom) { list = list.reversed.toList(); } return Column( mainAxisSize: MainAxisSize.min, children: list, ); } Widget _buildTabBar() { final textColor = widget.labelColor ?? Theme .of(context) .colorScheme .primary; final borderSide = BorderSide( color: textColor, width: 2.0, ); var decorationTop = BoxDecoration( border: Border( top: borderSide, ), ); var decorationBom = BoxDecoration( border: Border( bottom: borderSide, ), ); final tabBar = TabBar( controller: _tabController, tabs: widget.items.map((e) => Tab(text: e.item1)).toList(), labelColor: textColor, labelStyle: widget.labelStyle, indicator: widget.isTabBottom ? decorationTop : decorationBom, onTap: (index) { _pageController.jumpToPage(index); setState(() {}); }, ); if (!canScrollable) { return IgnorePointer( child: tabBar, ); } // if (widget.isReverse) { // return tabBar; // } return Material( color: widget.tabBgColor, child: SafeArea( child: tabBar, ) ); } Widget _buildPageView() { return Expanded( child: PageView( controller: _pageController, physics: canScrollable ? BouncingScrollPhysics() : NeverScrollableScrollPhysics(), onPageChanged: (index) { widget.onPageChanged(index); _tabController.animateTo(index); setState(() {}); }, children: widget.items.map((e) => e.item2).toList(), )); } }
// // RealmDatabase.swift // LesHabituesTest // // Created by Frédéric Mallet on 30/03/2020. // Copyright © 2020 Frederic Mallet. All rights reserved. // import Foundation import Realm import RealmSwift import RxRealm import RxSwift public protocol Storable {} extension Object: Storable {} public enum DatabaseError: Error { case noDatabase case objectNotSaved } public enum ConfigurationType { case basic(url: String?) case inMemory(identifier: String?) var associated: String? { switch self { case .basic(let url): return url case .inMemory(let identifier): return identifier } } } public final class RealmDatabase: Database { private let configuration: ConfigurationType public init(configuration: ConfigurationType = .basic(url: nil)) throws { self.configuration = configuration } private func instantiateRealm() -> Realm? { var rmConfig = Realm.Configuration() switch configuration { case .basic: rmConfig = Realm.Configuration.defaultConfiguration if let url = configuration.associated { rmConfig.fileURL = NSURL(string: url) as URL? } case .inMemory: rmConfig = Realm.Configuration() if let identifier = configuration.associated { rmConfig.inMemoryIdentifier = identifier } } return try? Realm(configuration: rmConfig) } public func fetchObservable<T: Storable>(_ model: T.Type, predicate: NSPredicate?) -> Observable<[T]> { guard let realm = instantiateRealm(), let objectType = model as? Object.Type else { return Observable.empty() } var objects = realm.objects(objectType) if let predicate = predicate { objects = objects.filter(predicate) } return Observable.collection(from: objects).map {result in result.compactMap { $0 as? T } } } public func fetch<T: Storable>(_ model: T.Type, predicate: NSPredicate?) -> [T] { guard let realm = instantiateRealm(), let objectType = model as? Object.Type else { return [] } var objects = realm.objects(objectType) if let predicate = predicate { objects = objects.filter(predicate) } return objects.compactMap { $0 as? T } } public func remove<T: Storable>(object: T) throws { guard let realm = instantiateRealm() else { throw DatabaseError.objectNotSaved } do { try realm.write { // swiftlint:disable force_cast realm.delete(object as! Object) // swiftlint:enable force_cast } } catch { throw DatabaseError.objectNotSaved } } public func removeAll<T: Storable>(object: T.Type) throws { guard let realm = instantiateRealm() else { throw DatabaseError.objectNotSaved } do { // swiftlint:disable force_cast let allObjects = realm.objects(object.self as! Object.Type) // swiftlint:enable force_cast try realm.write { realm.delete(allObjects) } } catch { throw DatabaseError.objectNotSaved } } public func removeAll() throws { guard let realm = instantiateRealm() else { throw DatabaseError.noDatabase } do { try realm.write { realm.deleteAll() } } catch { throw DatabaseError.objectNotSaved } } public func save<T: Storable>(object: T) throws { guard let realm = instantiateRealm() else { throw DatabaseError.objectNotSaved } do { try realm.write { // swiftlint:disable force_cast realm.add(object as! Object, update: .all) // swiftlint:enable force_cast } } catch { throw DatabaseError.objectNotSaved } } public func save<T: Storable>(objects: [T]) throws { guard let realm = instantiateRealm() else { throw DatabaseError.objectNotSaved } do { try realm.write { // swiftlint:disable force_cast realm.add(objects as! [Object], update: .all) // swiftlint:enable force_cast } } catch { throw DatabaseError.objectNotSaved } } public func changeSet<T: Storable>(_ model: T.Type) -> Observable<(AnyRealmCollection<Object>, RealmChangeset?)> { guard let realm = instantiateRealm(), let objectType = model as? Object.Type else { return .never() } let objects = realm.objects(objectType) return Observable.changeset(from: objects) .filter { $1 != nil } } }
* Copyright 2020-2022 NXP * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <string.h> #include <arpa/inet.h> #include <stdio.h> #include <pthread.h> #include <signal.h> #include <stdint.h> #include <stddef.h> #include "fpp.h" #include "fpp_ext.h" #include "libfci.h" #include "demo_common.h" static pthread_t pthread_events_catching = {0}; static volatile sig_atomic_t events_catching_is_running = 0; /* * @brief Main function in the parallel events-processing thread. * @param[in] p_cl FCI client passed as (void*) according to create_thread() convention. * @return Always NULL. */ static void* events_catching(void* p_cl) { assert(NULL != p_cl); int tmp = 0; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &tmp); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &tmp); /* fci_catch is blocking "indefinitely". It will stop blocking only when the registered callback function (the one registered with fci_cb_register()) returns anything else than FCI_CB_CONTINUE. */ fci_catch((FCI_CLIENT*)(p_cl)); events_catching_is_running = 0; return NULL; } /* * @brief Check rtn value and print error text if (FPP_ERR_OK != rtn). * @param[in] rtn Current return value of a caller function. * @param[in] p_txt_error Text to be printed if (FPP_ERR_OK != rtn). */ void print_if_error(int rtn, const char* p_txt_error) { assert(NULL != p_txt_error); if (FPP_ERR_OK != rtn) { printf("ERROR (%d): %s\n", rtn, p_txt_error); } } /* * @brief Network-to-host (ntoh) function for enum datatypes. * @param[in,out] p_rtn Value which is to be converted to a host byte order. * @param[in] size Byte size of the value. */ void ntoh_enum(void* p_rtn, size_t size) { assert(NULL != p_rtn); switch (size) { case (sizeof(uint16_t)): *((uint16_t*)p_rtn) = ntohs(*((uint16_t*)p_rtn)); break; case (sizeof(uint32_t)): *((uint32_t*)p_rtn) = ntohl(*((uint32_t*)p_rtn)); break; default: /* do nothing ; 'uint8_t' falls into this category as well */ break; } } /* * @brief Host-to-network (hton) function for enum datatypes. * @param[in,out] p_rtn Value which is to be converted to a network byte order. * @param[in] size Byte size of the value. */ void hton_enum(void* p_rtn, size_t size) { assert(NULL != p_rtn); switch (size) { case (sizeof(uint16_t)): *((uint16_t*)p_rtn) = htons(*((uint16_t*)p_rtn)); break; case (sizeof(uint32_t)): *((uint32_t*)p_rtn) = htonl(*((uint32_t*)p_rtn)); break; default: /* do nothing ; 'uint8_t' falls into this category as well */ break; } } /* * @brief Check and set text. * @param[out] p_dst Destination text array (to be modified). * @param[in] p_src Source text array. * Can be NULL or empty (""). If NULL or empty, then * the destination text array is zeroed. * @param[in] dst_ln Size of the destination text array. * @return FPP_ERR_OK : Function executed successfully. * other : Some error occured (represented by the respective error code). */ int set_text(char* p_dst, const char* p_src, const uint16_t dst_ln) { assert(NULL != p_dst); assert(0u != dst_ln); /* 'p_src' is allowed to be NULL */ int rtn = FPP_ERR_INTERNAL_FAILURE; if ((NULL == p_src) || ('\0' == p_src[0])) { /* zeroify dst */ memset(p_dst, 0, dst_ln); rtn = FPP_ERR_OK; } else if ((strlen(p_src) + 1u) > dst_ln) { rtn = FPP_ERR_INTERNAL_FAILURE; /* src is too long */ } else { /* set dst */ strncpy(p_dst, p_src, dst_ln); rtn = FPP_ERR_OK; } return (rtn); } /* * @brief Lock the interface database of PFE for exclusive access by this FCI client. * @details The interface database is stored in PFE. * @param[in] p_cl FCI client * @return FPP_ERR_OK : Lock successful * other : Lock not successful */ int demo_if_session_lock(FCI_CLIENT* p_cl) { assert(NULL != p_cl); return fci_write(p_cl, FPP_CMD_IF_LOCK_SESSION, 0u, NULL); } /* * @brief Unlock exclusive access lock of the PFE's interface database. * @details The exclusive access lock can be unlocked only by a FCI client which * currently holds exclusive access to the interface database. * @param[in] p_cl FCI client * @param[in] rtn Current return value of a caller function. * @return If a caller function provides NON-ZERO rtn, then that rtn value is returned. * If a caller function provides ZERO rtn, then return values are: * FPP_ERR_OK : Unlock successful * other : Unlock not successful */ int demo_if_session_unlock(FCI_CLIENT* p_cl, int rtn) { assert(NULL != p_cl); int rtn_unlock = fci_write(p_cl, FPP_CMD_IF_UNLOCK_SESSION, 0u, NULL); rtn = ((FPP_ERR_OK == rtn) ? (rtn_unlock) : (rtn)); return (rtn); } /* * @brief Open connection to an FCI endpoint as a command-mode FCI client. * @details Command-mode client can configure PFE via the FCI endpoint by * issuing FCI commands. * @param[out] pp_rtn_cl Pointer to a newly created FCI client. * @return FPP_ERR_OK : New FCI client was successfully created. * other : Failed to create a FCI client. */ int demo_client_open_in_cmd_mode(FCI_CLIENT** pp_rtn_cl) { assert(NULL != pp_rtn_cl); int rtn = FPP_ERR_INTERNAL_FAILURE; FCI_CLIENT* p_cl = fci_open(FCI_CLIENT_DEFAULT, FCI_GROUP_NONE); if (NULL != p_cl) { *pp_rtn_cl = p_cl; rtn = FPP_ERR_OK; } return (rtn); } /* * @brief Close connection to a FCI endpoint and destroy the associated FCI client. * @param[in] p_cl The FCI client to be destroyed. * @return FPP_ERR_OK : The FCI client was successfully destroyed. * other : Failed to destroy the FCI client instance. */ int demo_client_close(FCI_CLIENT* p_cl) { assert(NULL != p_cl); return fci_close(p_cl); } /* * @brief Initialize a parallel thread for FCI events catching. * @details FCI events are sent by PFE driver to FCI clients. * Client must register a callback in order to receive FCI events. * @param[in] p_cl The FCI client * @param[in] p_cb_events Callback function which will be used to process caught FCI events. * @return FPP_ERR_OK : FCI callback was registered and parallel thread was started. * other : Some error occurred (represented by the respective error code). */ int demo_events_catching_init(FCI_CLIENT* p_cl, demo_events_cb_t p_cb_events) { assert(NULL != p_cl); assert(NULL != p_cb_events); int rtn = FPP_ERR_INTERNAL_FAILURE; /* this demo allows only one parallel thread for FCI events catching */ if (0 != events_catching_is_running) { rtn = FPP_ERR_INTERNAL_FAILURE; print_if_error(rtn, "demo_events_catching_init(): Some instance of the parallel " "thread for catching FCI events is already up and running.\n"); } else { events_catching_is_running = 1; rtn = FPP_ERR_OK; } /* register a callback function (to process caught FCI events) for target FCI client */ if (FPP_ERR_OK == rtn) { rtn = fci_register_cb(p_cl, p_cb_events); if (FPP_ERR_OK != rtn) { events_catching_is_running = 0; print_if_error(rtn, "demo_events_catching_init(): Failed to register a callback " "for processing of caught FCI events.\n"); } } /* create a parallel thread which hosts fci_catch() */ /* fci_catch() calls its registered callback function each time some FCI event is caught (arrives from PFE driver). */ if (FPP_ERR_OK == rtn) { rtn = pthread_create(&pthread_events_catching, NULL, &events_catching, p_cl); if (0 != rtn) { events_catching_is_running = 0; print_if_error(rtn, "demo_events_catching_init(): Failed to create a parallel " "thread for catching FCI events.\n"); } } return (rtn); } /* * @brief Stop and destroy the parallel thread for FCI events catching. * @param[in] p_cl The FCI client * @return FPP_ERR_OK : FCI callback was unregistered and parallel thread was stopped. * other : Some error occurred (represented by the respective error code). */ int demo_events_catching_fini(FCI_CLIENT* p_cl) { assert(NULL != p_cl); int rtn = FPP_ERR_INTERNAL_FAILURE; /* check that some parallel thread for FCI catching is currently running */ if (0 == events_catching_is_running) { rtn = FPP_ERR_INTERNAL_FAILURE; print_if_error(rtn, "demo_events_catching_fini(): No parallel thread for catching " "FCI events was detected.\n"); } else { rtn = FPP_ERR_OK; } /* no need to "unregister" callback function, it will be unregistered by fci_close() */ /* stop and destroy the parallel thread which hosts fci_catch() */ if (FPP_ERR_OK == rtn) { rtn = pthread_cancel(pthread_events_catching); if (0 != rtn) { print_if_error(rtn, "demo_events_catching_fini(): Failed to cancel the parallel " "thread for catching FCI events.\n"); } } if (FPP_ERR_OK == rtn) { rtn = pthread_join(pthread_events_catching, NULL); if (0 != rtn) { print_if_error(rtn, "demo_events_fini(): Failed to join the parallel thread " "for catching FCI events.\n"); } } /* if all OK, then signal that no parallel thread is currently running */ if (FPP_ERR_OK == rtn) { events_catching_is_running = 0; } return (rtn); }
<?php /** * Copyright 2021-2023 InPost S.A. * * NOTICE OF LICENSE * * Licensed under the EUPL-1.2 or later. * You may not use this work except in compliance with the Licence. * * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/software/page/eupl * It is also bundled with this package in the file LICENSE.txt * * Unless required by applicable law or agreed to in writing, * software distributed under the Licence is distributed on an AS IS basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions * and limitations under the Licence. * * @author InPost S.A. * @copyright 2021-2023 InPost S.A. * @license https://joinup.ec.europa.eu/software/page/eupl */ namespace InPost\Shipping\Api\Resource\Traits; use InPost\Shipping\Api\Resource\ApiResource; /** * @mixin ApiResource */ trait UpdateTrait { /** * Update an ApiResource by id using an array of attributes. * * @param int|string $id * @param array $attributes * @param array $options * * @return static */ public static function update($id, array $attributes, array $options = []) { $instance = static::cast(array_merge($attributes, [ static::getIdField() => $id, ])); return $instance->saveChanges($options); } /** * Update an ApiResource using the instance attributes. * * @param array $options * * @return $this */ public function saveChanges(array $options = []) { $response = $this->getRequestFactory() ->createRequest('PUT', static::getResourcePath()) ->setPathParams([static::getIdField() => $this->getId()]) ->setJson($this->toArray()) ->setOptions($options) ->send(); return $this->mergeAttributes(is_null($attributes = $response->json()) ? [] : $attributes); } }
import { BoxProps, Container, Typography, styled } from "@mui/material"; import { Box, Ratio, Image, Headline } from "@/components"; import { useMedia } from "@/hooks"; import { HERO_RATIO_DESKTOP, HERO_RATIO_MOBILE, HERO_RATIO_TABLET } from "@/constants"; interface Props { img: string; title: string; subTitle?: string; isHomePage?: boolean; ratio?: string; } interface WrapperBoxProps extends BoxProps { isHomePage: boolean; } export default function Hero({ title, img, isHomePage = false, ratio = "600/740", subTitle, }: Props) { const { isSmDown, isMdDown, isMdUp } = useMedia(); const size = isMdUp ? HERO_RATIO_DESKTOP : isMdDown ? HERO_RATIO_TABLET : HERO_RATIO_MOBILE; return ( <StyledContainer maxWidth="lg"> <Ratio ratio={size}> <Overlay className="overlay" /> {img && ( <Image src={img} alt="" style={{ objectFit: "cover", backgroundPosition: "center center" }} /> )} <Wrapper isHomePage={isHomePage}> <WrapperContent className="wrapperContent"> {isHomePage ? ( <Title variant="BungeeText">{title}</Title> ) : ( <Headline title={title} subTitle={subTitle} /> )} </WrapperContent> </Wrapper> </Ratio> </StyledContainer> ); } const Wrapper = styled(Container, { shouldForwardProp: (propName) => { return propName !== "isHomePage"; }, })<WrapperBoxProps>(({ isHomePage }) => { return { // position: "relative", display: isHomePage ? "flex" : "block", justifyContent: "center", }; }); const StyledContainer = styled(Container)(({ theme }) => { return { padding: "0 !important", [theme.breakpoints.down("xl")]: { padding: 0, }, }; }); const WrapperContent = styled(Box)(({ theme }) => { return { position: "absolute", top: "50%", zIndex: 2, transform: "translateY(-50%)", "& .MuiTypography-root": { color: theme.palette.common.white, }, }; }); const Title = styled(Typography)(({ theme }) => { return { width: "100%", margin: "0 auto", color: theme.palette.common.white, [theme.breakpoints.down("md")]: { padding: 0, textAlign: "center", fontSize: "48px", lineHeight: "57.6px", }, [theme.breakpoints.down("sm")]: { padding: 0, width: "80%", fontSize: "32px", lineHeight: "40px", }, }; }); const Overlay = styled(Box)(({ theme }) => { return { position: "absolute", top: 0, left: 0, bottom: 0, width: "100%", background: "rgba(0,0,0,0.4)", zIndex: 1, }; });
from typing import Dict, Union import base64 import html from langchain.chat_models import AzureChatOpenAI from langchain.schema import OutputParserException from langchain.chains import LLMChain from langchain.tools import BaseTool from langchain.prompts import PromptTemplate from langchain.agents import AgentExecutor, initialize_agent, AgentType from langchain.tools import BaseTool from langchain.utilities import BingSearchAPIWrapper try: from .prompts import (BING_PROMPT_PREFIX) except Exception as e: print(e) from prompts import (BING_PROMPT_PREFIX) def text_to_base64(text): # Convert text to bytes using UTF-8 encoding bytes_data = text.encode('utf-8') # Perform Base64 encoding base64_encoded = base64.b64encode(bytes_data) # Convert the result back to a UTF-8 string representation base64_text = base64_encoded.decode('utf-8') return base64_text def table_to_html(table): table_html = "<table>" rows = [sorted([cell for cell in table.cells if cell.row_index == i], key=lambda cell: cell.column_index) for i in range(table.row_count)] for row_cells in rows: table_html += "<tr>" for cell in row_cells: tag = "th" if (cell.kind == "columnHeader" or cell.kind == "rowHeader") else "td" cell_spans = "" if cell.column_span > 1: cell_spans += f" colSpan={cell.column_span}" if cell.row_span > 1: cell_spans += f" rowSpan={cell.row_span}" table_html += f"<{tag}{cell_spans}>{html.escape(cell.content)}</{tag}>" table_html +="</tr>" table_html += "</table>" return table_html # Returning the toekn limit based on model selection def model_tokens_limit(model: str) -> int: """Returns the number of tokens limits in a text model.""" if model == "gpt-35-turbo": token_limit = 4096 elif model == "gpt-4": token_limit = 8192 elif model == "gpt-35-turbo-16k": token_limit = 16384 elif model == "gpt-4-32k": token_limit = 32768 else: token_limit = 4096 return token_limit def run_agent(question:str, agent_chain: AgentExecutor) -> str: """Function to run the brain agent and deal with potential parsing errors""" for i in range(5): try: response = agent_chain.run(input=question) break except OutputParserException as e: # If the agent has a parsing error, we use OpenAI model again to reformat the error and give a good answer chatgpt_chain = LLMChain( llm=agent_chain.agent.llm_chain.llm, prompt=PromptTemplate(input_variables=["error"],template='Remove any json formating from the below text, also remove any portion that says someting similar this "Could not parse LLM output: ". Reformat your response in beautiful Markdown. Just give me the reformated text, nothing else.\n Text: {error}'), verbose=False ) response = chatgpt_chain.run(str(e)) continue return response ######## TOOL CLASSES ##################################### ########################################################### class BingSearchResults(BaseTool): """Tool for a Bing Search Wrapper""" name = "@bing" description = "useful when the questions includes the term: @bing.\n" k: int = 5 def _run(self, query: str) -> str: bing = BingSearchAPIWrapper(k=self.k) try: return bing.results(query,num_results=self.k) except: return "No Results Found" async def _arun(self, query: str) -> str: """Use the tool asynchronously.""" raise NotImplementedError("BingSearchResults does not support async") class BingSearchTool(BaseTool): """Tool for a Bing Search Wrapper""" name = "@bing" description = "useful when the questions includes the term: @bing.\n" llm: AzureChatOpenAI k: int = 5 def _run(self, tool_input: Union[str, Dict],) -> str: try: tools = [BingSearchResults(k=self.k)] parsed_input = self._parse_input(tool_input) agent_executor = initialize_agent(tools=tools, llm=self.llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, agent_kwargs={'prefix':BING_PROMPT_PREFIX}, callback_manager=self.callbacks, verbose=self.verbose) for i in range(2): try: response = run_agent(parsed_input, agent_executor) break except Exception as e: response = str(e) continue return response except Exception as e: print(e) async def _arun(self, query: str) -> str: """Use the tool asynchronously.""" raise NotImplementedError("BingSearchTool does not support async")
import { Box, Flex } from '@chakra-ui/react'; import useTimer from '@hooks/useTimer'; import { BigNumber } from 'ethers'; import React, { useEffect } from 'react'; import useCurrentBlock from '@hooks/useCurrentBlock'; interface TimerProps { expiryBlock: BigNumber; setExpiryStep: () => void; fontSize?: string; } export const Timer: React.FC<TimerProps> = ({ expiryBlock, setExpiryStep, fontSize = '30px' }) => { const { currentBlock, estimatedBlocksLeft, timerExpiry, isExpired } = useCurrentBlock(expiryBlock); const { seconds, minutes, start, restart } = useTimer({ expiry: timerExpiry || 0, onExpire: () => {}, }); useEffect(() => { start(); }, []); useEffect(() => { if (timerExpiry) { restart(timerExpiry); } }, [timerExpiry]); useEffect(() => { if (isExpired) { setExpiryStep(); } }, [isExpired]); if (currentBlock === null) { return null; } return ( <Flex flexDirection="column" justifyContent="flex-end" alignItems="center" style={{ fontSize: '16px', padding: 5 }} mb={5} > <Box style={{ fontSize, fontWeight: 'bold' }}> {minutes < 10 ? `0${minutes}` : minutes}:{seconds < 10 ? `0${seconds}` : seconds} Time Left </Box> <Box style={{ fontWeight: 'bold' }}> {estimatedBlocksLeft?.toString() || '--'} Blocks left - {currentBlock?.toNumber() || '--'}/ {expiryBlock?.toNumber() || '--'} </Box> <Box style={{ fontSize: '12px', fontStyle: 'italic' }}> *time remaining based on <span style={{ fontWeight: 'bold' }}>Estimates.</span> </Box> </Flex> ); };
/* 1.game里面加入了一个win的指针指向主窗口,主要要用的接口函数是a_text(),这个函数可以在主界面的日志栏里面输出一行文字,用法如下: win->a_text(QString::fromUtf8( "字符串写在这里,注意使用uft-8编码")); 还有void e_happen(int idx),这个函数用于表现突发事件,idx是时间编号,具体显示内容在event_.cpp里面修改,目前只添加了事件id是0\1的事件 2.目前游戏缺少bgm,如果要填充音乐的话,可以填充上几首,亟待推荐 3.游戏预计还会做两段演出放在游戏末尾,分别做失败动画和成功动画(如果有什么对于脚本/文案的建议那再好不过了) 4.游戏界面读取隔离人数利用int Game::getquarantine()直接读取了隔离人数,因此修改隔离人数会在界面上直接显示 5.学生满意度的结算目前似乎有一些bug 6.关于政策,我直接使用了建筑的policy,其中取building*=NULL,idx从10开始取(但是加入all——policy时还是从0开始加入的),依次是 10 全员核酸(我把这个政策做出来了,在class.cpp底下有) 11 科研专项 12 接种疫苗 13 推迟开学 14 视频会议 15 线上十佳 16 线上军训 17 防控宣讲 18 线上毕业 19 线上开学 20 线上晚会 21 开始网课 22 pf制 23 口罩令 24 管控舆论 25 接收树洞 26 志愿者 27 暂停参观 28 开始流调 29 常态核酸 30 场所码 7.game中新增了一项total_infection_likelyhood,影响总体传播速度,受到学生满意度(抵抗力)以及政策(例如全员核酸小幅增加感染概率)的影响 8.我还添加了编号为2的事件“第一次核酸检测”,因为这个事件只显示,没有任何实际做用,所以没有新增一个类,但要注意添加新的事件时idx要从3开始 */ #define _CRT_SECURE_NO_WARNINGS #include<time.h> #include<iostream> #include<cstring> #include<iomanip> #include<cmath> #include<list> #include<random> #include"class.h" using namespace std; random_device seed; ranlux48 engine(seed()); Game::Game() { time_t now_time; time(&now_time); tm* p = localtime(&now_time); year = p->tm_year + 1900; month = p->tm_mon + 1; yam=to_string(year)+"年 "+to_string(month)+"月"; day = p->tm_mday; hour = 0; overall_satisfaction = 90; activity_point = 0; sum_healthy_person = 40000; sum_ill_person = 0; sum_quarantine_person = 0; sum_building = 71; //all_building /*kind: 0 学生宿舍 1 食堂 2 教学楼 3 图书馆 4 校医院 5 操场 6 体育馆 7 未名湖 8 实验楼 9 学校校门 code: 0~44 45个宿舍(0~44) 45~50 食堂 45 农园 46 艺园 47 家园 48 勺园 49 学一 50 学五 51~57 教学楼 51 一教 52 二教 53 三教 54 四教 55 理教 56 文史 57 地学 58 图书馆 59 校医院 60 五四操场 61 五四体育馆 62 邱徳拔体育馆 63 未名湖 64 理科实验楼 65 东门 66 南门 67 西门 68 西南门 69 东南门 70 东北门 */ for (int i = 0; i < sum_building; i++) { if (i <= 44) { all_building[i] = new Dormitory(0, i, this); all_building[i]->setInitialPolicy(); } if (i >= 45 && i <= 50) { all_building[i] = new DiningHall(1, i, this); all_building[i]->setInitialPolicy(); } if (i >= 51 && i <= 57) { all_building[i] = new TeachingBuilding(2, i, this); all_building[i]->setInitialPolicy(); } if (i == 58) { all_building[i] = new Library(3, i, this); all_building[i]->setInitialPolicy(); } if (i == 59) { all_building[i] = new Hospital(4, i, this); all_building[i]->setInitialPolicy(); } if (i == 60) { all_building[i] = new Playground(5, i, this); all_building[i]->setInitialPolicy(); } if (i >= 61 && i <= 62) { all_building[i] = new Gymnasium(6, i, this); all_building[i]->setInitialPolicy(); } if (i == 63) { all_building[i] = new Lake(7, i, this); all_building[i]->setInitialPolicy(); } if (i == 64) { all_building[i] = new Laboratory(8, i, this); all_building[i]->setInitialPolicy(); } if (i >= 65 && i <= 70) { all_building[i] = new Gate(9, i, this); all_building[i]->setInitialPolicy(); } } for (int i = 0; i < 40000; i++) { all_person[i] = new Person(); double P; uniform_int_distribution<> int_distrib(0, 44); int temp_dormitory = int_distrib(engine); for (int j = 0; j <= 6; j++) { all_person[i]->track[j] = temp_dormitory; } uniform_int_distribution<> int_distrib1(45, 50); int temp_morning_dininghall = int_distrib1(engine); uniform_real_distribution<> real_distrib(0, 1); P = real_distrib(engine); if (P >= 0.5) { all_person[i]->track[7] = temp_morning_dininghall; } else { all_person[i]->track[7] = temp_dormitory; } uniform_int_distribution<> int_distrib2(51, 57); int temp_teachingbuilding1 = int_distrib2(engine); uniform_real_distribution<> real_distrib1(0, 1); P = real_distrib1(engine); for (int j = 8; j <= 9; j++) { if (0 <= P && P < 0.4) { all_person[i]->track[j] = temp_teachingbuilding1; } else if (0.4 <= P && P < 0.7) { all_person[i]->track[j] = temp_dormitory; } else if (0.7 <= P && P < 0.9) { all_person[i]->track[j] = 58; } else if (0.9 <= P && P <= 1.0) { all_person[i]->track[j] = 63; } } uniform_int_distribution<> int_distrib3(51, 57); int temp_teachingbuilding2 = int_distrib3(engine); uniform_int_distribution<> int_distrib4(45, 50); int temp_lunchbuilding1 = int_distrib4(engine); uniform_int_distribution<> int_distrib5(61, 62); int temp_gymnasium1 = int_distrib5(engine); uniform_real_distribution<> real_distrib2(0, 1); P = real_distrib2(engine); for (int j = 10; j <= 11; j++) { if (0 <= P && P < 0.4) { all_person[i]->track[j] = temp_teachingbuilding2; } else if (0.4 <= P && P < 0.6) { all_person[i]->track[j] = temp_dormitory; } else if (0.6 <= P && P < 0.75) { all_person[i]->track[j] = 58; } else if (0.75 <= P && P < 0.85) { all_person[i]->track[j] = temp_lunchbuilding1; } else if (0.85 <= P && P < 0.95) { all_person[i]->track[j] = 63; } else if (0.95 <= P && P <= 1.0) { all_person[i]->track[j] = temp_gymnasium1; } } uniform_int_distribution<> int_distrib6(45, 50); int temp_lunchbuilding2 = int_distrib6(engine); uniform_int_distribution<> int_distrib7(51, 57); int temp_teachingbuilding3 = int_distrib7(engine); uniform_int_distribution<> int_distrib8(61, 62); int temp_gymnasium2 = int_distrib8(engine); uniform_real_distribution<> real_distrib3(0, 1); P = real_distrib3(engine); if (0 <= P && P < 0.4) { all_person[i]->track[12] = temp_lunchbuilding2; } else if (0.4 <= P && P < 0.55) { all_person[i]->track[12] = temp_teachingbuilding3; } else if (0.55 <= P && P < 0.75) { all_person[i]->track[12] = temp_dormitory; } else if (0.75 <= P && P < 0.85) { all_person[i]->track[12] = 58; } else if (0.85 <= P && P < 0.97) { all_person[i]->track[12] = 63; } else if (0.97 <= P && P <= 1.0) { all_person[i]->track[12] = temp_gymnasium2; } uniform_int_distribution<> int_distrib9(51, 57); int temp_teachingbuilding4 = int_distrib9(engine); uniform_int_distribution<> int_distrib10(45, 50); int temp_lunchbuilding3 = int_distrib10(engine); uniform_int_distribution<> int_distrib11(61, 62); int temp_gymnasium3 = int_distrib11(engine); uniform_real_distribution<> real_distrib4(0, 1); P = real_distrib4(engine); for (int j = 13; j <= 14; j++) { if (0 <= P && P < 0.4) { all_person[i]->track[j] = temp_teachingbuilding4; } else if (0.4 <= P && P < 0.6) { all_person[i]->track[j] = 58; }//ͼ��� else if (0.6 <= P && P < 0.8) { all_person[i]->track[j] = temp_dormitory; } else if (0.8 <= P && P < 0.9) { all_person[i]->track[j] = temp_lunchbuilding3; } else if (0.9 <= P && P < 0.95) { all_person[i]->track[j] = 63; }//δ���� else if (0.95 <= P && P < 0.98) { all_person[i]->track[j] = temp_gymnasium3; } else if (0.98 <= P && P <= 1.0) { all_person[i]->track[j] = 60; }//�ٳ� } uniform_int_distribution<> int_distrib12(51, 57); int temp_teachingbuilding5 = int_distrib12(engine); uniform_int_distribution<> int_distrib13(45, 50); int temp_lunchbuilding4 = int_distrib13(engine); uniform_int_distribution<> int_distrib14(61, 62); int temp_gymnasium4 = int_distrib14(engine); uniform_real_distribution<> real_distrib5(0, 1); P = real_distrib5(engine); for (int j = 15; j <= 16; j++) { if (0 <= P && P < 0.4) { all_person[i]->track[j] = temp_teachingbuilding5; } else if (0.4 <= P && P < 0.6) { all_person[i]->track[j] = 58; }//ͼ��� else if (0.6 <= P && P < 0.8) { all_person[i]->track[j] = temp_dormitory; } else if (0.8 <= P && P < 0.9) { all_person[i]->track[j] = temp_lunchbuilding4; } else if (0.9 <= P && P < 0.95) { all_person[i]->track[j] = 63; }//δ���� else if (0.95 <= P && P < 0.98) { all_person[i]->track[j] = temp_gymnasium4; } else if (0.98 <= P && P <= 1.0) { all_person[i]->track[j] = 60; }//�ٳ� } uniform_int_distribution<> int_distrib15(51, 57); int temp_teachingbuilding6 = int_distrib15(engine); uniform_int_distribution<> int_distrib16(45, 50); int temp_supperbuilding1 = int_distrib16(engine); uniform_int_distribution<> int_distrib17(61, 62); int temp_gymnasium5 = int_distrib17(engine); uniform_real_distribution<> real_distrib6(0, 1); P = real_distrib6(engine); if (0 <= P && P < 0.45) { all_person[i]->track[17] = temp_supperbuilding1; } else if (0.45 <= P && P < 0.6) { all_person[i]->track[17] = temp_teachingbuilding6; } else if (0.6 <= P && P < 0.75) { all_person[i]->track[17] = 58; } else if (0.75 <= P && P < 0.9) { all_person[i]->track[17] = temp_dormitory; } else if (0.9 <= P && P < 0.95) { all_person[i]->track[17] = 60; } else if (0.95 <= P && P < 0.98) { all_person[i]->track[17] = 63; } else if (0.98 <= P && P <= 1.0) { all_person[i]->track[17] = temp_gymnasium5; } uniform_int_distribution<> int_distrib18(51, 57); int temp_teachingbuilding7 = int_distrib18(engine); uniform_int_distribution<> int_distrib19(45, 50); int temp_supperbuilding2 = int_distrib19(engine); uniform_int_distribution<> int_distrib20(61, 62); int temp_gymnasium6 = int_distrib20(engine); uniform_real_distribution<> real_distrib7(0, 1); P = real_distrib7(engine); if (0 <= P && P < 0.3) { all_person[i]->track[18] = temp_supperbuilding2; } else if (0.3 <= P && P < 0.5) { all_person[i]->track[18] = temp_teachingbuilding7; } else if (0.5 <= P && P < 0.7) { all_person[i]->track[18] = 58; } else if (0.7 <= P && P < 0.85) { all_person[i]->track[18] = temp_dormitory; } else if (0.85 <= P && P < 0.9) { all_person[i]->track[18] = 60; } else if (0.9 <= P && P < 0.95) { all_person[i]->track[18] = 63; } else if (0.95 <= P && P <= 1.0) { all_person[i]->track[18] = temp_gymnasium6; } uniform_int_distribution<> int_distrib21(51, 57); int temp_teachingbuilding8 = int_distrib21(engine); uniform_int_distribution<> int_distrib22(61, 62); int temp_gymnasium7 = int_distrib22(engine); uniform_real_distribution<> real_distrib8(0, 1); P = real_distrib8(engine); for (int j = 19; j <= 20; j++) { if (0 <= P && P < 0.4) { all_person[i]->track[j] = temp_teachingbuilding8; } else if (0.4 <= P && P < 0.6) { all_person[i]->track[j] = 58; } else if (0.6 <= P && P < 0.8) { all_person[i]->track[j] = temp_dormitory; } else if (0.8 <= P && P < 0.86) { all_person[i]->track[j] = 60; } else if (0.86 <= P && P < 0.93) { all_person[i]->track[j] = 63; } else if (0.93 <= P && P <= 1.0) { all_person[i]->track[j] = temp_gymnasium7; } } uniform_int_distribution<> int_distrib23(51, 57); int temp_teachingbuilding9 = int_distrib23(engine); uniform_int_distribution<> int_distrib24(61, 62); int temp_gymnasium8 = int_distrib24(engine); uniform_real_distribution<> real_distrib9(0, 1); P = real_distrib9(engine); if (0 <= P && P < 0.2) { all_person[i]->track[21] = temp_teachingbuilding9; } else if (0.2 <= P && P < 0.6) { all_person[i]->track[21] = temp_dormitory; } else if (0.6 <= P && P < 0.68) { all_person[i]->track[21] = 60; } else if (0.68 <= P && P < 0.76) { all_person[i]->track[21] = 63; } else if (0.76 <= P && P < 0.85) { all_person[i]->track[21] = temp_gymnasium8; } else if (0.85 <= P && P <= 1.0) { all_person[i]->track[21] = 58; } uniform_int_distribution<> int_distrib25(51, 57); int temp_teachingbuilding10 = int_distrib25(engine); uniform_int_distribution<> int_distrib26(61, 62); int temp_gymnasium9 = int_distrib26(engine); uniform_real_distribution<> real_distrib10(0, 1); P = real_distrib10(engine); if (0 <= P && P < 0.1) { all_person[i]->track[22] = 63; } else if (0.1 <= P && P < 0.17) { all_person[i]->track[22] = temp_gymnasium9; } else if (0.17 <= P && P < 0.67) { all_person[i]->track[22] = temp_dormitory; } else if (0.67 <= P && P < 0.82) { all_person[i]->track[22] = 58; } else if (0.82 <= P && P < 0.92) { all_person[i]->track[22] = temp_teachingbuilding10; } else if (0.92 <= P && P <= 1.0) { all_person[i]->track[22] = 60; } uniform_real_distribution<> real_distrib11(0, 1); P = real_distrib11(engine); if (0 <= P && P < 0.95) { all_person[i]->track[23] = temp_dormitory; } else if (0.95 <= P && P <= 1.0) { all_person[i]->track[23] = 63; } } //All policys all_policy[0]=new Do_pcr(10,10,this); all_policy[1]=new ResearchOnVirus(11,500,this,NULL); all_policy[2]=new SuspendCampusTour(12,100,this,NULL); all_policy[3]=new PostponeStartOfSchool(13,200,this,NULL); all_policy[4]=new ProvideDesktopVideo(14,300,this,NULL); all_policy[5]=new StartOnlineCourse(15,300,this,NULL); all_policy[6]=new StartPF(16,50,this,NULL); } int Game::getdate() { return day; } int Game::getap() { return activity_point; } int Game::getsat() { return overall_satisfaction; } int Game::getill() { return sum_ill_person; } void Game::pcr() { ifpcr=true; } bool Game::getpcr_state() { return ifpcr; } void Game::startResearchOnVirus() { ifResearchOnVirusStart = true; } bool Game::getResearchOnVirus_state() { return ifResearchOnVirusStart; } void Game::suspendCampusTour() { campusTour_state = true; } bool Game::getCampusTour_state() { return campusTour_state; } void Game::postponeStartOfSchool() { postponeStartOfSchool_state = true; } bool Game::getPostponeStartOfschool_state() { return postponeStartOfSchool_state; } void Game::provideDesktopVideo() { provideDesktopVideo_state = true; } bool Game::getProvideDesktopVideo() { return provideDesktopVideo_state; } void Game::startOnlineCourse() { onlineCourse_state = true; } bool Game::getOnlineCourse_state() { return onlineCourse_state; } void Game::startPF() { PF_state = true; } bool Game::getPF_state() { return PF_state; } Building* Game::getBuilding(int building_id) { return all_building[building_id]; } bool Game::cost_ap(int t){ if(activity_point<t) return false; else { activity_point-=t; win->showap(); return true; } } void Game::gameRun() { activity_point = 0; overall_satisfaction = 90; uniform_int_distribution<> fucking(0, 40000); int intitial_infected_idx = fucking(engine); all_person[intitial_infected_idx]->health_state = 1; sum_healthy_person--; sum_ill_person++; } int Game::start_newday() { if (is_building_shut_down) updateTrack(); if (ifResearchOnVirusStart) { if (ifResearchOnVirusDone) { //遍历所有人,治愈1000个人,病人不足1000个则全部治愈 int cnt = 0; for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { if (all_person[i]->health_state == 1) { all_person[i]->health_state = 0; sum_healthy_person++; sum_ill_person--; cnt++; } if (cnt == 1000) { break; } } } else { researchOnVirusSchedule-=2; if (researchOnVirusSchedule == 0) { ifResearchOnVirusDone = true; win->a_text(QString::fromUtf8( "科研专项已经完成,我们终将要战胜病毒!即日起患者康复率大幅提升")); } } } startSpread(); startQuarantine(); updateAllSatisfaction(); //cout << "总健康人数:" << sum_healthy_person << ' ' << "总感染人数:" << sum_ill_person << ' ' << "总隔离人数:" << sum_quarantine_person << endl; int temp_satisfaction = 0; int temp_total_person = 0; for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { temp_satisfaction += all_person[i]->satisfaction; temp_total_person++; } overall_satisfaction = temp_satisfaction * 1.0 / temp_total_person; total_infection_likelyhood=0.00005*(100-overall_satisfaction);//满意度改变全局感染概率 for (int i = 0; i < sum_building; i++) { activity_point += all_building[i]->produceActionPoint(); } nextDay(); yam=to_string(year)+"年 "+to_string(month)+"月"; ifpcr=false; qDebug()<<sum_quarantine_person; win->showitems(); for (int building_index = 0; building_index < sum_building; building_index++) all_building[building_index]->checkAffairHappen(); if(gameLose()) return -1; else if(gameWin()) return 1; else return 0; } void Game::save(int i)//用于实现存档功能,把所有游戏有关参数全部写入i号文件中并保存(i>=0&&i<=2) { QFile file(QString::fromUtf8("save"+to_string(i)+".txt")); //如果i号文件已经存在,则删除 if(file.exists()) { file.remove(); } qDebug()<<"A"; file.open(QIODevice::WriteOnly); QTextStream out(&file); time_t now; time(&now); tm* tep = localtime(&now); out<<tep->tm_year + 1900<<'\n'; out<<tep->tm_mon + 1<<'\n'; out<<tep->tm_mday<<'\n'; out<<tep->tm_hour<<'\n'; out<<tep->tm_min<<'\n'; out<<year<<'\n'; out<<month<<'\n'; out<<day<<'\n'; out<<sum_building<<'\n'; out<<sum_healthy_person<<'\n'; out<<sum_ill_person<<'\n'; out<<sum_quarantine_person<<'\n'; out<<overall_satisfaction<<'\n'; out<<activity_point<<'\n'; out<<total_infection_likelyhood<<'\n'; out<<ifResearchOnVirusStart<<'\n'; out<<ifResearchOnVirusDone<<'\n'; out<<researchOnVirusSchedule<<'\n'; out<<is_building_shut_down<<'\n'; out<<ifpcr<<'\n'; //此外还有政策相关的状态需要存储 out<<this->campusTour_state<<'\n'; out<<this->PF_state<<'\n'; out<<this->provideDesktopVideo_state<<'\n'; out<<this->onlineCourse_state<<'\n'; qDebug()<<"B"; //还应该存储building相关的状态以及people相关的状态和people的track for(int i=0;i<40000;++i) { out<<all_person[i]->health_state<<'\n'; out<<all_person[i]->satisfaction<<'\n'; out<<all_person[i]->quarantine_day<<'\n'; for(int j=0;j<24;++j) { out<<all_person[i]->track[j]<<'\n'; } } qDebug()<<"C"; //下面存储building相关的状态 /* int level; Policy* available_policy[10]; int policy_state[10]; int kind; int idx; int action_point_per_day; int total_number_of_available; bool is_shut_down; int total_people; int total_infectd_people; int upgrade_cost[3]; Person* people_in_building[40000];*/ //运行下面这个循环的时候程序崩溃了 //可能是因为all_building[i]->people_in_building[j]中的people_in_building[j]为空指针 //应做的修改是 for(int i=0;i<=70;++i) { out<<all_building[i]->level<<'\n'; for(int j=0;j<10;++j) { out<<all_building[i]->policy_state[j]<<'\n'; } out<<all_building[i]->kind<<'\n'; out<<all_building[i]->idx<<'\n'; out<<all_building[i]->action_point_per_day<<'\n'; out<<all_building[i]->total_number_of_available<<'\n'; out<<all_building[i]->is_shut_down<<'\n'; out<<all_building[i]->total_people<<'\n'; out<<all_building[i]->total_infectd_people<<'\n'; for(int j=0;j<3;++j) { out<<all_building[i]->upgrade_cost[j]<<'\n'; } for(int j=0;j<all_building[i]->total_people;++j) { out<<all_building[i]->people_in_building[j]->health_state<<'\n'; out<<all_building[i]->people_in_building[j]->satisfaction<<'\n'; out<<all_building[i]->people_in_building[j]->quarantine_day<<'\n'; for(int k=0;k<24;++k) { out<<all_building[i]->people_in_building[j]->track[k]<<'\n'; } } out<<all_building[i]->change_in_infection_likelihood<<'\n'; } qDebug()<<"D"; //这里就结束了 file.close(); } void Game::load(int i) { //依据存档规则反向进行读档 QFile file(QString::fromUtf8("save"+to_string(i)+".txt")); if(!file.exists()) { return; } file.open(QIODevice::ReadOnly); QTextStream in(&file); int temp; in>>temp; in>>temp; in>>temp; in>>temp; in>>temp; in>>year; in>>month; in>>day; in>>sum_building; in>>sum_healthy_person; in>>sum_ill_person; in>>sum_quarantine_person; in>>overall_satisfaction; in>>activity_point; in>>total_infection_likelyhood; int tep; in>>tep; ifResearchOnVirusStart=tep; in>>tep; ifResearchOnVirusDone=tep; in>>researchOnVirusSchedule; in>>tep; is_building_shut_down=tep; in>>tep; ifpcr=tep; //这里需要根据save补充一点内容 in>>tep; this->campusTour_state=tep; in>>tep; this->PF_state=tep; in>>tep; this->provideDesktopVideo_state=tep; in>>tep; this->onlineCourse_state=tep; //还应该读取building相关的状态以及people相关的状态和people的track for(int i=0;i<40000;++i) { in>>all_person[i]->health_state; in>>all_person[i]->satisfaction; in>>all_person[i]->quarantine_day; for(int j=0;j<24;++j) { in>>all_person[i]->track[j]; } } //下面读取building相关的状态 for(int i=0;i<=70;++i) { in>>all_building[i]->level; for(int j=0;j<10;++j) { in>>all_building[i]->policy_state[j]; } in>>all_building[i]->kind; in>>all_building[i]->idx; in>>all_building[i]->action_point_per_day; in>>all_building[i]->total_number_of_available; in>>tep; all_building[i]->is_shut_down=tep; in>>all_building[i]->total_people; in>>all_building[i]->total_infectd_people; for(int j=0;j<3;++j) { in>>all_building[i]->upgrade_cost[j]; } for(int j=0;j<all_building[i]->total_people;++j) { in>>all_building[i]->people_in_building[j]->health_state; in>>all_building[i]->people_in_building[j]->satisfaction; in>>all_building[i]->people_in_building[j]->quarantine_day; for(int k=0;k<24;++k) { in>>all_building[i]->people_in_building[j]->track[k]; } } in>>all_building[i]->change_in_infection_likelihood; } file.close(); } bool Game::gameEnd() { if (gameWin()) cout << "win!" << endl; if (gameLose()) cout << "lose!" << endl; return gameWin() || gameLose(); } bool Game::gameWin() { bool ret = true; for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { if (all_person[i]->health_state == 1) { ret = false; } } if (sum_healthy_person == 0) { ret = false; } return ret; } bool Game::gameLose() { int ret = 0; for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { if (all_person[i]->health_state == 0) { ++ret; } } if(ret>=200) return false; return true; } Policy* Game::get_policy(int i) { return all_policy[i]; } void Game::startSpread() { int new_infected = 0; for (int h = 0; h < 24; h++) { for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { if (all_person[i]->health_state == 2) continue; all_building[all_person[i]->track[h]]->peopleArrived(1, all_person[i]); if (all_person[i]->health_state == 1) all_building[all_person[i]->track[h]]->infectedPeopleArrived(1); } for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { if (all_person[i]->health_state == 2 || all_person[i]->health_state == 1) continue; Building* this_building = all_building[all_person[i]->track[h]]; double p = this_building->change_in_infection_likelihood+total_infection_likelyhood; if(ifpcr) p+=0.00003; int tot = this_building->getInfectedNumber(); if (tot == 0) p = 0; else if (1 <= tot && tot <= 50) p += 0.0001; else if (51 <= tot && tot <= 100) p += 0.0003; else if (101 <= tot && tot <= 200) p += 0.0005; else if (201 <= tot && tot <= 300) p += 0.0007; else if (301 <= tot && tot <= 500) p += 0.002; else if (501 <= tot && tot <= 1000) p += 0.005; else p += 0.007; uniform_real_distribution<> real_distub(0, 1); double rand_p = real_distub(engine); if (rand_p <= p) { all_person[i]->is_now_infected = true; sum_ill_person++; sum_healthy_person--; new_infected++; } } //printf("in %d o'clock, %d people was infected.\n", h, new_infected); for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { if (all_person[i]->health_state == 2) continue; all_building[all_person[i]->track[h]]->peopleArrived(-1, all_person[i]); if (all_person[i]->health_state == 1) all_building[all_person[i]->track[h]]->infectedPeopleArrived(-1); if (all_person[i]->is_now_infected) { all_person[i]->health_state = 1; all_person[i]->is_now_infected = false; } } } if(ifpcr) { win->a_text(QString::fromUtf8( "昨日新增")+QString::fromUtf8(to_string(new_infected))+QString::fromUtf8("人感染")); } } void Game::startQuarantine() { // 开始进行隔离 double p = 0.01; if(ifpcr) p+=0.04; if(ifResearchOnVirusDone) p+=0.1; int cnt=0,cnt1=0; // 不必修改被隔离的人的轨迹,因为在开始传播里面会直接避免他们乱奔跑 for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { if (ifResearchOnVirusDone&&all_person[i]->health_state == 2) { all_person[i]->quarantine_day++; if (all_person[i]->quarantine_day >= 14) { all_person[i]->health_state = 0; sum_quarantine_person--; sum_healthy_person++; cnt1++; } continue; } if (all_person[i]->health_state == 0||all_person[i]->health_state == 2) continue; uniform_real_distribution<> real_distub(0, 1); double rand_p = real_distub(engine); if (rand_p <= p) { all_person[i]->health_state = 2; sum_quarantine_person++; sum_ill_person--; cnt++; } } if(cnt!=0&&cnt1!=0) win->a_text(QString::fromUtf8( "昨日有")+QString::fromUtf8(to_string(cnt))+QString::fromUtf8("名感染者被隔离") +QString::fromUtf8( " 有")+QString::fromUtf8(to_string(cnt1))+QString::fromUtf8("名隔离患者康复")); else if(cnt!=0&&cnt1==0) win->a_text(QString::fromUtf8( "昨日有")+QString::fromUtf8(to_string(cnt))+QString::fromUtf8("名感染者被隔离")); } void Game::updateAllSatisfaction() { // 如果被感染了,每天满意度掉0.5 // 如果被隔离了,每天满意度再掉0.4 // 如果康复了,每天满意度0.5 for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { if (all_person[i]->health_state == 1) { all_person[i]->satisfaction -= 0.5; } else if (all_person[i]->health_state == 2) { all_person[i]->satisfaction -= 0.9; } else { all_person[i]->satisfaction += 0.5; } } } void Game::nextDay() { int this_month_days = 30; if (month == 4 || month == 6 || month == 9 || month == 1) this_month_days = 30; else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) this_month_days = 31; else { if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) this_month_days = 29; else this_month_days = 28; } day++; if (day >= this_month_days) { day = 1; month++; if (month >= 12) { month = 1; year++; } } } void Game::updateTrack() { for (int i = 0; i < sum_healthy_person + sum_ill_person + sum_quarantine_person; i++) { int before_idx = all_person[i]->track[0]; for (int h = 0; h < 24; h++) { if (all_building[all_person[i]->track[h]]->isDormitoryShutDown()) { int idx = all_person[i]->track[h]; for (int h_hat = 0; h_hat < 24; h_hat++) { all_person[i]->track[h_hat] = idx; } break; } else if (all_building[all_person[i]->track[h]]->isShutDown()) { all_person[i]->track[h] = before_idx; } else { before_idx = all_person[i]->track[h]; } } } } int Game::getquarantine() { return sum_quarantine_person; } int Game::getSeason() { if (month == 3 || month == 4 || month == 5) return 1; else if (month == 6 || month == 7 || month == 8) return 2; else if (month == 9 || month == 10 || month == 11) return 3; else return 4; } Person::Person() { satisfaction = 90; health_state = 0; quarantine_day = 0; is_now_infected = false; memset(track, -1, sizeof(track)); } void Person::updateSatisfaction(double delta) { satisfaction += delta; } double Person::getSatisfaction() { return satisfaction; } Building::Building(int _kind, int _idx, Game* _g) :g(_g) { total_number_of_available = 0; memset(policy_state, 0, sizeof(policy_state)); level = 1; kind = _kind; idx = _idx; change_in_infection_likelihood = 0; action_point_per_day = 0; upgrade_cost[1] = 10; upgrade_cost[2] = 20; is_shut_down = false; total_people = 0; total_infectd_people = 0; } void Building::upgrade() { level++; for (int i = 0; i < total_number_of_available; i++) { if (policy_state[i] == 0 && available_policy[i]->available()) policy_state[i] = 1; } if(kind==0) updateActionPoint(2); updateChange(-0.00003); } void Building::enactPolcy(int policy_idx) { policy_state[policy_idx] = 2; available_policy[policy_idx]->takeEffect(); } int Building::produceActionPoint() { return action_point_per_day; } void Building::updateChange(double delta) { change_in_infection_likelihood += delta; } void Building::updateActionPoint(int delta) { action_point_per_day += delta; } void Building::shutDown() { try { if (is_shut_down == true) throw -1; } catch (int e) { } is_shut_down = true; } bool Building::isShutDown() { return is_shut_down; } void Building::addPolicy(Policy* p) { available_policy[total_number_of_available] = p; total_number_of_available++; } void Building::updatePolicyState() { memset(policy_state, 0, sizeof(policy_state)); for (int i = 0; i < total_number_of_available; i++) { if (policy_state[i] == 0 && available_policy[i]->available()) policy_state[i] = 1; } } void Building::setInitialPolicy() { addPolicy(new RequireMasks(0, 10, this)); addPolicy(new MeasureTemperatureAndScanCode(1, 20, this)); addPolicy(new ShutDownBuilding(2, 30, this)); updatePolicyState(); } void Building::peopleArrived(int delta, Person* p) { if (delta >= 1) { people_in_building[total_people] = p; } else people_in_building[total_people] = NULL; total_people += delta; } int Building::getLevel() { return level; } int Building::getkind() { return kind; } int Building::getaction_point_per_day() {return action_point_per_day;} int Building::getInfectedNumber() { return total_infectd_people; } int Building::getTotalNumber() { return total_people; } void Building::infectedPeopleArrived(int delta) { total_infectd_people += delta; } void Building::addBaffle() { } void Building::checkAffairHappen() { } void Building::updateSatisfaction(double delta) { for (int i = 0; i < total_people; i++) { people_in_building[i]->updateSatisfaction(delta); } } bool Building::isDormitoryShutDown() { if (kind == 0 && is_shut_down) return true; return false; } bool Building::isWinter() { return g->getSeason() == 4; } double Building::getSatisfaction() { // 得到这个建筑里的总的满意度 double sum = 0; for (int i = 0; i < total_people; i++) { sum += people_in_building[i]->getSatisfaction(); } return sum / (total_people + 1); // 万一只有0个人就崩溃了 } void DiningHall::setInitialPolicy() { addPolicy(new AddBaffle(3, 20, this)); addPolicy(new RequireMasks(0, 20, this)); addPolicy(new MeasureTemperatureAndScanCode(1, 30, this)); addPolicy(new StopDineIn(4, 40, this)); updatePolicyState(); } DiningHall::DiningHall(int _idx, int _kind, Game* _g) : Building(_idx, _kind,_g) { possible_affairs[0] = new NastyMeals(4, 0.001, this); possible_affairs[1] = new Gathering(10, 0.001, this); possible_affairs[2] = new ProtesetInShudong(11, 0.01, this); possible_affairs[3] = new BrokenOutPersonnel(21, 0.01, this); num_of_possible_affairs = 4; added_baffle = false; updateActionPoint(1); } void DiningHall::addBaffle() { added_baffle = true; } void DiningHall::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } TeachingBuilding::TeachingBuilding(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { updateActionPoint(1); possible_affairs[0] = new ProtesetInShudong(11, 0.03, this); possible_affairs[1] = new BrokenOutPersonnel(21, 0.03, this); num_of_possible_affairs = 2; } void TeachingBuilding::setInitialPolicy() { addPolicy(new RequireMasks(0, 20, this)); addPolicy(new MeasureTemperatureAndScanCode(1, 30, this)); addPolicy(new ShutDownBuilding(2, 40, this)); updatePolicyState(); } void TeachingBuilding::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Lake::Lake(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { possible_affairs[0] = new CoupleByLake(0, 0.03, this); possible_affairs[1] = new ReadByLake(1, 0.03, this); possible_affairs[2] = new ProtesetInShudong(11, 0.03, this); number_of_possible_affairs = 3; } void Lake::checkAffairHappen() { for (int i = 0; i < number_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Gymnasium::Gymnasium(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { updateActionPoint(1); possible_affairs[0] = new ProtesetInShudong(11, 0.001, this); possible_affairs[1] = new Top10(26, 0.04, this); num_of_possible_affairs = 2; } void Gymnasium::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Playground::Playground(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { updateActionPoint(1); possible_affairs[0] = new ProtesetInShudong(11, 0.04, this); num_of_possible_affairs = 1; } void Playground::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Library::Library(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { possible_affairs[0] = new OnlineExhibition(2, 0.001, this); possible_affairs[1] = new ProtesetInShudong(11, 0.001, this); possible_affairs[2] = new BrokenOutPersonnel(21, 0.001, this); num_of_possible_affairs = 3; updateActionPoint(5); } void Library::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Gate::Gate(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { possible_affairs[0] = new Detention(25, 0.001, this); num_of_possible_affairs = 1; } void Gate::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Laboratory::Laboratory(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { updateActionPoint(5); possible_affairs[0] = new ProtesetInShudong(11, 0.03, this); num_of_possible_affairs = 1; } void Laboratory::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Hospital::Hospital(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { updateActionPoint(-5); // 维持医院需要消耗行动点 possible_affairs[0] = new LuxuriousIsolationConditions(5, 0.02, this); possible_affairs[1] = new InterestingQuarantineLife(6, 0.02, this); possible_affairs[2] = new ProtesetInShudong(11, 0.02, this); possible_affairs[3] = new BrokenOutPersonnel(21, 0.02, this); possible_affairs[4] = new VolunteerLack(22, 0.02, this); possible_affairs[5] = new LackOfMedicalResources(23, 0.02, this); possible_affairs[6] = new GreatPrevention(24, 0.02, this); num_of_possible_affairs = 7; } void Hospital::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Dormitory::Dormitory(int _idx, int _kind, Game* _g) : Building(_idx, _kind, _g) { } void Dormitory::setInitialPolicy() { addPolicy(new RequireMasks(0, 20, this)); addPolicy(new TemporaryLockdown(5, 30, this)); addPolicy(new ShutDownDormitory(6, 40, this)); updatePolicyState(); possible_affairs[0] = new BrokenWashingMachine(7, 0.0006, this); possible_affairs[1] = new BrokenAirConditioner(8, 0.0006, this); possible_affairs[2] = new BrokenWaterHeater(9, 0.0006, this); possible_affairs[3] = new ProtesetInShudong(11, 0.0006, this); possible_affairs[4] = new SingInDormitory(12, 0.0006, this); possible_affairs[5] = new ShushuBegins(13, 0.0006, this); possible_affairs[6] = new QuarrelInDormitory(14, 0.0006, this); possible_affairs[7] = new UnbearableSnoring(15, 0.0006, this); possible_affairs[8] = new Top10InBathroom(16, 0.0006, this); possible_affairs[9] = new LearningInDormitory(17, 0.0006, this); possible_affairs[10] = new MahjongInDormitory(18, 0.0006, this); possible_affairs[11] = new HarmoniousDormitory(19, 0.0006, this); possible_affairs[12] = new HealthySleeping(20, 0.0006, this); possible_affairs[13] = new BrokenHeater(27, 0.0006, this); num_of_possible_affairs = 14; } void Dormitory::checkAffairHappen() { for (int i = 0; i < num_of_possible_affairs; i++) { possible_affairs[i]->happen(); } } Building* Policy::BuildingAttached() { return building_attached; } Policy::Policy(int _idx, int _cost, Building* _b) { idx = _idx; cost = _cost; building_attached = _b; } void Policy::takeEffect() { } void Policy::printPolicy() { } bool Policy::available() { return true; } RequireMasks::RequireMasks(int _idx, int _cost, Building* _b) : Policy(_idx, _cost, _b) { } void RequireMasks::takeEffect() { BuildingAttached()->updateChange(-0.00003); BuildingAttached()->updateActionPoint(1); } bool RequireMasks::available() { if (BuildingAttached()->getLevel() >= 1) return true; return false; } void RequireMasks::printPolicy() { } MeasureTemperatureAndScanCode::MeasureTemperatureAndScanCode(int _idx, int _cost, Building* _b) : Policy(_idx, _cost, _b) { } void MeasureTemperatureAndScanCode::takeEffect() { BuildingAttached()->updateChange(-0.00002); BuildingAttached()->updateActionPoint(2); } bool MeasureTemperatureAndScanCode::available() { if (BuildingAttached()->getLevel() >= 2) return true; return false; } void MeasureTemperatureAndScanCode::printPolicy() { } ShutDownBuilding::ShutDownBuilding(int _idx, int _cost, Building* _b) : Policy(_idx, _cost, _b) { } void ShutDownBuilding::takeEffect() { BuildingAttached()->updateChange(-0.00005); BuildingAttached()->updateActionPoint(3); BuildingAttached()->shutDown(); } bool ShutDownBuilding::available() { if (BuildingAttached()->getLevel() >= 3) return true; return false; } void ShutDownBuilding::printPolicy() { } AddBaffle::AddBaffle(int _idx, int _cost, Building* _b) : Policy(_idx, _cost, _b) { } void AddBaffle::takeEffect() { BuildingAttached()->updateChange(-0.0001); BuildingAttached()->updateActionPoint(1); BuildingAttached()->addBaffle(); } bool AddBaffle::available() { if (BuildingAttached()->getLevel() >= 1) return true; return false; } void AddBaffle::printPolicy() { } StopDineIn::StopDineIn(int _idx, int _kind, Building* _b) : Policy(_idx, _kind, _b) { } void StopDineIn::takeEffect() { BuildingAttached()->updateChange(-0.00003); BuildingAttached()->updateActionPoint(3); BuildingAttached()->shutDown(); } bool StopDineIn::available() { if (BuildingAttached()->getLevel() >= 3) return true; return false; } void StopDineIn::printPolicy() { } TemporaryLockdown::TemporaryLockdown(int _idx, int _kind, Building* _b) : Policy(_idx, _kind, _b) { } void TemporaryLockdown::takeEffect() { BuildingAttached()->updateChange(-0.00003); BuildingAttached()->updateActionPoint(2); } bool TemporaryLockdown::available() { if (BuildingAttached()->getLevel() >= 2) return true; return false; } void TemporaryLockdown::printPolicy() { } ShutDownDormitory::ShutDownDormitory(int _idx, int _kind, Building* _b) : Policy(_idx, _kind, _b) { } void ShutDownDormitory::takeEffect() { BuildingAttached()->updateChange(0.00002); BuildingAttached()->updateActionPoint(-2); BuildingAttached()->shutDown(); } bool ShutDownDormitory::available() { if (BuildingAttached()->getLevel() >= 3) return true; return false; } void ShutDownDormitory::printPolicy() { } Do_pcr::Do_pcr(int _idx, int _kind,Game* game, Building* _b) : Policy(_idx, _kind, _b),g(game) { } void Do_pcr::takeEffect() { g->pcr(); g->cost_ap(cost); printPolicy(); } bool Do_pcr::available() { if (g->getpcr_state())//每天只能颁布一次 return false; else return true; } void Do_pcr::printPolicy() { g->win->a_text(QString::fromUtf8( "进行了全员核酸检测,希望不要有太多新增病例")); if(ever_done==false) { ever_done=true; g->win->e_happen(2); } } ResearchOnVirus::ResearchOnVirus(int _idx, int _kind, Game* game, Building* _b) :Policy(_idx, _kind, _b), g(game) {} void ResearchOnVirus::takeEffect() { g->startResearchOnVirus(); g->cost_ap(cost); printPolicy(); } bool ResearchOnVirus::available() { return !g->getResearchOnVirus_state(); } void ResearchOnVirus::printPolicy() { g->win->a_text(QString::fromUtf8( "开始进行科研专项,这是和病毒在赛跑!")); } SuspendCampusTour::SuspendCampusTour(int _idx, int _kind, Game* game, Building* _b) :Policy(_idx, _kind, _b), g(game) {} void SuspendCampusTour::takeEffect() { g->suspendCampusTour(); for (int i = 0;i <= 70;i++) { if (g->all_building[i]->change_in_infection_likelihood >= 0.00001) { g->all_building[i]->updateChange(-0.00001); } } g->cost_ap(cost); printPolicy(); } bool SuspendCampusTour::available() { return !g->getCampusTour_state(); } void SuspendCampusTour::printPolicy() { g->win->a_text(QString::fromUtf8( "校园参观已经暂停")); } PostponeStartOfSchool::PostponeStartOfSchool(int _idx, int _kind, Game* game, Building* _b) :Policy(_idx, _kind, _b), g(game) {} void PostponeStartOfSchool::takeEffect() { g->postponeStartOfSchool(); for (int i = 0;i <= 70;i++) { if (g->all_building[i]->change_in_infection_likelihood >= 0.00001) { g->all_building[i]->updateChange(-0.00001); } } g->cost_ap(cost); printPolicy(); } void PostponeStartOfSchool::printPolicy() { g->win->a_text(QString::fromUtf8( "经过研究,学校决定实行错峰开学")); } bool Game::getPostponeStartOfSchool_state() { return this->postponeStartOfSchool_state; } bool PostponeStartOfSchool::available() { return !g->getPostponeStartOfSchool_state(); } ProvideDesktopVideo::ProvideDesktopVideo(int _idx, int _kind, Game* game, Building* _b) :Policy(_idx, _kind, _b), g(game) {}; void ProvideDesktopVideo::takeEffect() { g->provideDesktopVideo(); for (int i = 0;i <= 70;i++) { g->all_building[i]->updateSatisfaction(50); } g->cost_ap(cost); printPolicy(); } bool Game::getProvideDesktopVideo_state() { return provideDesktopVideo_state; } bool ProvideDesktopVideo::available() { return !g->getProvideDesktopVideo_state(); } void ProvideDesktopVideo::printPolicy() { g->win->a_text(QString::fromUtf8( "学校为全体学生以及教职工申请了视频会议账号,这或许是网课的先兆")); } StartOnlineCourse::StartOnlineCourse(int _idx, int _kind, Game* game, Building* _b) :Policy(_idx, _kind, _b), g(game) {}; void StartOnlineCourse::takeEffect() { g->startOnlineCourse(); for (int i = 0;i <= 70;i++) { if (g->all_building[i]->change_in_infection_likelihood >= 0.00001) { g->all_building[i]->updateChange(-0.00001); } g->all_building[i]->updateSatisfaction(50); } g->cost_ap(cost); printPolicy(); } bool StartOnlineCourse::available() { return !g->getOnlineCourse_state()&&g->getProvideDesktopVideo_state(); } void StartOnlineCourse::printPolicy() { g->win->a_text(QString::fromUtf8( "疫情影响下,学校决定全面开始网上授课")); } StartPF::StartPF(int _idx, int _kind, Game* game, Building* _b) :Policy(_idx, _kind, _b), g(game) {}; void StartPF::takeEffect() { g->startPF(); for (int i = 0;i <= 70;i++) { g->all_building[i]->updateSatisfaction(50); } g->cost_ap(cost); printPolicy(); } bool StartPF::available() { return !g->getPF_state()&&g->getOnlineCourse_state(); } void StartPF::printPolicy() { g->win->a_text(QString::fromUtf8( "经过研究,学校决定本学期学生可以自选pf")); } Affair::Affair(int _idx, double _p, Building* _b) { idx = _idx; probability_of_occurrence = _p; happened_place = _b; } double Affair::getProb() { return probability_of_occurrence; } Building* Affair::getPlace() { return happened_place; } void Affair::takeEffect() { } void Affair::printAffair() { } void Affair::happen() { } CoupleByLake::CoupleByLake(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void CoupleByLake::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void CoupleByLake::takeEffect() { getPlace()->updateChange(0.00001); getPlace()->updateSatisfaction(5); printAffair(); //system("pause"); } void CoupleByLake::printAffair() { getPlace()->g->win->e_happen(this->idx); } ReadByLake::ReadByLake(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void ReadByLake::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void ReadByLake::takeEffect() { getPlace()->updateChange(0.00001); getPlace()->updateSatisfaction(5); printAffair(); //system("pause"); } void ReadByLake::printAffair() { getPlace()->g->win->e_happen(this->idx); } OnlineExhibition::OnlineExhibition(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void OnlineExhibition::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void OnlineExhibition::takeEffect() { getPlace()->updateSatisfaction(5); printAffair(); //system("pause"); } void OnlineExhibition::printAffair() { getPlace()->g->win->e_happen(this->idx); } NastyMeals::NastyMeals(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void NastyMeals::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void NastyMeals::takeEffect() { getPlace()->updateSatisfaction(-10); printAffair(); } void NastyMeals::printAffair() { getPlace()->g->win->e_happen(this->idx); } LuxuriousIsolationConditions::LuxuriousIsolationConditions(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void LuxuriousIsolationConditions::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void LuxuriousIsolationConditions::takeEffect() { getPlace()->updateSatisfaction(10); printAffair(); } void LuxuriousIsolationConditions::printAffair() { getPlace()->g->win->e_happen(this->idx); } InterestingQuarantineLife::InterestingQuarantineLife(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void InterestingQuarantineLife::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void InterestingQuarantineLife::takeEffect() { getPlace()->updateSatisfaction(5); printAffair(); } void InterestingQuarantineLife::printAffair() { getPlace()->g->win->e_happen(this->idx); } BrokenWashingMachine::BrokenWashingMachine(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void BrokenWashingMachine::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void BrokenWashingMachine::takeEffect() { getPlace()->updateSatisfaction(-20); printAffair(); } void BrokenWashingMachine::printAffair() { getPlace()->g->win->e_happen(this->idx); } BrokenAirConditioner::BrokenAirConditioner(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void BrokenAirConditioner::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void BrokenAirConditioner::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void BrokenAirConditioner::printAffair() { getPlace()->g->win->e_happen(this->idx); } BrokenWaterHeater::BrokenWaterHeater(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void BrokenWaterHeater::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void BrokenWaterHeater::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void BrokenWaterHeater::printAffair() { getPlace()->g->win->e_happen(this->idx); } Gathering::Gathering(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void Gathering::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void Gathering::takeEffect() { getPlace()->updateChange(0.00001); getPlace()->updateSatisfaction(-10); printAffair(); } void Gathering::printAffair() { getPlace()->g->win->e_happen(this->idx); } ProtesetInShudong::ProtesetInShudong(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void ProtesetInShudong::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void ProtesetInShudong::takeEffect() { getPlace()->updateSatisfaction(-2.5); printAffair(); } void ProtesetInShudong::printAffair() { getPlace()->g->win->e_happen(this->idx); } SingInDormitory::SingInDormitory(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void SingInDormitory::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (getPlace()->getSatisfaction() < 50) rand_p /= 2; if (rand_p < getProb()) takeEffect(); } void SingInDormitory::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void SingInDormitory::printAffair() { getPlace()->g->win->e_happen(this->idx); } ShushuBegins::ShushuBegins(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void ShushuBegins::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (getPlace()->getSatisfaction() < 50) rand_p /= 2; if (rand_p < getProb()) takeEffect(); } void ShushuBegins::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void ShushuBegins::printAffair() { getPlace()->g->win->e_happen(this->idx); } QuarrelInDormitory::QuarrelInDormitory(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void QuarrelInDormitory::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (getPlace()->getSatisfaction() < 50) rand_p /= 2; if (rand_p < getProb()) takeEffect(); } void QuarrelInDormitory::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void QuarrelInDormitory::printAffair() { getPlace()->g->win->e_happen(this->idx); } UnbearableSnoring::UnbearableSnoring(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void UnbearableSnoring::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void UnbearableSnoring::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void UnbearableSnoring::printAffair() { getPlace()->g->win->e_happen(this->idx); } Top10InBathroom::Top10InBathroom(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void Top10InBathroom::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void Top10InBathroom::takeEffect() { getPlace()->updateSatisfaction(5); printAffair(); } void Top10InBathroom::printAffair() { getPlace()->g->win->e_happen(this->idx); } LearningInDormitory::LearningInDormitory(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void LearningInDormitory::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void LearningInDormitory::takeEffect() { getPlace()->updateSatisfaction(5); printAffair(); } void LearningInDormitory::printAffair() { getPlace()->g->win->e_happen(this->idx); } MahjongInDormitory::MahjongInDormitory(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void MahjongInDormitory::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void MahjongInDormitory::takeEffect() { getPlace()->updateSatisfaction(5); printAffair(); } void MahjongInDormitory::printAffair() { getPlace()->g->win->e_happen(this->idx); } HarmoniousDormitory::HarmoniousDormitory(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void HarmoniousDormitory::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void HarmoniousDormitory::takeEffect() { getPlace()->updateSatisfaction(5); printAffair(); } void HarmoniousDormitory::printAffair() { getPlace()->g->win->e_happen(this->idx); } HealthySleeping::HealthySleeping(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void HealthySleeping::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void HealthySleeping::takeEffect() { getPlace()->updateSatisfaction(5); printAffair(); } void HealthySleeping::printAffair() { getPlace()->g->win->e_happen(this->idx); } BrokenOutPersonnel::BrokenOutPersonnel(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void BrokenOutPersonnel::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void BrokenOutPersonnel::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void BrokenOutPersonnel::printAffair() { getPlace()->g->win->e_happen(this->idx); } VolunteerLack::VolunteerLack(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void VolunteerLack::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void VolunteerLack::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void VolunteerLack::printAffair() { getPlace()->g->win->e_happen(this->idx); } LackOfMedicalResources::LackOfMedicalResources(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void LackOfMedicalResources::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (getPlace()->getInfectedNumber() > 500) rand_p /= 2; if (rand_p < getProb()) takeEffect(); } void LackOfMedicalResources::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void LackOfMedicalResources::printAffair() { getPlace()->g->win->e_happen(this->idx); } GreatPrevention::GreatPrevention(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void GreatPrevention::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb() && getPlace()->getInfectedNumber() < 500 ) takeEffect(); } void GreatPrevention::takeEffect() { getPlace()->updateSatisfaction(5); printAffair(); } void GreatPrevention::printAffair() { getPlace()->g->win->e_happen(this->idx); } Detention::Detention(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void Detention::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void Detention::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void Detention::printAffair() { getPlace()->g->win->e_happen(this->idx); } Top10::Top10(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void Top10::happen() { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } void Top10::takeEffect() { getPlace()->updateChange(0.00001); getPlace()->updateSatisfaction(5); printAffair(); } void Top10::printAffair() { getPlace()->g->win->e_happen(this->idx); } BrokenHeater::BrokenHeater(int _idx, double _p, Building* _b) : Affair(_idx, _p, _b) { } void BrokenHeater::happen() { if (getPlace()->isWinter()) { uniform_real_distribution<> rdt(0, 1); double rand_p = rdt(engine); if (rand_p < getProb()) takeEffect(); } } void BrokenHeater::takeEffect() { getPlace()->updateSatisfaction(-5); printAffair(); } void BrokenHeater::printAffair() { getPlace()->g->win->e_happen(this->idx); }
'use client'; import clsx from 'clsx'; import Button from '@/components/Button'; import Footer from '@/components/Footer'; import Hero from '@/components/Sections/Hero'; import Navbar from '@/components/Navbar' import Services from '@/components/Sections/Services'; import Testimonials from '@/components/Sections/Testimonials'; import UsSection from '@/components/Sections/UsSection'; import SupportSection from '@/components/Sections/SupportSection'; import { texts } from '@/constants/texts'; import { externalLink } from '@/constants/messageExternal'; import useTheme from '@/hooks/useTheme'; export default function Home() { const { isDark, isLight } = useTheme(); return ( <main className={clsx(` flex flex-col items-center w-full h-auto min-h-screen `, isDark && 'bg-skyblue-90 text-skyblue-20', isLight && 'bg-skyblue-white text-skyblue-90', )} > <Navbar /> <Hero /> <Services /> <Testimonials /> <UsSection /> <SupportSection /> <div className="flex md:hidden justify-center w-full py-2 px-8 fixed top-[86%] z-30"> <Button text={texts.actions.requestTrip} icon="WhatsApp" className="w-full max-w-sm shadow-drop-1" external to={externalLink} /> </div> <Footer /> </main> ) }
import { Request, Response, NextFunction } from 'express'; import bcrypt from 'bcryptjs'; import jwt from 'jsonwebtoken'; import { users } from '../models/schema.js'; import { sendMailLinkPasswordOptions } from '../nodemailer/utils.js'; import transporter from '../nodemailer/config.js'; import { ServerError } from '../entities/errors/ServerError.js'; import { MongooseError } from 'mongoose'; import { BadRequestError } from '../entities/errors/BadRequestError.js'; import authServices from '../services/auth.services.js'; import { CustomError } from '../entities/errors/CustomError.js'; export const loginController = async ( req: Request, res: Response, next: NextFunction ) => { const { email, contrasena }: { email: string; contrasena: string } = req.body; try { const user = await authServices.login(email, contrasena); return res.status(200).json({ data: { _id: user._id, token: user.token }, message: 'Logged In!', }); } catch (error) { console.error(error); next(error); } }; export const signupController = async ( req: Request, res: Response, next: NextFunction ) => { const { nombre, apellido, telefono, email, contrasena, numero, calle, localidad, CP, complemento, } = req.body; try { const user = await authServices.signUp({ nombre, apellido, telefono, email, contrasena, numero, calle, localidad, CP, complemento, }); if (user.upsertUser.matchedCount > 0) { const userExists = new BadRequestError('Email already exists!', email); return next(userExists); } return res.status(200).json({ data: { _id: user.upsertUser.upsertedId, token: user.token, }, message: 'Succesfully Created Account!', }); } catch (error) { console.log('error', error); return next(error); } }; export const updatePasswordController = async ( req: Request, res: Response, next: NextFunction ) => { const { email, password } = req.body; try { const user = await authServices.updatePassword(email, password); if (!user) { return res.status(400).json({ message: 'No user found!' }); } return res.status(200).json({ message: 'Succesfully set new password' }); } catch (error: CustomError | Error | any | unknown) { return next(error); } }; export const sendLinkToMailController = async ( req: Request, res: Response, next: NextFunction ) => { const { email } = req.query; if (!email) return next(new BadRequestError(`email required`)); try { const user = await authServices.sendLinkToMail(email as string, next); console.log('user', user); return res.status(200).json({ message: 'Successfully mail sent' }); } catch (error) { console.log('error', error); next(error); } };
VERSION 5.00 Begin VB.UserControl uXMLHTTP ClientHeight = 3090 ClientLeft = 0 ClientTop = 0 ClientWidth = 3180 InvisibleAtRuntime= -1 'True ScaleHeight = 3090 ScaleWidth = 3180 Begin VB.Timer tmrReader Enabled = 0 'False Interval = 10 Left = 960 Top = 120 End Begin VB.Shape Shape1 BackColor = &H00FFFFFF& BackStyle = 1 'Opaque BorderColor = &H00808080& FillColor = &H00C0C0C0& FillStyle = 7 'Diagonal Cross Height = 420 Left = 0 Top = 0 Width = 420 End End Attribute VB_Name = "uXMLHTTP" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = True Attribute VB_PredeclaredId = False Attribute VB_Exposed = False Private m_Inet As Object Private m_Sync As Boolean Public Event OnDateArrived() Public Event OnReadyStateChange() Private Sub tmrReader_Timer() RaiseEvent OnReadyStateChange If ReadyState = 4 Then If Status = 200 Then tmrReader.Enabled = False RaiseEvent OnDateArrived End If End If End Sub Private Sub UserControl_Initialize() Set m_Inet = CreateObject("MSXML2.ServerXMLHTTP") End Sub Private Sub UserControl_Terminate() tmrReader.Enabled = False Set m_Inet = Nothing End Sub Private Sub UserControl_Resize() UserControl.Size 420, 420 End Sub Public Sub Open_(AMethod As String, AUrl As String, Optional Sync As Boolean = False) m_Inet.open UCase(AMethod), AUrl, Sync m_Sync = Sync End Sub Public Sub SetRequestHeader(AHeader As String, AValue As String) m_Inet.SetRequestHeader AHeader, AValue End Sub Public Sub Send_(Optional ABody As String) m_Inet.Send ABody tmrReader.Enabled = m_Sync End Sub Public Sub Abort_() tmrReader.Enabled = False m_Inet.Abort End Sub Public Property Get ReadyState() As Long ReadyState = m_Inet.ReadyState End Property Public Property Get Status() As Long On Error Resume Next Status = m_Inet.Status End Property Public Property Get StatusText() As String On Error Resume Next StatusText = m_Inet.StatusText End Property Public Property Get GetResponseHeader(AHeader As String) As String GetResponseHeader = m_Inet.GetResponseHeader(AHeader) End Property Public Property Get GetAllResponseHeaders() As String GetAllResponseHeaders = m_Inet.GetAllResponseHeaders End Property Public Property Get ResponseBody() As Byte() ResponseBody = m_Inet.ResponseBody End Property Public Property Get ResponseText() As String ResponseText = m_Inet.ResponseText End Property
# @tyangs/commitlint [English](./README.md) / 简体中文 ## 开始使用 ### 安装依赖 ```bash npm install @tyangs/commitlint @commitlint/cli -D # 或 yarn add @tyangs/commitlint @commitlint/cli -D # 或 pnpm install @tyangs/commitlint @commitlint/cli -D ``` ### 创建配置文件 > 参考 [commitlint](https://commitlint.js.org/#/reference-configuration) 的官方文档配置. 创建 `commitlint.config.js` 或 `.commitlintrc.js` 配置文件。 ```javascript module.exports = { extends: ['@tyangs/commitlint'], // 在此处添加自定义配置 }; ``` ### 校验 git 提交信息通过 git hook 使用 [`simple-git-hooks`](https://github.com/toplenboren/simple-git-hooks): 1. 依赖安装 ```bash npm install simple-git-hooks -D ``` 2. 编辑 `package.json > prepare` 的脚本信息,并执行一遍 ```bash npm pkg set scripts.prepare="simple-git-hooks" npm run prepare ``` 3. 添加 `commit-msg` hook 在你的 package.json 文件 ```json "simple-git-hooks": { "commit-msg": "npx --no-install commitlint --edit $1" } ``` 使用 [`husky`](https://github.com/typicode/husky) 1. 依赖安装 ```bash npm install husky -D ``` 2. 编辑 `package.json > prepare` 的脚本信息,并执行一遍 ```bash npm pkg set scripts.prepare="husky install" npm run prepare ``` 3. 添加 `commit-msg` 钩子 ```bash npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1" git add .husky/commit-msg ``` 然后,当你执行 git commit -m 'xxx' 时,`commitlint` 将会对你输入的 msg 进行检查。
/******************************************************************************* Copyright (c) 2006-2015 Cadence Design Systems Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- XTENSA VECTORS AND LOW LEVEL HANDLERS FOR AN RTOS Xtensa low level exception and interrupt vectors and handlers for an RTOS. Interrupt handlers and user exception handlers support interaction with the RTOS by calling XT_RTOS_INT_ENTER and XT_RTOS_INT_EXIT before and after user's specific interrupt handlers. These macros are defined in xtensa_<rtos>.h to call suitable functions in a specific RTOS. Users can install application-specific interrupt handlers for low and medium level interrupts, by calling xt_set_interrupt_handler(). These handlers can be written in C, and must obey C calling convention. The handler table is indexed by the interrupt number. Each handler may be provided with an argument. Note that the system timer interrupt is handled specially, and is dispatched to the RTOS-specific handler. This timer cannot be hooked by application code. Optional hooks are also provided to install a handler per level at run-time, made available by compiling this source file with '-DXT_INTEXC_HOOKS' (useful for automated testing). !! This file is a template that usually needs to be modified to handle !! !! application specific interrupts. Search USER_EDIT for helpful comments !! !! on where to insert handlers and how to write them. !! Users can also install application-specific exception handlers in the same way, by calling xt_set_exception_handler(). One handler slot is provided for each exception type. Note that some exceptions are handled by the porting layer itself, and cannot be taken over by application code in this manner. These are the alloca, syscall, and coprocessor exceptions. The exception handlers can be written in C, and must follow C calling convention. Each handler is passed a pointer to an exception frame as its single argument. The exception frame is created on the stack, and holds the saved context of the thread that took the exception. If the handler returns, the context will be restored and the instruction that caused the exception will be retried. If the handler makes any changes to the saved state in the exception frame, the changes will be applied when restoring the context. Because Xtensa is a configurable architecture, this port supports all user generated configurations (except restrictions stated in the release notes). This is accomplished by conditional compilation using macros and functions defined in the Xtensa HAL (hardware adaptation layer) for your configuration. Only the relevant parts of this file will be included in your RTOS build. For example, this file provides interrupt vector templates for all types and all priority levels, but only the ones in your configuration are built. NOTES on the use of 'call0' for long jumps instead of 'j': 1. This file should be assembled with the -mlongcalls option to xt-xcc. 2. The -mlongcalls compiler option causes 'call0 dest' to be expanded to a sequence 'l32r a0, dest' 'callx0 a0' which works regardless of the distance from the call to the destination. The linker then relaxes it back to 'call0 dest' if it determines that dest is within range. This allows more flexibility in locating code without the performance overhead of the 'l32r' literal data load in cases where the destination is in range of 'call0'. There is an additional benefit in that 'call0' has a longer range than 'j' due to the target being word-aligned, so the 'l32r' sequence is less likely needed. 3. The use of 'call0' with -mlongcalls requires that register a0 not be live at the time of the call, which is always the case for a function call but needs to be ensured if 'call0' is used as a jump in lieu of 'j'. 4. This use of 'call0' is independent of the C function call ABI. */ #include "portmacro.h" #include "xtensa_rtos.h" /* Define for workaround: pin no-cpu-affinity tasks to a cpu when fpu is used. Please change this when the tcb structure is changed */ #define TASKTCB_CORE_AFFINITY_OFFSET (4 + portMPU_SETTINGS_SIZE) .extern pxCurrentTCBs /* -------------------------------------------------------------------------------- In order for backtracing to be able to trace from the pre-exception stack across to the exception stack (including nested interrupts), we need to create a pseudo base-save area to make it appear like the exception dispatcher was triggered by a CALL4 from the pre-exception code. In reality, the exception dispatcher uses the same window as pre-exception code, and only CALL0s are used within the exception dispatcher. To create the pseudo base-save area, we need to store a copy of the pre-exception's base save area (a0 to a4) below the exception dispatcher's SP. EXCSAVE_x will be used to store a copy of the SP that points to the interrupted code's exception frame just in case the exception dispatcher's SP does not point to the exception frame (which is the case when switching from task to interrupt stack). Clearing the pseudo base-save area is uncessary as the interrupt dispatcher will restore the current SP to that of the pre-exception SP. -------------------------------------------------------------------------------- */ #define XT_DEBUG_BACKTRACE 1 /* Macro get_percpu_entry_for - convert a per-core ID into a multicore entry. Basically does reg=reg*configNUM_CORES+current_core_id Multiple versions here to optimize for specific configNUM_CORES values. */ .macro get_percpu_entry_for reg scratch #if (configNUM_CORES == 1) /* No need to do anything */ #elif (configNUM_CORES == 2) /* Optimized 2-core code. */ getcoreid \scratch addx2 \reg,\reg,\scratch #else /* Generalized n-core code. Untested! */ movi \scratch,configNUM_CORES mull \scratch,\reg,\scratch getcoreid \reg add \reg,\scratch,\reg #endif .endm /* -------------------------------------------------------------------------------- Macro extract_msb - return the input with only the highest bit set. Input : "ain" - Input value, clobbered. Output : "aout" - Output value, has only one bit set, MSB of "ain". The two arguments must be different AR registers. -------------------------------------------------------------------------------- */ .macro extract_msb aout ain 1: addi \aout, \ain, -1 /* aout = ain - 1 */ and \ain, \ain, \aout /* ain = ain & aout */ bnez \ain, 1b /* repeat until ain == 0 */ addi \aout, \aout, 1 /* return aout + 1 */ .endm /* -------------------------------------------------------------------------------- Macro dispatch_c_isr - dispatch interrupts to user ISRs. This will dispatch to user handlers (if any) that are registered in the XTOS dispatch table (_xtos_interrupt_table). These handlers would have been registered by calling _xtos_set_interrupt_handler(). There is one exception - the timer interrupt used by the OS will not be dispatched to a user handler - this must be handled by the caller of this macro. Level triggered and software interrupts are automatically deasserted by this code. ASSUMPTIONS: -- PS.INTLEVEL is set to "level" at entry -- PS.EXCM = 0, C calling enabled NOTE: For CALL0 ABI, a12-a15 have not yet been saved. NOTE: This macro will use registers a0 and a2-a7. The arguments are: level -- interrupt level mask -- interrupt bitmask for this level -------------------------------------------------------------------------------- */ .macro dispatch_c_isr level mask #ifdef CONFIG_PM_TRACE movi a6, 0 /* = ESP_PM_TRACE_IDLE */ getcoreid a7 call4 esp_pm_trace_exit #endif // CONFIG_PM_TRACE /* Get mask of pending, enabled interrupts at this level into a2. */ .L_xt_user_int_&level&: rsr a2, INTENABLE rsr a3, INTERRUPT movi a4, \mask and a2, a2, a3 and a2, a2, a4 beqz a2, 9f /* nothing to do */ /* This bit of code provides a nice debug backtrace in the debugger. It does take a few more instructions, so undef XT_DEBUG_BACKTRACE if you want to save the cycles. At this point, the exception frame should have been allocated and filled, and current sp points to the interrupt stack (for non-nested interrupt) or below the allocated exception frame (for nested interrupts). Copy the pre-exception's base save area below the current SP. */ #ifdef XT_DEBUG_BACKTRACE // TODO: causes LoadProhibited exception //rsr a0, EXCSAVE_1 + \level - 1 /* Get exception frame pointer stored in EXCSAVE_x */ //l32i a3, a0, XT_STK_A0 /* Copy pre-exception a0 (return address) */ //s32e a3, a1, -16 //l32i a3, a0, XT_STK_A1 /* Copy pre-exception a1 (stack pointer) */ //s32e a3, a1, -12 /* Backtracing only needs a0 and a1, no need to create full base save area. Also need to change current frame's return address to point to pre-exception's last run instruction. */ rsr a0, EPC_1 + \level - 1 /* return address */ movi a4, 0xC0000000 /* constant with top 2 bits set (call size) */ or a0, a0, a4 /* set top 2 bits */ addx2 a0, a4, a0 /* clear top bit -- simulating call4 size */ #endif // Jump to timer interrupt if this is a level 1 interrupt and it needs to be served .ifeq XT_TIMER_INTPRI - \level extract_msb a4, a2 /* a4 = MSB of a2, a2 trashed */ movi a3, XT_TIMER_INTEN /* a3 = timer interrupt bit */ beq a3, a4, 7f /* if timer interrupt then skip table */ .endif movi a6, \level mov a7, sp call4 __level_\level\()_interrupt j .L_xt_user_int_&level& /* check for more interrupts */ 7: .ifeq XT_TIMER_INTPRI - \level .L_xt_user_int_timer_&level&: wsr a4, INTCLEAR /* clear sw or edge-triggered interrupt */ /* Interrupt handler for the RTOS tick timer if at this level. We'll be reading the interrupt state again after this call so no need to preserve any registers except a6 (vpri_mask). */ #ifdef __XTENSA_CALL0_ABI__ call0 XT_RTOS_TIMER_INT #else call4 XT_RTOS_TIMER_INT #endif .endif j .L_xt_user_int_&level& /* check for more interrupts */ 9: /* done */ .endm /* -------------------------------------------------------------------------------- EXCEPTION AND LEVEL 1 INTERRUPT VECTORS AND LOW LEVEL HANDLERS (except window exception vectors). Each vector goes at a predetermined location according to the Xtensa hardware configuration, which is ensured by its placement in a special section known to the Xtensa linker support package (LSP). It performs the minimum necessary before jumping to the handler in the .text section. The corresponding handler goes in the normal .text section. It sets up the appropriate stack frame, saves a few vector-specific registers and calls XT_RTOS_INT_ENTER to save the rest of the interrupted context and enter the RTOS, then sets up a C environment. It then calls the user's interrupt handler code (which may be coded in C) and finally calls XT_RTOS_INT_EXIT to transfer control to the RTOS for scheduling. While XT_RTOS_INT_EXIT does not return directly to the interruptee, eventually the RTOS scheduler will want to dispatch the interrupted task or handler. The scheduler will return to the exit point that was saved in the interrupt stack frame at XT_STK_EXIT. -------------------------------------------------------------------------------- */ // User Exception (including Level 1 Interrupt from user mode). .section .UserExceptionVector.text .global _UserExceptionVector .type _UserExceptionVector,@function .align 4 _UserExceptionVector: wsr a0, EXCSAVE_1 /* preserve a0 */ call0 __user_exception_trampoline /* user exception handler */ /* never returns here - call0 is used as a jump (see note at top) */ // Double Exception. // Double exceptions are not a normal occurrence. They indicate a bug of some kind. .section .DoubleExceptionVector.text .global _DoubleExceptionVector .align 4 _DoubleExceptionVector: wsr a0, EXCSAVE_5 call0 __double_exception_trampoline // Kernel Exception (including Level 1 Interrupt from kernel mode). .section .KernelExceptionVector.text .global _KernelExceptionVector .align 4 _KernelExceptionVector: wsr a0, EXCSAVE_1 /* preserve a0 */ call0 __kernel_exception_trampoline /* kernel exception handler */ /* never returns here - call0 is used as a jump (see note at top) */ .section .Level2InterruptVector.text .global _Level2InterruptVector .type _Level2InterruptVector,@function .align 4 _Level2InterruptVector: wsr a0, EXCSAVE_2 /* preserve a0 */ call0 _xt_medint2 /* load interrupt handler */ /* never returns here - call0 is used as a jump (see note at top) */ .section .Level3InterruptVector.text, "ax" .global _Level3InterruptVector .type _Level3InterruptVector,@function .align 4 _Level3InterruptVector: wsr a0, EXCSAVE_3 /* preserve a0 */ call0 _xt_medint3 /* load interrupt handler */ /* never returns here - call0 is used as a jump (see note at top) */ .section .Level4InterruptVector.text, "ax" .global _Level4InterruptVector .type _Level4InterruptVector,@function .align 4 _Level4InterruptVector: wsr a0, EXCSAVE_4 /* preserve a0 */ call0 _xt_medint4 /* load interrupt handler */ .section .Level5InterruptVector.text, "ax" .global _Level5InterruptVector .type _Level5InterruptVector,@function .align 4 _Level5InterruptVector: wsr a0, EXCSAVE_5 /* preserve a0 */ call0 _xt_medint5 /* load interrupt handler */ // Debug Exception. .section .DebugExceptionVector.text .global _DebugExceptionVector .align 4 _DebugExceptionVector: #if 0 /* change condition to 1 to use the HAL minimal debug handler */ wsr a3, EXCSAVE+XCHAL_DEBUGLEVEL movi a3, xthal_debugexc_defhndlr_nw /* use default debug handler */ jx a3 #else wsr a0, EXCSAVE6 /* save original a0 somewhere */ # call0 __debug_exception #endif rfi 6 .section .NMIExceptionVector.text .global _NMIExceptionVector .type _NMIExceptionVector,@function .align 4 _NMIExceptionVector: wsr a0, EXCSAVE + XCHAL_NMILEVEL _ /* preserve a0 */ call0 _xt_nmi /* load interrupt handler */ /* never returns here - call0 is used as a jump (see note at top) */ /* -------------------------------------------------------------------------------- Insert some waypoints for jumping beyond the signed 8-bit range of conditional branch instructions, so the conditional branchces to specific exception handlers are not taken in the mainline. Saves some cycles in the mainline. -------------------------------------------------------------------------------- */ .section .rwtext #ifdef CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY .global LoadStoreErrorHandler .global AlignmentErrorHandler #endif #if XCHAL_HAVE_WINDOWED .align 4 _xt_to_alloca_exc: call0 _xt_alloca_exc /* in window vectors section */ /* never returns here - call0 is used as a jump (see note at top) */ #endif .align 4 _xt_to_syscall_exc: call0 _xt_syscall_exc /* never returns here - call0 is used as a jump (see note at top) */ #if XCHAL_CP_NUM > 0 .align 4 _xt_to_coproc_exc: call0 _xt_coproc_exc /* never returns here - call0 is used as a jump (see note at top) */ #endif #ifdef CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY .align 4 _call_loadstore_handler: call0 LoadStoreErrorHandler /* This will return only if wrong opcode or address out of range*/ j .LS_exit .align 4 _call_alignment_handler: call0 AlignmentErrorHandler /* This will return only if wrong opcode or address out of range*/ addi a0, a0, 1 j .LS_exit #endif /* -------------------------------------------------------------------------------- User exception handler. -------------------------------------------------------------------------------- */ .type __user_exception_trampoline,@function .align 4 __user_exception_trampoline: /* If level 1 interrupt then jump to the dispatcher */ rsr a0, EXCCAUSE beqi a0, EXCCAUSE_LEVEL1INTERRUPT, _xt_lowint1 /* Handle any coprocessor exceptions. Rely on the fact that exception numbers above EXCCAUSE_CP0_DISABLED all relate to the coprocessors. */ #if XCHAL_CP_NUM > 0 bgeui a0, EXCCAUSE_CP0_DISABLED, _xt_to_coproc_exc #endif /* Handle alloca and syscall exceptions */ #if XCHAL_HAVE_WINDOWED beqi a0, EXCCAUSE_ALLOCA, _xt_to_alloca_exc #endif beqi a0, EXCCAUSE_SYSCALL, _xt_to_syscall_exc #ifdef CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY beqi a0, EXCCAUSE_LOAD_STORE_ERROR, _call_loadstore_handler addi a0, a0, -1 beqi a0, 8, _call_alignment_handler addi a0, a0, 1 .LS_exit: #endif /* Handle all other exceptions. All can have user-defined handlers. */ /* NOTE: we'll stay on the user stack for exception handling. */ /* Allocate exception frame and save minimal context. */ mov a0, sp addi sp, sp, -XT_STK_FRMSZ s32i a0, sp, XT_STK_A1 rsr a0, PS /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_1 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_1 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 s32i a12, sp, XT_STK_A12 /* _xt_context_save requires A12- */ s32i a13, sp, XT_STK_A13 /* A13 to have already been saved */ call0 _xt_context_save /* Save exc cause and vaddr into exception frame */ rsr a0, EXCCAUSE s32i a0, sp, XT_STK_EXCCAUSE rsr a0, EXCVADDR s32i a0, sp, XT_STK_EXCVADDR /* Set up PS for C, reenable hi-pri interrupts, and clear EXCM. */ movi a0, PS_INTLEVEL(XCHAL_EXCM_LEVEL) | PS_UM | PS_WOE wsr a0, PS /* Create pseudo base save area. At this point, sp is still pointing to the allocated and filled exception stack frame. */ #ifdef XT_DEBUG_BACKTRACE l32i a0, sp, XT_STK_A1 s32e a0, sp, -12 /* for debug backtrace */ rsr a0, EXCSAVE_1 s32e a0, sp, -16 /* for debug backtrace */ rsr a0, EPC_1 /* return address for debug backtrace */ movi a5, 0xC0000000 /* constant with top 2 bits set (call size) */ rsync /* wait for WSR.PS to complete */ or a0, a0, a5 /* set top 2 bits */ addx2 a0, a5, a0 /* clear top bit -- thus simulating call4 size */ #elif rsync /* wait for WSR.PS to complete */ #endif rsr a6, EXCCAUSE /* recover exc cause */ mov a7, sp /* a6 = pointer to exc frame */ call4 __exception /* call handler */ /* Restore context and return */ call0 _xt_context_restore l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, PS l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, EPC_1 l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove exception frame */ rsync /* ensure PS and EPC written */ rfe /* PS.EXCM is cleared */ .align 4 __kernel_exception_trampoline: /* Handle all other exceptions. All can have user-defined handlers. */ /* NOTE: we'll stay on the user stack for exception handling. */ /* Allocate exception frame and save minimal context. */ mov a0, sp addi sp, sp, -XT_STK_FRMSZ s32i a0, sp, XT_STK_A1 rsr a0, PS /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_1 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_1 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 s32i a12, sp, XT_STK_A12 /* _xt_context_save requires A12- */ s32i a13, sp, XT_STK_A13 /* A13 to have already been saved */ call0 _xt_context_save /* Save exc cause and vaddr into exception frame */ rsr a0, EXCCAUSE s32i a0, sp, XT_STK_EXCCAUSE rsr a0, EXCVADDR s32i a0, sp, XT_STK_EXCVADDR /* Set up PS for C, reenable hi-pri interrupts, and clear EXCM. */ movi a0, PS_INTLEVEL(XCHAL_EXCM_LEVEL) | PS_UM | PS_WOE wsr a0, PS /* Create pseudo base save area. At this point, sp is still pointing to the allocated and filled exception stack frame. */ #ifdef XT_DEBUG_BACKTRACE l32i a0, sp, XT_STK_A1 s32e a0, sp, -12 /* for debug backtrace */ rsr a0, EPC_1 s32e a0, sp, -16 /* for debug backtrace */ rsr a0, EXCSAVE_1 /* return address for debug backtrace */ movi a5, 0xC0000000 /* constant with top 2 bits set (call size) */ rsync /* wait for WSR.PS to complete */ or a0, a0, a5 /* set top 2 bits */ addx2 a0, a5, a0 /* clear top bit -- thus simulating call4 size */ #elif rsync /* wait for WSR.PS to complete */ #endif rsr a6, EXCCAUSE /* recover exc cause */ mov a7, sp /* a6 = pointer to exc frame */ call4 __exception /* call handler */ /* Restore context and return */ call0 _xt_context_restore l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, PS l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, EPC_1 l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove exception frame */ rsync /* ensure PS and EPC written */ rfe /* PS.EXCM is cleared */ .align 4 __double_exception_trampoline: /* Allocate exception frame and save minimal context. */ mov a0, sp addi sp, sp, -XT_STK_FRMSZ s32i a0, sp, XT_STK_A1 rsr a0, PS /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, DEPC /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_5 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 s32i a12, sp, XT_STK_A12 /* _xt_context_save requires A12- */ s32i a13, sp, XT_STK_A13 /* A13 to have already been saved */ call0 _xt_context_save /* Save exc cause and vaddr into exception frame */ rsr a0, EXCCAUSE s32i a0, sp, XT_STK_EXCCAUSE rsr a0, EXCVADDR s32i a0, sp, XT_STK_EXCVADDR /* Set up PS for C, reenable hi-pri interrupts, and clear EXCM. */ movi a0, PS_INTLEVEL(XCHAL_EXCM_LEVEL) | PS_UM | PS_WOE wsr a0, PS /* Create pseudo base save area. At this point, sp is still pointing to the allocated and filled exception stack frame. */ #ifdef XT_DEBUG_BACKTRACE l32i a0, sp, XT_STK_A1 s32e a0, sp, -12 /* for debug backtrace */ rsr a0, DEPC s32e a0, sp, -16 /* for debug backtrace */ rsr a0, EXCSAVE_5 /* return address for debug backtrace */ movi a5, 0xC0000000 /* constant with top 2 bits set (call size) */ rsync /* wait for WSR.PS to complete */ or a0, a0, a5 /* set top 2 bits */ addx2 a0, a5, a0 /* clear top bit -- thus simulating call4 size */ #elif rsync /* wait for WSR.PS to complete */ #endif rsr a6, EXCCAUSE /* recover exc cause */ mov a7, sp /* a6 = pointer to exc frame */ call4 __double_exception /* call handler */ /* Restore context and return */ call0 _xt_context_restore l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, PS l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, DEPC l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove exception frame */ rsync /* ensure PS and EPC written */ rfde /* PS.EXCM is cleared */ /* -------------------------------------------------------------------------------- Exit point for dispatch. Saved in interrupt stack frame at XT_STK_EXIT on entry and used to return to a thread or interrupted interrupt handler. -------------------------------------------------------------------------------- */ .global _xt_user_exit .type _xt_user_exit,@function .align 4 _xt_user_exit: l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, PS l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, EPC_1 l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove interrupt stack frame */ rsync /* ensure PS and EPC written */ rfe /* PS.EXCM is cleared */ /* -------------------------------------------------------------------------------- Syscall Exception Handler (jumped to from User Exception Handler). Syscall 0 is required to spill the register windows (no-op in Call 0 ABI). Only syscall 0 is handled here. Other syscalls return -1 to caller in a2. -------------------------------------------------------------------------------- */ .text .type _xt_syscall_exc,@function .align 4 _xt_syscall_exc: #ifdef __XTENSA_CALL0_ABI__ /* Save minimal regs for scratch. Syscall 0 does nothing in Call0 ABI. Use a minimal stack frame (16B) to save A2 & A3 for scratch. PS.EXCM could be cleared here, but unlikely to improve worst-case latency. rsr a0, PS addi a0, a0, -PS_EXCM_MASK wsr a0, PS */ addi sp, sp, -16 s32i a2, sp, 8 s32i a3, sp, 12 #else /* Windowed ABI */ /* Save necessary context and spill the register windows. PS.EXCM is still set and must remain set until after the spill. Reuse context save function though it saves more than necessary. For this reason, a full interrupt stack frame is allocated. */ addi sp, sp, -XT_STK_FRMSZ /* allocate interrupt stack frame */ s32i a12, sp, XT_STK_A12 /* _xt_context_save requires A12- */ s32i a13, sp, XT_STK_A13 /* A13 to have already been saved */ call0 _xt_context_save #endif /* Grab the interruptee's PC and skip over the 'syscall' instruction. If it's at the end of a zero-overhead loop and it's not on the last iteration, decrement loop counter and skip to beginning of loop. */ rsr a2, EPC_1 /* a2 = PC of 'syscall' */ addi a3, a2, 3 /* ++PC */ #if XCHAL_HAVE_LOOPS rsr a0, LEND /* if (PC == LEND */ bne a3, a0, 1f rsr a0, LCOUNT /* && LCOUNT != 0) */ beqz a0, 1f /* { */ addi a0, a0, -1 /* --LCOUNT */ rsr a3, LBEG /* PC = LBEG */ wsr a0, LCOUNT /* } */ #endif 1: wsr a3, EPC_1 /* update PC */ /* Restore interruptee's context and return from exception. */ #ifdef __XTENSA_CALL0_ABI__ l32i a2, sp, 8 l32i a3, sp, 12 addi sp, sp, 16 #else call0 _xt_context_restore addi sp, sp, XT_STK_FRMSZ #endif movi a0, -1 movnez a2, a0, a2 /* return -1 if not syscall 0 */ rsr a0, EXCSAVE_1 rfe /* -------------------------------------------------------------------------------- Co-Processor Exception Handler (jumped to from User Exception Handler). These exceptions are generated by co-processor instructions, which are only allowed in thread code (not in interrupts or kernel code). This restriction is deliberately imposed to reduce the burden of state-save/restore in interrupts. -------------------------------------------------------------------------------- */ #if XCHAL_CP_NUM > 0 .section .rodata, "a" /* Offset to CP n save area in thread's CP save area. */ .global _xt_coproc_sa_offset .type _xt_coproc_sa_offset,@object .align 16 /* minimize crossing cache boundaries */ _xt_coproc_sa_offset: .word XT_CP0_SA, XT_CP1_SA, XT_CP2_SA, XT_CP3_SA .word XT_CP4_SA, XT_CP5_SA, XT_CP6_SA, XT_CP7_SA /* Bitmask for CP n's CPENABLE bit. */ .type _xt_coproc_mask,@object .align 16,,8 /* try to keep it all in one cache line */ .set i, 0 _xt_coproc_mask: .rept XCHAL_CP_MAX .long (i<<16) | (1<<i) // upper 16-bits = i, lower = bitmask .set i, i+1 .endr .data /* Owner thread of CP n, identified by thread's CP save area (0 = unowned). */ .global _xt_coproc_owner_sa .type _xt_coproc_owner_sa,@object .align 16,,XCHAL_CP_MAX<<2 /* minimize crossing cache boundaries */ _xt_coproc_owner_sa: .space (XCHAL_CP_MAX * configNUM_CORES) << 2 .section .rwtext .align 4 .L_goto_invalid: j .L_xt_coproc_invalid /* not in a thread (invalid) */ .align 4 .L_goto_done: j .L_xt_coproc_done /* -------------------------------------------------------------------------------- Coprocessor exception handler. At entry, only a0 has been saved (in EXCSAVE_1). -------------------------------------------------------------------------------- */ .type _xt_coproc_exc,@function .align 4 _xt_coproc_exc: /* Allocate interrupt stack frame and save minimal context. */ mov a0, sp /* sp == a1 */ addi sp, sp, -XT_STK_FRMSZ /* allocate interrupt stack frame */ s32i a0, sp, XT_STK_A1 /* save pre-interrupt SP */ #if XCHAL_HAVE_WINDOWED s32e a0, sp, -12 /* for debug backtrace */ #endif rsr a0, PS /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_1 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_1 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 #if XCHAL_HAVE_WINDOWED s32e a0, sp, -16 /* for debug backtrace */ #endif movi a0, _xt_user_exit /* save exit point for dispatch */ s32i a0, sp, XT_STK_EXIT rsr a0, EXCCAUSE s32i a5, sp, XT_STK_A5 /* save a5 */ addi a5, a0, -EXCCAUSE_CP0_DISABLED /* a5 = CP index */ /* Save a few more of interruptee's registers (a5 was already saved). */ s32i a2, sp, XT_STK_A2 s32i a3, sp, XT_STK_A3 s32i a4, sp, XT_STK_A4 s32i a15, sp, XT_STK_A15 /* Get co-processor state save area of new owner thread. */ call0 XT_RTOS_CP_STATE /* a15 = new owner's save area */ beqz a15, .L_goto_invalid /* not in a thread (invalid) */ /* FPU operations are incompatible with non-pinned tasks. If we have a FPU operation here, to keep the entire thing from crashing, it's better to pin the task to whatever core we're running on now. */ movi a2, pxCurrentTCBs getcoreid a3 addx4 a2, a3, a2 l32i a2, a2, 0 /* a2 = start of pxCurrentTCBs[cpuid] */ addi a2, a2, TASKTCB_CORE_AFFINITY_OFFSET /* offset to uxCoreAffinityMask in tcb struct */ addi a4, a3, 1 /* equivalent to (1 << coreid) */ s32i a4, a2, 0 /* store current cpuid */ /* Enable the co-processor's bit in CPENABLE. */ movi a0, _xt_coproc_mask rsr a4, CPENABLE /* a4 = CPENABLE */ addx4 a0, a5, a0 /* a0 = &_xt_coproc_mask[n] */ l32i a0, a0, 0 /* a0 = (n << 16) | (1 << n) */ /* Grab correct xt_coproc_owner_sa for this core */ movi a2, XCHAL_CP_MAX << 2 mull a2, a2, a3 /* multiply by current processor id */ movi a3, _xt_coproc_owner_sa /* a3 = base of owner array */ add a3, a3, a2 /* a3 = owner area needed for this processor */ extui a2, a0, 0, 16 /* coprocessor bitmask portion */ or a4, a4, a2 /* a4 = CPENABLE | (1 << n) */ wsr a4, CPENABLE /* Keep loading _xt_coproc_owner_sa[n] atomic (=load once, then use that value everywhere): _xt_coproc_release assumes it works like this in order not to need locking. */ /* Get old coprocessor owner thread (save area ptr) and assign new one. */ addx4 a3, a5, a3 /* a3 = &_xt_coproc_owner_sa[n] */ l32i a2, a3, 0 /* a2 = old owner's save area */ s32i a15, a3, 0 /* _xt_coproc_owner_sa[n] = new */ rsync /* ensure wsr.CPENABLE is complete */ /* Only need to context switch if new owner != old owner. */ beq a15, a2, .L_goto_done /* new owner == old, we're done */ /* If no old owner then nothing to save. */ beqz a2, .L_check_new /* If old owner not actively using CP then nothing to save. */ l16ui a4, a2, XT_CPENABLE /* a4 = old owner's CPENABLE */ bnone a4, a0, .L_check_new /* old owner not using CP */ .L_save_old: /* Save old owner's coprocessor state. */ movi a5, _xt_coproc_sa_offset /* Mark old owner state as no longer active (CPENABLE bit n clear). */ xor a4, a4, a0 /* clear CP bit in CPENABLE */ s16i a4, a2, XT_CPENABLE /* update old owner's CPENABLE */ extui a4, a0, 16, 5 /* a4 = CP index = n */ addx4 a5, a4, a5 /* a5 = &_xt_coproc_sa_offset[n] */ /* Mark old owner state as saved (CPSTORED bit n set). */ l16ui a4, a2, XT_CPSTORED /* a4 = old owner's CPSTORED */ l32i a5, a5, 0 /* a5 = XT_CP[n]_SA offset */ or a4, a4, a0 /* set CP in old owner's CPSTORED */ s16i a4, a2, XT_CPSTORED /* update old owner's CPSTORED */ l32i a2, a2, XT_CP_ASA /* ptr to actual (aligned) save area */ extui a3, a0, 16, 5 /* a3 = CP index = n */ add a2, a2, a5 /* a2 = old owner's area for CP n */ /* The config-specific HAL macro invoked below destroys a2-5, preserves a0-1. It is theoretically possible for Xtensa processor designers to write TIE that causes more address registers to be affected, but it is generally unlikely. If that ever happens, more registers needs to be saved/restored around this macro invocation, and the value in a15 needs to be recomputed. */ xchal_cpi_store_funcbody .L_check_new: /* Check if any state has to be restored for new owner. */ /* NOTE: a15 = new owner's save area, cannot be zero when we get here. */ l16ui a3, a15, XT_CPSTORED /* a3 = new owner's CPSTORED */ movi a4, _xt_coproc_sa_offset bnone a3, a0, .L_check_cs /* full CP not saved, check callee-saved */ xor a3, a3, a0 /* CPSTORED bit is set, clear it */ s16i a3, a15, XT_CPSTORED /* update new owner's CPSTORED */ /* Adjust new owner's save area pointers to area for CP n. */ extui a3, a0, 16, 5 /* a3 = CP index = n */ addx4 a4, a3, a4 /* a4 = &_xt_coproc_sa_offset[n] */ l32i a4, a4, 0 /* a4 = XT_CP[n]_SA */ l32i a5, a15, XT_CP_ASA /* ptr to actual (aligned) save area */ add a2, a4, a5 /* a2 = new owner's area for CP */ /* The config-specific HAL macro invoked below destroys a2-5, preserves a0-1. It is theoretically possible for Xtensa processor designers to write TIE that causes more address registers to be affected, but it is generally unlikely. If that ever happens, more registers needs to be saved/restored around this macro invocation. */ xchal_cpi_load_funcbody /* Restore interruptee's saved registers. */ /* Can omit rsync for wsr.CPENABLE here because _xt_user_exit does it. */ .L_xt_coproc_done: l32i a15, sp, XT_STK_A15 l32i a5, sp, XT_STK_A5 l32i a4, sp, XT_STK_A4 l32i a3, sp, XT_STK_A3 l32i a2, sp, XT_STK_A2 call0 _xt_user_exit /* return via exit dispatcher */ /* Never returns here - call0 is used as a jump (see note at top) */ .L_check_cs: /* a0 = CP mask in low bits, a15 = new owner's save area */ l16ui a2, a15, XT_CP_CS_ST /* a2 = mask of CPs saved */ bnone a2, a0, .L_xt_coproc_done /* if no match then done */ and a2, a2, a0 /* a2 = which CPs to restore */ extui a2, a2, 0, 8 /* extract low 8 bits */ s32i a6, sp, XT_STK_A6 /* save extra needed regs */ s32i a7, sp, XT_STK_A7 s32i a13, sp, XT_STK_A13 s32i a14, sp, XT_STK_A14 call0 _xt_coproc_restorecs /* restore CP registers */ l32i a6, sp, XT_STK_A6 /* restore saved registers */ l32i a7, sp, XT_STK_A7 l32i a13, sp, XT_STK_A13 l32i a14, sp, XT_STK_A14 j .L_xt_coproc_done /* Co-processor exception occurred outside a thread (not supported). */ .L_xt_coproc_invalid: #if XCHAL_HAVE_DEBUG break 1, 1 /* unhandled user exception */ #endif // TODO: panic # call0 __panic /* not in a thread (invalid) */ call0 __kernel_exception_trampoline /* never returns */ #endif /* XCHAL_CP_NUM */ /* ------------------------------------------------------------------------------- Level 1 interrupt dispatch. Assumes stack frame has not been allocated yet. ------------------------------------------------------------------------------- */ .section .rwtext .type _xt_lowint1,@function .align 4 _xt_lowint1: mov a0, sp /* sp == a1 */ addi sp, sp, -XT_STK_FRMSZ /* allocate interrupt stack frame */ s32i a0, sp, XT_STK_A1 /* save pre-interrupt SP */ rsr a0, PS /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_1 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_1 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 movi a0, _xt_user_exit /* save exit point for dispatch */ s32i a0, sp, XT_STK_EXIT /* Save rest of interrupt context and enter RTOS. */ call0 XT_RTOS_INT_ENTER /* common RTOS interrupt entry */ /* !! We are now on the RTOS system stack !! */ /* Set up PS for C, enable interrupts above this level and clear EXCM. */ movi a0, PS_INTLEVEL(1) | PS_UM | PS_WOE wsr a0, PS rsync /* OK to call C code at this point, dispatch user ISRs */ dispatch_c_isr 1 XCHAL_INTLEVEL1_MASK /* Done handling interrupts, transfer control to OS */ call0 XT_RTOS_INT_EXIT /* does not return directly here */ /* ------------------------------------------------------------------------------- MEDIUM PRIORITY (LEVEL 2+) INTERRUPT VECTORS AND LOW LEVEL HANDLERS. Medium priority interrupts are by definition those with priority greater than 1 and not greater than XCHAL_EXCM_LEVEL. These are disabled by setting PS.EXCM and therefore can easily support a C environment for handlers in C, and interact safely with an RTOS. Each vector goes at a predetermined location according to the Xtensa hardware configuration, which is ensured by its placement in a special section known to the Xtensa linker support package (LSP). It performs the minimum necessary before jumping to the handler in the .text section. The corresponding handler goes in the normal .text section. It sets up the appropriate stack frame, saves a few vector-specific registers and calls XT_RTOS_INT_ENTER to save the rest of the interrupted context and enter the RTOS, then sets up a C environment. It then calls the user's interrupt handler code (which may be coded in C) and finally calls XT_RTOS_INT_EXIT to transfer control to the RTOS for scheduling. While XT_RTOS_INT_EXIT does not return directly to the interruptee, eventually the RTOS scheduler will want to dispatch the interrupted task or handler. The scheduler will return to the exit point that was saved in the interrupt stack frame at XT_STK_EXIT. ------------------------------------------------------------------------------- */ .section .rwtext .type _xt_medint2,@function .align 4 _xt_medint2: mov a0, sp /* sp == a1 */ addi sp, sp, -XT_STK_FRMSZ /* allocate interrupt stack frame */ s32i a0, sp, XT_STK_A1 /* save pre-interrupt SP */ rsr a0, EPS_2 /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_2 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_2 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 movi a0, _xt_medint2_exit /* save exit point for dispatch */ s32i a0, sp, XT_STK_EXIT /* Save rest of interrupt context and enter RTOS. */ call0 XT_RTOS_INT_ENTER /* common RTOS interrupt entry */ /* !! We are now on the RTOS system stack !! */ /* Set up PS for C, enable interrupts above this level and clear EXCM. */ movi a0, PS_INTLEVEL(2) | PS_UM | PS_WOE wsr a0, PS rsync /* OK to call C code at this point, dispatch user ISRs */ dispatch_c_isr 2 XCHAL_INTLEVEL2_MASK /* Done handling interrupts, transfer control to OS */ call0 XT_RTOS_INT_EXIT /* does not return directly here */ /* Exit point for dispatch. Saved in interrupt stack frame at XT_STK_EXIT on entry and used to return to a thread or interrupted interrupt handler. */ .global _xt_medint2_exit .type _xt_medint2_exit,@function .align 4 _xt_medint2_exit: /* Restore only level-specific regs (the rest were already restored) */ l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, EPS_2 l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, EPC_2 l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove interrupt stack frame */ rsync /* ensure EPS and EPC written */ rfi 2 .section .rwtext .type _xt_medint3,@function .align 4 _xt_medint3: mov a0, sp /* sp == a1 */ addi sp, sp, -XT_STK_FRMSZ /* allocate interrupt stack frame */ s32i a0, sp, XT_STK_A1 /* save pre-interrupt SP */ rsr a0, EPS_3 /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_3 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_3 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 movi a0, _xt_medint3_exit /* save exit point for dispatch */ s32i a0, sp, XT_STK_EXIT /* Save rest of interrupt context and enter RTOS. */ call0 XT_RTOS_INT_ENTER /* common RTOS interrupt entry */ /* !! We are now on the RTOS system stack !! */ /* Set up PS for C, enable interrupts above this level and clear EXCM. */ movi a0, PS_INTLEVEL(3) | PS_UM | PS_WOE wsr a0, PS rsync /* OK to call C code at this point, dispatch user ISRs */ dispatch_c_isr 3 XCHAL_INTLEVEL3_MASK /* Done handling interrupts, transfer control to OS */ call0 XT_RTOS_INT_EXIT /* does not return directly here */ /* Exit point for dispatch. Saved in interrupt stack frame at XT_STK_EXIT on entry and used to return to a thread or interrupted interrupt handler. */ .global _xt_medint3_exit .type _xt_medint3_exit,@function .align 4 _xt_medint3_exit: /* Restore only level-specific regs (the rest were already restored) */ l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, EPS_3 l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, EPC_3 l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove interrupt stack frame */ rsync /* ensure EPS and EPC written */ rfi 3 .section .rwtext .type _xt_medint4,@function .align 4 _xt_medint4: mov a0, sp /* sp == a1 */ addi sp, sp, -XT_STK_FRMSZ /* allocate interrupt stack frame */ s32i a0, sp, XT_STK_A1 /* save pre-interrupt SP */ rsr a0, EPS_4 /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_4 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_4 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 movi a0, _xt_medint4_exit /* save exit point for dispatch */ s32i a0, sp, XT_STK_EXIT /* Save rest of interrupt context and enter RTOS. */ call0 XT_RTOS_INT_ENTER /* common RTOS interrupt entry */ /* !! We are now on the RTOS system stack !! */ /* Set up PS for C, enable interrupts above this level and clear EXCM. */ movi a0, PS_INTLEVEL(4) | PS_UM | PS_WOE wsr a0, PS rsync /* OK to call C code at this point, dispatch user ISRs */ dispatch_c_isr 4 XCHAL_INTLEVEL4_MASK /* Done handling interrupts, transfer control to OS */ call0 XT_RTOS_INT_EXIT /* does not return directly here */ /* Exit point for dispatch. Saved in interrupt stack frame at XT_STK_EXIT on entry and used to return to a thread or interrupted interrupt handler. */ .global _xt_medint4_exit .type _xt_medint4_exit,@function .align 4 _xt_medint4_exit: /* Restore only level-specific regs (the rest were already restored) */ l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, EPS_4 l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, EPC_4 l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove interrupt stack frame */ rsync /* ensure EPS and EPC written */ rfi 4 .section .rwtext .type _xt_medint5,@function .align 4 _xt_medint5: mov a0, sp /* sp == a1 */ addi sp, sp, -XT_STK_FRMSZ /* allocate interrupt stack frame */ s32i a0, sp, XT_STK_A1 /* save pre-interrupt SP */ rsr a0, EPS_5 /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_5 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_5 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 movi a0, _xt_medint5_exit /* save exit point for dispatch */ s32i a0, sp, XT_STK_EXIT /* Save rest of interrupt context and enter RTOS. */ call0 XT_RTOS_INT_ENTER /* common RTOS interrupt entry */ /* !! We are now on the RTOS system stack !! */ /* Set up PS for C, enable interrupts above this level and clear EXCM. */ movi a0, PS_INTLEVEL(5) | PS_UM | PS_WOE wsr a0, PS rsync /* OK to call C code at this point, dispatch user ISRs */ dispatch_c_isr 5 XCHAL_INTLEVEL5_MASK /* Done handling interrupts, transfer control to OS */ call0 XT_RTOS_INT_EXIT /* does not return directly here */ /* Exit point for dispatch. Saved in interrupt stack frame at XT_STK_EXIT on entry and used to return to a thread or interrupted interrupt handler. */ .global _xt_medint5_exit .type _xt_medint5_exit,@function .align 4 _xt_medint5_exit: /* Restore only level-specific regs (the rest were already restored) */ l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, EPS_5 l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, EPC_5 l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove interrupt stack frame */ rsync /* ensure EPS and EPC written */ rfi 5 .section .rwtext .type _xt_medint6,@function .align 4 _xt_medint6: mov a0, sp /* sp == a1 */ addi sp, sp, -XT_STK_FRMSZ /* allocate interrupt stack frame */ s32i a0, sp, XT_STK_A1 /* save pre-interrupt SP */ rsr a0, EPS_6 /* save interruptee's PS */ s32i a0, sp, XT_STK_PS rsr a0, EPC_6 /* save interruptee's PC */ s32i a0, sp, XT_STK_PC rsr a0, EXCSAVE_6 /* save interruptee's a0 */ s32i a0, sp, XT_STK_A0 movi a0, _xt_medint6_exit /* save exit point for dispatch */ s32i a0, sp, XT_STK_EXIT /* Save rest of interrupt context and enter RTOS. */ call0 XT_RTOS_INT_ENTER /* common RTOS interrupt entry */ /* !! We are now on the RTOS system stack !! */ /* Set up PS for C, enable interrupts above this level and clear EXCM. */ movi a0, PS_INTLEVEL(6) | PS_UM | PS_WOE wsr a0, PS rsync /* OK to call C code at this point, dispatch user ISRs */ dispatch_c_isr 6 XCHAL_INTLEVEL6_MASK /* Done handling interrupts, transfer control to OS */ call0 XT_RTOS_INT_EXIT /* does not return directly here */ /* Exit point for dispatch. Saved in interrupt stack frame at XT_STK_EXIT on entry and used to return to a thread or interrupted interrupt handler. */ .global _xt_medint6_exit .type _xt_medint6_exit,@function .align 4 _xt_medint6_exit: /* Restore only level-specific regs (the rest were already restored) */ l32i a0, sp, XT_STK_PS /* retrieve interruptee's PS */ wsr a0, EPS_6 l32i a0, sp, XT_STK_PC /* retrieve interruptee's PC */ wsr a0, EPC_6 l32i a0, sp, XT_STK_A0 /* retrieve interruptee's A0 */ l32i sp, sp, XT_STK_A1 /* remove interrupt stack frame */ rsync /* ensure EPS and EPC written */ rfi 6 /******************************************************************************* HIGH PRIORITY (LEVEL > XCHAL_EXCM_LEVEL) INTERRUPT VECTORS AND HANDLERS High priority interrupts are by definition those with priorities greater than XCHAL_EXCM_LEVEL. This includes non-maskable (NMI). High priority interrupts cannot interact with the RTOS, that is they must save all regs they use and not call any RTOS function. A further restriction imposed by the Xtensa windowed architecture is that high priority interrupts must not modify the stack area even logically "above" the top of the interrupted stack (they need to provide their own stack or static save area). Cadence Design Systems recommends high priority interrupt handlers be coded in assembly and used for purposes requiring very short service times. Here are templates for high priority (level 2+) interrupt vectors. They assume only one interrupt per level to avoid the burden of identifying which interrupts at this level are pending and enabled. This allows for minimum latency and avoids having to save/restore a2 in addition to a0. If more than one interrupt per high priority level is configured, this burden is on the handler which in any case must provide a way to save and restore registers it uses without touching the interrupted stack. Each vector goes at a predetermined location according to the Xtensa hardware configuration, which is ensured by its placement in a special section known to the Xtensa linker support package (LSP). It performs the minimum necessary before jumping to the handler in the .text section. *******************************************************************************/ /* Currently only shells for high priority interrupt handlers are provided here. However a template and example can be found in the Cadence Design Systems tools documentation: "Microprocessor Programmer's Guide". */ .section .rwtext .type _xt_nmi,@function .align 4 _xt_nmi: rsr a0, EXCSAVE + XCHAL_NMILEVEL /* restore a0 */ rfi XCHAL_NMILEVEL /******************************************************************************* WINDOW OVERFLOW AND UNDERFLOW EXCEPTION VECTORS AND ALLOCA EXCEPTION HANDLER Here is the code for each window overflow/underflow exception vector and (interspersed) efficient code for handling the alloca exception cause. Window exceptions are handled entirely in the vector area and are very tight for performance. The alloca exception is also handled entirely in the window vector area so comes at essentially no cost in code size. Users should never need to modify them and Cadence Design Systems recommends they do not. Window handlers go at predetermined vector locations according to the Xtensa hardware configuration, which is ensured by their placement in a special section known to the Xtensa linker support package (LSP). Since their offsets in that section are always the same, the LSPs do not define a section per vector. These things are coded for XEA2 only (XEA1 is not supported). Note on Underflow Handlers: The underflow handler for returning from call[i+1] to call[i] must preserve all the registers from call[i+1]'s window. In particular, a0 and a1 must be preserved because the RETW instruction will be reexecuted (and may even underflow if an intervening exception has flushed call[i]'s registers). Registers a2 and up may contain return values. *******************************************************************************/ /* -------------------------------------------------------------------------------- Window Overflow Exception for Call4. Invoked if a call[i] referenced a register (a4-a15) that contains data from ancestor call[j]; call[j] had done a call4 to call[j+1]. On entry here: window rotated to call[j] start point; a0-a3 are registers to be saved; a4-a15 must be preserved; a5 is call[j+1]'s stack pointer. -------------------------------------------------------------------------------- */ .section .WindowOverflow4.text .global _WindowOverflow4 _WindowOverflow4: s32e a0, a5, -16 /* save a0 to call[j+1]'s stack frame */ s32e a1, a5, -12 /* save a1 to call[j+1]'s stack frame */ s32e a2, a5, -8 /* save a2 to call[j+1]'s stack frame */ s32e a3, a5, -4 /* save a3 to call[j+1]'s stack frame */ rfwo /* rotates back to call[i] position */ /* -------------------------------------------------------------------------------- Window Underflow Exception for Call4 Invoked by RETW returning from call[i+1] to call[i] where call[i]'s registers must be reloaded (not live in ARs); where call[i] had done a call4 to call[i+1]. On entry here: window rotated to call[i] start point; a0-a3 are undefined, must be reloaded with call[i].reg[0..3]; a4-a15 must be preserved (they are call[i+1].reg[0..11]); a5 is call[i+1]'s stack pointer. -------------------------------------------------------------------------------- */ .section .WindowUnderflow4.text .global _WindowUnderflow4 _WindowUnderflow4: l32e a0, a5, -16 /* restore a0 from call[i+1]'s stack frame */ l32e a1, a5, -12 /* restore a1 from call[i+1]'s stack frame */ l32e a2, a5, -8 /* restore a2 from call[i+1]'s stack frame */ l32e a3, a5, -4 /* restore a3 from call[i+1]'s stack frame */ rfwu /* -------------------------------------------------------------------------------- Handle alloca exception generated by interruptee executing 'movsp'. This uses space between the window vectors, so is essentially "free". All interruptee's regs are intact except a0 which is saved in EXCSAVE_1, and PS.EXCM has been set by the exception hardware (can't be interrupted). The fact the alloca exception was taken means the registers associated with the base-save area have been spilled and will be restored by the underflow handler, so those 4 registers are available for scratch. The code is optimized to avoid unaligned branches and minimize cache misses. -------------------------------------------------------------------------------- */ .align 4 .global _xt_alloca_exc _xt_alloca_exc: rsr a0, WINDOWBASE /* grab WINDOWBASE before rotw changes it */ rotw -1 /* WINDOWBASE goes to a4, new a0-a3 are scratch */ rsr a2, PS extui a3, a2, XCHAL_PS_OWB_SHIFT, XCHAL_PS_OWB_BITS xor a3, a3, a4 /* bits changed from old to current windowbase */ rsr a4, EXCSAVE_1 /* restore original a0 (now in a4) */ slli a3, a3, XCHAL_PS_OWB_SHIFT xor a2, a2, a3 /* flip changed bits in old window base */ wsr a2, PS /* update PS.OWB to new window base */ rsync _bbci.l a4, 31, _WindowUnderflow4 rotw -1 /* original a0 goes to a8 */ _bbci.l a8, 30, _WindowUnderflow8 rotw -1 j _WindowUnderflow12 /* -------------------------------------------------------------------------------- Window Overflow Exception for Call8 Invoked if a call[i] referenced a register (a4-a15) that contains data from ancestor call[j]; call[j] had done a call8 to call[j+1]. On entry here: window rotated to call[j] start point; a0-a7 are registers to be saved; a8-a15 must be preserved; a9 is call[j+1]'s stack pointer. -------------------------------------------------------------------------------- */ .section .WindowOverflow8.text .global _WindowOverflow8 _WindowOverflow8: s32e a0, a9, -16 /* save a0 to call[j+1]'s stack frame */ l32e a0, a1, -12 /* a0 <- call[j-1]'s sp (used to find end of call[j]'s frame) */ s32e a1, a9, -12 /* save a1 to call[j+1]'s stack frame */ s32e a2, a9, -8 /* save a2 to call[j+1]'s stack frame */ s32e a3, a9, -4 /* save a3 to call[j+1]'s stack frame */ s32e a4, a0, -32 /* save a4 to call[j]'s stack frame */ s32e a5, a0, -28 /* save a5 to call[j]'s stack frame */ s32e a6, a0, -24 /* save a6 to call[j]'s stack frame */ s32e a7, a0, -20 /* save a7 to call[j]'s stack frame */ rfwo /* rotates back to call[i] position */ /* -------------------------------------------------------------------------------- Window Underflow Exception for Call8 Invoked by RETW returning from call[i+1] to call[i] where call[i]'s registers must be reloaded (not live in ARs); where call[i] had done a call8 to call[i+1]. On entry here: window rotated to call[i] start point; a0-a7 are undefined, must be reloaded with call[i].reg[0..7]; a8-a15 must be preserved (they are call[i+1].reg[0..7]); a9 is call[i+1]'s stack pointer. -------------------------------------------------------------------------------- */ .section .WindowUnderflow8.text .global _WindowUnderflow8 _WindowUnderflow8: l32e a0, a9, -16 /* restore a0 from call[i+1]'s stack frame */ l32e a1, a9, -12 /* restore a1 from call[i+1]'s stack frame */ l32e a2, a9, -8 /* restore a2 from call[i+1]'s stack frame */ l32e a7, a1, -12 /* a7 <- call[i-1]'s sp (used to find end of call[i]'s frame) */ l32e a3, a9, -4 /* restore a3 from call[i+1]'s stack frame */ l32e a4, a7, -32 /* restore a4 from call[i]'s stack frame */ l32e a5, a7, -28 /* restore a5 from call[i]'s stack frame */ l32e a6, a7, -24 /* restore a6 from call[i]'s stack frame */ l32e a7, a7, -20 /* restore a7 from call[i]'s stack frame */ rfwu /* -------------------------------------------------------------------------------- Window Overflow Exception for Call12 Invoked if a call[i] referenced a register (a4-a15) that contains data from ancestor call[j]; call[j] had done a call12 to call[j+1]. On entry here: window rotated to call[j] start point; a0-a11 are registers to be saved; a12-a15 must be preserved; a13 is call[j+1]'s stack pointer. -------------------------------------------------------------------------------- */ .section .WindowOverflow12.text .global _WindowOverflow12 _WindowOverflow12: s32e a0, a13, -16 /* save a0 to call[j+1]'s stack frame */ l32e a0, a1, -12 /* a0 <- call[j-1]'s sp (used to find end of call[j]'s frame) */ s32e a1, a13, -12 /* save a1 to call[j+1]'s stack frame */ s32e a2, a13, -8 /* save a2 to call[j+1]'s stack frame */ s32e a3, a13, -4 /* save a3 to call[j+1]'s stack frame */ s32e a4, a0, -48 /* save a4 to end of call[j]'s stack frame */ s32e a5, a0, -44 /* save a5 to end of call[j]'s stack frame */ s32e a6, a0, -40 /* save a6 to end of call[j]'s stack frame */ s32e a7, a0, -36 /* save a7 to end of call[j]'s stack frame */ s32e a8, a0, -32 /* save a8 to end of call[j]'s stack frame */ s32e a9, a0, -28 /* save a9 to end of call[j]'s stack frame */ s32e a10, a0, -24 /* save a10 to end of call[j]'s stack frame */ s32e a11, a0, -20 /* save a11 to end of call[j]'s stack frame */ rfwo /* rotates back to call[i] position */ /* -------------------------------------------------------------------------------- Window Underflow Exception for Call12 Invoked by RETW returning from call[i+1] to call[i] where call[i]'s registers must be reloaded (not live in ARs); where call[i] had done a call12 to call[i+1]. On entry here: window rotated to call[i] start point; a0-a11 are undefined, must be reloaded with call[i].reg[0..11]; a12-a15 must be preserved (they are call[i+1].reg[0..3]); a13 is call[i+1]'s stack pointer. -------------------------------------------------------------------------------- */ .section .WindowUnderflow12.text .global _WindowUnderflow12 _WindowUnderflow12: l32e a0, a13, -16 /* restore a0 from call[i+1]'s stack frame */ l32e a1, a13, -12 /* restore a1 from call[i+1]'s stack frame */ l32e a2, a13, -8 /* restore a2 from call[i+1]'s stack frame */ l32e a11, a1, -12 /* a11 <- call[i-1]'s sp (used to find end of call[i]'s frame) */ l32e a3, a13, -4 /* restore a3 from call[i+1]'s stack frame */ l32e a4, a11, -48 /* restore a4 from end of call[i]'s stack frame */ l32e a5, a11, -44 /* restore a5 from end of call[i]'s stack frame */ l32e a6, a11, -40 /* restore a6 from end of call[i]'s stack frame */ l32e a7, a11, -36 /* restore a7 from end of call[i]'s stack frame */ l32e a8, a11, -32 /* restore a8 from end of call[i]'s stack frame */ l32e a9, a11, -28 /* restore a9 from end of call[i]'s stack frame */ l32e a10, a11, -24 /* restore a10 from end of call[i]'s stack frame */ l32e a11, a11, -20 /* restore a11 from end of call[i]'s stack frame */ rfwu
// buttons // fn_add_mask . buttons with icons .fn_add_mask(@icon_name) { -webkit-mask-image: url('../../themes/default/icons/@{icon_name}'); mask-image: url('../../themes/default/icons/@{icon_name}'); -webkit-mask-size: contain; mask-size: contain; -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat; -webkit-mask-position: center; mask-position: center; } // fn_build_button .fn_build_button(@icon_name, @color:black, @opacity:0.7, @size:1em) { // create base standard button .button; // custom icon color background: @color; // custom size overwrite height: @size; width: @size; // custom size overwrite opacity: @opacity; // custom icon svg name .fn_add_mask(@icon_name); } // fn_append_icon (used by tag element 'button') .fn_append_icon(@icon_name, @color:#3f3f3f, @opacity:1) { --icon-path : url('../../themes/default/icons/@{icon_name}'); &:before { background-color: @color; content: ' '; display: inline-block; height: 1em; margin-right: 0.25em; opacity: @opacity; vertical-align: baseline; width: 1em; // .fn_add_mask(@icon_name); -webkit-mask-image: var(--icon-path); mask-image: var(--icon-path); -webkit-mask-size: contain; mask-size: contain; -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat; -webkit-mask-position: center; mask-position: center; @media screen and (max-width: @width_break_point_1) { margin-right: 0px; } } } // button : generic to apply to span elements and get a icon button without text .button, .icon_button { // @icon_name:null, @color:black, @opacity:0.7, @size:1em background-color: #000000; cursor: pointer; // display: inline-block; display: inline-flex; height: 1em; line-height: 1em; margin: 0px; margin-left: 0.25rem; margin-right: 0.25rem; min-width: 1em; opacity: 1; user-select: none; // vertical-align: middle; width: 1em; font-weight: 300; // height: fit-content; // margin-top: 0.25rem; // margin-left: 0.5em; // margin-right: 0.5em; // background-repeat: no-repeat; // background-position: center; // background-size: contain; //padding: 0.5em; // margin-top: 0.25em; // margin-bottom: 0.25em; &:hover { opacity: 1 !important; } &:active { opacity: 0.4 !important; } // inside buttons_container, all buttons are white .buttons_container & { background-color: #ffffff; margin-top: 0px; } // variants after create button &.white { background-color: #ffffff !important; } &.grey { background-color: @color_grey_dark; opacity: 0.75; } &.transparent { background-color: transparent !important; } }//end .button // icon .icon { &.loading { // spinner border: 1px solid #d1d5db; border-top-color: @color_orange_dedalo; border-radius: 50%; mask: unset !important; -webkit-mask: unset !important; background-color: transparent !important; animation: run_spinner 800ms linear infinite; } } // button tag. explicit buttons (dialog box etc.) button { // appearance: none; // font-size: .9em; // background-color: #a6a6a6; // border-radius: 0.30em; // color: #ffff; // border: none; height: min-content; margin-right: 0.25em; padding-bottom: 0.275rem; padding-left: 0.75rem; padding-right: 0.75rem; padding-top: 0.275rem; width: max-content; // bootstrap // display: inline-block; text-align: center; // vertical-align: middle; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: transparent; border: 1px solid transparent; // padding: .375rem .75rem; font-size: 1rem; font-weight: 400; line-height: 1.5; border-radius: 0.25rem; transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; display: inline-flex; align-items: center; justify-content: center; &.folding { @media screen and (max-width: @width_break_point_1) { // padding-right: 0.25rem; text-indent: -9999em; } } // @media screen and (max-width: @width_break_point_1) { // // padding-right: 0.25rem; // text-indent: -9999em; // } // color color: #212529; // default dark grey &.primary { @color: @color_primary; background-color: @color; border-color: darken(@color, 2%); color: #ffffff; &:before { background-color: #ffffff !important; } &:hover { background-color: darken(@color, 5%); border-color: darken(@color, 7%); } } &.secondary { @color: @color_secondary; background-color: @color; border-color: darken(@color, 2%); color: #ffffff; &:before { background-color: #ffffff !important; } &:hover { background-color: darken(@color, 5%); border-color: darken(@color, 7%); } } &.success { @color: @color_success; background-color: @color; border-color: darken(@color, 2%); color: #ffffff; &:before { background-color: #ffffff !important; } &:hover { background-color: darken(@color, 5%); border-color: darken(@color, 7%); } } &.danger { @color: @color_danger; background-color: @color; border-color: darken(@color, 2%); color: #ffffff; &:before { background-color: #ffffff !important; } &:hover { background-color: darken(@color, 5%); border-color: darken(@color, 7%); } } &.warning { @color: @color_orange_dedalo; background-color: @color; border-color: darken(@color, 2%); color: #ffffff; &:before { background-color: #ffffff !important; } &:hover { background-color: darken(@color, 5%); border-color: darken(@color, 7%); } } &.info { @color: @color_info; background-color: @color; border-color: darken(@color, 2%); color: #ffffff; &:before { background-color: #ffffff !important; } &:hover { background-color: darken(@color, 5%); border-color: darken(@color, 7%); } } &.light { @color: @color_light; background-color: @color; border-color: darken(@color, 2%); color: #212529; &:before { background-color: #212529 !important; } &:hover { background-color: darken(@color, 5%); border-color: darken(@color, 7%); } } &.dark { @color: @color_dark; background-color: @color; border-color: darken(@color, 2%); color: #ffffff; &:before { background-color: #ffffff !important; } &:hover { background-color: darken(@color, 5%); border-color: darken(@color, 7%); } } &.link { // no background for link button color: @color_primary; font-weight: 400; text-decoration: none; } // bg means the button have a custom background image // &.bg { // background-repeat: no-repeat; // background-size: contain; // background-position: -1.5em 0; // background-origin: content-box; // padding-left: 2em !important; // } &:active { opacity: 0.5; } &:focus { // background-color: #c45527 !important; border: 1.2px solid #0059fa !important; opacity: 1; // color: #ffffff; } }//end button // generic recyclable icons for buttons .add_light { @icon_name : 'add_light.svg'; // add_light, add button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .add, .new { @icon_name : 'add.svg'; // add_light, add button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .align_justify { @icon_name : 'justify.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .arrow_link { @icon_name : 'arrow_link.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .blank { @icon_name : ''; // trash.svg button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .calendar { @icon_name : 'calendar.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .cancel { @icon_name : 'cancel.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .check { @icon_name : 'check.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } .icon_button& { .fn_add_mask(@icon_name); } } .close { @icon_name : 'close.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .compress { @icon_name : 'compress.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .copy { @icon_name : 'copy.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .csv { @icon_name : 'csv.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .delete { @icon_name : 'trash_light.svg'; // trash.svg button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .delete_light { @icon_name : 'trash_light.svg'; // delete button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .delete_bold { @icon_name : 'trash_bold.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .diffusion { @icon_name : 'diffusion_light.svg'; // diffusion button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .document { @icon_name : 'document.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .download { @icon_name : 'download.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .drag { @icon_name : 'drag.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .duplicate { @icon_name : 'duplicate.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .edit { @icon_name : 'edit.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .email { @icon_name : 'email.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .email_multiple { @icon_name : 'email_multiple.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .eye { @icon_name : 'eye.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .file_av { @icon_name : 'file_av.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .film { @icon_name : 'film.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .find { @icon_name : 'find.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .full_screen { @icon_name : 'full_screen.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .gear { @icon_name : 'gear.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .geo { @icon_name : 'geo.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .history { // history (time_machine recover icon) @icon_name : 'history.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .info { @icon_name : 'info.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .label { @icon_name : 'tag.svg'; // label button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .lang { @icon_name : 'lang.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .link { @icon_name : 'link.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .list { @icon_name : 'list.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .media { @icon_name : 'media.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .note { @icon_name : 'note.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .pause { @icon_name : 'pause.svg'; button& { .fn_append_icon(@icon_name);} .button& { .fn_add_mask(@icon_name); } } .play { @icon_name : 'play.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .pen { @icon_name : 'pen.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .print { @icon_name : 'print.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } .icon_button& { .fn_add_mask(@icon_name); } } .remove { @icon_name : 'trash_light.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .reset { @icon_name : 'eraser.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .reload { @icon_name : 'reload.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .repair { @icon_name : 'repair.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .rotate { @icon_name : 'rotate.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } &.right { transform: scaleX(-1); } } .save { @icon_name : 'save.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .search { @icon_name : 'search_light.svg'; // search button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .sync { @icon_name : 'sync.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .table { @icon_name : 'table.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .tree { @icon_name : 'tree.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .uncertainty { @icon_name : 'uncertainty.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .upload { @icon_name : 'upload.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } .exclamation { @icon_name : 'warning.svg'; button& { .fn_append_icon(@icon_name); } .button& { .fn_add_mask(@icon_name); } } // .contenteditable_buttons (used by content editable) .contenteditable_buttons { // position: absolute; // height: 1.5em; // top: -1.54em; // z-index: 9; display: flex; // background-color: @color_grey_dark; padding: 0px; border-top-left-radius: 0.25em; border-top-right-radius: 0.25em; >.button { color: white; &:before { content: ' '; background-size: contain; background-repeat: no-repeat; height: 1em; width: 1em; margin-right: 0.25em; padding-right: 1em; vertical-align: text-bottom; } &.bold:before { //background-image: url(../../themes/default/icons/bold.svg); // .background_icon('bold.svg'); .fn_build_button('bold.svg', black, 1); } &.italic:before { //background-image: url(../../themes/default/icons/italic.svg); // .background_icon('italic.svg'); .fn_build_button('italic.svg', black, 1); } &.underline:before { //background-image: url(../../themes/default/icons/underline.svg); // .background_icon('underline.svg'); .fn_build_button('underline.svg', black, 1); } &.replace:before { //background-image: url(../../themes/default/icons/exchange.svg); // .background_icon('exchange.svg'); .fn_build_button('exchange.svg', black, 1); } } }//end .contenteditable_buttons
// 버튼 0 누르면 // 모든 버튼에 붙은 orange 클래스명 제거 // 버튼0에 orange 클래스명 추가 // 모든 div에 붙은 show 클래스명 제거 // div0에 show 클래스명 추가 let len = document.getElementsByClassName('tab-button').length; // 또는 let len2 = $('.tab-button').length; // for (let i = 0; i < len; i++) { // openTab(i); // } function openTab(n) { $('.tab-button').eq(n).on('click', () => { $('.tab-button').removeClass('orange'); $('.tab-button').eq(n).addClass('orange'); $('.tab-content').removeClass('show'); $('.tab-content').eq(n).addClass('show'); }) } // 성능 개선 -> 이벤트리스너 줄이기 (이벤트 버블링 활용) // 상위 태그에 이벤트 리스너 붙임 $('.list').click(function(e) { // if(e.target == document.querySelectorAll('.tab-button')[0]) { // openTab(0) // } // dataset 문법 활용 openTab(parseInt(e.target.dataset.id)); }) // $('.tab-button').eq(1).on('click', () => { // $('.tab-button').removeClass('orange'); // $('.tab-button').eq(1).addClass('orange'); // $('.tab-content').removeClass('show'); // $('.tab-content').eq(1).addClass('show'); // }) // $('.tab-button').eq(2).on('click', () => { // $('.tab-button').removeClass('orange'); // $('.tab-button').eq(2).addClass('orange'); // $('.tab-content').removeClass('show'); // $('.tab-content').eq(2).addClass('show'); // }) // 좋은 관습 : 자주 쓰는 셀렉터 변수에 저장하기 -> 성능 상 좋다 // var btn = $('.tab-button'); // btn.eq(1).on('click', () => { // btn.removeClass('orange'); // btn.eq(1).addClass('orange'); // btn.removeClass('show'); // btn.eq(1).addClass('show'); // })