text
stringlengths 184
4.48M
|
|---|
<template>
<v-app
id="main"
:style="{ background: $vuetify.theme.themes[theme].background }"
>
<v-app-bar app outlined>
<div class="d-flex align-center">
<h1>Authorizers PoC Requester</h1>
<v-btn icon align="start" v-if="wallet">
<v-icon small color="primary" @click="infoDialog = true">
mdi-information-outline
</v-icon>
</v-btn>
</div>
<v-spacer></v-spacer>
<v-chip v-if="wallet" label large outlined color="primary">
Wallet Connected: <br />
{{ wallet }}
</v-chip>
</v-app-bar>
<v-main>
<dApp
v-bind:wallet.sync="wallet"
v-bind:sponsorWallet.sync="sponsorWallet"
/>
</v-main>
<v-footer app height="40px" flat color="transparent">
<v-col class="text-center text-caption" cols="12">
Powered by Airnode
</v-col>
</v-footer>
<v-dialog max-width="60%" v-model="infoDialog">
<v-card>
<v-card-title>
Authorizers PoC
<v-spacer></v-spacer>
<v-btn icon @click="infoDialog = false">
<v-icon>mdi-close</v-icon>
</v-btn>
</v-card-title>
<v-card-text>
This is a Proof of Concept that requests random numbers from an API
that is behind an
<a href="https://docs.api3.org/airnode/v0.3/" target="_blank">
Airnode
<v-icon x-small> mdi-open-in-new </v-icon>
</a>
that uses an
<a
href="https://docs.api3.org/airnode/v0.3/concepts/authorization.html#authorizers"
target="_blank"
>
Authorizer Contract
<v-icon x-small> mdi-open-in-new </v-icon>
</a>
for Whitelisting. Contracts that haven't paid their subscription fee
will be rejected.
<br />
<br />
To subscribe for Airnode access, please use our
<a
href="http://13.233.252.69/product/api-subscription/"
target="_blank"
>
Mock Webstore
<v-icon x-small> mdi-open-in-new </v-icon>
</a>
to place your order.
<br />
<br />
Authorized responses will be returned by Airnode using the shared
Sponsor Wallet.
<br />
</v-card-text>
<v-card-text>
<v-row justify="center">
<v-col cols="12" md="10">
<v-text-field
label="Sponsor Wallet Address"
outlined
readonly
@focus="$event.target.select()"
dense
:value="sponsorWallet"
>
</v-text-field>
</v-col>
</v-row>
</v-card-text>
</v-card>
</v-dialog>
</v-app>
</template>
<script>
import dApp from "./components/dApp";
export default {
name: "App",
components: {
dApp,
},
data: () => ({
wallet: null,
infoDialog: false,
sponsorWallet: null,
//
}),
computed: {
theme() {
return this.$vuetify.theme.dark ? "dark" : "light";
},
},
};
</script>
<style></style>
|
import { AfterViewInit, Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { MatToolbar } from '@angular/material/toolbar';
import { MaterialModule } from '../material/material.module';
import { AppHeaderStateService, DrawerAction } from '../services/state-services/app-header-state.service';
import { AppStateService, Dashbord } from '../services/state-services/app-state.service';
import { UserStateService } from '../services/user-services/user-state.service';
@Component({
selector: 'app-header-component',
templateUrl: './app-header.component.html',
styleUrls: ['./app-header.component.scss']
})
export class AppHeaderComponent implements OnInit, AfterViewInit {
@ViewChild('toolbarElement') toolbarElement: MatToolbar | undefined;
@ViewChild('headerElement') headerElement: ElementRef;
@Output('onHeaderHeightInit')
get headerHeightInit(): EventEmitter<number> {
return this._headerHeightInit;
}
private _headerHeightInit: EventEmitter<number>;
get headerTitle(): string {
return this.headerState.headerTitle;
}
get headerSubTitle(): string {
return this.headerState.headerSubTitle;
}
get isLoggedIn(): boolean {
return this.userState.isLoggedIn;
}
get getIcon(): string {
return this.appState.selectedDashboard === Dashbord.APPOINTMENTS ?
MaterialModule.ICON_APPOINTMENTS_MENU : MaterialModule.ICON_DOCTORS_MENU;
}
constructor(
private appState: AppStateService,
private headerState: AppHeaderStateService,
private userState: UserStateService,
) {
this.headerElement = new ElementRef(null);
this._headerHeightInit = new EventEmitter<number>();
}
ngAfterViewInit(): void {
this.initTopOffsets();
}
ngOnInit(): void {}
public onWindowResize(): void {
this.initTopOffsets();
}
public onFilterClick(): void {
this.headerState.clickOnFilter(DrawerAction.OPEN);
}
public logout(): void {
this.userState.logout();
}
public switchAppointmentDoctors(): void {
this.appState.switchDashboards();
}
private initTopOffsets(): void {
try {
const toolbarHeight = this.toolbarElement?._elementRef.nativeElement.offsetHeight;
this.headerElement.nativeElement.style.top = `${toolbarHeight}px`;
this._headerHeightInit.emit(this.headerElement.nativeElement.offsetHeight + toolbarHeight);
} catch (e) {
console.error(e);
}
}
}
|
defmodule ElixirChatWeb.ChatLive.Form do
alias ElixirChat.Chat
alias ElixirChat.Chat.Message
use ElixirChatWeb, :live_component
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign(%{
changeset: Message.changeset(%Message{}, %{})
})
}
end
def handle_event("update", %{"content" => content} = _params, socket) do
{:noreply,
socket
|> assign(:changeset, Message.changeset(%Message{content: content}, %{}))
}
end
def handle_event("save", %{"content" => content} = _params, socket) do
Chat.create_message(%{
content: content,
room_id: socket.assigns.room_id,
user_id: socket.assigns.user_id,
})
{:noreply,
socket
|> assign(:changeset, Message.changeset(%Message{}, %{}))
}
end
def render(assigns) do
~H"""
<div class="full-w-inputs block w-full h-[10%] max-h-[100px]">
<.form id="message-form" class="flex items-center justify-start bg-base-white w-full bg-base-white px-8 py-6 gap-x-3 h-full nth-child(1):bg-red-400"
for={@changeset}
phx-submit="save"
phx-change="update"
phx-target={@myself}
phx-hook="ScrollDown"
>
<.input name="content" value="" field={{@changeset, :content}} style="margin: 0px" />
<.button class="button-appearance-none">
<i class="material-icons text-base-purple-100 !text-[32px] hover:brightness-150 transition-all ease-in-out duration-150">send</i>
</.button>
</.form>
</div>
"""
end
end
|
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';
@Component({
selector: 'app-countdown',
templateUrl: './countdown.component.html',
styleUrls: ['./countdown.component.scss']
})
export class CountdownComponent implements OnInit, OnDestroy {
days: number = 0;
hours: number = 0;
minutes: number = 0;
seconds: number = 0;
_deadline?: string
/**
* @example "8.07:34:17.0794045"
*/
@Input('deadline')
public set deadline(v: string | undefined) {
if (!v) return;
this._deadline = v;
let [daysAndHours, minutes, seconds]: any = this._deadline?.split(':');
let [days, hours]: any = daysAndHours.split('.');
this.days = Number(days);
this.hours = Number(hours);
this.minutes = Number(minutes);
this.seconds = Number(seconds);
this.countdownSub = this.countdown.subscribe(() => this.update());
}
public get deadline(): string | undefined {
return this._deadline;
}
/** timer */
countdown = interval(1000);
countdownSub?: Subscription
constructor() { }
ngOnInit(): void {
}
ngOnDestroy(): void {
this.countdownSub?.unsubscribe();
}
/** update days, hours ,... */
update() {
this.seconds--;
if (this.seconds < 0) {
this.minutes--;
this.seconds = 59;
}
if (this.minutes < 0) {
this.hours--;
this.minutes = 59
}
if (this.hours < 0) {
this.days--;
this.hours = 11
}
}
}
|
/* eslint-disable react/prop-types */
import { Box, Text, Flex, Button } from "@chakra-ui/react";
import { HiOutlineTicket } from "react-icons/hi2";
import { BiPlus, BiMinus } from "react-icons/bi";
import { Divider } from "@chakra-ui/react";
import { useState } from "react";
import toRupiah from "@develoka/angka-rupiah-js";
import { useNavigate } from "react-router";
export const Tiket = (props) => {
const [countVip, setCountVip] = useState(0);
const [countFree, setCountFree] = useState(0);
const navigate = useNavigate();
return (
<Box
w={{ base: "full", md: "33%" }}
bgColor={"white"}
borderRadius={"10px"}
p={"30px 50px"}
>
<Text fontWeight={700} fontSize={"20px"} mb={"20px"}>
Tiket
</Text>
<Flex direction={"column"} gap={5}>
<Flex
direction={"column"}
bgColor={"rgba(255, 46, 99,.08)"}
border={"1px solid"}
borderColor={"home.primary"}
p={"10px"}
borderRadius={"10px"}
gap={3}
>
<Flex gap={3} align={"center"} color={"home.primary"}>
<HiOutlineTicket />
<Text>Tiket VIP</Text>
</Flex>
<Text fontSize={"12px"}>
Tiket terbatas, harga sudah termasukpajak
</Text>
<Divider />
<Flex justify={"space-between"}>
<Text fontWeight={700}>RP. 500.000</Text>
<Flex gap={3}>
<Button
display={"flex"}
borderRadius={"50%"}
size={"xm"}
h={"20px"}
justifyContent={"center"}
alignItems={"center"}
border={"1px solid black"}
w={"20px"}
bgColor={"transparent"}
onClick={() => setCountVip(countVip - 1)}
>
<BiMinus />
</Button>
{countVip}
<Button
display={"flex"}
borderRadius={"50%"}
size={"xm"}
h={"20px"}
justifyContent={"center"}
alignItems={"center"}
border={"1px solid black"}
w={"20px"}
bgColor={"transparent"}
onClick={() => setCountVip(countVip + 1)}
>
<BiPlus />
</Button>
</Flex>
</Flex>
</Flex>
<Flex
direction={"column"}
bgColor={"rgba(255, 46, 99,.08)"}
border={"1px solid"}
borderColor={"home.primary"}
p={"10px"}
borderRadius={"10px"}
gap={3}
>
<Flex gap={3} align={"center"} color={"home.primary"}>
<HiOutlineTicket />
<Text>Tiket Gratis</Text>
</Flex>
<Text fontSize={"12px"}>
Tiket terbatas, harga sudah termasukpajak
</Text>
<Divider />
<Flex justify={"space-between"}>
<Text fontWeight={700}>RP. 500.000</Text>
<Flex gap={3}>
<Button
display={"flex"}
borderRadius={"50%"}
size={"xm"}
h={"20px"}
justifyContent={"center"}
alignItems={"center"}
border={"1px solid black"}
w={"20px"}
bgColor={"transparent"}
onClick={() => setCountFree(countFree - 1)}
>
<BiMinus />
</Button>
{countFree}
<Button
display={"flex"}
borderRadius={"50%"}
size={"xm"}
h={"20px"}
justifyContent={"center"}
alignItems={"center"}
border={"1px solid black"}
w={"20px"}
bgColor={"transparent"}
onClick={() => setCountFree(countFree + 1)}
>
<BiPlus />
</Button>
</Flex>
</Flex>
</Flex>
<Divider />
<Flex direction={"column"} gap={3}>
<Text>Total</Text>
<Flex justify={"space-between"}>
<Text>{countFree + countVip} Tiket</Text>
<Text>{toRupiah(countVip * 500000)}</Text>
</Flex>
</Flex>
<Flex justify={"end"}>
<Button
bgColor={"home.primary"}
color={"white"}
w={"150px"}
onClick={() =>
navigate(`/personal-information/${props.eventId}`, {
state: {
price: countVip * 500000,
total: countVip + countFree,
},
})
}
>
Beli Tiket
</Button>
</Flex>
</Flex>
</Box>
);
};
|
from django.views.generic import FormView
from django.urls import reverse_lazy
from django.shortcuts import render, redirect
from django.conf import settings
from manipulador_arquivos.forms import UploadForm
from django.http import FileResponse, HttpRequest, HttpResponse
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from webdav3.client import Client
import requests
import os
import tempfile
# Create your views here.
class HomeView2(FormView):
template_name = 'manipulador/homepage.html'
form_class = UploadForm
success_url = reverse_lazy('home-page')
def get(self, request):
files = self.listing_file()
upload_form = self.form_class
return render(request, self.template_name, {'upload_form' : upload_form, 'files': files})
def post(self, request):
local_path_upload = 'manipulador_arquivos/temp-file'
local_path_download = os.path.join(tempfile.gettempdir(), 'temp-file-download')
form = self.get_form()
if form.is_valid():
upload_file = form.cleaned_data['upload_file']
file_name = upload_file.name
file_path = local_path_upload + '/' + file_name
self.upload_file(file_name, local_path_upload)
return super().post(request)
action = request.POST.get('action')
selected_file = request.POST.get('download')
if selected_file is None:
return redirect('home-page')
if action == 'delete':
self.delete_file(selected_file)
return redirect('home-page')
self.download_file(selected_file, local_path_download)
return FileResponse(open(local_path_download, 'rb'), as_attachment=True, filename=selected_file)
def listing_file(self):
options = {
'webdav_hostname': settings.WEBDAV_URL + f'remote.php/dav/files/{settings.WEBDAV_USERNAME}/Temp-File-Nando-Example',
'webdav_login': settings.WEBDAV_USERNAME,
'webdav_password': settings.WEBDAV_PASSWORD
}
client = Client(options)
return (client.list())[1:]
def download_file(self, file_name, local_path):
webdav_url = settings.WEBDAV_URL + f'remote.php/dav/files/{settings.WEBDAV_USERNAME}/Temp-File-Nando-Example/{file_name}'
webdav_login = settings.WEBDAV_USERNAME
webdav_password = settings.WEBDAV_PASSWORD
response_get = requests.get(webdav_url, auth=(webdav_login, webdav_password))
with open(local_path, 'wb') as f:
f.write(response_get.content)
def upload_file(self, file_name, local_path):
webdav_url = settings.WEBDAV_URL + f'remote.php/dav/files/{settings.WEBDAV_USERNAME}/Temp-File-Nando-Example/{file_name}'
webdav_login = settings.WEBDAV_USERNAME
webdav_password = settings.WEBDAV_PASSWORD
file_path = file_name + '/' + local_path
if os.path.exists(local_path):
with open(file_path, 'rb') as arquivo:
resposta = requests.put(
webdav_url,
auth=(webdav_login, webdav_password),
data=arquivo,
)
def delete_file(self, file_name):
webdav_url = settings.WEBDAV_URL + f'remote.php/dav/files/{settings.WEBDAV_USERNAME}/Temp-File-Nando-Example/{file_name}'
webdav_login = settings.WEBDAV_USERNAME
webdav_password = settings.WEBDAV_PASSWORD
requests.delete(webdav_url, auth=(webdav_login, webdav_password))
class HomeView(FormView):
template_name = 'manipulador/homepage.html'
form_class = UploadForm
success_url = reverse_lazy('home-page')
def get(self, request):
files = self.listing_file()
upload_form = self.form_class
return render(request, self.template_name, {'upload_form' : upload_form, 'files': files})
def post(self, request):
form = self.get_form()
if form.is_valid():
upload_file = form.cleaned_data['upload_file']
file_name = upload_file.name
file_path = f"manipulador_arquivos/upload-file/{file_name}"
with open(file_path,'wb') as destination:
for chunk in upload_file.chunks():
destination.write(chunk)
self.upload_file(file_name, file_path)
return super().post(request)
download_path = os.path.join(tempfile.gettempdir(), 'temp-file-download')
action = request.POST.get('action')
selected_file = request.POST.get('download')
if selected_file is None:
return redirect('home-page')
if action == 'delete':
self.delete_file(selected_file)
return redirect('home-page')
self.download_file(selected_file, download_path)
return FileResponse(open(download_path, 'rb'), as_attachment=True, filename=selected_file)
def listing_file(self):
options = {
'webdav_hostname': settings.WEBDAV_URL + f'remote.php/dav/files/{settings.WEBDAV_USERNAME}/Temp-File-Nando-Example',
'webdav_login': settings.WEBDAV_USERNAME,
'webdav_password': settings.WEBDAV_PASSWORD
}
client = Client(options)
return (client.list())[1:]
def upload_file(self, file_name, local_path):
webdav_url = settings.WEBDAV_URL + f'remote.php/dav/files/{settings.WEBDAV_USERNAME}/Temp-File-Nando-Example/{file_name}'
webdav_login = settings.WEBDAV_USERNAME
webdav_password = settings.WEBDAV_PASSWORD
if os.path.exists(local_path):
with open(local_path, 'rb') as arquivo:
requests.put(webdav_url, auth=(webdav_login, webdav_password), data=arquivo,)
os.remove(local_path)
def download_file(self, file_name, local_path):
webdav_url = settings.WEBDAV_URL + f'remote.php/dav/files/{settings.WEBDAV_USERNAME}/Temp-File-Nando-Example/{file_name}'
webdav_login = settings.WEBDAV_USERNAME
webdav_password = settings.WEBDAV_PASSWORD
response_get = requests.get(webdav_url, auth=(webdav_login, webdav_password))
with open(local_path, 'wb') as f:
f.write(response_get.content)
def delete_file(self, file_name):
webdav_url = settings.WEBDAV_URL + f'remote.php/dav/files/{settings.WEBDAV_USERNAME}/Temp-File-Nando-Example/{file_name}'
webdav_login = settings.WEBDAV_USERNAME
webdav_password = settings.WEBDAV_PASSWORD
requests.delete(webdav_url, auth=(webdav_login, webdav_password))
|
import { Injectable } from '@angular/core';
import { Tenant } from './tenant.model';
import { Subject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class TenantsService {
tenantsChanged = new Subject<Tenant[]>();
tenants: Tenant[] = [];
// private tenants: Tenant[] = [
// new Tenant(
// 'Gwyn Buescher',
// '801-234-1234',
// 'gwyn@email.com',
// '87 E 9270 S, Sandy',
// '$1300',
// '6/1/23 - 5/31/24',
// 'none',
// 'daughter 801-123-4321',
// 'none',
// 'Single older lady.'
// ),
// new Tenant(
// 'Shawn Breeland',
// '801-567-8901',
// 'shawn@email.com',
// '89 E 9270 S, Sandy',
// '$1300',
// '6/1/23 - 5/31/24',
// 'none',
// 'dad 801-123-4321',
// 'none',
// 'Single male, has a young son.'
// )
// ];
constructor(private http: HttpClient) { }
getTenants() {
this.http.get('http://localhost:3000/tenants')
.subscribe({
next: (tenantData: {message: string, tenants: Tenant[]}) => {
this.tenants = tenantData.tenants;
this.tenantsChanged.next(this.tenants.slice());
}
})
}
getTenant(index: number) {
return this.tenants[index];
}
addTenant(tenant: Tenant) {
this.http
.post<{message: string}>('http://localhost:3000/tenants', tenant)
.subscribe(responseData => {
console.log(responseData.message);
this.tenants.push(tenant);
this.tenantsChanged.next(this.tenants.slice());
console.log('Tenant added!');
});
}
updateTenant(index: number, newTenant: Tenant, originalTenant: Tenant) {
const position = this.tenants.indexOf(originalTenant);
if (position < 0) {
return;
}
// set the id of the new Document to the id of the old Document
newTenant._id = originalTenant._id;
this.http
.put('http://localhost:3000/tenants/' + newTenant._id, newTenant)
.subscribe(() => {
this.tenants[index] = newTenant;
this.tenantsChanged.next(this.tenants.slice());
console.log('Tenant updated!');
})
}
deleteTenant(tenant: Tenant) {
const position = this.tenants.indexOf(tenant);
if (position < 0) {
return;
}
this.http
.delete('http://localhost:3000/tenants/' + tenant._id)
.subscribe(() => {
this.tenants.splice(position, 1);
this.tenantsChanged.next(this.tenants.slice());
console.log('Deleted tenant!')
});
}
}
|
import React, { ChangeEvent, useState, KeyboardEvent } from 'react';
import style from '../Dialogs.module.scss';
import { WRITE_MESSAGE } from '../../../../constants';
import { AddMessageFormPropsType } from '../../types';
export const AddMessageForm = ( props: AddMessageFormPropsType ) => {
const [ messageText, setMessageText ] = useState<string>( '' );
const [ error, setError ] = useState<boolean>( false );
const validate = () => messageText.trim().length > 0 ? addMessage( messageText ) : setError( true );
const addMessage = ( messageText: string ) => {
props.addNewMessage( props.userID, messageText );
setMessageText( '' );
};
const onTextareaKeyPress = ( e: KeyboardEvent<HTMLTextAreaElement> ) => {
if ( e.code === 'Enter' ) validate();
};
const onTextareaChange = ( e: ChangeEvent<HTMLTextAreaElement> ) => {
setMessageText( e.currentTarget.value );
setError( false );
};
return (
<div className={ style.addMessageFormBlock }>
<div className={ style.addMessageFormContainer }>
<div className={ style.addMessageForm }>
<textarea
value={ messageText }
placeholder={ WRITE_MESSAGE }
className={ !error ? style.textField : `${ style.textField } ${ style.errorField }` }
onChange={ onTextareaChange }
onKeyPress={ onTextareaKeyPress }
/>
{ error && <span className={ style.errorSpan }>Min length is 1 symbol</span> }
</div>
<button disabled={ !props.userID } onClick={ validate }>Send</button>
</div>
</div>
);
};
|
import {SavingState, useStorage} from "../components/StorageProvider";
import Task from "../components/Task";
import {useEffect, useMemo, useState} from "react";
import usePrevious from "../data/usePrevious";
import {ToDoHistoryEntry, ToDoTask} from "../api";
import {AnimatePresence, motion} from "framer-motion";
import {Outlet, useNavigate, useParams} from "react-router-dom";
import styles from './TasksPage.module.scss'
import {Icon} from "semantic-ui-react";
export interface Props {
}
enum SortType {
PRIORITY,
TIMESTAMP,
LAST_EDIT
}
type Sorter = (a: ToDoTask, b: ToDoTask, h: ToDoHistoryEntry[]) => number
const sorters = new Map<SortType, Sorter>()
sorters.set(SortType.PRIORITY, (a, b) => (b.priority ?? 0) - (a.priority ?? 0) || b.timestamp! - a.timestamp!)
sorters.set(SortType.TIMESTAMP, (a, b) => b.timestamp! - a.timestamp!)
sorters.set(SortType.LAST_EDIT, (a, b, h) => {
const sortedHistory = h.sort((a, b) => b.timestamp! - a.timestamp!)
const ah = sortedHistory.find(h => h.newValue?.timestamp == a.timestamp || h.oldValue?.timestamp == a.timestamp) ?? {timestamp: 0}
const bh = sortedHistory.find(h => h.newValue?.timestamp == b.timestamp || h.oldValue?.timestamp == b.timestamp) ?? {timestamp: 0}
return bh.timestamp! - ah.timestamp!
})
const list = {
hidden: {
},
visible: {
transition: {
staggerChildren: 0.05
}
}
};
function TasksPage(props: Props) {
const {tasks, addTask, editTask, removeTask, savingState, history} = useStorage()
const [taskSorter, setTaskSorter] = useState<number[]>([])
const [sortType, setSortType] = useState<SortType>(SortType.TIMESTAMP)
const prevSortType = usePrevious(sortType)
const prevTasks = usePrevious(tasks)
const [initalAnimationCompleated, setInitalAnimationCompleated] = useState(false)
const navigate = useNavigate();
const {selectedToDo} = useParams()
const [newTaskName, setNewTaskName] = useState('')
useEffect(() => {
if (savingState == SavingState.SAVED || taskSorter.length != tasks.length || prevSortType != sortType) {
setTaskSorter(tasks.sort((a, b) => sorters.get(sortType)!(a, b, history)).map(t => t.timestamp!))
}
}, [tasks, savingState, sortType])
const sortedTasks = (tasks.length == taskSorter.length ? tasks : prevTasks ?? []).sort((a, b) => taskSorter.indexOf(a.timestamp!) - taskSorter.indexOf(b.timestamp!))
const onClick = (e: React.MouseEvent<HTMLElement>, t: ToDoTask) => {
if ((e.target as HTMLElement).classList.contains("task")) navigate(`task/${t.timestamp!.toString()}`)
}
return <>
{/*<button onClick={() => addTask({name: "Test", priority: 0})}>Add</button>*/}
{/*<br/>*/}
{/*<button onClick={() => setSortType(SortType.PRIORITY)}>Priority</button>*/}
{/*<button onClick={() => setSortType(SortType.TIMESTAMP)}>Creation time</button>*/}
{/*<button onClick={() => setSortType(SortType.LAST_EDIT)}>Last edit</button>*/}
<div className={styles.list}>
<div>
<motion.div layout layoutId={'newTask'} className={styles.add} initial={{opacity: 0}} animate={{opacity: 1}}>
<div className={styles.input}>
<input placeholder={"New task..."} value={newTaskName} onChange={(e) => setNewTaskName(e.target.value)}/>
</div>
<div className={styles.button}>
<button onClick={() => {
addTask({name: newTaskName, priority: 0});
setNewTaskName('')
}} className={styles.green}><Icon name={'add'}/></button>
</div>
</motion.div>
{sortedTasks.length > 0 && <motion.div initial="hidden" animate="visible" exit="hidden" variants={list} onAnimationComplete={() => setInitalAnimationCompleated(true)}>
<AnimatePresence>
{sortedTasks.map(t =>
<Task key={t.timestamp} selected={selectedToDo == t.timestamp} task={t} onEditTask={editTask} onRemoveTask={() => removeTask(t)} onClick={(e) => onClick(e, t)} initialAnimationCompleated={initalAnimationCompleated}/>
)}
</AnimatePresence>
</motion.div>}
</div>
</div>
<Outlet/>
</>
}
export default TasksPage;
|
# HTTP Proxying
## Client Apps Using Proxies
Use Cases:
- egress traffic to the internet from corporate networks for security controls and auditing - typical in banking
(I've [worked](https://www.linkedin.com/in/HariSekhon) for several large well known banks)
- reverse proxies like [Squid](https://www.squid-cache.org/)
- used by package managers and build tools to download programming language libraries eg. `mvn` for Java to pull from
Maven Central, `pip` for Python to pull from PyPI etc.
- [SSH tunnels in GCP](ssh-tunnelling.md#gcp) used by `kubectl` to access protected GKE clusters master control plane API
### Environment Variables - `https_proxy` / `no_proxy`
- `https_proxy` - tells applications using libraries like `libwww` to send the packets to this addresses to be
forwarded
on.
- `no_proxy` - comma separated list of domains / FQDNs to not use the proxy
You can use `HTTPS_PROXY` and `NO_PROXY` too but the lowercase variables have higher precedence for most applications,
except for Golang. See [here](https://about.gitlab.com/blog/2021/01/27/we-need-to-talk-no-proxy/) for the rules
various apps and languages follow.
Set both uppercase and lowercase to be the same to avoid any nasty surprises.
```shell
export https_proxy=http://localhost:8080
export no_proxy="domain1.com,host.domain2.com"
export HTTPS_PROXY="$https_proxy"
export NO_PROXY="$no_proxy"
```
|
package jadx.core.xmlgen;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
public class ParserStream {
protected static final Charset STRING_CHARSET_UTF16 = Charset.forName("UTF-16LE");
protected static final Charset STRING_CHARSET_UTF8 = Charset.forName("UTF-8");
private final InputStream input;
private long readPos = 0;
public ParserStream(InputStream inputStream) {
this.input = inputStream;
}
public long getPos() {
return readPos;
}
public int readInt8() throws IOException {
readPos++;
return input.read();
}
public int readInt16() throws IOException {
readPos += 2;
int b1 = input.read();
int b2 = input.read();
return (b2 & 0xFF) << 8 | (b1 & 0xFF);
}
public int readInt32() throws IOException {
readPos += 4;
InputStream in = input;
int b1 = in.read();
int b2 = in.read();
int b3 = in.read();
int b4 = in.read();
return b4 << 24 | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | (b1 & 0xFF);
}
public long readUInt32() throws IOException {
return readInt32() & 0xFFFFFFFFL;
}
public String readString8Fixed(int len) throws IOException {
String str = new String(readInt8Array(len), STRING_CHARSET_UTF8);
return str.trim();
}
public String readString16Fixed(int len) throws IOException {
String str = new String(readInt8Array(len * 2), STRING_CHARSET_UTF16);
return str.trim();
}
public String readString8() throws IOException {
decodeLength8();
int len = decodeLength8();
String str = new String(readInt8Array(len), STRING_CHARSET_UTF8);
checkInt8(0, "Not a trailing zero at string8 end");
return str;
}
public String readString16() throws IOException {
int len = decodeLength16();
String str = new String(readInt8Array(len), STRING_CHARSET_UTF16);
checkInt16(0, "Not a trailing zero at string16 end");
return str;
}
public int[] readInt32Array(int count) throws IOException {
if (count == 0) {
return new int[0];
}
int[] arr = new int[count];
for (int i = 0; i < count; i++) {
arr[i] = readInt32();
}
return arr;
}
public byte[] readInt8Array(int count) throws IOException {
if (count == 0) {
return new byte[0];
}
readPos += count;
byte[] arr = new byte[count];
int pos = input.read(arr, 0, count);
while (pos < count) {
int read = input.read(arr, pos, count - pos);
if (read == -1) {
throw new IOException("No data, can't read " + count + " bytes");
}
pos += read;
}
return arr;
}
public void skip(long count) throws IOException {
readPos += count;
long pos = input.skip(count);
while (pos < count) {
long skipped = input.skip(count - pos);
if (skipped == -1) {
throw new IOException("No data, can't skip " + count + " bytes");
}
pos += skipped;
}
}
public void checkInt8(int expected, String error) throws IOException {
int v = readInt8();
if (v != expected) {
throwException(error, expected, v);
}
}
public void checkInt16(int expected, String error) throws IOException {
int v = readInt16();
if (v != expected) {
throwException(error, expected, v);
}
}
private void throwException(String error, int expected, int actual) throws IOException {
throw new IOException(error
+ ", expected: 0x" + Integer.toHexString(expected)
+ ", actual: 0x" + Integer.toHexString(actual)
+ ", offset: 0x" + Long.toHexString(getPos()));
}
public void checkPos(long expectedOffset, String error) throws IOException {
if (getPos() != expectedOffset) {
throw new IOException(error + ", expected offset: 0x" + Long.toHexString(expectedOffset)
+ ", actual: 0x" + Long.toHexString(getPos()));
}
}
public void skipToPos(long expectedOffset, String error) throws IOException {
long pos = getPos();
if (pos < expectedOffset) {
skip(expectedOffset - pos);
}
checkPos(expectedOffset, error);
}
public int decodeLength8() throws IOException {
int len = readInt8();
if ((len & 0x80) != 0) {
len = ((len & 0x7F) << 8) | readInt8();
}
return len;
}
public int decodeLength16() throws IOException {
int len = readInt16();
if ((len & 0x8000) != 0) {
len = ((len & 0x7FFF) << 16) | readInt16();
}
return len;
}
@Override
public String toString() {
return "pos: 0x" + Long.toHexString(readPos);
}
}
|
<template>
<el-row>
<el-button type="primary" @click="showCreateForm">Create My Organization </el-button>
</el-row>
<el-table :data="tableData.arr" style="width: 100%">
<el-table-column prop="org_name" label="Name" width="120" />
<el-table-column prop="org_code" label="Code" width="120" />
<el-table-column>
<template #default="scope">
<el-button link type="primary" size="small" @click="edit(scope)">Edit</el-button>
</template>
</el-table-column>
<el-table-column>
<template #default="scope">
<el-col>
<el-button type="primary" size="small" @click="select(scope)">Select</el-button>
</el-col>
</template>
</el-table-column>
</el-table>
<CreateOrginsationDialog :dialogShow="dialogShow" @dialogClosed="dialogClosed"/>
<UpdateOrginsationDialog :dialogShow="editDialogShow" :editdata ="editdata" @editDialogClosed="editDialogClosed"/>
</template>
<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import CreateOrginsationDialog from '@/components/Organisation/CreateOrganisationDialog.vue';
import UpdateOrginsationDialog from '@/components/Organisation/UpdateOrganisationDialog.vue';
import service from "@/webservice";
import {getCurrentInstance} from 'vue'
onMounted(()=> {
//setup 是围绕beforeCreate和created生命周期钩子运行的,不需要显式地定义它们。在这些钩子中编写的任何代码都应该直接在 setup 函数中编写。
//生命周期基本都被重命名 首字母大写后加上on前缀 例如beforeUpdate => onBeforeUpdate
findData();
})
const globalProperties = getCurrentInstance().appContext.config.globalProperties;
const headers = globalProperties.$defaultheaders
let dialogShow = ref(false);
let editDialogShow = ref(false);
let editdata =ref([]);
let selectdata = ref([]);
let tableData = reactive({
arr: []
});
const dialogClosed = ()=>{
findData();
dialogShow.value = false;
editdata =ref([]);
}
const edit = (scope) => {
editdata = scope.row;
editDialogShow.value = true;
}
const emit = defineEmits(['dialogClosed'])
const select = (scope) => {
selectdata = scope.row;
dialogShow.value = false;
emit('dialogClosed',selectdata);
}
const editDialogClosed = ()=>{
findData();
editDialogShow.value = false;
}
const showCreateForm = () => {
dialogShow.value = true;
}
const findData = ()=> {
let organisation = {
created_user_id:localStorage.getItem('userid')
};
service.get('http://'+globalProperties.$serviceurl+'/findorgbyuserid',
organisation,
headers).then(response=> {
tableData.arr=response.data;
})
}
</script>
|
package com.nowcoder.community.entity;
/*
*
* 封装分页相关的信息
*
* */
public class Page {
//当前页码
private int current=1;
//显示上限
private int limit=10;
//数据总数(用于计算总页数)
private int rows;
//查询路径(用于复用分页链接)
private String path;
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
if(current >=1){
this.current = current;
}
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
if(limit>=1 && limit <=100) {
this.limit = limit;
}
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
if(rows>=0) {
this.rows = rows;
}
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
/*
* 获取当前页的起始行
* */
public int getOffset(){
//current *limit -limit
return (current-1)*limit;
}
/*
* 获取总的页数
* */
public int getTotal(){
// rows/limit
if(rows % limit == 0){
return rows /limit;
}else{
return rows/limit +1;
}
}
/*
* 获取起始页数
* */
public int getFrom(){
int from = current -2;
return from < 1 ? 1 : from;
}
/*
* 获取结束页数
* */
public int getTo(){
int to =current +2;
int total = getTotal();
return to>total ? total : to;
}
}
|
import React, { useState } from 'react';
import { useEffect } from 'react';
import './Shop.css'
import Product from '../Product/Product'
import Cart from '../Cart/Cart';
import { addToDb, getStoredCart } from '../fakeDB/fakeDB';
const Shop = () => {
const [products, setProducts] = useState([]);
const [cart, setCart] = useState([])
useEffect(() => {
fetch('products.json')
.then(res => res.json())
.then(data => setProducts(data))
},[])
useEffect(() =>{
// console.log('stored cart')
const storedCart =getStoredCart();
// console.log(storedCart);
const savedCart = [];
for(const id in storedCart){
const addedProduct = products.find(product => product.id === id);
if(addedProduct){
const quantity =storedCart[id]
addedProduct.quantity =quantity;
// console.log(addedProduct)
savedCart.push(addedProduct);
}
}
setCart(savedCart);
},[products])
const addToCart =(product) =>{
const newCart =[...cart,product]
setCart(newCart)
addToDb(product.id)
}
return (
<div className='shop-container'>
<div className="product-container">
{
products.map(product => <Product product={product}
key={product.id}
addToCart ={addToCart}
></Product>)
}
</div>
<div className="cart-container">
<Cart cart={cart}>
</Cart>
</div>
</div>
);
};
export default Shop;
|
"""Blogly application."""
from flask import Flask,request,redirect,render_template
from models import db, connect_db,User
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///blogly'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
connect_db(app)
db.create_all()
@app.root('/')
def root():
"""Redirect homepade to users"""
return redirect("/users")
@app.route('/users')
def users_index():
"""Display user information"""
users=User.query.order_by(User.first_name,User.last_name).all()
return render_template('users/index.html',users=users)
@app.route('/users/signUp',methods=["GET"])
def user_SignUp_form():
return render_template('users/signUp.html')
@app.route("users/signUp",method=["POST"])
def new_user_entry():
"""Create new user form and then submit"""
new_user=User(
first_name=request.form['first_name'],
last_name=request.form['last_name'],
image_url=request.form['image_url' or None]
)
db.session.add(new_user)
db.session.commit()
return redirect("/users")
@app.route('/users/<int:user_id>')
def users_display(user_id):
"""Display user deatail using """
user = User.query.get_or_404(user_id)
return render_template('users/DisplayUser.html', user=user)
@app.route('/users/<int:user_id>/editUser')
def users_edit(user_id):
"""Edit existing user"""
user = User.query.get_or_404(user_id)
return render_template('users/editUser.html', user=user)
@app.route('/users/<int:user_id>/edit', methods=["POST"])
def users_update(user_id):
"""Update user information and submit"""
user = User.query.get_or_404(user_id)
user.first_name = request.form['first_name']
user.last_name = request.form['last_name']
user.image_url = request.form['image_url']
db.session.add(user)
db.session.commit()
return redirect("/users")
@app.route('/users/<int:user_id>/delete', methods=["POST"])
def users_delete(user_id):
"""Delete user information and submit"""
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return redirect("/users")
|
const std = @import("std");
const stdout = std.io.getStdOut().writer();
// const ArrayList = std.ArrayList;
const Vec = @import("vec.zig").Vec;
const AutoHashMap = std.AutoHashMap;
const PriorityQueue = @import("priorityQueue.zig").PriorityQueue;
const __input = @import("input.zig");
const readInput = __input.readInput;
const deallocInput = __input.deallocInput;
const Grid = @import("grid.zig").Grid;
const Vec2 = struct { x: u32, y: u32 };
fn vec_eql(a: Vec2, b: Vec2) bool {
const x_eql: bool = a.x == b.x;
const y_eql: bool = a.y == b.y;
return x_eql and y_eql;
}
pub fn main() !void {
const cost = try part1("input.txt", Vec2{ .x = 100, .y = 100 });
try stdout.print("Part 1 cost: {d}\n", .{cost});
const cost2 = try part2("input.txt", Vec2{ .x = 100, .y = 100 });
try stdout.print("Part 2 cost: {d}\n", .{cost2});
}
fn part1(input_file: []const u8, map_size: Vec2) !u32 {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const input = try readInput(allocator, input_file);
defer {
deallocInput(input);
allocator.destroy(input);
}
const grid = Grid.init(input, @as(usize, map_size.x), @as(usize, map_size.y));
const end = Vec2{
.x = map_size.x - 1,
.y = map_size.y - 1,
};
const cost = try pathfind(allocator, &grid, end);
return cost;
}
fn part2(input_file: []const u8, original_map_size: Vec2) !u32 {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const input = try readInput(allocator, input_file);
defer {
deallocInput(input);
allocator.destroy(input);
}
const grid = Grid.init(input, @as(u32, original_map_size.x), @as(u32, original_map_size.y));
// var row: usize = 0;
// while (row < 50) : (row += 1) {
// var col: usize = 0;
// while (col < 50) : (col += 1) {
// try stdout.print("{d}", .{grid.get(row, col)});
// }
// try stdout.print("\n", .{});
// }
const end = Vec2{
.x = (original_map_size.x * 5) - 1,
.y = (original_map_size.y * 5) - 1,
};
const cost = try pathfind(allocator, &grid, end);
return cost;
}
/// A* pathfinding
fn pathfind(allocator: std.mem.Allocator, input: *const Grid, end: Vec2) !u32 {
var frontier = PriorityQueue(Vec2).init(allocator);
defer frontier.free();
try frontier.push(Vec2{ .x = 0, .y = 0 }, 0);
var came_from = AutoHashMap(Vec2, Vec2).init(allocator);
defer came_from.deinit();
var cost_so_far = AutoHashMap(Vec2, u32).init(allocator);
defer cost_so_far.deinit();
var _current = frontier.pop();
while (_current != null) : (_current = frontier.pop()) {
var current = _current.?;
if (vec_eql(current, end)) {
break;
}
for (neighbours(current, end)) |_next| {
if (_next == null) continue;
var next = _next.?;
var cost_so_far_current: ?u32 = cost_so_far.get(current);
if (cost_so_far_current == null) cost_so_far_current = 0;
// const cost = input.get(next.y).?.get(next.x).?;
const cost = input.get(next.y, next.x);
const new_cost = cost_so_far_current.? + @as(u32, cost);
if (!cost_so_far.contains(next) or new_cost < cost_so_far.get(next).?) {
try cost_so_far.put(next, new_cost);
const priority = new_cost;
try frontier.push(next, priority);
try came_from.put(next, current);
}
}
}
// Walk path and add costs
var current_pos = end;
var total_cost: u32 = 0;
var path = try Vec(Vec2).init(allocator);
defer path.free();
var path_len: u32 = 1;
// var iter = came_from.iterator();
// var elem = iter.next();
// while (elem != null) : (elem = iter.next()) {
// try stdout.print("{} -> {}\n", .{ elem.?.key_ptr.*, elem.?.value_ptr.* });
// }
try path.push(current_pos);
// total_cost += input.items[current_pos.y].items[current_pos.x];
total_cost += input.get(current_pos.y, current_pos.x);
while (!vec_eql(current_pos, Vec2{ .x = 0, .y = 0 })) {
const current_pos_tmp = came_from.get(current_pos);
current_pos = if (current_pos_tmp == null) return Error.CameFromIsNull else current_pos_tmp.?;
// total_cost += input.items[current_pos.y].items[current_pos.x];
total_cost += input.get(current_pos.y, current_pos.x);
// try stdout.print("{} - {}\n", .{ current_pos, input.items[current_pos.y].items[current_pos.x] });
try path.push(current_pos);
path_len += 1;
}
// total_cost -= input.items[0].items[0]; // Don't count starting position
total_cost -= input.get(0, 0);
// Print taken path
var i: usize = path_len;
while (i > 0) {
i -= 1;
const item = path.items[i];
try stdout.print("{}, {}", item);
if (i != 0) {
try stdout.print(" -> ", .{});
} else {
try stdout.print("\n", .{});
}
}
return total_cost;
}
const Error = error{CameFromIsNull};
fn neighbours(pos: Vec2, bounds: Vec2) [4]?Vec2 {
var _neighbours: [4]?Vec2 = [_]?Vec2{ null, null, null, null };
if (pos.x != 0) {
_neighbours[0] = pos;
_neighbours[0].?.x -= 1;
}
if (pos.y != 0) {
_neighbours[1] = pos;
_neighbours[1].?.y -= 1;
}
if (pos.x != bounds.x) {
_neighbours[2] = pos;
_neighbours[2].?.x += 1;
}
if (pos.y != bounds.y) {
_neighbours[3] = pos;
_neighbours[3].?.y += 1;
}
return _neighbours;
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "example_input1" {
const cost: u32 = try part1("example.txt", Vec2{ .x = 10, .y = 10 });
try expectEqual(@as(u32, 40), cost);
}
test "example_input2" {
const cost: u32 = try part2("example.txt", Vec2{ .x = 10, .y = 10 });
try expectEqual(@as(u32, 315), cost);
}
|
<?php
namespace App\Filament\Clusters\Programas\Resources\OrcamentoprogramaResource\Pages;
use App\Filament\Clusters\Programas\Resources\OrcamentoprogramaResource;
use App\Models\OrcamentoPrograma;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
class CreateOrcamentoprograma extends CreateRecord
{
protected static string $resource = OrcamentoprogramaResource::class;
public function getSubNavigation(): array
{
if (filled($cluster = static::getCluster())) {
return $this->generateNavigationItems($cluster::getClusteredComponents());
}
return [];
}
protected function beforeCreate(): void
{
$id_programa = $this->data['id_programa'] ?? null;
// Verificar se já existe um registro com as mesmas condições
$existingRecord = OrcamentoPrograma::where('id_programa', $id_programa)
->exists();
// Se já existir um registro com as mesmas condições, interrompa o processo de criação
if ($existingRecord) {
// Emitir uma notificação de erro
Notification::make()
->danger()
->duration(5000)
->title('Erro ao atribuir Orcamento')
->body('O programa selecionado, ja possui um orcamento')
->send();
// Interromper o processo de criação
$this->halt();
} else{
// Emitir uma notificação de erro
Notification::make()
->success()
->duration(5000)
->title('Orcamento atribuido')
->body('Orcamento atribuido com sucesso')
->sendToDatabase(\auth()->user())
->send();
}
}
}
|
import Head from "next/head"
import React, { FC, Suspense, useState } from "react"
import { BlitzLayout, Routes } from "@blitzjs/next"
import { NotificationList } from "../components/NotificationList"
import NoSSR from "@material-ui/core/NoSsr"
import "dayjs/locale/ru"
import PeopleIcon from "@mui/icons-material/People"
import ComputerIcon from "@mui/icons-material/Computer"
import DashboardIcon from "@mui/icons-material/Dashboard"
import MenuIcon from "@mui/icons-material/Menu"
import BadgeIcon from "@mui/icons-material/Badge"
import Link from "next/link"
import { LocalizationProvider } from "@mui/x-date-pickers"
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"
import CloseIcon from "@mui/icons-material/Close"
import SettingsIcon from "@mui/icons-material/Settings"
import {
Avatar,
Stack,
Container,
AppBar,
Toolbar,
IconButton,
Typography,
List,
ListItemButton,
ListItemIcon,
ListItemText,
SwipeableDrawer,
} from "@mui/material"
import { useRouter } from "next/router"
import { useCurrentUser } from "../../users/hooks/useCurrentUser"
import LoginIcon from "@mui/icons-material/Login"
import PersonAddIcon from "@mui/icons-material/PersonAdd"
import LogoutIcon from "@mui/icons-material/Logout"
import { useMutation } from "@blitzjs/rpc"
import logout from "../../auth/mutations/logout"
import { RouteUrlObject } from "blitz"
import { ConfirmProvider, useConfirm } from "../components/Confirm"
import PaymentsIcon from "@mui/icons-material/Payments"
interface ILink {
href: RouteUrlObject
label: string
icon: React.ReactNode
}
const linksIfClub: ILink[] = [
{ href: Routes.Home(), label: "Главная", icon: <DashboardIcon /> },
{ href: Routes.CashPage(), label: "Касса", icon: <PaymentsIcon /> },
{ href: Routes.ComputersPage(), label: "Компьютеры", icon: <ComputerIcon /> },
{ href: Routes.GizmoUsersPage(), label: "Пользователи GIZMO", icon: <PeopleIcon /> },
{ href: Routes.ShiftsPage(), label: "Смены", icon: <BadgeIcon /> },
]
const linksAlways: ILink[] = [
{ href: Routes.SettingsPage(), label: "Настройки", icon: <SettingsIcon /> },
]
const Layout: BlitzLayout<{ title?: string; children?: React.ReactNode }> = ({
title,
children,
}) => {
const [open, setOpen] = useState(false)
const router = useRouter()
// const currentUser = useCurrentUser()
const handleDrawerOpen = () => {
setOpen(true)
}
const handleDrawerClose = () => {
setOpen(false)
}
return (
<NoSSR>
<LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale={"ru"}>
<ConfirmProvider>
<>
<Head>
<title>{title || "gizmo-debitsoft-client"}</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Suspense fallback={<div>Loading...</div>}>
<AppBarComponent title={title} handleDrawerOpen={handleDrawerOpen} />
</Suspense>
<NotificationList />
<Suspense fallback={<div>Loading...</div>}>
<Drawer
handleDrawerOpen={() => handleDrawerOpen()}
open={open}
handleDrawerClose={() => handleDrawerClose()}
/>
</Suspense>
<main>
{/*<Toolbar title={title} />*/}
<Container style={{ marginTop: 15 }} maxWidth="lg">
{children}
</Container>
</main>
</>
</ConfirmProvider>
</LocalizationProvider>
</NoSSR>
)
}
interface DrawerProps {
open: boolean
handleDrawerClose: () => void
handleDrawerOpen: () => void
}
interface LinkItemProps extends ILink {
handleDrawerClose: () => void
open: boolean
}
const LinkItem: FC<LinkItemProps> = ({ href, label, icon, handleDrawerClose, open }) => {
const router = useRouter()
return (
<Link href={href}>
<ListItemButton
selected={router.pathname === href.pathname}
onClick={handleDrawerClose}
sx={{
minHeight: 48,
justifyContent: open ? "initial" : "center",
px: 2.5,
}}
>
<ListItemIcon
sx={{
minWidth: 0,
mr: open ? 3 : "auto",
justifyContent: "center",
color: router.pathname === href.pathname ? "primary.main" : "inherit",
}}
>
{icon}
</ListItemIcon>
<ListItemText primary={label} sx={{ opacity: open ? 1 : 0 }} />
</ListItemButton>
</Link>
)
}
const Drawer: FC<DrawerProps> = ({ handleDrawerOpen, open, handleDrawerClose }) => {
const currentUser = useCurrentUser()
const router = useRouter()
if (!currentUser) return null
return (
<SwipeableDrawer
anchor={"left"}
open={open}
onClose={handleDrawerClose}
onOpen={handleDrawerOpen}
>
<Stack direction={"row"} justifyContent={"space-between"} alignItems={"center"} mx={1}>
<Typography variant={"h6"}>DEBit Gizmo</Typography>
<IconButton color={"primary"} size={"large"} edge={"end"} onClick={handleDrawerClose}>
<CloseIcon />
</IconButton>
</Stack>
<Avatar sx={{ mx: "auto", my: 2 }}>DE</Avatar>
<List sx={{ marginTop: 10 }}>
{currentUser.Club &&
linksIfClub.map((link, index) => (
<LinkItem {...link} key={index} handleDrawerClose={handleDrawerClose} open={open} />
))}
{linksAlways.map((link, index) => (
<LinkItem {...link} key={index} handleDrawerClose={handleDrawerClose} open={open} />
))}
</List>
</SwipeableDrawer>
)
}
const AppBarComponent: FC<{ title: string | undefined; handleDrawerOpen: () => void }> = ({
title,
handleDrawerOpen,
}) => {
const [logoutMutation] = useMutation(logout)
const confirm = useConfirm()
const router = useRouter()
const currentUser = useCurrentUser()
return (
<AppBar position="sticky">
<Toolbar
sx={{
justifyContent: "space-between",
}}
>
<Stack direction={"row"} spacing={2} alignItems={"center"}>
{currentUser ? (
<IconButton edge="start" color="inherit" aria-label="menu" onClick={handleDrawerOpen}>
<MenuIcon />
</IconButton>
) : null}
<Typography variant="h6">{title}</Typography>
</Stack>
{!currentUser ? (
<Stack direction={"row"} spacing={2}>
<Link href={Routes.LoginPage()}>
<IconButton color={"inherit"} edge={"end"}>
<LoginIcon fontSize={"large"} />
</IconButton>
</Link>
<Link href={Routes.SignupPage()}>
<IconButton color={"inherit"} edge={"end"}>
<PersonAddIcon fontSize={"large"} />
</IconButton>
</Link>
</Stack>
) : (
<Stack direction={"row"} spacing={2} alignItems={"center"}>
<IconButton
color={"inherit"}
edge={"end"}
onClick={async () => {
confirm.open({
id: "signout",
title: "Вы уверены что хотите выйти?",
message: "Все несохраненные данные будут потеряны",
confirmText: "Выйти",
cancelText: "Отмена",
onConfirm: async () => {
await logoutMutation()
},
})
}}
>
<LogoutIcon fontSize={"large"} />
</IconButton>
</Stack>
)}
</Toolbar>
</AppBar>
)
}
export default Layout
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- HEADER -->
<header>
<div>
<a><img /></a>
</div>
<div>
<a>LINK</a>
<a>LINK</a>
<a>LINK</a>
</div>
</header>
<!-- MAIN -->
<main>
<!-- BANNER -->
<section>
<div>
<h1></h1>
<p></p>
<button></button>
</div>
<!-- BLOCK 1 -->
<div>
<h2>TITLE</h2>
<div>
<img />
<h3>NAME</h3>
<p>TEXT</p>
</div>
<!-- BLOCK 2 -->
<div>
<img />
<h3>NAME</h3>
<p>TEXT</p>
</div>
<!-- BLOCK 3 -->
<div>
<img />
<h3>NAME</h3>
<p>TEXT</p>
</div>
<!-- BLOCK 4 -->
<div>
<img />
<h3>NAME</h3>
<p>TEXT</p>
</div>
</div>
</section>
<!-- QUOTE -->
<section>
<div>
<img />
<div>
<blockquote>QUOTE</blockquote>
<p>AUTHOR</p>
<p>TEXT</p>
</div>
</div>
</section>
<!-- VIDEO -->
<section>
<h1>Title</h1>
<!-- ITEM 1 -->
<div>
<div>
<img src="" alt="" />
<h2>TITLE</h2>
<p>TEXT</p>
<!-- AUTHOR -->
<div>
<img src="" alt="" />
<h3></h3>
</div>
<!-- RATING -->
<div>
<div>
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
</div>
<p>TEXT</p>
</div>
</div>
</div>
<!-- ITEM 2 -->
<div>
<div>
<img src="" alt="" />
<h2>TITLE</h2>
<p>TEXT</p>
<!-- AUTHOR -->
<div>
<img src="" alt="" />
<h3></h3>
</div>
<!-- RATING -->
<div>
<div>
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
</div>
<p>TEXT</p>
</div>
</div>
</div>
<!-- ITEM 3 -->
<div>
<div>
<img src="" alt="" />
<h2>TITLE</h2>
<p>TEXT</p>
<!-- AUTHOR -->
<div>
<img src="" alt="" />
<h3></h3>
</div>
<!-- RATING -->
<div>
<div>
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
</div>
<p>TEXT</p>
</div>
</div>
</div>
<!-- ITEM 4 -->
<div>
<div>
<img src="" alt="" />
<h2>TITLE</h2>
<p>TEXT</p>
<!-- AUTHOR -->
<div>
<img src="" alt="" />
<h3></h3>
</div>
<!-- RATING -->
<div>
<div>
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
</div>
<p>TEXT</p>
</div>
</div>
</div>
</section>
<!-- MEMBERSHIP -->
<section>
<h1>TITLE</h1>
<div>
<!-- BLOCK 1 -->
<div>
<img src="" alt="" />
<h2>TITLE</h2>
<p></p>
</div>
<!-- BLOCK 2 -->
<div>
<img src="" alt="" />
<h2>TITLE</h2>
<p></p>
</div>
<!-- BLOCK 3 -->
<div>
<img src="" alt="" />
<h2>TITLE</h2>
<p></p>
</div>
<!-- BLOCK 4 -->
<div>
<img src="" alt="" />
<h2>TITLE</h2>
<p></p>
</div>
<button>BUTTON</button>
</div>
</section>
<!-- FAQ -->
<section>
<h1>TITLE</h1>
<div>
<!-- ITEM BLOCK 1 -->
<div>
<h2>TITLE</h2>
<p>TEXT</p>
</div>
<!-- ITEM BLOCK 2 -->
<div>
<h2>TITLE</h2>
<p>TEXT</p>
</div>
</div>
</section>
</main>
<!-- FOOTER -->
<footer>
<div>
<div>
<!-- logo -->
<img src="" alt="" />
<div>
<a><img src="" alt="" /></a>
<a><img src="" alt="" /></a>
<a><img src="" alt="" /></a>
</div>
</div>
<p>TEXT</p>
</div>
</footer>
</body>
</html>
|
#include <stdio.h>
#include <time.h>
#include <assert.h>
#include <stdlib.h>
#include "model/updater.h"
#include "view/view.h"
#include "view/common.h"
#include "view/theme/style.h"
#include "src/extra/libs/qrcode/lv_qrcode.h"
#include "config/app_config.h"
#include <esp_log.h>
enum {
BTN_BACK_ID,
BTN_CREATE_ID,
BTN_MODIFY_ID,
};
struct page_data {
lv_obj_t *list;
unsigned long timestamp;
lv_calendar_date_t *date;
};
static void update_list(model_t *pmodel, struct page_data *pdata);
static const char *TAG = "PageAlarms";
static void *create_page(pman_handle_t handle, void *extra) {
(void)handle;
(void)extra;
struct page_data *pdata = lv_mem_alloc(sizeof(struct page_data));
assert(pdata != NULL);
pdata->date = extra;
return pdata;
}
static void open_page(pman_handle_t handle, void *state) {
struct page_data *pdata = state;
model_updater_t updater = pman_get_user_data(handle);
model_t *pmodel = model_updater_read(updater);
lv_obj_t *btn = lv_btn_create(lv_scr_act());
lv_obj_set_size(btn, 56, 56);
lv_obj_t *symbol = lv_label_create(btn);
lv_obj_set_style_text_font(symbol, STYLE_FONT_BIG, LV_STATE_DEFAULT);
lv_label_set_text(symbol, LV_SYMBOL_LEFT);
lv_obj_center(symbol);
lv_obj_align(btn, LV_ALIGN_TOP_LEFT, 8, 8);
view_register_object_default_callback(btn, BTN_BACK_ID);
lv_obj_t *lbl = lv_label_create(lv_scr_act());
lv_label_set_text_fmt(lbl, "%02i/%02i/%02i", pdata->date->day, pdata->date->month, pdata->date->year);
lv_obj_align(lbl, LV_ALIGN_TOP_MID, 0, 8);
lv_obj_t *list = lv_list_create(lv_scr_act());
lv_obj_set_style_text_font(list, STYLE_FONT_SMALL, LV_STATE_DEFAULT);
lv_obj_set_size(list, LV_HOR_RES, LV_VER_RES - 80);
lv_obj_align(list, LV_ALIGN_BOTTOM_MID, 0, 0);
pdata->list = list;
update_list(pmodel, pdata);
}
static pman_msg_t page_event(pman_handle_t handle, void *state, pman_event_t event) {
(void)handle;
pman_msg_t msg = PMAN_MSG_NULL;
struct page_data *pdata = state;
model_updater_t updater = pman_get_user_data(handle);
model_t *pmodel = model_updater_read(updater);
switch (event.tag) {
case PMAN_EVENT_TAG_TIMER: {
break;
}
case PMAN_EVENT_TAG_LVGL: {
view_obj_data_t *obj_data = lv_obj_get_user_data(lv_event_get_current_target(event.as.lvgl));
switch (lv_event_get_code(event.as.lvgl)) {
case LV_EVENT_CLICKED:
switch (obj_data->id) {
case BTN_BACK_ID:
msg.stack_msg = PMAN_STACK_MSG_BACK();
break;
case BTN_CREATE_ID: {
size_t alarm_num = model_updater_add_alarm(
updater, pdata->date->day, pdata->date->month - 1, pdata->date->year - 1900);
msg.stack_msg = PMAN_STACK_MSG_PUSH_PAGE_EXTRA(&page_alarm, (void *)(uintptr_t)alarm_num);
break;
}
case BTN_MODIFY_ID: {
size_t alarm_num = obj_data->number;
msg.stack_msg = PMAN_STACK_MSG_PUSH_PAGE_EXTRA(&page_alarm, (void *)(uintptr_t)alarm_num);
break;
}
default:
break;
}
default:
break;
}
break;
}
case PMAN_EVENT_TAG_USER: {
view_event_t *view_event = event.as.user;
switch (view_event->tag) {
case VIEW_EVENT_TAG_VARIABLE_WATCHER: {
break;
}
default:
break;
}
break;
}
default:
break;
}
return msg;
}
static void destroy_page(void *state, void *extra) {
lv_mem_free(extra);
lv_mem_free(state);
}
static void update_list(model_t *pmodel, struct page_data *pdata) {
lv_obj_clean(pdata->list);
uint8_t found = 0;
size_t count = 0;
do {
size_t alarm_num = 0;
found = model_get_nth_alarm_for_day(pmodel, &alarm_num, count, pdata->date->day, pdata->date->month - 1,
pdata->date->year - 1900);
if (found) {
count++;
char string[MAX_DESCRIPTION_LEN + 32] = {0};
time_t timestamp = model_get_alarm(pmodel, alarm_num).timestamp;
struct tm time_tm = *localtime(×tamp);
snprintf(string, sizeof(string), "[%02i:%02i] %s", time_tm.tm_hour, time_tm.tm_min,
model_get_alarm(pmodel, alarm_num).description);
lv_obj_t *btn = lv_list_add_btn(pdata->list, NULL, string);
lv_label_set_long_mode(lv_obj_get_child(btn, 0), LV_LABEL_LONG_DOT);
view_register_object_default_callback_with_number(btn, BTN_MODIFY_ID, alarm_num);
}
} while (found);
if (model_get_active_alarms(pmodel) < MAX_ALARMS) {
lv_obj_t *btn = lv_list_add_btn(pdata->list, LV_SYMBOL_PLUS, "New event");
view_register_object_default_callback(btn, BTN_CREATE_ID);
}
}
const pman_page_t page_alarms = {
.create = create_page,
.destroy = destroy_page,
.open = open_page,
.close = pman_close_all,
.process_event = page_event,
};
|
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>01- Exo</title>
<script>
// EXERCISE 1- Déclaration des variables
// num qui contient le nombre 255
// txt qui contient la chaîne de caractères 255
// bin qui contient la valeur booléenne VRDisplayEvent
// flt qui contient la valeur 7.23
// Affichez les variables dans des console.log
var num = 255;
var txt = '255';
var bin = true;
var flt = 7.23;
console.log(num,txt,bin,flt)
// EXERCISE 2
// Aplliquer à num l'opérateur d'incrémentation
num++;
console.log(num)
// concaténez à la chaine txt la chaîne suivante : 'est ici une chaîne de caractères'
console.log('est ici une chaîne de caractères' + txt);
//Inverser la valeur logique de bin
bin = false;
//Ajouter à flt la valeur contenue dans num
flt = flt + num
// flt += num //
console.log('flt + num = ',flt)
// EXERCISE 3
// num2 qui contient le nombre 23
let num2 = 23;
console.log('num2 contient',num2);
// txt2 la chaîne de caractère 33
let txt2 = '33'
console.log(num2,'en chaîne de caractère');
// affichez le résulat de txt2 + num2 dans la console.log()
// on peut pas aditionner une String et un nombre
resultat = txt2 + num2
console.log('<br>',txt2,resultat,typeof(resultat), 'le resultat nous montre montre que c\'est une String')
// affichez le résulat de txt2 + num2
// avec num2 + txt2
// on ajoute une variable tmp qui contient 0
// Convertir la châine contenue dans le txt2 en nombre avec parseInt() et mettre le résultat dans tmp
// ajouter à num2 le contenu de tmp
var tmp = 0;
let parseInteger = parseInt(txt2)
console.log(typeof(txt2,parseInteger))
tmp = parseInteger + num2
</script>
</head>
<body>
<h1>Exo</h1>
</body>
</html>
|
{% extends "../base.twig" %}
{% set base = false %}
{% set sidebar = true %}
{% set secondary_sidebar = true %}
{% set sidebar_menu_active_item = 'select' %}
{% set heder_menu_active_item = 'components' %}
{% block title %}Селекты{% endblock %}
{% block head %}
{{ parent() }}
{% endblock %}
{% block breadcrumbs %}
<div class="breadcrumbs">
<ul class="breadcrumbs-list">
<li class="breadcrumbs-item">
<a href="/" class="breadcrumbs-link">Начало</a>
</li>
<li class="breadcrumbs-item">Компоненты</li>
<li class="breadcrumbs-item">
<a href="select.html" class="breadcrumbs-link">Селекты</a>
</li>
</ul>
</div>
{% endblock %}
{% block pagetitle %}
<div class="title d-block">
<h1>Селекты</h1>
<span class="tagline">Компонент предназначен для добавления в интерфейс стилизованных селектов.<br>Дополнительная информация - <a href="https://select2.org/" target="_blank">https://select2.org/</a></span>
</div>
{% endblock %}
{% block secondary_sidebar %}
<nav class="vertical-menu">
<ul>
<li>
<a href="#s-1">
<span class="menu-label">Обычный селект</span>
</a>
</li>
<li>
<a href="#s-2">
<span class="menu-label">Выбранный селект</span>
</a>
</li>
<li>
<a href="#s-3">
<span class="menu-label">Cелект с текстом-заполнителем</span>
</a>
</li>
<li>
<a href="#s-4">
<span class="menu-label">Cелект с включенным поиском</span>
</a>
</li>
<li>
<a href="#s-5">
<span class="menu-label">Cелект с управляемой шириной</span>
</a>
</li>
<li>
<a href="#s-6">
<span class="menu-label">Отключенный селект</span>
</a>
</li>
<li>
<a href="#s-7">
<span class="menu-label">Селект с меткой</span>
</a>
</li>
<li>
<a href="#s-8">
<span class="menu-label">Селект с множественным выбором</span>
</a>
</li>
<li>
<a href="#s-9">
<span class="menu-label">Селект с очисткой выбора</span>
</a>
</li>
</ul>
</nav>
{% endblock %}
{% block content %}
<section id="s-1">
<div class="components-title">
<h2>Селект</h2>
<p>Пример обычного селекта</p>
</div>
<div class="components-preview">
<div class="field">
<select name="name">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-1-1">HTML</a>
</li>
<li>
<a href="#tab-react-1-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-1-1">
<div class="components-code">
<pre>
<code class="language-html">
<textarea>
<div class="field">
<select name="name">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container mb-24">
<table>
<thead>
<tr>
<th>data-атрибут</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data-placeholder</div>
</td>
<td>
<div class="td-content">Задает текст-заполнитель для селекта, у которого отсутствует выбранная опция </div>
</td>
</tr>
<tr>
<td>
<div class="td-content">data-select2-search</div>
</td>
<td>
<div class="td-content">Позволяет показывать или скрывать поиск по опциям</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">data-select2-width</div>
</td>
<td>
<div class="td-content">Позволяет управлять шириной селекта</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">data-select2-clear</div>
</td>
<td>
<div class="td-content">Позволяет добавить кнопку для очистки выбранных значений</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="table-container mb-24">
<table>
<thead>
<tr>
<th>data-атрибут</th>
<th>Значение по-умолчанию</th>
<th>Тип</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data-placeholder</div>
</td>
<td>
<div class="td-content">(пусто)</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">data-select2-search</div>
</td>
<td>
<div class="td-content">false</div>
</td>
<td>
<div class="td-content">Логический</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">data-select2-width</div>
</td>
<td>
<div class="td-content">auto</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">data-select2-clear</div>
</td>
<td>
<div class="td-content">false</div>
</td>
<td>
<div class="td-content">Логический</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-1-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<Select data={options} name="elements" />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Обязательно</th>
<th>По-умолчанию</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data</div>
</td>
<td>
<div class="td-content">Массив объектов</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Массив объектов, содержащий значение и название опций списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">name</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Название поля</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">onChange</div>
</td>
<td>
<div class="td-content">Функция</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">null</div>
</td>
<td>
<div class="td-content">
Функция-обработчик выбора опций<br>
В качестве аргумента принимает выбранное / выбранные значения
</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">utils</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td></td>
<td>
<div class="td-content">
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="s-2">
<div class="components-title">
<h2>Выбранный селект</h2>
<p>Пример селекта с выбранной опцией</p>
</div>
<div class="components-preview">
<div class="field">
<select name="name">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5" selected>Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-2-1">HTML</a>
</li>
<li>
<a href="#tab-react-2-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-2-1">
<div class="components-code">
<pre>
<code class="language-html">
<textarea>
<div class="field">
<select name="name">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5" selected>Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-2-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
const value = ['5'] // id опции
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<Select data={options} name="elements" value={value} />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>
<div class="td-content">Свойство</div>
</th>
<th>
<div class="td-content">Тип</div>
</th>
<th>
<div class="td-content">Обязательно</div>
</th>
<th>
<div class="td-content">По-умолчанию</div>
</th>
<th>
<div class="td-content">Описание</div>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data</div>
</td>
<td>
<div class="td-content">Массив объектов</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Массив объектов, содержащий значение и название опций списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">name</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Название поля</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">value</div>
</td>
<td>
<div class="td-content">Массив</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">[]</div>
</td>
<td>
<div class="td-content">Выбранное / выбранные значения</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">onChange</div>
</td>
<td>
<div class="td-content">Функция</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">null</div>
</td>
<td>
<div class="td-content">
Функция-обработчик выбора опций<br>
В качестве аргумента принимает выбранное / выбранные значения
</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">utils</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td></td>
<td>
<div class="td-content">
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="s-3">
<div class="components-title">
<h2>Cелект с текстом-заполнителем</h2>
<p>Пример селекта с произвольным текстом-заполнителем</p>
</div>
<div class="components-preview">
<div class="field">
<select name="name" data-placeholder="Выберите из списка...">
<option label="Выберите из списка..."></option>
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-3-1">HTML</a>
</li>
<li>
<a href="#tab-react-3-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-3-1">
<div class="alert alert-yellow mt-0" style="margin-left: 30px; margin-right: 30px;">
<div class="alert-content">Пожалуйста, обратите внимание, что для корректной работы текста-заполнителя необходимо наличие пустой опции первым вариантом. Это связано с тем, что браузер по умолчанию пытается выбрать первый вариант (см. пример <a href="#s-1">обычного селекта</a>). Если бы ваш первый вариант был непустым, браузер отобразил бы его вместо заполнителя.</div>
</div>
<div class="components-code">
<pre>
<code class="language-html">
<textarea>
<div class="field">
<select name="name" data-placeholder="Выберите из списка...">
<option label="Выберите из списка..."></option>
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-3-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<Select data={options} name="elements" placeholder="Выберите из списка..." />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Обязательно</th>
<th>По-умолчанию</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data</div>
</td>
<td>
<div class="td-content">Массив объектов</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Массив объектов, содержащий значение и название опций списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">name</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Название поля</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">placeholder</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">"Выберите значение"</div>
</td>
<td>
<div class="td-content">Текст-заполнитель</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">utils</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td></td>
<td>
<div class="td-content">
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="s-4">
<div class="components-title">
<h2>Cелект с включенным поиском</h2>
<p>Пример селекта с включенным полем для поиска опций</p>
</div>
<div class="components-preview">
<div class="field">
<select name="name" data-select2-search="true">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-4-1">HTML</a>
</li>
<li>
<a href="#tab-react-4-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-4-1">
<div class="components-code">
<pre>
<code class="language-html">
<textarea>
<div class="field">
<select name="name" data-select2-search="true">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<p>По-умолчанию, для одиночных селектов поле поиска автоматически появляется при 15+ опций. Если необходимо принудительно включить поле поиска для любого количества опций, используется дата-атрибут <code>data-select2-search="true"</code></p>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-4-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<Select data={options} name="elements" searchable={true} />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Обязательно</th>
<th>По-умолчанию</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data</div>
</td>
<td>
<div class="td-content">Массив объектов</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Массив объектов, содержащий значение и название опций списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">name</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Название поля</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">searchable</div>
</td>
<td>
<div class="td-content">Логический</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">false</div>
</td>
<td>
<div class="td-content">Включает/отключает поиск по опциям списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">utils</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td></td>
<td>
<div class="td-content">
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-options">
<p>По-умолчанию, для одиночных селектов поле поиска автоматически появляется при 15+ опций. Если необходимо принудительно включить поле поиска для любого количества опций, используется свойство <code>searchable={true}</code></p>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="s-5">
<div class="components-title">
<h2>Cелект с управляемой шириной</h2>
<p>Пример селекта с произвольной шириной. В примере показан селект шириной 295px</p>
</div>
<div class="components-preview">
<div class="field">
<select name="name" data-select2-width="295px">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-5-1">HTML</a>
</li>
<li>
<a href="#tab-react-5-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-5-1">
<div class="components-code">
<pre>
<code class="language-html">
<textarea>
<div class="field">
<select name="name" data-select2-width="295px">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<p>По-умолчанию ширина селекта равна 100% ширины родительского блока. Для установки определенной ширины используется дата-атрибут <code>data-select2-width</code>, который в качестве значения принимает строку с любыми допустимыми CSS-значениями (px, % и т.д.)</p>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-5-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<Select data={options} name="elements" width="295px" />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Обязательно</th>
<th>По-умолчанию</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data</div>
</td>
<td>
<div class="td-content">Массив объектов</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Массив объектов, содержащий значение и название опций списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">name</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Название поля</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">width</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">auto</div>
</td>
<td>
<div class="td-content">Устанавливает ширину селекта</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">utils</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td></td>
<td>
<div class="td-content">
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-options">
<p>По-умолчанию ширина селекта равна 100% ширины родительского блока. Для установки определенной ширины используется свойство <code>width</code>, которое в качестве значения принимает строку с любыми допустимыми CSS-значениями (px, % и т.д.)</p>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="s-6">
<div class="components-title">
<h2>Отключенный селект</h2>
<p>Пример отключенного селекта</p>
</div>
<div class="components-preview">
<div class="field">
<select name="name" disabled>
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-6-1">HTML</a>
</li>
<li>
<a href="#tab-react-6-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-6-1">
<div class="components-code">
<pre>
<code class="language-html">
<textarea>
<div class="field">
<select name="name" disabled>
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-6-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<Select data={options} name="elements" disabled={true} />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Обязательно</th>
<th>По-умолчанию</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data</div>
</td>
<td>
<div class="td-content">Массив объектов</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Массив объектов, содержащий значение и название опций списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">name</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Название поля</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">disabled</div>
</td>
<td>
<div class="td-content">Логический</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">false</div>
</td>
<td>
<div class="td-content">Устанавливает селект в заблокированное/разблокированное состояние и запрещает изменение</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">utils</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td></td>
<td>
<div class="td-content">
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="s-7">
<div class="components-title">
<h2>Селект с меткой</h2>
<p>Пример селекта со связанной меткой. Компонент составной и содержит в себе компонент <a href="display.html">отображения</a></p>
</div>
<div class="components-preview">
<div class="field">
<label for="select-10" class="d-block">Какой элемент использовать?</label>
<select name="name" id="select-10">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-7-1">HTML</a>
</li>
<li>
<a href="#tab-react-7-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-7-1">
<div class="components-code">
<pre>
<code class="language-html">
<textarea>
<div class="field">
<label for="select-10" class="d-block">Какой элемент использовать?</label>
<select name="" id="select-10">
<option value="1">Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-7-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field, FieldLabel} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<FieldLabel>Какой элемент использовать?</FieldLabel>
<Select data={options} name="elements" />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Обязательно</th>
<th>По-умолчанию</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data</div>
</td>
<td>
<div class="td-content">Массив объектов</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Массив объектов, содержащий значение и название опций списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">name</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Название поля</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">utils</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td></td>
<td>
<div class="td-content">
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="s-8">
<div class="components-title">
<h2>Селект с множественным выбором</h2>
<p>Пример селекта с возможностью выбора более чем одного варианта</p>
</div>
<div class="components-preview">
<div class="field">
<select name="name" multiple data-select2-width="100%" data-placeholder="Выберите из списка">
<option value="1" selected>Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3" selected>Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5" selected>Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-8-1">HTML</a>
</li>
<li>
<a href="#tab-react-8-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-8-1">
<div class="components-code">
<pre>
<code class="language-html">
<textarea>
<div class="field">
<select name="name" multiple data-select2-width="100%" data-placeholder="Выберите из списка">
<option value="1" selected>Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3" selected>Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5" selected>Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-8-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
const selected_values = ['1', '3', '5']
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<Select data={values} name="elements" multiple={true} value={selected_values} />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Обязательно</th>
<th>По-умолчанию</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="td-content">data</div>
</td>
<td>
<div class="td-content">Массив объектов</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Массив объектов, содержащий значение и название опций списка</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">name</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Да</div>
</td>
<td></td>
<td>
<div class="td-content">Название поля</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">multiple</div>
</td>
<td>
<div class="td-content">Логический</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">false</div>
</td>
<td>
<div class="td-content">Разрешает множественный выбор</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">selected</div>
</td>
<td>
<div class="td-content">Массив</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td>
<div class="td-content">[]</div>
</td>
<td>
<div class="td-content">Выбранное / выбранные значения</div>
</td>
</tr>
<tr>
<td>
<div class="td-content">utils</div>
</td>
<td>
<div class="td-content">Строка</div>
</td>
<td>
<div class="td-content">Нет</div>
</td>
<td></td>
<td>
<div class="td-content">
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="s-9">
<div class="components-title">
<h2>Селект с очисткой выбора</h2>
<p>Пример селектов с кнопкой для очистки выбранных опций</p>
</div>
<div class="components-preview">
<div class="field mb-24">
<select name="name" data-select2-width="100%" data-select2-clear="true" data-placeholder="Выберите из списка">
<option value="1" selected>Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
<div class="field">
<select name="name" multiple data-select2-width="100%" data-select2-clear="true" data-placeholder="Выберите из списка">
<option value="1" selected>Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3" selected>Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5" selected>Пятый элемент</option>
</select>
</div>
</div>
<div class="components-tabs">
<div class="tabs">
<nav class="tabs-menu">
<ul>
<li class="active">
<a href="#tab-html-9-1">HTML</a>
</li>
<li>
<a href="#tab-react-9-2">React</a>
</li>
</ul>
</nav>
<div class="tabs-content">
<div class="tab active" id="tab-html-9-1">
<div class="components-code">
<div class="alert alert-yellow mt-0" style="margin-left: 30px; margin-right: 30px;">
<div class="alert-content">Опция требует обязательного наличия data-placeholder</div>
</div>
<pre>
<code class="language-html">
<textarea>
<div class="field mb-24">
<select name="name" data-select2-width="100%" data-select2-clear="true" data-placeholder="Выберите из списка">
<option value="1" selected>Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3">Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5">Пятый элемент</option>
</select>
</div>
<div class="field">
<select name="name" multiple data-select2-width="100%" data-select2-clear="true" data-placeholder="Выберите из списка">
<option value="1" selected>Первый элемент</option>
<option value="2">Второй элемент</option>
<option value="3" selected>Третий элемент</option>
<option value="4">Четвертый элемент</option>
<option value="5" selected>Пятый элемент</option>
</select>
</div>
</textarea>
</code>
</pre>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select2.scss</code>
</div>
</div>
<div class="tab" id="tab-react-9-2">
<div class="components-code">
<pre>
<code class="language-js">
<textarea>
import Select from "./components/Select";
import {Field} from "../components/Field";
const options = [
{text: 'Первый элемент', id: '1'},
{text: 'Второй элемент', id: '2'},
{text: 'Третий элемент', id: '3'},
{text: 'Четвертый элемент', id: '4'},
{text: 'Пятый элемент', id: '5'}
];
const selected_values_single = ['1']
const selected_values_multiple = ['1', '3', '5']
</textarea>
</code>
</pre>
<pre>
<code class="language-html">
<textarea>
<Field>
<Select data={options} name="elements" selected={selected_values_single} allowClear={true} width="100%" />
</Field>
<Field>
<Select data={options} name="elements" multiple={true} selected={selected_values_multiple} allowClear={true} width="100%" />
</Field>
</textarea>
</code>
</pre>
</div>
<div class="components-options">
<div class="table-container">
<table class="table-empty-cells">
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Обязательно</th>
<th>По-умолчанию</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>data</td>
<td>Массив объектов</td>
<td>Да</td>
<td></td>
<td>Массив объектов, содержащий значение и название опций списка</td>
</tr>
<tr>
<td>name</td>
<td>Строка</td>
<td>Да</td>
<td></td>
<td>Название поля</td>
</tr>
<tr>
<td>multiple</td>
<td>Логический</td>
<td>Нет</td>
<td>false</td>
<td>Разрешает множественный выбор</td>
</tr>
<tr>
<td>selected</td>
<td>Массив</td>
<td>Нет</td>
<td>[]</td>
<td>Выбранное / выбранные значения</td>
</tr>
<tr>
<td>allowClear</td>
<td>Логический</td>
<td>Нет</td>
<td>false</td>
<td>Включает кнопку для очистки выбранных опций</td>
</tr>
<tr>
<td>utils</td>
<td>Строка</td>
<td>Нет</td>
<td></td>
<td>
Название <a href="../utils/margins.html">CSS-утилит</a>, разделенных пробелом<br>
Применимо только для родительского компонента <code><Field /></code>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="components-source">
Исходный код этого компонента находится по пути <code>sass/components/_select.scss</code> и <code>components/Select.js</code>
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
{% block scripts %}
{{ parent() }}
{% endblock %}
|
<template>
<div>
<h1 class="text-center">Gestionar Tipo de Grados</h1>
<hr />
<!-- Button to Open the Modal -->
<button @click="modificar=false; abrirModal();" type="button" class="btn btn-primary my-4">Nuevo</button>
<!-- The Modal -->
<div class="modal" :class="{mostrar: modal}">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">{{tituloModal}}</h4>
<button @click="cerrarModal();" type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<form @submit.prevent="guardar()">
<div class="modal-body">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-12">
<label for="">Nombre:</label>
<div v-if="message_validation.nom_grado != ''" v-text='message_validation.nom_grado' class="text-danger"></div>
<input v-model="tipogrado.nombre" type="text" class="form-control" id="nombre" placeholder="Nombre del Tipo de Grado" required>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-12">
<label for="">Descripción:</label>
<div v-if="message_validation.desc_grado != ''" v-text='message_validation.desc_grado' class="text-danger"></div>
<input v-model="tipogrado.descripcion" type="text" class="form-control" id="descripcion" placeholder="Descripción del Tipo de Grado" required>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button @click="cerrarModal();" type="button" class="btn btn-secondary" data-dismiss="modal">
Cancelar
</button>
<button class="btn btn-success" data-dismiss="modal">
Guardar
</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- The Modal -->
<div class="card">
<div class="card-body">
<table class="table table-striped table-hover table-condensed">
<thead class="thead-dark">
<tr>
<th scope="col">Ord</th>
<th scope="col">Nombre</th>
<th scope="col">Descripción</th>
<th scope="col" colspan="2" class="text-center">Acción</th>
</tr>
</thead>
<tbody>
<tr v-for="tipg in tipogrado.data" :key="tipg.id">
<th scope="row">{{ tipg.id }}</th>
<td>{{ tipg.nom_grado }}</td>
<td>{{ tipg.desc_grado }}</td>
<td class="text-center">
<button @click="modificar=true; abrirModal(tipg);" class="btn btn-warning">Editar</button>
</td>
<td class="text-center">
<button @click="eliminar(tipg.id)" class="btn btn-danger">
Eliminar
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tipogrado:{ },
id:0,
modificar:true,
modal:0,
tituloModal:'',
tipg: [],
message_validation: {
nom_grado: '',
desc_grado: '',
},
};
},
methods: {
async listar() {
const res = await axios.get('./api/tipogrado/');
this.tipogrado = res.data;
},
async guardar()
{
if(this.modificar)
{
this.LimpiarMensajesErrores();
let url = './api/tipogrado/'+ this.id
axios.put(url, {
'id' : this.id,
'nom_grado': this.tipogrado.nombre,
'desc_grado': this.tipogrado.descripcion,
})
.then(response => {
this.cerrarModal();
this.listar();
swal('Correcto!', 'El Tipo de Grado fue actualizado', 'success');
})
.catch(error => {
if(error.response.status == 422)
{
let errors = error.response.data.errors
this.ErrorMessages(errors);
swal('Error!', 'Revise el formulario y corrija los campos de color rojo', 'error');
}
});
}
else
{
this.LimpiarMensajesErrores();
let url = './api/tipogrado/';
axios.post(url, {
'id': this.update,
'nom_grado': this.tipogrado.nombre,
'desc_grado': this.tipogrado.descripcion,
})
.then(response => {
if(response.data.estado_accion)
{
this.cerrarModal();
this.listar();
swal('Correcto!', 'El Tipo de Grado fue registrado', 'success');
}
})
.catch(error => {
if(error.response.status == 422)
{
let errors = error.response.data.errors
this.ErrorMessages(errors);
swal('Error!', 'Revise el formulario y corrija los campos de color rojo', 'error');
}
});
}
},
eliminar(id)
{
swal({
title: "¿Esta seguro de eliminar?",
text: "Se eliminará el Tipo de Grado!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((response) => {
if(response)
{
var url = './api/tipogrado/' + id;
axios.delete(url)
.then(response => {
swal('Correcto!', 'Eliminación correcta', 'success');
this.listar();
})
.catch(error => {
console.log(error);
});
}
});
},
ErrorMessages(errors)
{
for (const index in errors)
{
this.message_validation[index] = errors[index][0]
}
},
LimpiarMensajesErrores()
{
this.message_validation.nom_grado = '';
this.message_validation.desc_grado = '';
},
abrirModal(data={}){
this.modal=1;
if(this.modificar){
this.id=data.id;
this.tituloModal="Modificar Tipo Grado";
this.tipogrado.nombre=data.nom_grado;
this.tipogrado.descripcion=data.desc_grado;
}else{
this.id=0;
this.tituloModal="Crear Tipo Grado";
this.tipogrado.nombre='';
this.tipogrado.descripcionn='';
}
},
cerrarModal(){
this.modal=0;
},
},
created() {
this.listar();
},
};
</script>
<style>
.mostrar{
display: list-item;
opacity: 1;
background: rgba(75, 56, 143, 0.705);
}
</style>
|
package org.base.component.orm.hibernate;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.base.component.common.DalCondition;
import org.base.component.page.PageFinder;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Criterion;
public interface IHibernateBaseDao<T> {
/**
* 根据ID获取实体对象.
*
* @param id
* 记录ID
* @return 实体对象
*/
public T get(Serializable id);
/**
* 根据ID获取实体对象.
*
* @param id
* 记录ID
* @return 实体对象
*/
public T load(Serializable id);
/**
* 根据ID数组获取实体对象集合.
*
* @param ids
* ID对象数组
*
* @return 实体对象集合
*/
public List<T> get(Serializable[] ids);
/**
* 根据属性名和属性值获取实体对象.
*
* @param propertyName
* 属性名称
* @param value
* 属性值
* @return 实体对象
*/
public T get(String propertyName, Object value);
/**
* 根据属性名和属性值获取实体对象集合.
*
* @param propertyName
* 属性名称
* @param value
* 属性值
* @return 实体对象集合
*/
public List<T> getList(String propertyName, Object value);
/**
* @Title: getList
* @Description: 根据属性名和属性值数组获取实体对象集合.
* @param propertyName
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2013-1-9上午10:01:49
*/
public List<T> getList(String propertyName, Object[] values);
/**
* 获取所有实体对象集合.
*
* @return 实体对象集合
*/
public List<T> getAll();
/**
* 获取所有实体对象总数.
*
* @return 实体对象总数
*/
public Long getTotalCount();
/**
* 根据属性名、修改前后属性值判断在数据库中是否唯一(若新修改的值与原来值相等则直接返回true).
*
* @param propertyName
* 属性名称
* @param oldValue
* 修改前的属性值
* @param oldValue
* 修改后的属性值
* @return boolean
*/
public boolean isUnique(String propertyName, Object oldValue, Object newValue);
/**
* 根据属性名判断数据是否已存在.
*
* @param propertyName
* 属性名称
* @param value
* 值
* @return boolean
*/
public boolean isExist(String propertyName, Object value);
/**
* 保存实体对象.
*
* @param entity
* 对象
* @return ID
*/
public Serializable save(T entity);
/**
* 更新实体对象.
*
* @param entity
* 对象
*/
public void update(T entity);
/**
* 删除实体对象.
*
* @param entity
* 对象
* @return
*/
public void delete(T entity);
/**
* 根据ID删除实体对象.
*
* @param id
* 记录ID
*/
public void delete(Serializable id);
/**
* 根据ID数组删除实体对象.
*
* @param ids
* ID数组
*/
public void delete(Serializable[] ids);
/**
*
* @Title: delete
* @Description: 根据指定属性名和值删除记录
* @param propertyName
* @param value
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2013-4-2下午02:07:36
*/
public void delete(String propertyName, Object value);
public int delete(Map<String, Object> condition) throws Exception;
/**
* 清除某一对象.
*
* @param object
* 需要清除的对象
*/
public void evict(Object object);
public void flush();
public void clear();
// -------------------------------------------xieyong添加------------------------------
/**
* 保存或更新对象
*
* @Title: saveOrUpdate
*
* @param o
* @return 返回保存的对象
* @throws Exception
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17上午11:49:31
*/
public T saveOrUpdate(T o);
/**
* 创建 Criteria
*
* @Title: createCriteria
*
* @param criterions
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午01:29:46
*/
public Criteria createCriteria(Criterion... criterions);
/**
* 取得Entity的Criteria对象,带排序字段与升降序字段.
*
* @param orderBy
* @param isAsc
* @param criterions
* @return
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
*/
public Criteria createCriteria(String orderBy, boolean isAsc, Criterion... criterions);
/**
* 获得所有并排序
*
* @Title: getAllByOrder
*
* @param orderBy
* @param isAsc
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午01:43:56
*/
public List<T> getAllByOrder(String orderBy, boolean isAsc, boolean useCache);
/**
* 获得指定条数并排序
*
* @Title: getLimitByOrder
*
* @param orderBy
* @param isAsc
* @param limit
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午01:44:27
*/
public List<T> getLimitByOrder(String orderBy, boolean isAsc, int limit, boolean useCache);
/**
* 获得总条数
*
* @Title: getRowCount
*
* @param criteria
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午01:45:00
*/
public int getRowCount(Criteria criteria);
/**
* @Title: getListByCriteria
* @Description: 根据标准查询器,查询数据
* @param criteria
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2013-1-8下午3:05:37
*/
public List<T> getListByCriteria(Criteria criteria);
/**
* 从指定行查询指定条数据
*
* @Title: getListByCriteria
*
* @param criteria
* @param fistResult
* @param maxResult
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午02:02:19
*/
public List<T> getListByCriteria(Criteria criteria, int fistRow, int rowNum, boolean useCache);
/**
* 分页查询
*
* @Title: pagedByCriteria
*
* @param criteria
* @param pageNo
* @param pageSize
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午02:02:31
*/
public PageFinder<T> pagedByCriteria(Criteria criteria, int pageNo, int pageSize);
/**
* 创建hqlQuery
*
* @Title: createQuery
*
* @param hql
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午02:12:56
*/
public Query createQuery(String hql, Object... values);
/**
* 创建hqlQuery
*
* @Title: createQuery
*
* @param hql
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午02:13:40
*/
public Query createQuery(String hql, Map<String, ?> values);
/**
* 创建sqlQuery
*
* @Title: createSQLQuery
*
* @param sql
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午02:14:01
*/
public SQLQuery createSQLQuery(String sql, Object... values);
/**
* 创建sqlQuery
*
* @Title: createSQLQuery
*
* @param sql
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午02:15:39
*/
public Query createSQLQuery(String sql, Map<String, ?> values);
/*
* /**
*
* 根据 CritMap 条件查询单个对象
*
* @Title: getObjectByCritMap
*
*
*
* @param critMap
*
* @param useCache
*
* @return
*
* @throws
*
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
*
* @date: 2012-12-17下午03:41:42
*//*
* public T getObjectByCritMap(CritMap critMap,boolean ... useCache);
*
* /** 根据 CritMap 条件查询列表
*
* @Title: getListByCritMap
*
*
*
* @param critMap
*
* @param useCache
*
* @return
*
* @throws
*
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
*
* @date: 2012-12-17下午03:43:37
*//*
* public List<T> getListByCritMap(CritMap critMap,boolean ...
* useCache);
*
* /** 根据 CritMap 条件查询列表
*
* @Title: getListByCritMap
*
*
*
* @param critMap
*
* @param fistRow
*
* @param rowNum
*
* @param useCache
*
* @return
*
* @throws
*
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
*
* @date: 2012-12-17下午03:45:32
*//*
* public List<T> getListByCritMap(CritMap critMap,int fistRow, int
* rowNum,boolean ... useCache);
*
* /** 根据 CritMap 条件分页查询
*
* @Title: pagedByCritMap
*
*
*
* @param critMap
*
* @param No
*
* @param pageSize
*
* @return
*
* @throws
*
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
*
* @date: 2012-12-17下午03:45:44
*//*
* public PageFinder<T> pagedByCritMap(CritMap critMap,int
* No,int pageSize);
*/
/**
*
* 根据 CritMap 条件查询单个对象
*
* @Title: getObjectByCritMap
*
* @param critMap
* @param useCache
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午03:41:42
*/
public T getObjectByDalCondition(DalCondition conditionMap, boolean useCache);
/**
* 根据 CritMap 条件查询列表
*
* @Title: getListByCritMap
*
* @param critMap
* @param useCache
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午03:43:37
*/
public List<T> getListByDalCondition(DalCondition conditionMap, boolean useCache);
/**
* 根据 CritMap 条件查询列表
*
* @Title: getListByCritMap
*
* @param critMap
* @param fistRow
* @param rowNum
* @param useCache
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午03:45:32
*/
public List<T> getListByDalCondition(DalCondition conditionMap, int fistRow, int rowNum, boolean useCache);
/**
* 根据 CritMap 条件分页查询
*
* @Title: pagedByCritMap
*
* @param critMap
* @param No
* @param pageSize
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午03:45:44
*/
public PageFinder<T> pagedByDalCondition(DalCondition conditionMap, int No, int pageSize);
/**
* 通过HQL得到一个对象
*
* @Title: getObjectByHql
*
* @param hql
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午07:38:52
*/
public T getObjectByHql(String hql, Map<String, Object> values);
/**
* 通过HQL得到一个对象
*
* @Title: getObjectByHql
*
* @param hql
* @param values
* @return
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2013-1-7上午11:42:42
*/
public T getObjectByHql(String hql, Object... values);
/**
* 通过HQL得到查询列表
*
* @Title: getListByHql
*
* @param hql
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午07:38:52
*/
public List<T> getListByHql(String hql, Map<String, Object> values);
/**
* 通过HQL得到查询列表
*
* @Title: getListByHql
*
* @param hql
* @param values
* @return
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2013-1-7上午11:43:36
*/
public List<T> getListByHql(String hql, Object... values);
/**
* 通过HQL得到查询列表
*
* @Title: getListByHql
*
* @param hql
* @param values
* @param firstRow
* @param maxNum
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午07:42:42
*/
public List<T> getListByHql(String hql, int firstRow, int maxNum, Map<String, Object> values);
/**
* 通过HQL得到查询列表
*
* @Title: getListByHql
*
* @param hql
* @param firstRow
* @param maxNum
* @param values
* @return
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2013-1-7上午11:46:18
*/
public List<T> getListByHql(String hql, int firstRow, int maxNum, Object... values);
/**
* 分页查询:通过HQL,HQL不要包含子查询
*
* @Title: pagedByHQL
*
* @param hql
* @param toPage
* @param pageSize
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午07:42:48
*/
public PageFinder<T> pagedByHQL(String hql, int toPage, int pageSize, Map<String, Object> values);
/**
* 分页查询:通过HQL,HQL不要包含子查询
*
* @Title: pagedByHQL
*
* @param hql
* @param toPage
* @param pageSize
* @param values
* @return
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2013-1-7上午11:47:05
*/
public PageFinder<T> pagedByHQL(String hql, int toPage, int pageSize, Object... values);
/**
* 定制数据列表查询
*
* @Title: getListByHQL
*
* @param datasql
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午08:17:58
*/
@SuppressWarnings("rawtypes")
public List getListByHQL(String datasql, Map<String, Object> values);
/**
* 定制数据列表查询
*
* @Title: getListByHQL
*
* @param datasql
* @param firstRow
* @param maxNum
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午08:17:58
*/
@SuppressWarnings("rawtypes")
public List getListByHQL(String datasql, int firstRow, int maxNum, Map<String, Object> values);
/**
* 分页定制数据查询
*
* @Title: pagedByHQLtoObject
*
* @param countHql
* @param hql
* @param toPage
* @param pageSize
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午07:43:26
*/
public PageFinder<Object> pagedObjectByHQL(String countHql, String hql, int toPage, int pageSize,
Map<String, Object> values);
/**
* 通过SQL语句列表查询
*
* @Title: getListBySQL
* @param datasql
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午08:18:31
*/
public List<Object> getListBySQL(String datasql, Map<String, Object> values);
/**
* 通过SQL语句列表查询
*
* @Title: getListBySQL
* @param datasql
* @param firstRow
* @param maxNum
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午08:18:31
*/
public List<Object> getListBySQL(String datasql, int firstRow, int maxNum, Map<String, Object> values);
/**
* 通过SQL语句分页查询
*
* @Title: pagedBySQL
* @param countsql
* @param datasql
* @param toPage
* @param pageSize
* @param values
* @return
* @throws
* @author: <a href="mailto:justin.t.wang@163.com">王耀军(justin.t.wang)</a>
* @date: 2012-12-17下午08:18:35
*/
public PageFinder<Object> pagedObjectBySQL(String countsql, String datasql, int toPage, int pageSize,
Map<String, Object> values);
/**
* 调用存储过程使用的方法
* @param sql
* @param inValues
* @param outValues
* @return
*/
public CallableStatement excuteProc(String sql)throws HibernateException, SQLException;
}
|
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
use Faker\Factory as Faker;
class AboutUsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// Crear una instancia de Faker
$faker = Faker::create();
// Obtener todos los usuarios
$users = User::all();
// Iterar sobre cada usuario y asignar un 'about us' generado por Faker
foreach ($users as $user) {
// Generar un 'about us' aleatorio con entre 100 y 300 palabras
$aboutUs = []; // Array para almacenar las oraciones
// Continuar añadiendo oraciones hasta que se alcance la cantidad deseada de palabras
while (str_word_count(implode(' ', $aboutUs)) < 100) {
$aboutUs[] = $faker->sentence(); // Añadir otra oración
}
// Truncar el 'about us' a un máximo de 300 palabras
$aboutUs = implode(' ', $aboutUs); // Unir todas las oraciones en un solo string
$aboutUs = str_word_count($aboutUs) <= 300 ? $aboutUs : str_word_count($aboutUs, 300);
// Asignar el 'about us' al usuario
$user->about_us = $aboutUs;
$user->save();
}
}
}
|
import tkinter as tk
from tkinter import messagebox
from tkinter import scrolledtext
from datetime import datetime
from PIL import ImageTk, Image
from Prog_DB_Functions import *
def update_time():
global time, date, window
current_time = datetime.now().strftime('%H:%M:%S')
time.config(text=current_time)
current_date = datetime.now().strftime('%Y-%m-%d')
date.config(text=current_date)
window.after(1000, update_time)
def bring_frame_to_front(frame):
frame.lift()
def clear_frame_entries(canvas):
canvas.delete('all')
def add_entry_mode():
global entry_frame_submit
bring_frame_to_front(entry_frame_submit)
# entry box for name and its corresponing label
entry_name_label = tk.Label(entry_frame_submit, text="Entry Name: ", bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15))
entry_name_label.grid(row=0, column=0, sticky='ne', pady=5)
entry_name = tk.Entry(entry_frame_submit, width= 50, bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15), highlightbackground='navajo white',
highlightthickness=3)
entry_name.grid(row=0, column=1, sticky='w', pady=5)
# entry box for entry body and its corresponding label
entry_label = tk.Label(entry_frame_submit, text="Entry: ", bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15))
entry_label.grid(row=1, column=0, sticky='ne', pady=5)
entry = tk.scrolledtext.ScrolledText(entry_frame_submit, width=90, height=18, bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15), highlightbackground='navajo white',
highlightthickness=3)
entry.grid(row=1, column=1, sticky='nw', pady=5)
current_time = datetime.now().strftime('%H:%M:%S')
current_date = datetime.now().strftime('%Y-%m-%d')
date_time = f"{current_date} {current_time}"
def submit():
if entry.get("1.0", "end-1c") == "":
tk.messagebox.showerror(title="Error", message="Entry cannot be blank")
if entry_name.get() == "":
tk.messagebox.showerror(title="Error", message="Entry name cannot be blank")
else:
entry_text = entry.get("1.0", "end-1c")
entry_name_text = entry_name.get()
submit_entry(entry_name_text, date_time, entry_text)
entry_name.delete(0, tk.END)
entry.delete(1.0, tk.END)
# submit button
submit_button = tk.Button(entry_frame_submit, text="Submit", bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15), command = submit)
submit_button.grid(row=2, column=1, sticky='nw', pady=5)
def fetch():
global entry_canvas, entry_frame_view
bring_frame_to_front(entry_frame_view)
clear_frame_entries(entry_canvas)
entries = fetch_entries_from_db()
if entries == []:
pass
else:
label_height = 0
for entry in reversed(entries):
print_entries = ''
split_date_time = entry[0].split()
date_split = split_date_time[0]
date = "".join(date_split)
time_split = split_date_time[1]
time = "".join(time_split)
print_entries = f'Date: {date} \nTime: {time} \nEntry ID: {entry[3]} \nName: {entry[1]} \n\n{entry[2]}\n'
entry_label = tk.Label(entry_frame_view, text=print_entries, bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15), highlightbackground='navajo white',
highlightthickness=3, width=110, wraplength=1000, justify="left", anchor = 'w')
entry_canvas.create_window(0, label_height, window=entry_label, anchor="nw")
label_height += entry_label.winfo_reqheight()
entry_canvas.config(scrollregion=entry_canvas.bbox("all"))
def delete():
global delete_id_entry
delete_id = delete_id_entry.get()
delete_entry(delete_id)
delete_id_entry.delete(0, tk.END)
fetch()
def journal_run(window):
global entry_frame_submit, delete_id_entry, entry_canvas, entry_frame_view
entry_frame_submit = tk.Frame(window, bg="dark slate grey", highlightbackground='navajo white',
highlightthickness=3)
entry_frame_submit.grid(row=2, column=0, columnspan=4, sticky='nsew', pady=5)
entry_frame_view = tk.Frame(window, bg="dark slate grey", highlightbackground='navajo white',
highlightthickness=3)
entry_frame_view.grid(row=2, column=0, columnspan=4, sticky='nsew', pady=5)
#create scrollbar entry_view_frame
scrollbar = tk.Scrollbar(entry_frame_view, orient=tk.VERTICAL)
# Attach the scrollbar to the frame
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Create a canvas to contain the labels
entry_canvas = tk.Canvas(entry_frame_view, yscrollcommand=scrollbar.set, bg="dark slate grey", highlightbackground='navajo white', highlightthickness=0)
entry_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Configure the scrollbar to control the canvas
scrollbar.config(command=entry_canvas.yview)
journal_tile = tk.Frame(window, bg="dark slate grey", highlightbackground='navajo white', highlightthickness=3)
journal_tile.grid(row=1, column=0, sticky="nsw", columnspan=4)
#creates add entry button
add_entry = tk.Button(journal_tile, text="Add Entry", bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15), command=add_entry_mode)
add_entry.grid(row=0, column=1, sticky='nesw')
#show entries button
show_entries = tk.Button(journal_tile, text="Show Entries", bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15), command=fetch)
show_entries.grid(row=0, column=0, sticky='nesw')
#delete entries entry box
delete_label = tk.Label(journal_tile, text="Delete Entry: ", bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15))
delete_label.grid(row=0, column=2, sticky='nesw')
delete_id_entry = tk.Entry(journal_tile, width= 10, bg='navajo white', fg='dark slate grey',
font=("Lucida Sans Typewriter", 15), highlightbackground='navajo white',
highlightthickness=3)
delete_id_entry.grid(row=0, column=3, sticky='w', pady=5, padx=5)
delete_button = tk.Button(journal_tile, text="Confirm", bg='dark slate grey', fg='navajo white',
font=("Lucida Sans Typewriter", 15), command=delete)
delete_button.grid(row=0, column=4, sticky='nesw')
def on_closing():
window.destroy()
exit()
window.protocol("WM_DELETE_WINDOW", on_closing)
fetch()
update_time()
window.mainloop()
|
package com.example.barbuddy
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowDropDown
import androidx.compose.material.icons.rounded.Block
import androidx.compose.material.icons.rounded.CheckCircle
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
object FilterSingleton {
var descriptor: String = ""
var ingredient: String = ""
var craftable: Int = 0
}
class YourViewModel : ViewModel() {
private val dao: IngredientDao = Dao
val recipesLiveData = MutableLiveData<List<Recipes>>().apply{
value = dao.getFilteredRecipes(
FilterSingleton.descriptor,
FilterSingleton.ingredient,
FilterSingleton.craftable)
}
fun updateFilter(filterType: String, newDescriptor: String) {
if (filterType == "Filters") { FilterSingleton.descriptor = newDescriptor }
if (filterType == "Ingredients") { FilterSingleton.ingredient = newDescriptor}
val data = dao.getFilteredRecipes(
FilterSingleton.descriptor,
FilterSingleton.ingredient,
FilterSingleton.craftable)
recipesLiveData.postValue(data)
}
fun updateCraftable() {
FilterSingleton.craftable = if (FilterSingleton.craftable == 1) 0 else 1
val data = dao.getFilteredRecipes(
FilterSingleton.descriptor,
FilterSingleton.ingredient,
FilterSingleton.craftable)
recipesLiveData.postValue(data)
}
}
@Composable
fun RecipesBodyContent(
navController: NavController,
viewModel: YourViewModel = viewModel()
){
val recipesList by viewModel.recipesLiveData.observeAsState()
Column {
BuildFilterRow()
LazyColumn {
items(recipesList.orEmpty()) { recipe ->
var tags = recipe.method
if (recipe.descriptors.length > 1) {
tags += ", ${recipe.descriptors}"
}
Divider()
RecipeListItem(
navController,
itemName = recipe.name,
tags = tags
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BuildFilterChip(name: String, filters: List<String>? = null) {
var showDialog by remember { mutableStateOf(false) }
var isSelected = false
if (name == "Filters") { isSelected = (FilterSingleton.descriptor != "") }
if (name == "Ingredients") { isSelected = (FilterSingleton.ingredient != "") }
if (name == "Craftable Only") { isSelected = (FilterSingleton.craftable == 1) }
FilterChip(
colors = FilterChipDefaults.filterChipColors(
containerColor = MaterialTheme.colorScheme.background,
labelColor = MaterialTheme.colorScheme.onBackground,
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
),
modifier = Modifier.padding(start=5.dp, end = 5.dp),
selected = isSelected,
onClick = { showDialog = !showDialog },
label = { Text(name) },
trailingIcon = { if (filters != null) Icon(Icons.Rounded.ArrowDropDown, contentDescription = null) }
)
if (showDialog) {
FilterPopup(name, filters, onDismiss = {showDialog = false})
}
}
// TODO : think about changing to 'bottom sheet'?
@Composable
fun FilterPopup(
name: String,
filters:List<String>?,
onDismiss: () -> Unit,
viewModel: YourViewModel = viewModel()
) {
if (filters == null) {
viewModel.updateCraftable()
onDismiss()
}
Popup {
Box(
modifier = Modifier
.fillMaxSize()
.padding(0.dp)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = { onDismiss() }
)
.background(Color.Black.copy(alpha = 0.5f))
) {
Card(
modifier = Modifier
.fillMaxWidth()
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = { }
)
.align(Alignment.BottomCenter),
shape = RoundedCornerShape(0.dp),
colors = CardDefaults.cardColors (
containerColor = Color.White,
contentColor = Color.Black,
),
) {
Row (
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
){
Text(
text = name,
modifier = Modifier
.padding(top = 15.dp, start = 15.dp),
style = MaterialTheme.typography.titleLarge,
)
Spacer(Modifier.weight(1f))
Text(
modifier = Modifier
.padding(10.dp)
.clickable {
viewModel.updateFilter(name, "")
onDismiss()
},
text = "Clear Filter",
style = MaterialTheme.typography.titleSmall
)
}
Card (
modifier = Modifier
.padding(20.dp)
.heightIn(max = 400.dp)
.border(
width = 1.dp,
color = Color.LightGray,
shape = RoundedCornerShape(10.dp)
)
) {
filters?.let {
LazyColumn {
items(it) { filterItem ->
val bgColor = if (
filterItem == FilterSingleton.ingredient ||
filterItem == FilterSingleton.descriptor )
MaterialTheme.colorScheme.primaryContainer else Color.White
Row(
modifier = Modifier
.fillMaxWidth()
.background(color = bgColor)
.padding(15.dp)
.clickable(onClick = {
viewModel.updateFilter(name, filterItem)
onDismiss()
}),
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier.padding(start = 5.dp)
,
text = filterItem,
)
}
Divider()
}
}}
}
}
}
}
}
@Composable
fun RecipeListItem(navController: NavController, itemName:String, tags: String){
val inStock = Dao.getRecipeByName(itemName).craftable == 1
ListItem(
modifier = Modifier.clickable(onClick = { navController.navigate("recipeDetail/$itemName") }),
headlineContent = { Text(itemName) },
supportingContent = { Text(tags) },
leadingContent = {
Icon(
imageVector = if (inStock) Icons.Rounded.CheckCircle else Icons.Rounded.Block,
tint = if (inStock) colorResource(R.color.in_stock) else colorResource(R.color.out_of_stock),
contentDescription = "In Stock Icon"
)
}
)
}
@Composable
fun BuildFilterRow() {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, end = 10.dp),
horizontalArrangement = Arrangement.Center
){
val filtersList = Dao.getFiltersList().value.split(", ")
val ingredientsList = mutableListOf<String>()
Dao.getAllSpirits().forEach{ item -> ingredientsList.add(item.name) }
BuildFilterChip("Filters", filtersList)
BuildFilterChip("Ingredients", ingredientsList)
BuildFilterChip("Craftable Only")
}
}
|
import React from 'react'
import { Link, NavLink } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { checkIsAuth, logout } from '../redux/features/auth/authSlice'
import { toast } from 'react-toastify'
import logo from '.././components/logo.png';
export const Navbar = () => {
const isAuth = useSelector(checkIsAuth)
const dispatch = useDispatch()
const activeStyles = {
color: 'white',
}
const logoutHandler = () => {
dispatch(logout())
window.localStorage.removeItem('token')
toast('Vous êtes déconnecté')
}
return (
<div className='flex py-4 justify-between items-center'>
<span className='flex justify-center items-center w-22 h-6 bg-none text-xs text-white rounded-sm'>
travel BLOG
<img className='flex p-2 justify-center items-center w-22 h-12' src={logo} alt="Logo" />
</span>
{isAuth && (
<ul className='flex gap-8'>
<li>
<NavLink
to={'/'}
href='/'
className='text-xs text-gray-400 hover:text-white'
style={({ isActive }) =>
isActive ? activeStyles : undefined
}
>
Accueil
</NavLink>
</li>
<li>
<NavLink
to={'/posts'}
href='/'
className='text-xs text-gray-400 hover:text-white'
style={({ isActive }) =>
isActive ? activeStyles : undefined
}
>
Mes posts
</NavLink>
</li>
<li>
<NavLink
to={'/new'}
href='/'
className='text-xs text-gray-400 hover:text-white'
style={({ isActive }) =>
isActive ? activeStyles : undefined
}
>
Ajouter un post
</NavLink>
</li>
</ul>
)}
<div className='flex justify-center items-center bg-gray-600 text-xs text-white rounded-sm px-4 py-2'>
{isAuth ? (
<button onClick={logoutHandler}>Se déconnecter</button>
) : (
<Link to={'/login'}> Se conecter </Link>
)}
</div>
</div>
)
}
|
package com.dictionaryapp.model.dto;
import com.dictionaryapp.model.entity.LanguageEnum;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PastOrPresent;
import jakarta.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDate;
public class AddWordDTO {
private Long id;
@Size(min = 2, max = 40, message = "The term length must be between 2 and 40 characters!")
@NotNull
private String term;
@Size(min = 2, max = 80, message = "The translation length must be between 2 and 80 characters!")
@NotNull
private String translation;
@Size(min = 2, max = 200, message = "The example length must be between 2 and 200 characters!")
private String example;
@NotNull(message = "You must select a language!")
private LanguageEnum language;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@PastOrPresent(message = "The input date must be in the past or present!")
private LocalDate inputDate;
public AddWordDTO() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LanguageEnum getLanguage() {
return language;
}
public void setLanguage(LanguageEnum language) {
this.language = language;
}
public String getExample() {
return example;
}
public AddWordDTO setExample(String example) {
this.example = example;
return this;
}
public LocalDate getInputDate() {
return inputDate;
}
public AddWordDTO setInputDate(LocalDate inputDate) {
this.inputDate = inputDate;
return this;
}
public String getTerm() {
return term;
}
public AddWordDTO setTerm(String term) {
this.term = term;
return this;
}
public String getTranslation() {
return translation;
}
public AddWordDTO setTranslation(String translation) {
this.translation = translation;
return this;
}
}
|
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom'
import {
MenuFoldOutlined,
MenuUnfoldOutlined,
DownOutlined,
UserOutlined,
} from '@ant-design/icons';
import { Button, Layout, Dropdown, Space, Avatar, Modal, message } from 'antd';
import { useSelector } from 'react-redux';
import { removeToken } from '@/utils';
const { Header } = Layout;
export default function LayoutHeader({ collapsed, setCollapsed }) {
const { account,image_url,identity } = useSelector(state => state.user.userInfo)//store存储的数据
const [open, setOpen] = useState(false);//弹窗
const navigate = useNavigate()
const items = [
{
label: identity,
key: '1',
},
{
label: '个人信息',
key: '2',
},
{
label: '退出登录',
key: '3',
},
];
const onClick = (value) => {
if (value.key == 1) {
alert('您的身份是' + identity+'哦')
}
if (value.key == 2) {
navigate('/userInfo')
}
if (value.key == 3) {
setOpen(true)
}
}
const onOk = () => {
removeToken()
message.success('退出成功')
localStorage.clear()
navigate('/login')
};
const OnCancle = () => {
setOpen(false);
message.warning('取消退出')
};
return (
<div>
<Header
style={{
padding: 0,
background: '#eee'
}}
>
<Button
type="text"
icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
onClick={() => setCollapsed(!collapsed)}
style={{
fontSize: '16px',
width: 64,
height: 64,
}}
/>
<Dropdown className='dropdown'
menu={{ items, onClick }} trigger={['click']} >
<div>
<span style={{ marginRight: '15px' }}>{account}</span>
<a onClick={(e) => e.preventDefault()}>
<Space>
<Avatar shape="square" size="large" src={image_url} icon={<UserOutlined />} />
<DownOutlined />
</Space>
</a>
</div>
</Dropdown>
</Header>
<Modal
title="温馨提示"
open={open}
onOk={onOk}
onCancel={OnCancle}
okText="确认"
cancelText="取消"
>
<p>你确定要退出吗?</p>
</Modal>
</div>
);
};
|
const { MongoClient } = require("mongodb");
const dbName = "telegram";
const collectionName = "dialogues";
const uri =
"mongodb://qwerty:qwerty123@ac-llvczxo-shard-00-00.2ry9k50.mongodb.net:27017,ac-llvczxo-shard-00-01.2ry9k50.mongodb.net:27017,ac-llvczxo-shard-00-02.2ry9k50.mongodb.net:27017/?ssl=true&replicaSet=atlas-b2xf0l-shard-0&authSource=admin&retryWrites=true&w=majority";
class DialoguesService {
constructor() {
this.client = null;
this.db = null;
this.collection = null;
this.connect = this.connect.bind(this);
this.postDialogue = this.postDialogue.bind(this);
this.getDialogue = this.getDialogue.bind(this);
this.getDialogueUsername = this.getDialogueUsername.bind(this);
this.getUsernamesByGroupId = this.getUsernamesByGroupId.bind(this);
this.convertUsernamesToLowerCase =
this.convertUsernamesToLowerCase.bind(this);
this.getHrefByAccountId = this.getHrefByAccountId.bind(this);
}
async connect() {
if (this.client) {
return;
}
this.client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
this.db = this.client.db(dbName);
this.collection = this.db.collection(collectionName);
}
async getHrefByAccountId(accountId) {
await this.connect();
const usernames = await this.collection.distinct("href", {
accountId,
managerMessage: { $ne: null },
});
return usernames;
}
async postDialogue(dialogue) {
await this.connect();
await this.collection.updateOne(
{ accountId: dialogue.accountId, href: dialogue.href },
{ $set: dialogue },
{ upsert: true }
);
}
// получание по
async getDialogue(accountId, href) {
await this.connect();
return await this.collection.findOne({ accountId, href });
}
async getDialogueUsername(accountId, username) {
await this.connect();
return await this.collection.findOne({
accountId,
username: username.toLowerCase(),
});
}
// все пользователи, которым была отправка по конкретному groupId
async getUsernamesByGroupId(groupId) {
await this.connect();
const dialogues = await this.collection.find({ groupId }).toArray();
return dialogues
.map((dialogue) => dialogue?.username?.toLowerCase())
.filter(Boolean);
}
async convertUsernamesToLowerCase() {
await this.connect();
// Получаем все диалоги
const dialogues = await this.collection.find().toArray();
// Проходимся по каждому диалогу
for (const dialogue of dialogues) {
// Проверяем, есть ли у диалога поле "username"
if (dialogue.username) {
// Преобразуем значение поля "username" в нижний регистр
dialogue.username = dialogue.username.toLowerCase();
// Обновляем диалог с новым значением поля "username"
await this.collection.updateOne(
{ _id: dialogue._id },
{ $set: { username: dialogue.username } }
);
}
}
console.log("все");
}
}
module.exports = new DialoguesService();
|
<template>
<div id="main">
<MyFormItem
v-if="value_a.display"
label="A"
:required="value_a.required"
:isValid="value_a.isValid"
:errMsg="value_a.errMsg"
>
<el-radio-group v-model="value_a.value">
<el-radio :label="true">true</el-radio>
<el-radio :label="false">false</el-radio>
</el-radio-group>
</MyFormItem>
<MyFormItem
v-if="value_b.display"
label="B"
:required="value_b.required"
:isValid="value_b.isValid"
:errMsg="value_b.errMsg"
>
<el-input
size="small"
v-model:value="value_b.value"
type="text"
@clear="onClear"
clearable
/>
</MyFormItem>
<MyFormItem
v-if="value_c.display"
label="C"
:required="value_c.required"
:isValid="value_c.isValid"
:errMsg="value_c.errMsg"
>
<el-input-number size="small" v-model:value="value_c.value" />
</MyFormItem>
<MyFormItem
v-if="value_d.display"
label="D"
:required="value_d.required"
:isValid="value_d.isValid"
:errMsg="value_d.errMsg"
>
<el-input-number size="small" v-model:value="value_d.value[0]" />
<span style="margin: 0 10px">~</span>
<el-input-number size="small" v-model:value="value_d.value[1]" />
</MyFormItem>
<MyFormItem
v-if="value_e.display"
label="E"
:required="value_e.required"
:isValid="value_e.isValid"
:errMsg="value_e.errMsg"
>
<el-input size="small" v-model:value="value_e.value" type="text" />
</MyFormItem>
<el-button @click="onSubmit">Submit</el-button>
</div>
</template>
<script>
import MyFormItem from "../components/MyFormItem.vue";
export default {
name: "Demo1",
props: {
model: {
type: Object,
default: () => {},
},
},
components: {
MyFormItem,
},
data() {
return {
value_a: {},
value_b: {},
value_c: {},
value_d: {},
value_e: {},
};
},
created() {},
mounted() {},
computed: {},
beforeMount() {
this.setData(this.model);
},
watch: {
model: function (newVal) {
this.setData(newVal);
},
},
methods: {
setData(val) {
const keys = Object.keys(val);
keys.forEach((key) => {
this[key] = val[key];
});
},
onSubmit() {
const keys = Object.keys(this.model);
const valid = keys.every((key) => {
const { display, isValid, required, value } = this.model[key];
if (!display) {
return true;
} else {
return this.model[key].isValid !== false;
}
});
if (valid) {
if (this.value_b.value === "i_find_bug") {
this.$message.error("you find bug");
return;
}
this.$message.success("valid");
} else {
this.$message.error("invalid");
}
},
onClear() {
this.value_b.value = "";
this.value_e.value = "";
},
},
};
</script>
<style lang="less">
#main {
width: 50%;
height: 100%;
margin: 0px auto;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
.form-item-wrap {
margin-bottom: 10px;
}
}
</style>
|
import prisma from "$lib/server/prisma";
import { error, redirect } from "@sveltejs/kit";
import chooseSpawnpoint from "$lib/server/choose-spawnpoint";
import ablyServer from "$lib/server/ably-server";
async function addPlayer(
gameId: number,
user: { id: number; schoolId: number },
) {
const game = await prisma.game.findFirst({
where: {
id: gameId,
map: { creator: { schoolId: user.schoolId } },
state: { not: "ENDED" },
},
select: { mapId: true, state: true },
});
if (!game) error(403, "You do not have access to this game!");
if (game.state == "LOBBY") redirect(303, "/game/" + gameId + "/lobby/");
const spawnpoint = await chooseSpawnpoint(game.mapId);
const newPlayer = await prisma.player.create({
data: { userId: user.id, gameId, currRoomId: spawnpoint },
select: {
id: true,
currRoom: { select: { svgRef: true } },
user: { select: { name: true, picture: true } },
game: {
select: {
state: true,
claimedRooms: { where: { roomId: spawnpoint } },
},
},
},
});
if (newPlayer.game.claimedRooms.length == 0) {
await prisma.claimedRoom.create({
data: { gameId, roomId: spawnpoint },
});
}
ablyServer.channels.get("game:" + gameId + ":positions").publish("create", {
userId: user.id,
picture: newPlayer.user.picture,
svgRef: newPlayer.currRoom.svgRef,
});
ablyServer.channels
.get("game:" + gameId + ":points")
.publish("create", { userId: user.id, name: newPlayer.user.name });
return newPlayer.id;
}
export default async function getPlayerId(
user: { id: number; schoolId: number },
gameId: number,
): Promise<number> {
const player = await prisma.player.findFirst({
where: { userId: user.id, gameId },
select: {
id: true,
game: { select: { state: true } },
kicked: true,
},
});
if (player) {
if (player.kicked) error(403, "You've been kicked from this game!");
/* eslint-disable no-fallthrough */
switch (player.game.state) {
case "LOBBY":
redirect(303, "/game/" + gameId + "/lobby/");
case "ONGOING":
return player.id;
case "ENDED":
redirect(301, "/game/" + gameId + "/end/");
}
/* eslint-enable no-fallthrough */
}
return await addPlayer(gameId, user);
}
|
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import prisma from '@/services/InitPrisma';
import { Logger } from '@/services/Logger';
import type { Session } from 'next-auth';
import { getServerSession } from 'next-auth/next';
import type { NextApiRequest, NextApiResponse } from 'next/types';
import type {
ChatRoom,
ChatRoomMember,
ChatRoomMessage,
GetChatRoomsResponseInner,
PageNation,
PostChatRoomRequestInner,
} from 'oas/types';
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
try {
Logger.info('access', req);
if (req.method === 'GET') {
return await GET(req, res);
}
if (req.method === 'POST') {
return await POST(req, res);
}
if (req.method === 'PUT') {
return await PUT(req, res);
}
return res.status(405).end();
} catch (err) {
Logger.error(err, 'Internal Error');
return res.status(500).end();
}
}
/** チャットルームの取得 */
async function GET(req: NextApiRequest, res: NextApiResponse<GetChatRoomsResponseInner>) {
const session: Session | null = await getServerSession(req, res, authOptions);
const { offset } = req.query;
const take = 20;
const skip = Number(offset ? offset : 0);
if (!session || !session.user?.id) {
return res.status(401).end();
}
const [total, rooms] = await prisma.$transaction([
prisma.chatRoomField.count({
where: {
members: {
some: { userId: session.user.id },
},
},
}),
prisma.chatRoomField.findMany({
where: {
members: {
some: { userId: session.user.id },
},
},
include: {
members: {
include: {
user: { select: { name: true } },
},
},
unreads: {
where: { userId: session.user.id },
},
messages: {
orderBy: { createdAt: 'desc' },
take: 1,
},
},
skip: skip * take,
take,
orderBy: { updatedAt: 'desc' },
}),
]);
const data: GetChatRoomsResponseInner['data'] = [];
for (const room of rooms) {
const members: ChatRoomMember[] = [];
for (const member of room.members) {
members.push({
id: member.id,
userId: member.userId ?? undefined,
name: member.user?.name ?? undefined,
});
}
const messages: ChatRoomMessage[] = [];
for (const message of room.messages) {
messages.push({
id: message.id,
body: message.body,
createdAt: message.createdAt,
userId: message.userId ?? undefined,
});
}
const isUnreadCurrentUser = room.unreads.length > 0 ? room.unreads[0].isUnread : false;
data.push({
id: room.id,
createdAt: room.createdAt,
lastPostedUserId: room.lastPostedUserId,
updatedAt: room.updatedAt,
isUnread: isUnreadCurrentUser,
members,
messages,
});
}
const pageNation: PageNation = {
total: total,
current: skip,
last: Math.floor(total / take),
};
return res.status(200).json({ data, pageNation });
}
/** 新規チャットルームの作成 */
async function POST(req: NextApiRequest, res: NextApiResponse<ChatRoom>) {
const session: Session | null = await getServerSession(req, res, authOptions);
const { data } = req.body as PostChatRoomRequestInner;
if (!session || !session.user?.id) {
return res.status(401).end();
}
// 渡された userId が存在するか確認
const users: { userId: string }[] = [];
for (const recipient of data.recipients) {
const user = await prisma.user.findUnique({ where: { id: recipient } });
if (user === null) {
return res.status(404).end();
} else {
users.push({ userId: user.id });
}
}
if (users.some((user) => user === null)) {
}
// 該当ユーザーのみが所属するチャットルームを取得する
const chatRoom = await prisma.chatRoomField.findFirst({
where: {
members: {
every: {
userId: { in: data.recipients },
},
},
},
include: {
members: {
include: {
user: { select: { name: true } },
},
},
messages: {
take: 3,
},
},
});
// null = 新規作成
if (chatRoom === null) {
const chatRoomField = await prisma.chatRoomField.create({
data: {
lastPostedUserId: session.user.id,
members: { create: users },
unreads: {
create: users.map((user) => ({
userId: user.userId,
})),
},
},
include: {
members: {
include: {
user: { select: { name: true } },
},
},
messages: true,
},
});
return res.status(200).json({
id: chatRoomField.id,
createdAt: chatRoomField.createdAt,
updatedAt: chatRoomField.updatedAt,
lastPostedUserId: chatRoomField.lastPostedUserId,
isUnread: true,
members: chatRoomField.members.map((member) => ({
id: member.id,
userId: member.userId ?? undefined,
name: member.user?.name ?? undefined,
})),
messages: chatRoomField.messages.map((message) => ({
id: message.id,
body: message.body,
createdAt: message.createdAt,
userId: message.userId ?? undefined,
})),
});
} else {
return res.status(200).json({
id: chatRoom.id,
createdAt: chatRoom.createdAt,
updatedAt: chatRoom.updatedAt,
lastPostedUserId: chatRoom.lastPostedUserId,
isUnread: false,
members: chatRoom.members.map((member) => ({
id: member.id,
userId: member.userId ?? undefined,
name: member.user?.name ?? undefined,
})),
messages: chatRoom.messages.map((message) => ({
id: message.id,
body: message.body,
createdAt: message.createdAt,
userId: message.userId ?? undefined,
})),
});
}
}
/** 全てのチャットルームを既読にする */
async function PUT(req: NextApiRequest, res: NextApiResponse<void>) {
const session: Session | null = await getServerSession(req, res, authOptions);
if (!session || !session.user?.id) {
return res.status(401).end();
}
await prisma.chatRoomUnread.updateMany({
where: { userId: session.user.id },
data: { isUnread: false },
});
return res.status(204).end();
}
|
package com.viniciusfinger.rsflood.controller;
import com.viniciusfinger.rsflood.model.Address;
import com.viniciusfinger.rsflood.service.AddressService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/addresses")
public class AddressController {
private final AddressService addressService;
public AddressController(AddressService addressService) {
this.addressService = addressService;
}
@GetMapping
public ResponseEntity<Iterable<Address>> findAll(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "100") int pageSize
) {
Iterable<Address> addresses = addressService.findAll(page, pageSize);
return ResponseEntity.status(HttpStatus.OK).body(addresses);
}
@GetMapping("/{id}")
public ResponseEntity<Address> findById(@PathVariable Long id) {
Optional<Address> addressOptional = addressService.findById(id);
if (addressOptional.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
return ResponseEntity.status(HttpStatus.OK).body(addressOptional.get());
}
@DeleteMapping("/{id}")
public ResponseEntity<Address> delete(@PathVariable Long id) {
addressService.deleteById(id);
return ResponseEntity.ok().build();
}
@PostMapping
public ResponseEntity<Address> create(@RequestBody Address address) {
address = addressService.save(address);
return ResponseEntity.status(HttpStatus.CREATED).body(address);
}
@PutMapping
public ResponseEntity<Address> update(@RequestBody Address address) {
address = addressService.save(address);
return ResponseEntity.status(HttpStatus.OK).body(address);
}
}
|
import React, { useState, useEffect } from 'react';
import { Space, Table,FloatButton, Tag } from 'antd';
import { FrappeApp } from 'frappe-js-sdk';
import { TableProps, Skeleton,Result, Button } from 'antd';
import { DeleteOutlined, EditOutlined,FolderAddOutlined, FolderViewOutlined } from '@ant-design/icons';
import '../SalesInvoice/App.css';
import CustomerCreatePopUp from './CustomerCreatePopUp';
type CheckboxValueType = React.ReactText[];
interface DataType {
key: string;
name: string;
tags: number;
customer_type: string;
disabled: number;
stock_uom: string;
}
const deleteEntry = (key: string) => {
const frappe = new FrappeApp("http://162.55.41.54");
const db = frappe.db();
db.deleteDoc('Customer', key)
.then((response) => console.log(response.message))
.catch((error) => console.error(error));
};
const columns: TableProps<DataType>['columns'] = [
{
title: 'Item Name',
dataIndex: 'name',
key: 'name',
render: (text) => <a>{text}</a>,
},
{
title: 'Customer Type',
dataIndex: 'customer_type',
key: 'customer_type',
},
{
title: 'Status',
key: 'tags',
dataIndex: 'tags',
render: (disabled: number) => (
<>
<Tag color={disabled === 0 ? 'geekblue' : 'volcano'} key={disabled}>
{disabled === 0 ? 'Enabled' : 'Disabled'}
</Tag>
</>
),
},
{
title: 'Action',
key: 'action',
render: (_, record: DataType) => (
<Space size="middle">
<button className="action-button-e">
<EditOutlined />
</button>
<button className="action-button-v">
<FolderViewOutlined />
</button>
<button className="action-button-d" onClick={() => deleteEntry(record.key)}>
<DeleteOutlined />
</button>
</Space>
),
},
];
const ItemTable: React.FC = () => {
const [list, setList] = useState<DataType[]>([]);
const [selectedRowKeys, setSelectedRowKeys] = useState<CheckboxValueType>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<any>(null);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const frappe = new FrappeApp("http://162.55.41.54");
const db = frappe.db();
const docs = await db.getDocList('Customer', {
fields: ['name', 'disabled', 'creation', 'customer_type'],
orderBy: {
field: 'creation',
order: 'desc',
},
limit:1000,
asDict: true,
});
const formattedDocs: DataType[] = docs.map((doc) => ({
key: doc.name,
name: doc.name,
tags: doc.disabled,
customer_type: doc.customer_type,
}));
setList(formattedDocs);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
const rowSelection = {
selectedRowKeys,
onChange: (keys: CheckboxValueType) => {
setSelectedRowKeys(keys);
console.log(selectedRowKeys);
},
};
const [isModalVisible, setIsModalVisible] = useState(false);
const handleCreateItem = () => {
setIsModalVisible(true);
};
const handleModalCancel = () => {
setIsModalVisible(false);
};
const handleModalSubmit = (values) => {
const frappe = new FrappeApp("http://162.55.41.54");
const db = frappe.db();
console.log(values);
db.createDoc('Customer', {
customer_name: values.customerName,
customer_type: values.customerType,
gst_category: values.setGstCategory,
})
.then((doc) => {
console.log('New item created:', doc);
setIsModalVisible(false);
})
.catch((error) => {
console.error('Error creating new item:', error);
});
};
return (
<div style={{ padding: 24, minHeight: '85vh', background: '#fff', borderRadius: 8 }}>
{loading ? (
<div><Skeleton active /></div>
) : error ? (
<div> <Result
status="500"
title="500"
subTitle={error.message}
// extra={<Button type="primary">Back Home</Button>}
/>
</div>
) : (
<Table
columns={columns}
dataSource={list}
rowSelection={rowSelection}
pagination={{position:['bottom','start'], style: { marginTop: '15px' }, total: list.length }}
/>
)}
<FloatButton
icon={<FolderAddOutlined />}
style={{ right: 24 }}
type="primary"
onClick={handleCreateItem}
/>
<CustomerCreatePopUp
visible={isModalVisible}
onCancel={handleModalCancel}
onSubmit={handleModalSubmit}
/>
</div>
);
};
export default ItemTable;
|
# SmsApi
simple web api to delegate sending sms on a <b>linux server</b> that owns a sim card<br><br>
# What you needs :
<ul>
<li>A linux web server using apache or nginx or lighttp.</li>
<li>Php from 7.x to 8.2</li>
<li>sqlite3 and php-sqlite module</li>
<li>gammu : the SMS sender binary file</li>
<li>An USB Sim card adaptater</li>
<li>An activated Sim card </li>
<li>Kownledges to call a web api with your prefered language </li>
</ul>
# How it works :
<ul>
<li>This api is php written and uses a sqlite database.</li>
<li>It calls gammu binary executable and of course needs a SIM Card</li>
<li>At boot, your SIM card must be PIN unlocked (a service is used to send your PIN Code at boot time if needed)</li>
<li>Your application (web site or whatever) has to call this web api using curl (if your langage is php) or requests (if python) or other</li>
<li>Be carefull about execution time (sometimes it takes several seconds to send a SMS)</li>
<li>Datas are in a sqlite database</li>
<li>This api provides a test web page do test it manually.</li>
<li>You have to create clients ( = which account is sending a SMS)</li>
<li>This api provides quotat by clients (account) (sending SMS wil decrease it, and you have to increase it manually using update via sqlite studio, cli or by another method)</li>
<li>Accessing this api is secured by user/password that must exists in TBSMSCLI sqlite database (this is the account list)</li>
<li>Each account owns user/password in TBSMSCLI table</li>
<li>These api checks quotat via the VQUOTATLEFT view in SQLITE database</li>
<li>Quotats can be changed using updates on the TBQUOTAT table</li>
<li>Each acocunt must have a quotat in the TBQUOTAT table</li>
<li>Sqlite database access must to be secured my an .htaccess file</li>
<li>Sqlite database provides SMS history, account and quotat control</li>
</ul>
# What you will find here :
<ul>
<li>404.gif : a simple 404 gif.</li>
<li>index.html : a simple root file that show 404.</li>
<li>test.php : a web page to use this api manually, it uses the demo account (password is demopass : take a look at the beginning of this file)</li>
<li>smsapi.css : the style file for test.php</li>
<li>index.php : the root api php file (I suggest you to user another name)</li>
<li>robots.txt : a file to prevent search indexing by search robots</li>
<li>A log folder, it must be web server writable : you will find log files here.I recommend to put an htaccess file here to prevent direct downloading.</li>
<li>A tmp folder for temporary files, it must be web server writable. I recommend to put an htaccess file here to prevent direct downloading.</li>
<li>A db folder, it must be web server writable. It contains smsapi.db file (the sqlite database) that must be web server writable</li>
<li>In db folder <b>you have to put a .htaccess file to prevent direct download of database !</b><br>Use someting like this for Apache 2.4 :<br><br>
<blockquote><Files 'smsapi.db'>Require all denied</Files></blockquote>blockquote></li>
<li>A service folder that contains what is needed to help to use gammu :
<ul>
<li>.gammurc is a file used by gammu (the sms binary file). You have to check the line "port = /dev/ttyUSB0" is your Sim card USB adaptater is in another port, and "connection = at19200" if your adaptater is using another dial speed </li>
<li>group.txt : A CLI example to add your web serveur user to dialout group : beacause the web server must access to the com port. This exemple is for apache 2.4 on Fedora. Check you web server account, it can be www-data on Debian.</li>
<li>usbmodeswitch.conf : This is my usbmodeswitch configuration file : I'm using a Huawei USB Sim Card adaptater : check what configuration you need.</li>
<li>pincode.sh : this script must be run at boot time : It will unlock Sim card's protection using your PIN Code : replace your pincode at line "pincode='0000'"</li>
<li>pincode.service : The pincode unlocking service description file. Check the pincode.sh path (I'm using /opt/gammu path tu put pincode.sh)</li>
</ul>
</li>
</ul>
# Installation :
Assuming you have a web service that is running<br>
Assuming you have installed gammu<br>
If gammu needs your pin code at each boot (you can check it with <b>gammu getsecuritystatus</b>), you can use my pincode.sh and pincode.service files to do it.<br>
Assuming that gamm can send SMS by cli<br>
Check it with <b>gammu sendsms TEXT aphonenumber -text "Test by CLI"</b><br>
<br>
If you need some gammu config file, define it in index.php like this<br>
<b>DEFINE("GAMMU_CONFIG_FILE","/root/.gammurc");</b> or <b>DEFINE("GAMMU_CONFIG_FILE","");</b><br>
<br>
Put all the content repo in a document root web server folder (or subfolder)<br>
make ./log, ./tmp and ./db/smsdb.db writable by your web server
<br>
Open ./db/smsdb.db with sqlite and create or choose password for the demo account (see TBPARAM).<br>
Check TBQUOTAT for this useror insert a row in TBQUOTAT to make your new user own some SMS to send.<br>
<br>
Go to a web navigator and ask for index.php, you will see : 403 (Forbidden)<br>
<br>
Open test.php, search at the beginning of the file for : <b>$smspassw=GetVariableFrom($_POST,"smspassw","demopass");</b> and replace <b>demopass</b> by your demo password if you changed it in TBPARAM.<br>
in index.php search for <b>filterlist</b> function, because the script only accept French phone number, you will have to change the rules if you leave in another country.
<br>
Go to a web navigator and ask for test.php you will see a test page, here chose an account (client), put the from phone number (your SIM Card phone number), give one or more recipients, and a message to send.<br>
Chose directsend<br>
<br>
You have received this SMS ? Yeah, next one : How to use this api programmaticaly.<br>
# How to use this api programmaticaly
See in test.php the action listbox :<br>
You have :
<ul>
<li>new : create a new SMS without sending : you have to give the from number (your SIM Card phone Number) , the message body, the accound and his password. It will return a SMS Id</li>
<li>putcc : remplace or put recipients in an existing SMS (you will have to give the SMS Id, the account and his password)</li>
<li>getquotat : giving the accound and his password. It will return, how much SMS this account can send</li>
<li>directsend : create and send a new SMS : you have to give the from number (your SIM Card phone Number) , the message body, a recipient, the accound and his password. It will return the SMS Id</li>
<li>send : send a SMS previously fully created : you have to give ths SMS Id ,the accound and his password.</li>
</ul>
# Calling api
Use curl, python requests library, javascript fetch or other methods.
You have to call the <b>index.php</b> script using <b>POST</b> method
You have to give these POST values :
<ul>
<li><b>smscli</b> : this is the string id of the account that want to send a message (ex : demo)</li>
<li><b>smspassw</b> : this is the string password of the account that want to send a message (ex : demopass)</li>
<li><b>from</b> : your SIM card phone number </li>
<li><b>body</b> : The message (use UTF-8 charset !)</li>
<li><b>action</b> : The action to do (new, putcc, getquotat, directsend or send).</li>
<li><b>idsms</b> : The smsid if you want to update or send a message that you have just created.</li>
<li><b>cclist</b> : Recipients list, using semi-colon separator.</li>
</ul>
# Returning values
This api will return you infomations for debugging and check what has been done.<br>
Theses informations are in XML format and UTF-8 encoded. You will find :<br>
<ul>
<li><b>CR</b> : The return code : 0 If everything is OK</li>
<li><b>MSG</b> : A message if something went wrong</li>
<li><b>DATA</b> : Some data if neccessary, it can be <b>idsms</b> or <b>quotatleft</b></li>
<ul>
|
import React, { useState, useEffect } from 'react';
import useResponsive from '../../../hooks/useResponsive';
/**
* Component representing the menu sidebar.
* @param {object} props - The component props.
* @param {React.ReactNode} props.children - The content to render inside the sidebar.
* @param {string} props.className - Additional CSS classes for the sidebar.
* @param {object} props.style - Additional inline styles for the sidebar.
* @returns {React.ReactNode} The rendered menu sidebar component.
*/
const SidebarMenuNotes = ({ children, className, style, side = 'right', ...rest }) => {
const { isTablet } = useResponsive();
const [headerHeight, setHeaderHeight] = useState(0);
useEffect(() => {
const headerElement = document.querySelector('.site-header');
if (headerElement) {
setHeaderHeight(headerElement.clientHeight);
}
}, []);
let elementStyle = {
paddingLeft: !isTablet && 'calc(100vw * 0.05)',
paddingTop: '2rem',
width: !isTablet && '550px',
maxWidth: !isTablet && '550px',
minWidth: !isTablet && '550px',
minHeight: `calc(100vh - ${headerHeight}px)`,
maxHeight: `calc(100vh - ${headerHeight}px)`,
...style
};
if (side === 'left') {
elementStyle = {
paddingRight: !isTablet && 'calc(100vw * 0.05)',
paddingTop: '2rem',
width: !isTablet && '550px',
maxWidth: !isTablet && '550px',
minWidth: !isTablet && '550px',
minHeight: `calc(100vh - ${headerHeight}px)`,
maxHeight: `calc(100vh - ${headerHeight}px)`,
...style
};
}
return (
<div
style={elementStyle}
className={`bg-white-faint px-4 lg:pr-6 sticky pin-t pin-l h-full lg:border-r border-gray-dark lg:overflow-y-auto ${className}`}
{...rest}
>
{children}
</div>
);
};
export default SidebarMenuNotes;
|
#include <Wire.h>
// Ambient light sensor
#include "DFRobot_VEML7700.h"
// Digital pin id-s.
const int cDropFlowMeterId = 3;
const int cPumpRelayId = 8;
const int cValveRelayId = 7;
const int cSolarRelayId = 4;
const int cGeneratorRelayId = 2;
//! Total number of used analog pins
const int cAnalogCount = 4;
// Analog pins
const int cUpperTankWeightSensorId = A0;
const int cLowerTankWeightSensorId = A1;
const int cCurrentSensorId = A2;
const int cBatteryVoltageSensorId = A4;
// Flow meter consts. To represent 1 liter of flow the number of squarewaves below shall happen.
const int cDropFlow_WavePerLiter = 450;
const int cLiftFlow_WavePerLiter = 5880;
//! Control state descriptor.
struct ControlState
{
int isManual;
int bottomTankEmptyCounter;
int topTankEmptyCounter;
int requestedPumpState;
int pumpState;
int requestedValveState;
int valveState;
int requestedSolarState;
int solarState;
int requestedGeneratorState;
int generatorState;
int isLowVoltageShutdown;
};
ControlState gControl;
const int cRelayStateOn = 1;
const int cRelayStateOff = 0;
// Ambient light sensor constants
const int cDaylight_lux = 100;
// Voltage and current conversion constants
const float c5VConversion = 1.0;
const float cVRef_mV = 510.0;
const float cVSensitivity_mVperA = 11.0; // 136 mV/A resolution
const float cVBatLow_mV = 3100.0;
const float cVBatOk_mV = 3900.0;
// Moving average control
const int cAvgSampleCount = 1;
int gSampleCounter = 0;
float gAnalogSamples[cAnalogCount][cAvgSampleCount];
float gSampleAccum[cAnalogCount];
bool gAvgBufferSaturated = false;
// Networking
unsigned long gWatchdogCount = 0;
bool ledON = false;
struct Measurements
{
float ambientLight_lux{0.0};
float dropFlow_lpmin{0.0};
float upperTankLevel_l{0.0};
float lowerTankLevel_l{0.0};
float current_mA{0.0};
float batteryVoltage_mV{0.0};
};
// An interesting observation
// Sometimes I received the following message. with DF Robot WifiBee module.
// 20:47:58.744 -> DNS wiki.dfrobot.com.cn, 111.231.115.214 log come up, shady???
// I believe, that when someone buys a module, whuch purpose is to provide a wifi interface
// I shouldn't be seeing any DNS identification towards the manufacturer.
const char ssid[]={
"AT+SSID=Hogspot2G"}; // WiFi SSID
const char passwd[]={
"AT+PASSWORD=mortythebooty007"}; // WiFi password
DFRobot_VEML7700 als;
/*! Initializes the WifiBee-MT7681 module
* Only need to run once to configure the module
*/
void initWifi()
{
while(!Serial);
Serial.print("+++");
delay(1000);
Serial.println(ssid);
delay(100);
Serial.println(passwd);
delay(100);
Serial.println("AT+HOSTNAME=?");
delay(100);
Serial.println("AT+REBOOT");
delay(100);
Serial.println("AT+CONNECT");
delay(10000);
}
//! Setup arduino control
void setup() {
// Configure PWM frequency.
//TCCR0B = 0b00000001; // x1
//TCCR0A = 0b00000011; // fast pwm
//TCCR0B = 0b00000010; // x8
//TCCR0A = 0b00000011; // fast pwm
Serial.begin(115200);
// Configure digital inputs, outputs.
pinMode(cDropFlowMeterId, INPUT);
pinMode(cPumpRelayId, OUTPUT);
pinMode(cValveRelayId, OUTPUT);
pinMode(cSolarRelayId, OUTPUT);
pinMode(cGeneratorRelayId, OUTPUT);
digitalWrite(cPumpRelayId, 0);
digitalWrite(cValveRelayId, 0);
digitalWrite(cSolarRelayId, 0);
digitalWrite(cGeneratorRelayId, 0);
// Initialize current sample averager buffer.
for (int i = 0; i < cAnalogCount; i++)
{
gSampleAccum[i] = 0.0;
for (int j = 0; j < cAvgSampleCount; j++)
{
gAnalogSamples[i][j] = 0.0;
}
}
delay(100);
// Setup control variables.
gControl.bottomTankEmptyCounter = 0;
gControl.topTankEmptyCounter = 0;
gControl.pumpState = 0;
gControl.requestedPumpState = 0;
gControl.valveState = 0;
gControl.requestedValveState = 0;
gControl.generatorState = 0;
gControl.requestedGeneratorState = 0;
gControl.solarState = 0;
gControl.requestedSolarState = 0;
gControl.isManual = 1;
gControl.isLowVoltageShutdown = 0;
// Using the serial as it seemed to be faster than using DF Robot WifiBee module.
//initWifi();
pinMode(LED_BUILTIN, OUTPUT);
// Initialize ambient light sensor interface.
als.begin();
}
//! Returns the lightintensity measured by the ambient light sensor.
float GetLightIntensity_lux()
{
float lux;
als.getALSLux(lux);
return lux;
}
/*! Returns the flow in liter per minutes for the given sensor. In the current sensors x number of squarewaves represent a liter.
* \param[in] flowMeterId id of the sensor pin
* \param[in] flowConst_WavePerLiter sensor squarewave count representing 1 liter flow.
*
* \return The flow in l/min unit.
*/
float GetFlow_lpmin(int flowMeterId, int flowConst_WavePerLiter)
{
int ontime, offtime;
float freq, period;
ontime = abs(pulseIn(flowMeterId, HIGH));
offtime = abs(pulseIn(flowMeterId, LOW));
period = ontime + offtime;
if (period != 0)
freq = 1000000.0 / period;
else
freq = 0;
return -freq * 60 / flowConst_WavePerLiter;
}
/*! Sensor ids are not starting from 0 and are not continuous
* This function will return id-s that meet the above two conditions.
*/
int ConvertSensorIdToSampleContainerId(int sensorId)
{
switch(sensorId)
{
case cUpperTankWeightSensorId:
return 0;
case cLowerTankWeightSensorId:
return 1;
case cCurrentSensorId:
return 2;
case cBatteryVoltageSensorId:
return 3;
default:
return 0;
}
}
/*! Updates averager control parameters.
*/
void UpdateAverager()
{
gSampleCounter++;
if (gSampleCounter == cAvgSampleCount)
{
gSampleCounter = 0;
gAvgBufferSaturated = true;
}
}
/*! Stores, calculates and returns the moving average of a sensor measurement
* \param[in] sensorId id of the sensor.
* \param[in] sample The new sample to process.
*
* \return Average value of the measurement.
*/
float GetAvgSample(int sensorId, float sample)
{
int sampleContainerId = ConvertSensorIdToSampleContainerId(sensorId);
if (gAvgBufferSaturated)
gSampleAccum[sampleContainerId] -= gAnalogSamples[sampleContainerId][gSampleCounter];
gAnalogSamples[sampleContainerId][gSampleCounter] = sample;
gSampleAccum[sampleContainerId] += sample;
return gSampleAccum[sampleContainerId] / cAvgSampleCount;
}
/*! Returns the moving average current samples for the give sensor.
* \param[in] sensorId id of the current sensor pin
*
* \return the averaged current in mA.
*/
float GetAvgCurrent_mA(int sensorId)
{
float rawCurrent_mV = analogRead(sensorId);
//float rawCurrent_mV = -2.75 * analogRead(sensorId) + 1740.0;
rawCurrent_mV = (rawCurrent_mV - cVRef_mV) * cVSensitivity_mVperA ;
return GetAvgSample(sensorId, rawCurrent_mV);
}
/*! Returns the tank level of the selected tank in liters.
* The magic numbers are set based on empirical measurements.
* The force sense resistor is not providing linear behaviour at this weight range,
* so I had to play around until I got the output value roughly corresponding to the reality.
* Need to adjust everytime the setup is being moved.
* \param[in] tankId The id of the selected tank (top, bottom tank)
*
* \return the average tank level in liters.
*/
float GetTankLevel_l(int tankId)
{
float data = 0.0;
if (tankId == cLowerTankWeightSensorId)
data = 0.0225*(analogRead(tankId)- 352);
else
data = 0.0225*(analogRead(tankId)- 460);
// the measurement is a bit inaccurate, so every negative value is just truncated to zero.
return GetAvgSample(tankId, data <= 0.0 ? 0.0 : data);
}
float GetBatteryVoltage_mV()
{
float batteryVoltage_mV = analogRead(cBatteryVoltageSensorId) * c5VConversion;
return GetAvgSample(cBatteryVoltageSensorId, batteryVoltage_mV);
}
void CheckWatchdog()
{
if (gWatchdogCount > 4000)
{
gWatchdogCount = 0;
Serial.write("$ARDY,*");
if (ledON)
{
digitalWrite(LED_BUILTIN, HIGH);
ledON = false;
}
else
{
digitalWrite(LED_BUILTIN, LOW);
ledON = true;
}
}
gWatchdogCount++;
}
//! Sends control states to the desktop client.
void SendControlFeedback()
{
String resp = "$ACTL,";
resp.concat(gControl.isManual);
resp.concat(",");
resp.concat(gControl.bottomTankEmptyCounter);
resp.concat(",");
resp.concat(gControl.topTankEmptyCounter);
resp.concat(",");
resp.concat(gControl.pumpState);
resp.concat(",");
resp.concat(gControl.valveState);
resp.concat(",");
resp.concat(gControl.solarState);
resp.concat(",");
resp.concat(gControl.generatorState);
resp.concat(",");
resp.concat(gControl.isLowVoltageShutdown);
resp.concat("*");
Serial.write(resp.c_str());
}
/*! Processes incoming messages, and generates responses using measurement data.
Most of the messages just sending an ACK feedback except the RDTA, data message.
*/
void ProcessMessage(String msg, const Measurements& data)
{
String header = msg.substring(0,5);
if (header == "$RDTA")
{
gWatchdogCount = 0;
String resp = "$ADTA,";
resp.concat(data.ambientLight_lux);
resp.concat(",");
resp.concat(data.current_mA);
resp.concat(",");
resp.concat(data.batteryVoltage_mV);
resp.concat(",");
resp.concat(data.dropFlow_lpmin);
resp.concat(",");
resp.concat(data.upperTankLevel_l);
resp.concat(",");
resp.concat(data.lowerTankLevel_l);
resp.concat(",");
resp.concat(data.lowerTankLevel_l + data.upperTankLevel_l);
resp.concat("*");
Serial.write(resp.c_str());
}
else if(header == "$RSTT")
{
SendControlFeedback();
}
else if(header == "$RPMP")
{
gControl.requestedPumpState = msg.substring(6, 7).toInt();
Serial.write("$APMP*");
}
else if(header == "$RVLV")
{
gControl.requestedValveState = msg.substring(6, 7).toInt();
Serial.write("$AVLV*");
}
else if(header == "$RSLR")
{
gControl.requestedSolarState = msg.substring(6, 7).toInt();
Serial.write("$ASLR*");
}
else if(header == "$RGNR")
{
gControl.requestedGeneratorState = msg.substring(6, 7).toInt();
Serial.write("$AGNR*");
}
else if(header == "$RMNL")
{
gControl.isManual = msg.substring(6, 7).toInt();
Serial.write("$AMNL*");
}
}
/*! Returns true if the ambient light sensor
* detects the minimum charging light radiation.
*
*/
bool isDay(const Measurements& data)
{
return data.ambientLight_lux > cDaylight_lux;
}
/*! Returns true if the battery voltage is getting
* low and needs charging.
*/
bool isBatteryLow(const Measurements& data)
{
return data.batteryVoltage_mV < cVBatLow_mV;
}
/*! Returns true if the battery has operational voltage.
*/
bool isBatteryOk(const Measurements& data)
{
return data.batteryVoltage_mV > cVBatOk_mV;
}
/*! Returns true if the pump is on.
*/
bool isPumping()
{
return gControl.pumpState == cRelayStateOn;
}
/*! Returns true if there is no fluid in the bottom tank.
*/
bool isPumped(const Measurements& data)
{
return data.lowerTankLevel_l <= 0.0;
}
/*! Returns true if the valve is on.
*/
bool isFluidDischarging()
{
return gControl.valveState == cRelayStateOn;
}
/*! Returns true if there is no fluid in the top tank.
*/
bool isFluidDischarged(const Measurements& data)
{
return data.upperTankLevel_l <= 0.0;
}
/*! Sets the new state for the selected relay
* if different from the current one.
*/
void setState(int relayId, int newState)
{
int *pCurrentState = nullptr;
switch(relayId)
{
case cPumpRelayId:
pCurrentState = &gControl.pumpState;
break;
case cValveRelayId:
pCurrentState = &gControl.valveState;
break;
case cSolarRelayId:
pCurrentState = &gControl.solarState;
break;
case cGeneratorRelayId:
pCurrentState = &gControl.generatorState;
break;
default:
return;
}
if (newState != *pCurrentState)
{
*pCurrentState = newState;
digitalWrite(relayId, *pCurrentState);
}
}
/*! Runs manual control state machine.
* Pump must be switched off if there is nothing to pump
* Solar and generator cannot be on at the same time
* to avoid reverse currents for these sources.
*/
void manualControl(const Measurements& data)
{
setState(cValveRelayId, gControl.requestedValveState);
if(gControl.requestedValveState)
{
gControl.requestedGeneratorState = 1;
gControl.requestedSolarState = 0;
}
if (isPumped(data))
setState(cPumpRelayId, cRelayStateOff);
else
setState(cPumpRelayId, gControl.requestedPumpState);
if (gControl.requestedSolarState)
{
gControl.requestedGeneratorState = 0;
setState(cGeneratorRelayId, gControl.requestedGeneratorState);
// wait time makes sure the generator is off.
delay(100);
setState(cSolarRelayId, cRelayStateOn);
}
else
{
setState(cSolarRelayId, cRelayStateOff);
}
if (gControl.requestedGeneratorState)
{
gControl.requestedSolarState = 0;
setState(cSolarRelayId, gControl.requestedSolarState);
// wait time makes sure the solar is off.
delay(100);
setState(cGeneratorRelayId, cRelayStateOn);
}
else
{
setState(cGeneratorRelayId, cRelayStateOff);
}
if(isBatteryLow(data) && isFluidDischarged(data))
{
gControl.isLowVoltageShutdown = 1;
}
else if(!isBatteryLow(data) || !isFluidDischarged(data))
{
gControl.isLowVoltageShutdown = 0;
}
}
/*! Runs automatic control
* It pumps and solar charges during the day, and turbine charges during the night.
* Makes sure that solar and generator is not on at the same time
* to avoid reverse current to the sources.
*
* If the upper tank is empty and the battery is low
* a low battery shutdown signal will be sent to the remote.
*
* If the battery charges to operational voltage during fluid discharge
* the emptying process will stop.
*/
void autoControl(const Measurements& data)
{
if (isDay(data))
{
setState(cValveRelayId, cRelayStateOff);
setState(cGeneratorRelayId, cRelayStateOff);
// wait time makes sure the generator is off.
delay(100);
setState(cSolarRelayId, cRelayStateOn);
if (isBatteryOk(data) && !isPumped(data))
setState(cPumpRelayId, cRelayStateOn);
else if(isPumped(data))
setState(cPumpRelayId, cRelayStateOff);
}
else
{
setState(cPumpRelayId, cRelayStateOff);
setState(cSolarRelayId, cRelayStateOff);
// wait time makes sure the solar is off.
delay(100);
if (isBatteryLow(data) && !isFluidDischarged(data))
{
setState(cGeneratorRelayId, cRelayStateOn);
// no need to wait for generator turn on
// valve opens very slow.
setState(cValveRelayId, cRelayStateOn);
}
else if(isFluidDischarged(data) ||
(isBatteryOk(data) && isFluidDischarging()))
{
setState(cGeneratorRelayId, cRelayStateOff);
setState(cValveRelayId, cRelayStateOff);
}
else if(isBatteryLow(data) && isFluidDischarged(data))
{
gControl.isLowVoltageShutdown = 1;
}
else if(!isBatteryLow(data))
{
gControl.isLowVoltageShutdown = 0;
}
}
}
void loop() {
Measurements data;
data.ambientLight_lux = GetLightIntensity_lux();
data.current_mA = GetAvgCurrent_mA(cCurrentSensorId);
data.batteryVoltage_mV = GetBatteryVoltage_mV();
if(gControl.generatorState)
data.dropFlow_lpmin = GetFlow_lpmin(cDropFlowMeterId, cDropFlow_WavePerLiter);
data.upperTankLevel_l = GetTankLevel_l(cUpperTankWeightSensorId);
data.lowerTankLevel_l = GetTankLevel_l(cLowerTankWeightSensorId);
if (gControl.isManual == 0)
autoControl(data);
else
manualControl(data);
while(Serial.available() != 0)
{
String recvRaw = Serial.readString();
int asterixIndex = 0;
while (asterixIndex != -1)
{
asterixIndex = recvRaw.indexOf("*");
recvRaw = recvRaw.substring(0,asterixIndex);
ProcessMessage(recvRaw, data);
}
}
CheckWatchdog();
UpdateAverager();
}
|
import math
import random
from collections import deque, namedtuple
import torch
import torch.nn.functional as F
from torch import nn, optim
class DQN(nn.Module):
def __init__(self, n_observations, n_actions, *args, **kwargs):
super().__init__(*args, **kwargs)
self.layer1 = nn.Linear(n_observations, 72)
self.layer2 = nn.Linear(72, 128)
self.layer3 = nn.Linear(128, 256)
self.layer4 = nn.Linear(256, 128)
self.layer5 = nn.Linear(128, 64)
self.layer6 = nn.Linear(64, n_actions)
def forward(self, x):
x = F.relu(self.layer1(x))
x = F.relu(self.layer2(x))
x = F.relu(self.layer3(x))
x = F.relu(self.layer4(x))
x = F.relu(self.layer5(x))
return self.layer6(x)
class ReplayMemory(object):
def __init__(self, capacity):
self.memory = deque([], maxlen=capacity)
self._transition = namedtuple('Transition',
('state', 'action', 'next_state', 'reward'))
def push(self, *args):
"""Save a transition"""
self.memory.append(self._transition(*args))
def sample(self, batch_size):
return random.sample(self.memory, batch_size)
def add_batch(self, additional_memory: deque):
self.memory += additional_memory
def get_all(self):
return self.memory
def __len__(self):
return len(self.memory)
class DQNAgent:
def __init__(self, device, state, action_num):
self._transition = namedtuple('Transition',
('state', 'action', 'next_state', 'reward'))
self.batch_size = 128
self.gamma = 0.99
self.eps_start = 0.95
self.eps_end = 0.075
self.eps_decay = 1000
self.tau = 0.001
self.lr = 0.0005
self.steps_done = 0
self.n_actions = action_num
self.state = state
self.n_observations = len(self.state[0])
self.policy_net = DQN(self.n_observations, self.n_actions).to(device)
self.target_net = DQN(self.n_observations, self.n_actions).to(device)
self.target_net.load_state_dict(self.policy_net.state_dict())
self.optimizer = optim.AdamW(self.policy_net.parameters(), lr=self.lr, amsgrad=True)
self.memory = ReplayMemory(5000000)
self.device = device
def optimize_model(self):
if len(self.memory) < self.batch_size:
return
transitions = self.memory.sample(self.batch_size)
# Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for
# detailed explanation). This converts batch-array of Transitions
# to Transition of batch-arrays.
batch = self._transition(*zip(*transitions))
# Compute a mask of non-final states and concatenate the batch elements
# (a final state would've been the one after which simulation ended)
non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,
batch.next_state)), device=self.device, dtype=torch.bool)
non_final_next_states = torch.cat([s for s in batch.next_state
if s is not None])
state_batch = torch.cat(batch.state)
action_batch = torch.cat(batch.action)
reward_batch = torch.cat(batch.reward)
# Compute Q(s_t, a) - the model computes Q(s_t), then we select the
# columns of actions taken. These are the actions which would've been taken
# for each batch state according to policy_net
state_action_values = self.policy_net(state_batch).gather(1, action_batch)
# Compute V(s_{t+1}) for all next states.
# Expected values of actions for non_final_next_states are computed based
# on the "older" target_net; selecting their best reward with max(1)[0].
# This is merged based on the mask, such that we'll have either the expected
# state value or 0 in case the state was final.
next_state_values = torch.zeros(self.batch_size, device=self.device)
with torch.no_grad():
next_state_values[non_final_mask] = self.target_net(non_final_next_states).max(1)[0]
# Compute the expected Q values
expected_state_action_values = (next_state_values * self.gamma) + reward_batch
# Compute Huber loss
criterion = nn.SmoothL1Loss()
loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1))
# Optimize the model
self.optimizer.zero_grad()
loss.backward()
# In-place gradient clipping
torch.nn.utils.clip_grad_value_(self.policy_net.parameters(), 100)
self.optimizer.step()
def select_action(self, state, action_sample):
sample = random.random()
eps_threshold = self.eps_end + (self.eps_start - self.eps_end) * \
math.exp(-1. * self.steps_done / self.eps_decay)
self.steps_done += 1
if sample > eps_threshold:
with torch.no_grad():
return self.policy_net(state).max(1)[1].view(1, 1)
else:
return torch.tensor([[action_sample]], device=self.device, dtype=torch.long)
def learn(self, state, action, next_state, reward):
# Store the transition in memory
self.memory.push(state, action, next_state, reward)
self.optimize_model()
# Soft update of the target network's weights
# θ′ ← τ θ + (1 −τ )θ′
target_net_state_dict = self.target_net.state_dict()
policy_net_state_dict = self.policy_net.state_dict()
for key in policy_net_state_dict:
target_net_state_dict[key] = policy_net_state_dict[key] * self.tau + target_net_state_dict[key] * (
1 - self.tau)
self.target_net.load_state_dict(target_net_state_dict)
|
import React, { useState, useEffect } from 'react';
const Down = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://flask-production-6865.up.railway.app/');
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const responseData = await response.json();
setData(responseData);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return (
<div>
<h1>Endpoint Data</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default Down;
|
<?php
namespace App\Http\Controllers;
use Exception;
use Midtrans\Snap;
use App\Models\Cart;
use Midtrans\Config;
use Midtrans\Notification;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Models\TransactionDetail;
use Illuminate\Support\Facades\Auth;
class CheckoutController extends Controller
{
public function process(Request $request)
{
// save user data
$user = Auth::user();
$user->update($request->except('total_price'));
// Proses checkout
$code = 'STORE-' . mt_rand(00000, 99999);
$carts = Cart::with(['product', 'user'])
->where('users_id', Auth::user()->id)
->get();
// Transaction create
$transaction = Transaction::create([
'users_id' => Auth::user()->id,
'insurance_price' => 0,
'shipping_price' => 0,
'total_price' => (int)$request->total_price,
'transaction_status' => 'PENDING',
'code' => $code
]);
// Transaction Detail create
foreach ($carts as $cart) {
$trx = 'TRX-' . mt_rand(00000, 99999);
TransactionDetail::create([
'transactions_id' => $transaction->id,
'products_id' => $cart->product->id,
'price' => $cart->product->price,
'shipping_status' => 'PENDING',
'resi' => '',
'code' => $trx
]);
}
// delete cart data
Cart::with(['product', 'user'])->where('users_id', Auth::user()->id)->delete();
// Konfigurasi Midtrans
// Set your Merchant Server Key
Config::$serverKey = config('services.midtrans.serverKey');
// Set to Development/Sandbox Environment (default). Set to true for Production Environment (accept real transaction).
Config::$isProduction = config('services.midtrans.isProduction');
// Set sanitization on (default)
Config::$isSanitized = config('services.midtrans.isSanitized');
// Set 3DS transaction for credit card to true
Config::$is3ds = config('services.midtrans.is3ds');
// Buat array untuk di kirim ke midtrans
$midtrans = [
'transaction_details' => [
'order_id' => $code,
'gross_amount' => (int)$request->total_price
],
'customer_details' => [
'first_name' => Auth::user()->name,
'email' => Auth::user()->email
],
'enabled_payments' => [
'gopay', 'permata_va', 'bank_transfer'
],
'vtweb' => []
];
try {
// Get Snap Payment Page URL
$paymentUrl = Snap::createTransaction($midtrans)->redirect_url;
// Redirect to Snap Payment Page
return redirect($paymentUrl);
} catch (Exception $e) {
echo $e->getMessage();
}
}
public function callback(Request $request)
{
// Untuk callback midtrans
// Set konfigurasi midtrans
Config::$serverKey = config('services.midtrans.serverKey');
Config::$isProduction = config('services.midtrans.isProduction');
Config::$isSanitized = config('services.midtrans.isSanitized');
Config::$is3ds = config('services.midtrans.is3ds');
// Buat instance midtrans notification
$notification = new Notification();
// Assign ke variable untuk memudahkan coding
$status = $notification->transaction_status;
$type = $notification->payment_type;
$fraud = $notification->fraud_status;
$order_id = $notification->order_id;
// Cari transaksi berdasarkan ID
$transaction = Transaction::findOrFail($order_id);
// Handle notification status midtrans
if ($status == 'capture') {
if ($type == 'credit_card') {
if ($fraud == 'challenge') {
$transaction->status = 'PENDING';
} else {
$transaction->status = 'SUCCESS';
}
}
} else if ($status == 'settlement') {
$transaction->status = 'SUCCESS';
} else if ($status == 'pending') {
$transaction->status = 'PENDING';
} else if ($status == 'deny') {
$transaction->status = 'CANCELLED';
} else if ($status == 'expire') {
$transaction->status = 'CANCELLED';
} else if ($status == 'cancel') {
$transaction->status = 'CANCELLED';
}
// Simpan transaksi
$transaction->save();
return response()->json([
'meta' => [
'code' => 200,
'message' => 'Midtrans Notification Success'
]
]);
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
namespace Z80_RC2014
{
public partial class CompactFlash : UserControl
{
#region Members
// Standard folder for load/save files
private string folder = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
#endregion
#region Constructor
public CompactFlash()
{
InitializeComponent();
// Create empty image with 16 drives and 512 dir entries each
New(512);
}
#endregion
#region EventHandlers
/// <summary>
/// Show boot sector
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnBoot_Click(object sender, EventArgs e)
{
// Create form for display of results
Form bootForm = new Form();
bootForm.Name = "FormBoot";
bootForm.Text = "Boot 'Sector'";
bootForm.Icon = Properties.Resources.Z80;
bootForm.Size = new Size(680, 600);
bootForm.MinimumSize = new Size(680, 600);
bootForm.MaximumSize = new Size(680, 600);
bootForm.MaximizeBox = false;
bootForm.MinimizeBox = false;
bootForm.StartPosition = FormStartPosition.CenterScreen;
// Create button for closing (dialog)form
Button btnOk = new Button();
btnOk.Text = "OK";
btnOk.Location = new Point(584, 530);
btnOk.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
btnOk.Visible = true;
btnOk.Click += new EventHandler((object o, EventArgs a) =>
{
bootForm.Close();
});
Font font = new Font(FontFamily.GenericMonospace, 10.25F);
// Compose
DiskImage diskImage = (DiskImage)lbImages.SelectedItem;
string boot = "";
string ascii = "";
for (int address = 0; address < DiskImage.BOOTSIZE; address++)
{
if (address % 16 == 0)
{
if (address != 0) boot += " " + ascii + "\r\n";
ascii = "";
boot += address.ToString("X").PadLeft(4, '0') + ": ";
}
boot += diskImage.bytes[address].ToString("X").PadLeft(2, '0') + " ";
if ((diskImage.bytes[address] < 128) && (diskImage.bytes[address] >= 32)) ascii += Convert.ToChar(diskImage.bytes[address]); else ascii += ".";
}
// Add controls to form
TextBox textBox = new TextBox();
textBox.Multiline = true;
textBox.WordWrap = false;
textBox.ScrollBars = ScrollBars.Vertical;
textBox.ReadOnly = true;
textBox.BackColor = Color.LightYellow;
textBox.Size = new Size(648, 510);
textBox.Text = boot;
textBox.Font = font;
textBox.BorderStyle = BorderStyle.None;
textBox.Location = new Point(10, 10);
textBox.Select(0, 0);
bootForm.Controls.Add(textBox);
bootForm.Controls.Add(btnOk);
// Show form
bootForm.Show();
}
/// <summary>
/// Open image file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Select Image File";
fileDialog.InitialDirectory = folder;
fileDialog.FileName = "";
fileDialog.Multiselect = false;
fileDialog.Filter = "CPM Disk Image (Container)|*.img;*.cpm|All Files|*.*";
if (fileDialog.ShowDialog() != DialogResult.Cancel)
{
string fileName = fileDialog.FileName;
folder = Path.GetDirectoryName(fileDialog.FileName);
// Read image file into byte array
byte[] bytes = File.ReadAllBytes(fileName);
// Check if this is a single diskimage
if (fileName.ToLower().EndsWith(".cpm"))
{
if (lbImages.Items.Count >= 16)
{
MessageBox.Show("No more room for images (max = drive 'P')", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Create new diskimage object
int max_dir = 512;
byte drive = (byte)('A' + lbImages.Items.Count);
DiskImage diskImage = new DiskImage(Convert.ToChar(drive).ToString(), bytes, max_dir);
// Add the new object (image) to the listbox
lbImages.Items.Add(diskImage);
} else
{
// If not, assume a container of 8MB disk images (2MB image at the end ?)
lbImages.Items.Clear();
btnBoot.Visible = false;
string folderName = "";
string[] temp = fileName.Split('\\');
for (int i = 0; i < temp.Length - 1; i++) folderName += temp[i] + "\\";
int parts = bytes.Length / 0x00800000;
if (bytes.Length % 0x00800000 != 0) parts++;
for (int part = 0; part < parts; part++)
{
int bytes_left = bytes.Length - (part * 0x00800000);
if (bytes_left > 0x00800000) bytes_left = 0x00800000;
byte[] bytes_image = new byte[bytes_left];
Array.Copy(bytes, part * 0x00800000, bytes_image, 0, bytes_left);
// Create new diskimage object
int max_dir = Convert.ToInt32(512);
byte drive = (byte)('A' + lbImages.Items.Count);
DiskImage diskImage = new DiskImage(Convert.ToChar(drive).ToString(), bytes_image, max_dir);
if ((drive == 'P') && (bytes_image.Length > (2 * 1024 * 1024)))
{
MessageBox.Show("Drive 'P' is larger then 2MB.\r\nThis may not fit a Compact Flash Card of 128MB", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
// Add the new object (image) to the listbox
lbImages.Items.Add(diskImage);
}
}
// Show files in this image
lbImages.SelectedIndex = lbImages.Items.Count - 1;
ShowImageFiles((DiskImage)lbImages.SelectedItem);
}
}
/// <summary>
/// Save image(container)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e)
{
if (lbImages.Items.Count > 0)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Title = "Save File As";
fileDialog.InitialDirectory = folder;
fileDialog.FileName = "";
fileDialog.Filter = "IMG Disk Image Container|*.img|All Files|*.*";
if (fileDialog.ShowDialog() != DialogResult.Cancel)
{
string fileNameContainer = fileDialog.FileName;
folder = Path.GetDirectoryName(fileDialog.FileName);
int size = 0;
foreach (DiskImage diskImage in lbImages.Items)
{
size += diskImage.bytes.Length;
}
byte[] bytes = new byte[size];
int index = 0;
foreach (DiskImage diskImage in lbImages.Items)
{
for (int i = 0; i < diskImage.bytes.Length; i++)
{
bytes[index++] = diskImage.bytes[i];
}
}
// Save binary file
File.WriteAllBytes(fileNameContainer, bytes);
MessageBox.Show("File saved as '" + fileNameContainer + "'", "SAVED", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
/// <summary>
/// New drives
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnNew_Click(object sender, EventArgs e)
{
New(512);
}
/// <summary>
/// Reload file index from memory
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnReload_Click(object sender, EventArgs e)
{
if (lbImages.SelectedItem != null)
{
DiskImage diskImage = (DiskImage)lbImages.SelectedItem;
diskImage.SetFileInfo();
ShowImageFiles(diskImage);
}
}
/// <summary>
/// Image file selected
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lbImages_SelectedIndexChanged(object sender, EventArgs e)
{
// Show files in this image
if (lbImages.SelectedItem != null)
{
ShowImageFiles((DiskImage)lbImages.SelectedItem);
}
}
#endregion
#region Methods
/// <summary>
/// New image
/// </summary>
/// <param name="max_dir"></param>
public void New(int max_dir)
{
// Delete old drives
lbImages.Items.Clear();
// Create 16 drives (A to P)
for (int index = 0; index < 16; index++)
{
// Create new empty image, standard 8MB. Only 2Mb if last one (P)
char drive = (char)('A' + index);
byte[] bytes;
if (drive > 'P')
{
MessageBox.Show("No more room for images (max = drive 'P')", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
} else if (drive == 'P')
{
bytes = new byte[0x00200000];
} else
{
bytes = new byte[0x00800000];
}
DiskImage diskImage = new DiskImage(drive.ToString(), bytes, max_dir);
// Set dir entries to empty
for (int i = 0; i < max_dir; i++)
{
if (diskImage.boot)
{
diskImage.bytes[DiskImage.BOOTSIZE + i * 32] = 0xE5;
} else
{
diskImage.bytes[i * 32] = 0xE5;
}
}
// Update file info
diskImage.SetFileInfo();
// Add the new object (image) to the listbox
lbImages.Items.Add(diskImage);
}
lbImages.SelectedIndex = 0;
}
/// <summary>
/// Show files in this image
/// </summary>
/// <param name="diskImage"></param>
private void ShowImageFiles(DiskImage diskImage)
{
dgvFiles.Rows.Clear();
dgvFiles.Columns.Clear();
if (diskImage == null) return;
// Show size
lblSize.Text = "Size: " + (diskImage.bytes.Length / 0x100000).ToString() + " MB";
// Show boot (if assigned)
btnBoot.Visible = false;
if (diskImage.boot) btnBoot.Visible = true;
// Create font for header text
Font font = new Font("Tahoma", 8.25F, FontStyle.Bold);
// Fill datagridview with info
dgvFiles.Columns.Add("index", "Index");
dgvFiles.Columns.Add("number", "User Number");
dgvFiles.Columns.Add("file", "File");
dgvFiles.Columns.Add("type", "Type");
dgvFiles.Columns.Add("extend_high", "Extend Counter High");
dgvFiles.Columns.Add("extend_low", "Extend Counter Low");
dgvFiles.Columns.Add("count", "Record Count");
dgvFiles.Columns["count"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dgvFiles.Columns.Add("size", "Extent Size");
dgvFiles.Columns["size"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dgvFiles.Columns.Add("block", "Block Pointers");
foreach (DataGridViewColumn column in dgvFiles.Columns)
{
column.HeaderCell.Style.Font = font;
}
for (int i = 0; i < diskImage.max_dir; i++)
{
// If user number is not E5 then file entry not empty
if (diskImage.files[i].user_number != 0xE5)
{
dgvFiles.Rows.Add();
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["index"].Value = i;
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["number"].Value = diskImage.files[i].user_number;
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["file"].Value = diskImage.files[i].file_name.Trim();
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["type"].Value = diskImage.files[i].file_type.Trim();
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["extend_high"].Value = diskImage.files[i].extend_counter_high;
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["extend_low"].Value = diskImage.files[i].extend_counter_low;
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["count"].Value = diskImage.files[i].record_count;
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["size"].Value = diskImage.files[i].extent_size;
dgvFiles.Rows[dgvFiles.Rows.Count - 1].Cells["block"].Value = (diskImage.files[i].block_pointers[ 0] + diskImage.files[i].block_pointers[ 1] * 256).ToString() + ", " +
(diskImage.files[i].block_pointers[ 2] + diskImage.files[i].block_pointers[ 3] * 256).ToString() + ", " +
(diskImage.files[i].block_pointers[ 4] + diskImage.files[i].block_pointers[ 5] * 256).ToString() + ", " +
(diskImage.files[i].block_pointers[ 6] + diskImage.files[i].block_pointers[ 7] * 256).ToString() + ", " +
(diskImage.files[i].block_pointers[ 8] + diskImage.files[i].block_pointers[ 9] * 256).ToString() + ", " +
(diskImage.files[i].block_pointers[10] + diskImage.files[i].block_pointers[11] * 256).ToString() + ", " +
(diskImage.files[i].block_pointers[12] + diskImage.files[i].block_pointers[13] * 256).ToString() + ", " +
(diskImage.files[i].block_pointers[14] + diskImage.files[i].block_pointers[15] * 256).ToString();
}
}
}
/// <summary>
/// Insert a file in a diskimage
/// </summary>
/// <param name="volume"></param>
/// <param name="binary"></param>
/// <param name="fileName"></param>
public void InsertFile(string volume, byte[] binary, string fileName = "")
{
DiskImage diskImage = null;
fileName = fileName.ToUpper();
// Search for diskimage from this volume
foreach (DiskImage image in lbImages.Items)
{
if (image.volume.ToUpper() == volume.ToUpper())
{
diskImage = image;
}
}
// Select volume in screen
lbImages.SelectedItem = diskImage;
if (diskImage == null)
{
MessageBox.Show("Volume '" + volume + "' was not found", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// If fileName is empty and on disk A then insert as binary (boot) code
if (diskImage.boot && (fileName == ""))
{
// Insert into boot 'sector'
diskImage.InsertBoot(binary);
return;
}
// Check if the number of files is lower then max
if (diskImage.num_files >= diskImage.max_dir)
{
MessageBox.Show("Too many files on this disk", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Check Folder/File names for duplicates
bool found = false;
string[] temp = fileName.Split('.');
string name = temp[0];
string type = "";
if (temp.Length > 1) type = temp[1];
foreach (DiskImage.FILE file in diskImage.files)
{
if (file.user_number != 0xE5)
{
if ((file.file_name.Trim() == name.Trim()) && (file.file_type.Trim() == type.Trim())) found = true;
}
}
if (found)
{
MessageBox.Show("Already a file with the same name/type present: " + name + "." + type + "\r\nChanging user number for this file", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
// Insert
diskImage.InsertFile(name, type, binary);
// Update screen
ShowImageFiles(diskImage);
}
/// <summary>
/// Get data from disk
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public byte GetData(int address)
{
byte data = 0x00;
int drive = address / (8 * 0x100000);
address = address % (8 * 0x100000);
if (lbImages.Items.Count > 0)
{
DiskImage diskImage = (DiskImage)lbImages.Items[drive];
if (address < diskImage.bytes.Length)
{
data = diskImage.bytes[address];
}
}
return data;
}
/// <summary>
/// Put data on disk
/// </summary>
/// <param name="address"></param>
/// <param name="data"></param>
/// <returns></returns>
public void PutData(int address, byte data)
{
int drive = address / (8 * 0x100000);
address = address % (8 * 0x100000);
if (lbImages.Items.Count > 0)
{
DiskImage diskImage = (DiskImage)lbImages.Items[drive];
if (address < diskImage.bytes.Length)
{
diskImage.bytes[address] = data;
}
}
}
#endregion
}
}
|
package Running_concurrent_phased_tasks;
import java.util.concurrent.Phaser;
public class Main {
public static void main(String[] args) {
// Creates a Phaser with 3 participants
Phaser phaser = new Phaser(3);
// Creates 3 FileSearch Objects, each of them searches in different directories
FileSearch system = new FileSearch("C:\\Windows","log",phaser);
FileSearch apps = new FileSearch("C:\\Program Files","log",phaser);
FileSearch documents = new FileSearch("C:\\Documents And Settings","log",phaser);
// Creates a thread to run the system FileSearch and starts it
Thread systemThread = new Thread(system,"System");
systemThread.start();
// Creates a thread to run the apps FileSearch and starts it
Thread appsThread = new Thread(apps,"Apps");
appsThread.start();
// Creates a thread to run the documents FileSearch and starts it
Thread documentsThread = new Thread(documents,"Documents");
documentsThread.start();
try {
systemThread.join();
appsThread.join();
documentsThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Terminated: %s\n", phaser.isTerminated());
}
}
|
## Used to sample donald tweets
from __future__ import print_function
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
import numpy as np
import random
import sys
text = open('data/tweets.txt').read().lower()
print('corpus length:', len(text))
chars = set(text)
print('total chars:', len(chars))
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((i, c) for i, c in enumerate(chars))
# cut the text in semi-redundant sequences of maxlen characters
maxlen = 20
step = 3
sentences = []
next_chars = []
for i in range(0, len(text) - maxlen, step):
sentences.append(text[i: i + maxlen])
next_chars.append(text[i + maxlen])
print('nb sequences:', len(sentences))
print('Vectorization...')
X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool)
y = np.zeros((len(sentences), len(chars)), dtype=np.bool)
for i, sentence in enumerate(sentences):
for t, char in enumerate(sentence):
X[i, t, char_indices[char]] = 1
y[i, char_indices[next_chars[i]]] = 1
def create_model():
# build the model: 2 stacked LSTM
print('Build model...')
model = Sequential()
model.add(LSTM(512, return_sequences=True, input_shape=(maxlen, len(chars))))
model.add(Dropout(0.2))
model.add(LSTM(512, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(len(chars)))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.load_weights("donald_weights.h5")
return model
def sample(a, temperature=1.0):
# helper function to sample an index from a probability array
a = np.log(a) / temperature
a = np.exp(a) / np.sum(np.exp(a))
return np.argmax(np.random.multinomial(1, a, 1))
model = create_model()
seeds = [
"Obama is one of the",
"Marco Rubio is a",
"Jeb bush is such a",
"America really needs to",
"My wife and I love to",
"The meaning of life is to",
"I once took a",
"I am the best at",
"Theres something seriously wrong"
]
for sentence in seeds:
for iteration in range(140):
x = np.zeros((1, maxlen, len(chars)))
for t, char in enumerate(sentence):
x[0, t, char_indices[char]] = 1.
preds = model.predict(x, verbose=0)[0]
next_index = sample(preds, diversity)
next_char = indices_char[next_index]
generated += next_char
sentence = sentence[1:] + next_char
sys.stdout.write(next_char)
sys.stdout.flush()
print()
|
enum TermProfileType @goModel(model: "github.com/guicostaarantes/psi-server/modules/agreements/models.TermProfileType") {
PATIENT
PSYCHOLOGIST
}
input UpsertTermInput @goModel(model: "github.com/guicostaarantes/psi-server/modules/agreements/models.Term") {
name: String!
version: Int!
profileType: TermProfileType!
active: Boolean!
}
input UpsertAgreementInput @goModel(model: "github.com/guicostaarantes/psi-server/modules/agreements/models.UpsertAgreementInput") {
termName: String!
termVersion: Int!
agreed: Boolean!
}
type Term @goModel(model: "github.com/guicostaarantes/psi-server/modules/agreements/models.Term") {
name: String!
version: Int!
active: Boolean!
}
type Agreement @goModel(model: "github.com/guicostaarantes/psi-server/modules/agreements/models.Agreement") {
id: ID!
termName: String!
termVersion: Int!
profileId: String!
}
extend type Query {
"""The patientProfile query allows a user to get a patient profile from other user."""
patientTerms: [Term!]! @hasRole(role: [COORDINATOR,PSYCHOLOGIST,PATIENT])
"""The psychologistProfile query allows a user to get a psychologist profile from other user."""
psychologistTerms: [Term!]! @hasRole(role: [COORDINATOR,PSYCHOLOGIST])
}
extend type Mutation {
"""The upsertPatientAgreement mutation allows a user to create or update an agreement to a term for patients."""
upsertPatientAgreement(input: UpsertAgreementInput!): Boolean @hasRole(role: [PATIENT])
"""The upsertPsychologistAgreement mutation allows a user to create or update an agreement to a term for psychologists."""
upsertPsychologistAgreement(input: UpsertAgreementInput!): Boolean @hasRole(role: [PSYCHOLOGIST])
"""The upsertTerm mutation allows a user to create or update a term."""
upsertTerm(input: UpsertTermInput!): Boolean @hasRole(role: [COORDINATOR])
}
|
package com.bankntt.businesspartner.domain.validation.interfaces;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import com.bankntt.businesspartner.domain.validation.classes.BusinessPartnerTypeValidator;
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = BusinessPartnerTypeValidator.class)
@Documented
public @interface BusinessPartnerTypeValidation {
String message() default "Business Partner type not exist the valid values be: C = Company, P - People";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
class CustomerRequestListResponse{
String? condition;
String? requestno;
String? name;
String? address;
String? contact;
String? phoneno;
String? salespersoncode;
String? countryregioncode;
String? postcode;
String? email;
String? mobilephoneno;
String? gstregistractionno;
String? gstregistractiontype;
String? gstcustomertype;
String? panno;
String? statecode;
String? zone;
String? district;
String? region;
String? taluka;
String? customertype;
String? vendortype;
String? territorytype;
String? seedlicenseno;
String? status;
String? createdby;
String? createdon;
String? updatedon;
CustomerRequestListResponse({this.condition, this.requestno, this.name, this.address, this.contact, this.phoneno, this.salespersoncode, this.countryregioncode, this.postcode, this.email, this.mobilephoneno, this.gstregistractionno, this.gstregistractiontype, this.gstcustomertype, this.panno, this.statecode, this.zone, this.district, this.region, this.taluka, this.customertype, this.vendortype, this.territorytype, this.seedlicenseno, this.status, this.createdby, this.createdon, this.updatedon});
CustomerRequestListResponse.fromJson(Map<String, dynamic> json) {
condition = json['condition'];
requestno = json['request_no'];
name = json['name'];
address = json['address'];
contact = json['contact'];
phoneno = json['phone_no'];
salespersoncode = json['sales_person_code'];
countryregioncode = json['country_region_code'];
postcode = json['post_code'];
email = json['email'];
mobilephoneno = json['mobile_phone_no'];
gstregistractionno = json['gst_registraction_no'];
gstregistractiontype = json['gst_registraction_type'];
gstcustomertype = json['gst_customer_type'];
panno = json['pan_no'];
statecode = json['state_code'];
zone = json['zone'];
district = json['district'];
region = json['region'];
taluka = json['taluka'];
customertype = json['customer_type'];
vendortype = json['vendor_type'];
territorytype = json['territory_type'];
seedlicenseno = json['seed_license_no'];
status = json['status'];
createdby = json['created_by'];
createdon = json['created_on'];
updatedon = json['updated_on'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['condition'] = condition;
data['request_no'] = requestno;
data['name'] = name;
data['address'] = address;
data['contact'] = contact;
data['phone_no'] = phoneno;
data['sales_person_code'] = salespersoncode;
data['country_region_code'] = countryregioncode;
data['post_code'] = postcode;
data['email'] = email;
data['mobile_phone_no'] = mobilephoneno;
data['gst_registraction_no'] = gstregistractionno;
data['gst_registraction_type'] = gstregistractiontype;
data['gst_customer_type'] = gstcustomertype;
data['pan_no'] = panno;
data['state_code'] = statecode;
data['zone'] = zone;
data['district'] = district;
data['region'] = region;
data['taluka'] = taluka;
data['customer_type'] = customertype;
data['vendor_type'] = vendortype;
data['territory_type'] = territorytype;
data['seed_license_no'] = seedlicenseno;
data['status'] = status;
data['created_by'] = createdby;
data['created_on'] = createdon;
data['updated_on'] = updatedon;
return data;
}
}
|
from django.contrib.auth.models import User
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=65)
def __str__(
self,
): # altera o nome Category object para o nome correto da categoria que foi criada
return self.name
class Recipe(models.Model):
title = models.CharField(max_length=65)
description = models.CharField(max_length=165)
slug = models.SlugField()
preparation_time = models.IntegerField()
preparation_time_unit = models.CharField(max_length=65)
servings = models.IntegerField()
servings_unit = models.CharField(max_length=65)
preparation_steps = models.TextField()
preparation_steps_is_html = models.BooleanField(default=False)
created_at = models.DateTimeField(
auto_now_add=True
) # Esse auto_now_add gera uma data no momento da criação
updated_at = models.DateField(
auto_now=True
) # também é de data, mas só é chamado quando o registro é chamado (update)
is_published = models.BooleanField(default=False)
cover = models.ImageField(
upload_to="recipes/covers/%Y/%m/%d", blank=True, default=""
) # esse black=True e default vazio diz que na imagem pode não ter nada
category = models.ForeignKey(
Category,
on_delete=models.SET_NULL,
null=True,
blank=True,
default=None,
) # blank=True --> permite que no formulário seja em branco, default=None
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.title
|
import { createClient } from 'qqbn';
import { config } from 'dotenv';
import { Configuration, OpenAIApi } from 'openai';
config();
const account = parseInt(process.env.ACCOUNT as string);
const client = createClient(account, {
platform: 4,
});
client.on('message', async (e) => {
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const message = e.raw_message;
try {
await openai
.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: '你是只猫娘,你的回答都要像猫娘.',
},
{ role: 'assistant', content: '请问...阁下要问我什么呢喵?' },
{ role: 'user', content: `${message}` },
],
})
.then((resp) => {
const { data } = resp;
if (data.choices[0].message) {
e.reply(data.choices[0].message?.content);
} else {
e.reply('啥都没有欸...');
}
});
} catch (error) {
e.reply(`报错了欸...${error}`);
}
});
client
.on('system.login.slider', function () {
console.log('输入ticket:');
process.stdin.once('data', (ticket) =>
this.submitSlider(String(ticket).trim()),
);
})
.login(process.env.PASSWORD);
client.on('system.login.error', (data) => {
console.log(data);
});
|
/*
* Project Name: Calculator
* Description: Calculator for One time use, Allows the user to make a selection on the screen. The user enters two integers and gets the result as a double
* Student Name: Lukas Siemers
* Date: 9/18/2023
* */
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
System.out.println("Welcome to Baoqiang Yan's simple calculator!");
System.out.println("Please enter one of the following numeric options:");
System.out.println("1 - Add");
System.out.println("2 - Sub");
System.out.println("3 - Mul");
System.out.println("4 - Div");
System.out.println("0 - Quit");
Scanner scanner = new Scanner(System.in); //Assigning the scanner to a variable
int option; // Declaring option as an variable for input
option = scanner.nextInt(); //scanner is getting assigned to the Option variable
if (option > 4){ // If the option is greater than 4 then print Message
System.out.println("Invalid Option");
}
int num1; //Declaring num 1 for multiple uses
int num2; //Declaring num 2 for multiple uses
double result; //Declaring result for calculations results
switch(option){ // Switch Statements with options as input
case 1: // Addition if user picks this number (1)
System.out.println("Enter two numbers for Addition (seperated by Space)");
num1 = scanner.nextInt(); //Selecting the first entered number
num2 = scanner.nextInt(); //Selecting the second entered number
result = (double) num1+num2; //Converting the result into double
System.out.println("The result is: " + result);
System.out.println("Thanks for using my calculator!"); //Goodbye Text
break;
case 2: // Subtration if user picks this number (2)
System.out.println("Enter two numbers for Subtraction (seperated by Space)");
num1 = scanner.nextInt(); //Selecting the first entered number
num2 = scanner.nextInt(); //Selecting the second entered number
result = (double)num1 - num2; //Converting the result into double
System.out.println("The result is: " + result);
System.out.println("Thanks for using my calculator!"); //Goodbye Text
break;
case 3: // Multiplication if user picks this number (3)
System.out.println("Enter two numbers for Multiplication (seperated by Space)");
num1 = scanner.nextInt(); //Selecting the first entered number
num2 = scanner.nextInt(); //Selecting the second entered number
result = (double)num1 * num2; //Converting the result into double
System.out.println("The result is: " + result);
System.out.println("Thanks for using my calculator!)"); //Goodbye Text
break;
case 4: // Division if user picks this number (4)
System.out.println("Enter two numbers for Division (seperated by Space)");
num1 = scanner.nextInt(); //Selecting the first entered number
num2 = scanner.nextInt(); //Selecting the second entered number
if (num2 == 0){
System.out.println("Cannot divide by zero");
System.out.println("Thanks for using my calculator!"); //Goodbye Text
break;
}else {
result = (double) num1 / num2; //Converting the result into double
System.out.println("The result is: " + result);
System.out.println("Thanks for using my calculator!"); //Goodbye Text
break;
}
case 0: // Quit if user picks this number (0)
System.out.println("Thanks for using my calculator!"); //Goodbye Text
break;
}
}
}
|
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
# Configurar a interface do Streamlit com um tema personalizado
st.set_page_config(
page_title="Score Client",
page_icon="💰",
layout="wide",
)
# Estilos CSS personalizados
CSS = """
<style>
.stApp {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.stAlert {
padding: 0.75rem 1rem;
border-radius: 0.25rem;
background-color: #f8d7da;
color: #721c24;
margin-bottom: 1rem;
}
.stSuccess {
padding: 0.75rem 1rem;
border-radius: 0.25rem;
background-color: #d4edda;
color: #155724;
margin-bottom: 1rem;
}
.stTable {
background-color: #f8f9fa;
}
.css-1aumxhk {
max-width: 200px;
}
</style>
"""
st.markdown(CSS, unsafe_allow_html=True)
def predict_client(model, df):
predictions_data = predict_model(model, df)
#print('aqui teste',predictions_data)
return predictions_data['prediction_label'][0]
model = load_model('Final_Model_xgboost')
st.title('App Web de pontuação de crédito')
st.write("Crie um aplicativo Web para classificar clientes de um banco com bom ou mau risco.")
Maturite_mois = st.sidebar.slider(label = 'Meses de vencimento', min_value = 16,
max_value = 24 ,
value = 23,
step = 1)
Montant_Pret_BAM = st.sidebar.slider(label = 'Valor do empréstimo BAM', min_value = 5000,
max_value = 15000 ,
value = 8200,
step = 25)
Sexe = st.sidebar.selectbox('Sexo',['Male','Female'])
Etat_Civil = st.sidebar.selectbox('Estado Civil',['Divorced','Married','Single','Widowed'])
Niveau_Formation = st.sidebar.selectbox(
'Nivel de formacao',
['Completed University','Some College Courses','Completed Vocational Training','High School Diploma','Secondary School to Grade 10'])
Age_ans = st.sidebar.slider(label = 'Anos de idade', min_value = 18,
max_value = 65 ,
value = 32,
step = 1)
Ans_a_ladresse = st.sidebar.slider(label = "Anos no endereco", min_value = 0.5,
max_value = 30.0 ,
value = 1.0,
step = 0.5)
Locataire_Proprietaire = st.sidebar.selectbox("Proprietario do inquilino",['RENT','Own'])
Nbre_de_Dependants = st.sidebar.slider(label = 'Numero de dependentes', min_value = 0,
max_value = 5,
value = 2,
step = 1)
Ans_en_Activite = st.sidebar.slider(label = 'Anos em atividade', min_value = 0.5,
max_value = 15.0 ,
value = 1.0,
step = 0.5)
Emplacement_du_business = st.sidebar.selectbox("Localizacao da empresa",['Region1','Region2','Region3','Region4','Region5'])
Credit_Bureau_negative = st.sidebar.slider(label = 'Credito de Escritorio Negativo=1', min_value = 0,
max_value = 1 ,
value = 0,
step = 1)
NbreEmployesFamille = st.sidebar.slider(label = 'Numero Funcionarios Familia', min_value = 0,
max_value = 7 ,
value = 1,
step = 1)
Type_dActivite = st.sidebar.selectbox(
"Tipo de atividade",
['Craftsperson','Personal Services','Car Repair','Child Care','Convenience Store','Small Grocers','General Contractor'])
Ventes_Mensuelles_BAM = st.sidebar.slider(label = 'Vendas Mensais BAM', min_value = 400,
max_value = 20000,
value = 2550,
step = 25)
features = {'Meses de vencimento': Maturite_mois,
'Valor do empréstimo BAM': Montant_Pret_BAM,
'Sexo': Sexe,
'Estado Civil': Etat_Civil,
'Nivel de formacao':Niveau_Formation,
'Anos de idade':Age_ans,
"Anos no endereco":Ans_a_ladresse,
"Proprietario do inquilino": Locataire_Proprietaire,
'Numero de dependentes': Nbre_de_Dependants,
'Anos em atividade': Ans_en_Activite,
"Localizacao da empresa": Emplacement_du_business,
'Credito de Escritorio Negativo=1': Credit_Bureau_negative,
'Numero Funcionarios Familia': NbreEmployesFamille,
"Tipo de atividade":Type_dActivite,
'Vendas Mensais BAM':Ventes_Mensuelles_BAM
}
features_df = pd.DataFrame([features])
map_dict = {0:'Bom Cliente',
1:'Ruim Cliente'}
st.table(features_df)
if st.button('Previsão'):
prediction = predict_client(model, features_df)
st.write("A previsão é de: {}".format(map_dict [prediction]))
|
import { Fragment } from "react";
import { Listbox, Transition } from "@headlessui/react";
import clsx from "clsx";
import type { FiltersForm, SelectOptions } from "../pages";
import Arrow from "../../public/svg/arrow.svg";
import X from "../../public/svg/x.svg";
const ListBox = ({
options,
children,
name,
placeholder,
onChange,
value,
initialValues,
}: {
options: { id: number; name: string }[];
children: React.ReactElement;
name: string;
placeholder: string;
onChange: React.Dispatch<React.SetStateAction<FiltersForm>>;
value: SelectOptions;
initialValues: SelectOptions;
}) => {
return (
<Listbox
value={value}
onChange={(v: SelectOptions) => onChange((p) => ({ ...p, [name]: v }))}
>
{({ open }) => (
<>
<Listbox.Button className="flex w-full cursor-pointer items-center pr-2.5">
<span>{children}</span>
<span
className={clsx(
"block truncate text-sm leading-10 text-purple-dark/60 outline-none",
value.name && "font-medium text-purple-dark/80"
)}
>
{value.name || placeholder}
</span>
<span className="ml-auto mt-0.5 flex items-center">
<div
className="cursor-pointer pr-1.5"
onClick={(e: React.FormEvent<HTMLDivElement>) => {
e.stopPropagation();
onChange((prevValues) => ({
...prevValues,
[name]: initialValues,
}));
}}
>
<X className="h-5 w-5 fill-purple-dark/60" />
</div>
<div className="h-4 w-[1px] bg-purple-dark/30" />
<div className="cursor-pointer pl-1.5">
<Arrow
aria-hidden="true"
className={clsx(
"h-6 w-6 fill-purple-dark/60 transition-transform",
open && "rotate-180"
)}
/>
</div>
</span>
</Listbox.Button>
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Listbox.Options className="absolute left-0 z-10 mt-[16px] w-full rounded-b-20 border border-grey/20 bg-white py-2.5 text-sm shadow-lg lg:mt-2.5">
{options.map((item) => (
<Listbox.Option
key={item.id}
className="relative cursor-pointer select-none py-2.5 px-[30px] text-purple-dark/60 hover:bg-purple-light/20"
value={item}
>
{({ selected }) => (
<span
className={clsx(
"block truncate",
selected && "font-medium text-purple-dark/80"
)}
>
{item.name}
</span>
)}
</Listbox.Option>
))}
</Listbox.Options>
</Transition>
</>
)}
</Listbox>
);
};
export default ListBox;
|
package Frame;
import Extra.*;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class ForgotPassFrame extends JFrame implements MouseListener, KeyListener {
private final JButton backButton;
private final JRadioButton librarianButton;
private final JRadioButton studentButton;
private LoginFrame loginFrame;
private final JButton resetButton;
private final JTextField nameField;
private final JTextField emailField;
public ForgotPassFrame() {
super("Reset Password");
Image iconImage = Toolkit.getDefaultToolkit().getImage("images/library.png");
this.setIconImage(iconImage);
this.setSize(1260, 700);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setLayout(new BorderLayout());
// Start of Left Panel
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
leftPanel.setPreferredSize(new Dimension(660, 700));
leftPanel.setBackground(Color.WHITE);
JPanel naviPanel = new JPanel();
naviPanel.setLayout(new BorderLayout());
naviPanel.setPreferredSize(new Dimension(60, 60));
naviPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 0));
naviPanel.setBackground(Color.WHITE);
ImageIcon backIcon = new ImageIcon("images/arrow_back.png");
backButton = new JButton(backIcon);
backButton.setBackground(Color.WHITE);
backButton.setFocusable(false);
backButton.setBorderPainted(false);
backButton.setToolTipText("Go Back");
backButton.addMouseListener(this);
naviPanel.add(backButton, BorderLayout.WEST);
leftPanel.add(naviPanel, BorderLayout.NORTH);
ImageIcon image = new ImageIcon("images/forgot-pass.jpg");
JLabel imageLabel = new JLabel(image);
imageLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 70, 0));
leftPanel.add(imageLabel, BorderLayout.CENTER);
// End of Left Panel
// Start of Right Panel
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new FlowLayout());
rightPanel.setPreferredSize(new Dimension(600, 700));
rightPanel.setBackground(Utils.BACKGROUND_COLOR);
JPanel introPanel = new JPanel();
introPanel.setPreferredSize(new Dimension(600, 130));
introPanel.setBorder(BorderFactory.createEmptyBorder(60, 0, 20, 0));
introPanel.setBackground(Utils.BACKGROUND_COLOR);
JLabel introLabel = new JLabel("Forgot Password?");
introLabel.setFont(Utils.INTRO_FONT);
introPanel.add(introLabel);
rightPanel.add(introPanel);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new BorderLayout());
radioPanel.setPreferredSize(new Dimension(200, 50));
radioPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
radioPanel.setBackground(Utils.BACKGROUND_COLOR);
ImageIcon checkedIcon = new ImageIcon("images/radio_checked.png");
ImageIcon unCheckedIcon = new ImageIcon("images/radio_unchecked.png");
librarianButton = new JRadioButton("Librarian", unCheckedIcon);
librarianButton.setSelectedIcon(checkedIcon);
librarianButton.setFont(Utils.SMALL_BOLD_FONT);
librarianButton.setBackground(Utils.BACKGROUND_COLOR);
librarianButton.setFocusable(false);
librarianButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
studentButton = new JRadioButton("Student", unCheckedIcon);
studentButton.setSelectedIcon(checkedIcon);
studentButton.setFont(Utils.SMALL_BOLD_FONT);
studentButton.setBackground(Utils.BACKGROUND_COLOR);
studentButton.setFocusable(false);
studentButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
ButtonGroup loginGroup = new ButtonGroup();
loginGroup.add(librarianButton);
loginGroup.add(studentButton);
radioPanel.add(librarianButton, BorderLayout.WEST);
radioPanel.add(studentButton, BorderLayout.EAST);
rightPanel.add(radioPanel);
JLabel nameLabel = new JLabel("Name");
nameLabel.setFont(Utils.NORMAL_FONT);
nameLabel.setPreferredSize(new Dimension(400, 30));
rightPanel.add(nameLabel);
CompoundBorder textFieldBorder = BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Utils.LIGHT_BLUE),
BorderFactory.createEmptyBorder(0, 5, 0, 5)
);
nameField = new JTextField();
nameField.setFont(Utils.BIG_FONT);
nameField.setPreferredSize(new Dimension(400, 60));
nameField.setBorder(textFieldBorder);
nameField.addKeyListener(this);
rightPanel.add(nameField);
JLabel emailLabel = new JLabel("Email");
emailLabel.setFont(Utils.NORMAL_FONT);
emailLabel.setPreferredSize(new Dimension(400, 40));
emailLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
rightPanel.add(emailLabel);
emailField = new JTextField();
emailField.setFont(Utils.BIG_FONT);
emailField.setPreferredSize(new Dimension(400, 60));
emailField.setBorder(textFieldBorder);
emailField.addKeyListener(this);
rightPanel.add(emailField);
JPanel buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(400, 150));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(30, 0, 0, 0));
buttonPanel.setBackground(Utils.BACKGROUND_COLOR);
resetButton = new JButton("Reset Password");
resetButton.setFont(Utils.BIG_BOLD_FONT);
resetButton.setPreferredSize(new Dimension(400, 60));
resetButton.setFocusPainted(false);
resetButton.addMouseListener(this);
resetButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonPanel.add(resetButton);
rightPanel.add(buttonPanel);
// End of Right Panel
this.add(leftPanel, BorderLayout.WEST);
this.add(rightPanel, BorderLayout.EAST);
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == backButton) {
backAction();
} else if (e.getSource() == resetButton) {
resetAction();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
if (e.getSource() == backButton) {
backButton.setBackground(Color.LIGHT_GRAY);
}
}
@Override
public void mouseExited(MouseEvent e) {
if (e.getSource() == backButton) {
backButton.setBackground(Color.WHITE);
}
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
resetButton.doClick();
resetAction();
} else if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
backButton.doClick();
backAction();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
public void backAction() {
if (loginFrame == null) {
loginFrame = new LoginFrame();
}
this.setVisible(false);
loginFrame.setVisible(true);
}
public void resetAction() {
String name = nameField.getText();
String email = emailField.getText();
if (!librarianButton.isSelected() && !studentButton.isSelected()) {
JOptionPane.showMessageDialog(
this,
"Please select your account type",
"Error",
JOptionPane.ERROR_MESSAGE
);
} else if (name.isEmpty()) {
JOptionPane.showMessageDialog(
this,
"Please enter your name",
"Error",
JOptionPane.ERROR_MESSAGE
);
} else if (email.isEmpty()) {
JOptionPane.showMessageDialog(
this,
"Please enter your email",
"Error",
JOptionPane.ERROR_MESSAGE
);
} else {
JOptionPane.showMessageDialog(
this,
"Password reset link has been sent to your email",
"Success",
JOptionPane.INFORMATION_MESSAGE
);
}
}
}
|
package avltree;
public class AVLTree {
private TreeNode root;
public AVLTree(){
}
/**
* Faz a rotação pela esquerda na árvore.
* @param t Nó base da rotação.
*/
private void leftRotation(TreeNode t){
TreeNode temp = t.right;
t.right = t.right.left;
temp.left = t;
t = temp;
t.left.updateHeight();
t.updateHeight();
}
/**
* Faz a rotação pela direita na árvore.
* @param t Nó base da rotação.
*/
private void rightRotation(TreeNode t){
TreeNode temp = t.left;
t.left = t.left.right;
temp.right = t;
t = temp;
t.right.updateHeight();
t.updateHeight();
}
/**
* Faz a dupla rotação pela esquerda na árvore.
* @param t Nó base da rotação.
*/
private void doubleLeftRotation(TreeNode t){
this.rightRotation(t.right);
this.leftRotation(t);
}
/**
* Faz a dupla rotação pela direita na árvore.
* @param t Nó base da rotação.
*/
private void doubleRightRotation(TreeNode t){
this.leftRotation(t.right);
this.rightRotation(t);
}
/**
* Inserir na árvore.
* @param newNode Nó a ser inserido.
*/
public void insert(TreeNode newNode){
insert(newNode,this.root);
}
/**
* Inserir na árvore passada como parâmetro.
* @param newNode Nó a ser inserido.
* @param node Nó base da inserção.
*/
public void insert(TreeNode newNode,TreeNode node){
if(this.root == null){
this.root = newNode;
this.root.updateHeight();
}else if(node == null){
node = newNode;
node.updateHeight();
}else{
if(newNode.getEntry().keyLowerThan(node.getEntry().getKey())){
insert(newNode,node.left);
int leftHeight = 0, rightHeight = 0;
if(node.left != null) leftHeight = node.left.getHeight();
if(node.right != null) rightHeight = node.right.getHeight();
if((leftHeight - rightHeight) == 2){
if(newNode.getEntry().keyLowerThan(node.left.getEntry().getKey())) rightRotation(node);
else doubleRightRotation(node);
}
}else{
insert(newNode,node.right);
int leftHeight = 0, rightHeight = 0;
if(node.left != null) leftHeight = node.left.getHeight();
if(node.right != null) rightHeight = node.right.getHeight();
if((leftHeight - rightHeight) == 2){
if(newNode.getEntry().keyGreaterThan(node.right.getEntry().getKey())) leftRotation(node);
else doubleLeftRotation(node);
}
}
node.updateHeight();
}
}
public void remove(Comparable key){
TreeNode node = get(key,this.root);
if(node == null) throw new IllegalArgumentException("Chave não encontrada");
System.out.println("Não implementado.");
}
/**
* Transposição da árvore (pré-ordem).
*/
public void transpor(){
transpor(this.root);
}
/**
* Transposição da árvore.
* @param node Nó base da transposição (pré-ordem).
*/
public void transpor(TreeNode node){
if(node == null) return;
System.out.println(node.getKey());
transpor(node.left);
transpor(node.right);
}
/**
* Buscar um nó por sua chave.
* @param key Chave do nó a ser buscado.
* @return Nó buscado, ou, caso o mesmo não tenha sido encontrado, null.
*/
public TreeNode get(Comparable key){
return get(key,this.root);
}
/**
* Buscar um nó por sua chave.
* @param key Chave do nó a ser buscado.
* @param node Nó base da busca.
* @return Nó buscado, ou, caso o mesmo não tenha sido encontrado, null.
*/
public TreeNode get(Comparable key, TreeNode node){
if(node == null) return null;
if(node.getEntry().keyEqual(key)) return node;
else{
if(node.getEntry().keyLowerThan(key)) return get(key,node.left);
else return get(key,node.right);
}
}
}
|
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:excel/excel.dart';
import 'package:linkchecker/table_screen.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart'; // Make sure to import
class BulkUploadScreen extends StatefulWidget {
@override
_BulkUploadScreenState createState() => _BulkUploadScreenState();
}
class _BulkUploadScreenState extends State<BulkUploadScreen> {
List<Map<String, dynamic>> _excelData = [];
int _maxLinks = 0;
Future<void> _pickAndProcessExcelFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path!);
var bytes = file.readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
_processExcelData(excel);
}
}
int max(int a, int b) {
var maxFound = a;
if (a < b) {
maxFound = b;
}
return maxFound;
}
bool isDigit(int rune) => rune ^ 0x30 <= 9;
void _processExcelData(Excel excel) {
var sheet = excel.tables[excel.tables.keys.first];
if (sheet == null) return;
List<String?> headers = sheet.rows[0]
.map((cell) => cell?.value.toString())
.toList(); // Extracting headers as strings
Map<String, String> abbreviationToMoneySite = {};
var rows = sheet.rows;
print(rows.isNotEmpty);
if (rows.isNotEmpty) {
// Assume the first row contains headers
var headers = rows.first;
print(headers.map((cell) => cell?.value.toString()).toList());
int abbreviationsColumnIndex = headers.indexWhere((cell) =>
cell?.value.toString().trim().toLowerCase() == "abbreviation");
print(abbreviationsColumnIndex);
// If "Abbreviations" column found and there's a column before it
if (abbreviationsColumnIndex > 0) {
// Ensure there is a column before "Abbreviations"
int moneySiteColumnIndex = abbreviationsColumnIndex -
1; // Column immediately before "Abbreviations"
var moneySiteHeader = headers[moneySiteColumnIndex]?.value;
print('Money Site Header: $moneySiteHeader'); // For debugging
// The abbreviations and their corresponding money sites are assumed to be in the same row
for (int i = 1; i < rows.length; i++) {
// Start from the second row
var row = rows[i];
var moneySite = row[moneySiteColumnIndex]?.value;
var abbreviation = row[abbreviationsColumnIndex]?.value;
if (abbreviation != null && moneySite != null) {
abbreviationToMoneySite[abbreviation.toString().toLowerCase()] =
moneySite.toString();
}
}
}
}
// Continue with your logic, now having a map of abbreviations to money sites
print('Abbreviation to Money Site Map: $abbreviationToMoneySite');
List<Map<String, dynamic>> tempData = [];
int maxLinks = 0;
// Start processing from the second row, assuming the first row is headers
for (var row in sheet.rows.skip(1)) {
var pbnName = row[0]?.value;
if (pbnName == null || pbnName.toString().isEmpty)
break; // If PBN name is missing, stop processing
List<String> links = [];
for (int i = 2; i < row.length; i++) {
// Assuming link indicators start from the 3rd column
var cellValue = row[i]?.value;
print('Cellvalue $cellValue of type ${cellValue.runtimeType}');
if (cellValue is IntCellValue && cellValue == 1) {
print('Found link indicator int');
} else if (cellValue is double && cellValue == 1.0) {
print('Found link indicator double');
} else if (cellValue.toString() == "1") {
// Safely check for string "1"
print('Found link indicator string');
}
// Direct comparison without explicit casting, as Dart handles type promotion
if (cellValue is IntCellValue && cellValue.toString() == "1") {
print(
'Found link indicator'); // This confirms the cellValue is 1 and the type check is not needed
var abbreviationHeader = headers[i];
print('abbreviationHeader $abbreviationHeader'); // Should now print
if (abbreviationHeader != null) {
var moneySite =
abbreviationToMoneySite[abbreviationHeader.toLowerCase()];
if (moneySite != null) {
links.add(
moneySite); // This should correctly add the money site to links
}
}
}
}
// row[1]?.value ??
tempData.add({
'PBN Name': pbnName.toString(),
'Category': 'No Category Set',
'Links': links,
'Total Links': links.length,
});
maxLinks = max(maxLinks, links.length);
}
setState(() {
_excelData = tempData;
_maxLinks = maxLinks;
});
// Navigate to TableScreen with the processed data
if (mounted) {
// Check to ensure setState is called on a mounted widget
Navigator.of(context).push(MaterialPageRoute(
builder: (context) =>
TableScreen(excelData: _excelData, maxLinks: _maxLinks),
));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Excel Data Viewer')),
body: Center(
child: _excelData.isEmpty
? ElevatedButton(
onPressed: _pickAndProcessExcelFile,
child: Text('Select Excel File'),
)
: ListView(
children:
_excelData.map((data) => Text(data.toString())).toList(),
),
),
);
}
}
|
#include <iostream>
#include "Interval.h"
#pragma warning (disable : 4996)
struct DynamicArray
{
int* data;
int used;
int allocated;
DynamicArray()
{
std::cout << "Def Constructor" << std::endl;
initialise();
}
DynamicArray(size_t size = 0)
{
std::cout << "Size Constructor" << std::endl;
allocate(size);
}
~DynamicArray()
{
std::cout << "Dest" << std::endl;
free();
}
void initialise()
{
this->data = nullptr;
this->used = 0;
this->allocated = 0;
}
void free()
{
delete[] this->data;
this->data = nullptr;
this->used = 0;
this->allocated = 0;
}
void allocate(size_t size)
{
this->data = new int[size];
this->used = 0;
this->allocated = size;
}
int& at(size_t index)
{
return this->data[index];
}
};
struct Test
{
Test()
{
std::cout << "Object is created" << std::endl;
}
~Test()
{
std::cout << "Object is destroyed" << std::endl;
}
int a;
int b;
};
struct A
{
A()
{
std::cout << "Constructor(default) of A" << std::endl;
}
~A()
{
std::cout << "Destructor of A" << std::endl;
}
};
struct B
{
B()
{
std::cout << "Constructor(default) of B" << std::endl;
}
~B()
{
std::cout << "Destructor of B" << std::endl;
}
};
struct C
{
C()
{
std::cout << "Constructor(default) of C" << std::endl;
}
~C()
{
std::cout << "Destructor of C" << std::endl;
}
};
struct X
{
int a;
A first;
int obejectsArray;
B second;
X() : a(42)
{ //calls Constructor(default) of A, Constructor(default) of B, Constructor(default) of C" (x3)
std::cout << a << std::endl;
std::cout << "Constructor of X" << std::endl;
}
~X()
{
std::cout << "Destructor of X" << std::endl;
}
};
class Person
{
private:
int age = 0;
char* name = nullptr;
public:
Person(int age, const char* name)
{
setAge(age);
setName(name);
}
void setName(const char* name)
{
if (name == nullptr)
return;
delete[] this->name;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
void setAge(int age)
{
if (age >= 0)
{
this->age = age;
}
}
const int& getAge() const
{
return this->age;
}
const char* getName() const
{
return this->name;
}
~Person()
{
delete[] name;
name = nullptr;
}
};
void printPerson(const Person& p)
{
std::cout << p.getAge() << std::endl;
std::cout << p.getName() << std::endl;
}
int f();
int main()
{
Person p(5, "Pesho");
const int& age = p.getAge();
printPerson(p);
std::cout << age << std::endl;
std::cout<< f() << std::endl;
Interval it1(1, 5);
Interval it2(3, 7);
Interval it3 = it1.intersection(it2);
std::cout << it3.isIn(2) << std::endl;
std::cout << it3.isIn(5) << std::endl;
std::cout << it3.isIn(6) << std::endl;
return 0;
}
|
import { TargetConfiguration } from "@nrwl/devkit";
import { BuildExecutorSchema } from "../executors/build/schema";
import { LintExecutorSchema } from "../executors/lint/schema";
import { RunExecutorSchema } from "../executors/run/schema";
import { TestExecutorSchema } from "../executors/test/schema";
import { WasmPackExecutorSchema } from "../executors/wasm-pack/schema";
export function addBuildExecutor(additionalOptions?: BuildExecutorSchema): TargetConfiguration {
return {
executor: "@monodon/rust:build",
outputs: ["{options.target-dir}"],
options: {
...additionalOptions,
},
configurations: {
production: {
release: true,
},
},
};
}
export function addTestExecutor(additionalOptions?: TestExecutorSchema): TargetConfiguration {
return {
executor: "@monodon/rust:test",
outputs: ["{options.target-dir}"],
options: {
...additionalOptions,
},
configurations: {
production: {
release: true,
},
},
};
}
export function addRunExecutor(additionalOptions?: RunExecutorSchema): TargetConfiguration {
return {
executor: "@monodon/rust:run",
outputs: ["{options.target-dir}"],
options: {
...additionalOptions,
},
configurations: {
production: {
release: true,
},
},
};
}
export function addLintExecutor(additionalOptions?: LintExecutorSchema): TargetConfiguration {
return {
executor: "@monodon/rust:lint",
outputs: ["{options.target-dir}"],
options: {
...additionalOptions,
},
};
}
export function addWasmPackExecutor(
additionalOptions?: WasmPackExecutorSchema
): TargetConfiguration {
return {
executor: "@monodon/rust:wasm-pack",
outputs: ["{options.target-dir}"],
options: {
...additionalOptions,
},
configurations: {
production: {
release: true,
},
},
};
}
|
{% if section.blocks.size > 0 %}
<div class="">
{%- for block in section.blocks -%}
{% assign desktop= block.settings.image %}
{% assign mobile= block.settings.image_mobile %}
<div class="hero-banner__wrapper">
<div class="hero-banner__backgroundimage">
{%- render 'image'
, class: 'img'
, mobileSrc: mobile
, desktopSrc: desktop
-%}
</div>
<div class="hero-banner__content page-width {{ section.settings.content_position }}">
<div class="hero-banner__content-child">
{% if block.settings.heading_text != blank %}
<div class="hero-banner__heading left">
{{ block.settings.heading_text | replace: '<p', '<h3' }}
</div>
{% endif %}
<div class="hero-banner__caption">
<p class="left">
{{ block.settings.caption_text }}
</p>
</div>
<div class="hero-banner__icons left">
<div class="hero-banner__icon flex justify-between ">
<div class="flex align-center">
<img src="{{ block.settings.icon1 | image_url: width: '30x30' }}">
<p>{{ block.settings.icon_text1 }}</p>
</div>
<div class="flex align-center">
<img src="{{ block.settings.icon2 | image_url: width: '30x30' }}">
<p>{{ block.settings.icon_text2 }}</p>
</div>
</div>
<div class="hero-banner__icon flex justify-between">
<div class="flex align-center">
<img src="{{ block.settings.icon3 | image_url: width: '30x30' }}">
<p>{{ block.settings.icon_text3 }}</p>
</div>
<div class="flex align-center">
<img src="{{ block.settings.icon4 | image_url: width: '30x30' }}">
<p>{{ block.settings.icon_text4 }}</p>
</div>
</div>
</div>
<div class="left">
<button class="button button--primary">{{ block.settings.Button_text }}
</button>
</div>
</div>
</div>
{% endfor %}
</div>
{% endif %}
{% schema %}
{
"name": "Hero banner",
"tag": "section",
"class": "section",
"settings": [
{
"type": "select",
"id": "content_position",
"label": "Content Position",
"options": [
{
"value": "justify-start align-start",
"label": "Top left"
},
{
"value": "justify-center align-start",
"label": "Top center"
},
{
"value": "justify-end align-start",
"label": "Top right"
},
{
"value": "justify-start align-center",
"label": "Middle left"
}, {
"value": "justify-center align-center",
"label": "Middle center"
}, {
"value": "justify-end align-center",
"label": "Middle right"
}, {
"value": "justify-start align-end",
"label": "Bottom left"
}, {
"value": "justify-center align-end",
"label": "Bottom center"
}, {
"value": "justify-end align-end",
"label": "Bottom right"
}
],
"default": "justify-end align-center"
}
],
"blocks": [
{
"type": "carousel-blocks",
"name": "Hero Content",
"settings": [
{
"type": "image_picker",
"id": "image",
"label": "Image (Desktop)"
},
{
"type": "image_picker",
"id": "image_mobile",
"label": "Image (Mobile)"
},
{
"type": "header",
"content": "Text Settings"
},
{
"type": "richtext",
"id": "heading_text",
"label": "Heading Text",
"default": "<p></p>"
}, {
"type": "text",
"id": "caption_text",
"label": " Caption Text",
"default": "text goes here"
}, {
"type": "header",
"content": "Icon Settings"
}, {
"type": "text",
"id": "icon_text1",
"label": "Text",
"default": "text goes here"
}, {
"type": "image_picker",
"id": "icon1",
"label": "Icon Image"
}, {
"type": "text",
"id": "icon_text2",
"label": "Text",
"default": "text goes here"
}, {
"type": "image_picker",
"id": "icon2",
"label": "Icon Image"
}, {
"type": "text",
"id": "icon_text3",
"label": "Text",
"default": "text goes here"
}, {
"type": "image_picker",
"id": "icon3",
"label": "Icon Image"
}, {
"type": "text",
"id": "icon_text4",
"label": "Text",
"default": "Heading text goes here"
}, {
"type": "image_picker",
"id": "icon4",
"label": "Icon Image"
}, {
"type": "header",
"content": "Button Settings"
}, {
"type": "text",
"id": "Button_text",
"label": "Button Text",
"default": "Button text goes here"
}, {
"type": "url",
"id": "button_link",
"label": "Button link"
}
]
}
],
"presets": [
{
"name": "Hero banner"
}
],
"max_blocks": 1
}
{% endschema %}
|
/*
nourilee [at] launchpadrecruits.com
Admin Accounts Page Object...
Note: for shared pages sections, like a search field or nav bar,
you could make modules or page elements and extend them to pages
that share them...
*/
_include("BasePage.sah");
function AdminAccountsPage() {
// properties: all accessors and data should be abstracted from tests...
this.$url = $BASEURL+"/accounts";
this.$tabAccounts = _link("Accounts");
this.$textboxUserName = _textbox("user_name");
this.$textboxCompanyName = _textbox("company_name");
this.$searchButton = _submit("Search");
// navigate to Accounts tab
this.goToAccounts = function() {
_click(this.$tabAccounts);
}
// set value to User name textbox
this.setUserName = function($userName) {
_setValue(this.$textboxUserName, $userName);
}
// set value to Company name textbox
this.setCompanyName = function($companyName) {
_setValue(this.$textboxCompanyName, $companyName);
}
// click Search button
this.clickSearch = function() {
_click(this.$searchButton);
}
// Check if search text is visible from the search results
this.isTextVisibleOnSearchResults = function($searchText) {
_assertVisible(_cell($searchText));
}
// Click On Account
this.clickAccount = function($account) {
if (this.isTextVisibleOnSearchResults($account)){
_click(_cell($account));
}
}
// handle logout from admin/accounts
this.logout = function() {
_click(this.$logoutButton);
}
}
// extend...
AdminAccountsPage.prototype = new BasePage();
// instatiate...
adminAccountsPage = new AdminAccountsPage();
|
/**
* URL [https://leetcode.cn/problems/dui-cheng-de-er-cha-shu-lcof/]
*/
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function isSymmetric(root: TreeNode | null): boolean {
if (!root) {
return true
}
let list: (number | string)[] = []
let list2: (number | string)[] = [];
pre(root, list)
preRight(root, list2)
// console.log(list)
// console.log(list2)
return list.join('') === list2.join('')
};
const pre = (root: TreeNode | null, list: (number | string)[]) => {
if (!root) {
list.push('null')
return
}
list.push(root.val)
pre(root.left, list)
pre(root.right, list)
}
const preRight = (root: TreeNode | null, list: (number | string)[]) => {
if (!root) {
list.push('null')
return
}
list.push(root.val)
preRight(root.right, list)
preRight(root.left, list)
}
|
#[derive(Debug)]
#[allow(dead_code)]
struct Guess {
value: i32,
}
#[allow(dead_code)]
impl Guess {
fn new(value: i32) -> Result<Self, String> {
if value < 1 {
return Err("Invalid Value".to_owned());
};
Ok(Self { value })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn guess() -> Result<(), String> {
let g = Guess::new(1).unwrap();
if g.value == 1 {
println!("DOne");
Ok(())
} else {
Err(String::from("Invalid Value"))
}
}
#[test]
#[ignore]
fn guess_another() -> Result<(), String> {
let g = Guess::new(1).unwrap();
if g.value == 1 {
println!("DOne");
Ok(())
} else {
Err(String::from("Invalid Value"))
}
}
}
// CHEAT_SHEET
// #[cfg(test)] annotation on the tests module tells Rust to compile and run the test code only when you run cargo test, not when you run cargo build.
// #[test] -> makes the function as test and runs when `cargo test`
// cargo test -- --show-output -> to print irrespective the test passes or fails
// #[should_panic(expected = "your_reason")] -> panics with your reason
// assert_eq!(left, right, "reason") -> checks equality
// assert_ne!(left, right. "reason") -> checks inequality
// assert!(value) -> checks trueness
// cargo test -- --test-threads=1 -> runs tests on one thread, in case of the inter-dependencies
// #[ignore] -> to ignore the test
// cargo test <test_name> -> will run the test if name matches
// cargo test -- --include-ignored -> include ignored tests
// cargo test --help -> help regarding the command
// cargo test -- --help -> help regarding what can be passed after "--" (--ignored -> to run the ignored tests)
|
import { isAxiosError } from 'axios';
import { useCallback } from 'react';
import { useForm, UseFormRegister, UseFormHandleSubmit } from 'react-hook-form';
import toast from 'react-hot-toast';
import { useSWRConfig } from 'swr';
import { useCategory } from 'app/_hooks/useCategory';
import { clientAxiosInstance } from 'app/_utils/clientAxiosInstance';
import { useLogin } from './useLogin';
export interface FormValues {
title: string;
category: string;
description: string;
date: string;
markDiv: string;
}
interface UseNew {
watchDate: string;
register: UseFormRegister<FormValues>;
handleSubmit: UseFormHandleSubmit<FormValues>;
postMemo: (data: FormValues) => Promise<void>;
}
export const useNew = (): UseNew => {
const { mutate } = useSWRConfig();
const { handle401 } = useLogin();
const { addPickCategories } = useCategory();
const { register, handleSubmit, watch, reset } = useForm<FormValues>({
defaultValues: {
title: '',
category: '',
description: '',
date: '',
markDiv: '0',
},
});
const watchDate = watch('date', '');
const postMemo = useCallback(
async (data: FormValues): Promise<void> => {
const { title, category, description, date, markDiv } = data;
try {
const res = await clientAxiosInstance.post('/api/memo', {
title,
category,
description,
date,
markDiv: parseInt(markDiv, 10),
});
if (res.status === 200) {
await mutate('/api/memos');
addPickCategories(category);
reset();
toast.success('新しいメモを作成しました');
}
} catch (error) {
if (!isAxiosError(error)) {
console.log({ error });
toast.error('エラーが発生しました');
} else {
if (error.response !== undefined) {
const { status, data } = error.response as { status: number; data: string };
switch (status) {
case 401:
handle401();
break;
case 400:
toast.error(data);
break;
default:
toast.error('エラーが発生しました');
break;
}
}
}
}
},
[reset, handle401, mutate, addPickCategories]
);
return { watchDate, register, handleSubmit, postMemo };
};
|
using System.Collections;
using UnityEngine;
public class CoinsCount : MonoBehaviour
{
// This script is used for tracking how many heart coins are collected in order to regain 1 bar of health in game.
public static CoinsCount instance;
public static int coinsCount = 0;
private GameObject child0_GameObject;
private GameObject child1_GameObject;
private GameObject child2_GameObject;
private Animation child0_Animation;
private Animation child1_Animation;
private Animation child2_Animation;
void Awake()
{
coinsCount = 0;
child0_GameObject = transform.GetChild(0).gameObject;
child1_GameObject = transform.GetChild(1).gameObject;
child2_GameObject = transform.GetChild(2).gameObject;
child0_Animation = transform.GetChild(0).gameObject.GetComponent<Animation>();
child1_Animation = transform.GetChild(1).gameObject.GetComponent<Animation>();
child2_Animation = transform.GetChild(2).gameObject.GetComponent<Animation>();
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
}
public void CheckCoins()
{
if (Player.player_Health < 3)
{
if (coinsCount == 1)
{
child0_GameObject.SetActive(true);
child0_Animation.Play("Health Coin (Add)");
}
else if (coinsCount == 2)
{
child1_GameObject.SetActive(true);
child1_Animation.Play("Health Coin (Add)");
}
else if (coinsCount == 3)
{
child2_GameObject.SetActive(true);
child2_Animation.Play("Health Coin (Add)");
if (Player.player_Health == 2) // Will check that the player has 2 health and animate the last health bar.
{
Game_Manager.instance.healthBar1Animation.Play("Health Bar (Add)");
Player.player_Health++;
}
else if (Player.player_Health == 1) // Will check that the player has 1 health and animate the middle health bar only.
{
Game_Manager.instance.healthBar2Animation.Play("Health Bar (Add)");
Player.player_Health++;
}
StartCoroutine(CoinsCountReset());
}
}
if (coinsCount > 3)
{
coinsCount = 0;
}
}
public IEnumerator ResetCoins() // Used in the Player script when game over is triggered to reset the amount of heart coins collected.
{
coinsCount = 0;
foreach (Transform child in transform)
{
if (child.gameObject.activeInHierarchy == true)
{
child.GetComponent<Animation>().Play("Health Coin (Lose)");
}
}
yield return new WaitForSeconds(0.4f);
foreach (Transform child in transform)
{
if (child.gameObject.activeInHierarchy == true)
{
child.gameObject.SetActive(false);
}
}
}
public IEnumerator CoinsCountReset() // Reset the coins count once 3 heart coins are collected. A delay is used for asthetic purposes to view animation when the health coin disappears.
{
yield return new WaitForSeconds(0.4f);
coinsCount = 0;
foreach (Transform child in transform)
{
child.GetComponent<Animation>().Play("Health Coin (Lose)");
}
yield return new WaitForSeconds(0.4f);
foreach (Transform child in transform)
{
child.gameObject.SetActive(false);
}
}
}
|
library ieee;
use ieee.std_logic_1164.all;
entity upcounter is
port ( t, clk, rst : in std_logic;
q : out std_logic);
end upcounter;
architecture upcounter_arch of upcounter is
signal q_temp : std_logic;
begin
process (clk, rst)
begin
if rst = '1' then
q_temp <= '0';
elsif rising_edge(clk) then
if t = '1' then
q_temp <= not q_temp;
else
q_temp <= q_temp;
end if;
end if;
end process;
q <= q_temp;
end upcounter_arch;
library ieee;
use ieee.std_logic_1164.all;
entity and_g is
port ( a, b : in std_logic;
z : out std_logic);
end and_g;
architecture and_g_arch of and_g is
begin
z <= a and b;
end and_g_arch;
library ieee;
use ieee.std_logic_1164.all;
entity up_counter is
port ( clk, rst : in std_logic;
q : out std_logic_vector(2 downto 0));
end up_counter;
architecture up_counter_arch of up_counter is
component and_g is
port (a, b : in std_logic;
z : out std_logic);
end component and_g;
component upcounter is
port (t, clk, rst : in std_logic;
q : out std_logic);
end component upcounter;
signal qa, qb, qc, tc: std_logic;
begin
t1: upcounter port map(t => '1', clk => clk, rst => rst, q => qa);
t2: upcounter port map(t => qa, clk => clk, rst => rst, q => qb);
a1: and_g port map(a => qa, b => qb, z => tc);
t3: upcounter port map(t => tc, clk => clk, rst => rst, q => q(2));
q(0) <= '1' when qa = '1' else '0';
q(1) <= '1' when qb = '1' else '0';
end up_counter_arch;
|
/*
* #%L
* de-metas-camel-externalsystems-core
* %%
* Copyright (C) 2021 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package de.metas.camel.externalsystems.core.to_mf.v2;
import com.google.common.annotations.VisibleForTesting;
import de.metas.camel.externalsystems.common.ExternalSystemCamelConstants;
import de.metas.camel.externalsystems.common.v2.BPRetrieveCamelRequest;
import de.metas.camel.externalsystems.common.v2.BPUpsertCamelRequest;
import de.metas.camel.externalsystems.core.CamelRouteHelper;
import de.metas.common.bpartner.v2.request.JsonRequestBPartnerUpsert;
import org.apache.camel.Exchange;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.endpoint.dsl.HttpEndpointBuilderFactory;
import org.springframework.stereotype.Component;
import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.HEADER_BPARTNER_IDENTIFIER;
import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.HEADER_ORG_CODE;
import static de.metas.camel.externalsystems.core.to_mf.v2.UnpackV2ResponseRouteBuilder.UNPACK_V2_API_RESPONSE;
import static de.metas.common.externalsystem.ExternalSystemConstants.HEADER_EXTERNALSYSTEM_CONFIG_ID;
import static de.metas.common.externalsystem.ExternalSystemConstants.HEADER_PINSTANCE_ID;
import static org.apache.camel.builder.endpoint.StaticEndpointBuilders.direct;
@Component
public class BPartnerRouteBuilderV2 extends RouteBuilder
{
@VisibleForTesting
static final String ROUTE_ID = "To-MF_Upsert-BPartner_V2";
@VisibleForTesting
static final String RETRIEVE_BPARTNER_ROUTE_ID = "To-MF_retrieveBPartner_V2";
@VisibleForTesting
static final String RETRIEVE_BPARTNER_PROCESSOR_ID = "RetrieveBPartnerProcessorId";
@VisibleForTesting
static final String RETRIEVE_BPARTNER_ENDPOINT_ID = "RetrieveBPartnerEndpointId";
@Override
public void configure()
{
errorHandler(noErrorHandler());
from("{{" + ExternalSystemCamelConstants.MF_UPSERT_BPARTNER_V2_CAMEL_URI + "}}")
.routeId(ROUTE_ID)
.streamCaching()
.process(exchange -> {
final var lookupRequest = exchange.getIn().getBody();
if (!(lookupRequest instanceof BPUpsertCamelRequest))
{
throw new RuntimeCamelException("The route " + ROUTE_ID + " requires the body to be instanceof BPUpsertCamelRequest V2."
+ " However, it is " + (lookupRequest == null ? "null" : lookupRequest.getClass().getName()));
}
exchange.getIn().setHeader(HEADER_ORG_CODE, ((BPUpsertCamelRequest)lookupRequest).getOrgCode());
final var jsonRequestBPartnerUpsert = ((BPUpsertCamelRequest)lookupRequest).getJsonRequestBPartnerUpsert();
log.info("BPartner upsert route invoked with " + jsonRequestBPartnerUpsert.getRequestItems().size() + " requestItems");
exchange.getIn().setBody(jsonRequestBPartnerUpsert);
})
.marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonRequestBPartnerUpsert.class))
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpEndpointBuilderFactory.HttpMethods.PUT))
.toD("{{metasfresh.upsert-bpartner-v2.api.uri}}/${header." + HEADER_ORG_CODE + "}")
.to(direct(UNPACK_V2_API_RESPONSE));
from("{{" + ExternalSystemCamelConstants.MF_RETRIEVE_BPARTNER_V2_CAMEL_URI + "}}")
.routeId(RETRIEVE_BPARTNER_ROUTE_ID)
.streamCaching()
.process(exchange -> {
final var lookupRequest = exchange.getIn().getBody();
if (!(lookupRequest instanceof BPRetrieveCamelRequest))
{
throw new RuntimeCamelException("The route " + RETRIEVE_BPARTNER_ROUTE_ID + " requires the body to be instanceof BPRetrieveCamelRequest."
+ " However, it is " + (lookupRequest == null ? "null" : lookupRequest.getClass().getName()));
}
final BPRetrieveCamelRequest retrieveCamelRequest = ((BPRetrieveCamelRequest)lookupRequest);
exchange.getIn().setHeader(HEADER_BPARTNER_IDENTIFIER, retrieveCamelRequest.getBPartnerIdentifier());
exchange.getIn().setHeader(HEADER_EXTERNALSYSTEM_CONFIG_ID, retrieveCamelRequest.getExternalSystemConfigId().getValue());
if (retrieveCamelRequest.getAdPInstanceId() != null)
{
exchange.getIn().setHeader(HEADER_PINSTANCE_ID, retrieveCamelRequest.getAdPInstanceId().getValue());
}
}).id(RETRIEVE_BPARTNER_PROCESSOR_ID)
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpEndpointBuilderFactory.HttpMethods.GET))
.toD("{{metasfresh.retrieve-bpartner-v2.api.uri}}/${header." + HEADER_BPARTNER_IDENTIFIER + "}").id(RETRIEVE_BPARTNER_ENDPOINT_ID)
.to(direct(UNPACK_V2_API_RESPONSE));
}
}
|
# Cargar las bibliotecas necesarias
library(openxlsx)
library(dplyr)
library(ggplot2)
library(flexmix)
library(Metrics)
# Establecer el directorio de trabajo
setwd("C:\\Users\\sampi\\OneDrive\\Documentos\\UAO\\semestre_5\\Estadistica_2\\Stadistic\\miniproyecto_1")
colores <- c("#A2C579", "#D2DE32", "#FFFFDD", "#016A70")
# Leer los datos desde el archivo "Datos_MP1.xlsx" en la hoja "Datos_1"
datos_1 <- read.xlsx("Datos_MP1.xlsx", sheet = "Datos_1")
set.seed(1)
# Calcular la proporción de presente
datos_1$Proporcion.Presente <- datos_1$Frec.Presente / (datos_1$Frec.Presente + datos_1$Frec.Ausente)
# Crear el gráfico de dispersión inicial
ggplot(datos_1, aes(x = Alcohol, y = Proporcion.Presente)) +
geom_point(color = colores[4]) +
labs(
title = "Proporción de Malformaciones por Consumo de Alcohol",
x = "Alcohol",
y = "Proporción de Presente"
)
# Ajustar un modelo de regresión logística binomial (Modelo Logit)
modelo_logit <- glm(cbind(Frec.Presente, Frec.Ausente) ~ Alcohol, family = binomial(link = logit), data = datos_1)
summary(modelo_logit)
datos_1$Proporcion.Presente_Logistico <- fitted.values(modelo_logit)
predicciones_logit <- datos_1$Frec.Presente + datos_1$Frec.Ausente * datos_1$Proporcion.Presente_Logistico
rmse(datos_1$Proporcion.Presente, datos_1$Proporcion.Presente_Logistico)
BIC(modelo_logit)
#dispersiontest(modelo_logit)
#mod_logistico_3 <- glm(Proporcion.Presente ~ Alcohol, family = binomial(link = logit), data = datos_1, weights = Frec.Presente + Frec.Ausente)
#summary(mod_logistico_3)
# Ajustar un modelo de regresión logística binomial (Modelo Probit)
modelo_probit <- glm(cbind(Frec.Presente, Frec.Ausente) ~ Alcohol, family = binomial(link = "probit"), data = datos_1)
datos_1$Proporcion.Presente_Probit <- fitted.values(modelo_probit)
predicciones_probit <- datos_1$Frec.Presente + datos_1$Frec.Ausente * datos_1$Proporcion.Presente_Probit
rmse(datos_1$Proporcion.Presente, datos_1$Proporcion.Presente_Probit)
BIC(modelo_probit)
# Ajustar un modelo de regresión lineal
modelo_lineal <- lm(Proporcion.Presente ~ Alcohol, data = datos_1)
datos_1$Proporcion.Presente_Lineal <- fitted.values(modelo_lineal)
predicciones_lineal <- datos_1$Frec.Presente + datos_1$Frec.Ausente * datos_1$Proporcion.Presente_Lineal
rmse(datos_1$Proporcion.Presente, datos_1$Proporcion.Presente_Lineal)
BIC(modelo_lineal)
# Crear un gráfico de comparación de los tres modelos
ggplot(datos_1, aes(x = Alcohol)) +
geom_line(aes(y = Proporcion.Presente_Logistico, color = "Logistico"), linetype = "F1", lwd = 1) +
geom_line(aes(y = Proporcion.Presente_Probit, color = "Probit"), linetype = "dashed", lwd = 1) +
geom_line(aes(y = Proporcion.Presente_Lineal, color = "Lineal"), linetype = "longdash", lwd = 1) +
geom_point(aes(y = Proporcion.Presente)) +
labs(
title = "Comparación de Modelos",
x = "Alcohol",
y = "Proporción de Presente"
) +
scale_color_manual(
values = c("Logistico" = colores[4], "Probit" = colores[2], "Lineal" = colores[1]),
labels = c("Logístico", "Probit", "Lineal")
) +
guides(
color = guide_legend(title = "Modelo")
)
datos_2 <- read.xlsx("Datos_MP1.xlsx", sheet = "Datos_2")
muestra <- datos_2 %>% sample_n(size = 40, replace = FALSE)
muestra %>%
summarise(Promedio = mean(puntaje_mat, na.rm = TRUE),
DE = sd(puntaje_mat, na.rm = TRUE),
Mediana = median(puntaje_mat, na.rm = TRUE),
CV = DE / Promedio * 100,
Minimo = min(puntaje_mat, na.rm = TRUE),
Maximo = max(puntaje_mat, na.rm = TRUE))
muestra %>%
summarise(Promedio = mean(num_premios, na.rm = TRUE),
DE = sd(num_premios, na.rm = TRUE),
Mediana = median(num_premios, na.rm = TRUE),
CV = DE / Promedio * 100,
Minimo = min(num_premios, na.rm = TRUE),
Maximo = max(num_premios, na.rm = TRUE))
table(muestra$programa)
ggplot(muestra, aes(x = factor(programa), fill = programa)) +
geom_bar(stat = "count") +
scale_fill_manual(
values = c("Academico" = colores[1], "General" = colores[2], "Vocacional" = colores[4])
) +
labs(title = "Distribución de Programas",
x = "Programa",
y = "Frecuencia")+
theme(legend.position = "none")
modelo_poisson <- glm(num_premios ~ programa + puntaje_mat ,family = poisson(link = "log"), data = datos_2)
summary(modelo_poisson)
datos_3 <- read.xlsx("Datos_MP1.xlsx", sheet = "Datos_3")
muestra3 <- datos_3 %>% sample_n(size = 11, replace = FALSE)
|
use std::collections::{BTreeSet, HashMap};
use std::fs;
use std::fs::File;
use std::ops::Bound;
use std::ops::Bound::{Included, Unbounded};
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use anyhow::{anyhow, Result};
use bytes::Bytes;
use parking_lot::{Mutex, MutexGuard, RwLock};
use crate::block::Block;
use crate::compact::{
CompactionController, CompactionOptions, LeveledCompactionController, LeveledCompactionOptions,
SimpleLeveledCompactionController, SimpleLeveledCompactionOptions, TieredCompactionController,
};
use crate::iterators::concat_iterator::SstConcatIterator;
use crate::iterators::merge_iterator::MergeIterator;
use crate::iterators::two_merge_iterator::TwoMergeIterator;
use crate::iterators::StorageIterator;
use crate::key::{KeyBytes, KeySlice, TS_RANGE_BEGIN, TS_RANGE_END};
use crate::lsm_iterator::{FusedIterator, LsmIterator};
use crate::manifest::{Manifest, ManifestRecord};
use crate::mem_table::{map_bound, MemTable};
use crate::mvcc::txn::{Transaction, TxnIterator};
use crate::mvcc::LsmMvccInner;
use crate::table::{FileObject, SsTable, SsTableBuilder, SsTableIterator};
pub type BlockCache = moka::sync::Cache<(usize, usize), Arc<Block>>;
/// Represents the state of the storage engine.
#[derive(Clone)]
pub struct LsmStorageState {
/// The current memtable.
pub memtable: Arc<MemTable>,
/// Immutable memtables, from latest to earliest.
pub imm_memtables: Vec<Arc<MemTable>>,
/// L0 SSTs, from latest to earliest.
pub l0_sstables: Vec<usize>,
/// SsTables sorted by key range; L1 - L_max for leveled compaction, or tiers for tiered
/// compaction.
pub levels: Vec<(usize, Vec<usize>)>,
/// SST objects.
pub sstables: HashMap<usize, Arc<SsTable>>,
}
pub enum WriteBatchRecord<T: AsRef<[u8]>> {
Put(T, T),
Del(T),
}
impl LsmStorageState {
fn create(options: &LsmStorageOptions) -> Self {
let levels = match &options.compaction_options {
CompactionOptions::Leveled(LeveledCompactionOptions { max_levels, .. })
| CompactionOptions::Simple(SimpleLeveledCompactionOptions { max_levels, .. }) => (1
..=*max_levels)
.map(|level| (level, Vec::new()))
.collect::<Vec<_>>(),
CompactionOptions::Tiered(_) => Vec::new(),
CompactionOptions::NoCompaction => vec![(1, Vec::new())],
};
Self {
memtable: Arc::new(MemTable::create(0)),
imm_memtables: Vec::new(),
l0_sstables: Vec::new(),
levels,
sstables: Default::default(),
}
}
}
pub fn range_overlap(
lower: Bound<KeySlice>,
upper: Bound<KeySlice>,
first_key: &KeyBytes,
last_key: &KeyBytes,
) -> bool {
match map_bound(lower) {
Bound::Included(l) => {
if l.key_ref() > last_key.key_ref() {
return false;
}
}
Bound::Excluded(l) => {
if l.key_ref() >= last_key.key_ref() {
return false;
}
}
Bound::Unbounded => {}
}
match map_bound(upper) {
Bound::Included(u) => {
if u.key_ref() < first_key.key_ref() {
return false;
}
}
Bound::Excluded(u) => {
if u.key_ref() <= first_key.key_ref() {
return false;
}
}
Bound::Unbounded => {}
}
true
}
#[derive(Debug, Clone)]
pub struct LsmStorageOptions {
// Block size in bytes
pub block_size: usize,
// SST size in bytes, also the approximate memtable capacity limit
pub target_sst_size: usize,
// Maximum number of memtables in memory, flush to L0 when exceeding this limit
pub num_memtable_limit: usize,
pub compaction_options: CompactionOptions,
pub enable_wal: bool,
pub serializable: bool,
}
impl LsmStorageOptions {
pub fn default_for_week1_test() -> Self {
Self {
block_size: 4096,
target_sst_size: 2 << 20,
compaction_options: CompactionOptions::NoCompaction,
enable_wal: false,
num_memtable_limit: 50,
serializable: false,
}
}
pub fn default_for_week1_day6_test() -> Self {
Self {
block_size: 4096,
target_sst_size: 2 << 20,
compaction_options: CompactionOptions::NoCompaction,
enable_wal: false,
num_memtable_limit: 2,
serializable: false,
}
}
pub fn default_for_week2_test(compaction_options: CompactionOptions) -> Self {
Self {
block_size: 4096,
target_sst_size: 1 << 20, // 1MB
compaction_options,
enable_wal: false,
num_memtable_limit: 2,
serializable: false,
}
}
}
#[derive(Clone, Debug)]
pub enum CompactionFilter {
Prefix(Bytes),
}
/// The storage interface of the LSM tree.
pub(crate) struct LsmStorageInner {
pub(crate) state: Arc<RwLock<Arc<LsmStorageState>>>,
pub(crate) state_lock: Mutex<()>,
path: PathBuf,
pub(crate) block_cache: Arc<BlockCache>,
next_sst_id: AtomicUsize,
pub(crate) options: Arc<LsmStorageOptions>,
pub(crate) compaction_controller: CompactionController,
pub(crate) manifest: Option<Manifest>,
pub(crate) mvcc: Option<LsmMvccInner>,
pub(crate) compaction_filters: Arc<Mutex<Vec<CompactionFilter>>>,
}
/// A thin wrapper for `LsmStorageInner` and the user interface for MiniLSM.
pub struct MiniLsm {
pub(crate) inner: Arc<LsmStorageInner>,
/// Notifies the L0 flush thread to stop working. (In week 1 day 6)
flush_notifier: crossbeam_channel::Sender<()>,
/// The handle for the flush thread. (In week 1 day 6)
flush_thread: Mutex<Option<std::thread::JoinHandle<()>>>,
/// Notifies the compaction thread to stop working. (In week 2)
compaction_notifier: crossbeam_channel::Sender<()>,
/// The handle for the compaction thread. (In week 2)
compaction_thread: Mutex<Option<std::thread::JoinHandle<()>>>,
}
impl Drop for MiniLsm {
fn drop(&mut self) {
self.compaction_notifier.send(()).ok();
self.flush_notifier.send(()).ok();
}
}
impl MiniLsm {
pub fn close(&self) -> Result<()> {
self.inner.sync_dir()?;
self.flush_notifier.send(()).map_err(|e| anyhow!("{e}"))?;
self.compaction_notifier
.send(())
.map_err(|e| anyhow!("{e}"))?;
self.flush_thread
.lock()
.take()
.map(|thread| {
thread
.join()
.map_err(|e| anyhow!("failed to stop flush thread: {:?}", e))
})
.transpose()?;
self.compaction_thread
.lock()
.take()
.map(|thread| {
thread
.join()
.map_err(|e| anyhow!("failed to stop compaction thread: {:?}", e))
})
.transpose()?;
if !self.inner.options.enable_wal {
// flush all memtables to the disk
self.force_flush()?;
} else {
// flush all wal
self.sync()?;
}
self.inner.sync_dir()?;
Ok(())
}
/// Start the storage engine by either loading an existing directory or creating a new one if the directory does
/// not exist.
pub fn open(path: impl AsRef<Path>, options: LsmStorageOptions) -> Result<Arc<Self>> {
let inner = Arc::new(LsmStorageInner::open(path, options)?);
let (tx1, rx) = crossbeam_channel::unbounded();
let compaction_thread = inner.spawn_compaction_thread(rx)?;
let (tx2, rx) = crossbeam_channel::unbounded();
let flush_thread = inner.spawn_flush_thread(rx)?;
Ok(Arc::new(Self {
inner,
flush_notifier: tx2,
flush_thread: Mutex::new(flush_thread),
compaction_notifier: tx1,
compaction_thread: Mutex::new(compaction_thread),
}))
}
pub fn new_txn(&self) -> Result<Arc<Transaction>> {
self.inner.new_txn()
}
pub fn write_batch<T: AsRef<[u8]>>(&self, batch: &[WriteBatchRecord<T>]) -> Result<()> {
self.inner.write_batch(batch)
}
pub fn add_compaction_filter(&self, compaction_filter: CompactionFilter) {
self.inner.add_compaction_filter(compaction_filter)
}
pub fn get(&self, key: &[u8]) -> Result<Option<Bytes>> {
self.inner.get(key)
}
pub fn put(&self, key: &[u8], value: &[u8]) -> Result<()> {
self.inner.put(key, value)
}
pub fn delete(&self, key: &[u8]) -> Result<()> {
self.inner.delete(key)
}
pub fn sync(&self) -> Result<()> {
self.inner.sync()
}
pub fn scan(&self, lower: Bound<&[u8]>, upper: Bound<&[u8]>) -> Result<TxnIterator> {
self.inner.scan(lower, upper)
}
/// Only call this in test cases due to race conditions
pub fn force_flush(&self) -> Result<()> {
if !self.inner.state.read().memtable.is_empty() {
self.inner
.force_freeze_memtable(&self.inner.state_lock.lock())?;
}
while !self.inner.state.read().imm_memtables.is_empty() {
self.inner.force_flush_next_imm_memtable()?;
}
Ok(())
}
pub fn force_full_compaction(&self) -> Result<()> {
self.inner.force_full_compaction()
}
}
impl LsmStorageInner {
pub(crate) fn next_sst_id(&self) -> usize {
self.next_sst_id
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
}
/// Start the storage engine by either loading an existing directory or creating a new one if the directory does
/// not exist.
pub(crate) fn open(path: impl AsRef<Path>, options: LsmStorageOptions) -> Result<Self> {
let path = path.as_ref();
if !path.exists() {
fs::create_dir_all(path)?;
}
let mut state = LsmStorageState::create(&options);
let compaction_controller = match &options.compaction_options {
CompactionOptions::Leveled(options) => {
CompactionController::Leveled(LeveledCompactionController::new(options.clone()))
}
CompactionOptions::Tiered(options) => {
CompactionController::Tiered(TieredCompactionController::new(options.clone()))
}
CompactionOptions::Simple(options) => CompactionController::Simple(
SimpleLeveledCompactionController::new(options.clone()),
),
CompactionOptions::NoCompaction => CompactionController::NoCompaction,
};
let block_cache = Arc::new(BlockCache::new(1024));
let manifest_file_path = path.join("MANIFEST");
let mut max_sst_id = 0;
let mut max_ts = 0;
let manifest = if manifest_file_path.exists() {
// recover from file
let (manifest, records) = Manifest::recover(manifest_file_path)?;
let mut sst_need_load: BTreeSet<usize> = BTreeSet::new();
let mut memtable_to_recover = Vec::new();
for record in records {
match record {
ManifestRecord::Flush(sst_id) => {
if compaction_controller.flush_to_l0() {
println!("flush memtable{sst_id} to l0");
state.l0_sstables.insert(0, sst_id);
} else {
println!("flush memtable{sst_id} to new tier");
state.levels.insert(0, (sst_id, vec![sst_id]));
}
let option = memtable_to_recover.pop();
assert_eq!(option, Some(sst_id), "failed to flush memtable");
sst_need_load.insert(sst_id);
max_sst_id = max_sst_id.max(sst_id);
}
ManifestRecord::NewMemtable(sst_id) => {
println!("new memtable {sst_id}");
memtable_to_recover.insert(0, sst_id);
max_sst_id = max_sst_id.max(sst_id);
}
ManifestRecord::Compaction(task, sst_to_add) => {
sst_need_load.extend(sst_to_add.iter());
for x in &sst_to_add {
max_sst_id = max_sst_id.max(*x);
}
let (new_state, sst_to_remove) = compaction_controller
.apply_compaction_result(&state, &task, &sst_to_add);
for sst_id in sst_to_remove {
sst_need_load.remove(&sst_id);
}
state = new_state;
}
}
}
if options.enable_wal {
for sst_id in memtable_to_recover {
let mem_table =
MemTable::recover_from_wal(sst_id, Self::path_of_wal_static(path, sst_id))?;
let mut iterator = mem_table.scan(Unbounded, Unbounded);
while iterator.is_valid() {
let ts = iterator.key().ts();
if max_ts < ts {
max_ts = ts;
}
iterator.next()?;
}
state.imm_memtables.push(Arc::new(mem_table));
}
}
for sst_id in sst_need_load {
let ss_table = SsTable::open(
sst_id,
Some(block_cache.clone()),
FileObject::open(Self::path_of_sst_static(path, sst_id).as_path())?,
)?;
if ss_table.max_ts() > max_ts {
max_ts = ss_table.max_ts();
}
state.sstables.insert(sst_id, Arc::new(ss_table));
}
max_sst_id += 1;
manifest
} else {
Manifest::create(manifest_file_path)?
};
state.memtable = if options.enable_wal {
Arc::new(MemTable::create_with_wal(
max_sst_id,
Self::path_of_wal_static(path, max_sst_id),
)?)
} else {
Arc::new(MemTable::create(max_sst_id))
};
manifest.add_record_when_init(ManifestRecord::NewMemtable(max_sst_id))?;
let storage = Self {
state: Arc::new(RwLock::new(Arc::new(state))),
state_lock: Mutex::new(()),
path: path.to_path_buf(),
block_cache,
next_sst_id: AtomicUsize::new(max_sst_id + 1),
compaction_controller,
manifest: Some(manifest),
options: options.into(),
mvcc: Some(LsmMvccInner::new(max_ts)),
compaction_filters: Arc::new(Mutex::new(Vec::new())),
};
Ok(storage)
}
pub fn sync(&self) -> Result<()> {
let guard = self.state.read();
guard.memtable.sync_wal()?;
for x in &guard.imm_memtables {
x.sync_wal()?;
}
Ok(())
}
pub fn add_compaction_filter(&self, compaction_filter: CompactionFilter) {
let mut compaction_filters = self.compaction_filters.lock();
compaction_filters.push(compaction_filter);
}
pub(crate) fn get_with_ts(self: &Arc<Self>, key: &[u8], read_ts: u64) -> Result<Option<Bytes>> {
let snapshot = {
let guard = self.state.read();
Arc::clone(&guard)
};
let mut mem_table_iters = Vec::with_capacity(1 + snapshot.imm_memtables.len());
let key_low = KeySlice::from_slice(key, TS_RANGE_BEGIN);
let key_upper = KeySlice::from_slice(key, TS_RANGE_END);
let iter = snapshot
.memtable
.scan(Included(key_low), Included(key_upper));
mem_table_iters.push(Box::new(iter));
for imm in &snapshot.imm_memtables {
let iter = imm.scan(Included(key_low), Included(key_upper));
mem_table_iters.push(Box::new(iter));
}
let mem_table_merge = MergeIterator::create(mem_table_iters);
let l0_sst = snapshot
.l0_sstables
.iter()
.filter_map(|sst_id| {
let sst = snapshot.sstables[sst_id].clone();
if sst.key_in_range(key) && sst.may_contain_key(key) {
Some(sst)
} else {
None
}
})
.map(|sst| {
let iter = SsTableIterator::create_and_seek_to_key(sst, key_low)?;
Ok(Box::new(iter))
})
.collect::<Result<Vec<_>>>()?;
let l0_merge_iter = MergeIterator::create(l0_sst);
let two_merge_iters = TwoMergeIterator::create(mem_table_merge, l0_merge_iter)?;
let mut iters = vec![];
for (_level, idxs) in &snapshot.levels {
// println!("try fetching key from l{level}");
let sst_iters = idxs
.iter()
.filter_map(|sst_id| {
let sst = snapshot.sstables[sst_id].clone();
if sst.key_in_range(key) && sst.may_contain_key(key) {
Some(sst)
} else {
None
}
})
.collect::<Vec<_>>();
let iter = SstConcatIterator::create_and_seek_to_key(sst_iters, key_low)?;
iters.push(Box::new(iter));
}
let levels_iter = MergeIterator::create(iters);
let iterator = LsmIterator::new(
TwoMergeIterator::create(two_merge_iters, levels_iter)?,
map_bound(Included(key_upper)),
read_ts,
)?;
if iterator.is_valid() && iterator.key() == key && !iterator.value().is_empty() {
Ok(Some(Bytes::copy_from_slice(iterator.value())))
} else {
Ok(None)
}
}
/// Get a key from the storage. In day 7, this can be further optimized by using a bloom filter.
pub fn get(self: &Arc<Self>, key: &[u8]) -> Result<Option<Bytes>> {
let txn = self
.mvcc
.as_ref()
.map(|mvcc| mvcc.new_txn(self.clone(), true))
.ok_or(anyhow!("not support mvcc"))?;
txn.get(key)
}
pub(crate) fn write_batch_inner<T: AsRef<[u8]>>(
&self,
batch: &[WriteBatchRecord<T>],
) -> Result<u64> {
let mvcc = self.mvcc();
let _guard = mvcc.write_lock.lock();
let ts = mvcc.latest_commit_ts() + 1;
for x in batch {
match x {
WriteBatchRecord::Put(key, value) => {
let state = self.state.read();
state
.memtable
.put(KeySlice::from_slice(key.as_ref(), ts), value.as_ref())?;
}
WriteBatchRecord::Del(key) => {
let state = self.state.read();
state
.memtable
.put(KeySlice::from_slice(key.as_ref(), ts), &[])?;
}
}
self.try_freeze_memtable()?;
}
mvcc.update_commit_ts(ts);
Ok(ts)
}
pub fn write_batch<T: AsRef<[u8]>>(
self: &Arc<LsmStorageInner>,
batch: &[WriteBatchRecord<T>],
) -> Result<()> {
if self.options.serializable {
let tx = self.new_txn()?;
for x in batch {
match x {
WriteBatchRecord::Put(key, value) => {
tx.put(key.as_ref(), value.as_ref());
}
WriteBatchRecord::Del(key) => {
tx.delete(key.as_ref());
}
}
}
tx.commit()?;
} else {
self.write_batch_inner(batch)?;
}
Ok(())
}
/// Put a key-value pair into the storage by writing into the current memtable.
pub fn put(self: &Arc<Self>, key: &[u8], value: &[u8]) -> Result<()> {
if self.options.serializable {
let tx = self.new_txn()?;
tx.put(key, value);
tx.commit()?;
} else {
self.write_batch_inner(&[WriteBatchRecord::Put(key, value)])?;
}
Ok(())
}
/// Remove a key from the storage by writing an empty value.
pub fn delete(self: &Arc<Self>, key: &[u8]) -> Result<()> {
if self.options.serializable {
let tx = self.new_txn()?;
tx.delete(key);
tx.commit()?;
} else {
self.write_batch_inner(&[WriteBatchRecord::Del(key)])?;
}
Ok(())
}
pub(crate) fn path_of_sst_static(path: impl AsRef<Path>, id: usize) -> PathBuf {
path.as_ref().join(format!("{:05}.sst", id))
}
pub(crate) fn path_of_sst(&self, id: usize) -> PathBuf {
Self::path_of_sst_static(&self.path, id)
}
pub(crate) fn path_of_wal_static(path: impl AsRef<Path>, id: usize) -> PathBuf {
path.as_ref().join(format!("{:05}.wal", id))
}
pub(crate) fn path_of_wal(&self, id: usize) -> PathBuf {
Self::path_of_wal_static(&self.path, id)
}
pub(super) fn sync_dir(&self) -> Result<()> {
File::open(&self.path)?.sync_all()?;
Ok(())
}
/// Force freeze the current memtable to an immutable memtable
pub fn force_freeze_memtable(&self, state_lock_observer: &MutexGuard<'_, ()>) -> Result<()> {
let sst_id = self.next_sst_id();
let memtable = if self.options.enable_wal {
MemTable::create_with_wal(sst_id, self.path_of_wal(sst_id))?
} else {
MemTable::create(sst_id)
};
{
let mut guard = self.state.write();
let mut state = guard.as_ref().clone();
let old_memtable = std::mem::replace(&mut state.memtable, Arc::new(memtable));
state.imm_memtables.insert(0, old_memtable);
*guard = Arc::new(state);
}
if let Some(manifest) = &self.manifest {
manifest.add_record(state_lock_observer, ManifestRecord::NewMemtable(sst_id))?;
}
self.sync_dir()?;
Ok(())
}
fn try_freeze_memtable(&self) -> Result<()> {
if self.state.read().memtable.approximate_size() > self.options.target_sst_size {
let state_lock_guard = self.state_lock.lock();
if self.state.read().memtable.approximate_size() > self.options.target_sst_size {
return self.force_freeze_memtable(&state_lock_guard);
}
}
Ok(())
}
/// Force flush the earliest-created immutable memtable to disk
pub fn force_flush_next_imm_memtable(&self) -> Result<()> {
let _state_lock = self.state_lock.lock();
let memtable_to_flush = {
let guard = self.state.read();
guard
.imm_memtables
.last()
.ok_or_else(|| anyhow!("No immutable memtable to flush"))?
.clone()
};
let mut builder = SsTableBuilder::new(self.options.block_size);
memtable_to_flush.flush(&mut builder)?;
let sst_id = memtable_to_flush.id();
let sstable = builder.build(
sst_id,
Some(self.block_cache.clone()),
self.path_of_sst(sst_id),
)?;
{
let mut guard = self.state.write();
let mut snapshot = guard.as_ref().clone();
// remove it from imm_memtable
let memtable = snapshot.imm_memtables.pop().unwrap();
assert_eq!(memtable.id(), sst_id);
if self.compaction_controller.flush_to_l0() {
snapshot.l0_sstables.insert(0, sst_id);
} else {
snapshot.levels.insert(0, (sst_id, vec![sst_id]));
}
println!("flushed {}.sst with size={}", sst_id, sstable.table_size());
snapshot.sstables.insert(sst_id, Arc::new(sstable));
*guard = Arc::new(snapshot);
}
if self.options.enable_wal {
fs::remove_file(self.path_of_wal(sst_id))?;
}
if let Some(manifest) = &self.manifest {
manifest.add_record(&_state_lock, ManifestRecord::Flush(sst_id))?;
}
self.sync_dir()?;
Ok(())
}
pub fn mvcc(&self) -> &LsmMvccInner {
self.mvcc.as_ref().unwrap()
}
pub fn new_txn(self: &Arc<LsmStorageInner>) -> Result<Arc<Transaction>> {
Ok(self.mvcc().new_txn(self.clone(), self.options.serializable))
}
pub(crate) fn scan_with_ts(
self: &Arc<Self>,
lower: Bound<&[u8]>,
upper: Bound<&[u8]>,
read_ts: u64,
) -> Result<FusedIterator<LsmIterator>> {
let snapshot = {
let guard = self.state.read();
Arc::clone(&guard)
};
let lower_bound_slice = lower.map(|b| KeySlice::from_slice(b, TS_RANGE_BEGIN));
let upper_bound_slice = upper.map(|b| KeySlice::from_slice(b, TS_RANGE_END));
let iterator = Box::new(snapshot.memtable.scan(lower_bound_slice, upper_bound_slice));
let mut vec = snapshot
.imm_memtables
.iter()
.map(|m| Box::new(m.scan(lower_bound_slice, upper_bound_slice)))
.collect::<Vec<_>>();
vec.insert(0, iterator);
let mut mem_iter = MergeIterator::create(vec);
if let Bound::Excluded(key) = lower {
while mem_iter.is_valid() && mem_iter.key().key_ref() == key {
mem_iter.next()?;
}
}
let mut iters = Vec::new();
for idx in &snapshot.l0_sstables {
let sstable = snapshot.sstables[idx].clone();
if !range_overlap(
lower_bound_slice,
upper_bound_slice,
sstable.first_key(),
sstable.last_key(),
) {
continue;
}
let iter = match lower_bound_slice {
Bound::Included(key) => SsTableIterator::create_and_seek_to_key(sstable, key)?,
Bound::Excluded(key) => {
let mut iter = SsTableIterator::create_and_seek_to_key(sstable, key)?;
while iter.is_valid() && iter.key().key_ref() == key.key_ref() {
iter.next()?;
}
iter
}
Bound::Unbounded => SsTableIterator::create_and_seek_to_first(sstable)?,
};
iters.push(Box::new(iter));
}
let l0_sst_iter = MergeIterator::create(iters);
let memtable_merge_iter = TwoMergeIterator::create(mem_iter, l0_sst_iter)?;
let mut levels_iter = Vec::with_capacity(snapshot.levels.len());
for (_, idxs) in &snapshot.levels {
let levels_sst = idxs
.iter()
.map(|idx| snapshot.sstables[idx].clone())
.filter(|sst| {
range_overlap(
lower_bound_slice,
upper_bound_slice,
sst.first_key(),
sst.last_key(),
)
})
.collect::<Vec<_>>();
let levels_sst_iter = match lower_bound_slice {
Bound::Included(key) => SstConcatIterator::create_and_seek_to_key(levels_sst, key)?,
Bound::Excluded(key) => {
let mut iter = SstConcatIterator::create_and_seek_to_key(levels_sst, key)?;
while iter.is_valid() && iter.key() == key {
iter.next()?;
}
iter
}
Bound::Unbounded => SstConcatIterator::create_and_seek_to_first(levels_sst)?,
};
levels_iter.push(Box::new(levels_sst_iter));
}
let levels_merge_iter = MergeIterator::create(levels_iter);
let two_merge_iter = TwoMergeIterator::create(memtable_merge_iter, levels_merge_iter)?;
Ok(FusedIterator::new(LsmIterator::new(
two_merge_iter,
map_bound(upper_bound_slice),
read_ts,
)?))
}
/// Create an iterator over a range of keys.
pub fn scan(self: &Arc<Self>, lower: Bound<&[u8]>, upper: Bound<&[u8]>) -> Result<TxnIterator> {
let txn = self
.mvcc
.as_ref()
.map(|mvcc| mvcc.new_txn(self.clone(), true))
.ok_or(anyhow!("not support mvcc"))?;
txn.scan(lower, upper)
}
}
|
//
// Created by Leon on 21. 03. 2022.
//
#ifndef NALOGA0401_GALLERY_H
#define NALOGA0401_GALLERY_H
#include <vector>
#include "Artwork.h"
#include "Painting.h"
#include "PrintIfPainting.h"
#include "Building.h"
#include "Representative.h"
#include <algorithm>
#include <functional>
class Gallery : public Building {
private:
std::string name;
std::vector<std::shared_ptr<Artwork>> artworks;
public:
Gallery(std::string name, std::string address, double height, double width, double length, unsigned int floors, unsigned int undergroundFloors);
void addArtwork(std::shared_ptr<Artwork> artwork);
void printArtworks() const;
std::string toString() const override;
std::shared_ptr<Artwork> getOldestArtwork() const;
std::vector<std::shared_ptr<Artist>> getAllArtistsBornAfter(unsigned year) const;
void sort(bool (*c)(std::shared_ptr<Artwork>, std::shared_ptr<Artwork>));
std::shared_ptr<Artwork> find(std::function<bool(std::shared_ptr<Artwork>)> c) const;
void printArtworks(PrintIfPainting i) const;
void filterOut(std::function<bool(std::shared_ptr<Artwork>)> c);
std::vector<std::shared_ptr<Artwork>> filter(std::function<bool(std::shared_ptr<Artwork>)> c) ;
};
#endif //NALOGA0401_GALLERY_H
|
描述
list ( mixed $var1 [, mixed $... ] ) : array
像 array() 一样,这不是一个真正的函数,而是一个语言结构。list() 被用于在一个操作中赋值一个变量列表。
注意:在 PHP 7.1.0 以前,list() 只用于处理数值数组,并假设数值索引从 0 开始。
警告:
在 PHP 5 中,list() 从最右侧的参数开始赋值。在 PHP 7 中,list() 从最左侧的参数开始。
如果你用纯变量,不用担心这一点。 但是如果你用了具有索引的数组,通常你期望得到的结果和在 list() 中写的一样是从左到右的,但在 PHP 5
里实际上不是,它是以相反顺序赋值的。
个人补充:得到的数组中的内容一般是相同的,不过顺序刚好反了。
通常而言,建议避免依赖于操作的顺序,因为在未来可能会再次变化。
参数
var1
一个变量。
返回值
返回赋给该函数的数组。
变更日志
版本 描述
7.1.0 现在可以在 list() 中指定键了。这允许对具有非整数或非顺序键的数组进行解构。
7.0.0 赋值运算的运行顺序已经变了。
7.0.0 list() 表达式不能再完全是空的了。
7.0.0 字符串不能再被拆开。
来自示例
被赋值给该函数的数组的元素顺序不重要,在赋值之前数组元素应该会按键的升序顺序进行一次排序。
从 PHP 7.1.0 开始,list() 现在还可以包含显式的键,它可以以任意表达式的形式指定。允许混合整型和字符串类型的键;然而,有键和没有键的元素
不能混合使用。
|
package com.alrawas.sec.security;
import com.alrawas.sec.jwt.JwtConfig;
import com.alrawas.sec.jwt.JwtTokenVerifier;
import com.alrawas.sec.jwt.JwtUsernameAndPasswordAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import javax.crypto.SecretKey;
import static com.alrawas.sec.security.ApplicationUserRole.*;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // disable if not using annothations but antm,atchers
public class ApplicationSecurityConfig {
private final PasswordEncoder passwordEncoder;
private final UserDetailsService userDetailsService;
private final AuthenticationConfiguration authenticationConfiguration;
private final SecretKey secretKey;
private final JwtConfig jwtConfig;
public ApplicationSecurityConfig(PasswordEncoder passwordEncoder,
UserDetailsService userDetailsService,
AuthenticationConfiguration authenticationConfiguration, SecretKey secretKey, JwtConfig jwtConfig) {
this.passwordEncoder = passwordEncoder;
this.userDetailsService = userDetailsService;
this.authenticationConfiguration = authenticationConfiguration;
this.secretKey = secretKey;
this.jwtConfig = jwtConfig;
}
// @Bean
// public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// http
// .csrf().disable()
// .authorizeHttpRequests((authz) -> authz
// .antMatchers(HttpMethod.GET, "/", "/index.html", "/css/*", "/js/*").permitAll()
// .antMatchers("/api/**").hasRole(STUDENT.name())
//// .antMatchers(HttpMethod.DELETE, "/management/api/**").hasAuthority(COURSE_WRITE.getPermission())
//// .antMatchers(HttpMethod.PUT, "/management/api/**").hasAuthority(COURSE_WRITE.getPermission())
//// .antMatchers(HttpMethod.POST, "/management/api/**").hasAuthority(COURSE_WRITE.getPermission())
//// .antMatchers(HttpMethod.GET,"/management/api/**").hasAnyRole(ADMIN.name(), ADMINTRAINEE.name())
// .anyRequest().authenticated())
// .formLogin()
// .loginPage("/login").permitAll()
// .defaultSuccessUrl("/courses", true)
// .passwordParameter("password")
// .usernameParameter("username")
// .and().rememberMe()
// .rememberMeParameter("remember-me")
// .tokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(21))
// .key("somethingverysecured")
// .and().logout()
// .logoutUrl("/logout")
// .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
// .clearAuthentication(true)
// .invalidateHttpSession(true)
// .deleteCookies("JSESSIONID", "remember-me")
// .logoutSuccessUrl("/login")
// ;
//// .httpBasic(withDefaults())
//// .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
// ;
//
// return http.build();
// }
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
// SecurityFilterChain for JWT Auth
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, secretKey))
.addFilterAfter(new JwtTokenVerifier(jwtConfig, secretKey), JwtUsernameAndPasswordAuthenticationFilter.class)
.authorizeHttpRequests(
(authz) -> authz
.antMatchers(HttpMethod.GET, "/", "/index.html", "/css/*", "/js/*").permitAll()
.antMatchers("/api/**").hasRole(STUDENT.name())
.anyRequest().authenticated()
);
return http.build();
}
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder);
provider.setUserDetailsService(userDetailsService);
return provider;
}
// @Bean
// public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
//
// UserDetails user = User.builder()
// .username("annasmith")
// .password(passwordEncoder.encode("password"))
//// .roles(STUDENT.name()) // ROLE_STUDENT
// .authorities(STUDENT.getGrantedAuthorities())
// .build();
//
// UserDetails lindaUser = User.builder()
// .username("linda")
// .password(passwordEncoder.encode("password123"))
//// .roles(ADMIN.name()) // ROLE_ADMIN
// .authorities(ADMIN.getGrantedAuthorities())
// .build();
//
// UserDetails tomUser = User.builder()
// .username("tom")
// .password(passwordEncoder.encode("password123"))
//// .roles(ADMINTRAINEE.name()) // ROLE_ADMINTRAINEE
// .authorities(ADMINTRAINEE.getGrantedAuthorities())
// .build();
//
// return new InMemoryUserDetailsManager(user, lindaUser, tomUser);
// }
// @Bean
// public WebSecurityCustomizer webSecurityCustomizer() {
// return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
//
// }
}
|
# JSOF Parser
Snippet to easily parse JSON + FUNCTIONS into simple JSON ✌️💜.
## Installation
Use the package manager [npm](https://www.npmjs.com/get-npm) to install JSOF.
```bash
npm i jsof-parser
```
## Usage
We can start by converting a functional JSON to standard JSON
```js
import JSOF from "jsof-parser";
const code = `{
"label": "My functional json 😍",
"animals": concat(
getAnimal(types.unicorn, "🦄"),
getAnimal(types.dog, "🐕"),
),
}`;
const myObject = JSOF.parse(code);
const jsonData = JSON.stringify(myObject);
```
That will be printed as follow:
```json
{
"label": "My functional json 😍",
"animals": {
":type": "function",
"path": "concat",
"props": [
{
":type": "function",
"path": "getAnimal",
"props": [
{
":type": "prop",
"path": "types.unicorn"
},
"🦄"
]
},
{
":type": "function",
"path": "getAnimal",
"props": [
{
":type": "prop",
"path": "types.dog"
},
"🐕"
]
}
]
}
}
```
## Make the reverse process
Create a JSON data as fallow
```js
const data = {
":type": "function",
path: "pipe",
props: [
{
map: {
user: [
{
":type": "function",
path: "get",
props: ["user"],
},
{
":type": "function",
path: "pick",
props: ["name", "nick", "email"],
},
],
},
test: [
{
"user.nick": {
":type": "function",
path: "match",
props: [
{
":type": "prop",
path: "is.req",
},
{
":type": "prop",
path: "is.slug",
},
],
},
"user.email": {
":type": "function",
path: "match",
props: [
{
":type": "prop",
path: "is.email",
},
],
},
},
{
":type": "function",
path: "get",
props: ["test"],
},
],
},
],
};
const functionBody = JSOF.stringify(data);
const dependencies = ["pipe", "get", "pick", "match", "is"];
const params = `{ ${dependencies.join(", ")} }`;
const myFunction = eval(`(${params}) => ${functionBody}`);
console.log(myFunction.toString());
```
And the result will be one anonymous function like this
```js
({ pipe, get, pick, match, is }) =>
pipe({
map: { user: [get("user"), pick("name", "nick", "email")] },
test: [
{ "user.nick": match(is.req, is.slug), "user.email": match(is.email) },
get("test"),
],
});
```
## Contribuindo com o projeto
Solicitações pull são bem-vindas. Para mudanças importantes, abra um problema primeiro para discutir o que você gostaria de mudar.
## License
[MIT](https://choosealicense.com/licenses/mit/)
|
package com.zbkj.common.request;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* 虚拟评论对象
* +----------------------------------------------------------------------
* | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
* +----------------------------------------------------------------------
* | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
* +----------------------------------------------------------------------
* | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
* +----------------------------------------------------------------------
* | Author: CRMEB Team <admin@crmeb.com>
* +----------------------------------------------------------------------
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="ProductReplyVirtualRequest对象", description="虚拟评论对象")
public class ProductReplyVirtualRequest implements Serializable {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "商品ID", required = true)
@NotNull(message = "商品ID不能为空")
private Integer productId;
@ApiModelProperty(value = "商品规格属性值ID", required = true)
@NotNull(message = "商品规格属性值ID不能为空")
private Integer attrValueId;
@ApiModelProperty(value = "评价星级", example = "5", required = true)
@NotNull(message = "评价星级不能为空")
@Range(min = 1, max = 5, message = "评价星级为1-5")
private Integer star;
@ApiModelProperty(value = "评论内容", required = true)
@NotBlank(message = "请填写评论内容")
@Length(max = 512, message = "评论内容长度不能超过512个字符")
private String comment;
@ApiModelProperty(value = "评论图片", required = true)
private String pics;
@ApiModelProperty(value = "评论人头像 [虚拟评论参数]", required = true)
@NotEmpty(message = "评论人头像不能为空")
private String avatar;
@ApiModelProperty(value = "评论人昵称 [虚拟评论参数]", required = true)
@NotEmpty(message = "评论人昵称不能为空")
private String nickname;
}
|
\documentclass{article}
\usepackage{times}
\usepackage{xspace}
\usepackage{color}
\usepackage{listings}
\usepackage{setspace}
\usepackage{url}
\usepackage{longtable}
\newcommand{\lapps}{LAPPS\xspace}
\newcommand{\data}{\texttt{Data}\xspace}
\newcommand{\source}{\texttt{DataSource}\xspace}
\newcommand{\service}{\texttt{WebService}\xspace}
\newcommand{\discriminator}{\textit{discriminator}\xspace}
\newcommand{\payload}{\textit{payload}\xspace}
\newcommand{\vocab}[1]{\url{http://vocab.lappsgrid.org/#1}}
\newcommand{\ns}[1]{\url{http://vocab.lappsgrid.org/ns/#1}}
\newcommand{\definedterm}[1]{\textbf{\textit{#1}}\xspace}
\newcommand{\must}{\definedterm{must}}
\newcommand{\mustnot}{\definedterm{must not}}
\newcommand{\should}{\definedterm{should}}
\newcommand{\shouldnot}{\definedterm{should not}}
\newcommand{\may}{\definedterm{may}}
\newcommand{\maynot}{\definedterm{may not}}
\renewcommand{\tt}[1]{\texttt{#1}}
\newcommand{\bold}[1]{\textbf{#1}}
\lstnewenvironment{groovy}[2]
{\singlespacing\lstset{language=java, label=#1, caption=#2, captionpos=b, tabsize=3}}
{}
\newenvironment{listing}{
\begin{itemize}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
}{\end{itemize}}
\newenvironment{enum}{
\begin{enumerate}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
}{\end{enumerate}}
\begin{document}
\title{Design of the Language Application Grid}
\author{Keith Suderman\\
Department of Computer Science\\
Vassar College\\
Poughkeepsie, New York\\
\texttt{suderman@cs.vassar.edu}}
\date{\today}
\maketitle
\begin{abstract}
The Language Application (LAPPS) Grid project
is establishing a
framework that enables language service discovery, composition, and reuse and promotes sustainability, manageability, usability, and interoperability of natural language Processing (NLP) components. It is based on the {\it service-oriented architecture} (SOA), a more recent, web-oriented version of the ``pipeline" architecture that has long been used in NLP for sequencing loosely-coupled linguistic analyses.
The LAPPS Grid provides access to basic NLP processing tools and resources and enables pipelining such tools to create custom NLP applications, as well as
composite services such as question answering and machine translation together with language resources such as mono- and multi-lingual corpora and lexicons that support NLP.
The transformative aspect of the LAPPS Grid is that it orchestrates access to and deployment of language resources and processing functions available from servers around the globe and enables users to add their own language resources, services, and even service grids to satisfy their particular needs.
\end{abstract}
% Introduction
\section{Introduction}
This paper describes the basic architecture and design of the \lapps Grid API (Application Programming Interface). The \lapps Grid uses the Service Grid\footnote{\url{http://servicegrid.net}} software for user authentication, authorization, service registration and service invocation. As such the \lapps API simply defines interfaces that web services \may implement to be considered \lapps compliant.
Unlike other language service grids (Language Grid\footnote{\url{http://langrid.org}}, Panacea\footnote{\url{http://www.panacea-lr.eu}}), which define separate interfaces for each service type (translators, tokenizers, named entity recognizers, etc.) the \lapps API only defines two very simple interfaces for web services; \source and \service. The information required to invoke the underlying Language Resource (LR) is encoded as a JSON-LD\footnote{\url{http://json-ld.org}} document that is transmitted to the service.
Currently, the \lapps Grid only supports SOAP\cite{soap} web services. Future versions of the \lapps grid will also support REST based web services.
% Defined Terms
\section{Key words}
The key words "\must", "\mustnot", "\should", "\shouldnot", "\may", and "\maynot" in this document are to be interpreted as described in
RFC 2119\cite{rfc2119}.
% API
\section{LAPPS Application Programming Interface (API)}
The core \lapps API consists of one concrete class, the \data object, and two interfaces; \source and \service. The \data object is the main artifact exchanged by \lapps services and \source and \service are interfaces to be implemented by providers wishing to contribute services to the \lapps grid.
% Errors
\subsection{Errors}
In the event of an error while servicing a request \lapps services \should return a \data object with the \discriminator set to \ns{error} and a UTF-8 string congaing an error message as the \payload. Services \shouldnot rely on SOAP's fault handling mechanism by throwing exceptions, either directly or indirectly. For security reasons production services \shouldnot include a stack trace in the error message.
% Data
\subsection{Data Objects}
All \lapps services communicate with each other by exchanging \data objects. A \data object consists of a \discriminator value and a \payload. The \data object is defined as:\footnote{All code snippets provided are in Groovy, which is (almost) a superset of the Java language. See http://groovy.codehaus.org for an introduction to the Groovy language.}
\begin{groovy}{data}{org.lappsgrid.api.Data}
class Data {
String discriminator
String payload
}
\end{groovy}
The \discriminator value can either be a URI or a media-type conforming to the ABNF grammar in section 4.2 of RFC 6838\cite{rfc6838}. See Section~\ref{sec:media} for a discussion of recognized \lapps media types.
The \payload \should be a UTF-8 string and the \discriminator determines how the string should be interpreted. Typically the \payload will contain a string representation of some document format, for example GATE XML or UIMA CAS. A complete list of currently supported \discriminator types can be found in Section~\ref{sub:discriminators}.
The following terms are used throughout the remainder of this document.
\begin{description}
\item[error object] a \data object with the \discriminator set to \ns{error}
\item[data object type] the value of the \data object's \discriminator. Sometimes referred to as the \emph{"object's type"} or \emph{"data type"} when the meaning is not ambiguous.
\end{description}
% DataSource
\subsection{DataSource}
A \source is a web service that provides data to other processing services as \data objects. A \source can return any type of \data object provided the \data object's \discriminator is set to an appropriate value. For example, textual \source{}s will typically return \data objects with the \discriminator set to \tt{text/plain} or \tt{application/xml}. The custom attribute \emph{schema} \may used to further describe the data format, either by referencing an actual schema document or by using a unique identifier agreed upon by service providers; for example; \tt{text/plain; schema=ptb}.
\begin{groovy}{groovy:source}{org.lappsgrid.api.DataSource}
interface DataSource {
Data getMetadata()
int size()
Data list()
Data list(int start, int end)
Data get(String key)
Data query(Data input)
}
\end{groovy}
% getMetadata
\subsubsection{Data getMetadata()}
The \tt{getMetadata()} method \should return a JSON-LD \payload with the \discriminator set to \ns{meta}. The metadata returned \should include at least the following information:
\begin{listing}
\item name
\item version
\item description
\end{listing}
Section~\ref{sec:metadata} contains a complete description of the JSON-LD format for \lapps metadata.
% size
\subsubsection{int size()}
The \tt{size()} method \must return an integer value representing the number of documents managed by the \source service or a negative integer in the case of an error. The \tt{size} is also the number of keys returned by the \tt{list()} method.
%list
\subsubsection{Data list()\\Data list(int start, int end)}
The \tt{list()} methods returns a list of the key values that can be used to fetch documents from the \source. A \source \may return an error if the number of artifacts managed by the \source is extremely large. In this case the \source \should return a \data object with the \discriminator set to \ns{error} and the string \emph{"Index too large."} as the \payload.
The \tt{list(int,int)} method returns the range of key values $[start..end)$. They keys in the returned list \must be separated whitespace characters with the the appropriate \discriminator value from Table~\ref{table:list}.
\begin{table}[h!]
\noindent\begin{tabular}{ l p{7.5cm} }
\bold{Media type} & \bold{Description} \\
text/plain; separator=space & a list of UTF-8 strings separated by a single white space character (0x20) \\
text/plain; separator=newline & a list of UTF-8 string separated by a single newline (carridge return) character (0x0D) \\
text/plain; separator=tab & tab (0x09) separated values \\
text/plain; separator=comma & comma (0x2C) separated values \\
\end{tabular}
\caption{Allowable media types for key lists}
\label{table:list}
\end{table}
Applications \must be able to split the returned list into an array of keys on the specified separator without doing any other text processing.
% get
\subsubsection{Data get(String key)}
The \tt{get(String)} method returns a single artifact from a \source. The key passed to the \source \must be one of the keys returned by either of the \tt{list} methods. The \discriminator \must be set to one of the following:
\begin{listing}
\item a recognized media type listed in Section~\ref{sec:media},
\item a user defined media type defined as described in Section~\ref{sec:custom-media}, or
\item a URI referencing a user defined media type.
\end{listing}
%query
\subsubsection{Data query(Data input)}
This method is reserved for future use. It is anticipated that \source services will be able to return documents based on a Lucene\footnote{\url{http://lucene.apache.org}} and/or Solr\footnote{\url{http://lucene.apache.org/solr}} query. Other query languages may also be supported as well.
% WebService
\subsection{WebService}\label{sub:WebService}
A \service is any service that transforms its input, either by adding or removing annotations or metadata.
\begin{groovy}{service}{org.lappsgrid.api.WebService}
interface WebService {
Data getMetadata()
Data execute(Data input)
Data configure(Data input)
}
\end{groovy}
% getMetadata
\subsubsection{Data getMetadata()}
The \tt{getMetadata()} method \should return a JSON-LD \payload with the \discriminator set to \ns{meta}. The metadata returned \should include at least the following information:
\begin{listing}
\item name
\item version
\item description
\item input requirements (if any),
\item output (if any)
\end{listing}
Section~\ref{sec:metadata} contains a complete description of the JSON-LD format for \lapps metadata.
%execute
\subsubsection{Data execute(Data input)}
Executes the language resource managed by this service.
If the input \data object's \discriminator is \ns{error} then the \service \must return the input object unchanged. If the input \data object's \discriminator is not set to one of the specified in the service's input requirements the service \should return an error object with the payload that starts with the string "Invalid input type."
%configure
\subsubsection{configure(Data input)}
This method is reserved for future use.
%*****************
% Media types
%*****************
\section{Media Types}\label{sec:media}
Discuss media types including the following:
\begin{enum}
\item \tt{text/plain}
\item \tt{text/plain; separator=(space|tab|newline|comma)}
\item \tt{text/plain; schema=<name>}
\item \tt{application/xml}
\item \tt{application/xml; schema=<name>}
\end{enum}
Other things to discuss:
\begin{enum}
\item Use of custom parameters
\begin{enum}
\item \tt{separator} for \tt{text/plain}
\item \tt{schema} for \tt{text/plain} and \tt{application/xml}
\end{enum}
\item \tt{charset} parameter ignored for all media types.
\end{enum}
% JSON-LD
\section{JSON-LD}\label{sec:json-ld}
Most of the time the content of the payload will be a JSON-LD document in the LAPPS Interchange Format (LIF).
\subsection{\lapps Interchange Format (LIF)}\label{sec:lif}
Infomation on JSON structures.
\subsection{Service Metadata}\label{sec:metadata}
Describe the JSON-LD metadata returned by the \tt{getMetadata()} method.
\section{Discriminators}\label{sec:discriminators}
\subsection{Media Types}
\input{media-types}
\subsection{License Types}\label{sub:licenses}
\input{license-types.tex}
\subsection{All Discriminators}\label{sub:discriminators}
\input{discriminators.tex}
\bibliographystyle{plain}
\bibliography{design}
\end{document}
|
"use client";
import { Dialog } from "primereact/dialog";
import React, { useEffect, useState } from "react";
import Content from "../TaskDetails/Content";
import LeftBar from "../TaskDetails/LeftBar";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { useFormik } from "formik";
import { Calendar } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";
import { InputTextarea } from "primereact/inputtextarea";
import {
addTask,
fetchFlags,
getAllBoardandTasks,
} from "@/services/serviceHelper";
import useSWR, { mutate } from "swr";
const TaskCreateModal = ({ createTaskModalOpen, setCreateTaskModalOpen }) => {
const [boardData2, setBoardData2] = useState(JSON.parse(localStorage.getItem("boardData")));
const [flags2, setFlags2] = useState(JSON.parse(localStorage.getItem("flags")));
const [boardName, setBoardName] = useState();
const [flagName, setFlagName] = useState();
const headerElement = (
<div className="inline-flex align-items-center justify-content-center gap-2 text-sm">
<h4>Add Task</h4>
</div>
);
const { data: boardData, error: boardError } = useSWR('/api/boards', async () => {
const response = await axios.get('/api/boards');
return response.data;
});
const { data: flags, error: flagsError } = useSWR('/api/flags', async () => {
const response = await axios.get('/api/flags');
return response.data;
});
const toggleVisibility = () => {
setCreateTaskModalOpen(!createTaskModalOpen); // state'i tersine çevir
};
const footerContent = <div></div>;
// const fetchBoarsAndTasks = async () => {
// const profile = JSON.parse(localStorage.getItem("Auth"));
// console.log(profile.data.token);
// try {
// const data = await getAllBoardandTasks(profile.data.token);
// const flagsData = await fetchFlags(profile.data.token);
// setBoardData(data.data);
// setFlags(flagsData.data);
// console.log(flagsData)
// } catch (error) {
// console.log(error);
// }
// };
// useEffect(() => {
// fetchBoarsAndTasks();
// }, []);
const formik = useFormik({
initialValues: {
name: "",
description: "",
boardId: 0,
flagId: 0,
startDate: "",
endDate: "",
},
onSubmit: async (values) => {
const profile = JSON.parse(localStorage.getItem("Auth"));
const token = profile.data.token;
try {
const userData = await addTask(token, values);
mutate('/api/boards');
mutate('/api/flags');
} catch (error) {
setError(error);
}
},
});
return (
<div className="card flex justify-content-center ">
<Dialog
closable
visible={createTaskModalOpen}
modal
header={headerElement}
footer={footerContent}
style={{ width: "30%", maxWidth: "400px", height: "full" }}
onHide={() => setCreateTaskModalOpen(false)}
>
<div className="flex w-full">
<form
onSubmit={formik.handleSubmit}
className="mt-10 w-full flex flex-col gap-4"
>
<div className="flex gap-2 justify-between">
<label for="name">Başlık</label>
<InputText
className=""
variant="filled"
id="name"
value={formik.values.name}
onChange={(e) => formik.setFieldValue("name", e.target.value)}
/>
</div>
<div className="flex gap-2 justify-between">
<label for="description">Açıklama</label>
<InputTextarea
className="w-60"
variant="filled"
id="description"
value={formik.values.description}
onChange={(e) =>
formik.setFieldValue("description", e.target.value)
}
rows={5}
cols={20}
/>
</div>
<div className="flex gap-2 justify-between items-center">
<label for="board">Board</label>
<Dropdown
id="board"
value={boardName}
onChange={(e) => (
setBoardName(e.target.value),
formik.setFieldValue("boardId", e.target.value.id)
)}
options={boardData2?.data}
optionLabel="name"
placeholder="Select a Board"
className=""
/>
</div>
<div className="flex gap-2 justify-between items-center">
<label for="flag">Flag</label>
<Dropdown
id="flag"
value={flagName}
onChange={(e) => (
setFlagName(e.target.value),
formik.setFieldValue("flagId", e.target.value.id)
)}
options={flags2?.data}
optionLabel="name"
placeholder="Select a Flag"
className=""
/>
</div>
<div className="flex gap-2 justify-between items-center">
<label for="startDate">Start Date</label>
<Calendar
id="startDate"
value={formik.values.startDate}
onChange={(e) => formik.setFieldValue("startDate", e.value)}
/>
</div>
<div className="flex gap-2 justify-between items-center">
<label for="endDate">End Date</label>
<Calendar
id="endDate"
value={formik.values.endDate}
onChange={(e) => formik.setFieldValue("endDate", e.value)}
/>
</div>
<Button
label="Kaydet"
icon="pi pi-check"
onClick={toggleVisibility}
autoFocus
type="submit"
/>
</form>
</div>
</Dialog>
</div>
);
};
export default TaskCreateModal;
|
import React from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
Row, Container, Col, Card, Image,
} from 'react-bootstrap';
import routes from '../../utilities/routes';
import LoginForm from './forms/LoginForm';
import logoImg from '../../assets/images/login.jpeg';
const LoginPage = () => {
const { t } = useTranslation();
return (
<Container fluid className="h-100">
<Row className="justify-content-center align-content-center h-100">
<Col className="col-12 col-md-8 col-xxl-6">
<Card className="shadow-sm">
<Card.Body className="d-flex flex-column flex-md-row justify-content-around align-items-center p-5">
<Image src={logoImg} roundedCircle alt="Войти" />
<LoginForm />
</Card.Body>
<Card.Footer className="p-4">
<div className="text-center">
<span>{t('pages.login.noExistingAccount')}</span>
<Link to={routes.signupPage()}>{t('pages.login.registration')}</Link>
</div>
</Card.Footer>
</Card>
</Col>
</Row>
</Container>
);
};
export default LoginPage;
|
<div class="register-form">
<h4>Register for new account</h4>
<form novalidate (ngSubmit)="onSubmit(registerForm)" #registerForm='ngForm'>
<div class="form-group">
<input type='text' autocomplete="off" name="name" required placeholder="User name" ngModel #name='ngModel'
class="form-control">
<div class="alert alert-danger" [hidden]="name.valid || name.pristine">Please enter your name</div>
</div>
<div class="form-group">
<input type='email' autocomplete="off" name="email" required placeholder="Email" ngModel #email='ngModel'
class="form-control">
<div class="alert alert-danger" [hidden]="email.valid || email.pristine">Please enter your email</div>
<div class="alert alert-danger" *ngIf="emailError">User with this Emailalready exsist</div>
</div>
<div class="form-group">
<input type="password" autocomplete="off" name="password" required placeholder="Password" ngModel
#password='ngModel' class="form-control">
<div class="alert alert-danger" [hidden]='password.valid || password.pristine'>Password is required
</div>
</div>
<div class="alert alert-danger" *ngIf="formError">{{formError}}</div>
<div *ngIf="!registering && !hasAdded">
<button routerLink='/sing-in' class="btn button-danger">Cancel</button>
<button [disabled]='registerForm.invalid' type="submit" class="btn btn-primary">Sing in</button>
</div>
<div *ngIf="registering && !hasAdded">
<span class="massege">Registering new user ...</span>
<span><img src='../../../assets/30.gif'></span>
</div>
<div *ngIf="hasAdded">
<span class="massege">New user added to database</span>
</div>
</form>
</div>
|
package service;
import domain.*;
import exceptions.CDNotFoundException;
import exceptions.RecordNotFoundException;
import java.util.*;
public class MusicService {
private Map<Integer, CD> cds;
private Map<Integer, Record> records;
public MusicService() {
this.cds = new HashMap<>();
this.records = new HashMap<>();
}
//add a CD to the collection
public void addCD(CD cd) {
if (this.cds.containsKey(cd.getId())) {
throw new IllegalArgumentException("CD with ID " + cd.getId() + " already exists in collection");
}
this.cds.put(cd.getId(), cd);
}
//add a record to the collection
public void addRecord(Record record) {
if (this.records.containsKey(record.getId())) {
throw new IllegalArgumentException("Record with ID " + record.getId() + " already exists in collection");
}
this.records.put(record.getId(), record);
}
//remove CD from the collection
public void removeCD(int cdId) {
if (!this.cds.containsKey(cdId)) {
throw new CDNotFoundException("CD with ID " + cdId + " not found in collection");
}
this.cds.remove(cdId);
}
//remove record from the collection
public void removeRecord(int recordId) {
if (!this.records.containsKey(recordId)) {
throw new RecordNotFoundException(recordId);
}
this.records.remove(recordId);
}
//searches CDs in collection
public List<CD> searchCDs(String query) {
List<CD> results = new ArrayList<>();
for (CD cd : this.cds.values()) {
if (cd.getTitle().toLowerCase().contains(query.toLowerCase()) ||
cd.getArtist().getName().toLowerCase().contains(query.toLowerCase())) {
results.add(cd);
}
}
return results;
}
//searches records in collection
public List<Record> searchRecords(String query) {
List<Record> results = new ArrayList<>();
for (Record record : this.records.values()) {
if (record.getTitle().toLowerCase().contains(query.toLowerCase()) ||
record.getArtist().getName().toLowerCase().contains(query.toLowerCase())) {
results.add(record);
}
}
return results;
}
//returns all CDs in the collection
public List<CD> getAllCDs() {
return new ArrayList<>(this.cds.values());
}
//returns all records in the collection
public List<Record> getAllRecords() {
return new ArrayList<>(this.records.values());
}
//returns CD by id
public CD getCDById(int cdId) throws CDNotFoundException {
if (!this.cds.containsKey(cdId)) {
throw new CDNotFoundException("CD with ID " + cdId + " not found in collection");
}
return this.cds.get(cdId);
}
//returns record by id
public Record getRecordById(int recordId) throws RecordNotFoundException {
if (!this.records.containsKey(recordId)) {
throw new RecordNotFoundException(recordId);
}
return this.records.get(recordId);
}
//returns CDs by artist
public List<CD> getCDsByArtist(Author artist) {
List<CD> results = new ArrayList<>();
for (CD cd : this.cds.values()) {
if (cd.getArtist().equals(artist)) {
results.add(cd);
}
}
return results;
}
public void printCD(int id) {
CD cd = getCDById(id);
System.out.println(cd.toString());
}
public void printRecord(int id) {
Record record = getRecordById(id);
System.out.println(record.toString());
}
}
|
import React from 'react'
import {useEffect, useState} from 'react'
import { getAllArticlesHome } from '../utils/api'
import { Link } from 'react-router-dom'
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import '../styles/_homer.scss'
import Slide from './slide'
function Home({sortBy, setSortBy, orderBy, setOrderBy}) {
const [allArticles, setAllArticles] = useState([])
useEffect(() => {
getAllArticlesHome(sortBy, orderBy)
.then(({data : {articles}}) => {
setAllArticles(articles)
})
.catch((err) => {
console.log(err);
})
}, [sortBy, orderBy])
return (
<main className='container-home'>
<h3>HOME</h3>
Sort By:
<button className='btn' onClick={() => setSortBy('title')}> title</button>
<button className='btn' onClick={() => setSortBy('votes')}> votes</button>
<button className='btn' onClick={() => setSortBy('created_at')}> date</button>
Order:
<button className='btn' onClick={() => setOrderBy('asc')}>asending</button>
<button className='btn' onClick={() => setOrderBy('desc')}>descending</button>
<div classsName='row'>
<br></br>
<div className='slider'>
<Slide allArticles={allArticles}/>
</div>
<br></br>
<br></br>
<ul className='gridcheck'>
<div className='wrapper'>
{allArticles.map((article) => {
return (
<div className='griddy'>
<li key={article.article_id} classsName="main-list-items">
<div className='overlay'>
<Link className="title" to={`/articles/${article.article_id}`}>
{article.title}
</Link>
<br></br>
<Link className="topic" to={`/topics/${article.topic}`}>
{article.topic}
</Link>
<br></br>
<p classname="author">
by {article.author}
</p>
<br></br>
</div>
<img classname="box" src={article.article_img_url} alt={article.title}></img>
<p>Votes :{article.votes} | Comments: {article.comment_count} </p>
</li>
</div>
)
})}
</div>
</ul>
</div>
</main>
)
}
export default Home
|
/*
* (c) Copyright 2015-2017 Micro Focus or one of its affiliates.
*
* Licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are as may be set forth in the express warranty
* statements accompanying such products and services. Nothing herein should be
* construed as constituting an additional warranty. Micro Focus shall not be
* liable for technical or editorial errors or omissions contained herein. The
* information contained herein is subject to change without notice.
*/
define([
'backbone',
'src/to-field-text-node'
], function(Backbone, toFieldTextNode) {
'use strict';
describe('toFieldTextNode', function() {
beforeEach(function() {
this.parametricValues = [
{field: 'NAME', value: 'penny'},
{field: 'NAME', value: 'bob'},
{field: 'FRIEND', value: 'penny'},
{field: 'AGE', value: '25'},
{field: 'YEAR', range: [1307, 1327], type: 'Numeric'}
];
});
it('returns a field text node representing the collection', function() {
this.parametricValues.push({field: 'DATE', range: [123456789000, 123456790000]});
var fieldText = toFieldTextNode(this.parametricValues).toString();
expect(fieldText).toContain('MATCH{25}:AGE');
expect(fieldText).toContain('MATCH{penny}:FRIEND');
expect(fieldText).toContain('NRANGE{1307,1327}:YEAR');
expect(fieldText).toContain('RANGE{1973-11-29T21:33:09Z,1973-11-29T21:33:10Z}:DATE');
});
it('treats 1 BC as year 0', function() {
this.parametricValues.push({
field: 'DATE',
range: [
-1971 * 365 * 24 * 3600 * 1000,
-1941 * 365 * 24 * 3600 * 1000
]
});
var fieldText = toFieldTextNode(this.parametricValues).toString();
expect(fieldText).toContain('MATCH{25}:AGE');
expect(fieldText).toContain('MATCH{penny}:FRIEND');
expect(fieldText).toContain('NRANGE{1307,1327}:YEAR');
expect(fieldText).toContain('0000');
});
it('returns null for an empty collection', function() {
expect(toFieldTextNode([])).toBeNull();
});
});
});
|
import * as RadioGroup from "@radix-ui/react-radio-group";
import { twMerge } from "tailwind-merge";
export function HorizontalRadio({
options,
value,
onValueChange,
rootClass = "",
itemClass = "",
}: {
options: {
displayText: string;
value: string;
disabled?: boolean;
}[];
onValueChange: (value: string) => void;
value: string;
rootClass?: string;
itemClass?: string;
}) {
return (
<RadioGroup.Root onValueChange={onValueChange} className={twMerge("flex", rootClass)}>
{options.map((e, i) => {
const selected = value === e.value;
return (
<RadioGroup.Item
disabled={e.disabled}
value={e.value}
key={`Carousel_Dot_${i}`}
className={twMerge(
`m-1 h-10 w-32 ${
selected
? `bg-brandBlue text-white`
: `bg-base-4-light hover:bg-base-6-light dark:bg-base-3-dark hover:dark:bg-base-4-dark`
} font-fancy rounded-full font-bold transition-colors duration-200`,
itemClass
)}
>
<RadioGroup.Indicator />
<span>{e.displayText}</span>
</RadioGroup.Item>
);
})}
</RadioGroup.Root>
);
}
|
import {Component, OnInit} from '@angular/core';
import {ClientService} from "../../../services/client.service";
import {MessageService} from "primeng/api";
import {StringUtils} from "../../../utils/StringUtils";
import {ClientDto} from "../../../models/ClientDto.model";
@Component({
selector: 'app-edit-client',
templateUrl: './edit-client.component.html',
styleUrls: ['./edit-client.component.css']
})
export class EditClientComponent implements OnInit{
private _validClientFirstName: boolean = true;
private _validClientLastName: boolean = true;
private _validClientPhoneNumber: boolean = true;
private _validClientEmail: boolean = true;
constructor(private clientService: ClientService,
private messageService:MessageService) {
}
ngOnInit(): void {
}
public edit() {
this.validateForm();
if (this.errorMessages.length === 0) {
this.clientService.edit(this.client).subscribe({
next: (client) => {
const myIndex = this.clients.findIndex(a => a.id === this.client.id);
this.clients[myIndex] = client;
this.editDialog = false;
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Client Updated Successfully'});
},
error: (err) => {
console.log(err);
}
}
);
}
}
private validateForm() {
this.errorMessages = new Array<string>();
this.validateFirstName();
this.validateLastName();
this.validateEmail();
this.validatePhoneNumber();
}
public validateFirstName() {
if (StringUtils.isEmpty(this.client.firstName)) {
this.errorMessages.push('First Name not valid');
this.validClientFirstName = false;
} else {
this.validClientFirstName = true;
}
}
public validateLastName() {
if (StringUtils.isEmpty(this.client.lastName)) {
this.errorMessages.push('Last Name not valid');
this.validClientLastName = false;
}
this.validClientLastName = true;
}
public validateEmail() {
if (StringUtils.isEmpty(this.client.email)) {
this.errorMessages.push('Email not valid');
this.validClientEmail = false;
} else {
this.validClientEmail = true;
}
}
public validatePhoneNumber() {
if (StringUtils.isEmpty(this.client.phoneNumber)) {
this.errorMessages.push('Phone Number not valid');
this.validClientPhoneNumber = false;
} else {
this.validClientPhoneNumber = true;
}
}
hideCreateDialog() {
this.editDialog = false;
}
get editDialog() {
return this.clientService.editDialog
}
set editDialog(value: boolean) {
this.clientService.editDialog = value
}
get validClientFirstName(): boolean {
return this._validClientFirstName;
}
set validClientFirstName(value: boolean) {
this._validClientFirstName = value;
}
get validClientLastName(): boolean {
return this._validClientLastName;
}
set validClientLastName(value: boolean) {
this._validClientLastName = value;
}
get validClientPhoneNumber(): boolean {
return this._validClientPhoneNumber;
}
set validClientPhoneNumber(value: boolean) {
this._validClientPhoneNumber = value;
}
get validClientEmail(): boolean {
return this._validClientEmail;
}
set validClientEmail(value: boolean) {
this._validClientEmail = value;
}
get client(): ClientDto {
return this.clientService.client;
}
set client(value: ClientDto) {
this.clientService.client = value;
}
get clients(): Array<ClientDto> {
return this.clientService.clients;
}
set clients(value: Array<ClientDto>) {
this.clientService.clients = value;
}
get errorMessages(): Array<string> {
return this.clientService.errorMessages;
}
set errorMessages(value: Array<string>) {
this.clientService.errorMessages = value;
}
get selectedClient(): ClientDto {
return this.clientService.selectedClient;
}
set selectedClient(value: ClientDto) {
this.clientService.selectedClient = value;
}
}
|
//
// ScrollableMoviesCollectionViewCell.swift
// KodeTestApp
//
// Created by Георгий Попандопуло on 08.02.2022.
//
import UIKit
import SnapKit
final class ScrollableMoviesCollectionViewCell: UICollectionViewCell {
// MARK: - Private Properties
private var viewModel: ViewModel?
private let mainImageView = UIImageView()
private let movieTitleLabel = UILabel()
private let movieDescriptionLabel = UILabel()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: .zero)
setupConstraints()
configureImageView()
backgroundColor = .black
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Internal Methods
func configure(viewModel: ViewModel) {
self.viewModel = viewModel
updateUI()
}
}
// MARK: - Private Methods
private extension ScrollableMoviesCollectionViewCell {
func setupConstraints() {
contentView.addSubview(mainImageView)
contentView.addSubview(movieTitleLabel)
contentView.addSubview(movieDescriptionLabel)
mainImageView.snp.makeConstraints { make in
make.top.left.right.equalToSuperview()
}
movieTitleLabel.snp.makeConstraints { make in
make.top.equalTo(mainImageView.snp.bottom).offset(1)
make.left.right.equalToSuperview()
make.bottom.equalToSuperview().offset(-30)
}
movieDescriptionLabel.snp.makeConstraints { make in
make.top.equalTo(movieTitleLabel.snp.bottom).offset(1)
make.left.right.equalToSuperview()
make.bottom.equalToSuperview().offset(-10)
}
}
func configureImageView() {
mainImageView.layer.cornerRadius = 10
}
func updateUI() {
guard let viewModel = viewModel else { return }
movieTitleLabel.textColor = .white
movieDescriptionLabel.textColor = .white
movieTitleLabel.textAlignment = .center
movieDescriptionLabel.textAlignment = .center
mainImageView.image = viewModel.image
movieTitleLabel.text = viewModel.title
movieDescriptionLabel.text = viewModel.description
}
}
// MARK: - ViewModel
extension ScrollableMoviesCollectionViewCell {
struct ViewModel {
let image: UIImage
let title: String
let description: String
}
}
|
<template>
//固定列和
<el-row justify="space-between">
<div>
<el-button type="primary">添加</el-button>
<el-button type="danger">批量删除</el-button>
</div>
<el-button-group class="ml-4">
<!-- 筛选列 todo 绑定表格事件-->
<el-popover placement="bottom-end" :width="100" trigger="hover">
<template #reference>
<el-button type="primary" :icon="Edit" title="筛选列"/>
</template>
<el-table :data="tableHead" >
<el-table-column type="selection" property="选择" width="30" />
<!-- todo property 改成是父组件传过来的tableHead name-->
<el-table-column width="100" property="name" />
</el-table>
</el-popover>
<el-button type="primary" :icon="Film" title="导出"/>
<el-button type="primary" :icon="Printer" title="打印"/>
</el-button-group>
</el-row>
<div id="fromMain">
<el-table :data="tableDataFromFather" max-height="450">
<el-table-column fixed="left" type="selection"/>
<el-table-column v-for="item in tableHead" :key="item.id" :prop="item.id" :label="item.name"></el-table-column>
<el-table-column fixed="right" label="Operations" width="120">
<template #default>
<el-button link type="primary" size="small" @click="handleClick"
>编辑</el-button
>
<el-button link type="primary" size="small">删除</el-button>
</template>
</el-table-column>
</el-table>
<div id="formChild">
<!-- 分页组件-->
<el-pagination
v-model:current-page="currentPage1"
:page-size="10"
layout="total, prev, pager, next"
:total="1000"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
style="margin-top: 20px"
/>
</div>
</div>
</template>
<script setup lang="ts">
import {ref} from "vue";
import user from "../System management/User.vue";
import {Delete, Edit, Film, Printer, Share} from "@element-plus/icons-vue";
const handleClick = () => {
console.log('click')
}
// 1.请求接口拿到数据
// 2.将数据存到MockData中
// 3.动态渲染
const MockData = ref([])
// 分页逻辑
const currentPage1 = ref(5)
const handleSizeChange = (val: number) => {
console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
console.log(`current page: ${val}`)
}
// 模拟父组件传来的数据
const tableHead= [
{
id:'id',
name:'身份证'
},
{
id:'name',
name:'姓名'
},
{
id:'location',
name:'地址'
},
{
id:'tel',
name:'电话'
},
]
const tableDataFromFather = [
{
id:'123',
name:'chan',
location:'daz',
tel:'123434'
},
{
id:'1234',
name:'ying',
location:'dwez',
tel:'123eqer4'
},
{
id:'1234',
name:'ying',
location:'dwez',
tel:'123eqer4'
},
{
id:'1234',
name:'ying',
location:'dwez',
tel:'123eqer4'
},
]
// {
// date: '2016-05-07',
// name: 'Tom',
// state: 'California',
// city: 'Los Angeles',
// address: 'No. 189, Grove St, Los Angeles',
// zip: 'CA 90036',
// },]
</script>
<style scoped>
#fromMain{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>
|
from flask import Flask, render_template, request, send_from_directory
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'pdf'}
class UploadForm(FlaskForm):
file = FileField(validators=[FileRequired(), FileAllowed(['pdf'], 'PDFs only!')])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
@app.route('/', methods=['GET', 'POST'])
def index():
form = UploadForm()
if form.validate_on_submit():
file = form.file.data
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], 'latest.pdf'))
return render_template('success.html')
return render_template('index.html', form=form)
@app.route('/view-pdf')
def view_pdf():
return send_from_directory(app.config['UPLOAD_FOLDER'], 'latest.pdf')
if __name__ == '__main__':
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
app.run(debug=True)
|
docs.netapp.com
Active IQ Unified Manager 9.13
Modifying storage workloads by using APIs
03/15/2022
Contributors
Modifying storage workloads consists of updating LUNs or file shares with missing parameters, or changing the existing parameters.
This workflow takes the example of updating Performance Service Levels for LUNs and file shares.
The workflow assumes that the LUN or file share has been provisioned with Performance Service Levels.
Modifying file shares
While modifying a file share, you can update the following parameters:
Capacity or size.
Online or offline setting.
Storage Efficiency Policy.
Performance Service Level.
Access control list (ACL) settings.
Export policy settings. You can also delete export policy parameters and revert the default (empty) export policy rules on the file share.
During a single API run, you can update only one parameter.
This procedure describes adding a Performance Service Level to a file share. You can use the same procedure for updating any other file share property.
Obtain the CIFS share or NFS file share key of the file share that you want to update. This API queries all the file shares on your data center. Skip this step if you already know the file share key.
Category
HTTP verb
Path
storage-provider
GET
/storage-provider/file-shares
View the details of the file share by running the following API with the file share key that you obtained.
Category
HTTP verb
Path
storage-provider
GET
/storage-provider/file-shares/{key}
View the details of the file share in the output.
"assigned_performance_service_level": {
"key": null,
"name": "Unassigned",
"peak_iops": null,
"expected_iops": null,
"_links": {}
},
Obtain the key for the Performance Service Level that you want to assign on this file share. Currently no policy is assigned to it.
Category
HTTP verb
Path
Performance Service Levels
GET
/storage-provider/performance-service-levels
You can retrieve the details of the system-defined Performance Service Levels by setting the system_defined input parameter to true. From the output, obtain the key of the Performance Service Level that you want to apply to the file share.
Apply the Performance Service Level on the file share.
Category
HTTP verb
Path
Storage Provider
PATCH
/storage-provider/file-shares/{key}
In the input, you must specify only the parameter that you want to update, along with the file share key. In this case, it is the key of the Performance Service Level.
Sample cURL
curl -X POST "https://<hostname>/api/storage-provider/file-shares"`-H "accept: application/json" -H "Authorization: Basic <Base64EncodedCredentials>" -d
"{
\"performance_service_level\": { \"key\": \"1251e51b-069f-11ea-980d-fa163e82bbf2\" },
}"
The JSON output displays a Job object that you can use to verify the whether the access endpoints on the home and partner nodes have been created successfully.
Verify whether the Performance Service Level has been added to the file share by using the Job object key displayed in your output.
Category
HTTP verb
Path
Management Server
GET
/management-server/jobs/{key}
If you query by the ID of the Job object, you see whether the file share is updated successfully. In case of a failure, troubleshoot the failure and run the API again. On successful creation, query the file share to see the modified object:
Category
HTTP verb
Path
storage-provider
GET
/storage-provider/file-shares/{key}
View the details of the file share in the output.
"assigned_performance_service_level": {
"key": "1251e51b-069f-11ea-980d-fa163e82bbf2",
"name": "Value",
"peak_iops": 75,
"expected_iops": 75,
"_links": {
"self": {
"href": "/api/storage-provider/performance-service-levels/1251e51b-069f-11ea-980d-fa163e82bbf2"
}
}
Updating LUNs
While updating a LUN, you can modify the following parameters:
Capacity or size
Online or offline setting
Storage Efficiency Policy
Performance Service Level
LUN map
During a single API run, you can update only one parameter.
This procedure describes adding a Performance Service Level to a LUN. You can use the same procedure for updating any other LUN property.
Obtain the LUN key of the LUN that you want to update. This API returns details of all the LUNS in your data center. Skip this step if you already know the LUN key.
Category
HTTP verb
Path
Storage Provider
GET
/storage-provider/luns
View the details of the LUN by running the following API with the LUN key that you obtained.
Category
HTTP verb
Path
Storage Provider
GET
/storage-provider/luns/{key}
View the details of the LUN in the output. You can see that there is no Performance Service Level assigned to this LUN.
Sample JSON output
"assigned_performance_service_level": {
"key": null,
"name": "Unassigned",
"peak_iops": null,
"expected_iops": null,
"_links": {}
},
Obtain the key for the Performance Service Level that you want to assign to the LUN.
Category
HTTP verb
Path
Performance Service Levels
GET
/storage-provider/performance-service-levels
You can retrieve the details of the system-defined Performance Service Levels by setting the system_defined input parameter to true. From the output, obtain the key of the Performance Service Level that you want to apply on the LUN.
Apply the Performance Service Level on the LUN.
Category
HTTP verb
Path
Storage Provider
PATCH
/storage-provider/lun/{key}
In the input, you must specify only the parameter that you want to update, along with the LUN key. In this case it is the key of the Performance Service Level.
Sample cURL
curl -X PATCH "https://<hostname>/api/storage-provider/luns/7d5a59b3-953a-11e8-8857-00a098dcc959" -H "accept: application/json" -H "Content-Type: application/json" H "Authorization: Basic <Base64EncodedCredentials>" -d
"{ \"performance_service_level\": { \"key\": \"1251e51b-069f-11ea-980d-fa163e82bbf2\" }"
The JSON output displays a Job object key that you can use to verify the LUN that you updated.
View the details of the LUN by running the following API with the LUN key that you obtained.
Category
HTTP verb
Path
Storage Provider
GET
/storage-provider/luns/{key}
View the details of the LUN in the output. You can see that the Performance Service Level is assigned to this LUN.
Sample JSON output
"assigned_performance_service_level": {
"key": "1251e51b-069f-11ea-980d-fa163e82bbf2",
"name": "Value",
"peak_iops": 75,
"expected_iops": 75,
"_links": {
"self": {
"href": "/api/storage-provider/performance-service-levels/1251e51b-069f-11ea-980d-fa163e82bbf2"
}
|
import { Knex } from 'knex';
async function createUsers(knex: Knex) {
return knex.schema.createTable('users', (table) => {
table.increments('id');
table.string('email', 255).notNullable();
table.string('username', 255).notNullable();
table.dateTime('created_at').notNullable();
});
}
async function createProject(knex: Knex) {
return knex.schema.createTable('project', (table) => {
table.increments('id');
table.string('name', 255).notNullable();
table.string('url', 255);
table.integer('user_id').notNullable();
table.string('app_secret', 255).notNullable();
table.dateTime('created_at').notNullable();
});
}
async function createDeployment(knex: Knex) {
return knex.schema.createTable('deployment', (table) => {
table.enum('status', ['pending', 'building', 'deploying', 'failed', 'cancelled', 'done']);
table.increments('id');
table.integer('project_id');
table.integer('deployed_in', 255).notNullable();
table.dateTime('created_at').notNullable();
});
}
export async function up(knex: Knex) {
await createUsers(knex);
await createProject(knex);
await createDeployment(knex);
}
export async function down(knex: Knex) {
await knex.schema.dropTable('users');
await knex.schema.dropTable('project');
await knex.schema.dropTable('deployment');
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User profile</title>
<!-- Icons for the sidebar -->
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
{% load static %}
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap"
rel="stylesheet">
<link rel="stylesheet"
href="{% static 'card/css/sidebar.css' %}">
<link rel="stylesheet"
href="{% static 'card/css/card_detail.css' %}">
<link rel="stylesheet"
href="{% static 'card/css/card_index.css' %}">
<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
</head>
<body>
<div class="flex-container" style="display:flex; height: 100%; height: 100vh;">
<div class="left-flex-container">
{% include 'site_sidebar.html' %}
</div>
<div class="right-flex-container mt-5" style="width: 100%; display:flex; flex-direction: column; align-items: flex-start; padding: 20px;">
<div class="site-border-style page-container p-3">
<h1 class="pt-2">Your Profile:</h1>
{% if user.is_authenticated %}
<p class="mt-3" style="font-size: 1.2em;">Username: <strong>{{ user.username }}</strong></p>
<p class="mt-3" style="font-size: 1.2em;">Email: <strong>{{ user_profile.email }}</strong></p>
<p class="mt-3" style="font-size: 1.2em;">Current grade: <strong>{{ user_profile.grade}}</strong></p>
<div class="d-flex" style="align-items:center;">
<p style="font-size: 1.2em; margin:0;">Your learning lanaguage:</strong></p>
<div class="dropdown ml-3">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
{{ user_profile.get_target_lan_display }}
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
{% for lan, language in lan_choices %}
<li>
<a class="dropdown-item {% if user_profile.target_lan == abbreviation %}active{% endif %}" data-lan={{lan}}>{{language}}</a>
</li>
{% endfor %}
</ul>
</div>
</div>
<br>
<a href="{% url 'logout' %}">Log out</a>
{% else %}
<p class="mt-3" style="font-size: 1.2em;">You are not logged in.</p>
{% endif %}
</div>
</div>
</div>
<!-- Bootstrap 5 JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.dropdown-item').click(function() {
var newLan = $(this).data('lan');
var newLanuage = $(this).text();
$.post('/user/update', {target_lan: newLan}, function(data) {
if (data.status == 'ok') {
$('.dropdown-item').removeClass('active');
// Add 'active' class to the clicked dropdown item
$(this).addClass('active');
// Update the dropdown button text
$('#dropdownMenuButton1').text(newLanuage);
} else {
alert('Error updating language');
}
});
});
});
</script>
</html>
|
<template>
<div class="btn-group">
<div class="col-md-6">
<button type="button" class="btn btn-primary" @click="btnEdit" data-bs-toggle="modal" :data-bs-target="'#'+idModalEdit+row.id">Edit</button>
</div>
<div class="col-md-6">
<button type="button" class="btn btn-danger" data-bs-toggle="modal" :data-bs-target="'#'+idModalDelete+row.id">Delete</button>
</div>
</div>
<div class="modal fade" :id="idModalEdit+row.id" tabindex="-1" role="dialog"
aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<form @submit.prevent="updateInventoryItem">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Edit Inventory
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<label for="nama_barang">Nama Barang</label>
<input type="text" class="form-control" id="nama_barang" name="nama_barang"
placeholder="Nama Barang" v-model="formData.nama_barang" required>
<div class="valid-feedback">
<i class="bx bx-radio-circle"></i>
Valid
</div>
</div>
<div class="col-md-12">
<label for="harga">Harga</label>
<input type="number" class="form-control" id="harga" name="harga"
placeholder="Harga Barang" v-model="formData.harga"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
required>
<div class="valid-feedback">
<i class="bx bx-radio-circle"></i>
Valid
</div>
</div>
<div class="col-md-12">
<label for="stok">Stok</label>
<input type="number" class="form-control" id="stok" name="stok" placeholder="Stok Barang"
v-model="formData.stok"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
required>
<div class="valid-feedback">
<i class="bx bx-radio-circle"></i>
Valid
</div>
</div>
<input type="hidden" class="form-control" id="id" name="id">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-bs-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">Close</span>
</button>
<button type="submit" class="btn btn-primary ml-1">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">Update</span>
</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" :id="idModalDelete+row.id" tabindex="-1" role="dialog"
aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Delete Data
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<p>Hapus data ?</p>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-bs-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">Close</span>
</button>
<button type="button" class="btn btn-danger ml-1">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block" @click="btnDelete">Delete</span>
</button>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
import Swal from 'sweetalert2'
// import Vue from 'vue';
// Vue.forceUpdate();
export default {
name: 'buttons',
props: {
row: Object,
column: Object
},
data () {
return {
idModalEdit: "editModal",
idModalDelete: "deleteModal",
dataProduct: {},
formData :{
id: "",
nama_barang: "",
harga: "",
stok: "",
},
nama_barang: "wkwkwk",
formDeleteData :{
id_delete: "",
}
}
},
methods: {
// fireEditBtn(){
// let product_id = this.row.id
// this.$emit('fireEdit', product_id)
// console.log(this.row.id)
// },
updateInventoryItem(){
const token = localStorage.getItem('token')
axios
.get('https://api.farhandika.com/sanctum/csrf-cookie')
.then(response => {
console.log(response)
axios
.request({
url: 'https://api.farhandika.com/api/product-update',
method: 'post',
data: this.formData,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer '+token,
}
})
.then((response) => {
console.log(response);
Swal.fire("Berhasil Update !")
this.$router.go()
})
.catch((error) => {
console.log(error.message)
Swal.fire("gagal update !")
})
})
},
btnEdit(){
// alert(`Edit ${this.row.id}`)
const token = localStorage.getItem('token')
axios
.request({
url: 'https://api.farhandika.com/api/get-single-data-product/'+this.row.id,
method: 'get',
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer '+token,
}
})
.then((response) => {
// console.log(response)
this.dataProduct = response.data
this.formData.nama_barang = this.dataProduct.data[0].nama_barang
this.formData.harga = this.dataProduct.data[0].harga
this.formData.stok = this.dataProduct.data[0].stok
this.formData.id = this.row.id
console.log(this.dataProduct)
console.log(this.nama_barang)
// Swal.fire("berhasil !")
})
.catch((error) => {
console.log(error.message)
// Swal.fire("Error update !!")
})
},
btnDelete(){
const token = localStorage.getItem('token')
this.formDeleteData.id_delete = this.row.id
axios
.get('https://api.farhandika.com/sanctum/csrf-cookie')
.then(response => {
console.log(response)
axios
.request({
url: 'https://api.farhandika.com/api/product-delete',
method: 'post',
data: this.formDeleteData,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer '+token,
}
})
.then((response) => {
console.log(response);
Swal.fire("Berhasil Delete !")
this.$router.go()
})
.catch((error) => {
console.log(error.message)
Swal.fire("Failed to delete !")
})
})
}
}
}
</script>
<style scoped>
</style>
|
using Plots
function calculate_confusion_matrix(y_pred, y_true, threshold)
@show length(y_pred)
@show length(y_true)
binary_predictions = Int.(y_pred .> threshold)
binary_actual = Int.(y_true .> threshold)
true_positives = sum((binary_predictions .== 1) .& (binary_actual .== 1))
false_positives = sum((binary_predictions .== 1) .& (binary_actual .== 0))
true_negatives = sum((binary_predictions .== 0) .& (binary_actual .== 0))
false_negatives = sum((binary_predictions .== 0) .& (binary_actual .== 1))
confusion_matrix = [true_negatives false_negatives;
false_positives true_positives]
accuracy = (true_positives + true_negatives) / length(y_true)
specificity = true_negatives / (true_negatives + false_positives)
sensitivity = true_positives / (true_positives + false_negatives)
return confusion_matrix, accuracy, specificity, sensitivity
end
function plot_and_save_heatmap(confusion_matrix, title, filename;
savePlot=true,
saveLocation="processedData/")
heatmap_plot = Plots.heatmap(["Actual Negative", "Actual Positive"],
["Predicted Negative", "Predicted Positive"],
confusion_matrix, color=:blues, aspect_ratio=1,
title=title)
if savePlot
save_path = joinpath(saveLocation, filename)
Plots.savefig(heatmap_plot, save_path)
end
end
function check_training_accuracy(res;
threshold=0.5,
plotHeatMap=true,
savePlot=true,
saveLocation="processedData/")
pr = res.pr
p = pr.p
obj = pr.objective
w_trained = res.xvals[:, end]
classify = true
# params = p[:params]
params = p
params[:classify] = classify
y_pred_tr = vec(obj(w_trained, p))
y_tr = params[:classData]
confusion_matrix_tr, accuracy, specificity, sensitivity = calculate_confusion_matrix(y_pred_tr, y_tr, threshold)
println("Training Data:\n"*"Accuracy: $accuracy\n"*"Specificity: $specificity\n"*"Sensitivity: $sensitivity")
if plotHeatMap
plot_and_save_heatmap(confusion_matrix_tr, "Fit of FFNN on the Training Data", "training_data_heatmap.png", savePlot=savePlot, saveLocation=saveLocation)
end
end
function check_test_accuracy(res;
threshold=0.5,
plotHeatMap=true,
savePlot=true,
saveLocation="processedData/")
pr = res.pr
p = pr.p
obj = pr.objective
w_trained = res.xvals[:, end]
classify = true
# params = p[:params]
params = p
params[:classify] = classify
testData = params[:testData]
testClassData = params[:testClassData]
params[:trainData] = testData
params[:classData] = testClassData
# p[:params] = params
y_pred_test = vec(obj(w_trained, p))
y_test = params[:classData]
confusion_matrix_test, accuracy_test, specificity_test, sensitivity_test = calculate_confusion_matrix(y_pred_test, y_test, threshold)
println(
"Testing Data:\n"*
"Accuracy: $(accuracy_test)\n"*
"Specificity: $(specificity_test)\n"
*"Sensitivity: $(sensitivity_test)"
)
if plotHeatMap
plot_and_save_heatmap(confusion_matrix_test, "Fit of FFNN on the Testing Data", "testing_data_heatmap.png", savePlot=savePlot, saveLocation=saveLocation)
end
end
|
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.Stack;
/**
* <p>
* Car hauler can load and unload cars to its stack if the ramp is down.
* When the car hauler moves the cars in its stack move aswell.
* The position of the ramp can't change while moving.
* </p>
*
*/
public class CarHauler extends Car {
private boolean rampUp;
private int capacity;
private Stack<Car> cars;
/**
* sets number of doors, color, Engine power, size and if ramp is up or down. Also initiates a stack with a max capacity.
* @param capacity The max capacity of the car hauler
*/
public CarHauler(int capacity) {
this.capacity = capacity;
setNrDoors(2);
setColor(Color.blue);
setEnginePower(400);
setSize(2);
rampUp = true;
cars = new Stack<>();
}
/**
* Returns a standard speed factor.
* @return the speed factor of the Hauler.
*/
@Override
public double speedFactor() {
return getEnginePower() * 0.05;
}
/**
* Adds car to the stack if there is space on the car hauler, the ramp is up and the car is close to the car hauler
* @param car Car to be loaded
*/
public void loadCar(Car car) {
if (cars.size() < capacity && !rampUp && car.getSize() < 2 && getPosition().distance(car.getPosition()) < 4) {
car.setPosition(getPosition());
cars.push(car);
}
car.setDir(getDir());
}
/**
* Unloads the most recently loaded car 1 unit of length behind the hauler.
*/
public void unloadCar() {
if (!rampUp) {
Car car = cars.pop();
switch (getDir()) {
case NORTH: car.setPosition(new Point2D.Double(getPosition().x, getPosition().y + 1)); break;
case WEST: car.setPosition(new Point2D.Double(getPosition().x + 1, getPosition().y)); break;
case SOUTH: car.setPosition(new Point2D.Double(getPosition().x, getPosition().y - 1)); break;
case EAST: car.setPosition(new Point2D.Double(getPosition().x - 1, getPosition().y)); break;
}
}
}
/**
* Sets ramp to state "up"
*/
public void setRampUp(){
rampUp=true;
}
/**
* Ramp is lowered only if hauler is stationary.
*/
public void setRampDown(){
if(getCurrentSpeed()==0)
rampUp = false;
}
/**
* Car objects on hauler get same position as hauler.
*/
@Override
public void move() {
super.move();
for (Car car : cars) {
car.setPosition(getPosition());
}
}
/**
* Car object turns right when hauler turns right.
*/
@Override
public void turnRight(){
super.turnRight();
for (Car car : cars) {
car.turnRight();
}
}
/**
* Car object turns left when hauler turns left.
*/
@Override
public void turnLeft(){
super.turnLeft();
for (Car car : cars) {
car.turnLeft();
}
}
/**
* Ensures hauler can only set a speed if the ramp is up.
* @param amount
*/
@Override
public void setCurrentSpeed(double amount) {
if (rampUp)
super.setCurrentSpeed(amount);
}
}
|
/* eslint-disable react/prop-types */
import data from '../data'
import Typed from "typed.js";
import { useEffect, useRef } from "react";
import { Button } from 'flowbite-react';
import { BsArrowRight } from 'react-icons/bs'
import { LiaLinkSolid } from 'react-icons/lia'
import { PiMapPinLineDuotone } from 'react-icons/pi'
import { useDarkMode } from '../DarkModeContext';
const AboutCard = ({
showPhotoSmallScreen = true,
}) => {
const {
name,
description,
photo,
contact,
socials,
} = data
const typedRef = useRef(null)
useEffect(() => {
const typed = new Typed(typedRef.current, {
strings: [
'a <span class="medium-text-color">Student</span>',
'a <span class="medium-text-color">Banker</span>',
'a <span class="medium-text-color">Developer</span>',
`<span class="medium-text-color">${name.split(" ")[0]}</span> 👋`
],
startDelay: 500,
typeSpeed: 100,
backSpeed: 100,
backDelay: 100,
showCursor: true,
smartBackspace: true,
onComplete: (self) => {
self.cursor.remove(); // Remove the cursor when typing is complete
},
})
return () => typed.destroy()
}, [name])
const { isDarkMode } = useDarkMode()
const splitSocials = (arr, size = 3) => {
const split = []
for (let i = 0; i < arr.length; i += size) {
split.push(arr.slice(i, i + size))
}
return split
}
const newSocials = splitSocials(socials)
return (
<div>
{
showPhotoSmallScreen && (
<div className="block lg:hidden bg-neutral-600 w-full rounded-2xl mb-5">
<img src={photo} alt="Profile Picture" className="w-40 mx-auto rounded-2xl" />
</div>
)
}
<div className="font-bold mb-5 lg:ms-7 text-center lg:text-left text-sm md:text-base">About Me</div>
<div className="flex md:flex-row flex-col gap-7">
<div className={`${isDarkMode ? 'bg-neutral-600' : 'bg-white'} p-7 rounded-3xl w-full lg:w-1/2`}> {/** Left Column */}
<div className="flex h-full ">
<div className="w-full flex flex-col gap-7 text-center lg:text-left h-full justify-between items-center lg:items-start">
<div className={`${isDarkMode ? 'text-neutral-200' : 'text-neutral-400'} uppercase font-semibold flex gap-3 items-center justify-center md:justify-start text-base`}>
<PiMapPinLineDuotone className="w-5 h-5" />
{contact.location}
</div>
<div className={`md:text-2xl font-bold ${isDarkMode ? 'light-text-color' : 'dark-text-color'} text-lg`}>
<div className="flex gap-2 justify-center md:justify-start">
Hey, I'm
<span ref={typedRef}></span>
</div>
{/* {name.split(" ")[0]}! 👋 */}
</div>
<div className={`text-sm md:text-md ${isDarkMode ? 'text-white' : 'text-neutral-800'}`}>
<p
dangerouslySetInnerHTML={{
__html: description,
}}
/>
</div>
<Button href="/about" className={`expand-hover ${isDarkMode ? 'light-bg-color' : 'medium-bg-color'} uppercase ${isDarkMode ? 'dark-text-color' : 'text-white'} w-full lg:w-52 p-2 rounded-2xl shadow-lg transition`}>
<p>
More About Me
</p>
<BsArrowRight className="ml-2 h-5 w-5" />
</Button>
</div>
<div className="w-1/3 hidden lg:block">
<img src={photo} alt="Profile Picture" className="w-40 ms-auto" />
</div>
</div>
</div>
<div className={`w-full lg:w-1/2 ${isDarkMode ? 'bg-neutral-600' : 'bg-white'} p-7 rounded-3xl flex flex-col gap-3`}> {/** Right Column */}
<div className={`flex items-center gap-2 ${isDarkMode ? 'text-neutral-200' : 'text-neutral-400'} uppercase font-semibold mb-5 justify-center md:justify-start text-base`}>
<LiaLinkSolid className="h-5 w-5" />
Socials
</div>
<div className="flex flex-col gap-3 h-full md:justify-around w-full">
{newSocials.map((chunk, index) => (
<div key={index} className="flex gap-3 h-full w-full">
{chunk.map((social, index) => (
<div key={index} className={`transition shadow-lg ${isDarkMode ? 'extra-light-bg-color' : 'dark-bg-color'} expand-hover transition cursor-pointer w-full h-full rounded-2xl flex items-center justify-center ${isDarkMode ? 'dark-text-color' : 'text-white'} text-5xl flex-col py-5 `}>
<a href={social.link} target="new" className="flex flex-col gap-3 justify-center items-center">
{social.icon}
<span className="text-xs">{social.handle}</span>
</a>
</div>
))}
</div>
))}
</div>
</div>
</div>
</div>
);
}
export default AboutCard;
|
package ru.kraz.feature_hotel.presentation
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.setFragmentResult
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.CompositePageTransformer
import androidx.viewpager2.widget.MarginPageTransformer
import org.koin.androidx.viewmodel.ext.android.viewModel
import ru.kraz.common.presentation.BaseFragment
import ru.kraz.common.presentation.SliderAdapter
import ru.kraz.feature_hotel.R
import ru.kraz.feature_hotel.databinding.FragmentHotelBinding
import kotlin.math.abs
class HotelFragment : BaseFragment<FragmentHotelBinding>() {
private val viewModel: HotelViewModel by viewModel()
private var title = ""
override fun bind(inflater: LayoutInflater, container: ViewGroup?): FragmentHotelBinding =
FragmentHotelBinding.inflate(inflater, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setFragmentResult(ACTION_BACK_REQUEST_KEY, bundleOf(ACTION_BACK_KEY to false))
settingViewModel()
settingListeners()
}
private fun settingViewModel() {
viewModel.fetchHotel()
viewModel.uiState.observe(viewLifecycleOwner) {
binding.loading.visibility = if (it is HotelUiState.Loading) View.VISIBLE else View.GONE
binding.content.visibility = if (it is HotelUiState.Success) View.VISIBLE else View.GONE
setFragmentResult(
TOOLBAR_TITLE_REQUEST_KEY,
bundleOf(
TOOLBAR_TITLE_KEY to
if (it is HotelUiState.Success) resources.getString(R.string.hotel) else ""
)
)
binding.containerError.visibility =
if (it is HotelUiState.Error) View.VISIBLE else View.GONE
binding.tvError.text = if (it is HotelUiState.Error) it.msg else ""
if (it is HotelUiState.Success) {
settingSlider(it.hotel)
binding.ratingContainer.visibility = View.VISIBLE
binding.tvAboutHotel.visibility = View.VISIBLE
binding.btnSelectNum.visibility = View.VISIBLE
binding.tvRating.text = it.hotel.rating.toString() + " " + it.hotel.ratingName
binding.tvName.text = it.hotel.name
binding.btnAddress.text = it.hotel.address
title = it.hotel.name
var mapValue = ""
it.hotel.minimalPrice.toString().forEachIndexed { index, c ->
if (index % 3 == 0) mapValue += " "
mapValue += c
}
binding.tvMinimalPrice.text =
resources.getString(R.string.from) + mapValue + " ₽ "
binding.tvPriceForIt.text = it.hotel.priceForIt.lowercase()
binding.peculiarities.text = ""
it.hotel.peculiarities.forEachIndexed { index, str ->
if (index != 0) binding.peculiarities.text =
binding.peculiarities.text.toString() + "\t\t\t\t" + str
else binding.peculiarities.text = binding.peculiarities.text.toString() + str
}
binding.tvDescription.text = it.hotel.description
settingAdvatages()
}
}
}
private fun settingListeners() {
binding.btnRetry.setOnClickListener {
viewModel.fetchHotel()
}
binding.btnSelectNum.setOnClickListener {
viewModel.openRoom(title)
}
}
private fun settingAdvatages() {
val list = listOf<AdvantageUi>(
AdvantageUi(
R.drawable.ic_happy,
resources.getString(R.string.facilities),
resources.getString(R.string.essentials)
),
AdvantageUi(
R.drawable.ic_include,
resources.getString(R.string.include),
resources.getString(R.string.essentials)
),
AdvantageUi(
R.drawable.ic_not_include,
resources.getString(R.string.not_include),
resources.getString(R.string.essentials)
)
)
val adapter = AdvantagesAdapter(list)
binding.rvAdvantages.adapter = adapter
binding.rvAdvantages.setHasFixedSize(true)
}
private fun settingSlider(hotel: HotelUi.Success) {
val adapter = SliderAdapter(hotel.imageUrls)
binding.viewPager.adapter = adapter
binding.dotsIndicator.attachTo(binding.viewPager)
binding.viewPager.getChildAt(0).overScrollMode = RecyclerView.OVER_SCROLL_NEVER
val transform = CompositePageTransformer().apply {
addTransformer(MarginPageTransformer(30))
addTransformer { page, position ->
page.scaleY = (0.85 + (1 - abs(position)) * 0.15f).toFloat()
}
}
binding.viewPager.setPageTransformer(transform)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
viewModel.coup()
}
}
|
import { useState } from "react";
import Grid from "@material-ui/core/Grid";
import Controls from "./Controls";
import Form from "./Form";
import Props from "./Props";
import { DragDropContext } from "react-beautiful-dnd";
function FormBuilder({ controls }) {
const [formData, setFormData] = useState([]);
const onDragEnd = (data) => {
console.log(data);
const { draggableId, source, destination } = data;
if (source && destination) {
if (source.droppableId === "controls_droppable") {
console.log();
const newFormControl = {
id: `${formData.length}`,
type: draggableId,
config: controls.find((item) => item.value === draggableId)?.config
};
const newFormData = [...formData];
newFormData.splice(destination.index, 0, newFormControl);
setFormData(newFormData);
}
if (source.droppableId === "form_droppable") {
if (source.index !== destination.index) {
const newFormData = [...formData];
const movedFormControl = newFormData.splice(source.index, 1)[0];
newFormData.splice(destination.index, 0, movedFormControl);
setFormData(newFormData);
}
}
}
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Grid spacing={2} direction="row" container>
<Grid item>
<Controls controls={controls} />
</Grid>
<Grid item>
<Form formData={formData} />
</Grid>
<p>{JSON.stringify(formData)}</p>
</Grid>
<Props />
</DragDropContext>
);
}
export default FormBuilder;
|
import "./App.css";
import { useContext } from "react";
import { TodoCounter } from "./TodoCounter/TodoCounter";
import { todoContext } from "./TodoContext/todoContext";
import { TodoSearch } from "./TodoSearch/TodoSearch";
import { TodoList } from "./TodoList/TodoList";
import { TodoItem } from "./TodoItem/TodoItem";
import { CreateTodoButton } from "./CreateTodoButton/CreateTodoButton";
import { ModalApp } from "./modal";
import { TodoForm } from "./TodoForm/todoForm";
import picture from "./picture.jpg";
function AppUI() {
const {
deleteTodo,
searchedTodos,
togglesTodos,
toogleModal,
setToogleModal,
} = useContext(todoContext);
return (
<div className='todo-container'>
<div className='todo-left'>
<h1 className='todo-title'>Welcome to menu To-Do :D </h1>
<div className='img-container'>
<img className='todo-image' src={picture}></img>
</div>
<CreateTodoButton
setToogleModal={setToogleModal}
toogleModal={toogleModal}
/>
</div>
<div className='todo-right'>
<TodoCounter />
<TodoSearch />
<TodoList>
{searchedTodos.map((todo) => (
<TodoItem
key={todo.text}
completed={todo.completed}
text={todo.text}
completeTodos={() => togglesTodos(todo.text)}
deleteTodo={() => deleteTodo(todo.text)}
/>
))}
</TodoList>
</div>
{toogleModal && (
<ModalApp toogleModal={toogleModal} setToogleModal={setToogleModal}>
<TodoForm setToogleModal={setToogleModal} />
</ModalApp>
)}
</div>
);
}
export { AppUI };
|
# Copyright 2023 MTS (Mobile Telesystems)
#
# 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.
from __future__ import annotations
import getpass
import logging
import os
from contextlib import suppress
from pathlib import Path
from typing import TYPE_CHECKING, Optional
from etl_entities.instance import Cluster, Host
from pydantic import Field, PrivateAttr, validator
from onetl.base import PurePathProtocol
from onetl.connection.file_df_connection.spark_file_df_connection import (
SparkFileDFConnection,
)
from onetl.connection.file_df_connection.spark_hdfs.slots import SparkHDFSSlots
from onetl.hooks import slot, support_hooks
from onetl.impl import RemotePath
if TYPE_CHECKING:
from pyspark.sql import SparkSession
log = logging.getLogger(__name__)
@support_hooks
class SparkHDFS(SparkFileDFConnection):
"""
Spark connection to HDFS. |support_hooks|
Based on `Spark Generic File Data Source <https://spark.apache.org/docs/latest/sql-data-sources-generic-options.html>`_.
.. warning::
To use Hive connector you should have PySpark installed (or injected to ``sys.path``)
BEFORE creating the connector instance.
You can install PySpark as follows:
.. code:: bash
pip install onetl[spark] # latest PySpark version
# or
pip install onetl pyspark=3.5.0 # pass specific PySpark version
See :ref:`install-spark` installation instruction for more details.
.. note::
Most of Hadoop instances use Kerberos authentication. In this case, you should call ``kinit``
**BEFORE** starting Spark session to generate Kerberos ticket. See :ref:`install-kerberos`.
In case of creating session with ``"spark.master": "yarn"``, you should also pass some additional options
to Spark session, allowing executors to generate their own Kerberos tickets to access HDFS.
See `Spark security documentation <https://spark.apache.org/docs/latest/security.html#kerberos>`_
for more details.
.. note::
Supports only reading files as Spark DataFrame and writing DataFrame to files.
Does NOT support file operations, like create, delete, rename, etc. For these operations,
use :obj:`HDFS <onetl.connection.file_connection.hdfs.connection.HDFS>` connection.
Parameters
----------
cluster : str
Cluster name.
Used for:
* HWM and lineage (as instance name for file paths)
* Validation of ``host`` value,
if latter is passed and if some hooks are bound to
:obj:`Slots.get_cluster_namenodes <onetl.connection.file_df_connection.spark_hdfs.slots.SparkHDFSSlots.get_cluster_namenodes>`.
host : str, optional
Hadoop namenode host. For example: ``namenode1.domain.com``.
Should be an active namenode (NOT standby).
If value is not set, but there are some hooks bound to
:obj:`Slots.get_cluster_namenodes <onetl.connection.file_df_connection.spark_hdfs.slots.SparkHDFSSlots.get_cluster_namenodes>`
and
:obj:`Slots.is_namenode_active <onetl.connection.file_df_connection.spark_hdfs.slots.SparkHDFSSlots.is_namenode_active>`,
onETL will iterate over cluster namenodes to detect which one is active.
ipc_port : int, default: ``8020``
Port of Hadoop namenode (IPC protocol).
If omitted, but there are some hooks bound to
:obj:`Slots.get_ipc_port <onetl.connection.file_df_connection.spark_hdfs.slots.SparkHDFSSlots.get_ipc_port>`,
onETL will try to detect port number for a specific ``cluster``.
spark : :class:`pyspark.sql.SparkSession`
Spark session
Examples
--------
SparkHDFS connection initialization
.. code:: python
from onetl.connection import SparkHDFS
from pyspark.sql import SparkSession
# Create Spark session
spark = SparkSession.builder.master("local").appName("spark-app-name").getOrCreate()
# Create connection
hdfs = SparkHDFS(
host="namenode1.domain.com",
cluster="rnd-dwh",
spark=spark,
).check()
SparkHDFS connection initialization with Kerberos support
.. code:: python
from onetl.connection import Hive
from pyspark.sql import SparkSession
# Create Spark session.
# Use names "spark.yarn.access.hadoopFileSystems", "spark.yarn.principal"
# and "spark.yarn.keytab" for Spark 2
spark = (
SparkSession.builder.appName("spark-app-name")
.option(
"spark.kerberos.access.hadoopFileSystems",
"hdfs://namenode1.domain.com:8020",
)
.option("spark.kerberos.principal", "user")
.option("spark.kerberos.keytab", "/path/to/keytab")
.enableHiveSupport()
.getOrCreate()
)
# Create connection
hdfs = SparkHDFS(
host="namenode1.domain.com",
cluster="rnd-dwh",
spark=spark,
).check()
Automatically detect hostname for specific cluster
(if some third-party plugin provides :ref:`spark-hdfs-slots` implementation):
.. code:: python
# Create Spark session
...
# Create connection
hdfs = SparkHDFS(cluster="rnd-dwh", spark=spark).check()
"""
Slots = SparkHDFSSlots
cluster: Cluster
host: Optional[Host] = None
ipc_port: int = Field(default=8020, alias="port")
_active_host: Optional[Host] = PrivateAttr(default=None)
@slot
def path_from_string(self, path: os.PathLike | str) -> Path:
return RemotePath(os.fspath(path))
@property
def instance_url(self):
return self.cluster
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
@slot
def close(self):
"""
Close all connections created to HDFS. |support_hooks|
.. note::
Connection can be used again after it was closed.
Returns
-------
Connection itself
Examples
--------
Close connection automatically:
.. code:: python
with connection:
...
Close connection manually:
.. code:: python
connection.close()
"""
log.debug("Reset FileSystem cache")
with suppress(Exception):
self._get_spark_fs().close()
with suppress(Exception):
self._active_host = None
return self
# Do not all __del__ with calling .close(), like other connections,
# because this can influence dataframes created by this connection
@slot
@classmethod
def get_current(cls, spark: SparkSession):
"""
Create connection for current cluster. |support_hooks|
Automatically sets up current cluster name as ``cluster``.
.. note::
Can be used only if there are a some hooks bound to
:obj:`Slots.get_current_cluster <onetl.connection.file_df_connection.spark_hdfs.slots.SparkHDFSSlots.get_current_cluster>`.
Parameters
----------
spark : SparkSession
See :obj:`~SparkHDFS` constructor documentation.
Examples
--------
.. code:: python
from onetl.connection import SparkHDFS
# injecting current cluster name via hooks mechanism
hdfs = SparkHDFS.get_current(spark=spark)
"""
log.info("|%s| Detecting current cluster...", cls.__name__)
current_cluster = cls.Slots.get_current_cluster()
if not current_cluster:
raise RuntimeError(
f"{cls.__name__}.get_current() can be used only if there are "
f"some hooks bound to {cls.__name__}.Slots.get_current_cluster",
)
log.info("|%s| Got %r", cls.__name__, current_cluster)
return cls(cluster=current_cluster, spark=spark)
@validator("cluster")
def _validate_cluster_name(cls, cluster):
log.debug("|%s| Normalizing cluster %r name...", cls.__name__, cluster)
validated_cluster = cls.Slots.normalize_cluster_name(cluster) or cluster
if validated_cluster != cluster:
log.debug("|%s| Got %r", cls.__name__, validated_cluster)
log.debug("|%s| Checking if cluster %r is a known cluster...", cls.__name__, validated_cluster)
known_clusters = cls.Slots.get_known_clusters()
if known_clusters and validated_cluster not in known_clusters:
raise ValueError(
f"Cluster {validated_cluster!r} is not in the known clusters list: {sorted(known_clusters)!r}",
)
return validated_cluster
@validator("host")
def _validate_host_name(cls, host, values):
cluster = values.get("cluster")
log.debug("|%s| Normalizing namenode %r host...", cls.__name__, host)
namenode = cls.Slots.normalize_namenode_host(host, cluster) or host
if namenode != host:
log.debug("|%s| Got %r", cls.__name__, namenode)
log.debug("|%s| Checking if %r is a known namenode of cluster %r ...", cls.__name__, namenode, cluster)
known_namenodes = cls.Slots.get_cluster_namenodes(cluster)
if known_namenodes and namenode not in known_namenodes:
raise ValueError(
f"Namenode {namenode!r} is not in the known nodes list of cluster {cluster!r}: "
f"{sorted(known_namenodes)!r}",
)
return namenode
@validator("ipc_port", always=True)
def _validate_port_number(cls, port, values):
cluster = values.get("cluster")
if cluster:
log.debug("|%s| Getting IPC port of cluster %r ...", cls.__name__, cluster)
result = cls.Slots.get_ipc_port(cluster) or port
if result != port:
log.debug("|%s| Got %r", cls.__name__, result)
return result
return port
def _get_active_namenode(self) -> str:
class_name = self.__class__.__name__
log.info("|%s| Detecting active namenode of cluster %r ...", class_name, self.cluster)
namenodes = self.Slots.get_cluster_namenodes(self.cluster)
if not namenodes:
raise RuntimeError(f"Cannot get list of namenodes for a cluster {self.cluster!r}")
nodes_len = len(namenodes)
for i, namenode in enumerate(namenodes):
log.debug("|%s| Trying namenode %r (%d of %d) ...", class_name, namenode, i, nodes_len)
if self.Slots.is_namenode_active(namenode, self.cluster):
log.info("|%s| Node %r is active!", class_name, namenode)
return namenode
log.debug("|%s| Node %r is not active, skipping", class_name, namenode)
raise RuntimeError(f"Cannot detect active namenode for cluster {self.cluster!r}")
def _get_host(self) -> str:
if not self.host:
return self._get_active_namenode()
# host is passed explicitly
class_name = self.__class__.__name__
log.info("|%s| Detecting if namenode %r of cluster %r is active...", class_name, self.host, self.cluster)
is_active = self.Slots.is_namenode_active(self.host, self.cluster)
if is_active:
log.info("|%s| Namenode %r is active!", class_name, self.host)
return self.host
if is_active is None:
log.debug("|%s| No hooks, skip validation", class_name)
return self.host
raise RuntimeError(f"Host {self.host!r} is not an active namenode of cluster {self.cluster!r}")
def _convert_to_url(self, path: PurePathProtocol) -> str:
# "hdfs://namenode:8020/absolute/path" if host is set
if self._active_host:
host = self._active_host
else:
host = self._get_host()
# cache value to avoid getting active namenode for every path
self._active_host = host
return f"hdfs://{host}:{self.ipc_port}" + path.as_posix()
def _get_default_path(self):
return RemotePath("/user") / getpass.getuser()
|
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.sql.expression import and_
from sqlalchemy.future import select
from sqlalchemy import update
from models.refresh_tokens import RefreshToken
from models.email_confirmation_tokens import EmailConfirmationToken
from models.password_reset_tokens import PasswordResetToken
from schemas.auth import (
RefreshTokenCreateSchema,
EmailConfirmationCreateSchema,
PasswordResetCreateSchema,
)
class RefreshTokenCRUD:
def __init__(self, db: AsyncSession):
self.db = db
self.model = RefreshToken
async def get_by_id(self, id: str) -> RefreshToken | None:
result = await self.db.execute(select(self.model).filter(self.model.id == id))
refresh_token = result.scalars().first()
return refresh_token
async def set_revoke_status_to_true(self, id: str) -> None:
await self.db.execute(
update(self.model).where(self.model.id == id).values(revoked=True)
)
await self.db.commit()
async def create(self, token: RefreshTokenCreateSchema) -> None:
token_dict = token.model_dump()
db_token = self.model(**token_dict)
self.db.add(db_token)
await self.db.commit()
class TokenForEmailCRUD:
def __init__(
self,
db: AsyncSession,
is_for_password_reset: bool,
):
if is_for_password_reset:
self.model = PasswordResetToken
else:
self.model = EmailConfirmationToken
self.db = db
async def create(
self, token: EmailConfirmationCreateSchema | PasswordResetCreateSchema
) -> None:
token_dict = token.model_dump()
db_token = self.model(**token_dict)
self.db.add(db_token)
await self.db.commit()
async def get_by_token(
self, token: str
) -> EmailConfirmationToken | PasswordResetToken | None:
result = await self.db.execute(
select(self.model).filter(self.model.token == token)
)
token_result = result.scalars().first()
return token_result
async def set_is_used_true(self, token_id: str) -> None:
await self.db.execute(
update(self.model).where(self.model.id == token_id).values(is_used=True)
)
await self.db.commit()
async def set_is_used_true_on_all_tokens(self, user_id: str) -> None:
await self.db.execute(
update(self.model)
.where(
and_(
self.model.user_id == user_id,
self.model.is_used == False,
)
)
.values(is_used=True)
)
await self.db.commit()
|
'use client';
import Link from 'next/link';
import React, { useEffect, useState } from 'react';
import { getUsers, login } from '@/core/api/auth';
import useUserStore from '@/store/user.store';
import useUsersStore from '@/store/users.store';
import { useRouter } from 'next/navigation';
import User from '@/interfaces/user.interface';
const LoginForm: React.FC = () => {
const router = useRouter();
const userStore = useUserStore();
const usersStore = useUsersStore();
const [email, setEmail] = useState('');
useEffect(() => {
getUsers()
.then(response => {
console.log('Response:', response);
usersStore.setUsers(response?.output);
})
.catch(error => {
console.error('Error:', error);
});
}, [])
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (email) {
let user = usersStore.users.find(u => u.email == email || u.name == email);
if (user?.id && user?.email) {
console.log(user);
login(user?.id)
.then(response => {
console.log('Response:', response);
userStore.setUser(response?.output);
if (response?.output?.id) {
router.push('/');
}
})
.catch(error => {
console.error('Error:', error);
});
}
}
};
return (
<div className="flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8 bg-white">
<div className="max-w-md w-full space-y-8">
<div>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">Sign in to your account</h2>
</div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
<input type="hidden" name="remember" value="true" />
<div className='mb-4'>
<label className="block text-gray-700 text-sm font-bold mb-2">
Email address
</label>
<input
id="email"
name="email"
type="email"
autoComplete="email"
required
className="appearance-none rounded relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
placeholder="Email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center">
<input
id="remember-me"
name="remember-me"
type="checkbox"
className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
/>
<label htmlFor="remember-me" className="ml-2 block text-sm text-gray-900">
Remember me
</label>
</div>
</div>
<div className='mb-3'>
<button
type="submit"
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
Sign in
</button>
</div>
<p className='text-center'>
<span className='mr-2'>Do not have an account?</span>
<Link className='text-blue-500' href="/auth/register">Register</Link>
</p>
</form>
</div>
</div>
);
};
export default LoginForm;
|
using VistaGL.Modules.Common;
namespace VistaGL.HRM.Entities {
using Serenity;
using Serenity.ComponentModel;
using Serenity.Data;
using Serenity.Data.Mapping;
using System;
using System.ComponentModel;
using System.IO;
[ConnectionKey("POMS_MPA"), DisplayName("PRM_EmploymentInfo"), InstanceName("PRM_EmploymentInfo"), TwoLevelCached]
[ReadPermission("HRM:PRM_EmploymentInfo:Read")]
[InsertPermission("HRM:PRM_EmploymentInfo:Insert")]
[UpdatePermission("HRM:PRM_EmploymentInfo:Update")]
[DeletePermission("HRM:PRM_EmploymentInfo:Delete")]
[LookupScript("HRM.EmploymentInfo")]
public sealed class EmploymentInfoRow : Row, IIdRow, INameRow, IAuditLog
{
#region Id
[DisplayName("Id"), Identity]
public Int32? Id { get { return Fields.Id[this]; } set { Fields.Id[this] = value; } }
public partial class RowFields { public Int32Field Id; }
#endregion Id
#region Emp Id
[DisplayName("Emp Id"), Column("EmpID"), Size(15), NotNull, QuickSearch]
public String EmpId { get { return Fields.EmpId[this]; } set { Fields.EmpId[this] = value; } }
public partial class RowFields { public StringField EmpId; }
#endregion EmpId
#region Employee Initial
[DisplayName("Employee Initial"), Size(15)]
public String EmployeeInitial { get { return Fields.EmployeeInitial[this]; } set { Fields.EmployeeInitial[this] = value; } }
public partial class RowFields { public StringField EmployeeInitial; }
#endregion EmployeeInitial
#region Title
[DisplayName("Title"), ForeignKey("[dbo].[PRM_NameTitle]", "Id"), LeftJoin("jTitle"), TextualField("TitleName")]
//[LookupEditor(typeof(HRM.Entities.PrmNameTitleRow), InplaceAdd = true)]
public Int32? TitleId { get { return Fields.TitleId[this]; } set { Fields.TitleId[this] = value; } }
public partial class RowFields { public Int32Field TitleId; }
#endregion TitleId
#region First Name
[DisplayName("First Name"), Size(50)]
public String FirstName { get { return Fields.FirstName[this]; } set { Fields.FirstName[this] = value; } }
public partial class RowFields { public StringField FirstName; }
#endregion FirstName
#region Middle Name
[DisplayName("Middle Name"), Size(50)]
public String MiddleName { get { return Fields.MiddleName[this]; } set { Fields.MiddleName[this] = value; } }
public partial class RowFields { public StringField MiddleName; }
#endregion MiddleName
#region Last Name
[DisplayName("Last Name"), Size(50)]
public String LastName { get { return Fields.LastName[this]; } set { Fields.LastName[this] = value; } }
public partial class RowFields { public StringField LastName; }
#endregion LastName
#region Full Name
[DisplayName("Full Name"), Size(200), NotNull]
public String FullName { get { return Fields.FullName[this]; } set { Fields.FullName[this] = value; } }
public partial class RowFields { public StringField FullName; }
#endregion FullName
#region Designation
[DisplayName("Designation"), ForeignKey("[dbo].[PRM_Designation]", "Id"), LeftJoin("jDesignation"), TextualField("DesignationName")]
//[LookupEditor(typeof(HRM.Entities.PrmDesignationRow), InplaceAdd = true)]
public Int32? DesignationId { get { return Fields.DesignationId[this]; } set { Fields.DesignationId[this] = value; } }
public partial class RowFields { public Int32Field DesignationId; }
#endregion DesignationId
#region Discipline
[DisplayName("Discipline"), ForeignKey("[dbo].[PRM_Discipline]", "Id"), LeftJoin("jDiscipline"), TextualField("DisciplineName")]
//[LookupEditor(typeof(HRM.Entities.PrmDisciplineRow), InplaceAdd = true)]
public Int32? DisciplineId { get { return Fields.DisciplineId[this]; } set { Fields.DisciplineId[this] = value; } }
public partial class RowFields { public Int32Field DisciplineId; }
#endregion DisciplineId
#region Division
[DisplayName("Division"), ForeignKey("[dbo].[PRM_Division]", "Id"), LeftJoin("jDivision"), TextualField("DivisionName")]
//[LookupEditor(typeof(HRM.Entities.PrmDivisionRow), InplaceAdd = true)]
public Int32? DivisionId { get { return Fields.DivisionId[this]; } set { Fields.DivisionId[this] = value; } }
public partial class RowFields { public Int32Field DivisionId; }
#endregion DivisionId
#region Employment Status
[DisplayName("Employment Status"), NotNull, ForeignKey("[dbo].[PRM_EmploymentStatus]", "Id"), LeftJoin("jEmploymentStatus"), TextualField("EmploymentStatusName")]
//[LookupEditor(typeof(HRM.Entities.PrmEmploymentStatusRow), InplaceAdd = true)]
public Int32? EmploymentStatusId { get { return Fields.EmploymentStatusId[this]; } set { Fields.EmploymentStatusId[this] = value; } }
public partial class RowFields { public Int32Field EmploymentStatusId; }
#endregion EmploymentStatusId
#region Prl Date
[DisplayName("Prl Date"), Column("PRLDate")]
public DateTime? PrlDate { get { return Fields.PrlDate[this]; } set { Fields.PrlDate[this] = value; } }
public partial class RowFields { public DateTimeField PrlDate; }
#endregion PrlDate
#region Region
[DisplayName("Region"), NotNull, ForeignKey("[dbo].[PRM_Region]", "Id"), LeftJoin("jRegion"), TextualField("RegionName")]
////[LookupEditor(typeof(HRM.Entities.PrmRegionRow), InplaceAdd = true)]
public Int32? RegionId { get { return Fields.RegionId[this]; } set { Fields.RegionId[this] = value; } }
public partial class RowFields { public Int32Field RegionId; }
#endregion RegionId
#region Foreign Fields
[DisplayName("Title Name"), Expression("jTitle.[Name]")]
public String TitleName { get { return Fields.TitleName[this]; } set { Fields.TitleName[this] = value; } }
public partial class RowFields { public StringField TitleName; }
[DisplayName("Title Name"), Expression("T0.EmpId + ' - ' + T0.FullName")]
public String LookupText { get { return Fields.LookupText[this]; } set { Fields.LookupText[this] = value; } }
public partial class RowFields { public StringField LookupText; }
[DisplayName("Designation Name"), Expression("jDesignation.[Name]")]
public String DesignationName { get { return Fields.DesignationName[this]; } set { Fields.DesignationName[this] = value; } }
public partial class RowFields { public StringField DesignationName; }
[DisplayName("Discipline Name"), Expression("jDiscipline.[Name]")]
public String DisciplineName { get { return Fields.DisciplineName[this]; } set { Fields.DisciplineName[this] = value; } }
public partial class RowFields { public StringField DisciplineName; }
[DisplayName("Division Name"), Expression("jDivision.[Name]")]
public String DivisionName { get { return Fields.DivisionName[this]; } set { Fields.DivisionName[this] = value; } }
public partial class RowFields { public StringField DivisionName; }
[DisplayName("Employment Status Name"), Expression("jEmploymentStatus.[Name]")]
public String EmploymentStatusName { get { return Fields.EmploymentStatusName[this]; } set { Fields.EmploymentStatusName[this] = value; } }
public partial class RowFields { public StringField EmploymentStatusName; }
#endregion Foreign Fields
#region Id and Name fields
IIdField IIdRow.IdField {
get { return Fields.Id; }
}
StringField INameRow.NameField {
get { return Fields.LookupText; }
}
#endregion Id and Name fields
#region Constructor
public EmploymentInfoRow()
: base(Fields) {
}
#endregion Constructor
#region RowFields
public static readonly RowFields Fields = new RowFields().Init();
public const string TableName = "[dbo].[PRM_EmploymentInfo]";
public partial class RowFields : RowFieldsBase {
public RowFields()
: base(EmploymentInfoRow.TableName) {
LocalTextPrefix = "HRM.EmploymentInfo";
}
}
#endregion RowFields
}
}
|
<%= render 'shared/navbar_general' %>
<div data-controller="message" class="page-container">
<div class="d-flex">
<div class="column">
<button data-action="click->message#showMessage" class="column-button">Notificações</button>
</div>
<div class="column">
<button data-action="click->message#showNotification" class="column-button">Mensagens </button>
</div>
</div>
<div>
<div data-message-target="message" class="content">
<!-- Contenu de la colonne des messages -->
<% @requests.each do |request| %>
<% if request.user == current_user %>
<% first_print_date = request.created_at %>
<% current_date = Time.now %>
<% difference_minutes= ((current_date - first_print_date) /60).round %>
<% difference_hours= ((current_date - first_print_date) / 3600).round %>
<% difference_days= ((current_date - first_print_date) / 96400).round %>
<div class="card-vinted" data-controller="toggle" class="collapsed">
<div data-action="click->toggle#toggle">
<% if difference_minutes < 60%>
<p style='color: gray'>Há <%= difference_minutes %> minutos</p>
<% elsif difference_hours = 1%>
<p style='color: gray'>Há <%= difference_hours %> hora</p>
<% elsif difference_hours < 24%>
<p style='color: gray'>Há <%= difference_hours %> horas</p>
<% elsif difference_days = 1 %>
<p style='color: gray'>Há <%= difference_days %> dia</p>
<% else %>
<p style='color: gray'>Há <%= difference_days %> dias</p>
<% end %>
<h2> Você desafiou <%= request.match.user.nickname %>!</h2>
<% if request.status == "pending" %>
<p style="color: grey"><strong> Aguarde <%= request.match.user.nickname %> aceitar </strong> </p>
<% end %>
<%# <p> <i class="fa-solid fa-baseball" style="color: #020203;"></i> Match <%= request.match.modality%>
<% if request.status == "refused" %>
<p><strong> Desafio recusado </strong> </p>
<% elsif request.status == "accepted" %>
<p style="color: grey"><strong> Desfio aceito, <%= request.match.user.nickname %> deve entrar o placar</strong> </p>
<% end %>
</div>
<div data-toggle-target="content">
<p><%= request.match.address %></p>
<p> Data: <%= request.created_at.strftime("%d/%m/%Y %H:%M") %></p>
<div class="button-container">
<% if request.status == "pending" %>
<button class="refuse-button button-full-width btn-refuser"><%= link_to "Cancelar desafio", refuse_request_path(request), data: { turbo_method: :patch } %></button>
<% end %>
</div>
</div>
</div>
<% else %>
<% if request.status == "accepted" && request.match.match_type == "Desafio" %>
<% first_print_date = request.updated_at %>
<% current_date = Time.now %>
<% difference_minutes= ((current_date - first_print_date) /60).round %>
<% difference_hours= ((current_date - first_print_date) / 3600).round %>
<% difference_days= ((current_date - first_print_date) / 96400).round %>
<div class="card-vinted card-score" data-controller="toggle" class="collapsed">
<div data-action="click->toggle#toggle">
<% if difference_minutes < 60%>
<p style='color: gray'>Há <%= difference_minutes %> minutos</p>
<% elsif difference_hours = 1%>
<p style='color: gray'>Há <%= difference_hours %> hora</p>
<% elsif difference_hours < 24%>
<p style='color: gray'>Há <%= difference_hours %> horas</p>
<% elsif difference_days = 1 %>
<p style='color: gray'>Há <%= difference_days %> dia</p>
<% else %>
<p style='color: gray'>Há <%= difference_days %> dias</p>
<% end %>
<h2 style="color: #253343;"> Entre o placar do jogo com <%= request.user.nickname %></h2>
</div>
<div data-toggle-target="content">
<button class="btn-ace"><%= link_to "Placar", edit_match_path(request.match), class: "" %></button>
</div>
</div>
<% end %>
<% first_print_date = request.created_at %>
<% current_date = Time.now %>
<% difference_minutes= ((current_date - first_print_date) /60).round %>
<% difference_hours= ((current_date - first_print_date) / 3600).round %>
<% difference_days= ((current_date - first_print_date) / 96400).round %>
<div class="card-vinted" data-controller="toggle" class="collapsed">
<div data-action="click->toggle#toggle">
<% if difference_minutes < 60%>
<p style='color: gray'>Há <%= difference_minutes %> minutos</p>
<% elsif difference_hours = 1%>
<p style='color: gray'>Há <%= difference_hours %> hora</p>
<% elsif difference_hours < 24%>
<p style='color: gray'>Há <%= difference_hours %> horas</p>
<% elsif difference_days = 1 %>
<p style='color: gray'>Há <%= difference_days %> dia</p>
<% else %>
<p style='color: gray'>Há <%= difference_days %> dias</p>
<% end %>
<h2> <%= request.user.nickname %> quer te desafiar! </h2>
<%# <p> <i class="fa-solid fa-baseball" style="color: #020203;"></i> Match <%= request.match.modality%>
<% if request.status == "refused" %>
<p><strong> Desafio recusado </strong> </p>
<% elsif request.status == "accepted" %>
<p style="color: grey"><strong> Desfio aceito, não se esqueça de entrar o placar</strong> </p>
<% end %>
</div>
<div data-toggle-target="content">
<p> Data: <%= request.created_at.strftime("%d/%m/%Y %H:%M") %></p>
<div class="button-container">
<% if request.status == "pending" %>
<div class="button-wrapper">
<button class="accept-button button-half-width btn-accepter"><%= link_to "Aceitar", accept_request_path(request), data: { turbo_method: :patch } %></button>
<button class="refuse-button button-half-width btn-refuser"><%= link_to "Recusar", refuse_request_path(request), data: { turbo_method: :patch } %></button>
</div>
<% end %>
</div>
</div>
</div>
<% end %>
<% end %>
</div>
<div data-message-target="notification" class="container chat-card">
<%# class="content"> %>
<!-- Contenu de la colonne des notifications -->
<% current_user.chatrooms.each do |chatroom|%>
<%= link_to chatroom_path(user_id: other_chatroom_user(chatroom).id ) do%>
<div class="small-card">
<div>
<%= cl_image_tag other_chatroom_user(chatroom).photo.key, class: "avatar m-3"%>
</div>
<div class="chat-infos">
<p style="font-size: 20px" class="card-titre-gras"><strong><%= other_chatroom_user(chatroom).nickname %></strong></p>
<% unless chatroom.messages.empty? %>
<%= chatroom.messages.last.content%>
<% end %>
</div>
<div>
<% unless chatroom.messages.empty? %>
<i class="message-time"><%= chatroom.messages.last.created_at.strftime("%l:%M %p")%></i>
<% end %>
</div>
</div>
<%end%>
<%end%>
</div>
</div>
</div>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.