text
stringlengths 184
4.48M
|
---|
// Final Project Milestone 4
//
// Version 1.0
// Date 2023-04-03
// Author Ching Wei Lai
// Description
// This program test the student implementation of the PosApp class
// for submission.
//
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include "Date.h"
#include "Utils.h"
using namespace std;
namespace sdds {
// The valid range of values for the year
const int MIN_YEAR = 2000;
const int MAX_YEAR = 2038;
//implemented function
//system date and time
void Date::getSystemDate() {
time_t currentTime = time(NULL);
tm* localTime = localtime(¤tTime);
m_year = localTime->tm_year + 1900;
m_month = localTime->tm_mon + 1;
m_day = localTime->tm_mday;
if (!m_dateOnly) {
m_hour = localTime->tm_hour;
m_min = localTime->tm_min;
}
}
//set the error to error object in the class
void Date::errCheck(int errorCode) {
err = errorCode;
}
//constructor
Date::Date() {
m_dateOnly = false;
getSystemDate();
err = noerr;
}
//year, month, day
Date::Date(int year, int month, int day) {
m_dateOnly = true;
m_year = year;
m_month = month;
m_day = day;
m_hour = m_min = 0;
err = noerr;
}
//year, month, day, hour, min
Date::Date(int year, int month, int day, int hour, int min) {
m_dateOnly = false;
m_year = year;
m_month = month;
m_day = day;
m_hour = hour;
m_min = min;
err = noerr;
}
//year, month, day ,hour, nin
void Date::set(int year, int month, int day, int hour, int min) {
m_year = year;
m_month = month;
m_day = day;
m_hour = hour;
m_min = min;
err = noerr;
}
//error is empty
bool Date::empty() const {
return err != noerr;
}
//is date only
bool Date::isDateOnly() const {
return m_dateOnly;
}
//set error to empty state
void Date::setEmpty() {
err = noerr;
}
//return error message
string Date::error() const {
string message;
switch (err) {
case noerr:
message = "";
break;
case missY:
message = "Cannot read year entry";
break;
case yerr:
message = "Invalid Year";
break;
case missM:
message = "Cannot read month entry";
break;
case merr:
message = "Invalid Month";
break;
case missD:
message = "Cannot read day entry";
break;
case derr:
message = "Invalid Day";
break;
case missH:
message = "Cannot read hour entry";
break;
case herr:
message = "Invalid Hour";
break;
case missMin:
message = "Cannot read minute entry";
break;
case minerr:
message = "Invlid Minute";
break;
}
return message;
}
//error attribute is not "no error"
bool Date::bad() const {
return err != noerr;
}
//Comparison Operator Overloads -> ==, != , < , > , <= , >=
bool Date::operator==(const Date& D) const {
return (this->m_year == D.m_year && this->m_month == D.m_month &&
this->m_day == D.m_day && this->m_hour == D.m_hour &&
this->m_min == D.m_min);
}
bool Date::operator!=(const Date& D) const {
return !(*this == D);
}
bool Date::operator<(const Date& D) const {
if (this->m_year < D.m_year)
return true;
else if (this->m_year == D.m_year && this->m_month < D.m_month)
return true;
else if (this->m_year == D.m_year && this->m_month == D.m_month &&
this->m_day < D.m_day)
return true;
else if (this->m_year == D.m_year && this->m_month == D.m_month &&
this->m_day == D.m_day && this->m_hour < D.m_hour)
return true;
else if (this->m_year == D.m_year && this->m_month == D.m_month &&
this->m_day == D.m_day && this->m_hour == D.m_hour &&
this->m_min < D.m_min)
return true;
else
return false;
}
bool Date::operator>(const Date& D) const {
return !(*this <= D);
}
bool Date::operator<=(const Date& D) const {
return (*this == D || *this < D);
}
bool Date::operator>=(const Date& D) const {
return !(*this < D);
}
Date& Date::dateOnly(bool value)
{
m_dateOnly = value;
if (m_dateOnly) {
m_hour = 0;
m_min = 0;
}
return *this;
}
//Overload the bool type conversion operator
bool Date::operator!() const {
return err != noerr;
}
//Number of days in the month
int Date::mdays() const {
//set the day to zero
int days = 0;
//check the month is valid
if (m_month >= 1 && m_month <= 12) {
//2 -> 28, 4.6.9.11 -> 30, else -> 31
switch (m_month) {
case 2:
days = 28 + (int)(m_year % 4 == 0 && (m_year % 100 != 0 || m_year % 400 == 0));
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
break;
}
}
return days;
}
//set the correct format for output
ostream& Date::write(ostream& ostr) const {
if (err != noerr) {
ostr << error() << "(";
}
ostr << m_year << '/';
ostr.fill('0');
ostr.width(2);
ostr << m_month << '/';
ostr.width(2);
ostr.fill('0');
ostr << m_day;
if (!m_dateOnly) {
ostr << ", ";
ostr << setw(2);
ostr.fill('0');
ostr << m_hour << ':';
ostr.width(2);
ostr.fill('0');
ostr << m_min;
}
if (err != noerr) {
ostr << ")";
}
return ostr;
}
//read the data -> do the date validation process
istream& Date::read(istream& istr) {
// Reset everything to default state
m_year = 0;
m_month = 0;
m_day = 0;
m_hour = 0;
m_min = 0;
//create an array for reading
int ent = m_dateOnly ? 3 : 5;
//dynamic allocation
int* entries = new int[ent];
for (int i = 0; i < ent; i++) {
entries[i] = 0;
}
//do not need to verify the delimiters
char del = '\0';
int i = 0;
bool flag = false;
while (!istr.fail() && i < ent) {
if (flag) { //ignore delimeter
istr >> del;
flag = false;
}
else { //keep reading
istr >> entries[i];
i += 1;
flag = true;
}
}
m_year = entries[0];//set the year value
m_month = entries[1];//set the month value
m_day = entries[2];//set the day value
//check the dateOnly -> set hour & minuter to 0
if (m_year == 0) {
errCheck(missY);
delete[] entries;
entries = nullptr;
return istr;
}
else if (m_year < MIN_YEAR || m_year > MAX_YEAR) {
errCheck(yerr);
delete[] entries;
entries = nullptr;
return istr;
}
// Validate the month
if (m_month == 0) {
errCheck(missM);
delete[] entries;
entries = nullptr;
return istr;
}
else if (m_month < 1 || m_month > 12) {
errCheck(merr);
delete[] entries;
entries = nullptr;
return istr;
}
// Validate the day
if (m_day == 0) {
errCheck(missD);
delete[] entries;
entries = nullptr;
return istr;
}
else if (m_day < 1 || m_day > mdays()) {
errCheck(derr);
delete[] entries;
entries = nullptr;
return istr;
}
// If date only, we are done.
if (m_dateOnly) {
errCheck(noerr);
delete[] entries;
entries = nullptr;
return istr;
}
else {
m_hour = entries[3];
m_min = entries[4];
}
// Validate the hour
if (m_hour == 0 && istr.fail()) {
errCheck(missH);
delete[] entries;
entries = nullptr;
return istr;
}
else if (m_hour < 0 || m_hour > 23) {
errCheck(herr);
delete[] entries;
entries = nullptr;
return istr;
}
// Validate the minute
if (m_min == 0 && istr.fail()) {
errCheck(missMin);
delete[] entries;
entries = nullptr;
return istr;
}
else if (m_min < 0 || m_min > 59) {
errCheck(minerr);
delete[] entries;
entries = nullptr;
return istr;
}
// All entries are valid
errCheck(noerr);
delete[] entries;
entries = nullptr;
return istr;
}
//ostream insertion operator overload
std::ostream& operator<<(std::ostream& ostr, const Date& D) {
return D.write(ostr);
}
// istream extraction operator overload
std::istream& operator>>(std::istream& istr, Date& D) {
return D.read(istr);
}
}
|
# Copyright (c) 2020-present, Royal Bank of Canada.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from typing import Tuple, Dict
import numpy as np
from ssl import constants as c
from ssl.loader import datautils
from ssl.utils import data_dropout
def load_classification_data(dataset: str, loader: str) -> Tuple[str, Dict[str, np.ndarray]]:
if loader == c.CLASSIFICATION.UCR:
train_data, train_labels, test_data, test_labels = datautils.load_UCR(dataset)
elif loader == c.CLASSIFICATION.UEA:
train_data, train_labels, test_data, test_labels = datautils.load_UEA(dataset)
else:
raise KeyError(
f"{dataset} and {loader} are not valid. Have you specified the correct names?"
)
return (
c.CLASSIFICATION.TASK,
{
c.CLASSIFICATION.TRAIN_DATA: train_data,
c.CLASSIFICATION.TRAIN_LABEL: train_labels,
c.CLASSIFICATION.TEST_DATA: test_data,
c.CLASSIFICATION.TEST_LABEL: test_labels,
},
)
def load_forecasting_data(dataset: str, loader: str) -> Tuple[str, Dict[str, np.ndarray]]:
if loader in [c.FORECASTING.CSV, c.FORECASTING.CSV_UNIVAR]:
is_univar = False if loader == c.FORECASTING.CSV else True
(
data,
train_slice,
valid_slice,
test_slice,
scaler,
pred_lens,
n_covariate_cols,
) = datautils.load_forecast_csv(dataset, univar=is_univar)
elif loader in [c.FORECASTING.NUMPY, c.FORECASTING.NUMPY_UNIVAR]:
is_univar = False if loader == c.FORECASTING.NUMPY else True
(
data,
train_slice,
valid_slice,
test_slice,
scaler,
pred_lens,
n_covariate_cols,
) = datautils.load_forecast_npy(dataset, univar=is_univar)
else:
raise KeyError(
f"{dataset} and {loader} are not valid. Have you specified the correct names?"
)
return (
c.FORECASTING.TASK,
{
c.FORECASTING.DATA: data,
c.FORECASTING.TRAIN_SLICE: train_slice,
c.FORECASTING.VALID_SLICE: valid_slice,
c.FORECASTING.TEST_SLICE: test_slice,
c.FORECASTING.SCALAR: scaler,
c.FORECASTING.PRED_LENS: pred_lens,
c.FORECASTING.NUM_COV_COL: n_covariate_cols,
},
)
def load_anomaly_data(dataset: str, loader: str) -> Tuple[str, Dict[str, np.ndarray]]:
(
all_train_data,
all_train_labels,
all_train_timestamps,
all_test_data,
all_test_labels,
all_test_timestamps,
delay,
) = datautils.load_anomaly(dataset)
return (
c.ANOMALY_DETECTION.TASK,
{
c.ANOMALY_DETECTION.TRAIN_DATA: all_train_data,
c.ANOMALY_DETECTION.TRAIN_LABEL: all_train_labels,
c.ANOMALY_DETECTION.TRAIN_TIMESTAMP: all_train_timestamps,
c.ANOMALY_DETECTION.TEST_DATA: all_test_data,
c.ANOMALY_DETECTION.TEST_LABEL: all_test_labels,
c.ANOMALY_DETECTION.TEST_TIMESTAMP: all_test_timestamps,
c.ANOMALY_DETECTION.DELAY: delay,
},
)
_mapping = {
c.CLASSIFICATION.UCR: load_classification_data,
c.CLASSIFICATION.UEA: load_classification_data,
c.FORECASTING.CSV: load_forecasting_data,
c.FORECASTING.CSV_UNIVAR: load_forecasting_data,
c.FORECASTING.NUMPY: load_forecasting_data,
c.FORECASTING.NUMPY_UNIVAR: load_forecasting_data,
c.ANOMALY_DETECTION.ANOMALY: load_anomaly_data,
c.ANOMALY_DETECTION.COLD_START_ANOMALY: load_anomaly_data,
}
def load_data(dataset: str, loader: str, irregular: float) -> Tuple[str, Dict, np.ndarray]:
loader_func = _mapping.get(loader)
if loader_func is None:
raise KeyError(f"Invalid loader is specified. Got {loader}")
task_type, data_dict = loader_func(dataset, loader)
if loader in [c.CLASSIFICATION.UCR, c.CLASSIFICATION.UEA]:
train_data = data_dict[c.CLASSIFICATION.TRAIN_DATA]
if irregular > 0:
train_data = data_dropout(train_data, irregular)
if loader.startswith("forecast"):
train_data = data_dict[c.FORECASTING.DATA][:, data_dict[c.FORECASTING.TRAIN_SLICE]]
if loader == c.ANOMALY_DETECTION.ANOMALY:
train_data = datautils.gen_ano_train_data(data_dict[c.ANOMALY_DETECTION.TRAIN_DATA])
if loader == c.ANOMALY_DETECTION.COLD_START_ANOMALY:
train_data, _, _, _ = datautils.load_UCR("FordA")
return task_type, data_dict, train_data
|
#include <chrono>
#include <iostream>
#include <sstream>
#include <thread>
#include <benchmark/benchmark.h>
void func1() {
std::string a = "hello";
std::string b = "world";
std::string c = "";
for (int i = 0; i < 10000; i++) {
c = a + b;
}
}
void func2() {
std::string a = "hello";
std::string b = "world";
std::string c = "";
for (int i = 0; i < 10000; i++) {
c += a;
c += b;
}
}
void func3() {
std::string a = "hello";
std::string b = "world";
std::string c = "";
for (int i = 0; i < 10000; i++) {
c.append(a);
c.append(b);
}
}
void func4() {
std::stringstream ss;
std::string a = "hello";
std::string b = "world";
for (int i = 0; i < 10000; i++) {
ss << a;
ss << b;
}
}
static void BM_S1(benchmark::State& state) {
for (auto _ : state) {
func1();
}
}
BENCHMARK(BM_S1);
static void BM_S2(benchmark::State& state) {
for (auto _ : state) {
func2();
}
}
BENCHMARK(BM_S2);
static void BM_S3(benchmark::State& state) {
for (auto _ : state) {
func3();
}
}
BENCHMARK(BM_S3);
static void BM_S4(benchmark::State& state) {
for (auto _ : state) {
func4();
}
}
BENCHMARK(BM_S4);
BENCHMARK_MAIN();
|
################## -Explicacion General del funcionamiento- ############################
########################################################################################
-Archivo Principal (app.js):
-Ajusta el Canvas a la pantalla (que la cubra hasta abajo)
-Se encarga de los cambios de GameMode. Y de modificar el DOM y demas
en base a las caracteristicas de c/u.
----------------------------------------------------------------------------------
-Game Modes:
-Un GameMode debe exportar si o si un object con:
-"html":el html particular del Mode (controles, texto, etc)
-"functions": un obj con las funciones que aparezcan en el html
{"key"->nombre usado en el html, value->callback}
-Obj_Manager: es un obj de tipo Dom_Manager()
se ponen los ids de los elements del html y su tipo, a los que se quiera acceder
facilmente. app.js se lo va a pasar a la class para que los pueda usar.
-class: clase que debe heredar de Base_GameMode(), y donde se encuentra la logica del Mode.
Debido a esta herencia, todos cuentan con la integracion de GraphGenerator() que crea el Grafo.
Y tambien cuentan con generate_shortPath() mediante this.__find_path().
----------------------------------------------------------------------------
-Graph Generator section:
-Tenemos un archivo principal (generators.js), donde deberian convivir los distintos GraphGenerators.
Por ahora solo tenemos uno y no hicimos arquitectura para que hayan varias clases. Asi que hablemos de este.
Cabe destacar que aqui se importa todo lo de la carpeta GraphGenerator_tools.
-La funcion de GraphGenerator() es devolver con cada generate(), tanto un InMemory_Graph() (el Grafo en dataStructure)
como tambien un GraphDraw_Manager() (el Grafo en dibujo con el que se puede interactuar)
-Primero genera la data del Grafo con la clase RandGraphData_Generator(), luego la formatea y la usa para construir
las dos clases mencionadas anteeiormente. (InMemory_Graph, GraphDraw_Manager)
Por eso al construir el GraphGenerator() se le pasa data que necesite el RandGraphData_Generator(), asi como tambien que necesite
el GraphDraw_Manager (colores de nodos, de edges, el objeto canvas, etc)
Tambien tiene la opcion de pasarle un type. Como lo tenemos ahora, ese type tambien se le pasa al RandGraphData_Generator().
Que segun ese type elije de que forma generar el Grafo. Sin embargo, por ahora tambien tenemos uno solo ("alligned"). Y por eso dejamos fijo ese.
-RandGraphData_Generator():
-Forma parte de GraphGenerator_tools en la carpeta DataGraph_Generators.
-Como vimos antes, esta clase se encarga de generar la data del Grafo (basicamente es quien crea el Grafo)(hace los calculos todo, etc)
-Como genera la data:
-Primero que nada recibe ciertos params al contruirse, como el espacio total, el tamaño del node, la minima distancia entre nodes, etc.
-El sistema esta basado en crear distintas divisiones en el espacio total.
-Luego crea nodos random (que no se toquen) en cada una de esas divisiones.
-Luego conecta los nodos dentro de cada division
-Por ultimo elije ciertos nodos y los conecta con nodes de otras divisiones (conecta las divisiones)
-Si usaramos distintos types, lo que cambiaria es la forma de generar las divisiones. Osea el DivisionsGenerator().
Lo demas es fijo (conectar nodos, conectar divs, el objeto node, el objeto Division, etc)
Por ahora solo tenemos uno "AlignedRandom_DivisionsGenerator()" que hereda de DivisionsGenerator().
Si se quiere hacer otro, estan muy bien especificados los requisitos que debe cumplir en el mismo archivo "DivGenerator.js".
Como devuelve la data: (el formato)
-Devuelve un arr con todo lo que creo. Cada cosa creada la devuelve en un obj lit.
-Los nodes son {"type":"node", "value"->coordenada} coordenada="{coord_x},{coord_y}"
-Los edges son {"type":"edge", "value"->coordenadas de ambos nodes} coordenadas de ambos="{cordenadas_node1}-{cordenadas_node2}"
Las coords son iguales que las de arriba.
Estan separadas las de un node de las otras por un "-"
Por eso si recibimos un edge, y queremos cada node. Tenemos que hacer obj.value.split("-")
(De eso se encargan los formatters luego en el GraphGenerator())
generate_shortPath:
-Es una funcion que al igual que GraphGenerator(), se encuentra en generators.js
-Se encarga de lidiar con todo lo de encontrar el shortest_path
-Lo pusimos en este archivo porque tambien usa cosas de la carpeta GraphGenerator_tools.
-Ahi tiene los algortimos, su formatter.
|
import React, { useEffect, useState, useRef } from "react";
import { useNavigate, useOutletContext } from "react-router-dom";
import PostService from "../services/PostService";
import ShopService from "../services/ShopService";
import AuthService from "../services/AuthService";
const AddProduct = () => {
const navigate = useNavigate();
const [currentUser, setCurrentUser] = useState(null);
const [postData, setPostData] = useState({
title: "",
price: "",
stock: "",
});
const [cover, setCover] = useState("file name");
const [preview, setPreview] = useState();
const [ifPreview, setIfPreview] = useState(false);
const titleRef = useRef(null);
const priceRef = useRef(null);
const stockRef = useRef(null);
const descriptionRef = useRef(null);
useEffect(() => {
window.scrollTo(0, 0);
setCurrentUser(AuthService.getCurrentUser());
}, []);
//預覽封面
const handleCoverPreview = (e) => {
if (!e.target.files || e.target.files.length == 0) {
return;
}
console.log(URL.createObjectURL(e.target.files[0]));
setPreview(URL.createObjectURL(e.target.files[0]));
setCover(e.target.files[0].name);
};
//預覽商品貼文
const handlePreviewPostBtn = () => {
setPostData((prev) => {
return {
title: titleRef.current.value,
price: priceRef.current.value,
stock: stockRef.current.value,
description: descriptionRef.current.value,
};
});
setIfPreview((prev) => {
return () => {
return postData.title && postData.price && postData.stock
? true
: false;
};
});
};
const handleSubmit = async (e) => {
try {
const title = postData.title;
const price = postData.price;
const stock = postData.stock;
const description = postData.description;
const response = JSON.parse(localStorage.getItem("user")).username;
const file = document.querySelector("#fileUpload").files[0];
const result = await ShopService.addProduct(
{ title, price, stock, description, response },
file
);
console.log(result);
navigate("/profile");
} catch (e) {
console.log(e);
}
};
return (
<div className="addProductPage">
{currentUser && currentUser.role == "instructor" ? (
<div className="addPostPage">
<h1 className="addPostTitle">Add Product</h1>
<div className="addPostAndRender">
<form action="post" className="addPostMain">
<div className="titleAndPrice">
<label htmlFor="title">Title</label>
<input
className="titleInput"
type="text"
id="title"
ref={titleRef}
/>
<label htmlFor="price">Price(NTD)</label>
<input
type="number"
id="price"
className="productPriceInput"
ref={priceRef}
/>
<label htmlFor="stock">Stock</label>
<input
type="number"
id="stock"
className="productStockInput"
ref={stockRef}
/>
</div>
<div className="postCover">
<div className="uploadImgWord">Upload Cover Image (square)</div>
<div className="uploadImgSection">
<label htmlFor="fileUpload" className="customFileUpload">
Click to select
</label>
<input
id="fileUpload"
type="file"
accept="image/jpg, image/png, image/jpeg, image/svg, image/JPG, image/JPEG, image/gif, image/GIF, image/webp"
onChange={handleCoverPreview}
/>
<div style={{ overflow: "scroll" }}>{cover}</div>
</div>
<div className="postCoverPreview">
{preview ? <img src={preview} alt="" /> : "preview"}
</div>
</div>
<div className="productDescription">
<label htmlFor="description">Introduce the MAG!</label>
<textarea
ref={descriptionRef}
name="description"
id="description"
cols="30"
rows="10"
></textarea>
</div>
</form>
<div className="previewPostBtn" onClick={handlePreviewPostBtn}>
Double Check!
</div>
<div className="previewPost">
{postData.title && (
<div className="previewPostTitleAndImg">
<h1 className="previewPostTitle ">{postData.title}</h1>
<div className="previewPostImg">
<img src={preview} alt="" />
</div>
<div className="previewDescription">
{postData.description}
</div>
</div>
)}
<div className="previewPostPrAndSt">
{postData.price && (
<div className="previewPostPrice">
PRICE:{postData.price}NTD
</div>
)}
{postData.stock && (
<div className="previewPostStock">STOCK:{postData.stock}</div>
)}
</div>
</div>
{postData.title &&
postData.price &&
postData.stock &&
postData.description ? (
<button
className="submitPost"
type="submit"
onClick={handleSubmit}
disabled={!ifPreview}
>
Submit
</button>
) : (
<>
<button
className="submitPost"
type="submit"
onClick={handleSubmit}
disabled
>
Submit
</button>
<p style={{ color: "#aaa" }}>(*double check before submit)</p>
</>
)}
</div>
</div>
) : (
<div className="errorPage">Edditor Only</div>
)}
</div>
);
};
export default AddProduct;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
crossorigin="anonymous"
/>
<link rel="stylesheet" href="css/utilites.css" />
<link rel="stylesheet" href="css/style.css " />
<title>Fake Cloud Hosting</title>
</head>
<body>
<div class="navbar">
<div class="container flex">
<h1 class="logo">Fake Cloud.</h1>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="./innerPage/features.html">Features</a></li>
<li><a href="./innerPage/docs.html">Docs</a></li>
</ul>
</nav>
</div>
</div>
<!-- showcase -->
<section class="showcase">
<div class="container grid">
<div class="showcase-text">
<h1>Easier Deployment</h1>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Incidunt
recusandae ipsa distinctio veritatis est ipsam!
</p>
<a href="features.html" class="btn btn-outline">Read More</a>
</div>
<div class="showcase-form card">
<h2>Request a Demo</h2>
<form name="contact" method="POST" data-netlify="true">
<input type="hidden" name="form-name" value="contact" />
<p class="hidden">
<label
>Don’t fill this out if you're human: <input name="bot-field"
/></label>
</p>
<div class="form-control">
<input type="text" name="name" placeholder="Name" required />
</div>
<div class="form-control">
<input
type="text"
name="company"
placeholder="Compnay Name"
required
/>
</div>
<div class="form-control">
<input type="email" name="email" placeholder="Email" required />
</div>
<input type="submit" value="Send" class="btn btn-primary" />
</form>
</div>
</div>
</section>
<!-- showcase -->
<!-- stats -->
<section class="stats">
<div class="container">
<h3 class="stats-heading text-center my-1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus aliquam
voluptates ea, excepturi magni aspernatur aliquid?
</h3>
<div class="grid grid-3 text-center my-4">
<div>
<i class="fas fa-server fa-3x"></i>
<h3>10,3449,405</h3>
<p class="text-secondary">Deployments</p>
</div>
<div>
<i class="fas fa-upload fa-3x"></i>
<h3>987 TB</h3>
<p class="text-secondary">Published</p>
</div>
<div>
<i class="fas fa-project-diagram fa-3x"></i>
<h3>2,343,265</h3>
<p class="text-secondary">Projects</p>
</div>
</div>
</div>
</section>
<!-- stats -->
<!-- cli -->
<section class="cli">
<div class="container grid">
<img src="images/cli.png" alt="" />
<div class="card">
<h3>Easy to use, cross platform CLI</h3>
</div>
<div class="card">
<h3>Deployment in Seconds</h3>
</div>
</div>
</section>
<!-- cli -->
<!-- cloud hosting -->
<section class="cloud bg-primary my-2 py-2">
<div class="container grid">
<div class="text-center">
<h2 class="lg">Extreme Cloud Hosting</h2>
<p class="lead my-1">
Cloud hosting like you've never seen. Fast, efficent and scalable
</p>
<a href="features.html" class="btn btn-dark">Read More</a>
</div>
<img src="images/cloud.png" alt="" />
</div>
</section>
<!-- cloud hosting -->
<!-- language -->
<section class="languages">
<h2 class="md text-center my-2">
Supported Languages
</h2>
<div class="container flex">
<div class="card">
<h4>Node.js</h4>
<img src="images/logos/node.png" alt="" />
</div>
<div class="card">
<h4>C#</h4>
<img src="images/logos/csharp.png" alt="" />
</div>
<div class="card">
<h4>Go</h4>
<img src="images/logos/go.png" alt="" />
</div>
<div class="card">
<h4>PHP</h4>
<img src="images/logos/php.png" alt="" />
</div>
<div class="card">
<h4>Python</h4>
<img src="images/logos/python.png" alt="" />
</div>
<div class="card">
<h4>Ruby</h4>
<img src="images/logos/ruby.png" alt="" />
</div>
<div class="card">
<h4>Scala</h4>
<img src="images/logos/scala.png" alt="" />
</div>
</div>
</section>
<!-- language -->
<!-- footer -->
<footer class="footer bg-dark py-5">
<div class="container grid grid-3">
<div>
<h1>Fake Cloud Hosting</h1>
<p>Copyright © 2020</p>
</div>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="./innerPage/features.html">Features</a></li>
<li><a href="docs.html">Docs</a></li>
</ul>
</nav>
<div class="social">
<a href=""><i class="fab fa-github fa-2x"></i></a>
<a href=""><i class="fab fa-facebook fa-2x"></i></a>
<a href=""><i class="fab fa-instagram fa-2x"></i></a>
<a href=""><i class="fab fa-twitter fa-2x"></i></a>
</div>
</div>
</footer>
<!-- footer -->
</body>
</html>
|
import XCTest
@testable import SeaShell
@testable import BasicMath
final class SeaShellTests: XCTestCase {
let seaShell = SeaShell(math: Math())
func testAdd() throws {
XCTAssertEqual(seaShell.add(a: 1, b: 2), 3)
}
func testSubtract() throws {
XCTAssertEqual(seaShell.subtract(a: 2, b: 1), 1)
}
func testRepeatNumber() throws {
XCTAssertEqual(seaShell.repeatNumber(x: 9, n: 3), [9, 9, 9])
}
func testRandomRepeatNumber() throws {
let a = seaShell.randomRepeatNumber(x: 42)
XCTAssertGreaterThanOrEqual(a.count, 2)
XCTAssertLessThanOrEqual(a.count, 5)
a.forEach {
XCTAssertEqual($0, 9)
}
}
func testAddNumbers() throws {
XCTAssertEqual(seaShell.addNumbers(a: [3, 3, 3]), 9)
}
}
|
import { useEffect, useState } from "react";
import { Form } from "./Form";
import { uid } from "uid";
import List from "./components/List";
import useLocalStorageState from "use-local-storage-state";
import "./styles.css";
function App() {
const [emoji, setEmoji] = useState("⏳");
const [temp, setTemp] = useState("");
const [weather, setWeather] = useState(true);
const [activities, setActivities] = useLocalStorageState("activity", {
defaultValue: [],
});
function handleAddActivity(newActivity) {
setActivities([...activities, { id: uid(), ...newActivity }]);
console.log(newActivity);
}
function handleDeleteActivity(id) {
setActivities(activities.filter((activity) => activity.id !== id));
}
const filteredActivities = activities.filter(
(activity) => activity.isForGoodWeather === weather
);
async function weatherFetch() {
try {
const response = await fetch(
"https://example-apis.vercel.app/api/weather"
);
const data = await response.json();
console.log(data);
setWeather(data.isGoodWeather);
setEmoji(data.condition);
setTemp(data.temperature);
} catch (error) {
console.log("Error", error);
}
}
useEffect(() => {
const interval = setInterval(weatherFetch, 2000);
return () => clearInterval(interval);
}, []);
return (
<>
<header>
<p className="weather--emoji">{emoji}</p>
<p className="weather--temperature">
{!temp ? "Loading..." : `${temp}°C`}
</p>
</header>
<Form
title={
!temp
? ""
: weather
? "good weather activities"
: "bad weather activities"
}
onAddActivity={handleAddActivity}
/>
<List
activities={filteredActivities}
onDeleteActivity={handleDeleteActivity}
/>
</>
);
}
export default App;
|
/*
* Copyright 2022 storch.dev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package torch
package nn
package functional
import org.bytedeco.pytorch
import org.bytedeco.pytorch.global.torch as torchNative
import org.bytedeco.javacpp.LongPointer
import torch.internal.NativeConverters.toOptional
import org.bytedeco.pytorch.{ScalarTypeOptional, TensorOptional}
private[torch] trait Activations {
/** Applies a softmax followed by a logarithm.
*
* While mathematically equivalent to log(softmax(x)), doing these two operations separately is
* slower and numerically unstable. This function uses an alternative formulation to compute the
* output and gradient correctly.
*
* See `torch.nn.LogSoftmax` for more details.
*
* @group nn_activation
*/
def logSoftmax[In <: DType, Out <: DType](input: Tensor[In], dim: Long)(
dtype: Out = input.dtype
): Tensor[Out] =
val nativeDType =
if dtype == input.dtype then ScalarTypeOptional() else ScalarTypeOptional(dtype.toScalarType)
Tensor(torchNative.log_softmax(input.native, dim, nativeDType))
/** Applies the rectified linear unit function element-wise.
*
* See [[torch.nn.ReLU]] for more details.
*
* @group nn_activation
*/
def relu[D <: DType](input: Tensor[D]): Tensor[D] = Tensor(torchNative.relu(input.native))
/** Applies the element-wise function $\text{Sigmoid}(x) = \frac{1}{1 + \exp(-x)}$
*
* See `torch.nn.Sigmoid` for more details.
*
* @group nn_activation
*/
def sigmoid[D <: DType](input: Tensor[D]): Tensor[D] = Tensor(torchNative.sigmoid(input.native))
/** Applies a softmax function.
*
* @group nn_activation
*/
def softmax[In <: DType, Out <: DType](input: Tensor[In], dim: Long)(
dtype: Out = input.dtype
): Tensor[Out] =
val nativeDType =
if dtype == input.dtype then ScalarTypeOptional() else ScalarTypeOptional(dtype.toScalarType)
Tensor(torchNative.softmax(input.native, dim, nativeDType))
}
|
import { Routes } from "@angular/router";
import { HomeComponent } from "./home/home.component";
import { ErrorPageComponent } from "./error-page/error-page.component";
import { JourneysComponent } from "./journeys/journeys.component";
import { JourneyFormComponent } from "./journey-form/journey-form.component";
import { JourneyComponent } from "./journey/journey.component";
import { LoginComponent } from "./login/login.component";
import { RegisterComponent } from "./register/register.component";
export const AppRoutes = [
{
path: "",
component: HomeComponent
},
{
path: "journeys",
component: JourneysComponent
},
{
path: "journeys/create",
component: JourneyFormComponent
},
{
path: "journey/:journeyId",
component: JourneyComponent
},
{
path: "journey/:journeyId/edit",
component: JourneyFormComponent
},
{
path: "register",
component: RegisterComponent
},
{
path: "login",
component: LoginComponent
},
{
path: "**",
component: ErrorPageComponent
}
]
|
import pygame
from configs import width, height
# Item 클래스
class Item:
def __init__(self, x, y):
self.image = pygame.image.load('item.png')
self.size = [30, 30]
self.image = pygame.transform.scale(self.image, (self.size[0], self.size[1]))
self.x = x
self.y = y
self.speed = 10
self.move_direction = 1
def move(self):
self.y += self.speed
def draw(self, surface):
surface.blit(self.image, (self.x, self.y))
class RegisterItem(Item):
def __init__(self, x, y):
super().__init__(x, y)
self.image = pygame.image.load('register_item.png') # 폭발 아이템 이미지
self.image = pygame.transform.scale(self.image, (self.size[0], self.size[1]))
class CapacitorItem(Item):
def __init__(self, x, y):
super().__init__(x, y)
self.image = pygame.image.load('capacitor_item.png') # 폭발 아이템 이미지
self.image = pygame.transform.scale(self.image, (self.size[0], self.size[1]))
class OscillatorItem(Item):
def __init__(self, x, y):
super().__init__(x, y)
self.size = [20, 20]
self.image = pygame.image.load('oscillator_item.png') # 폭발 아이템 이미지
self.image = pygame.transform.scale(self.image, (self.size[0], self.size[1]))
class MosfetItem(Item):
def __init__(self, x, y):
super().__init__(x, y)
self.size = [20, 20]
self.image = pygame.image.load('mosfet_item.png') # 폭발 아이템 이미지
self.image = pygame.transform.scale(self.image, (self.size[0], self.size[1]))
class StarItem(Item):
def __init__(self, x, y):
super().__init__(x, y)
self.size = [20, 20]
self.image = pygame.image.load('star.png')
self.image = pygame.transform.scale(self.image, (self.size[0], self.size[1]))
|
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClient, HttpClientModule } from '@angular/common/http';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
BrowserAnimationsModule,
HttpClientModule
],
declarations: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});
|
import { playwrightExpect } from '../utils/fixtureHooks';
/* The above code is a generic class which is used to call the playwright expect methods but its all generic. */
export abstract class ExpectGenericCoreCalls {
public static negativeAssertion: boolean = false;
/**
* toHaveLength
* * To check if the object/array to have expected length
* @param object The Object/Array to checked for length
* @param expected Expected Length of the Object/Array
* @param message The Message to be used on expect
*/
public static toHaveLength = (
object: unknown,
expected: number,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(object, message).not.toHaveLength(expected)
: playwrightExpect.expect(object, message).toHaveLength(expected);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toHaveProperty
* * To check if the object/array to have expected property/key
* @param object The Object/Array to checked for length
* @param keyPath The property/key of an object
* @param value The expected value of key/property
* @param message The Message to be used on expect
*/
public static toHaveProperty = (
object: unknown,
keyPath: string | Array<string>,
value?: unknown,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect
.expect(object, message)
.not.toHaveProperty(keyPath, value)
: playwrightExpect.expect(object, message).toHaveProperty(keyPath, value);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBe
* * To check if the actual is same as expected
* @param actual The actual data to be checked
* @param expected The expected data to be checked
* @param message The Message to be used on expect
*/
public static toBe = (
actual: unknown,
expected: unknown,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(actual, message).not.toBe(expected)
: playwrightExpect.expect(actual, message).toBe(expected);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toEqual
* * To check if the actual is same as expected
* @param actual The actual data to be checked
* @param expected The expected data to be checked
* @param message The Message to be used on expect
*/
public static toEqual = (
actual: unknown,
expected: unknown,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(actual, message).not.toEqual(expected)
: playwrightExpect.expect(actual, message).toEqual(expected);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBeFalsy
* * To check if the actual data is false
* @param actual The actual data to be checked
* @param message The Message to be used on expect
*/
public static toBeFalsy = (
actual: unknown,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(actual, message).not.toBeFalsy()
: playwrightExpect.expect(actual, message).toBeFalsy();
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBeTruthy
* * To check if the actual data is true
* @param actual The actual data to be checked
* @param message The Message to be used on expect
*/
public static toBeTruthy = (
actual: unknown,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(actual, message).not.toBeTruthy()
: playwrightExpect.expect(actual, message).toBeTruthy();
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBeCloseTo
* * To check if the actual data is as close to expected
* @param actual The actual data to be checked
* @param expected The expected data to be checked
* @param numDigits The expected data to close to match
* @param message The Message to be used on expect
*/
public static toBeCloseTo = (
actual: unknown,
expected: number,
numDigits?: number,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect
.expect(actual, message)
.not.toBeCloseTo(expected, numDigits)
: playwrightExpect
.expect(actual, message)
.toBeCloseTo(expected, numDigits);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBeGreaterThan
* * To check if the actual data is greater than expected
* @param actual The actual data to be checked
* @param expected The expected data to be checked
* @param message The Message to be used on expect
*/
public static toBeGreaterThan = (
actual: unknown,
expected: number | bigint,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(actual, message).not.toBeGreaterThan(expected)
: playwrightExpect.expect(actual, message).toBeGreaterThan(expected);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBeGreaterThanOrEqual
* * To check if the actual data is greater than or equal to expected
* @param actual The actual data to be checked
* @param expected The expected data to be checked
* @param message The Message to be used on expect
*/
public static toBeGreaterThanOrEqual = (
actual: unknown,
expected: number | bigint,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect
.expect(actual, message)
.not.toBeGreaterThanOrEqual(expected)
: playwrightExpect
.expect(actual, message)
.toBeGreaterThanOrEqual(expected);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBeLessThan
* * To check if the actual data is less than expected
* @param actual The actual data to be checked
* @param expected The expected data to be checked
* @param message The Message to be used on expect
*/
public static toBeLessThan = (
actual: unknown,
expected: number | bigint,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(actual, message).not.toBeLessThan(expected)
: playwrightExpect.expect(actual, message).toBeLessThan(expected);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBeLessThanOrEqual
* * To check if the actual data is less than or equal to expected
* @param actual The actual data to be checked
* @param expected The expected data to be checked
* @param message The Message to be used on expect
*/
public static toBeLessThanOrEqual = (
actual: unknown,
expected: number | bigint,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect
.expect(actual, message)
.not.toBeLessThanOrEqual(expected)
: playwrightExpect.expect(actual, message).toBeLessThanOrEqual(expected);
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toBeUndefined
* * To check if the actual data is undefined
* @param actual The actual data to be checked
* @param message The Message to be used on expect
*/
public static toBeUndefined = (
actual: unknown,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(actual, message).not.toBeUndefined()
: playwrightExpect.expect(actual, message).toBeUndefined();
ExpectGenericCoreCalls.negativeAssertion = false;
};
/**
* toContain
* * To check if the actual data to contain expected
* @param actual The actual data to be checked
* @param expected The actual data to be checked
* @param message The Message to be used on expect
*/
public static toContain = (
actual: unknown,
expected: unknown,
message?: string | undefined
): void => {
ExpectGenericCoreCalls.negativeAssertion
? playwrightExpect.expect(actual, message).not.toContain(expected)
: playwrightExpect.expect(actual, message).toContain(expected);
ExpectGenericCoreCalls.negativeAssertion = false;
};
}
|
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
import pandas as pd
from sqlalchemy import create_engine
import tempfile
import os
import ccxt
def create_dataframe(**kwargs):
exchange = ccxt.binance()
bars = exchange.fetch_ohlcv("BTC/USDT", timeframe = "5m", limit =10)
df = pd.DataFrame(bars,columns=["time","open","high","low","close","volumen"])
# Guarda el DataFrame en un archivo temporal
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as temp_file:
df.to_csv(temp_file.name, index=False)
kwargs['ti'].xcom_push(key='temp_file_path', value=temp_file.name)
def load_to_redshift(**kwargs):
temp_file_path = kwargs['ti'].xcom_pull(task_ids='create_dataframe_task', key='temp_file_path')
# Lee el DataFrame desde el archivo temporal
df = pd.read_csv(temp_file_path)
# Cambia el nombre de la columna "open" a "open_price"
df.rename(columns={'open': 'open_price'}, inplace=True)
# Cadena de conexión de Redshift
redshift_connection_string = "postgresql://arturomontesdeoca4892_coderhouse:AqiS616AWa@data-engineer-cluster.cyhh5bfevlmn.us-east-1.redshift.amazonaws.com:5439/dev"
# Crea un motor de SQLAlchemy para la conexión
engine = create_engine(redshift_connection_string)
# Convierte el DataFrame a una tabla en Redshift
table_name = 'pietroboni'
df.to_sql(table_name, engine, if_exists='replace', index=False)
# Cierra la conexión de SQLAlchemy
engine.dispose()
default_args = {
'owner': 'DavidBU',
'retries': 3,
'retry_delay': timedelta(minutes=1)
}
with DAG(
default_args=default_args,
dag_id='BINANCE',
start_date=datetime(2023, 9, 10),
schedule_interval='0 0 * * *'
) as dag:
task1 = PythonOperator(
task_id='create_dataframe_task',
python_callable=create_dataframe,
provide_context=True # Deshabilita la serialización JSON del valor de retorno
)
task2 = PythonOperator(
task_id='load_to_redshift_task',
python_callable=load_to_redshift,
provide_context=True # Deshabilita la serialización JSON del valor de retorno
)
task1 >> task2
|
package chaperone.com.securityConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebSecurity
public class MyConfig extends WebSecurityConfigurerAdapter {
@Value("${my.urls.loginUrl}")
private String loginUrl;
@Value("${my.urls.logout}")
private String logoutUrl;
@Value("${my.urls.baseUrl")
private String baseUrl;
@Bean
public UserDetailsService getUserDetailsService(){
return new UserDetailsServiceImp();
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(this.getUserDetailsService());
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
authenticationManagerBuilder.authenticationProvider(authenticationProvider());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity
.cors()
.and()
.authorizeRequests()
.antMatchers("/chaperone/admin/**")
.hasRole("ADMIN")
.antMatchers("chaperone/user/**")
.hasRole("CUSTOMER")
.antMatchers("/**")
.permitAll()
.and()
.formLogin()
.and()
.csrf()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://localhost:3000");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
|
import React from "react";
import { Paper, Title, Text, TextInput, Button, Container, Group, Anchor, Center, Box } from "@mantine/core";
import { showNotification } from "@mantine/notifications";
import { ArrowLeft } from "tabler-icons-react";
import { Link } from "react-router-dom";
import { useStyles } from "../../styles/ForgotPassword";
import { auth, sendPasswordResetEmail } from "../../utils/firebaseConfig";
const ForgotPassword = () => {
const { classes } = useStyles();
const [email, setEmail] = React.useState("");
const submitHandler = (e) => {
e.preventDefault();
sendPasswordResetEmail(auth, email)
.then(() => showNotification({ title: "Password reset mail sent Successfull !", message: "Please check your inbox !" }))
.catch((error) => showNotification({ color: "red", title: "Error sending password reset mail", message: "Please try again" }));
};
return (
<Container size={460} my={30}>
<Title className={classes.title} align="center">
Forgot your password?
</Title>
<Text color="dimmed" size="sm" align="center">
Enter your email to get a reset link
</Text>
<Paper withBorder shadow="md" p={30} radius="md" mt="xl">
<TextInput label="Your email" placeholder="[email protected]" required value={email} onChange={(e) => setEmail(e.currentTarget.value)} />
<Group position="apart" mt="lg" className={classes.controls}>
<Link to="/auth">
<Anchor color="dimmed" size="sm" className={classes.control}>
<Center inline>
<ArrowLeft size={12} />
<Box ml={5}>Back to login page</Box>
</Center>
</Anchor>
</Link>
<Button type="submit" className={classes.control} onClick={submitHandler}>
Reset password
</Button>
</Group>
</Paper>
</Container>
);
};
export default ForgotPassword;
|
import { useReducer } from "react";
import { MemoryGameContext } from "../contexts/MemoryGameContext";
import { shuffle } from "../util";
import Card from "./Card";
import leagueLogo from "../assets/league-logo.png";
function reducer(state: MemoryGame, action: GameCardAction): MemoryGame {
function resetCards() {
return state.cards.map((card) => ({ ...card, clicked: false }));
}
switch (action.type) {
case "set_clicked":
const cards = [];
for (const card of state.cards) {
if (card.id == action.id) {
if (card.clicked) {
state.isOver = true;
} else {
card.clicked = true;
state.score = state.score + 1;
if (state.score > state.highScore) {
state.highScore = state.score;
localStorage.setItem("x34.f-22f.", state.highScore.toString(16));
}
if (state.score == state.cards.length) state.isOver = true;
}
}
cards.push(card);
}
return {
...state,
cards: shuffle(cards),
};
case "shuffle":
return { ...state, cards: shuffle(state.cards) };
case "reset":
return {
highScore: state.highScore,
isOver: false,
score: 0,
cards: shuffle(resetCards()),
};
default:
throw new Error("Invalid action type");
}
}
export default function MemoryGame({ cards }: { cards: GameCard[] }) {
const highScore = localStorage.getItem("x34.f-22f.");
const [game, dispatch] = useReducer(reducer, {
cards,
isOver: false,
score: 0,
highScore: highScore ? parseInt(highScore, 16) : 0,
});
return (
<>
{game.isOver && (
<div className="flex items-center justify-center fixed top-0 left-0 w-screen h-screen min-h-[900px] bg-gray-800/40 z-30">
<div
className="px-10 py-2 rounded-md bg-emerald-500 text-3xl cursor-pointer font-bold text-white hover:bg-emerald-600 hover:scale-105 transition-all duration-500"
onClick={() => {
dispatch({ type: "reset" });
}}
>
Retry
</div>
</div>
)}
<div className="relative">
<img
src={leagueLogo}
alt="League of Legends"
className="font-extrabold text-4xl text-center h-40 mx-auto"
/>
<div className="flex flex-col text-center text-3xl font-extrabold mb-4 text-gray-50 absolute top-4 right-4">
<div className="flex gap-x-4">
<span>Score:</span>
<span>{game.score}</span>
</div>
<div className="flex gap-x-4">
<span>Highscore:</span>
<span>{game.highScore}</span>
</div>
</div>
</div>
<div className="flex gap-4 flex-wrap">
<MemoryGameContext.Provider value={{ game, dispatch }}>
{game.cards.map((card) => (
<Card key={card.id} {...card} />
))}
</MemoryGameContext.Provider>
</div>
</>
);
}
|
import React, { useEffect, useState } from 'react';
import raw from '../files/day10.txt';
import { readFile } from '../utils';
const Day10 = () => {
const [input, setInput] = useState();
const [part, setPart] = useState();
const [part1Result, setPart1Result] = useState();
const [part2Result, setPart2Result] = useState();
const bracketMap = {
['(']: ')',
['{']: '}',
['<']: '>',
['[']: ']',
};
const scoreMap = {
[')']: 1,
[']']: 2,
['}']: 3,
['>']: 4,
};
const findPart1Answer = () => {
console.log(input);
const invalids = [];
input.forEach((row) => {
const openBrackets = [];
for (let i = 0; i < row.length; i++) {
const char = row[i];
const lastOpenBracket = openBrackets.slice(-1)[0];
if (char === '(' || char === '{' || char === '<' || char === '[') {
openBrackets.push(char);
} else if (
(char === ')' && lastOpenBracket !== '(') ||
(char === '}' && lastOpenBracket !== '{') ||
(char === '>' && lastOpenBracket !== '<') ||
(char === ']' && lastOpenBracket !== '[')
) {
invalids.push(char);
break;
} else {
openBrackets.pop();
}
}
});
let total =
invalids.filter((val) => val === ')').length * 3 +
invalids.filter((val) => val === ']').length * 57 +
invalids.filter((val) => val === '}').length * 1197 +
invalids.filter((val) => val === '>').length * 25137;
setPart1Result(total);
};
const findPart2Answer = () => {
console.log(input);
const justValids = input.filter((row) => {
const openBrackets = [];
for (let i = 0; i < row.length; i++) {
const char = row[i];
const lastOpenBracket = openBrackets.slice(-1)[0];
if (char === '(' || char === '{' || char === '<' || char === '[') {
openBrackets.push(char);
} else if (
(char === ')' && lastOpenBracket !== '(') ||
(char === '}' && lastOpenBracket !== '{') ||
(char === '>' && lastOpenBracket !== '<') ||
(char === ']' && lastOpenBracket !== '[')
) {
return false;
} else {
openBrackets.pop();
}
}
return true;
});
console.log(justValids);
const completionStrings = [];
justValids.forEach((row) => {
const completionString = [];
const closeBrackets = [];
for (let i = row.length - 1; i >= 0; i--) {
const char = row[i];
const lastCloseBracket = closeBrackets.slice(-1)[0];
if (char === ')' || char === '}' || char === '>' || char === ']') {
closeBrackets.push(char);
} else if (
(char === '(' && lastCloseBracket !== ')') ||
(char === '{' && lastCloseBracket !== '}') ||
(char === '<' && lastCloseBracket !== '>') ||
(char === '[' && lastCloseBracket !== ']')
) {
completionString.push(bracketMap[char]);
} else {
closeBrackets.pop();
}
}
completionStrings.push(completionString);
});
const completionScores = completionStrings.map((completionString) =>
completionString.reduce((acc, char) => acc * 5 + scoreMap[char], 0)
);
completionScores.sort((a, b) => a - b);
setPart2Result(
completionScores.slice(
completionScores.length / 2,
completionScores.length / 2 + 1
)[0]
);
};
useEffect(() => {
if (part === 1) {
findPart1Answer();
}
if (part === 2) {
findPart2Answer();
}
}, [input]);
const part1 = () => {
setPart(1);
readFile(raw, setInput);
};
const part2 = () => {
setPart(2);
readFile(raw, setInput);
};
return (
<div>
<br />
Day 10
<div className="flex">
<button onClick={part1}>part 1</button>
{part1Result && ` ${part1Result}`}
</div>
<div className="flex">
<button onClick={part2}>part 2</button>
{part2Result && ` ${part2Result}`}
</div>
</div>
);
};
export default Day10;
|
const video = document.getElementById('video')
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
faceapi.nets.faceExpressionNet.loadFromUri('/models')
]).then(GetBrightness)
// function startVideo() {
// // navigator.getUserMedia(
// // { video: {} },
// // stream => video.srcObject = stream,
// // err => console.error(err)
// // )
// navigator.getUserMedia = navigator.getUserMedia ||
// navigator.webkitGetUserMedia ||
// navigator.mozGetUserMedia;
// if (navigator.getUserMedia) {
// navigator.getUserMedia({ audio: false, video: {} },
// function(stream) {
// var video = document.querySelector('video');
// video.srcObject = stream;
// video.onloadedmetadata = function(e) {
// video.play();
// };
// },
// function(err) {
// console.log("The following error occurred: " + err.name);
// }
// );
// } else {
// console.log("getUserMedia not supported");
// }
// }
video.addEventListener('play', () => {
const canvas = faceapi.createCanvasFromMedia(video)
var canvasctx = canvas.getContext('2d')
const area = document.getElementById('container')
area.append(canvas)
const displaySize = { width: video.width, height: video.height }
faceapi.matchDimensions(canvas, displaySize)
setInterval(async () => {
const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions()
const count = await faceapi
.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions())
.withFaceLandmarks()
if(count.length>1){
alert("There are multiple faces in the frame. Please keep only one face.");
}
else{
if(document.getElementById('avg-brightness').textContent<60){
button.disabled = true
document.getElementById('label').value="Low light"
document.getElementById('label').style.color='red'
document.getElementById('label').style.fontWeight='bold'
}
else{
document.getElementById('label').value="Light is ok"
document.getElementById('label').style.color='green'
document.getElementById('label').style.fontWeight='bold'
const resizedDetections = faceapi.resizeResults(detections, displaySize)
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
//faceapi.draw.drawDetections(canvas, resizedDetections)
//faceapi.draw.drawFaceLandmarks(canvas, resizedDetections)
//faceapi.draw.drawFaceExpressions(canvas, resizedDetections)
// console.log(resizedDetections[0].detection._box._height)
// console.log(resizedDetections[0].detection._box._width)
// console.log(resizedDetections[0].detection._box._x)
// console.log(resizedDetections[0].detection._box._y)
const frame_height = resizedDetections[0].detection._box._height
const frame_width = resizedDetections[0].detection._box._width
const frame_x = resizedDetections[0].detection._box._x
const frame_y = resizedDetections[0].detection._box._y
const button = document.getElementById('button')
if (((frame_height>=160 && frame_height<=270) && (frame_width>=180 && frame_width<=270)) &&
((frame_x>=100 && frame_x<=195) && (frame_y>=80 && frame_y<=190)))
{
//alert("Perfect")
button.disabled = false
button.onclick = function(){
CaptureImage();
};
}
else{
button.disabled = true
}
}
// const landmarks = await faceapi.detectFaceLandmarks(video)
// const mouth = landmarks.getMouth()
// const nose = landmarks.getNose()
// const leftEye = landmarks.getLeftEye()
// console.log(mouth[0]._x, mouth[0]._y)
// console.log(nose[0]._x, nose[0]._y)
// console.log(leftEye[0]._x, leftEye[0]._y)
// if((((mouth[0]._x<=330) && (mouth[0]._x>=280)) && ((mouth[0]._y<=310) && (mouth[0]._y>=260))) &&
// (((nose[0]._x<=320) && (nose[0]._x>=270)) && ((nose[0]._y<=220) && (nose[0]._y>=160))) &&
// (((leftEye[0]._x<=270) && (leftEye[0]._x>=210)) && ((leftEye[0]._y<=240) && (leftEye[0]._y>=180))))
// (((mouth[1]._x<=400) && (mouth[1]._x>=300)) && ((mouth[1]._y<=300) && (mouth[1]._y>=200))) &&
// (((mouth[2]._x<=400) && (mouth[2]._x>=300)) && ((mouth[2]._y<=300) && (mouth[2]._y>=200))) &&
// (((mouth[3]._x<=400) && (mouth[3]._x>=300)) && ((mouth[3]._y<=300) && (mouth[3]._y>=200))) &&
// (((mouth[4]._x<=400) && (mouth[4]._x>=300)) && ((mouth[4]._y<=300) && (mouth[4]._y>=200))) &&
// (((mouth[5]._x<=400) && (mouth[5]._x>=300)) && ((mouth[5]._y<=300) && (mouth[5]._y>=200))))
// {
// alert("Click for perfect photo");
// }
// else{
// alert("Image not ready");
// }
}
}, 100)
})
function CaptureImage(){
document.querySelectorAll("#screenshot img")
.forEach(img => img.remove());
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d')
canvas.width = 306;
canvas.height = 392;
ctx.drawImage(video, 169, 47, 306, 392, 0, 0, 306, 392);
// const img = document.createElement("img");
// img.src = canvas.toDataURL('image/png');
// document.getElementById('screenshot').appendChild(img)
removebackground(canvas, ctx)
}
function GetBrightness(){
var w=500;
var h=375;
var imageCanvas = document.createElement( 'canvas' );
var imagectx = imageCanvas.getContext('2d');
var thresholdCanvas = document.getElementById( 'threshold-canvas' );
var thresholdctx = thresholdCanvas.getContext('2d');
var t3Canvas = document.getElementById( 't3-canvas' );
var t3ctx = t3Canvas.getContext('2d');
var brightnessCanvas = document.getElementById( 'brightness-canvas' );
var brightnessctx = brightnessCanvas.getContext('2d');
var rangeBrightness = document.getElementById( 'range-brightness' );
var rangeThreshold = document.getElementById( 'range-threshold' );
var thPercent = 0;
var overPercent = 0;
var underPercent = 0;
// var video = document.createElement('video');
// video.autoplay='autoplay';
// video.width=w;
// video.height=h;
// var constraints = {'video':true};
// if(navigator.webkitGetUserMedia){
// constraints = {
// video: {
// mandatory: {
// maxWidth: w,
// maxHeight: h
// }
// }
// };
// }
// navigator.getUserMedia = navigator.getUserMedia ||
// navigator.webkitGetUserMedia ||
// navigator.mozGetUserMedia ||
// navigator.msGetUserMedia;
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
window.requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame;
init = function(){
imageCanvas.height = video.videoHeight;
imageCanvas.width = video.videoWidth;
thresholdCanvas.height = imageCanvas.height/2;
thresholdCanvas.width = imageCanvas.width/2;
brightnessCanvas.height = imageCanvas.height/3;
brightnessCanvas.width = imageCanvas.width/2;
t3Canvas.height = imageCanvas.height/2;
t3Canvas.width = imageCanvas.width/2;
update();
}
brightness = function(pixels, adjustment) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
d[i] += adjustment;
d[i+1] += adjustment;
d[i+2] += adjustment;
}
return pixels;
};
threshold = function(imgData, threshold) {
thPercent=1;
var d = imgData.data;
for (var i=0; i<d.length; i+=4) {
var v = (0.2126*d[i] + 0.7152*d[i+1] + 0.0722*d[i+2] >= threshold) ? 255 : 0;
d[i] = d[i+1] = d[i+2] = v;
if(v===255){
thPercent++;
}
}
thPercent=thPercent/(d.length/4);
return imgData;
};
threshold3 = function(imgData, threshold,floor,ceil) {
underPercent=1;
overpercent=1;
var d = imgData.data, f,b,c,v;
for (var i=0; i<d.length; i+=4) {
b = 0.2126*d[i] + 0.7152*d[i+1] + 0.0722*d[i+2];
if (b >= ceil){
d[i] = 255;
d[i+1] = 255;
d[i+2] = 0;
overPercent++;
} else if(b <= floor){
d[i] = 255;
d[i+1] = 0;
d[i+2] = 0;
underPercent++;
} else {
v = (b >= threshold) ? 255 : 0
d[i] = v;
d[i+1] = v;
d[i+2] = v;
}
}
overPercent=overPercent/(d.length/4);
underPercent=underPercent/(d.length/4);
return imgData;
};
average = function(imgData) {
var d = imgData.data;
var rgb ={r:0,g:0,b:0};
for (var i=0; i<d.length; i+=4) {
rgb.r += d[i];
rgb.g += d[i+1];
rgb.b += d[i+2];
}
rgb.r = ~~(rgb.r/(d.length/4));
rgb.g = ~~(rgb.g/(d.length/4));
rgb.b = ~~(rgb.b/(d.length/4));
return rgb;
};
update = function(){
var alpha,data;
imagectx.drawImage(video, 0, 0,video.videoWidth, video.videoHeight, 0,0,imageCanvas.width,imageCanvas.height);
if(rangeBrightness.value < 50){
alpha = 0-((1-(rangeBrightness.value/50))*255);
} else {
alpha = ((rangeBrightness.value-50)/50)*255;
}
pixThreshold = rangeThreshold.value;
data = brightness(imagectx.getImageData(0,0,imageCanvas.width,imageCanvas.height), alpha);
imagectx.putImageData(data,0,0);
thresholdctx.drawImage(imageCanvas, 0, 0,imageCanvas.width, imageCanvas.height, 0,0,thresholdCanvas.width,thresholdCanvas.height);
data = threshold(thresholdctx.getImageData(0,0,thresholdCanvas.width,thresholdCanvas.height),pixThreshold);
thresholdctx.putImageData(data,0,0);
document.getElementById( 'samples' ).innerHTML = Math.round(thPercent*100*100)/100+'%';
t3ctx.drawImage(imageCanvas, 0, 0,imageCanvas.width, imageCanvas.height, 0,0,t3Canvas.width,t3Canvas.height);
data = threshold3(t3ctx.getImageData(0,0,t3Canvas.width,t3Canvas.height),pixThreshold, 55,200);
t3ctx.putImageData(data,0,0);
document.getElementById( 'samples-under' ).innerHTML = Math.round(underPercent*100*100)/100+'%';
document.getElementById( 'samples-over' ).innerHTML = Math.round(overPercent*100*100)/100+'%';
data = average(imagectx.getImageData(0,0,imageCanvas.width,imageCanvas.height));
document.getElementById( 'avg-brightness' ).innerHTML = Math.round(((0.2126*data.r + 0.7152*data.g + 0.0722*data.b)/255)*100*100)/100;
brightnessctx.fillStyle = 'rgb('+data.r+','+data.g+','+data.b+')';
brightnessctx.fillRect(0,0,brightnessCanvas.width,brightnessCanvas.height);
window.requestAnimationFrame(update);
}
error = function(e){
console.log('Snap!', e);
alert('No camera or getUserMedia() not available')
}
if (navigator.getUserMedia) {
navigator.getUserMedia(
//constraints,
{ audio: false, video: {} },
function(stream) {
var video = document.querySelector('video');
video.srcObject=stream;
// onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
vidReady = setInterval(function(){
if(video.videoHeight !== 0){
clearInterval(vidReady);
init();
}
},100)
}, error);
} else {
error('No getUserMedia')
}
// if (navigator.getUserMedia) {
// navigator.getUserMedia({ audio: false, video: {} },
// function(stream) {
// var video = document.querySelector('video');
// video.srcObject = stream;
// video.onloadedmetadata = function(e) {
// video.play();
// };
// },
// function(err) {
// console.log("The following error occurred: " + err.name);
// }
// );
// } else {
// console.log("getUserMedia not supported");
// }
}
/**
* Remove background an image
*/
async function removebackground(canvas, ctx) {
const net = await bodyPix.load({
architecture: 'MobileNetV1',
outputStride: 16,
multiplier: 0.75,
quantBytes: 2
});
// Segmentation
const { data:map } = await net.segmentPerson(canvas, {
internalResolution: 'high',
});
// Extracting image data
const { data:imgData } = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Creating new image data
const newImg = ctx.createImageData(canvas.width, canvas.height);
const newImgData = newImg.data;
for(let i=0; i<map.length; i++) {
//The data array stores four values for each pixel
const [r, g, b, a] = [imgData[i*4], imgData[i*4+1], imgData[i*4+2], imgData[i*4+3]];
[
newImgData[i*4],
newImgData[i*4+1],
newImgData[i*4+2],
newImgData[i*4+3]
] = !map[i] ? [255, 255, 255, 0] : [r, g, b, a];
}
// Draw the new image back to canvas
ctx.putImageData(newImg, 0, 0);
const img = document.createElement("img");
img.src = canvas.toDataURL('image/png');
document.getElementById('screenshot').appendChild(img)
}
|
import {
AccountBox,
DarkMode,
Group,
Home,
ModeNight,
Pages,
Settings,
Shop,
VerifiedUserSharp,
} from "@mui/icons-material";
import {
Box,
List,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
Switch,
} from "@mui/material";
import React from "react";
const SideBar = ({ mode, setMode }) => {
return (
<Box
bgcolor={"background.default"}
flex={1}
p={2}
sx={{ display: { xs: "none", sm: "block" } }}
>
<Box position="fixed">
<List>
<ListItem disablePadding>
<ListItemButton Component="a" href="#simple-list">
<ListItemIcon>
<Settings />
</ListItemIcon>
<ListItemText primary="Home" />
</ListItemButton>
</ListItem>
<ListItem disablePadding>
<ListItemButton Component="a" href="#simple-list">
<ListItemIcon>
<Pages />
</ListItemIcon>
<ListItemText primary="Pages" />
</ListItemButton>
</ListItem>
<ListItem disablePadding>
<ListItemButton Component="a" href="#simple-list">
<ListItemIcon>
<Group />
</ListItemIcon>
<ListItemText primary="Groups" />
</ListItemButton>
</ListItem>
<ListItem disablePadding>
<ListItemButton Component="a" href="#simple-list">
<ListItemIcon>
<Shop />
</ListItemIcon>
<ListItemText primary="MarketPlace" />
</ListItemButton>
</ListItem>
<ListItem disablePadding>
<ListItemButton Component="a" href="#simple-list">
<ListItemIcon>
<VerifiedUserSharp />
</ListItemIcon>
<ListItemText primary="Friends" />
</ListItemButton>
</ListItem>
<ListItem disablePadding>
<ListItemButton Component="a" href="#simple-list">
<ListItemIcon>
<Home />
</ListItemIcon>
<ListItemText primary="simple-list" />
</ListItemButton>
</ListItem>
<ListItem disablePadding>
<ListItemButton Component="a" href="#simple-list">
<ListItemIcon>
<AccountBox />
</ListItemIcon>
<ListItemText primary="Profile" />
</ListItemButton>
</ListItem>
<ListItem disablePadding>
<ListItemButton Component="a" href="#simple-list">
<ListItemIcon>
<DarkMode />
</ListItemIcon>
<Switch
onChange={(e) => setMode(mode === "light" ? "dark" : "light")}
/>
</ListItemButton>
</ListItem>
</List>
</Box>
</Box>
);
};
export default SideBar;
|
import { FunctionComponent } from 'react';
import styled from 'styled-components';
import { Palette } from '@/types/theme';
import InputFieldWrapper, { BaseInputProps } from '../inputFieldWrapper';
type BaseCheckboxProps = Omit<JSX.IntrinsicElements['input'], 'type' | 'checked'>;
type Props = BaseInputProps & BaseCheckboxProps & { color?: keyof Palette };
const CheckboxField: FunctionComponent<Props> = ({
helperText,
errorMessage,
label,
className,
value,
onChange,
...checkboxProps
}) => {
return (
<InputFieldWrapper helperText={helperText} errorMessage={errorMessage}>
<StyledCheckbox className={className} onClick={onChange}>
<input type="checkbox" checked={value} onChange={onChange} {...checkboxProps} />
<span className="checkmark"></span>
<div className="label">{label}</div>
</StyledCheckbox>
</InputFieldWrapper>
);
};
CheckboxField.defaultProps = {
color: 'primary',
defaultChecked: false,
};
const StyledCheckbox = styled.label<Props>`
display: block;
position: relative;
padding-left: 1.5rem;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
&:checked {
~ .checkmark:after {
display: block;
}
~ .checkmark {
background-color: ${(props) => props.theme.palette[props.color ?? 'primary']};
}
}
&:disabled {
+ .checkmark,
input:disabled + .checkmark + .label {
opacity: 0.5;
}
}
}
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 1.25rem;
width: 1.25rem;
margin-top: 0.125rem;
background-color: ${(props) => props.theme.palette.gray};
&:after {
content: '';
position: absolute;
display: none;
left: 0.375rem;
top: 0.2rem;
width: 0.45rem;
height: 0.75rem;
border: solid white;
border-width: 0 0.125rem 0.125rem 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
}
&:hover {
.checkmark,
.label {
opacity: 0.7;
}
}
`;
export default CheckboxField;
|
# Algoritmo De Ordenaçao QuickSort.
O algoritmo QuickSort é um eficiente algoritmo de ordenação que segue a abordagem "divide e conquista" para ordenar uma lista de elementos. Ele foi desenvolvido por Tony Hoare em 1959 e é amplamente utilizado devido à sua eficiência e velocidade em muitos casos.
- A ideia fundamental por trás do QuickSort é escolher um elemento pivô da lista e particionar os elementos ao redor desse pivô, de forma que os elementos menores que o pivô fiquem à esquerda e os elementos maiores à direita. Em seguida, o algoritmo é aplicado recursivamente às sublistas formadas antes e depois do pivô, até que toda a lista esteja ordenada.
- A escolha eficiente do pivô é crucial para o desempenho do QuickSort. Geralmente, o pivô é escolhido como o primeiro elemento da lista, mas também pode ser escolhido aleatoriamente ou como o elemento do meio. Uma estratégia comum é usar o método conhecido como "partição de Hoare" ou "partição de Lomuto" para particionar os elementos ao redor do pivô.
- O QuickSort possui uma complexidade de tempo médio de O(n log n) e uma complexidade de pior caso de O(n^2), onde n é o número de elementos na lista. No entanto, na prática, o QuickSort é geralmente mais rápido do que outros algoritmos de ordenação como o Merge Sort e o Heap Sort, devido à sua eficiência em partições de dados e baixo uso de memória auxiliar.
- Em resumo, o QuickSort é um algoritmo eficiente e amplamente utilizado para ordenação de listas, especialmente em situações onde o desempenho é crucial. Sua abordagem "divide e conquista" e escolha eficiente do pivô o tornam uma escolha popular em muitos cenários de ordenação.
# Código fonte


Esse código implementa o algoritmo de ordenação QuickSort em Java. Vamos analisar cada parte do código:
# Método quickSort:
- Recebe um array arr, um índice esquerda e um índice direita.
Se esquerda for menor que direita, realiza a ordenação.
Obtém o índice do pivô usando o método particaoAleatoria.
Chama recursivamente quickSort para as sublistas à esquerda e à direita do pivô.
Método partition:
- Recebe um array arr, um índice de início start e um índice de fim end.
Escolhe o pivô como o elemento do meio do array.
Usa uma abordagem de partição onde os elementos menores que o pivô são movidos para a esquerda, e os maiores para a direita.
Retorna o novo índice do pivô.
Método particaoAleatoria:
- Recebe um array arr, um índice esquerda e um índice direita.
Escolhe aleatoriamente um índice para o pivô e troca o valor do pivô com o valor na posição direita.
Realiza a partição, movendo os elementos menores que o pivô para a esquerda.
Retorna o novo índice do pivô.
Método troca:
- Recebe um array arr e dois índices i e j.
Troca os elementos nas posições i e j no array.
Funcionamento geral:
- O método quickSort inicia a ordenação chamando particaoAleatoria para obter o pivô inicial.
A escolha aleatória do pivô ajuda a evitar casos em que o QuickSort pode ter desempenho ruim em arrays quase ordenados.
A partição é realizada movendo os elementos menores que o pivô para a esquerda e os maiores para a direita.
A recursão continua nas sublistas à esquerda e à direita do pivô até que a lista esteja ordenada.
Em resumo, o código implementa uma versão do algoritmo QuickSort em Java, incorporando a escolha aleatória do pivô para melhorar o desempenho em cenários específicos.
# Main

# Execução do Algoritmo QuickSort - MainQuickSort
O código Java em `MainQuickSort` demonstra a aplicação do algoritmo QuickSort em um vetor de inteiros com 100.000 elementos. Aqui está uma explicação detalhada do código:
## Criação e Inicialização do Vetor:
Um vetor chamado `arr` com 100.000 elementos é criado para armazenar números inteiros.
Cada elemento do vetor recebe um valor aleatório entre 100 e 999 (inclusive), gerado usando a classe `Random`. Esses valores são gerados para simular um vetor desordenado.
Impressão do Vetor Desordenado:
O programa imprime no console a mensagem "Vetor desordenado:" seguida dos elementos do vetor desordenado. Isso permite que o usuário veja como o vetor estava antes de ser ordenado.
Ordenação do Vetor Usando QuickSort:
O programa inicia a contagem do tempo (startTime) antes de chamar o método `quickSort` da classe `Quicksort`, que contém a implementação do algoritmo QuickSort.
Após a ordenação, o programa registra o tempo novamente (endTime) e calcula a diferença para obter o tempo de execução (duration).
Impressão do Vetor Ordenado e Tempo de Execução:
O programa imprime no console a mensagem "Vetor ordenado:" seguida dos elementos do vetor após a aplicação do QuickSort.
Também imprime o tempo de execução em milissegundos.
No geral, esse código gera um vetor com valores aleatórios, o imprime desordenado, ordena esse vetor usando o algoritmo QuickSort e, finalmente, imprime o vetor ordenado e o tempo que levou para realizar essa ordenação.
|
package main
/**
* Represents a SelfClosingElement entity within a ParentElement structure.
* This class implements the [Element] interface.
*
* @property name The name of the SelfClosingElement entity.
* @property content The content associated with the SelfClosingElement entity.
* @property parent The parent ParentElement entity of the SelfClosingElement entity, if any.
* @property attributes Additional attributes associated with the SelfClosingElement entity, stored as key-value pairs.
*/
data class SelfClosingElement(
override var name: String,
var content: String? = null,
override val parent: ParentElement? = null,
override val attributes: MutableMap<String, String>? = mutableMapOf()
) : Element {
init {
parent?.children?.add(this)
}
/**
* Generates a pretty-printed representation of the SelfClosingElement entity with optional indentation.
*
* @param indentLevel The level of indentation to apply.
* @return A string containing the pretty-printed representation of the SelfClosingElement entity.
*/
override fun prettyPrint(indentLevel: Int): String = buildString {
// Construct the string representation of attributes
val attributesStr = attributes?.entries?.joinToString(separator = " ") { (key, value) -> "$key=\"$value\"" }.orEmpty()
// Determine if attributes are present to decide the prefix
val attributePrefix = if (attributesStr.isNotEmpty()) " " else ""
// Construct the content tag
val contentTag = content?.let { ">$it</$name>" } ?: "/>"
// Append the final formatted string
append("<$name$attributePrefix$attributesStr$contentTag\n")
}
}
|
const passport = require('passport');
const { Strategy: LocalStrategy} = require('passport-local');
const bcrypt = require('bcrypt');
const { User } = require('../models');
module.exports = () => {
passport.use(new LocalStrategy({
usernameField: 'email', //여기가 아이디 칸. req.body에서 받아오는 것의 이름. 만약 id이면 id로 이름 바꿔야 함.
passwordField: 'password', //여기가 비밀번호 칸.
}, async (email, password, done) => {
try {
const user = await User.findOne ({
where: { email }
});
if (!user) {
return done(null, false, { reason: '존재하지 않는 이메일입니다.' }) //passport는 응답을 보내진 않고 done으로 처리. 1번 자리: 서버 에러, 2번 자리: 성공 여부, 3번 자리: 클라이언트 에러
}
const result = await bcrypt.compare(password, user.password);
if (result) {
return done(null, user);
}
return done(null, false, { reason: '비밀번호가 일치하지 않습니다.' });
} catch (error) {
console.error(error);
return done(error);
}
}));
};
|
---CURSOR THAT UPLOADS ALL THE ENTRIES INSIDE CRC_CHECKED OF TABLE UPLAODS TO "YES"
DECLARE
total_rows number(3);
BEGIN
UPDATE UPLOADS
SET CRC_CHECKED = 'YES';
IF sql%notfound THEN
dbms_output.put_line('No DATA selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' DATA selected ');
END IF;
END;
--CURSOR USED TO RETRIEVE THE DETAILED INFORMATION OF THE USERS WHO ARE CONNECTED TO ATLEAST ONE HUB
DECLARE
u_list hub_list.LIST_URL%type;
u_url hub.URL_ADDRESS%type;
u_name hub.NAME%type;
u_country hub.COUNTRY%type;
u_user_id users.USER_ID%type;
u_user_name users.USER_NAME%type;
u_description users.DESCRIPTION%type;
u_ip users.IP%type;
u_connection_status users.CONNECTION_STATUS%type;
CURSOR userdata is
SELECT HB.LIST_URL,H.URL_ADDRESS,H.NAME,H.COUNTRY,U.USER_ID,U.USER_NAME,U.DESCRIPTION,U.IP,U.CONNECTION_STATUS
FROM HUB_LIST HB,HUB H,CONNECTION C,USERS U
WHERE HB.URL_ADDRESS=H.URL_ADDRESS
AND HB.URL_ADDRESS=C.URL_ADDRESS
AND C.USER_ID=U.USER_ID;
BEGIN
OPEN userdata;
LOOP
FETCH userdata into u_list,u_url,u_name,u_country,u_user_id,u_user_name,u_description,u_ip,u_connection_status;
EXIT WHEN userdata%notfound;
dbms_output.put_line(u_user_id||' | '||u_user_name||' | '||u_description||' | '||u_ip||' | '||u_connection_status||' | '||u_list||' | '||u_url||' | '||u_name||' | '||u_country);
END LOOP;
CLOSE userdata;
END;
---CURSOR THAT COUNTS THE NUMBER OF USERS REGISTERED AT DC++
DECLARE
cur sys_refcursor;
cur_rec USERS%rowtype;
BEGIN
OPEN cur FOR
SELECT * FROM USERS;
dbms_output.put_line(cur%rowcount);
LOOP
FETCH cur INTO cur_rec;
EXIT WHEN cur%notfound;
END LOOP;
dbms_output.put_line('Total no of users registered at dc++: ' || cur%rowcount);
END;
---PROCEDURE FOR INSERTING DATA IN DATA TABLE
CREATE OR REPLACE PROCEDURE insertDATA(
u_dataid IN DATA.DATA_ID%TYPE,
u_datemodified IN DATA.DATE_MODIFIED%TYPE,
u_description IN DATA.DESCRIPTION%TYPE,
u_filename IN DATA.FILE_NAME%TYPE,
u_type IN DATA.TYPE%TYPE,
u_filesize IN DATA.FILE_SIZE%TYPE)
IS
BEGIN
INSERT INTO DATA ("DATA_ID","DATE_MODIFIED","DESCRIPTION","FILE_NAME","TYPE","FILE_SIZE")
VALUES (u_dataid,u_datemodified,u_description,u_filename,u_type,u_filesize);
COMMIT;
END;
---
BEGIN
insertDATA('D13','14-JAN-2016','movie','video1','3gp','560MiB');
END;
/*---Doubt---
CREATE OR REPLACE PROCEDURE insertDATA(
u_dataid IN DATA.DATA_ID%TYPE,
u_datemodified IN DATA.DATE_MODIFIED%TYPE,
u_description IN DATA.DESCRIPTION%TYPE,
u_filename IN DATA.FILE_NAME%TYPE,
u_type IN DATA.TYPE%TYPE,
u_filesize IN DATA.FILE_SIZE%TYPE)
IS
BEGIN
u_dataid:=&u_dataid;
u_datemodified:=&u_datemodified;
u_description:=&u_description;
u_filename:=&u_filename;
u_type:=&u_type;
u_filesize:=&u_filesize;
insertDATA(u_dataid,u_datemodified,u_description,u_filename,u_type,u_filename);
END;
BEGIN
INSERT INTO DATA ("DATA_ID","DATE_MODIFIED","DESCRIPTION","FILE_NAME","TYPE","FILE_SIZE")
VALUES (u_dataid,u_datemodified,u_description,u_filename,u_type,u_filesize);
COMMIT;
END;*/
---TRIGGER THAT TELLS THE UPDATE DONE IN MAX USER CAPACITY IN HUB TABLE
CREATE OR REPLACE TRIGGER display_MAX_USERS_changes
BEFORE DELETE OR INSERT OR UPDATE ON HUB
FOR EACH ROW
WHEN (NEW.MAX_USERS > 1000)
DECLARE
MAX_USERS_diff number;
BEGIN
MAX_USERS_diff := :NEW.MAX_USERS - :OLD.MAX_USERS;
dbms_output.put_line('Old MAX_USERS: ' || :OLD.MAX_USERS);
dbms_output.put_line('New MAX_USERS: ' || :NEW.MAX_USERS);
dbms_output.put_line('MAX_USERS difference: ' || MAX_USERS_diff);
END;
---
set serveroutput on;
INSERT INTO HUB
VALUES('dcashfub.co.uk','werocks','uk hub','uk','4.2PiB',10000,2);
---TRIGGER THAT NOTIFIES THAT NEW USER HAS REGISTERED TO DC++
CREATE OR REPLACE TRIGGER INSERT_TRIGGER
AFTER INSERT ON USERS
BEGIN
DBMS_OUTPUT.PUT_LINE('NEW USER ENTERED');
END;
---
INSERT INTO USERS
VALUES('U1','codelover5','american','192.168.1.5','CONNECTED');
---TRIGGER THAT DOESNT ALLOW UPLOAD BETWEEN 11 PM AND 6 AM
CREATE OR REPLACE TRIGGER RESTRICT_UPLAODS
BEFORE INSERT ON UPLOADS
BEGIN
IF(TO_CHAR(SYSDATE,'HH24:MI')NOT BETWEEN '23:00' AND '6:00') THEN
RAISE_APPLICATION_ERROR(-2010,'UPLAOD NOT ALLOWED');
END IF;
END;
---
INSERT INTO UPLOADS
VALUES('D2','4','10s','2MiB/s','NO');
--EXCEPTION thrown when MAX_USERS=1 DONT EXSISTS
DECLARE
name HUB.NAME%type;
address HUB.URL_ADDRESS%type;
BEGIN
SELECT name, address INTO name,address
FROM HUB
WHERE MAX_USERS = 1;
DBMS_OUTPUT.PUT_LINE ('Name: '|| name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || address);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such HUB!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
|
import { AppError } from "@shared/errors/AppError";
import HttpStatusCode from "@shared/errors/HttpStatusCode";
import { Request, Response } from "express";
import { container } from "tsyringe";
import { CreateSpecificationUseCase } from "./CreateSpecificationUseCase";
/** NOTE TSyringe
*
* container.resolve() é usado para resolver (ou instanciar) a classe passada
* como parâmetro através do container.
*/
class CreateSpecificationController {
async handle(request: Request, response: Response): Promise<Response>{
try {
const { name, description } = request.body;
const createSpecificationUseCase = container.resolve(CreateSpecificationUseCase);
await createSpecificationUseCase.execute({ name, description });
return response.status(201).send("Created");
} catch (error) {
if(error.message === "Specification Alrseady exists!") {
throw new AppError(error.message, HttpStatusCode.CONFLICT);
}
throw new Error(error.message);
}
}
}
export { CreateSpecificationController };
|
import PropTypes from "prop-types";
import { forwardRef } from "react";
import { SelectContainer, SelectLabel, StyledSelect } from "./styles";
const SelectDespacho = forwardRef(
({ labelText, helperText, inputName, data, ...props }, ref) => {
return (
<SelectContainer>
<SelectLabel htmlFor={inputName}>{labelText}</SelectLabel>
<StyledSelect id={labelText} name={inputName} {...props} ref={ref}>
<option value="">selecione</option>
{data.map((item) => (
<option key={item.valor} value={item?.valor}>
{item.label}
</option>
))}
</StyledSelect>
{!!helperText && <span>Inválido</span>}
</SelectContainer>
);
},
);
SelectDespacho.displayName = "SelectDespacho";
SelectDespacho.propTypes = {
labelText: PropTypes.string,
helperText: PropTypes.string,
inputName: PropTypes.string.isRequired,
data: PropTypes.array.isRequired,
};
SelectDespacho.defaultProps = {};
export default SelectDespacho;
|
# Validando Endereços IP (IPv4) com Expressões Regulares em Python 3
**Introdução:**
A validação de endereços IP (IPv4) é uma tarefa comum em programação, e uma maneira eficiente de
realizar essa validação é através do uso de expressões regulares em Python 3. Expressões regulares
são padrões de busca em strings, permitindo a validação de formatos específicos.
**Código de Exemplo:**
```python
import re
cpf = '025.258.963-10'
cpf_reg_exp = re.compile(r'^\d{3}\.\d{3}\.\d{3}-\d{2}$', flags=0)
ip_reg_exp = re.compile(
r'^'
r'(?:'
r'(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.'
r'){3}'
r'(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'
r'$',
flags=0
)
for i in range(301):
ip = f'{i}.{i}.{i}.{i}'
print(ip, ip_reg_exp.findall(ip))
```
**Explicação:**
1. **CPF:**
- A expressão regular para o CPF (`cpf_reg_exp`) valida um formato específico de CPF, garantindo três dígitos
seguidos de um ponto, repetido três vezes, seguido de dois dígitos após um traço.
2. **Endereço IP (IPv4):**
- A expressão regular para o endereço IP (`ip_reg_exp`) valida o formato de um endereço IPv4.
- `25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9]`: Esta parte valida cada octeto do endereço IP, garantindo que esteja dentro do intervalo válido (0 a 255).
- `(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.`: Esta parte valida os três primeiros octetos, cada um seguido por um ponto.
- `{3}`: Garante que os três primeiros octetos se repitam exatamente três vezes.
- A última parte valida o último octeto, sem ponto no final.
3. **Loop de Teste:**
- O loop `for` gera 300 endereços IP fictícios e os valida usando a expressão regular. Os resultados são impressos no console.
**Conclusão:**
Utilizando expressões regulares em Python 3, podemos criar padrões de validação poderosos para garantir que os dados,
como CPF e endereços IP, estejam no formato desejado.
|
import { Button, Grid, Paper, Typography } from "@mui/material";
import { CardElement, Elements, ElementsConsumer } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import { useContext } from "react";
import CommerceHandler from "../../../contexts/commerce-context";
import styles from "../styles.module.scss";
const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLIC_KEY);
function PaymentForm() {
const commerceHandling = useContext(CommerceHandler);
const handleSubmit = async (event, elements, stripe) => {
event.preventDefault();
if (!stripe || !elements) return;
const cardElement = elements.getElement(CardElement);
const { error, paymentMethod } = await stripe.createPaymentMethod({ type: "card", card: cardElement });
if (error) {
console.log(error);
} else {
const orderData = {
line_items: commerceHandling.checkoutToken.live.line_items,
customer: {
firstname: commerceHandling.shippingData.fullName,
lastname: commerceHandling.shippingData.fullName,
email: commerceHandling.shippingData.emailAdress,
},
shipping: {
name: "Primary",
street: commerceHandling.shippingData.shippingAdress,
town_city: commerceHandling.shippingData.city,
county_state: commerceHandling.shippingData.shippingState,
postal_zip_code: commerceHandling.shippingData.zipCode,
country: commerceHandling.shippingData.shippingCountry,
},
fulfillment: {
shipping_method: commerceHandling.shippingData.shippingOption,
},
payment: {
gateway: "stripe",
stripe: {
payment_method_id: paymentMethod.id,
},
},
};
commerceHandling.onCaptureCheckout(commerceHandling.checkoutToken.id, orderData);
commerceHandling.checkoutNextStep();
}
};
return (
<>
<Grid container spacing={4}>
<Grid item xs={12}>
<Paper className={styles.review_paperWrapper}>
<Typography variant="h6">Payment Method</Typography>
<Elements stripe={stripePromise}>
<ElementsConsumer>
{({ elements, stripe }) => (
<form onSubmit={(e) => handleSubmit(e, elements, stripe)}>
<CardElement />
<br />
<br />
<div style={{ display: "flex", justifyContent: "space-between" }}>
<Button variant="outlined" onClick={() => commerceHandling.checkoutBackStep()}>
Back
</Button>
<Button
type="submit"
variant="contained"
disabled={!stripe}
style={{
backgroundColor: "rgba(32, 36, 49, 1)",
color: "rgba(255, 255, 255, 0.8)",
}}
>
Proceed Payment
</Button>
</div>
</form>
)}
</ElementsConsumer>
</Elements>
</Paper>
</Grid>
</Grid>
</>
);
}
export default PaymentForm;
|
<script>
import axios from 'axios';
import { endpoint } from '../data';
import AppLoader from '../components/AppLoader.vue';
import ApartmentCard from '../components/apartments/ApartmentCard.vue';
import AppHeader from '../components/AppHeader.vue';
import AppHero from '../components/AppHero.vue';
export default {
name: 'HomePage',
components: { AppHeader, AppHero, AppLoader, ApartmentCard },
data() {
return {
endpoint,
isLoading: false,
isHomePage: true,
apartments: [],
addressFilter: '',
rangeValue: 20,
hasFiltered: false,
};
},
created() {
this.fetchApartments();
},
methods: {
fetchApartments() {
this.isLoading = true;
axios.get(endpoint + "?all=true").then((res) => {
this.apartments = res.data;
}).catch((err) => { console.error(err) })
.then(() => {
this.isLoading = false;
})
},
onDistanceChange(input) {
this.rangeValue = input;
},
onAddressChange(input) {
this.addressFilter = input;
},
onFormSubmit() {
this.hasFiltered = true;
const params = {
params: {
city: this.addressFilter,
range: this.rangeValue,
},
};
this.isLoading = true
axios.get(endpoint, params)
.then(res => {
this.apartments = res.data
})
.catch(error => {
console.error(error);
}).then(() => {
this.isLoading = false
});
}
},
computed: {
apartmentsWithSponsors() {
return this.apartments.filter(apartment => apartment.sponsors.length > 0);
},
},
}
</script>
<template>
<main>
<AppHeader :is-home-page="isHomePage" />
<AppHero @address-change="onAddressChange" @form-submit="onFormSubmit" @distance-change="onDistanceChange" />
<div class="center-button">
<a href="#sponsored">
<i id="slidedown-btn" class="material-icons">
expand_more
</i>
</a>
</div>
<div id="sponsored" class="container-fluid px-5">
<div class="row px-2 gy-4 d-flex justify-content-start">
<div class="col-auto col-lg-3 col-md-6 col-sm-12" v-for="(apartment, index) in apartmentsWithSponsors"
:key="index">
<div>
<ApartmentCard :apartment="apartment" />
</div>
</div>
</div>
</div>
<AppLoader v-if="isLoading" />
</main>
</template>
<style lang="scss" scoped>
@use "../scss/vars" as *;
#slidedown-btn {
color: $white;
font-size: 100px;
}
.center-button {
display: flex;
justify-content: center;
align-items: center;
position: relative;
top: -50px;
height: 0px;
}
#sponsored {
padding-top: 100px;
}
</style>
|
import React, { useEffect, useState } from "react";
import { XrplClient } from "xrpl-client";
import ListedNFT from "./ListedNFT";
const client = new XrplClient();
type AccountNfts = {
Issuer: string;
NFTokenID: string;
NFTokenTaxon: number;
nft_serial: number;
flags: number;
TransferFee: number;
URI?: string;
}[];
type Props = {
account: string;
};
const NFTListPage = ({ account }: Props) => {
const [nfts, setNfts] = useState<AccountNfts>([]);
useEffect(() => {
const f = async () => {
await client.ready();
const response = await client.send({
command: "account_nfts",
account,
});
const nfts = (response.account_nfts as AccountNfts)
.filter((nft) => nft.Issuer === account)
.sort((a, b) => a.nft_serial - b.nft_serial);
setNfts(nfts);
};
f();
}, [account]);
return (
<div className="my-2">
{nfts.map((nft) => (
<ListedNFT key={nft.NFTokenID} nft={nft} />
))}
</div>
);
};
export default NFTListPage;
|
# 10.1 객체지향 쿼리 소개
Criteria / queryDSL 등은 결국 JPQL을 편리하게 다루도록 해주는 기술이므로
JPQL을 잘 숙지해야 한다.
---
EntityManager.find() 메소드를 사용해서 식별자로 엔티티 하나를 조회 할 수 있고,
조회된 엔티티에 객체 그래프 탐색으로 연관된 엔티티들을 조회할 수 있다.
하지만 이 기능만으로 어플리케이션을 개발하기는 힘들다. 예를 들어
나이 30살 이상의 미필 남자만 검색하는 방법이 필요하다. 식별자로 모든 회원을 메모리에 올리고 컬렉션을 필터링 하는 방법은 현실성이 없다.
SQL로 결국에 조건문을 걸어서 가져와야 하는데 JPA는 엔티티를 대상으로 개발하므로 검색도 엔티티를 대상으로 하는 방법이 필요하다.
이를 위해 만든 기술이 JPQL이고, 아래와 같은 특징이 있다.
* 테이블이 아닌 객체를 대상으로 검색하는 객체지향 쿼리이다.
* SQL을 추상화해서 특정 DB SQL에 의존하지 않는다.
JPQL을 사용하면 객체를 대상으로 SQL을 만들어 데이터베이스를 조회하고 엔티티로 결과를 반환한다.
아래는 JPA가 공식으로 지원하는 기능들이다.
* JPQL : Java Persistance Query Language
* Criteria 쿼리 : JPLQ을 편하게 작성하도록 도와주는 빌더 클래스 모음
* 네이티브 SQL : JPA에서 JPQL 대신 직접 SQL을 사용할 수 있다.
아래는 JPA 공식 지원은 아니지만 알아둬야 한다.
* QueryDSL : Criteria 쿼리처럼 JPQL을 편하게 작성하도록 도와주는 빌더 클래스 모음, 비표준 오픈소스 프레임워크이다.
* JDBC 직접 사용 / MyBatis 같은 SQL 매퍼 프레임워크 사용
---
## 10.1.1 JPQL 소개
JPQL은 엔티티 객체를 조회하는 객체지향 쿼리이며 SQL을 추상화하여 특정 DB에 의존하지 않는다.
따라서 방언만 변경하면 DB를 교체해도 사용 가능하다. 간단한 예를 보자
~~~java
@Entity
public class Member {
@Column
private String name;
}
public static void main(String[] args) {
String jqpl = "select m" +
"from Member as m" +
"where m.name = 'kim'";
List<Member> members = em.createQuery(jqpl, Member.class).getResultList();
}
~~~
테이블이 아닌 엔티티 Member를 대상으로 쿼리를 생성하였다.
---
## 10.1.2 Criteria 쿼리 소개
Criteria는 JQPL을 생성하는 빌더 클래스다. 문자가 아닌 query.select(m).where(...) 처럼 프로그래밍 코드로 JQPL을 작성할 수 있다는
점이 장점이다. 이 경우, 직접 문자로 쿼리를 작성할때와 달리, 컴파일 타임에서 에러를 감지해준다는 장점이 있다.
추가적인 장점은 아래와 같다.
* 컴파일 시점에 오류를 발견할 수 있다.
* IDE를 사용하면 코드 자동완성을 지원한다.
* 동적 쿼리를 작성하기 편하다.
위에 JQPL로 작성한 쿼리를 criteria 쿼리를 사용해서 바꿔보자.
~~~java
// criteria 사용 준비
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Membmer> query = cb.createQUery(Member.class);
// 루트 클래스
Root<Member> m = query.from(Member.class);
// 쿼리 생성
CriteriaQuery<Member> cq = query.select(m).where(cb.equal(m.get("userName)", "Kim"));
List<Member> resultList = em.createQuery(cq).getResultList();)
~~~
하나 아쉬운점은 m.get("userName") 부분은 여전히 DB 컬럼 명을 문자열로 작성했다는 점이다.
뒤에 이 부분을 고치는 방법에 대해서 말해준다.
Criteria가 가진 장점은 많지만 모든 장점을 상쇄할 정도로 복잡하고 장황하다. 따라서 잘 안쓴다.
---
## 10.1.3 QueryDSL 소개
QueryDsl도 JPQL 빌더 역할을 한다. 근데 단순하고 사용하기 쉽다. Criteria를 사용하면 너무 복잡하다.
백문이 불여일견 한 번 보자.
~~~java
JPAQuery query = new JPAQuery(em);
QMember member = QMember.member;
List<Member> members =
query.from(member)
.where(member.username.eq("kim"))
.list(member);
~~~
단순하고 쓰기 쉽다. QMember는 어노테이션 프로세스를 사용해서 쿼리 전용 클래스를 만든 것이다.
---
## 10.1.4 네이티브 SQL 소개
JPQL을 사용하더라도 가끔은 특정 DB의 의존적인 기능을 사용할 떄가 있다. 예를 들어
오라클에서만 지원하는 CONNECT BY라던가 특정 DB에서만 동작하는 SQL힌트 같은 것이다.
이들은 전혀 표준화 되어 있지 않으므로 JPQL에서 사용할 수 없다. 이떄 쓰면 된다.
단 DB를 수정하면 같이 수정되어야 한다.
~~~sql
String sql = "SELECT ID, AGE, TEMI_ID, NAME FROM MEMBER WHERE NAME = 'kim ’ ”;
List<Member> resultList = em.createNativeQuery(sql, Member.class).getResultList();
~~~
---
## 10.1.5 JDBC 직접 사용, 마이바티스 같은 SQL 매퍼 프레임워크 사용
드물지만 JDBC 커넥션에 직접 접근하고 싶으면 JPA는 JDBC는 이를 지원하지 않으므로 JPA 구현체가 제공하는 방법을 사용해야 한다.
하이버네이트(구현체)에서 직접 JDBC Connection을 획득하는 방법은 아래와 같다.
~~~java
Session session = entitiyManager.unwrap(Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
}
});
~~~
먼저 JPA Entity Manager에서 하이버네이트 Session을 구한 후 Session에 doWork 메서드를 호출하면 된다.
JDBC나 마이바티스를 JPA와 함께 사용하면 영속성 컨텍스트를 적절한 시점에 강제로 플러시 해줘야 한다.
JDBC를 직접 사용하든 마이바티르 같은 SQL 매퍼를 사용하든 모두 JPA를 우회해서 데이터베이스에 접근한다.
하지만 JPA를 우회하는 SQL에 대해서 JPA가 인식을 못한다는 점이다. 최악의 시나리오는 영속성 컨텍스트와 DB 불일치로 데이터 무결성을 훼손할수있다.
이런 이슈를 해결하는 방법은 JPA를 우회해서 SQL을 실행하기 전에 영속성 컨텍스트를 플러시해서 동기화 하면 된다.
참고로 스프링을 쓰면 JPA와 마이바티스를 손쉽게 통합할 수 있다. 또한 AOP를 사용하면 JPA를 우회하여 DB에 접근하는 메서드를 호출할때마다
영속성 컨텍스트를 플러시하여 손쉽게 해결할 수 있다.
---
# 10.2 JPQL
다시 한 번 JPQL의 특징을 소개하고 시작해보자.
* JPQL은 객체지향 쿼리 언어이므로 테이블이 아닌 엔티티 객체를 대상으로 쿼리한다.
* JPQL은 SQL을 추상화해서 특정 DB에 의존하지 않는다.
* JPQL은 결국 SQL로 변환된다.

---
## 10.2.1 기본 문법과 쿼리 API
저장할때는 em.persist를 사용하면 되므로 이를 제외한 SELECT, UPDATE, DELETE문을 사용할 수 있다.
### SELECT 문
아래와 같이 사용한다.
~~~
SELECT m FROM Member AS m where m.username = 'shin';
~~~
* 대소문자 구분
* 엔티티와 속성은 대소문자를 구분한다. 예를 들어, Member, username은 대소문자를 구분한다
* 반면에 SELECT, AS 등과 같은 JPQL 키워드는 대소문자를 구분하지 않는다.
* 엔티티 이름
* JPQL에서 사용한 Member는 클래스가 아니고 엔티티 명이다.
* 별칭은 필수
* Member as m 을 보면 Member에 m이란 별칭을 주었는데 JPQL은 별칭을 필수로 줘야 한다.
* 하이버네이트는 HQL도 지원하는데 나중에 알아보자..
---
### TypeQuery, Query
JPQL을 실행하려면 쿼리 객체를 만들어야 하는데 반환 타입이 명확하면 TypeQuery / 그렇지 못하면 Query 객체를 사용하면 된다.
아래 예제를 보자.
~~~java
TypedQuery<Member> query = em.createQuery("select m from Member m", Member.class);
List<Member> resultList = query.getResultList();
for (Member member : resultList) {
어쩌구저쩌구..
}
~~~
---
### 결과 조회
다음 메소드들을 호출하면 실제 쿼리를 실행해서 디비를 조회한다.
~~~java
public static void main(String[]args){
query.getResultList() : 결과를 예제로 반환한다. 만약 결과가 없으면 빈 컬렉션이 반환된다.
query.getSingleResult() : 결과가 하나일때 사용된다. 결과가 없거나 1개 보다 많으면 각각
NoResultException / NonUniqueResultException이 발생한다.
}
~~~
---
## 10.2.2 파라미터 바인딩
JDBC는 위치 기준 파라미터 바인딩만 지원하지만 JPQL은 이름 기준 파라미터 바인딩도 지원한다.
이름 기준 파라미터는 파라미터를 이름으로 구분하는 방법이고 예제는 아래와 같다.
~~~java
{
String userName = "원호";
TypedQuery<Member> query =
em.createQuery("select m from Member m where m.userName = :userName", Member,class);
query.setParameter("userName", userName);
List<Member> members = query.getResultList();
~~~
참고로 JPQL API는 대부분 체이닝을 제공하고 있어서 아래처럼 작성가능하다.
~~~java
List<Member> members =
em.createQuery("select m from member m where m.userName = :userName", Member.class)
.setParameter("userName", userName)
.getResultList():
~~~
### 위치 기준 파라미터
위치 기준 파라미터를 사용하려면 ? 를 주면 된다. ?는 1부터 시작한다.
이름 기준 파라미터 파인딩을 써라.
---
## 10.2.3 프로젝션
Select 절에 조회할 대상을 지정하는 것을 프로젝션이라 하고, select 프로젝션 대상 from 으로 대상을 선택한다.
프로젝션 대상은 엔티티 / 임베디드 타입 / 스칼라 타입 등이 있다.
### 엔티티 프로젝션
엔티티를 대상으로 지정한 경우이다.
~~~java
select m from Member m;
select m.team from Member m
~~~
이렇게 조회된 엔티티는 영속성 컨텍스트에서 관리된다.
---
### 임베디드 타입 프로젝션
JQPL에서 임베디드 타입은 엔티티와 거의 비슷하게 사용된다. 임베디드 타입은 조회의 시작을 알 수 없다는 제약이 있다.
아래는 Member의 Address를 조회의 시작점으로 잘못 선택한 쿼리이다.
~~~
String query = "SELECT a from Address a";
~~~
아래처럼 해야 한다.
~~~
String query = "SELECT o.address from Order.o";
List<Address> addresses = em.createQuery(query, Address,class).getResultList();
~~~
임베디드 타입은 엔티티가 아니고 값이다. 그러므로 영속성 컨텍스트에서 관리되지 않는다.

---
### 여러 값 조회
엔티티 말고 필요한 컬럼들만 대상으로 조회를 해야할 떄도 있다.
이때는 typeQuery를 사용할 수 없고 대신에 Query를 사용해아 한다.
~~~java
Query query = em.createQuery("select m.userName, m,age from Member m");
List resultList = query.getResultList();
Iterator iterator = resultList.iterator();
while(iterator.hasNext()) {
Object[] row = (Object[]) iterator.next();
String userName = (String) row[0];
Integer age = (Integer) row[1];
}
~~~
제네륵을 활용해서 아래처럼 좀 더 간결하게 할 수도 있다.
~~~java
List<Object[]> resultList = em.createQuery("select m.userName, m,age from Member m");
.getResultList();
for (Object[] row : resultList) {
String name = (String) row[0];
Integer age = (Integer) row[1];
}
~~~
---


---
## 10.2.4 페이징 API
JPA는 페이징을 두 API로 추상화 했다.
setFirstResult(int startPosition) : 조회 시작 위치 (0 based)
setMaxResults(int maxResult) : 조회할 데이터 수
~~~java
TypedQuery<Member> query =
em.createQuery("select m from Member m order by m.userName desc", Member.class);
query.setFirstResult(10);
query.setMaxResults(20);
query.getResultList();
~~~
위를 분석하면 11~30 데이터를 가져오는 것이다.
---
## 10.2.5 집합과 정렬
집계 함수는 어래 처럼 사용한다.



---
## 10.2.6 JPQL 조인
SQL 조인이랑 비슷하다.
### 내부 조인 (Inner Join)
inner는 생략 가능하다.
~~~java
String teamName = "a";
String query = "select m from Member m join m.team t where t.name = :teamName";
List<Member> members = em.createQuery(query, Member.class)
.setParameter("teamName", teamName)
.getResultList();
~~~
외부조인도 동일하다.
한가지 특이점은 조인할 엔티티가 team 이 아니고 m.team 이라는 것이다.
연관관계를 맺는 필드를 통해 작성해야 한다.
---

---
## 10.2.7 페치 조인
패치 조인은 SQL 성능 최적화 기능을 제공하는데 연관 엔티티나 컬렉션을 한번에 같이 조회하는 기능이며
join fetch 명령어로 사용할 수 있다.

---
### 엔티티 패치 조인
페치 조인을 사용해서 회원 엔티티를 조회하며 연관된 팀 엔티티도 함께 조회하는 JQPL을 보자.
~~~
select m
from Member m join fetch m.team;
~~~
member / team 엔티티를 함께 조회한다. JPA에서는 m.team 에 별칭이 없다. fetchJoin 에서는 별칭이 없다.
근데 하이버네이트는 있다.


select m만 했는데 m, t 모두를 조회했다.
또한 10.5를 보면 연관관계가 모두 로딩된 것을 알 수 있다.
패치 조인을 쓰면 이렇게 연관관계도 함께 로딩되기 때문에 m.getTeam()을 해도 지연로딩이 발생하지 않는다.
반환된 엔티티도 프록시가 아닌 실제 엔티티 이다.
---
### 컬렉션 패치 조인
일대다 관계인 컬렉션을 패치 조인 해보자.
~~~
select t
from Team t
join fetch t.members
where t.name = 'a'
~~~


---
### 패치 조인과 DISTINCT
위 이유 때문에 DISTINCT 키워드를 쓰는데 JPA에 DISTINCT는 SQL 기능과 좀 다른게
SQL에도 추가하고, 애플리케이션에서 한 번 더 중복을 제거한다.
아래처럼 해보자.
~~~
select Distinct t
from Team t join fetch t.members
where t.name = '팀A'
~~~
SQL에 distinct가 추가된다. 하지만 지금은 각 로우의 데이터가 다르므로 효과가 없다.
이제 애플리케이션에서 중복을 한 번 걸러낸다. select distinct t는 팀 엔티티의 중복을 제거하라는 뜻이다.
그러므로 아래처럼 조회가 된다.

---
### 페치 조인과 일반 조인의 차이
페치 조인은 명세된 연관관계도 같이 가져오지만 일반 조인은 안가져온다.
JQPL은 결과를 반환할때 연관관계까지 고려하지 않고 select 절에 지정한 엔티티만 조회한다.
그러므로 일반 조인은 지연로딩이 된어 프록시가 반환된다. (연관관계에)
---
### 페치 조인의 특징과 한계
* 한번에 연관관계 엔티티를 조회할 수 있어서 성능에 좋다.
* 페치 조인은 글로벌 로딩 전략보다 우선순위가 높다. (엔티티 등에 명세)
* 패치 조인 대상에는 별칭을 줄 수 없다.
* select / where / 서브 쿼리에서 사용할 수 없다.
* 둘 이상의 컬렉션을 패치할 수 없다.
* 컬렉션을 패치 조인하면 페이징을 사용할 수 없다
그냥 필요한 필드들만 프로젝션으로 DTO로 만들어서 반환하는게 더 효과적일 수 있다.
---
## 10.2.8 경로 표현식
경로 표현식에 대해 알아보자

이렇게 점찍어서 표현한게 경로 표현식이다.
---
### 경로 표현식 용어 정리


---
### 경로 표현식과 특징
* 상태 필드 경로 : 경로 탐색의 끝이다 더는 탐색할 수 없다.
* t.user.age 등은 불가능하다.
* 단일 / 컬렉션 값 연관 경로는 묵시적으로 내부 조인이 일어난다.
* 단일 : 계속 탐색 가능
* 컬렉션 : 계속 탐색 하려면 FROM 절에서 조인을 통해 별칭을 얻으면 별칭으로 탐색이 가능하다.
---
### 상태 필드 경로 탐색

---
### 단일 값 연관 경로 탐색

단일 값 연관 필드로 경로 탐색을 하면 내부 조인이 일어나는데 이를 묵시적 조인이라고 하며 모두 내부 조인이다.

---

---
### 컬렉션 값 연관 탐색



---
## 10.2.9 서브쿼리
서브쿼리는 where / having 에만 사용할 수 있다.

---
### 서브 쿼리 함수


---
## 10.2.10 조건식















---
## 10.2.14 엔티티 직접 사용
엔티티 식별자 대신에 엔티티 그 자체를 넣어도 된다.



---
## 10.2.15 Named 쿼리 : 정적 쿼리






---
# 질문
1. 어노테이션 프로세서를 통해 queryDSL 클래스를 만든다.
2. 10.2.7 패치조인은 그러면 프로젝션 생성 + 일반 조인으로 해결하면 되는 것인가...!!
|
from pydantic import BaseModel, Field
from datetime import datetime
from typing import Optional
class ServiceModel(BaseModel):
id: int = Field(default = None)
name: str
company_id: int
description: str
price: float
created_at : datetime = Field(default = None)
class ServicePostModel(BaseModel):
name: str
company_id: int
description: str
price: float
class Config:
json_schema_extra = {
"example": {
"name" : "serviceName",
"company_id" : "1",
"description" : "Service description",
"price" : 10.88,
}
}
class ServiceUpdateModel(BaseModel):
name: Optional[str] = Field(default = None)
description: Optional[str] = Field(default = None)
price: Optional[float] = Field(default = None)
class ServiceAvailabilityModel(BaseModel):
service_id: int
start_date: datetime
end_date: datetime
|
import {
ChatInputCommandInteraction,
SlashCommandBuilder,
SlashCommandNumberOption,
SlashCommandStringOption,
TextChannel,
} from "discord.js";
import { ExtendedClient } from "../interfaces/ExtendedClient";
import * as ShopUtils from "../models/Shop";
import { isAdmin } from "../utils/isAdmin";
export const data = new SlashCommandBuilder()
.setName("add_stock")
.setDescription("Purchase an item from shop")
.addStringOption(
new SlashCommandStringOption()
.setName("item_name")
.setDescription("Item Name")
.setRequired(true)
.setAutocomplete(true)
)
.addNumberOption(
new SlashCommandNumberOption()
.setName("stock")
.setDescription("Stock")
.setRequired(true)
);
export async function execute(
bot: ExtendedClient,
interaction: ChatInputCommandInteraction
) {
if(!(await isAdmin(interaction)))
return;
const itemName: string = interaction.options.getString("item_name");
const allShopItems = await ShopUtils.getAllItems(bot);
const itemNameChoice = allShopItems.find(
(item) => item.itemName === itemName
);
const stock = interaction.options.getNumber("stock");
await ShopUtils.addStock(itemNameChoice.itemName, Number(stock), bot);
return await interaction.reply({content:`A stock of ${stock} has been added to ${itemNameChoice.itemName}`, ephemeral:true})
}
|
/**
* @param {string} text1
* @param {string} text2
* @return {number}
*/
var longestCommonSubsequence = function(text1, text2) {
// text1, text2 길이 비교
// dp
const m = text1.length, n = text2.length;
// edge case 를 위해 m+1, n+1로 dp 배열 생성
let dp = new Array(m+1).fill().map(() => new Array(n+1).fill(0));
// text1, text2를 순회하며 dp 업데이트
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
// 두 문자가 동일한 문자라면 길이를 1 증가시킨다.
if (text1[i-1] === text2[j-1]) {
dp[i][j] = 1 + dp[i-1][j-1];
}
// 다른 경우, 현재 dp 에서 이전값들의 최대값을 취한다.
// dp grid에서 업데이트할 위치의 이전값은 위로 한칸, 왼쪽으로 한칸의 값
else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
// dp 업데이트 후 마지막 인덱스를 리턴한다.
return dp[m][n];
};
|
# Automatización de Reportes Diarios y Distribución de Correos Electrónicos
## Descripción General
Este script automatiza el proceso de descarga de reportes diarios desde Google Drive, procesamiento de datos desde archivos Excel, generación de reportes resumen y envío de estos reportes por correo electrónico a las tiendas correspondientes. Realiza tres tareas principales:
1. **Descargar Archivos desde Google Drive**
2. **Procesar Archivos Excel**
3. **Enviar Reportes Resumen por Correo Electrónico**
## Requisitos Previos
- Python 3.6 o superior
- Bibliotecas de Python requeridas:
- `pandas`
- `xlsxwriter`
- `fpdf`
- `google-auth`
- `google-auth-oauthlib`
- `google-auth-httplib2`
- `google-api-python-client`
- `smtplib`
- `email`
- `numpy`
- `glob`
- `warnings`
- `xlsx2csv`
## Instrucciones de Configuración
1. **Configuración de la API de Google**:
- Asegúrese de tener `credentials.json` para la API de Google en su directorio de trabajo.
- Configure un ID de cliente OAuth 2.0 desde la Consola de Google Cloud.
2. **Configuración del Entorno**:
- Cree un entorno virtual de Python y actívelo:
```sh
python -m venv venv
source venv/bin/activate # En Windows: venv\Scripts\activate
```
- Instale las bibliotecas requeridas:
```sh
pip install pandas xlsxwriter fpdf google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client smtplib email numpy glob warnings xlsx2csv
```
3. **Estructura del Directorio**:
- Asegúrese de que exista la siguiente estructura de directorios:
```
C:\Users\<username>\Falabella\<ruta>
├── PRD_Tienda
│ ├── Lista_PRD
│ └── Lista_STORE_PICKUP
```
4. **Credenciales**:
- Reemplace los marcadores de posición en el script con valores reales:
- `usuario`: Su nombre de usuario.
- `ruta`: Subdirectorio para Falabella.
- Credenciales de correo electrónico y configuraciones SMTP.
- IDs y URLs de los archivos de Google Sheets.
## Descripción del Script
### 1. Descargar Archivos desde Google Drive
La función `main` maneja la autenticación de Google Drive y descarga hojas de cálculo específicas de Google como archivos Excel:
```python
SCOPES = ["https://www.googleapis.com/auth/drive"]
def download_sheet(service, sheet_id, output_filename):
# Función para descargar una hoja de cálculo de Google como un archivo Excel
...
def main():
creds = None
...
try:
service = build(API_SERVICE_NAME, API_VERSION, credentials=creds)
download_sheet(service, sheet_id_1, os.path.join(ruta_lista_PRD,'Personal Recoleccion diaria '+ str(fecha_hoy)+'.xlsx'))
download_sheet(service, sheet_id_2, 'Dato_tienda_Dev_C&C.xlsx')
except HttpError as error:
print(f"An error occurred: {error}")
if __name__ == "__main__":
main()
```
### 2. Procesar Archivos Excel
El script lee y procesa datos de los archivos Excel descargados, fusiona la información necesaria y crea reportes resumen:
```python
def read_excel(path: str, sheet_name: str) -> pd.DataFrame:
buffer = StringIO()
Xlsx2csv(path, outputencoding="utf-8", sheet_name=sheet_name).convert(buffer)
buffer.seek(0)
df = pd.read_csv(buffer)
return df
# Procesamiento de datos
...
```
### 3. Enviar Reportes Resumen por Correo Electrónico
El script genera un reporte resumen para cada tienda, adjunta los archivos Excel correspondientes y envía un correo electrónico:
```python
# Configuración del correo electrónico
email_usuario = '[email protected]'
contrasena = 'su_contraseña'
servidores_smtp = 'smtp.office365.com'
puertos_smtp = 587
# Iterar sobre las tiendas y enviar correos electrónicos
for tienda in PICKUP_TIENDA['Nombre_Tienda'].unique():
...
# Crear el contenido del correo y adjuntar archivos
...
try:
# Enviar el correo electrónico
server.sendmail(email_usuario, destinatarios_str_to.split(',') + destinatarios_str_CC.split(','), msg.as_string())
registro_correos = pd.concat([registro_correos, pd.DataFrame({"Tienda": tienda, "Resultado": "Correo enviado correctamente"}, index=[0])])
print(f"Correo electrónico enviado correctamente a {tienda}")
except smtplib.SMTPDataError as e:
registro_correos = pd.concat([registro_correos, pd.DataFrame({"Tienda": tienda, "Resultado": f"Error al enviar correo electrónico: {e}"}, index=[0])])
print(f"Error al enviar correo electrónico a {tienda}: {e}")
finally:
server.quit()
```
### Conclusión
Este script automatiza la descarga, el procesamiento y la distribución de reportes diarios, asegurando que los interesados reciban datos actualizados de manera oportuna. Asegúrese de actualizar los marcadores de posición con datos y credenciales reales antes de ejecutar el script.
|
import { RequestHandler } from "express";
import ErrorCodes from "../utils/ErrorCodes";
import { STATUS_CODES } from "http";
export const svcErr: RequestHandler = function (req, res, next) {
res.svcErr = function (error: { code: number; data: any }) {
const httpsStatusCode: number =
error?.code && !!STATUS_CODES[error?.code] ? error.code : 500;
res.status(httpsStatusCode).json(error.data);
};
next();
};
export const unauthorized: RequestHandler = function (req, res, next) {
res.unauthorized = function (
message = "You are not authorized to access this page"
) {
res
.status(401)
.json({ code: ErrorCodes.ISSYKO005, message, element: null });
};
next();
};
export const notFound: RequestHandler = function (req, res, next) {
res.notFound = function (
message: string = "We could not find what you were looking for",
code: string = ErrorCodes.ISSYKO002
) {
res.status(404).json({ code, message, element: null });
};
next();
};
export const badRequest: RequestHandler = function (req, res, next) {
res.badRequest = function (
message: string,
error: any,
code: string = ErrorCodes.ISSYKO004
) {
return res.status(400).json({
code,
message,
element: error
});
};
next();
};
export const unprocessableEntityRequest: RequestHandler = function (
req,
res,
next
) {
res.unprocessableEntityRequest = function ({
element,
message,
code
}: {
element?: any;
message?: string;
code?: string;
}) {
message = message ?? "Validation failed, please check your data";
element = element ?? null;
code = code ?? ErrorCodes.ISSYKO004;
return res.status(422).json({
code,
message,
element
});
};
next();
};
export const done: RequestHandler = function (req, res, next) {
res.done = function (data: any) {
res.status(200).json(data);
};
next();
};
export const ok: RequestHandler = function (req, res, next) {
res.ok = function (data: any, code = "Ok", message = null) {
res.status(200).json({
code,
message: message || "Success",
element: data || null
});
};
next();
};
export const paymentRequired: RequestHandler = function (req, res, next) {
res.paymentRequired = function (
message = "You don't have a plan, please select a plan to continue"
) {
res
.status(402)
.json({ code: ErrorCodes.ISSYKO006, message, element: null });
};
next();
};
export const forbidden: RequestHandler = function (req, res, next) {
res.forbidden = function (
message = "You don't have permission to perform this action"
) {
res
.status(403)
.json({ code: ErrorCodes.ISSYKO007, message, element: null });
};
next();
};
|
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from channels.generic.websocket import AsyncWebsocketConsumer
import cv2
import os
import face_recognition
import asyncio
prototxt = "/home/edmartinez/Documents/UTPL/Septimo Ciclo/Inteligencia Artificial/DeteccionFacialGUI/FaceRecognition/deteccion/static/model/deploy.prototxt" # Arquitectura
model = "/home/edmartinez/Documents/UTPL/Septimo Ciclo/Inteligencia Artificial/DeteccionFacialGUI/FaceRecognition/deteccion/static/model/res10_300x300_ssd_iter_140000.caffemodel" # Pesos
haarcascade = "/home/edmartinez/Documents/UTPL/Septimo Ciclo/Inteligencia Artificial/DeteccionFacialGUI/FaceRecognition/deteccion/static/model/haarcascade_frontalface_default.xml"
net = cv2.dnn.readNetFromCaffe(prototxt, model)# Cargamos el modelo de la red
def index(request):
return render(request, 'principal.html')
def principal_view(request):
return render(request, 'principal.html')
def train_model(request):
if request.method == 'POST' and request.FILES['train_image']:
# Obtiene la imagen desde el formulario
uploaded_image = request.FILES['train_image']
nombre = request.POST['nombre']
image_path = os.path.join(settings.MEDIA_ROOT, 'Uploads', uploaded_image.name)
if not os.path.exists(os.path.dirname(image_path)):
os.makedirs(os.path.dirname(image_path))
# Guarda la imagen en la carpeta "uploads"
with open(image_path, 'wb') as destination:
for chunk in uploaded_image.chunks():
destination.write(chunk)
image = cv2.imread(image_path)
height, width, _ = image.shape
image_resized = cv2.resize(image, (300, 300))
# Create a blob
blob = cv2.dnn.blobFromImage(image_resized, 1.0, (300, 300), (104, 117, 123))
print("blob.shape: ", blob.shape)
blob_to_show = cv2.merge([blob[0][0], blob[0][1], blob[0][2]])
net.setInput(blob)
detections = net.forward()
print("detections.shape:", detections.shape)
for idx, detection in enumerate(detections[0][0]):
if detection[2] > 0.5:
box = detection[3:7] * [width, height, width, height]
x_start, y_start, x_end, y_end = int(box[0]), int(box[1]), int(box[2]), int(box[3])
face = image[y_start:y_end, x_start:x_end]
face = cv2.resize(face, (150, 150))
# Save the detected face as an image
face_filename = os.path.join(settings.MEDIA_ROOT, 'RostrosDetectados', (nombre+f"{idx}.jpg"))
if not os.path.exists(os.path.dirname(face_filename)):
os.makedirs(os.path.dirname(face_filename))
cv2.imwrite(face_filename, face)
cv2.rectangle(image, (x_start, y_start), (x_end, y_end), (0, 255, 0), 2)
cv2.putText(image, "Conf: {:.2f}".format(detection[2] * 100), (x_start, y_start - 5), 1, 1.2, (0, 255, 255), 2)
cv2.destroyAllWindows()
return render(request, 'principal.html')
def activar_camera(request):
faces_encodings, faces_names = get_faces_encodings()
cap = cv2.VideoCapture(0, cv2.CAP_ANY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.flip(frame, 1)
orig = frame.copy()
faces = face_cascade.detectMultiScale(frame, 1.1, 5)
for (x, y, w, h) in faces:
face = orig[y:y + h, x:x + w]
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
actual_face_encoding = face_recognition.face_encodings(face, known_face_locations=[(0, w, h, 0)])[0]
result = face_recognition.compare_faces(faces_encodings, actual_face_encoding)
if True in result:
index = result.index(True)
name = faces_names[index]
color = (125, 220, 0)
else:
name = "Desconocido"
color = (50, 50, 255)
cv2.rectangle(frame, (x, y + h), (x + w, y + h + 30), color, -1)
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, name, (x, y + h + 25), 2, 1, (255, 255, 255), 2, cv2.LINE_AA)
cv2.imshow("Frame", frame)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cap.release()
return render(request, 'principal.html')
def detect_people(request):
if request.method == 'POST' and request.FILES['detect_image']:
# Obtiene la imagen desde el formulario
uploaded_image = request.FILES['detect_image']
image_path = os.path.join(settings.MEDIA_ROOT, 'Detecciones', uploaded_image.name)
# Guarda la imagen en la carpeta "uploads"
with open(image_path, 'wb') as destination:
for chunk in uploaded_image.chunks():
destination.write(chunk)
faces_encodings, faces_names = get_faces_encodings()
frame = cv2.imread(image_path)
orig = frame.copy()
faces = face_recognition.face_locations(frame)
for (top, right, bottom, left) in faces:
face = orig[top:bottom, left:right]
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
actual_face_encoding = face_recognition.face_encodings(face)
if actual_face_encoding:
# Si se detecta una cara, realiza la comparación
result = face_recognition.compare_faces(faces_encodings, actual_face_encoding[0])
if True in result:
index = result.index(True)
name = faces_names[index]
else:
name = "Desconocido"
else:
# Si no se detecta ninguna cara, asigna el nombre como "Desconocido"
name = "Desconocido"
# Muestra el nombre en el cuadro del rostro
if (name == "Desconocido"):
color = (0, 0, 255)
else:
color = (125, 220, 0)
cv2.rectangle(frame, (left, top), (right, bottom), color, 2)
cv2.putText(frame, name, (left, bottom + 25), 2, 1, (255, 255, 255), 2, cv2.LINE_AA)
cv2.imshow("Frame", frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
#return HttpResponse('Personas detectadas en la imagen.')
return render(request, 'principal.html')
def get_faces_encodings():
image_faces_path = "/home/edmartinez/Documents/UTPL/Septimo Ciclo/Inteligencia Artificial/DeteccionFacialV2/RostrosDetectados"
faces_encodings = []
faces_names = []
for file_name in os.listdir(image_faces_path):
image = cv2.imread(os.path.join(image_faces_path, file_name))
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
f_coding = face_recognition.face_encodings(image, known_face_locations=[(0, 150, 150, 0)])[0]
faces_encodings.append(f_coding)
faces_names.append(file_name.split(".")[0])
return faces_encodings, faces_names
|
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useNavigate } from "react-router-dom";
import { addForm, addSchema } from "../../models/category";
import { addCategory } from "../../api/category";
const AddCategory = () => {
const navigate = useNavigate();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<addForm>({
resolver: yupResolver(addSchema),
});
const onSubmit = async (category: addForm) => {
try {
const response = await addCategory(category);
console.log(response);
navigate("/admin/categories");
} catch (error) {
console.log(error);
}
};
return (
<div className="flex">
<div className="w-full p-7">
<h1 className="leading-[30px] mb-4 text-xl text-[#5F5E61] font-semibold">
Thêm mới Danh mục
</h1>
<form className="flex gap-x-[35px]" onSubmit={handleSubmit(onSubmit)}>
<div className="w-full">
<h1 className="text-[#3D5170] font-medium mb-4 px-4 shadow-md leading-6 pb-4">
Thông tin danh mục
</h1>
<div className="mb-4">
<label
htmlFor=""
className="text-[13px] leading-5 text-[#5A6169] block mb-2"
>
Tên danh mục
</label>
<input
{...register("name")}
type="text"
className="px-3 py-2 w-full text-sm text-[#444444] leading-5 border border-gray-200 rounded-md outline-none"
/>
<p className="text-xs text-red-500">
{errors.name && errors.name.message}
</p>
</div>
<button className="bg-[#00B0D7] hover:bg-[#007BFF] transition-all text-white text-xs leading-[14px] px-[13px] py-[10px] rounded-md">
Thêm mới
</button>
</div>
</form>
</div>
</div>
);
};
export default AddCategory;
|
<div class="container">
<div class="alert alert-danger" *ngIf="errorMsg">
{{ errorMsg }}
</div>
<!--form for number of tickets-->
<form #UserFrom="ngForm" *ngIf="!submitted" (ngSubmit)="submit()">
<h1>Select Your Tickets here!</h1>
<br />
<div class="row">
<div class="col">
<h6>VIP Tickets:</h6>
</div>
<div class="col">
<button id="increase" type="button" (click)="increament(0)">+</button>
<p>{{ count[0] }}</p>
<button id="decrease" type="button" (click)="decriment(0)">-</button>
</div>
</div>
<br />
<div class="row">
<div class="col">
<h6>Standard Tickets:</h6>
</div>
<div class="col">
<button type="button" (click)="increament(1)">+</button>
<p>{{ count[1] }}</p>
<button type="button" (click)="decriment(1)">-</button>
</div>
</div>
<br />
<div class="row">
<div class="col">
<h6>Student Tickets:</h6>
</div>
<div class="col">
<button id="increase" type="button" (click)="increament(2)">+</button>
<p>{{ count[2] }}</p>
<button id="decrease" type="button" (click)="decriment(2)">-</button>
</div>
</div>
<br />
<div class="row">
<div class="col">
<h6>Special Tickets:</h6>
</div>
<div class="col">
<button id="increase" type="button" (click)="increament(3)">+</button>
<p>{{ count[3] }}</p>
<button id="decrease" type="button" (click)="decriment(3)">-</button>
</div>
</div>
<br />
<!--Submit button for ticket number-->
<div class="submit-ticket-number" (click)="toggleCollapse()">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
<!--form for name input-->
<div *ngIf="!isCollapsed">
<div *ngFor="let j of iterative2(4)">
<h1 *ngIf="count[j] > 0">{{ getName(j) }}</h1>
<div *ngFor="let i of iterative(j)">
<form>
<div>
<h1>Give first and last name</h1>
<div class="form-group">
<label>First Name</label>
<input
type="text"
required
#firstName="ngModel"
[class.is-invalid]="firstName.invalid && firstName.touched"
class="form-control"
name="firstName"
[(ngModel)]="userModel.firstName"
/>
<small
class="text-danger"
[class.d-none]="firstName.valid || firstName.untouched"
>First name is required!</small
>
</div>
<div class="form-group">
<label>Last Name</label>
<input
type="text"
required
#lastName="ngModel"
[class.is-invalid]="lastName.invalid && lastName.touched"
class="form-control"
name="lastName"
[(ngModel)]="userModel.lastName"
/>
<small
class="text-danger"
[class.d-none]="lastName.valid || lastName.untouched"
>Last name is required!</small
>
</div>
</div>
</form>
</div>
</div>
</div>
<!--Submit button for names-->
<div *ngIf="!isCollapsed" class="submit-names">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
|
Duck class
Goal: - to deal with vary behaviours through subclasses:
- flying_behaviours
- quack_sound
Design Principle 1:
"Take what varies and “encapsulate” it"
if you’ve got some aspect of your code that is changing, saywith every new requirement, then you know you’ve got a behaviour that needsto be pulled out and separated from all the stuff that doesn’t change.
"take the parts that vary and encapsulate them, so that later you can alter or extend the parts that varywithout affecting those that don’t"
We know that fly() and quack() are the parts of the Duck class that vary across ducks.To separate these behaviours from the Duck class, we’ll pull both methods out of the Duck class and create a new set of classes to represent each behaviour.
Design Principle 2:
Use interfaces to represent these sets of behaviours
for instance, FlyBehavior and QuackBehavior — and each implementation of a behaviour will implement one of those interfaces.
See files to see the implementation of these two principles.
Addtionally, in an ideal situation, there isn't a need to create an instance of a subclass like in DuckClient. We also do not need for a hardcode (e.g., RubberDuck class). We have already have concrete implemenations (the sets of behaviours classes: FlywithWings, ..., etc).
We can use "dependency injection".
Directly injecting behaviors into a superclass or any class is typically referred to as "dependency injection".
In the context of the strategy pattern or similar design patterns, when you pass the behavior (usually in the form of an interface) as a parameter to a class, you are using dependency injection to decouple the specific behavior from the class itself. This allows for more flexibility and promotes the principle of composition over inheritance.
In object-oriented design and the SOLID principles, the "D" stands for Dependency Inversion Principle, which suggests that high-level modules should not depend on low-level modules, but both should depend on abstractions. Dependency injection is one way to achieve this principle.
Duck wildDuck = new Duck(new Quack(), new FlyWithWings());
wildDuck.performQuack(); // Output: Quack!
wildDuck.performFly(); // Output: I'm flying with wings!
using constructor-based dependency injection to pass specific behaviors (Quack and FlyWithWings) directly into a Duck instance. By doing this, you've decoupled the Duck class from the concrete implementations of its behaviors, allowing you to easily change or add new behaviors without modifying the Duck class itself. This approach provides flexibility and adheres to the open/closed principle, which is one of the SOLID principles, meaning that a class should be open for extension but closed for modification.
|
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
import 'cypress-wait-until';
import '@testing-library/cypress/add-commands';
Cypress.Commands.add('clearAndType', (locator, text, numberOfElement = 0, waitTime = 0) => {
cy.wait(waitTime);
cy.get(locator).eq(numberOfElement).clear({ force: true });
cy.get(locator).eq(numberOfElement).type(text, { force: true });
});
Cypress.Commands.add('visitAndWait', (url, waitTime) => {
cy.visit(url);
cy.wait(waitTime);
});
Cypress.Commands.add('goToPage', (url, clickBody = false) => {
cy.visit(url);
if (clickBody) {
cy.get('div.header-wrapper').click();
}
//cy.acceptCookies();
//cy.closeModal();
});
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
|
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { CreateNotificationDto } from '../../interfaces/CreateNotificationDto'
const notificationsApi = createApi({
reducerPath: 'messageLogs',
baseQuery: fetchBaseQuery({
baseUrl: process.env.REACT_APP_API_BASE_URL,
}),
endpoints(builder) {
return {
fetchNotifications: builder.query({
query: (user_id: string) => {
return {
url: '/message-log',
params: {
user_id,
},
method: 'GET',
}
},
}),
sendNotification: builder.mutation({
query: (body: CreateNotificationDto) => {
return {
url: '/message-log',
body,
method: 'POST',
}
},
}),
}
},
})
export const { useFetchNotificationsQuery, useSendNotificationMutation, useLazyFetchNotificationsQuery } = notificationsApi
export { notificationsApi }
|
import { SortAZ } from "assets/icons/SortAZ";
import axios from "axios";
import Image from "components/image/image";
import moment from "moment";
import { useRouter } from "next/router";
import React, { useState } from "react";
import Table from "react-bootstrap/Table";
import { FormattedMessage } from "react-intl";
import StarRatings from "react-star-ratings";
import { getCookie } from "utils/session";
import { Box } from "./manage-post.style";
import {
getReviews,
createReview,
deleteReview,
editReview,
} from "utils/api/user";
import { Reply } from "assets/icons/Reply";
import { Remove } from "assets/icons/Remove";
import { Edit } from "assets/icons/Edit";
import Spinner from "components/spinner";
import { alignItems, justifyContent } from "styled-system";
type ManagePostProps = {
deviceType?: {
mobile: boolean;
tablet: boolean;
desktop: boolean;
};
userId?: number;
data?: any;
onAddReview?: () => void;
};
const ManagePostReview: React.FC<ManagePostProps> = ({
deviceType,
userId,
data,
onAddReview,
}) => {
const [errorReview, setErrorReview] = React.useState("");
const [addingLoading, setAddingLoading] = useState(false);
const [removingLoading, setRemovingLoading] = useState(false);
const [review, setReview] = React.useState("");
const [rating, setRating] = React.useState(0);
const router = useRouter();
const token = getCookie("access_token");
const handleSubmit = async () => {
if (token == null) {
setErrorReview("errorLoginReview");
return;
}
if (review.trim().length === 0) {
setErrorReview("errorReview");
return;
}
if (userId == getCookie("userId")) {
setErrorReview("errorBlockReview");
return;
} else {
setAddingLoading(true);
setErrorReview("");
const reviewObject = {
user_id: userId,
star: rating,
content: review,
};
const { result, error } = await createReview(token, reviewObject);
//call api
if (result) {
setReview("");
setRating(0);
setAddingLoading(false);
onAddReview();
} else {
setErrorReview("addReviewOneTimeError");
setAddingLoading(false);
}
return;
}
};
// remove parent node
const removeMyReview = async (id) => {
setRemovingLoading(true);
const { result, error } = await deleteReview(token, id);
if (result) {
setRemovingLoading(false);
onAddReview();
}
};
// edit review parent
return (
<Box>
{data.length != 0 && data
? data.map((d) => (
<div key={d.id} className="parent-node">
<div className="td-img">
<Image
url={d.reviewer.avatar}
className="avatar-in-table"
style={{ position: "relative", marginRight: "10px" }}
alt={d.star}
/>
<div
className="td-profile"
onClick={() => {
router.push(
Number(getCookie("userId")) != d.reviewer_id
? `/profile/${d.reviewer_id}`
: "/profile"
);
}}
style={{ cursor: "pointer" }}
>
<span>{d.reviewer.name}</span>
<p>{moment(d.created_at).format("LLL")}</p>
</div>
</div>
<div className="td">
<StarRatings
rating={d.star}
starDimension="20px"
starSpacing="5px"
starRatedColor={"#ffc107"}
/>
<p>{d.content}</p>
</div>
<div className="td" style={{ maxWidth: 500 }}>
{d.description}
</div>
{/* check me to edit */}
{Number(getCookie("userId")) == d.reviewer.id ? (
<div className="td" style={{ maxWidth: 100 }}>
<span
style={{ cursor: "pointer" }}
onClick={() => removeMyReview(d.id)}
>
{removingLoading ? <Spinner /> : <Remove />}
</span>
</div>
) : null}
</div>
))
: null}
{userId != Number(getCookie("userId")) ? (
<form style={{ paddingTop: 10, borderTop: "1px solid #dae0df" }}>
<div style={{ fontWeight: 600, margin: "20px 0" }}>
<label>
Review:
<br />
<textarea
rows={4}
cols={50}
value={review}
style={{ marginTop: "10px 0" }}
onChange={(e) => setReview(e.target.value)}
/>
</label>
</div>
<div style={{ fontWeight: 600, marginBottom: "20px" }}>
<label>
Rating:
<br />
<StarRatings
starHoverColor={"#ffc107"}
rating={rating}
starDimension="20px"
starSpacing="5px"
starRatedColor={"#ffc107"}
changeRating={(rating) => setRating(rating)}
/>
</label>
</div>
<div
style={{
color: "white",
border: 0,
width: "100px",
height: "40px",
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "#009e7f",
padding: "5px 10px",
borderRadius: 5,
cursor: "pointer",
}}
onClick={handleSubmit}
>
{addingLoading ? <Spinner /> : "Submit"}
</div>
{errorReview ? (
<p style={{ color: "red", marginTop: 10 }}>
<FormattedMessage
id={errorReview}
defaultMessage="Please login!"
/>
</p>
) : null}
</form>
) : null}
</Box>
);
};
export default ManagePostReview;
|
describe('API Response after Submit Button Click', () => {
it('captures the response of an API call after clicking on submit button', () => {
// Intercept the API call
cy.intercept('POST', '/signup').as('submitRequest');
// Visit the webpage
cy.visit('https://automationexercise.com/signup');
// Click on the submit button
cy.get('input[type="text"]').type('Sunny')
cy.get('input[data-qa="signup-email"]').type('[email protected]')
cy.get('button[data-qa="signup-button"]').click();
// Wait for the API call to complete and capture its response
cy.wait('@submitRequest').then((interception) => {
// Assertion: Check if the response is successful (status code 200)
expect(interception.response.statusCode).to.equal(200);
// Log the response body for further inspection
cy.log('Response Body:', interception.response.body);
});
});
});
|
from django.shortcuts import render
# Create your views here.
"""
Views for the recipe APIs
"""
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Recipe,Tag
from recipe import serializers
from rest_framework import viewsets,mixins
class RecipeViewSet(viewsets.ModelViewSet):
"""View for manage recipe APIs."""
serializer_class = serializers.RecipeDetailSerializer #uses this for the Create,Update and Delete endpoints
queryset = Recipe.objects.all()
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get_queryset(self):
"""Retrieve recipes for authenticated user."""
return self.queryset.filter(user=self.request.user).order_by('-id')
def get_serializer_class(self):
if self.action == 'list':
return serializers.RecipeSerializer #this is used for listing the recipes
return self.serializer_class
def perform_create(self,serializer):
serializer.save(user=self.request.user)
class TagViewSet(mixins.DestroyModelMixin,mixins.ListModelMixin,mixins.UpdateModelMixin,viewsets.GenericViewSet):
serializer_class =serializers.TagSerializer
queryset = Tag.objects.all()
authentication_classes=[TokenAuthentication]
permission_classes = [IsAuthenticated]
def get_queryset(self):
"""Filter queryset to authenticated user."""
return self.queryset.filter(user=self.request.user).order_by('-name')
|
---
tags:
- SigmaScheduling
---
# Float To Sigmas
## Documentation
- Class name: `FloatToSigmas`
- Category: `KJNodes/noise`
- Output node: `False`
Transforms a list of float values into a tensor of sigmas, facilitating the conversion of numerical data into a format suitable for noise generation and manipulation within neural networks.
## Input types
### Required
- **`float_list`**
- A list of float values to be converted into a sigmas tensor. This input is crucial for defining the specific noise levels to be applied in the neural network's processing.
- Comfy dtype: `FLOAT`
- Python dtype: `List[float]`
## Output types
- **`SIGMAS`**
- Comfy dtype: `SIGMAS`
- A tensor of sigmas derived from the input list of float values, used for noise generation and manipulation in neural network operations.
- Python dtype: `torch.Tensor`
## Usage tips
- Infra type: `GPU`
- Common nodes: unknown
## Source code
```python
class FloatToSigmas:
@classmethod
def INPUT_TYPES(s):
return {"required":
{
"float_list": ("FLOAT", {"default": 0.0, "forceInput": True}),
}
}
RETURN_TYPES = ("SIGMAS",)
RETURN_NAMES = ("SIGMAS",)
CATEGORY = "KJNodes/noise"
FUNCTION = "customsigmas"
DESCRIPTION = """
Creates a sigmas tensor from list of float values.
"""
def customsigmas(self, float_list):
return torch.tensor(float_list, dtype=torch.float32),
```
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<script>
function validateForm() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var birthday = document.getElementById("birthday").value;
var email = document.getElementById("email").value;
var phoneNumber = document.getElementById("phone").value;
var subject = document.getElementById("subject").value;
var maleRadio = document.getElementById("male");
var femaleRadio = document.getElementById("female");
var genderSelected = maleRadio.checked || femaleRadio.checked;
if (
!firstName ||
!lastName ||
!birthday ||
!email ||
!phoneNumber ||
subject === "" ||
!genderSelected
) {
alert("Please fill in all required fields.");
return false;
}
}
</script>
<title>Document</title>
</head>
<body>
<div class="container">
<div class="title">Registration Form</div>
<form id="registrationForm" onsubmit="return validateForm()" action="#">
<div class="user-details">
<div class="input-box">
<span class="details">First Name</span>
<input id="fname" type="text" required />
</div>
<div class="input-box">
<span class="details">Last Name</span>
<input id="lname" type="text" required />
</div>
<div class="input-box">
<span class="details">Birthday</span>
<input id="birthday" type="date" />
</div>
<div class="radio-box">
<span class="details">Gender</span>
<div class="gender-options">
<div>
<input id="male" type="radio" id="male" name="gender" value="male" />
<label for="male">Male</label>
</div>
<div>
<input id="female" type="radio" id="female" name="gender" value="female" />
<label for="female">Female</label>
</div>
</div>
</div>
<div class="input-box">
<span class="details">Email</span>
<input id="email" type="email" required />
</div>
<div class="input-box">
<span class="details">Phone Number</span>
<input id="phone" type="number" required />
</div>
<div class="input-box">
<div class="input-box full-width">
<span class="details">Subject</span>
<select id="subject">
<option value="">Choose Subject</option>
<option value="DSA">DSA</option>
<option value="Theory of Automata">Theory of Automata</option>
<option value="Compiler Construction">Math</option>
<option value="Database Systems">Database Systems</option>
<option value="HCI">HCI</option>
</select>
</div>
</div>
</div>
<div class="button">
<input type="submit" value="submit" />
</div>
</form>
</div>
</body>
</html>
|
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { NbThemeModule, NbLayoutModule } from '@nebular/theme';
import { NbEvaIconsModule } from '@nebular/eva-icons';
import { MovieSearchComponent } from './movie-search/movie-search.component';
import { BookmarkedMoviesComponent } from './bookmarked-movies/bookmarked-movies.component';
import { ReactiveFormsModule } from '@angular/forms';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent,
MovieSearchComponent,
BookmarkedMoviesComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
NoopAnimationsModule,
NbThemeModule.forRoot({ name: 'default' }),
NbLayoutModule,
NbEvaIconsModule,
ReactiveFormsModule
],
providers: [
{ provide: 'API_KEY', useValue: environment.apiKey }
],
bootstrap: [AppComponent]
})
export class AppModule { }
|
import { Module } from "@nestjs/common";
import { UserModule } from "./user/user.module";
import { OrganizationModule } from "./organization/organization.module";
import { WebsiteModule } from "./website/website.module";
import { PageModule } from "./page/page.module";
import { PageSectionModule } from "./pageSection/pageSection.module";
import { SectionTemplateModule } from "./sectionTemplate/sectionTemplate.module";
import { HealthModule } from "./health/health.module";
import { PrismaModule } from "./prisma/prisma.module";
import { SecretsManagerModule } from "./providers/secrets/secretsManager.module";
import { ServeStaticModule } from "@nestjs/serve-static";
import { ServeStaticOptionsService } from "./serveStaticOptions.service";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { GraphQLModule } from "@nestjs/graphql";
import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";
import { ACLModule } from "./auth/acl.module";
import { AuthModule } from "./auth/auth.module";
@Module({
controllers: [],
imports: [
ACLModule,
AuthModule,
UserModule,
OrganizationModule,
WebsiteModule,
PageModule,
PageSectionModule,
SectionTemplateModule,
HealthModule,
PrismaModule,
SecretsManagerModule,
ConfigModule.forRoot({ isGlobal: true }),
ServeStaticModule.forRootAsync({
useClass: ServeStaticOptionsService,
}),
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
useFactory: (configService: ConfigService) => {
const playground = configService.get("GRAPHQL_PLAYGROUND");
const introspection = configService.get("GRAPHQL_INTROSPECTION");
return {
autoSchemaFile: "schema.graphql",
sortSchema: true,
playground,
introspection: playground || introspection,
};
},
inject: [ConfigService],
imports: [ConfigModule],
}),
],
providers: [],
})
export class AppModule {}
|
package baekjoon_01001_02000;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
//[골드 5] 최단경로
//https://www.acmicpc.net/problem/1753
//제출전에 Main으로 바꾸기, file input 지우기, package 지우기
public class bj_1753_최단경로_최민수 {
// static int adj[][];
static class Node implements Comparable<Node> {
int vertex;
int weight;
public Node(int vertex, int weight) {
super();
this.vertex = vertex;
this.weight = weight;
}
@Override
public int compareTo(Node o) {
return Integer.compare(this.weight, o.weight);
}
}
static List<Node>[] adjList;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws Exception {
// 테스트 입력
System.setIn(new FileInputStream("res/baekjoon/bj_input_1753"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
// 정점의 개수 V 1~2만, 간선의 개수 E 1~30만
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int v = Integer.parseInt(st.nextToken());
int e = Integer.parseInt(st.nextToken());
// 시작 정점의 번호 K: 1~V
int k = Integer.parseInt(br.readLine()) - 1;
// adj = new int[v][v];
adjList = new ArrayList[v];
for (int i = 0; i < v; i++) {
adjList[i] = new ArrayList<>();
}
// 간선을 나타내는 u->v, 가중치 w, w: 1~10, u, v는 다름
// 다른 두 정점 사이에 여러 간선이 존재할 수 있음.
for (int i = 0; i < e; i++) {
st = new StringTokenizer(br.readLine(), " ");
int start = Integer.parseInt(st.nextToken()) - 1;
int end = Integer.parseInt(st.nextToken()) - 1;
int weight = Integer.parseInt(st.nextToken());
// if(adj[start][end] == 0) adj[start][end] = weight;
// else adj[start][end] = adj[start][end] < weight ? adj[start][end] : weight;
// 이미 값이 있는지 확인
// boolean isExist = false;
// for (Node temp = adjList[start]; temp != null; temp = temp.next) {
// if (temp.vertex == end) { //도착지점 노드 찾음.
// isExist = true;
// if (temp.weight > weight) { // 기존 가중치보다 더 작다.
// temp.weight = weight; // 값 갱신
// }
// break;
// }
// }
// if(!isExist) { //기존에 없던 노드면
// adjList[start] = new Node(end, weight, adjList[start]);
// }
// adjList[start] = new Node(end, weight);
adjList[start].add(new Node(end, weight));
}
// 출력 v줄에 걸쳐 출발->i로의 최단 경로값 출력
// 경로 없으면 INF 출력
dijkstra(k, v);
for (int i = 0; i < v; i++) {
if (distance[i] == INFINITY)
sb.append("INF\n");
else
sb.append(distance[i] + "\n"); // 지금까지 더한 누적값 출력
}
bw.write(sb.toString());
bw.close();
br.close();
}
static final int INFINITY = Integer.MAX_VALUE;
static int distance[];
private static void dijkstra(int start, int nodeNum) {
// int nodeNum = adj.length;
distance = new int[nodeNum];
boolean visited[] = new boolean[nodeNum];
PriorityQueue<Node> pq = new PriorityQueue<Node>();
Arrays.fill(distance, INFINITY);
distance[start] = 0;
pq.offer(new Node(start, 0));
while (!pq.isEmpty()) {
Node now = pq.poll();
int current = now.vertex;
if (!visited[current]) {
visited[current] = true;
for (Node temp : adjList[current]) {
if (!visited[temp.vertex] && distance[temp.vertex] > distance[current] + temp.weight) {
distance[temp.vertex] = distance[current] + temp.weight;
pq.offer(new Node(temp.vertex, distance[temp.vertex]));
}
}
}
}
}
}
// 1. 메모리 초과: 아마 인접 행렬 사용 -> 인접 리스트로 교체해볼 예정
// 2. 시간 초과: syso 에서 sb + bw 사용
// 3. 시간 초과: => priority queue사용?
// 4. 시간 초과 해결: dijkstra를 한번만 돌리면 되는데, 각 정점마다 다 돌렸다.
|
import Link from "next/link";
import { type FC } from "react";
import { RegisterForm } from "@/app/features/register/registerForm";
import { I18nProps } from "@/app/i18n/props";
import { ERoutes } from "@/app/shared/enums";
import { createPath } from "@/app/shared/utils";
import {
ETypographyVariant,
Typography,
} from "@/app/uikit/components/typography";
import "./RegisterPage.scss";
export const RegisterPage: FC<I18nProps> = ({ i18n }) => {
return (
<div className="RegisterPage">
<div className="RegisterPage-Center">
<div className="RegisterPage-Content">
<div className="RegisterPage-Title">
<Typography
value={i18n.t("pages.register.title")}
variant={ETypographyVariant.TextH1Bold}
/>
</div>
<RegisterForm />
<div className="RegisterPage-HaveAccount">
<Typography
value={i18n.t("pages.register.haveAccount")}
variant={ETypographyVariant.TextB3Regular}
/>
<Link
href={createPath({
route: ERoutes.Login,
})}
>
<Typography
value={i18n.t("pages.register.enter")}
variant={ETypographyVariant.TextB3Regular}
/>
</Link>
</div>
</div>
</div>
</div>
);
};
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PedidosComponent } from './components/vistas/pedidos/pedidos.component';
import {FormComponent} from './components/vistas/form/form.component';
import { AddressFormComponent } from './components/vistas/address-form/address-form.component';
import { ProductInfoComponent } from './components/vistas/product-info/product-info.component';
import { AddressListComponent } from './components/shared/address-list/address-list.component';
import { ModalMessageComponent } from './components/shared/modal-message/modal-message.component';
import { OrderShipmentDataComponent } from './components/shared/order-shipment-data/order-shipment-data.component';
import { ConfirmationMessageComponent } from './components/shared/confirmation-message/confirmation-message.component';
import { ToPrintComponent } from './components/shared/to-print/to-print.component';
import { ChartsComponent } from './components/charts/charts.component';
import { InventoryComponent } from './components/inventory/inventory.component';
import { LoaderComponent } from './components/shared/loader/loader.component';
import { ProductRequestComponent } from './components/shared/product-request/product-request.component';
import { OrderEditComponent } from './components/vistas/order-edit/order-edit.component';
import { LoginComponent } from './components/vistas/login/login.component';
import { ForgetPasswordComponent } from './components/vistas/forget-password/forget-password.component';
//const domain : string = 'http://localhost:4200/';
//const index : string = 'https://azban-buzos.azurewebsites.net/';s
const index : string = '';
const routes: Routes = [
{ path: index+'order-edit', component: OrderEditComponent },
{ path: index+'vista-pedidos', component: PedidosComponent },
{ path: index+'', component: PedidosComponent },
{ path: index+'crear-pedido', component: FormComponent },
{ path: index+'address-form', component: AddressFormComponent},
{ path: index+'product-info', component: ProductInfoComponent },
{ path: index+'address-list', component: AddressListComponent},
{ path: index+'modal-message', component: ModalMessageComponent},
{ path: index+'order-shipment-data', component: OrderShipmentDataComponent},
{ path: index+'confirmation-message', component: ConfirmationMessageComponent},
{ path: index+'to-print', component: ToPrintComponent},
{ path: index+'charts', component: ChartsComponent},
{ path: index+'inventory', component: InventoryComponent},
{ path: index+'loader', component: LoaderComponent},
{ path: index+'product-request', component: ProductRequestComponent},
{ path: index+'login', component: LoginComponent},
{ path: index+'forget-password', component: ForgetPasswordComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import React from "react";
import "./filialinner.scss";
import Footer from "../../footer/Footer";
import Navbar from "../../navbar/Navbar";
import { ApiFuncsContext } from "../../../anyFunc/apiFuncs";
import { useParams } from "react-router-dom";
const FilialInner = ({ match }) => {
const { filials } = React.useContext(ApiFuncsContext);
const { id } = useParams();
const filial = filials.find((filial) => filial.id == id);
return (
<>
<Navbar />
<div key={id} className="filial-inner-container">
<div
className="filial-inner-card my-5"
style={{ boxShadow: "0 4px 30px rgb(0 0 0 / 7%)" }}
>
<div className="filial-inner-left-div">
<h1>{filial?.name}</h1>
<div className="filial-inner-left-div-linkers my-4">
<div className="address">{filial?.address}</div>
<div className="worktime">Часы работы: {filial?.work_time}</div>
<div className="phone">
Номер телефона: <a href="tel:+998712445445">{filial?.phone}</a>
</div>
<div className="location">Ориентир: San Farm</div>
</div>
</div>
<div className="filial-inner-right-div">
<iframe
src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d390.10922419401896!2d69.25442865812578!3d41.32330762633482!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x38ae8b036f632131%3A0x35a1d62811fbf156!2sBDDDY%20BURGER!5e0!3m2!1sru!2s!4v1656020834641!5m2!1sru!2s"
width="100%"
height="446"
className="border-0"
style={{ borderRadius: "12px" }}
allowFullScreen=""
loading="lazy"
referrerPolicy="no-referrer-when-downgrade"
></iframe>
</div>
</div>
</div>
<Footer />
</>
);
};
export default FilialInner;
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shop_getx/controllers/admin/category_controller.dart';
import 'package:shop_getx/controllers/client/shopping_cart_controller.dart';
import 'package:shop_getx/core/app_colors.dart';
import 'package:shop_getx/core/app_sizes.dart';
import 'package:shop_getx/generated/locales.g.dart';
import 'package:shop_getx/views/widgets/custom_button.dart';
import 'package:shop_getx/views/widgets/custom_dialog.dart';
import 'package:shop_getx/views/widgets/custom_text.dart';
import '../../../controllers/shared/product_controller.dart';
import '../../../models/shopping_cart.dart';
import '../../widgets/product_item.dart';
class ShoppingCartPage extends GetView {
ShoppingCartPage({Key? key}) : super(key: key);
final ProductController productController = Get.find<ProductController>();
@override
Widget build(BuildContext context) {
Get.lazyPut(() => ShoppingCartController());
Get.lazyPut(() => CategoryController());
return GetBuilder<ShoppingCartController>(
assignId: true,
builder: (logic) {
return SafeArea(
child: Scaffold(
backgroundColor: AppColors.backGroundColor,
body: buyBasketList.isNotEmpty
? _bodyItems(logic)
: Center(
child: CustomText(
text: LocaleKeys.ShoppingCart_page_noCartMsg.tr,
textSize: AppSizes.normalTextSize1,
textColor: Colors.black),
),
),
);
},
);
}
Widget _bodyItems(ShoppingCartController controller) {
return SingleChildScrollView(
child: Column(
children: [
_completeShopping(controller),
AppSizes.littleSizeBox,
_shoppingCartList(controller)
],
),
);
}
Widget _shoppingCartList(ShoppingCartController shoppingController) {
return ListView.builder(
shrinkWrap: true,
itemCount: buyBasketList.length,
itemBuilder: (context, index) {
return ProductItem(
iconLike: false,
isFade: false,
onAddBtnClick: () {
shoppingController.editShoppingCart(buyBasketList[index]);
},
onRemoveBtnClick: () {
num? productCount = buyBasketList[index].productCountInBasket;
//if product count is more than 1 in basket remove 1 else remove product totally
if (productCount! > 1) {
shoppingController
.removeProductFromBasket(buyBasketList[index]);
} else {
Get.dialog(CustomAlertDialog(
messageTxt: LocaleKeys.ShoppingCart_page_lastItemRemove.tr,
onOkTap: () {
Get.back();
shoppingController
.removeProductFromBasket(buyBasketList[index]);
},
confirmBtnTxt: LocaleKeys.Dialogs_message_yesBtn.tr,
negativeBtnTxt: LocaleKeys.Dialogs_message_noBtn.tr,
onNoTap: () => Get.back(),
));
}
},
product: buyBasketList[index],
productIndex: index,
);
}
);
}
Widget _completeShopping(ShoppingCartController controller) {
return Container(
color: Colors.white,
padding: const EdgeInsets.all(15),
child: Row(
children: [
GetBuilder<CategoryController>(builder: (logic) {
return CustomButton(
onTap: () {
if (controller.allProductStock()) {
Get.dialog(CustomAlertDialog(
messageTxt: LocaleKeys.ShoppingCart_page_confirmShopping.tr,
onOkTap: () {
_emptyShoppingCart(controller, logic);
Get.back();
},
confirmBtnTxt: LocaleKeys.Add_product_page_yesBtn.tr,
negativeBtnTxt: LocaleKeys.Add_product_page_noBtn.tr,
onNoTap: () => Get.back(),
));
} else {
Get.dialog(CustomAlertDialog(
messageTxt:
LocaleKeys.ShoppingCart_page_unavailableProduct.tr,
onOkTap: () => Get.back(),
confirmBtnTxt: LocaleKeys.Dialogs_message_closeBtn.tr,
));
}
},
buttonText: LocaleKeys.ShoppingCart_page_completeShoppingBtn.tr,
buttonColor: AppColors.primaryColor,
textColor: Colors.white,
buttonWidth: 150,
buttonHeight: 40,
textSize: AppSizes.littleTextSize,
);
}),
const Spacer(),
CustomText(
text:
'${LocaleKeys.ShoppingCart_page_totalShoppingTxt.tr} ${controller.totalShoppingCart().toString()} ${LocaleKeys.ShoppingCart_page_moneyUnit.tr} '),
],
),
);
}
Future<void> _emptyShoppingCart(ShoppingCartController catController,
CategoryController categoryController) async {
int allShopping = 0;
// search each item in product and check their availability
for (var cartProduct in buyBasketList) {
for (var product in productList) {
if ((cartProduct.id == product.id) &&
(cartProduct.productCountInBasket! <= product.totalProductCount!)) {
// reduce product availability
product.totalProductCount =
product.totalProductCount! - cartProduct.productCountInBasket!;
product.productCountInBasket = 0;
await productController.editProduct(product).then((value) async {
// find product in categories and delete its availability from it
for (var category in categoryList) {
if (category.name == product.productCategory) {
for (int i = 0; i < category.productsList!.length; i++) {
if (category.productsList![i].id == product.id) {
category.productsList![i] = product;
await categoryController
.editCategory(category)
.then((value) {
allShopping += 1;
});
break;
}
}
}
}
});
}
}
}
if (allShopping == buyBasketList.length) {
catController.emptyShoppingCart();
Get.snackbar(LocaleKeys.Dialogs_message_doneMsg.tr,
LocaleKeys.ShoppingCart_page_successFullShopping.tr);
} else {
Get.snackbar(LocaleKeys.Dialogs_message_warning.tr,
LocaleKeys.ShoppingCart_page_unSuccessFullShopping.tr);
}
}
}
|
import { createReducer, on } from '@ngrx/store';
import { User } from '../models/user';
import * as fromAuthActions from './auth.actions';
export const authFeatureKey = 'auth';
export interface State {
user: User | null;
error: any;
isLoggedIn: boolean | null;
}
export const initialState: State = {
user: null,
error: null,
isLoggedIn:null,
};
export const reducer = createReducer(
initialState,
on(fromAuthActions.loginSuccess, (state, action) => {
return {
...state,
error: null,
isLoggedIn:true,
};
}),
on(fromAuthActions.loginFailure, (state, action) => {
return {
...state,
user: null,
error: action.error,
isLoggedIn:false,
};
}),
on(fromAuthActions.logout, (state) => {
return {
...state,
user: null,
error: null,
isLoggedIn: false
};
}),
on(fromAuthActions.getCurrentUserInfoSuccess, (state, action) => {
return {
...state,
user: action.user,
error: null,
isLoggedIn: true
};
}),
on(fromAuthActions.getCurrentUserInfoFailure, (state, action) => {
return {
...state,
user: null,
error: action.error,
isLoggedIn: false
};
}),
on(fromAuthActions.clearCurrentUserInfo, (state, action) => {
return {
...state,
user: null,
error: null,
isLoggedIn: false
};
}),
);
|
//
// CNAccountInputView.m
// HYNewNest
//
// Created by cean.q on 2020/7/13.
// Copyright © 2020 james. All rights reserved.
//
#import "CNAccountInputView.h"
@interface CNAccountInputView () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *tipLb;
@property (weak, nonatomic) IBOutlet UITextField *inputTF;
@property (weak, nonatomic) IBOutlet UIView *lineView;
/// 记录对错,用于UI改变风格
@property (assign, nonatomic) BOOL wrongAccout;
@property (nonatomic, strong) UIColor *hilghtColor;
@property (nonatomic, strong) UIColor *wrongColor;
@property (nonatomic, strong) UIColor *normalColor;
@end
@implementation CNAccountInputView
- (void)loadViewFromXib {
[super loadViewFromXib];
[self.inputTF addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
self.normalColor = kHexColorAlpha(0xFFFFFF, 0.15);
self.hilghtColor = kHexColor(0x10B4DD);
self.wrongColor = kHexColor(0xFF5860);
self.correct = NO; //初始化不能正确
}
- (void)showWrongMsg:(NSString *)msg {
self.wrongAccout = YES;
self.tipLb.hidden = NO;
self.tipLb.text = msg;
self.tipLb.textColor = self.wrongColor;
self.lineView.backgroundColor = self.wrongColor;
}
#pragma mark - delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
self.tipLb.hidden = NO;
self.tipLb.textColor = _wrongAccout ? self.wrongColor: self.hilghtColor;
self.lineView.backgroundColor = _wrongAccout ? self.wrongColor: self.hilghtColor;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
if (self.phoneLogin || self.fromServer) {
self.correct = [textField.text validationType:ValidationTypePhone];
if (!self.correct) {
[self showWrongMsg:@"您输入的手机不符合规则"];
}
} else { //结束编辑时校验不根据长度
if (self.isRegister) {
self.correct = [textField.text validationType:ValidationTypeUserName];
if (self.correct == false) {
[self showWrongMsg:@"f开头的5-11位数字+字母组合"];
}
}
else {
self.correct = [textField.text validationType:ValidationTypeLoginName];
if (self.correct == false) {
[self showWrongMsg:@"f开头的5-13位数字+字母组合 或 11位手机号码"];
}
}
}
if (self.correct) {
self.tipLb.hidden = YES;
self.lineView.backgroundColor = self.normalColor;
self.wrongAccout = NO;
}
}
- (void)textFieldChange:(UITextField *)textField {
// 长度优先
if (textField.text.length > 13 && self.isRegister == false && [textField.text hasPrefix:@"f"]) {
// textField.text = [textField.text substringToIndex:13];
}
else if (textField.text.length > 11 && (self.isRegister == true || (self.isRegister == false && [textField.text hasPrefix:@"1"]))) {
textField.text = [textField.text substringToIndex:11];
}
NSString *text = textField.text;
self.lineView.backgroundColor = self.hilghtColor;
self.tipLb.textColor = self.hilghtColor;
// 这里校验是判断手机号 还是 账号
if ((!self.isRegister && [text hasPrefix:@"1"]) || self.fromServer) {
self.tipLb.text = @"手机号码*";
self.phoneLogin = YES;
} else {
self.tipLb.text = @"用户名*";
self.phoneLogin = NO;
}
// 校验
// 手机号
if ((self.fromServer || self.phoneLogin) && text.length >= 11) {
self.correct = [textField.text validationType:ValidationTypePhone];
if (!self.correct) {
[self showWrongMsg:@"您输入的手机不符合规则"];
}
// 用户名
} else if (text.length >= 5 && !self.fromServer && self.isRegister){
self.correct = [textField.text validationType:ValidationTypeUserName];
if (self.correct == false) {
[self showWrongMsg:@"f开头的5-11位数字+字母组合"];
}
}
else if (self.fromServer == false && self.isRegister == false) {
self.correct = [textField.text validationType:ValidationTypeLoginName];
if (self.correct == false) {
[self showWrongMsg:@"f开头的5-13位数字+字母组合 或 11位手机号码"];
}
}
else {
self.correct = NO;
}
if (_delegate && [_delegate respondsToSelector:@selector(accountInputViewTextChange:)]) {
[_delegate accountInputViewTextChange:self];
}
}
#pragma mark - SET & GET
- (NSString *)account {
return [self.inputTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].lowercaseString;
}
- (void)setAccount:(NSString * _Nonnull)account {
self.inputTF.text = [account stringByReplacingOccurrencesOfString:@" " withString:@""];
}
- (void)setIsRegister:(BOOL)isRegister {
_isRegister = isRegister;
if (isRegister) {
self.tipLb.text = @"用户名*";
}
}
- (void)setFromServer:(BOOL)fromServer {
_fromServer = fromServer;
self.inputTF.keyboardType = UIKeyboardTypePhonePad;
}
- (void)setPlaceholder:(NSString *)text {
self.inputTF.placeholder = text;
}
@end
|
package by.itacademy.ganina.core.sorter.impl;
import by.itacademy.ganina.core.sorter.SortingReader;
import by.itacademy.ganina.core.sorter.SortingReaderException;
import by.itacademy.ganina.core.sorter.SortingType;
import by.itacademy.ganina.web.model.Transport;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class RequestParamSortingReader implements SortingReader {
@Override
public Comparator<Transport> readSorting(final String requestParamLine) throws SortingReaderException {
if (requestParamLine == null) {
return null;
}
try {
String[] sortingCommand = requestParamLine.split(", ");
List<String> commandsList = new ArrayList<>();
for (String command : sortingCommand) {
commandsList.add(command);
}
return chooseComparator(commandsList);
} catch (final IllegalArgumentException ex) {
throw new SortingReaderException("ошибка чтения сортировки из request parameters", ex);
}
}
public static Comparator<Transport> chooseComparator(final List<String> commandsList) {
Comparator<Transport> comparator = null;
if (commandsList == null) {
return comparator;
}
final List<Comparator<Transport>> comparatorList = new ArrayList<>();
for (final String commandLine : commandsList) {
final String[] splitedCommandLine = commandLine.split("-");
comparator = SortingType.valueOf(splitedCommandLine[0]).getTransportComparator();
switch (splitedCommandLine[1]) {
case "H":
comparatorList.add(comparator);
break;
case "L":
comparatorList.add(comparator.reversed());
break;
default:
comparator = null;
System.out.println("you don't choose sorting by" + SortingType.valueOf(splitedCommandLine[0]));
}
}
System.out.println("you choose next sorting: " + commandsList);
switch (comparatorList.size()) {
case 1: //выбрана сортировка по 1 параметру
comparator = comparatorList.get(0);
break;
case 2: //выбрана сортировка по 2 параметрам
comparator = comparatorList.get(0).thenComparing(comparatorList.get(1));
break;
default:
return null;
}
return comparator;
}
}
|
---
title: Accélération des téléchargements de Brand Portal
seo-title: Speed up the Brand Portal downloads
description: Améliorez les performances de téléchargement à partir de Brand Portal et des liens partagés.
seo-description: Enhance download performance from Brand Portal and the shared links.
uuid: 2871137e-6471-49a7-872a-841bd92543d1
contentOwner: Vishabh Gupta
topic-tags: download-install, download assets
content-type: reference
products: SG_EXPERIENCEMANAGER/Brand_Portal
discoiquuid: 301f7a0b-5527-4aac-b731-bfc145fed0c0
exl-id: cf28df58-c6dd-4b12-8279-01351892009f
source-git-commit: ce765700aaecba4bfff7b55effb05f981b94bdec
workflow-type: tm+mt
source-wordcount: '999'
ht-degree: 99%
---
# Accélération des téléchargements de Brand Portal {#guide-to-accelerate-downloads-from-brand-portal}
<!-- This topic is woefully out of date. It talks at length about using a third party application whose URLs have a variety of problems. Topic should either be deleted or updated entirely to not talk about a specific third party application that Adobe has no control over. It also appears that the third party app is NOT free anymore. -->
Adobe Experience Manager Assets Brand Portal permet d’améliorer les performances de téléchargement des fichiers de ressources volumineux par le biais d’une intégration à l’application IBM® Aspera Connect, qui s’installe à la demande. Cette application utilise une technologie propriétaire pour éliminer les surcharges TCP, et améliore la vitesse de transfert des fichiers de ressources. Cette intégration garantit une meilleure expérience de téléchargement.
>[!NOTE]
>
>La vitesse de téléchargement varie en fonction de facteurs tels que la bande passante du réseau, la latence du serveur et l’emplacement géographique des clients.
La configuration **[!UICONTROL Téléchargement rapide]** est activée par défaut, ce qui réduit considérablement le temps nécessaire au téléchargement des fichiers de ressources désirés à partir de Brand Portal.

## Conditions préalables pour accélérer le téléchargement de fichiers {#prerequisites-to-accelerate-file-download}
Pour télécharger les fichiers plus rapidement, vérifiez les points suivants :
* Accédez à **[!UICONTROL Outils]** > **[!UICONTROL Télécharger]** et vérifiez que la configuration **[!UICONTROL Téléchargement rapide]** est activée dans les **[!UICONTROL Paramètres de téléchargement]**.
* Veillez à ce que le port 33001 (TCP et UDP) soit ouvert sur le pare-feu.
* **Installez IBM® Aspera Connect 3.9.9** dans l’extension de votre navigateur à l’aide des droits d’administration ([Téléchargements IBM® Asperra Connect](https://www.ibm.com/support/fixcentral/swg/selectFixes?parent=ibm%7EOther%20software&product=ibm/Other+software/IBM+Aspera+Connect&release=3.9.9&platform=All&function=all)).
>[!NOTE]
>
>Il existe un problème connu avec IBM® Aspera Connect. Le téléchargement rapide ne fonctionne pas avec les versions 3.10 et ultérieures d’IBM® Aspera Connect.
## Domaines de téléchargement {#download-domains}
Vous trouverez ci-après les domaines de téléchargement pour différentes zones géographiques :
| Code de région | Domaine |
|---|---|
| NA OR1 | downloads-na1.brand-portal.adobe.com |
| NA VA5 | downloads-na2.brand-portal.adobe.com |
| EMEA LON5 | downloads-emea1.brand-portal.adobe.com |
| APAC SIN2 | downloads-apac1.brand-portal.adobe.com |
## Exemple de performances de téléchargement à l’aide de l’accélérateur de fichiers {#expected-download-performance-using-file-accelerator}
Le tableau suivant affiche les performances de téléchargement obtenues pour un fichier de 2 Go en utilisant l’accélérateur de téléchargement de fichiers d’Aspera Connect :
*Les résultats observés varient en fonction de facteurs tels que la bande passante du réseau, la latence du serveur et l’emplacement du client, en sachant que le serveur Brand Portal se situe dans l’État de l’Oregon aux États-Unis.*
| Emplacement du client | Latence entre le client et le serveur (millisecondes) | Vitesse mesurée avec l’accélérateur de transfert de fichiers d’Aspera Connect (Mbit/s) | Temps nécessaire pour télécharger un fichier de 2 Go avec l’accélérateur de transfert de fichiers d’Aspera (en secondes) |
|---------------------------|-----------------------------------|---------------------------------------------|-------------------------------------------------------------------------|
| Ouest des États-Unis (Californie du Nord) | 18 | 36 | 57 |
| Ouest des États-Unis (Oregon) | 42 | 36 | 57 |
| Est des États-Unis (Virginie du Nord) | 85 | 35 | 58 |
| Asie-Pacifique (Tokyo) | 124 | 36 | 57 |
| Noida (Inde) | 275 | 13.36 | 153 |
| Sydney | 175 | 29 | 70 |
| Londres | 179 | 35 | 58 |
| Singapour | 196 | 34 | 60 |
## Téléchargement de ressources {#download-assets}
Pour télécharger des ressources plus rapidement à partir de Brand Portal :
1. Connectez-vous à votre client Brand Portal. Par défaut, la vue **[!UICONTROL Fichiers]** s’ouvre et contient toutes les ressources et dossiers publiés.
Utilisez l’une des méthodes suivantes :
* Sélectionnez les ressources ou les dossiers que vous souhaitez télécharger. Dans la barre d’outils supérieure, cliquez sur l’icône **[!UICONTROL Télécharger]**.

* Pour télécharger des rendus de ressource spécifiques pour une ressource, survolez celle-ci avec le pointeur et cliquez sur l’icône **[!UICONTROL Télécharger]** disponible dans les miniatures d’action rapide.

1. La boîte de dialogue **[!UICONTROL Télécharger]** qui répertorie toutes les ressources sélectionnées s’ouvre.
Pour conserver la hiérarchie des dossiers de Brand Portal lors du téléchargement des ressources, cochez la case **[!UICONTROL Créer un dossier distinct pour chaque ressource]**.
Le bouton de téléchargement indique le nombre d’éléments sélectionnés. Une fois les règles appliquées, cliquez sur **[!UICONTROL Télécharger les éléments]**. Pour en savoir plus sur l’application des règles, consultez [Téléchargement de ressources](../using/brand-portal-download-assets.md#download-assets).

1. Par défaut, le paramètre **[!UICONTROL Téléchargement rapide]** est activé dans les **[!UICONTROL Paramètres de téléchargement]**. Par conséquent, une zone de confirmation s’affiche pour télécharger des ressources à l’aide d’IBM® Aspera Connect.
Si vous téléchargez les ressources pour la première fois et qu’IBM® Aspera Connect n’est pas installé dans votre navigateur ou si votre version existante n’est pas à jour, vous devez installer l’accélérateur de téléchargement d’Aspera (`https://www.ibm.com/docs/en/aspera-connect/3.9.9`).

1. **Installer le client d’Aspera Connect**
Pour installer la configuration cliente IBM® Aspera Connect, exécutez le programme d’installation à partir du fichier .msi de l’application cliente IBM® Aspera Connect et suivez l’assistant d’installation.

1. Une fois le client installé, actualisez la page du navigateur et relancez les étapes de téléchargement.
1. Pour continuer à utiliser le **[!UICONTROL Téléchargement rapide]**, cliquez sur **[!UICONTROL Autoriser]**. Tous les rendus sélectionnés sont téléchargés dans un dossier ZIP à l’aide d’IBM® Aspera Connect.
À la fin du téléchargement, une boîte de dialogue affiche l’emplacement où les ressources sont téléchargées sur le système de l’utilisateur ou de l’utilisatrice.

Si vous ne souhaitez pas utiliser IBM® Aspera Connect, cliquez sur **[!UICONTROL Refuser]**. Si le **[!UICONTROL Téléchargement rapide]** est refusé ou échoue, le système renvoie un message d’erreur. Cliquez sur le bouton **[!UICONTROL Téléchargement normal]** pour continuer à télécharger les ressources.
>[!NOTE]
>
Si le paramètre **[!UICONTROL Téléchargement rapide]** est désactivé par l’administration, les rendus sélectionnés sont directement téléchargés dans un dossier ZIP sans utiliser IBM® Aspera Connect.
<!--
On successful completion of the download, a dialog box shows the location where assets are downloaded onto the user's system. If there is a failure, it shows error.
>[!NOTE]
>
>There is a known limitation in Aspera Connect client application that no prompt to select download location appears if **[!UICONTROL Always ask me where to save downloaded files]** is enabled under the tab **[!UICONTROL Transfers]** within **[!UICONTROL Preferences]**. Before any download begins, provide the location in the text box **[!UICONTROL Save downloaded files to]**.
1. Log in to Brand Portal using a supported browser.
1. Browse and select the folders or assets you want to download. From the toolbar at the top, click the **[!UICONTROL Download]** icon. the **[!UICONTROL Download]** dialog appears with the **[!UICONTROL Asset(s)]** and **[!UICONTROL Enable download acceleration]** check boxes selected by default.

>[!NOTE]
>
>The functionality to send email notification with the link to download assets is presently not supported while faster downloads are enabled.

1. Click **[!UICONTROL Download]**.
To speed up the download experience on your Brand Portal tenant account, you need to have Aspera Connect client application installed in your browser's extension.
1. **Download Aspera Connect Client**
If Aspera Connect client is not installed on your system or the existing Aspera Connect client is out of date, a prompt is displayed on the browser page from where you can download the system-specific Aspera Connect client by selecting **[!UICONTROL Download Latest Version]**.

To download the latest version of Aspera Connect from [https://downloads.asperasoft.com/connect2/](https://downloads.asperasoft.com/connect2/), select **[!UICONTROL Download Now]** and follow the instructions.
1. **Install Aspera Connect Client**
To install IBM Aspera Connect client setup, run the setup from .msi file of IBM Aspera Connect client application and follow the installation wizard.
1. Once the client is successfully installed, refresh the browser page and initiate the download steps again.
When using Aspera Connect for the first time, the browser prompts to open the link using **[!UICONTROL IBM Aspera Connect]**. To skip this dialog in future, enable **[!UICONTROL Remember my choice for FASP links]**.
>[!NOTE]
>
>This message is different on the different browsers.
1. A dialog box confirms whether to proceed the transfer or not. Select **[!UICONTROL Allow]** to begin.
To skip this dialog in future, enable **[!UICONTROL Use my choice for all connections with this host]**.
Download begins. A dialog box shows the progress of the download. Use the dialog box to **[!UICONTROL pause]**, **[!UICONTROL resume]**, or **[!UICONTROL cancel]** the download.
Aspera Connect application provides an Activity Window on the system where user can view and manage all transfer sessions. For more information, refer [Aspera Connect Client documentation](https://downloads.asperasoft.com/en/documentation/8).

On successful completion of the download, a dialog box shows the location where assets are downloaded onto the user's system. If there is a failure, it shows error.
>[!NOTE]
>
>There is a known limitation in Aspera Connect client application that no prompt to select download location appears if **[!UICONTROL Always ask me where to save downloaded files]** is enabled under the tab **[!UICONTROL Transfers]** within **[!UICONTROL Preferences]**. Before any download begins, provide the location in the text box **[!UICONTROL Save downloaded files to]**.
-->
## Utiliser l’accélérateur de fichiers sur le navigateur Microsoft® Edge {#using-file-accelerator-on-microsoft-edge-browser}
Microsoft® Edge s’exécute en mode protégé amélioré (EPM), ce qui empêche la communication avec le serveur d’Aspera Connect, sur le même réseau privé ou avec un site de confiance. Par conséquent, une fenêtre contextuelle s’affiche chaque fois qu’une connexion au serveur est établie.

Pour utiliser la fonctionnalité de téléchargement accéléré sur Microsoft® Edge, supprimez le site Brand Portal de la liste des sites de confiance.
1. Ouvrez le Panneau de configuration (**[!UICONTROL touche Windows + X]**, puis sélectionnez **[!UICONTROL Panneau de configuration]**).
1. Accédez à **[!UICONTROL Réseau et Internet]** > **[!UICONTROL Options Internet]**. Cliquez sur l’onglet **[!UICONTROL Sécurité]**.
1. Cliquez sur **[!UICONTROL Zone Sites de confiance]**, puis sur **[!UICONTROL Sites]**.
1. Supprimez le site Brand Portal de la liste.
## Préférences du client Aspera Connect {#aspera-connect-client-preferences}
Certaines préférences utiles peuvent être définies dans les préférences du client IBM® Aspera Connect en cliquant avec le bouton droit sur l’icône et en sélectionnant **[!UICONTROL Préférences]**.

Vous pouvez définir l’emplacement de téléchargement par défaut.

En outre, le client Aspera Connect peut être marqué pour se lancer automatiquement au démarrage du système de manière à ce que le client de connexion soit exécuté et disponible pour que le téléchargement démarre plus rapidement.

## Résolution des problèmes liés à l’accélération des téléchargements {#troubleshoot-issues-with-download-acceleration}
Si l’accélération de téléchargement ne fonctionne pas, essayez les suggestions suivantes :
1. Vérifiez que les ports ne sont pas bloqués. Effectuez une recherche Google pour trouver les options permettant de vérifier si les ports sont bloqués, en fonction du système d’exploitation utilisé. <!-- THIS URL IS 404 AND DOES NOT REDIRECT [https://test-connect.asperasoft.com](https://test-connect.asperasoft.com/) from your computer. -->
Si les ports ne sont pas ouverts, demandez à votre équipe réseau de veiller à ce que les ports 33001 (à la fois TCP et UDP) ne soient pas bloqués dans le pare-feu.
1. Si les ports sont ouverts, vérifiez que votre réseau n’est pas trop lent en mesurant la bande passante disponible à l’aide de [https://www.speedtest.net/](https://www.speedtest.net/).
Si la bande passante est faible (1 à 10 Mbit/s) ou en Kbit/s, utilisez les Préférences Aspera et essayez de limiter la bande passante en fonction de celle disponible.
<!-- The URL in this step is giving a 404 error. 1. To confirm whether the downloads from Aspera demo server are working, use [https://demo.asperasoft.com/aspera/user](https://demo.asperasoft.com/aspera/user).
(login: asperaweb , password: demoaspera ) -->
1. Si aucune des étapes de dépannage ci-dessus ne fonctionne, désélectionnez l’option Activer l’accélération des téléchargements et utilisez le téléchargement normal.
|
/*
* Copyright 2015 Philip Gasteiger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.aau.dwaspgui.debugger.protocol.response;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import at.aau.dwaspgui.debugger.protocol.response.QueryResponseMessage;
/**
* Unit tests for {@link QueryResponseMessage}.
* @author Philip Gasteiger
*/
@RunWith(JUnit4.class)
public class QueryResponseMessageTest {
@Test
public void construct_noQueries_returnsCorrect() {
QueryResponseMessage msg = new QueryResponseMessage("query:");
assertTrue(msg.getAtoms().isEmpty());
}
@Test
public void construct_oneQuery_returnsCorrect() {
QueryResponseMessage msg = new QueryResponseMessage("query:atom1(a)");
assertEquals(Arrays.asList("atom1(a)"), msg.getAtoms());
}
@Test
public void construct_multipleQueries_returnsCorrect() {
QueryResponseMessage msg = new QueryResponseMessage("query:atom1(a):atom2:atom3(a,b,c)");
assertEquals(Arrays.asList("atom1(a)", "atom2", "atom3(a,b,c)"), msg.getAtoms());
}
}
|
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Service>
*/
class ServiceFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->words(3, true),
'image' => fake()->imageUrl(),
'content' => fake()->paragraphs(4, true),
'price' => fake()->numberBetween(0, 100),
'user_id' => fake()->numberBetween(1, 20),
'category_id' => fake()->numberBetween(1, 10)
];
}
}
|
<!DOCTYPE html>
<html lang="en">
<header>
<meta charset="UTF-8">
<title>Парный тег</title>
<link rel="stylesheet" href="../../../css/DeskBook.css">
</header>
<head>
<table width="100%" border="0" cellspacing="3" cellpadding="0">
<tr align="center">
<td>
<img align="left" src="../../../img/WebDesign/WebDesign.png"
width="200"
height="200">
<h1 align="left"> DeskBook HTML</h1>
<h2 align="left"> Справочник по тегам и атрибутам HTML</h2>
</td>
</tr>
<tr align="center">
<td>
<hr size="5" color="white">
|<a class="warn" href="../../../index.html"><b>ГЛАВНАЯ</b></a>|
<a class="warn" href="../../menu/sections&articles.html"><b>РАЗДЕЛЫ И СТАТЬИ</b></a>|
<a class="warn" href="../../menu/contacts.html"><b>КОНТАКТЫ</b></a>|
<hr size="5" color="white">
</td>
</tr>
</head>
<body>
<tr valign="top">
<td>
<h1 align="center">Парный тег</h1>
<ul type="disc">
<li><h3><u>Описание:</u></h3></li>
<p> Парные теги, называемые по-другому контейнеры, состоят из двух частей — открывающий и закрывающий тег. Открывающий тег обозначается как и одиночный — <тег>, а в закрывающем используется слэш — </тег>. Допускается вкладывать в контейнер другие теги, однако следует соблюдать их порядок. </p>
<p> Не все контейнеры требуют обязательно закрывающего тега, иногда его можно и опустить. Тем не менее, закрывайте все требуемые теги, так вы приучитесь сводить к нулю возможные ошибки. </p>
<li><h3><u>Пример:</u></h3></li>
<p> <b>Неправильное вложение тегов</b> </p>
<img src="../../../img/articles/other/Теги(не%20правильно).png"
alt="Теги(не правильно)" width="40%">
<p> <b>Правильное вложение тегов</b> </p>
<img src="../../../img/articles/other/Теги(правильно).png"
alt="Теги(правильно)" width="40%">
</td>
</tr>
</ul>
</body>
<footer>
<tr align="center">
<td>
<p align="center"><a href="#top"><b>Up!</b></a>
<hr size="5" color="white">
<div class="copyright">
<br>
© Маршалова Валерия 2017-2018г.
<br>Все права защищены.
</div>
<div align="left">
<a href="https://vk.com/leramarshalova"><img src="../../../img/contacts/vkontakte.png" width="4%"></a>
<a href="https://www.instagram.com/lerochka_marsh"><img src="../../../img/contacts/instagram.png" width="4%"></a>
<a href="https://www.facebook.com/leramarshalova"><img src="../../../img/contacts/facebook.png" width="4%"></a>
<a href="https://twitter.com/leramarshalova"><img src="../../../img/contacts/twitter.png" width="4%"></a>
<br>[email protected]
</div>
</td>
</tr>
</table>
</footer>
</html>
|
import React from "react";
import styles from "./UserDetail.module.scss";
import classNames from "classnames";
import moment from "moment";
import UserCommonBtn from "./common/UserCommonBtn";
import { useSelector } from "react-redux";
const UserDetails = ({ setStep, setTab }) => {
const { userDetails } = useSelector(state => state.login);
return (
<div className={classNames(styles.main_container, "container d-flex")}>
<div className={classNames(styles.detail_container, "container")}>
<span className={classNames(" mb-3 fw-bold", styles.fs_18)}>
Before we proceed, please check your details
</span>
<span className={classNames("mb-3 ", styles.fs_14)}>
Please notify your admin immediately if the information is not
accurate.
</span>
<div className={styles.infoSection}>
<span className={classNames("fw-bold")}>Personal Information</span>
<div className={classNames("", styles.innerSection)}>
<div>
<div className={classNames("", styles.salutation_inner)}>
Salutation
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_salutation
? userDetails?.tutor?.tut_salutation
: "-"}
</div>
</div>
<div>
<div className={classNames("", styles.salutation_inner)}>
First Name
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_fname
? userDetails?.tutor?.tut_fname
: "-"}
</div>
</div>
</div>
<div className={classNames("", styles.innerSection)}>
<div>
<div className={classNames("", styles.salutation_inner)}>
Last Name
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_surname
? userDetails?.tutor?.tut_surname
: "-"}
</div>
</div>
<div>
<div className={classNames("", styles.salutation_inner)}>
Birth Date
</div>
<div className={styles.textSecondary}>
{moment(userDetails?.tutor?.tut_dob).format("D MMM YYYY")}
</div>
</div>
</div>
</div>
<div className={styles.infoSection}>
<span>Address Information</span>
<div
className={classNames(styles.addressSection, styles.innerSection)}
>
<div>
<div className={classNames("", styles.salutation_inner)}>
Address
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_address
? userDetails?.tutor?.tut_address
: "-"}
</div>
</div>
{/* <div>
<div className={classNames("", styles.salutation_inner)}>
Country
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.country_name
? userDetails?.tutor?.country_name
: "-"}
</div>
</div> */}
</div>
<div className={classNames("", styles.innerSection)}>
<div>
<div className={classNames("", styles.salutation_inner)}>
Country
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.country_name
? userDetails?.tutor?.country_name
: "-"}
</div>
</div>
<div>
<div className={classNames("", styles.salutation_inner)}>
State
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_state
? userDetails?.tutor?.tut_state
: "-"}
</div>
</div>
</div>
<div className={classNames("", styles.innerSection)}>
<div>
<div className={classNames("", styles.salutation_inner)}>
City
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_city
? userDetails?.tutor?.tut_city
: "-"}
</div>
</div>
<div>
<div className={classNames("", styles.salutation_inner)}>
Postcode
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_zip
? userDetails?.tutor?.tut_zip
: "-"}
</div>
</div>
</div>
</div>
<div className={styles.infoSection}>
<span>Contact Information</span>
<div className={classNames("", styles.innerSection)}>
<div>
<div>Home Phone</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_home_phone
? userDetails?.tutor?.tut_home_phone
: "-"}
</div>
</div>
<div>
<div className={classNames("", styles.salutation_inner)}>
Work Phone
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_work_phone
? userDetails?.tutor?.tut_work_phone
: "-"}
</div>
</div>
</div>
<div className={classNames("", styles.innerSection)}>
<div>
<div className={classNames("", styles.salutation_inner)}>
Mobile
</div>
<div className={styles.textSecondary}>
{}
{userDetails?.tutor?.tut_mobile
? userDetails?.tutor?.tut_mobile
: "-"}
</div>
</div>
<div>
<div className={classNames("", styles.salutation_inner)}>
Email
</div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_emailid
? userDetails?.tutor?.tut_emailid
: "-"}
</div>
</div>
</div>
</div>
<div className={styles.infoSection}>
<span>About Tutor</span>
<div className={classNames("", styles.innerSection)}>
<div>
<div className={styles.textSecondary}>
{userDetails?.tutor?.tut_notes
? userDetails?.tutor?.tut_notes
: "-"}
</div>
</div>
</div>
</div>
<div className={classNames("mb-3", styles.btnDiv)}>
<UserCommonBtn
setStep={setStep}
setTab={setTab}
step={1}
btn1_text="Back"
btn2_text="Next"
isBackBtn={false}
/>
</div>
</div>
</div>
);
};
export default UserDetails;
|
% Dynamic Macroeconomics
% Author: Edinson Tolentino
% Ramsey Cass-Koopmans
% FIRST METHODS
clc;
clear all;
clear close;
% parameters
% -------------------------------------------------
alpha = 0.35;
k0 = 0.075;
beta = 0.985;
tol = 0.00001;
T = 30;
% steady stacionary
%----------------------------------
ks = (alpha*beta)^(1/(1-alpha));
x0 = ones(T,1)*0.8*ks;
param = [alpha k0 beta ks];
% iteration
%-----------------------------------
sol = secant('sys', x0, param);
time = (0:1:T-1); %% time index
figure(1)
plot(time, sol,'r-')
ylabel('Capital Stock')
xlabel('Time')
name = [fig_path '\capital_time' ];
print('-depsc', name)
% Functions
%-----------------------------------
function x = secant(sys, x0, param)
del = diag(max(abs(x0)*1e-4,1e-8));
n = length(x0);
for i=1:1000
f=feval(sys,x0, param);
for j=1:n
J(:,j)=(f-feval(sys,x0-del(:,j),param))/del(j,j);
end
x = x0-inv(J)*f';
if norm(x-x0)<0.00001
break;
end
x0 = x;
end
end
function f=sys(z,p)
a = p(1);
b = p(2);
c = p(3);
d = p(4);
f(1)=((((z(1)^a)-z(2))/((b^a)-z(1))))-a*c*(z(1)^(a-1));
for i=2:30-1
f(i)=((((z(i)^a)-z(i+1))/((z(i-1)^a)-z(i))))-a*c*(z(i)^(a-1));
end
i = 30;
f(i)=((((z(i)^a)-d)/((z(i-1)^a)-z(i))))-a*c*(z(i)^(a-1));
end
|
package by.yLab;
import static by.yLab.util.SelectionItems.*;
import by.yLab.inOut.*;
import by.yLab.util.Action;
import by.yLab.util.FormatDateTime;
import by.yLab.entity.Audit;
import by.yLab.entity.Exercise;
import by.yLab.entity.NoteDiary;
import by.yLab.entity.User;
import by.yLab.dto.ExerciseDto;
import by.yLab.dto.NoteDiaryDto;
import by.yLab.dto.UserDto;
import by.yLab.controller.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
/**
* @author Arseni Karatkou
* @version 1.1
*/
public class TrainingDiary {
private static final LoginController LOGIN_CONTROLLER = LoginController.getInstance();
private static final DiaryController DIARY_CONTROLLER = DiaryController.getInstance();
private static final ExerciseController EXERCISE_CONTROLLER = ExerciseController.getInstance();
private static final AdminController ADMIN_CONTROLLER = AdminController.getInstance();
private static User userNow;
private static DisplayedPage displayedPage = DisplayedPage.LOGIN;
/**
* @param args не используется.
* Входная точка приложения
*/
public static void main(String[] args) {
changePages();
}
/**
* Переход по логическим частям приложения
*/
private static void changePages() {
while (true) {
switch (displayedPage) {
case LOGIN -> userNow = registrationAndAuthorization();
case MENU -> selectableMenuItems();
case ADD_EXERCISE_TO_DIARY -> addExerciseToDiaryMenuItem();
case CREATE_EXERCISE -> createExerciseMenuItem();
case SHOW_DIARY -> showDiaryMenuItem();
case SHOW_DIARY_TIME_SLICE -> showDiaryTimeSliceMenuItem();
case ADMIN -> adminFunctions();
}
}
}
/**
* Вход в систему.
* Регистрация пользователя.
* Авторизация пользователя
*/
private static User registrationAndAuthorization() {
String answer;
while (true) {
LoginPage.startConversation();
answer = LoginPage.takeAnswerAboutAccount();
if (answer.equals(SHORT_AGREE) || answer.equals(AGREE)) {
Optional<User> userOptional = LOGIN_CONTROLLER.checkAccount(LoginPage.Authorization());
if (userOptional.isEmpty()) {
LoginPage.showAnswers(LOGIN_CONTROLLER.getBadAnswers());
} else {
displayedPage = DisplayedPage.MENU;
ADMIN_CONTROLLER.addAction(userOptional.get(), Action.AUTHORIZATION);
return userOptional.get();
}
} else if (answer.equals(SHORT_REFUSE) || answer.equals(REFUSE)) {
Optional<User> userOptional = LOGIN_CONTROLLER.createUser(LoginPage.Registration());
if (userOptional.isEmpty()) {
LoginPage.showAnswers(LOGIN_CONTROLLER.getBadAnswers());
} else {
displayedPage = DisplayedPage.MENU;
ADMIN_CONTROLLER.addAction(userOptional.get(), Action.REGISTRATION);
return userOptional.get();
}
} else {
LoginPage.questionYesOrNo();
}
}
}
/**
* Переход по частям приложения через основное меню по полученным от пользователя запросам
*/
private static void selectableMenuItems() {
switch (MenuOptionsPage.sayOptionsList().toLowerCase(Locale.ROOT)) {
case ADD_EXERCISE_TO_DIARY -> displayedPage = DisplayedPage.ADD_EXERCISE_TO_DIARY;
case CREATE_EXERCISE -> displayedPage = DisplayedPage.CREATE_EXERCISE;
case SHOW_DIARY -> displayedPage = DisplayedPage.SHOW_DIARY;
case ADMIN -> displayedPage = DisplayedPage.ADMIN;
case EXIT -> displayedPage = DisplayedPage.LOGIN;
default -> MenuOptionsPage.nonMenuMessage();
}
}
/**
* Пункт основного меню.
* Добавление актуальной тренировки в дневник.
* Сохранение в текущем моменте времени с указанием количества единиц выполнения
*
* @see TrainingDiary#changePages()
*/
private static void addExerciseToDiaryMenuItem() {
Set<Exercise> userExercises = EXERCISE_CONTROLLER.getUserExercises(userNow);
Optional<NoteDiaryDto> noteExerciseInDiaryDto = AddExerciseInDiaryPage.addExerciseInDiary(userExercises);
if (noteExerciseInDiaryDto.isPresent()) {
Optional<Exercise> exerciseOptional =
EXERCISE_CONTROLLER.getExerciseToName(userNow, noteExerciseInDiaryDto.get().getExerciseName());
if (exerciseOptional.isPresent()) {
DIARY_CONTROLLER.addExercise(userNow,
exerciseOptional.get(),
noteExerciseInDiaryDto.get().getTimesCount());
ADMIN_CONTROLLER.addAction(userNow, Action.WRITE_DIARY_NOTE);
AddExerciseInDiaryPage.agreeMessage();
} else {
ADMIN_CONTROLLER.addAction(userNow, Action.TRY_WRITE_DIARY_NOTE);
AddExerciseInDiaryPage.refuseEmptyExercisesMessage();
}
}
displayedPage = DisplayedPage.MENU;
}
/**
* Пункт основного меню.
* Создание нового типа тренировки, расширение перечня типов тренировок.
* Включает в себя название тренировки и ее энергозатратность в единицу выполнения
*
* @see TrainingDiary#changePages()
*/
private static void createExerciseMenuItem() {
ExerciseDto exerciseDto = CreateExercisePage.createExercise();
Exercise exercise = new Exercise(exerciseDto.getExerciseName(), exerciseDto.getCaloriesBurnInHour());
boolean isExerciseNew = EXERCISE_CONTROLLER.isExerciseNew(userNow, exercise);
EXERCISE_CONTROLLER.createExercise(userNow,
exerciseDto.getExerciseName(),
exerciseDto.getCaloriesBurnInHour());
if (isExerciseNew) {
CreateExercisePage.exerciseCreated(exercise);
ADMIN_CONTROLLER.addAction(userNow, Action.WRITE_DIARY_NOTE);
} else {
CreateExercisePage.exerciseUpdated(exercise);
ADMIN_CONTROLLER.addAction(userNow, Action.UPDATE_EXERCISE);
}
displayedPage = DisplayedPage.MENU;
}
/**
* Пункт основного меню.
* Просмотр тренировок за текущие сутки.
* Вывод суммы сожженных калорий за текущие сутки.
*
* @see TrainingDiary#changePages()
*/
private static void showDiaryMenuItem() {
List<NoteDiary> todayNote = DIARY_CONTROLLER.getLastDay(userNow);
int burnCalories = DIARY_CONTROLLER.getBurnCalories(todayNote);
String answer = ShowDiaryPage.showDiary(todayNote, burnCalories);
ADMIN_CONTROLLER.addAction(userNow, Action.SEE_TODAY_DIARY);
if (answer.equalsIgnoreCase(SHORT_AGREE) || answer.equalsIgnoreCase(AGREE)) {
displayedPage = DisplayedPage.SHOW_DIARY_TIME_SLICE;
} else {
displayedPage = DisplayedPage.MENU;
}
}
/**
* Подпункт просмотра тренировок
* Просмотр тренировок в прошедший промежуток времени отсортированные по дате.
* Реализация возможности получения статистики по тренировкам выводя количество потраченных калорий в конце списка
* Если заданный промежуток времени выходит за рамки пребывания в системе, он ограничивается этими рамками
*
* @see TrainingDiary#showDiaryMenuItem()
*/
private static void showDiaryTimeSliceMenuItem() {
List<NoteDiary> diaryTimeSlice =
DIARY_CONTROLLER.getDiaryTimeSlice(ShowDiaryTimeSlicePage.askTimeSlice(), userNow);
int burnCalories = DIARY_CONTROLLER.getBurnCalories(diaryTimeSlice);
ShowDiaryTimeSlicePage.showTrainingDays(diaryTimeSlice, burnCalories);
ADMIN_CONTROLLER.addAction(userNow, Action.SEE_BEFORE_DIARY);
String answer = ShowDiaryTimeSlicePage.diaryMenu();
switch (answer) {
case ADD -> addMissingExerciseDairy();
case DELETE -> deleteExerciseDairy();
default -> displayedPage = DisplayedPage.MENU;
}
}
/**
* Подпункт правок тренировок в прошедшем промежутке времени
* Добавление неактуальной тренировки в дневник
*
* @see TrainingDiary#showDiaryTimeSliceMenuItem()
*/
private static void addMissingExerciseDairy() {
LocalDateTime exerciseTime = LocalDateTime.parse(ShowDiaryTimeSlicePage.askDate(), FormatDateTime.reformDateTime());
Set<Exercise> userExercises = EXERCISE_CONTROLLER.getUserExercises(userNow);
Optional<NoteDiaryDto> noteExerciseInDiaryDto = AddExerciseInDiaryPage.addExerciseInDiary(userExercises);
if (noteExerciseInDiaryDto.isPresent()) {
Optional<Exercise> exerciseOptional =
EXERCISE_CONTROLLER.getExerciseToName(userNow, noteExerciseInDiaryDto.get().getExerciseName());
if (exerciseOptional.isPresent()) {
DIARY_CONTROLLER.addMissingExercise(userNow,
exerciseOptional.get(),
noteExerciseInDiaryDto.get().getTimesCount(),
exerciseTime);
AddExerciseInDiaryPage.agreeMessage();
ADMIN_CONTROLLER.addAction(userNow, Action.UPDATE_BEFORE_DIARY_NOTE);
} else {
ADMIN_CONTROLLER.addAction(userNow, Action.TRY_UPDATE_BEFORE_DIARY_NOTE);
AddExerciseInDiaryPage.refuseNoSuchExerciseMessage();
}
} else {
AddExerciseInDiaryPage.refuseEmptyExercisesMessage();
ADMIN_CONTROLLER.addAction(userNow, Action.TRY_UPDATE_BEFORE_DIARY_NOTE);
}
displayedPage = DisplayedPage.MENU;
}
/**
* Подпункт правок тренировок в прошедшем промежутке времени.
* Удаление неактуальной тренировки из дневника.
*
* @see TrainingDiary#showDiaryTimeSliceMenuItem()
*/
private static void deleteExerciseDairy() {
LocalDateTime exerciseDate = LocalDateTime.parse(ShowDiaryTimeSlicePage.askDate(), FormatDateTime.reformDateTime());
Set<Exercise> userExercises = EXERCISE_CONTROLLER.getUserExercises(userNow);
Optional<String> stringOptional = ShowDiaryTimeSlicePage.selectExerciseToDelete(userExercises);
if (stringOptional.isPresent()) {
Optional<Exercise> exerciseOptional =
EXERCISE_CONTROLLER.getExerciseToName(userNow, stringOptional.get());
if (exerciseOptional.isPresent() && DIARY_CONTROLLER
.isExerciseInDiary(userNow, exerciseOptional.get(), exerciseDate)) {
DIARY_CONTROLLER.deleteExercise(userNow,
exerciseOptional.get(), exerciseDate.toLocalDate());
ShowDiaryTimeSlicePage.agreeMessage();
ADMIN_CONTROLLER.addAction(userNow, Action.DELETE_DIARY_NOTE);
} else {
ADMIN_CONTROLLER.addAction(userNow, Action.TRY_DELETE_DIARY_NOTE);
ShowDiaryTimeSlicePage.refuseMessage();
}
}
displayedPage = DisplayedPage.MENU;
}
/**
* Пункт основного меню.
* Доступ пользователю к возможностям администратора через пароль.
* Реализация контроля прав пользователя
*/
private static void adminFunctions() {
if (ADMIN_CONTROLLER.checkPassword(AdminPage.askAdminPassword())) {
String answer = AdminPage.showAllUsers(userNow, ADMIN_CONTROLLER.getAllUsers());
switch (answer) {
case SHOW_USERS_DATA -> showUserFromAdmin();
case DELETE_USER -> deleteUserFromAdmin();
case SHOW_AUDIT_USER_FILES -> showUserAudit();
case EXIT -> displayedPage = DisplayedPage.MENU;
}
} else {
AdminPage.refuseAnswer();
displayedPage = DisplayedPage.MENU;
}
}
/**
* Подпункт возможностей администратора
* Просмотр списка всех пользователей со списками их тренировок
*
* @see TrainingDiary#adminFunctions()
*/
private static void showUserFromAdmin() {
UserDto userDto = AdminPage.getUserDto();
Optional<User> userOptional = ADMIN_CONTROLLER.getUser(userDto.getLastName(), userDto.getEmail());
if (userOptional.isPresent()) {
User user = userOptional.get();
String registrationDate = user.getRegistrationDate().format(FormatDateTime.reformDate());
String timeSlice = registrationDate + REGEX + LocalDate.now().format(FormatDateTime.reformDate());
List<NoteDiary> diaryTimeSlice = DIARY_CONTROLLER.getDiaryTimeSlice(timeSlice, user);
AdminPage.showUser(user, diaryTimeSlice);
} else {
AdminPage.noFindUserAnswer();
}
}
/**
* Подпункт возможностей администратора
* Просмотр списка всех действий пользователя приложения
*
* @see TrainingDiary#adminFunctions()
*/
private static void showUserAudit() {
UserDto userDto = AdminPage.getUserDto();
Optional<User> userOptional = ADMIN_CONTROLLER.getUser(userDto.getLastName(), userDto.getEmail());
if (userOptional.isPresent()) {
User user = userOptional.get();
List<Audit> auditUser = ADMIN_CONTROLLER.getAuditUser(user);
AdminPage.showUserAudit(user, auditUser);
} else {
AdminPage.noFindUserAnswer();
}
}
/**
* Подпункт возможностей администратора
* Удаление из списка всех пользователей
*
* @see TrainingDiary#adminFunctions()
*/
private static void deleteUserFromAdmin() {
UserDto userDto = AdminPage.getUserDto();
Optional<User> userOptional = ADMIN_CONTROLLER.getUser(userDto.getLastName(), userDto.getEmail());
userOptional.ifPresentOrElse(ADMIN_CONTROLLER::deleteUser, AdminPage::noFindUserAnswer);
}
}
|
import tkinter as tk
import nltk
from nltk import bigrams, FreqDist
from nltk.probability import ConditionalFreqDist
import os
from tkinter import ttk
from nltk.tokenize import word_tokenize
import re
import numbers
import Levenshtein
from tkinter import scrolledtext
import string
root = tk.Tk()
file_path = "C:/....../english_words_479k.txt"
file = open(file_path, 'r', encoding='utf-8', errors='ignore')
word_list = set()
for x in file:
# here we got to tokenize and preprocessing the word dictionary
tokens = word_tokenize(x)
normalized_tokens = [token.lower() for token in tokens if re.match('^[a-zA-Z\']+$|[.,;]$', token)]
word_list.update(normalized_tokens)
# Check is there any numerical value inside
list2 = [x for x in word_list if isinstance(x, numbers.Number)]
train_folder_path = 'C:/....../Corpus'
train_file_path = []
bigrams_list = []
for train_file in os.listdir(train_folder_path):
if os.path.isfile(os.path.join(train_folder_path, train_file)):
file_path = os.path.join(train_folder_path, train_file).replace('\\', '/')
train_file_path.append(file_path)
word_list_2 = set() # used to store those word that are not in the word dictionary before
for file_path in train_file_path:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
training_file = file.read()
word_tokens = word_tokenize(training_file)
word_normalized_token = [token.lower() for token in word_tokens if re.match('^[a-zA-Z\']+$|[.,;]$', token)]
# print(word_normalized_token)
word_list_2.update(word_normalized_token)
bigrams_list.extend(list(bigrams(word_normalized_token)))
own_dict_bigrams = list(bigrams(word_list))
bigrams_list.extend(own_dict_bigrams)
word_list.update(word_list_2)
bigrams_freq = ConditionalFreqDist(bigrams_list)
freq_dist = FreqDist(bigrams_list)
# remove punctuation for word searching
word_list_exclude_punc = [char for char in word_list if char not in string.punctuation]
contains_punctuation = any(char in string.punctuation for char in word_list_exclude_punc)
if contains_punctuation:
print("The list contains punctuation.")
else:
print("The list does not contain punctuation.")
class SpellingChecker():
def OtherTextWidget(self, string):
print("Key Press Phase:", string)
# Solution - Step 1. toggle full flag
global full # (update)
full = False
# Solution - Step 4. profit
def AfterRestrict(self, e=None): # (update)
global full
if True == full:
self.OtherTextWidget(e.widget.get("1.0", "1.5"))
print("Key Release Phase:", e.widget.get("1.0", "1.5"))
# Solution - Step 3. limit input
def Restrict(self, e=None):
global full # (update)
string = e.widget.get("1.0", "end-1c")
if 499 <= len(string):
e.widget.delete('1.499', "end-1c")
full = True # (update)
else: # (update)
full = False
# Here we update for chac count and word count and also restrict the char limit
def update_char_count(self, e=None):
current_text = self.input_text_widget.get("1.0", "end-1c")
current_text_char = current_text.replace(' ', '').replace('\n', '')
self.char_count.set(f"Character Count: {len(current_text_char)}/500")
tokens = re.split(r'\s+', current_text)
non_empty_words = [token for token in tokens if token] # Count non-empty tokens
self.word_count.set(f"Word Count: {len(non_empty_words)}")
# Here we use to restrict those use copy and paste that more than 500 word
global full # (update)
string = e.widget.get("1.0", "end-1c")
if 499 <= len(string):
e.widget.delete('1.500', "end-1c")
full = True # (update)
else: # (update)
full = False
# Bigram the input text
user_input_bigram = []
# use to store the found word and store where it is placed in the user input.
result_dict = {}
# use to store those real word error (which mean spelling correct but bigram wrong)
real_word_list = []
# use for label the real word
real_word_label = {}
# use to store spelling error in list
non_real_word_list = []
# use for label the real word
non_real_word_label = {}
# use to save the word and position of clicked word
clicked_word_list = []
def transfer_text(self):
# here use to clear out the list and dictionary
self.user_input_bigram = []
self.result_dict = {}
self.real_word_list = []
self.non_real_word_list = []
self.real_word_label = {}
self.non_real_word_label = {}
# inside here using bigram to find the probability
input_text = self.input_text_widget.get("1.0", "end-1c") # to get whole sentence from input
split_input_text = nltk.tokenize.word_tokenize(input_text.lower()) # split sentences into one by one
user_input_first_word_with_pos = [split_input_text[0], 0]
if split_input_text[0] not in word_list:
self.non_real_word_list.append(user_input_first_word_with_pos)
user_input_tokens = word_tokenize(input_text)
user_input_normalized_token = [token.lower() for token in user_input_tokens if
re.match('^[a-zA-Z\']+$|[.,;]$', token)]
self.user_input_bigram.extend(list(
bigrams(user_input_normalized_token))) # until here we got a list that contain the bigram of user input
# here is where we used to identify the real word or non-real word error
for bigram_element in self.user_input_bigram:
if bigram_element in bigrams_list:
found = True
# here is where we found same bigram from user input in the trained bigram list
pass
else:
# here is if not found in the bigram list, now we need to determine in real word err or non real word err
bigram_index = self.user_input_bigram.index(
bigram_element) # this is use to find which bigram index in the user input
# print(bigram_element, " It is not found. The index of bigram is ", bigram_index)
bigram_second_word = bigram_element[1]
second_word_index = bigram_index + 1
# here we use to save the first word and second word for each bigram and to know the place of the word in user input
for index, (first_word, second_word) in enumerate(self.user_input_bigram, start=1):
self.result_dict[index - 1] = {
'first word': first_word,
'second word': second_word
}
# bigram second word with their position
# this same clickable text with index
bigram_second_word_with_pos = [bigram_second_word, second_word_index]
print('This is the first word: ', split_input_text[0])
# save the word into either real word or non_real word
if bigram_second_word in word_list:
self.real_word_list.append(bigram_second_word_with_pos)
else:
self.non_real_word_list.append(bigram_second_word_with_pos)
if not self.non_real_word_list:
print(" ")
else:
for item in split_input_text:
non_real_word_list_only_word = [item[0] for item in self.non_real_word_list]
non_real_word_list_with_position = [item[1] for item in self.non_real_word_list]
user_input_word_index = split_input_text.index(item) # to get the index of word of the user input
if user_input_word_index in non_real_word_list_with_position:
pointed_word = split_input_text[user_input_word_index]
start_char_index = input_text.find(item)
end_char_index = start_char_index + len(pointed_word) - 1
word_index = f"{user_input_word_index}"
self.non_real_word_label.setdefault(pointed_word, {})[word_index] = (
start_char_index, end_char_index
)
if not self.real_word_list:
print(" ")
else:
for item in split_input_text:
real_word_list_only_word = [item[0] for item in self.real_word_list]
real_word_list_with_position = [item[1] for item in self.real_word_list]
user_input_word_index = split_input_text.index(item) # to get the index of word of the user input
if user_input_word_index in real_word_list_with_position:
pointed_word = split_input_text[user_input_word_index]
start_char_index = input_text.find(item)
end_char_index = start_char_index + len(pointed_word) - 1
word_index = f"{user_input_word_index}"
self.real_word_label.setdefault(pointed_word, {})[word_index] = (
start_char_index, end_char_index
)
self.output_text_widget.config(state=tk.NORMAL) # here is to insert into the output textbox
self.output_text_widget.delete("1.0", "end")
# use to highlight the non real word error in red
for word, indices in self.non_real_word_label.items():
for category, (start, end) in indices.items():
self.output_text_widget.insert(tk.END, input_text[:start]) # Add text before the word
self.output_text_widget.insert(tk.END, input_text[start:end + 1]) # Add the word
self.output_text_widget.tag_add("red_bg", f"1.{start}", f"1.{end + 1}") # Highlight with red background
input_text = input_text[end + 1:] # Remove processed part from input text
# use to highlight the non real word error in blue
for word, indices in self.real_word_label.items():
for category, (start, end) in indices.items():
self.output_text_widget.insert(tk.END, input_text[:start]) # Add text before the word
self.output_text_widget.insert(tk.END, input_text[start:end + 1]) # Add the word
self.output_text_widget.tag_add("blue_bg", f"1.{start}",
f"1.{end + 1}") # Highlight with blue background
input_text = input_text[end + 1:]
self.output_text_widget.insert(tk.END, input_text) # Add the remaining text after the highlighted range
self.output_text_widget.config(state=tk.DISABLED) # Disable editing of output textbox
def on_click(self, event):
# Get the clicked word
self.clicked_word_list = []
start_index = event.widget.index("current wordstart")
# this is purposely use for extarct word because .get() will not include the last character hence we need to add 1 to it
end_index_word_extract = event.widget.index("current wordend")
# Exclude the trailing whitespace by adjusting the end index
end_index = event.widget.index("current wordend-1c")
extracted_text = self.output_text_widget.get(start_index, end_index_word_extract)
index = self.output_text_widget.index("current wordend")
first_word_until_clicked = self.output_text_widget.get("1.0", index)
# assumption: we include the punctuation in word predicting for better model structure but during the suggestion, we will exclude the punctuation for better word structure
first_word_until_clicked_split = nltk.tokenize.word_tokenize(first_word_until_clicked)
# this is used to find the word index of the clicked word
word_index = len(first_word_until_clicked_split) - 1
# this is used to get the last word index to prevent any error when click the last word
input_text = self.input_text_widget.get("1.0", "end-1c") # to get whole sentence from input
split_input_text = nltk.tokenize.word_tokenize(input_text.lower()) # split sentences into one by one
# purpose for this list is used to check whether the word we click exist in real word list or not
word_list_verified_used = [extracted_text, word_index]
print(word_list_verified_used)
# purpose for this list is used to save the clicked word into a list actually can use this 'word_list_verified_used' list also,
# we may change word_list_verified_used to this name
self.clicked_word_list = [extracted_text, word_index]
if word_list_verified_used in self.real_word_list:
if len(first_word_until_clicked_split) >= 2:
# to get the previous word from the word we clicked (purposely used for real word error suggestion)
previous_word_clicked = first_word_until_clicked_split[-2]
# here we do real word check
# here we need to do the condition check whether the word is exist in the real word list or not
if word_index == 0:
self.tree.delete(*self.tree.get_children())
print("")
else:
print(word_index)
self.check_real_words(previous_word_clicked)
# here we do non real word check
if word_list_verified_used in self.non_real_word_list:
self.check_non_real_word(extracted_text)
# Display the word index at the bottom
self.bottom_label.config(text=f"Start Index: {start_index}, End Index: {end_index}")
def calculate_edit_distance(self, misspelled_word):
# if not same as predicted word and spell is not in dict, then it is non-real word, then use min edit dist
# next we are going to do this and solve how to check the error word when there is only one word is enter
# (by adding the first word from user input into non_real_word_list)
# the procedure is almost the same as what we done in real word error
distances = [(word, Levenshtein.distance(misspelled_word, word)) for word in word_list]
# Sort words based on edit distance in ascending order
sorted_distances = sorted(distances, key=lambda x: x[1])
# Select top 5 predictions along with their distances
top_predictions = sorted_distances[:5]
return top_predictions
def check_non_real_word(self, non_real_word):
# Get predictions for a list of words
predictions = self.calculate_edit_distance(non_real_word)
print(predictions)
print(f"Misspelled word: {non_real_word}")
print(f"Top 5 suggestions:")
for suggestion, distance in predictions:
print(f"- {suggestion} (Edit Distance: {distance})")
print()
self.process_tuple_list(predictions)
def check_real_words(self, real_word):
# here we used not same as the predicted word but spell is correct, then it is real word error
candidate_bigrams = [bigram for bigram in bigrams_list if bigram[0] == real_word]
# print(candidate_bigrams)
total_bigrams = len(candidate_bigrams)
predicted_bigrams_probs = []
for bigram in candidate_bigrams:
word, probability = bigram[1], freq_dist[bigram] / total_bigrams
is_word_found = any(word_going_to_found == word for word_going_to_found, _ in predicted_bigrams_probs)
if is_word_found:
pass
else:
predicted_bigrams_probs.append((word, probability))
# Sort the candidate bigrams by probability in descending order
sorted_predictions = sorted(predicted_bigrams_probs, key=lambda x: x[1], reverse=True)
# Select the top 5 predicted words
top_5_predictions = sorted_predictions[:5]
for word, probability in top_5_predictions:
print("")
print(f"Word: {word}, Probability: {probability:.4f}")
self.process_tuple_list(top_5_predictions)
def process_tuple_list(self, tuple_list):
self.tree.delete(*self.tree.get_children())
for item in tuple_list:
word, value = item # Unpack the tuple into word and value
self.tree.insert('', 'end', values=(word, value))
def update_input_text(self, event):
selected_item = self.tree.item(self.tree.selection())
selected_word = selected_item['values'][0]
current_text = self.input_text_widget.get("1.0", "end-1c")
words = nltk.tokenize.word_tokenize(current_text)
print(self.clicked_word_list)
clicked_index = self.clicked_word_list[1]
if len(words) >= 2:
words[clicked_index] = selected_word
updated_text = ' '.join(words)
self.input_text_widget.delete("1.0", "end-1c")
self.input_text_widget.insert("1.0", updated_text)
# This is for search window update
def update_list(self, event):
user_input = self.entry.get().lower()
filtered_list = [word for word in word_list_exclude_punc if user_input in word.lower()]
filtered_list.sort()
self.text.delete(1.0, tk.END)
for word in filtered_list:
self.text.insert(tk.END, word + '\n')
def __init__(self, root):
super().__init__()
self.root = root
self.root.geometry("1200x600")
# This is for input window
self.input_text_widget = tk.Text(self.root, height=5, width=30)
self.input_text_widget.grid(row=0, column=0, padx=10, pady=10)
# This is the check button
self.transfer_button = tk.Button(self.root, text="Check Spelling", command=self.transfer_text)
self.transfer_button.grid(row=0, column=1, padx=10, pady=10)
# This is for output window
self.output_text_widget = tk.Text(self.root, height=5, width=30, state=tk.DISABLED)
self.output_text_widget.grid(row=0, column=2, padx=10, pady=10)
self.output_text_widget.tag_configure("red_bg", background="light coral") # Configure tag for red background
self.output_text_widget.tag_configure("blue_bg", background="light blue") # Configure tag for blue
# This is for suggestion window
self.tree = ttk.Treeview(root, columns=("Word", "Value"), show="headings")
self.tree.heading("Word", text="Word")
self.tree.heading("Value", text="Value")
self.tree.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
# This is for searching window
self.entry_label = tk.Label(root, text="Enter a word:")
self.entry_label.grid(row=5, column=0, padx=10, pady=10)
self.entry = tk.Entry(root, width=30)
self.entry.grid(row=5, column=1, padx=10, pady=10)
self.text = scrolledtext.ScrolledText(root, width=40, height=10)
self.text.grid(row=6, column=0, columnspan=3, padx=10, pady=10)
# This is for show char and word index
self.bottom_label = tk.Label(root, text="Start Index: , End Index: ")
self.bottom_label.grid(row=1, column=4, padx=10, pady=10)
self.char_count = tk.StringVar()
self.char_count.set("Character Count: 0/500")
self.word_count = tk.StringVar()
self.word_count.set("Word Count: 0")
self.char_count_label = tk.Label(root, textvariable=self.char_count)
self.char_count_label.grid(row=1, column=2, padx=10, pady=10)
self.word_count_label = tk.Label(root, textvariable=self.word_count)
self.word_count_label.grid(row=1, column=3, padx=10, pady=10)
# This is used to bind the event
self.input_text_widget.bind('<Key>', self.Restrict)
self.input_text_widget.bind('<KeyRelease>', self.AfterRestrict) # (update)
self.input_text_widget.bind('<KeyRelease>', self.update_char_count)
self.output_text_widget.bind("<ButtonRelease-1>", self.on_click)
self.tree.bind("<ButtonRelease-1>", self.update_input_text)
self.entry.bind('<KeyRelease>', self.update_list)
root.mainloop()
if __name__ == "__main__":
program = SpellingChecker(root)
|
import axios from 'axios';
import firebase from 'firebase';
import inquirer from 'inquirer';
import { log } from '../../utils';
import {
AUTH_SITE_ID,
FB_DATABASE_URL,
FB_WEB_API_KEY,
} from '../config';
import readUserConfig from '../helpers/readUserConfig';
import saveUserConfig from '../helpers/saveUserConfig';
const fb = firebase.initializeApp({
apiKey: FB_WEB_API_KEY,
databaseURL: FB_DATABASE_URL,
}, 'dobi-auth-client');
const loginEmail = async () => {
// prompt
const { email, password } = await inquirer.prompt([{
message: 'Enter your email',
name: 'email',
type: 'input',
}, {
message: 'Enter your password',
name: 'password',
type: 'password',
}]);
let user;
try {
const url = 'https://api.maestro.io/auth/v1/login/maestro';
const { data } = await axios.post(url, {
email,
firebase: 'lessthan3',
password,
site_id: AUTH_SITE_ID,
});
user = data;
} catch ({ response }) {
throw new Error(`${response.status} - ${response.data}`);
}
const { custom_token: customToken, token } = user;
if (!customToken) {
throw new Error('invalid response from server');
}
await fb.auth().signInWithCustomToken(customToken);
const idTokenResult = await fb.auth().currentUser.getIdTokenResult();
const { refreshToken } = fb.auth().currentUser;
return {
idTokenResult, refreshToken, token, user,
};
};
const loginRefreshToken = async ({ refreshToken }) => {
if (!refreshToken) {
throw new Error('invalid refresh token');
}
let user;
try {
const url = 'https://api.maestro.io/auth/v1/login/refresh-token';
const { data } = await axios.post(url, {
firebase: 'lessthan3',
refresh_token: refreshToken,
site_id: AUTH_SITE_ID,
});
user = data;
} catch ({ response }) {
throw new Error(`${response.status} - ${response.data}`);
}
const { custom_token: customToken, token } = user;
if (!customToken) {
throw new Error('invalid response from server');
}
await fb.auth().signInWithCustomToken(customToken);
const idTokenResult = await fb.auth().currentUser.getIdTokenResult();
return {
idTokenResult, refreshToken, token, user,
};
};
/**
* @param {boolean} [requireLoggedIn=false]
*/
export default async (requireLoggedIn = true) => {
const userConfig = await readUserConfig();
let { refreshToken, token } = userConfig;
if (!requireLoggedIn && !refreshToken) {
return { user: null };
}
let idTokenResult;
let user;
if (refreshToken && token) {
({
idTokenResult, refreshToken, token, user,
} = await loginRefreshToken({ refreshToken }));
} else if (requireLoggedIn) {
log('not logged in - must authenticate');
({
idTokenResult, refreshToken, token, user,
} = await loginEmail());
}
const newUserConfig = saveUserConfig({
idTokenResult,
refreshToken,
token,
user,
});
log('you are now logged in.');
return newUserConfig;
};
|
import { Sprite } from '@pixi/sprite';
import i18n from '../../config/i18n';
import { Button } from '../basic/Button';
import { Window as BasicWindow } from '../basic/Window';
import { game } from '../../Game';
import { GameScreen, GameTypes } from '../../screens/GameScreen';
import { LayoutOptions } from '@pixi/layout';
import { gitHubURL } from '../../config';
/** Game menu component. */
export class PauseWindow extends BasicWindow
{
constructor()
{ // pass the ViewController to the constructor to be able to control the views
// give config differences to the Window base component
super({ // Window constructor accepts an object with all the config
title: i18n.titleScreen.menu.title, // menu title text
styles: { // styles is an object with all the styles that will be applied to the window
background: Sprite.from('MenuWindow'), // menu window background
maxHeight: '80%', // set max height to 80% of parent, so it will scale down to fit the screen height on canvas resize
maxWidth: '95%', // set max width to 95% of parent, so it will scale down to fit the screen width on canvas resize
},
ribbonStyles: { // ribbonStyles is an object with all the styles that will be applied to the ribbon layout
marginTop: -27, // move the ribbon 27px up from the top of the parent
scale: 0.7 // scale the ribbon sprite to 70% of it's original size
}
});
}
/** Create content of the component. Automatically called by extended class (see Window.ts). */
override createContent()
{
const menuButtons: {
[name: string]: LayoutOptions;
} = {}; // create an array to store menu buttons
const items: { [name: string]: string } = i18n.titleScreen.menu.items;
for (const gameType in items)
{
const text = items[gameType]; // get the text for the button from the i18n file
menuButtons[gameType] = { // levels is the id of the button
content: new Button( // create a levels window navigational button
text, // button text
() => this.selectMenuItem(gameType as GameTypes), // button click callback
), // content is the button component
styles: { // styles is an object with all the styles that will be applied to the button
marginTop: 10, // move the button 10px down from the neighbour buttons
}
};
}
this.addContent({ // add the buttons to the window layout system
menu: { // menu is the id of the layout
content: menuButtons, // content is an array of all the components that will be added to the layoutSystem
styles: { // styles is an object with all the styles that will be applied to the layout
position: 'centerTop', // center the layout in the middle of the parent
marginTop: 120, // move the layout 120px down from the top of the parent
width: '66%', // set width to 66% of parent, so children will be able to use 66% of the screen width
}
}
});
}
/**
* Select menu item.
* @param gameType
*/
private selectMenuItem(gameType: GameTypes | 'repo')
{
switch (gameType)
{
case 'repo':
(window as any).open(gitHubURL, '_blank').focus();
break;
default:
game.showScreen(GameScreen, { // show the game screen
type: gameType, // pass the level type to the game screen
});
}
}
}
|
import React, { useState, useEffect, useRef } from "react";
// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";
// core components
import GridItem from "../../components/Grid/GridItem.js";
import GridContainer from "../../components/Grid/GridContainer.js";
// import Card1 from "../../components/Card/Card.js";
import { UPDATE_LOADING } from "../../actions/types";
import { useAlert } from "react-alert";
import { APP_ERROR_MSGS, BASE_URL } from "../../common/constants";
import { useDispatch } from "react-redux";
import { useHistory, useParams } from "react-router-dom";
import { videoCallRecordsList } from "../../actions/common";
// import Card from '@material-ui/core/Card';
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";
import Avatar from "@material-ui/core/Avatar";
// import CardHeader from "@material-ui/core/CardHeader";
import Card from "../../components/Card/Card.js";
import CardHeader from "../../components/Card/CardHeader.js";
import Table from "../../common/tableRendrer";
import CardBody from "../../components/Card/CardBody.js";
import moment from "moment";
import Dialog from "../../components/Modals/ErrorModal";
import FormGroup from "@material-ui/core/FormGroup";
import { scrollToDiv } from "../../common/commonMethods";
const styles = {
root: {
minWidth: 275,
paddingTop: 15,
marginTop: 15,
marginBottom: 5,
paddingBottom: 5,
},
bullet: {
display: "inline-block",
margin: "0 2px",
transform: "scale(0.8)",
},
title: {
fontSize: 14,
},
pos: {
marginLeft: 55,
},
};
const useStyles = makeStyles(styles);
export default function CallRecordsTable() {
// Hooks
const classes = useStyles();
const alert = useAlert();
const dispatch = useDispatch();
const history = useHistory();
const [search, setSearch] = useState(history.location.state?.backRedirection?.search ?? "");
const [modalProps, setModalProps] = useState({
open: false,
title: "",
message: "",
});
// state
const [tableProps, setTableProps] = useState({
data: [],
page: 1,
sizePerPage: 20,
totalSize: 0,
loading: false,
sortName: "",
sortOrder: "",
});
const handleTableChange = (type, newState) => {
if (type == "sort") {
let sortOrder =
newState.sortField == tableProps.sortName
? tableProps.sortOrder == "" || tableProps.sortOrder == "asc"
? "desc"
: "asc"
: "desc";
setTableProps({
...tableProps,
page: 1,
sortName: newState.sortField,
sortOrder: sortOrder,
});
} else if (type == "pagination") {
setTableProps({
...tableProps,
page: newState.page,
sizePerPage: newState.sizePerPage,
});
}
};
const getCallRecordsAgora = (bookingId = "") => {
setTableProps({ ...tableProps, loading: true, data: [] });
let paramString = ``;
if (bookingId && bookingId != "") {
paramString = `?bookingId=${bookingId}`;
}
// dispatch({ type: UPDATE_LOADING, payload: true });
videoCallRecordsList(paramString)
.then((result) => {
setTableProps({ ...tableProps, loading: false });
// dispatch({ type: UPDATE_LOADING, payload: false });
if (result.data.status === true) {
// Populate Table
setTableProps({
...tableProps,
data: result.data.data ? result.data.data : [],
totalSize: result.data.data ? result.data.totalCount : 0,
loading: false,
});
// setTableProps({ ...tableProps, data: [] });
// setTimeout(() => {
// setTableProps({
// ...tableProps,
// data: result.data.data ? result.data.data : [],
// totalSize: result.data.data ? result.data.totalCount : 0,
// });
// }, 30);
} else {
setTableProps({ ...tableProps, loading: false });
alert.error(
result.data.message
? result.data.message
: APP_ERROR_MSGS.StandardErrorMsg
);
}
})
.catch((error) => {
setTableProps({ ...tableProps, loading: false });
// dispatch({ type: UPDATE_LOADING, payload: false });
alert.error(
error?.response?.data?.error
? error?.response?.data?.error
: APP_ERROR_MSGS.StandardErrorMsg
);
});
};
const onSearch = (value) => {
setSearch(value);
// getCallRecordsAgora(value);
// if (value.length > 4) {
// getCallRecordsAgora(value);
// }
// if (value.length == 0) {
// getCallRecordsAgora();
// }
};
const showBooking = (id) => {
let state ={
redirectToURL: `/admin/call-records`,
data: { search },
search: ""
}
let pathName = `/admin/booking/${id}`
history.push({
pathname: pathName,
state: { backRedirection: state }
})
// history.push("/admin/booking/" + id);
};
useEffect(() => {
getCallRecordsAgora(search);
}, [
tableProps.page,
tableProps.sizePerPage,
tableProps.sortName,
tableProps.sortOrder,
search
]);
useEffect(() => {
scrollToDiv("callRecords-list-container");
}, [tableProps.page, tableProps.sizePerPage]);
// const showModal = (msg) => {
// setModalProps({
// ...modalProps,
// open: true,
// title: "Comments",
// message: msg,
// })
// }
const rowEvents = {
onDoubleClick: (e, row, rowIndex) => {
showBooking(row?.booking._id);
},
};
const CellMenu = (cell, row) => {
return (
<>
<button
data-toggle="tooltip"
title="View"
className="pd-setting-ed"
onClick={() => showBooking(row?.booking._id)}
>
<i className="fa fa-eye" aria-hidden="true"></i>
</button>
</>
);
};
const columns = [
{
dataField: "i",
text: "Booking Id",
formatter: (cell, row) => {
return <>{row.booking?.bookingId}</>;
},
csvFormatter: (cell, row, rowIndex) => row.booking?.bookingId,
},
{
dataField: "uname",
text: "Booking Person",
formatter: (cell, row) => {
return (
<>
{row.booking?.user.role == "user"
? row.booking?.user.fullName
: row.booking?.user.professionalName}
</>
);
},
csvFormatter: (cell, row, rowIndex) =>
row.booking?.user.role == "user"
? row.booking?.user.fullName
: row.booking?.user.professionalName,
},
{
dataField: "fname",
text: "Funncar",
formatter: (cell, row) => {
return <>{row.booking?.funncar.professionalName}</>;
},
csvFormatter: (cell, row, rowIndex) =>
row.booking?.funncar.professionalName,
},
{
dataField: "duration",
text: "Total Call Duration",
// sort: true,
},
{
dataField: "actions",
text: "View Details",
formatter: (cell, row) => {
return CellMenu(cell, row);
},
csvExport: false,
},
];
return (
<>
<Dialog
{...modalProps}
setOpen={(resp) => {
setModalProps({ ...modalProps, open: resp });
}}
/>
<GridContainer id="callRecords-list-container">
<GridItem xs={12} sm={12} md={12}>
<FormGroup
row
className="d-flex"
style={{ justifyContent: "flex-end" }}
>
<input
type="number"
value={search}
onChange={(e) => onSearch(e.target.value)}
placeholder="Search by booking ID"
style={{ height: "35px", minWidth: "250px", margin: 10 }}
/>
</FormGroup>
</GridItem>
<GridItem xs={12} sm={12} md={12}>
<Card>
<CardHeader color="primary">
<h4 className={classes.cardTitleWhite}>
AGORA Video Call Records{" "}
</h4>
</CardHeader>
<CardBody>
<Table
{...tableProps}
onTableChange={handleTableChange}
columns={columns}
rowEvents={rowEvents}
/>
</CardBody>
</Card>
</GridItem>
</GridContainer>
</>
);
}
|
package com.groupe6.babycare.activities.dialogs;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.material.textfield.TextInputEditText;
import com.groupe6.babycare.R;
import com.groupe6.babycare.dtos.error.ErrorDTO;
import com.groupe6.babycare.dtos.notes.NoteDTO;
import com.groupe6.babycare.listeners.OnDatePickListener;
import com.groupe6.babycare.listeners.OnTimePickerListener;
import com.groupe6.babycare.listeners.ResponseListener;
import com.groupe6.babycare.repositories.apis.NoteApi;
import com.groupe6.babycare.repositories.implementations.NoteApiImpl;
import com.groupe6.babycare.utils.InputsUtils;
public class AddNoteDialog extends Dialog {
private Button btnAdd, btnCancel;
private TextInputEditText inputTitle, inputContent;
public AddNoteDialog(@NonNull Context context) {
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_add_note);
btnAdd = findViewById(R.id.btn_add);
btnCancel = findViewById(R.id.btn_cancel);
inputTitle = findViewById(R.id.input_title);
inputContent = findViewById(R.id.input_content);
btnCancel.setOnClickListener(v -> dismiss());
btnAdd.setOnClickListener(v -> {
save();
});
}
private void save() {
if (!InputsUtils.validateInputs(inputTitle, inputContent))
return;
NoteDTO noteDTO = new NoteDTO();
noteDTO.setContent(inputContent.getText().toString());
noteDTO.setTitle(inputTitle.getText().toString());
NoteApiImpl noteApi = NoteApiImpl.getInstance(getContext());
noteApi.createNote(noteDTO, new ResponseListener<NoteDTO>() {
@Override
public void onSuccess(NoteDTO response) {
Toast.makeText(getContext(), "Note added successfully !!", Toast.LENGTH_SHORT).show();
dismiss();
}
@Override
public void onError(ErrorDTO error) {
Toast.makeText(getContext(), "An error was occured !!", Toast.LENGTH_SHORT).show();
}
});
}
}
|
//------------------------------------------------
// 逐顶点光照案例,实现逐顶点的漫反射光照
// 缺点:背光面和向光面交界处有锯齿
//------------------------------------------------
Shader "GameLib/Light/DiffuseVertexLevel"
{
Properties
{
//材质的漫反射颜色
_Diffuse ("Diffuse", Color) = (1, 1, 1, 1)
}
SubShader
{
Pass
{
//指定光照的渲染模式,这里是为了得到Unity的内置光照变量
Tags { "LightModel"="ForwardBase" }
//开始CG的代码片段 和 ENDCG对应
CGPROGRAM
//指定顶点和片元函数,相当于是告诉Unity,哪个函数执行顶点着色,哪个函数执行片元着色
#pragma vertex vert
#pragma fragment frag
//引入Unity内置的光照函数模块,会用到里面的一些变量
#include "Lighting.cginc"
//为了使用上门定义的变量,定义一个和Properties输入变量同名的变量
fixed4 _Diffuse;
//------------------------
//POSITION NORMAL COLOR这些东西从哪来的呢?
//是由该材质的MeshRender组件提供的,在每帧调用DrawCall的时候,MeshRender把模型数据发送给Shader
//------------------------
//------------------------
//a2v是什么意思?
//a是application v是顶点着色器(vertex shader), a2v就是把数据从应用阶段传递到顶点着色器里面
//------------------------
//定义顶点着色器的输入和输出结构体(输出结构也是片元着色器的输入结构体)
struct a2v
{
// 把顶点数据填充到vertex字段
float4 vertex : POSITION;
// 通过使用NORMAL语义来告诉Unity要把模型顶点的法线信息存储到normal变量中
float3 normal : NORMAL;
};
//为了把顶点着色器计算的光照颜色传递给片元着色器,定义color变量
//v2f vertex 2 frag 就是顶点到片元的数据传递
struct v2f
{
float4 pos : SV_POSITION;
//这里也可以使用TEXCOORD0 fixed3 color : TEXCOORD0;
fixed3 color : COLOR;
};
//顶点着色器,最基本的任务就是把顶点位置从模型空间转换到裁剪空间
//返回值是一个v2f结构体,输入的数据是MeshRender提供的,这里只取了顶点和法线数据
v2f vert(a2v v)
{
v2f o;
// 把顶点坐标从模型空间转换到裁剪空间(投影空间)
o.pos = UnityObjectToClipPos(v.vertex);
// 得到环境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
// 把法线从模型空间转换到世界空间,主要是后面进行点积的时候需要是同坐标系,
//UnityObjectToWorldNormal(v.normal)代替mul(v.normal, (float3x3)unity_WorldToObject)
fixed3 worldNormal = normalize(UnityObjectToWorldNormal(v.normal));
//根据_WorldSpaceLightPos0归一化来获取世界空间中光源的方向
fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
//通过计算得到漫反射光
//根据_LightColor0内置变量来访问该Pass处理的光源的颜色和强度信息
//saturate函数的作用是把参数截取到[0,1]的范围内,在计算点积时需要两者都处于同一坐标空间下,这里选择的是世界坐标系,这里相当于是对法线和光源进行归一化操作,并且保证结果不为负值
fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLight));
//把环境光和漫反射光相加得到光照
o.color = ambient + diffuse;
//返回给片元着色器处理
return o;
}
// 片元着色器, SV_TARGET描述片元着色器的输出颜色,它等同于告诉渲染器,把用户的输出颜色存储到一个渲染目标(render target),framebuffer rendertexture
fixed3 frag(v2f i) : SV_TARGET
{
//输出顶点着色器计算出的颜色
return fixed4(i.color, 1.0);
}
ENDCG
}
}
Fallback "Diffuse"
}
|
import javax.swing.*;
import java.awt.*;
import java.io.InputStream;
import java.net.URL;
public class ImagePanel extends JPanel {
private Image backgroundImage;
public ImagePanel(String resourcePath) {
try {
// Using getClass().getResource() to get the URL of the resource
URL url = getClass().getResource(resourcePath);
if (url != null) {
backgroundImage = new ImageIcon(url).getImage();
} else {
System.err.println("Resource not found: " + resourcePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImage != null) {
g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
} else {
// Optional: Set a default background color if the image fails to load
g.setColor(Color.GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
|
import React from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';
import { getParrots } from '../data/parrotResource';
import HomePage from '../pages/HomePage';
import CreateAParrot from '../pages/CreateAParrot';
import AddAPhrase from '../pages/AddAPhrase';
import PickAParrot from '../pages/PickAParrot';
import { useParrotContext } from '../context/Parrot';
import Navigation from '../components/Navigation';
import PlayGame from '../pages/PlayGame';
import Games from '../pages/Games';
import ReplayGame from '../pages/ReplayGame';
import { useAuthContext } from '../context/Auth';
import BetaFooter from '../components/BetaFooter';
import EditParrot from '../pages/EditParrot';
import Phrases from '../pages/Phrases';
import EditPhrase from '../pages/EditPhrase';
import Settings from '../pages/Settings';
import Admin from '../pages/Admin';
const Authenticated: React.FC = () => {
const { signOut } = useAuthContext();
const [parrots] = getParrots();
const { parrot } = useParrotContext();
const noParrots = parrots && parrots.data.length === 0;
if (noParrots) return <CreateAParrot />;
if (!parrot) return <PickAParrot />;
return (
<>
<BetaFooter />
<Navigation
{...{
logout: signOut,
links: [
{ to: '/', text: 'Home' },
{ to: '/phrases', text: 'Phrases' },
{ to: '/games', text: 'Games' },
{ to: '/parrot', text: 'Create parrot' },
{ to: '/settings', text: 'Settings' },
],
}}
/>
<Switch>
<Route path="/settings">
<Settings />
</Route>
<Route path="/games">
<Games />
</Route>
<Route path="/edit">
<EditParrot />
</Route>
<Route path="/parrot">
<CreateAParrot />
</Route>
<Route path="/pick">
<PickAParrot />
</Route>
<Route path="/phrases/:id">
<EditPhrase />
</Route>
<Route path="/phrases">
<Phrases />
</Route>
<Route path="/phrase">
<AddAPhrase />
</Route>
<Route path="/replay/:id">
<ReplayGame />
</Route>
<Route path="/play">
<PlayGame />
</Route>
<Route path="/admin">
<Admin />
</Route>
<Route exact path="/">
<HomePage />
</Route>
<Route>
<Redirect to="/" />
</Route>
</Switch>
</>
);
};
export default Authenticated;
|
---
unique-page-id: 18874767
description: Impostazione delle fasi del boomerang - [!DNL Marketo Measure] - Documentazione del prodotto
title: Impostazione delle fasi del boomerang
exl-id: 00dd2826-27a3-462e-a70e-4cec90d07f92
feature: Boomerang
source-git-commit: 8ac315e7c4110d14811e77ef0586bd663ea1f8ab
workflow-type: tm+mt
source-wordcount: '305'
ht-degree: 0%
---
# Impostazione delle fasi del boomerang {#setting-up-boomerang-stages}
>[!AVAILABILITY]
>
>La funzione Boomerang è abilitata solo per i clienti di livello 3. Per richiedere un livello di account più alto, contatta l’Adobe Account Team (il tuo account manager).
Per abilitare [!UICONTROL Boomerang] Per il tuo account, devi essere un Amministratore account. In alternativa, può essere abilitata contattando il [Supporto Marketo](https://nation.marketo.com/t5/support/ct-p/Support){target="_blank"}. Una volta abilitata la funzione, segui queste istruzioni per configurarla.
## Configurazione fase boomerang {#boomerang-stage-setup}
1. Vai a [!UICONTROL Stage Mapping]. Sotto la colonna intitolata "[!UICONTROL Boomerang]," seleziona le caselle accanto alle fasi che desideri tracciare.

1. Vai a [!UICONTROL Attribution Settings] e immettere il numero di punti di contatto per ogni fase che si desidera visualizzare. Consentiamo un massimo di 10. Il valore predefinito è 1.

1. Clic **[!UICONTROL Save]**.
>[!NOTE]
>
>Attendi 24-48 ore per la rielaborazione dei dati in base a queste modifiche.
## Configurazione di Boomerang Stage con attribuzione di modello personalizzato {#boomerang-stage-setup-with-custom-model-attribution}
1. Vai a [!UICONTROL Stage Mapping]. Nella colonna intitolata "[!UICONTROL Boomerang]," seleziona le caselle accanto alle fasi che desideri tracciare.

1. Se desideri anche che queste fasi Boomerang siano incluse nel modello personalizzato e ricevano il merito di attribuzione, assicurati di selezionare anche la casella sotto "[!UICONTROL Custom Model]".

1. Vai a [!UICONTROL Attribution Settings] scheda. Determina come desideri ponderare l’attribuzione per le fasi del boomerang. Le opzioni consentono di ponderare l’attribuzione sulla prima o sull’ultima occorrenza oppure di suddividerla in modo uniforme tra tutte le occorrenze.

1. Immettere il numero di occorrenze di ogni fase che si desidera visualizzare. Possiamo consentire un massimo di 10. Il valore predefinito è 1.

1. Imposta la percentuale di attribuzione da allocare agli stadi boomerang inclusi nel modello personalizzato. Assicurati che l’attribuzione totale per tutte le fasi sia pari al 100%. Clic **[!UICONTROL Save and Process]**.

>[!NOTE]
>
>Attendi 24-48 ore per la rielaborazione dei dati in base a queste modifiche.
|
import 'package:calorie_tracker/src/views/tracking/plan_calculators/CustomPlan.dart';
import 'package:calorie_tracker/src/views/tracking/plan_calculators/MifflinStJeorCalculator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class PlanCalculators extends StatefulWidget {
@override
State<PlanCalculators> createState() =>
_PlanCalculatorsState();
}
class _PlanCalculatorsState extends State<PlanCalculators> {
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
final List<String> _appbarTitles = [
AppLocalizations.of(context)!.caloriesGoalPlanMSJ,
AppLocalizations.of(context)!.caloriesGoalPlanCustom
];
return Scaffold(
appBar: AppBar(
title: DropdownButton(
isExpanded: true,
style: Theme.of(context).textTheme.titleLarge,
value: _appbarTitles[_selectedIndex],
items: _appbarTitles.map((String value){
return DropdownMenuItem(
value: value,
child: Text(value)
);
}).toList(),
onChanged: (String? value) {
setState(() {
_selectedIndex = _appbarTitles.contains(value) ? _appbarTitles.indexOf(value!) : 0;
});
},
),
),
body: [
MifflinStJeorCalculator(),
CustomPlan(),
][_selectedIndex]
);
}
}
|
import axios from 'axios'
import { AxiosInstance } from 'axios'
import { ElLoading } from 'element-plus'
import { JHRequestInterceptors, JHRequestConfig } from './type'
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'
import {
commentlike,
commentReply,
LikeMusic,
UserSub,
UserPlayList,
UserDetail,
LikeList,
RefLogin,
MVList,
CollectSinger,
SingerList,
LoginStatus
} from './API'
import Localcache from '@/utlis/caches'
const DEFAULT_LOAFING = true
const url = [
commentlike,
commentReply,
LikeMusic,
UserSub,
UserPlayList,
UserDetail,
LikeList,
RefLogin,
MVList,
CollectSinger,
SingerList,
LoginStatus
]
class WJHRequest {
instance: AxiosInstance
interceptorss?: JHRequestInterceptors
isloading?: LoadingInstance
showloading: boolean
withCredentials: boolean
constructor(config: JHRequestConfig) {
this.instance = axios.create(config)
this.interceptorss = config.interceptorss
this.showloading = config.showloading ?? DEFAULT_LOAFING
this.withCredentials = config.withCredentials ?? true
// // 请求拦截器,对需要携带cookie的api添加cookie参数
this.instance.interceptors.request.use(
(data) => {
// console.log(data, 'data')
// console.log(data.url?.split('?')[0], 'data')
const isNeverLogin = url.findIndex(
(item) => item == data.url?.split('?')[0]
)
console.log(isNeverLogin, 'cookieisNeverLogin')
const cookie = Localcache.getCache('cookie')
if (cookie && isNeverLogin >= 0) {
if (data.params) {
data.params.cookie = cookie
console.log(data.params.cookie, ' data.params.cookie')
}
}
// console.log(data, 'cookieData')
return data
},
(err) => {
console.log(err)
return err
}
)
// 实例的拦截器
this.instance.interceptors.request.use(
this.interceptorss?.requestcg,
this.interceptorss?.requestsb
)
this.instance.interceptors.response.use(
this.interceptorss?.requestxy,
this.interceptorss?.requestxysb
)
// 全局的拦截器 直接写
this.instance.interceptors.request.use(
(config) => {
console.log('全局的请求成功:::')
if (this.showloading) {
this.isloading = ElLoading.service({
lock: true,
text: '俢钩~ ,Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
})
}
return config
},
(err) => {
console.log('全局的请求失败')
return err
}
)
this.instance.interceptors.response.use(
(res) => {
console.log('全局的响应成功')
const data = res.data
if (data.returnCode === '-1001') {
console.log('-1001,响应请求失败~')
} else {
this.isloading?.close()
return data
}
},
(err) => {
console.log('全局的响应失败')
if (err.response.status === 404) {
console.log('404~错误')
}
this.isloading?.close()
return err
}
)
}
// 单独请求来到这里调用
request<T = any>(config: JHRequestConfig<T>): Promise<T> {
return new Promise((resolve, reject) => {
// 判断传进来的config 有没有拦截器 如果有就执行这个函数 本质上就是在请求的前一步做判断 执行函数 里的loading等事情 达到效果 后 然后把传进来的值原路返回 类似于过滤器只是增加东西执行
if (config.interceptorss?.requestcg) {
config = config.interceptorss.requestcg(config) //发送请求成功
} else if (config.interceptorss?.requestsb) {
config = config.interceptorss.requestsb(config) //发送请求失败
}
// 修改 this,showloading
if (config.showloading === false) {
this.showloading = config.showloading
}
//真正的 网络请求
this.instance
.request<any, T>(config)
.then((res) => {
// 服务器返回时 判断config里面是否有响应式拦截器 如果有就调用这个函数把服务器的数据res传进去 执行里面的loading等事情 后 再把res服务器返回的数据 返回出去
if (config.interceptorss?.requestxy) {
res = config.interceptorss.requestxy(res) //响应成功
} else if (config.interceptorss?.requestxysb) {
res = config.interceptorss.requestxysb(res) //响应失败
}
resolve(res) //数据
// 返回数据之后 还原 showloading
this.showloading = DEFAULT_LOAFING
})
.catch((error) => {
this.showloading = DEFAULT_LOAFING
reject(error)
console.log(error, 'error')
})
})
}
get<T = any>(config: JHRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'GET' })
}
post<T = any>(config: JHRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'POST' })
}
delete<T = any>(config: JHRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'DELETE' })
}
patch<T = any>(config: JHRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'PATCH' })
}
}
export default WJHRequest
|
package com.yy.codebasecase.ui.screens.propertylist
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yy.codebasecase.domain.usecase.GetPropertiesUseCase
import com.yy.codebasecase.utils.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class PropertyListViewModel @Inject constructor(
private val getPropertiesUseCase: GetPropertiesUseCase
) : ViewModel() {
private val _state = MutableStateFlow(PropertyListState())
val state: StateFlow<PropertyListState> = _state
init {
getProperties()
}
/**
* İlanları yükler ve sonuçları [_state] üzerinde yayınlar.
*/
fun getProperties() {
viewModelScope.launch {
getPropertiesUseCase().collect { result ->
when (result) {
is Resource.Success -> {
_state.value = PropertyListState(
properties = result.data.data,
filteredProperties = result.data.data
)
}
is Resource.Error -> {
_state.value = PropertyListState(
error = result.exception ?: "İlanlar getirilirken bir hata oluştu."
)
}
is Resource.Loading -> {
_state.value = PropertyListState(isLoading = true)
}
}
}
}
}
/**
* Kullanıcının arama sorgusunu günceller ve filtrelenmiş ilanları günceller.
* @param query Kullanıcının girdiği arama sorgusu.
*/
fun onSearchQueryChanged(query: String) {
_state.value = _state.value.copy(searchQuery = query)
if (_state.value.properties.isNotEmpty())
updateFilteredProperties()
}
/**
* [_state] içindeki arama sorgusuna göre ilanları filtreler.
*/
private fun updateFilteredProperties() {
_state.value = _state.value.copy(
filteredProperties = if (_state.value.searchQuery.isBlank()) {
_state.value.properties
} else {
_state.value.properties.filter {
it.category?.contains(_state.value.searchQuery, ignoreCase = true) == true
}
}
)
}
}
|
@extends('layouts.app')
@section('content')
<div class="section-header">
<h1>Carousel</h1>
<div class="section-header-breadcrumb">
<div class="breadcrumb-item"><a href="{{ route('home') }}">Dashboard</a></div>
<div class="breadcrumb-item"><a href="{{ route('konfigurasi') }}">Konfigurasi</a></div>
<div class="breadcrumb-item"><a href="{{ route('konfigurasi.aplikasi') }}">Aplikasi</a></div>
<div class="breadcrumb-item"><a href="{{ route('konfigurasi.aplikasi.carousel') }}">Carousel</a></div>
<div class="breadcrumb-item"><a href="{{ route('konfigurasi.aplikasi.carousel.show', $carousel->carousel_id) }}">Detail</a></div>
<div class="breadcrumb-item">Ubah</div>
</div>
</div>
<div class="section-body">
<h2 class="section-title">Ubah Carousel</h2>
<p class="section-lead">
Ubahkan data Carousel.
</p>
<div class="row justify-content-center">
<div class="col-md-12">
@if(session('msg')){!! session('msg') !!} @endif
</div>
<div class="col-md-12">
<form action="{{ route('konfigurasi.aplikasi.carousel.update', $carousel->carousel_id) }}" method="post" enctype="multipart/form-data">@csrf @method('put')
<div class="card">
<div class="card-header">
<h4>{{ __('Carousel') }}</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="row mb-3 justify-content-center reg-in">
<label for="aplikasi_id" class="col-md-4 col-form-label text-md-end">{{ __('Aplikasi')
}}</label>
<div class="col-md-6">
<div class="input-group mb-3">
<select name="aplikasi_id" id="aplikasi_id" class="form-control @error('aplikasi_id') is-invalid @enderror">
@foreach($aplikasi as $apl)
<option {{ $carousel->aplikasi_id == $apl->aplikasi_id ? 'selected' : '' }} value="{{ $apl->aplikasi_id }}">{{ $apl->nama_aplikasi }}</option>
@endforeach
</select>
</div>
@error('aplikasi_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3 justify-content-center reg-in">
<label for="title" class="col-md-4 col-form-label text-md-end">{{ __('Judul')
}}</label>
<div class="col-md-6">
<div class="input-group mb-3">
<input id="title" type="text"
class="form-control @error('title') is-invalid @enderror" name="title"
value="{{ $carousel->title }}" />
</div>
@error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3 justify-content-center reg-in">
<label for="subtitle" class="col-md-4 col-form-label text-md-end">{{ __('Sub-Judul')
}}</label>
<div class="col-md-6">
<div class="input-group mb-3">
<textarea id="subtitle" class="form-control @error('subtitle') is-invalid @enderror" name="subtitle" cols="30" rows="10">{{ $carousel->subtitle }}</textarea>
</div>
@error('subtitle')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3 justify-content-center reg-in">
<label for="urutan" class="col-md-4 col-form-label text-md-end">{{ __('Urutan')
}}</label>
<div class="col-md-6">
<div class="input-group mb-3">
<input id="urutan" class="form-control @error('urutan') is-invalid @enderror" name="urutan" value="{{ $carousel->urutan }}" type="number" />
</div>
@error('urutan')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3 justify-content-center reg-in">
<label for="page" class="col-md-4 col-form-label text-md-end">{{ __('Halaman')
}}</label>
<div class="col-md-6">
<div class="input-group mb-3">
<input id="page" class="form-control @error('page') is-invalid @enderror" name="page" value="{{ $carousel->page }}" type="text" />
</div>
@error('page')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3 justify-content-center">
<label for="gambar" class="col-md-4 col-form-label text-md-end">{{
__('Gambar Carousel')
}}</label>
<div class="col-md-6">
<div class="custom-file">
<input type="file" name="gambar" class="custom-file-input" id="gambar">
<label class="custom-file-label" for="gambar">Pilih File</label>
</div>
@error('gambar')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
<img src="{{ asset('storage/carousel/' . $carousel->image_src) }}" alt="{{ $carousel->image_src }}" class="img img-thumbnail img-temporary" style="width: 800px; height: auto">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h4>{{ __('Pilihan') }}</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="row mb-0">
<div class="col-md-6 offset-md-4 d-flex align-items-end">
<a type="button" href="{{ route('konfigurasi.aplikasi.carousel.show', $carousel->carousel_id) }}" class="btn btn-primary mr-2"><i class="fas fa-arrow-left"></i> Kembali</a>
<button type="submit" class="btn mx-2 btn-success"><i class="fas fa-pen"></i> Simpan</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
@endsection
|
import React from 'react'
import styled from 'styled-components'
import { useLcdText } from '../../hooks'
const NUM_COLS = 16
const NUM_ROWS = 2
const DisplayOuter = styled.div`
display: flex;
border: 1px solid #b8b8b82b;
background-color: #0f0f0f;
padding: 20px;
`
const DisplayInner = styled.div`
flex-grow: 1;
background-color: #003805;
display: grid;
grid-template-columns: repeat(${NUM_COLS}, auto);
grid-template-rows: repeat(${NUM_ROWS}, auto);
padding: 5px;
`
const Digit = styled.div`
font-family: monospace;
background-color: #005f18;
color: black;
font-weight: bold;
font-size: 24px;
width: 24px;
height: 24px;
line-height: 24px;
vertical-align: center;
text-align: center;
margin: 2px;
`
const LcdDisplay: React.FunctionComponent = () => {
const text = useLcdText() ?? ''
return (
<DisplayOuter>
<DisplayInner>
{Array.from(text.padEnd(NUM_COLS * NUM_ROWS, ' ')).map((c, i) => (
<Digit key={i}>{c}</Digit>
))}
</DisplayInner>
</DisplayOuter>
)
}
export default LcdDisplay
|
package com.example.demo.items.model;
import com.example.demo.users.model.User;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.List;
@Entity
@Data
@NoArgsConstructor
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private String id;
@NotBlank(message = "Name cannot be empty!")
@Size(min = 3, message = "Name should have minimal of 3 characters!")
private String name;
@Min(value = 0, message = "Amount cannot be lower than zero!")
private Long amount;
@Enumerated(EnumType.STRING)
private Unit unit;
@ManyToMany(mappedBy = "wishlist")
@JsonBackReference
private List<User> wishlistedBy;
@Getter
public enum Unit {
PC("pieces"),
KG("kilograms");
private final String name;
Unit(String name) {
this.name = name;
}
}
}
|
import React from 'react';
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faEnvelope} from "@fortawesome/free-solid-svg-icons";
import {faPhone} from "@fortawesome/free-solid-svg-icons";
import {faLocationDot} from "@fortawesome/free-solid-svg-icons";
import './Contact.css'
const Contact = () => {
const onSubmit = async (event) => {
event.preventDefault();
const formData = new FormData(event.target);
formData.append("access_key", "67fdd906-94b1-4a53-82df-eeafbc8dc0cc");
const object = Object.fromEntries(formData);
const json = JSON.stringify(object);
const res = await fetch("https://api.web3forms.com/submit", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: json
}).then((res) => res.json());
if (res.success) {
alert(res.message);
}
};
return (
<div className={"contact-section"} id={"contact"}>
<div className={"contact-title"}>
<h1>Get in touch</h1>
</div>
<div className={"contact-content"}>
<div className={"contact-left"}>
<h2>Let's talk</h2>
<p>I'd love to hear from you! Whether you have a question about my projects, want to collaborate, or
just want to say hi, feel free to reach out.
</p>
<div className={"contact-left-details"}>
<a><FontAwesomeIcon icon={faEnvelope} className={"contact-icon"}/></a>
<p>[email protected]</p>
</div>
<div className={"contact-left-details"}>
<a><FontAwesomeIcon icon={faPhone} className={"contact-icon"}/></a><p>+940770754683</p>
</div>
<div className={"contact-left-details"}>
<a><FontAwesomeIcon icon={faLocationDot} className={"contact-icon"}/></a><p>Galle, Sri Lanka</p>
</div>
</div>
<form onSubmit={onSubmit} className={"contact-right"}>
<label htmlFor={""}>Your Name</label>
<input className={"contact-input"} type="text" placeholder={"Enter your name"} name={"name"} required/>
<label htmlFor={""}>Your Email</label>
<input className={"contact-input"} type="email" placeholder={"Enter your email"} name={"email"} required/>
<label>Write your message here</label>
<textarea className={"contact-textarea"} placeholder={"Enter your message here"} name={"message"} rows={8} required></textarea>
<button className={"contact-submit"} type={"submit"}>Submit Now</button>
</form>
</div>
</div>
);
};
export default Contact;
|
import React, { Component } from 'react'
import '../../assets/index.css'
// 导入图片
import tx from '../../assets/images/avatar.png'
// 导入moment
import mt from 'moment'
class App extends Component {
// B站评论数据
state = {
// 新增评论输入
content: '',
// hot: 热度排序 time: 时间排序
tabs: [
{
id: 1,
name: '热度',
type: 'hot',
},
{
id: 2,
name: '时间',
type: 'time',
},
],
// 当前选中的tab的type值
active: 'time',
list: [
{
id: 1,
author: '刘德华',
comment: '给我一杯忘情水',
time: new Date('2021-10-10 09:09:00'),
// 1: 点赞 0:无态度 -1:踩
attitude: 1,
},
{
id: 2,
author: '周杰伦',
comment: '哎哟,不错哦',
time: new Date('2021-10-11 09:09:00'),
// 1: 点赞 0:无态度 -1:踩
attitude: 0,
},
{
id: 3,
author: '五月天',
comment: '不打扰,是我的温柔',
time: new Date('2021-10-11 10:09:00'),
// 1: 点赞 0:无态度 -1:踩
attitude: -1,
},
],
}
/**
* 格式化时间方法
* @param {*} date
* @returns
*/
formatTime = (date) => {
return mt(date).format('YYYY年MM月DD日')
}
// 1. 点击切换tab栏高亮效果
// type 当前点击tab栏的type值
changeTab = (type) => {
// console.log(type)
this.setState({
active: type,
})
}
// 2. 点击删除评论
delList = (id) => {
// 说明:不能用splice方法删除=》因为splice方法会直接修改list=》react数据不可变
this.setState({
list: this.state.list.filter((item) => item.id !== id),
})
}
/**
* 3. 新增一条评论
* 思路:
* 1. 获取输入框的值=》受控组件
* 2. 根据输入的值向list列表新增评论
*/
// 存储输入值
changeContent = (e) => {
this.setState({
content: e.target.value,
})
}
addList = () => {
if (!this.state.content.trim()) {
return alert('评论内容不能为空!')
}
this.setState({
list: [
// 新增数据
{
id: Date.now(),
author: '匿名',
comment: this.state.content,
time: new Date(),
// 1: 点赞 0:无态度 -1:踩
attitude: 0,
},
// 之前的数据
...this.state.list,
],
// 清空输入框值
content: '',
})
}
// 4. 点赞或踩处理
/**
*
* @param {*} id 当前点击评论ID
* @param {*} attitude 当前点击评论的状态:1: 点赞 0:无态度 -1:踩(最新)
*/
changeAttitude = (id, attitude) => {
this.setState({
list: this.state.list.map((item) => {
if (item.id === id) {
// 当前需要修改的评论状态
return {
...item,
attitude,
}
} else {
// 不需要修改,直接返回给新数据
return item
}
}),
})
}
render() {
return (
<div className="App">
<div className="comment-container">
{/* 评论数 */}
<div className="comment-head">
<span>5 评论</span>
</div>
{/* 排序 */}
<div className="tabs-order">
<ul className="sort-container">
{/* <li className="on">按热度排序</li>
<li>按时间排序</li> */}
{this.state.tabs.map((tab) => (
<li
className={this.state.active === tab.type ? 'on' : ''}
key={tab.id}
// react事件传值口诀:函数套函数=> 是在里边传值
onClick={() => this.changeTab(tab.type)}>
按{tab.name}排序
</li>
))}
</ul>
</div>
{/* 添加评论 */}
<div className="comment-send">
<div className="user-face">
<img className="user-head" src={tx} alt="" />
</div>
<div className="textarea-container">
<textarea
cols="80"
rows="5"
value={this.state.content}
onChange={this.changeContent}
placeholder="发条友善的评论"
className="ipt-txt"
/>
<button onClick={this.addList} className="comment-submit">
发表评论
</button>
</div>
<div className="comment-emoji">
<i className="face"></i>
<span className="text">表情</span>
</div>
</div>
{/* 评论列表 */}
<div className="comment-list">
{/* <div className="list-item">
<div className="user-face">
<img className="user-head" src={tx} alt="" />
</div>
<div className="comment">
<div className="user">zqran</div>
<p className="text">前排吃瓜</p>
<div className="info">
<span className="time">2021-10-08 09:05:00</span>
<span className="like liked">
<i className="icon" />
</span>
<span className="hate hated">
<i className="icon" />
</span>
<span className="reply btn-hover">删除</span>
</div>
</div>
</div> */}
{this.state.list.map((item) => (
<div className="list-item" key={item.id}>
{/* 评论人头像 */}
<div className="user-face">
<img className="user-head" src={tx} alt="" />
</div>
<div className="comment">
<div className="user">{item.author}</div>
<p className="text">{item.comment}</p>
<div className="info">
<span className="time">{this.formatTime(item.time)}</span>
{/* 点赞-支持 */}
<span
className={item.attitude === 1 ? 'like liked' : 'like'}
// item.attitude === 1 ? 0 : 1
// 说明:1. 如果是1说明是点赞,再次点击取消0 2. 相反,赋值1就是点赞
onClick={() =>
this.changeAttitude(
item.id,
item.attitude === 1 ? 0 : 1
)
}>
<i className="icon" />
</span>
{/* 踩-不支持 */}
<span
className={item.attitude === -1 ? 'hate hated' : 'hate'}
onClick={() =>
this.changeAttitude(
item.id,
item.attitude === -1 ? 0 : -1
)
}>
<i className="icon" />
</span>
<span
onClick={() => this.delList(item.id)}
className="reply btn-hover">
删除
</span>
</div>
</div>
</div>
))}
</div>
</div>
</div>
)
}
}
export default App
|
// Copyright 2022 The SiliFuzz Authors.
//
// 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
//
// https://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.
// Test for lss wrappers. We assume linux_syscall_support works so these are
// lightly tested.
#include <fcntl.h>
#include <linux/limits.h>
#include <strings.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <csignal>
#include <cstring>
#include "third_party/lss/lss/linux_syscall_support.h"
#include "./util/checks.h"
#include "./util/itoa.h"
#include "./util/nolibc_gunit.h"
#include "./util/strcat.h"
namespace silifuzz {
namespace {
// By default test files are create readable and writable.
static constexpr int kDefaultOpenFlags = O_CREAT | O_TRUNC | O_RDWR;
// By default files are created to be user readable and writable only.
static constexpr mode_t kDefaultCreationMode = S_IRUSR | S_IWUSR;
// Holds a temporary file path.
class TempFilePath {
public:
explicit TempFilePath(const char* label) {
// Temp file path is /tmp/syscalls_test.<label>.<pid>
pid_t pid = sys_getpid();
CHECK_NE(pid, -1)
set_path(StrCat({"/tmp/syscalls_test.", label, ".", IntStr(pid)}));
}
~TempFilePath() = default;
// Copyable and movable by default.
TempFilePath(const TempFilePath&) = default;
TempFilePath& operator=(const TempFilePath&) = default;
TempFilePath(TempFilePath&&) = default;
TempFilePath& operator=(TempFilePath&&) = default;
const char* path() const { return path_; }
private:
void set_path(const char* value) {
// Neither strcpy() nor strncpy() is available in nolibc environment.
size_t size = strlen(value) + 1;
CHECK_LE(size, PATH_MAX);
memcpy(path_, value, size);
}
char path_[PATH_MAX];
};
// In all tests below, use linux_syscall_support functions direct for unless
// it is for the syscall being tested.
TEST(Syscalls, close) {
int fd = sys_open("/dev/zero", O_RDONLY, 0);
CHECK_NE(fd, -1);
errno = 0;
int result = close(fd);
CHECK_EQ(result, 0);
CHECK_EQ(errno, 0);
}
TEST(Syscalls, getegid) { CHECK_EQ(getegid(), sys_getegid()); }
TEST(Syscalls, geteuid) { CHECK_EQ(geteuid(), sys_geteuid()); }
TEST(Syscalls, getpid) { CHECK_EQ(getpid(), sys_getpid()); }
TEST(Syscalls, kill) {
// A process should have permission to signal itself.
errno = 0;
CHECK_EQ(kill(getpid(), 0), 0);
CHECK_EQ(errno, 0);
// Bad signal number.
CHECK_EQ(kill(getpid(), 1000000), -1);
CHECK_EQ(errno, EINVAL)
}
TEST(Syscalls, lseek) {
TempFilePath temp("lseek");
int fd = sys_open(temp.path(), kDefaultOpenFlags, kDefaultCreationMode);
CHECK_NE(fd, -1);
constexpr char kTestData[] = "Hello world.";
constexpr size_t kTestDataSize = sizeof(kTestData);
CHECK_EQ(sys_write(fd, kTestData, kTestDataSize), kTestDataSize);
errno = 0;
CHECK_EQ(lseek(fd, 2, SEEK_SET), 2);
CHECK_EQ(errno, 0);
CHECK_EQ(lseek(fd, 2, SEEK_CUR), 4);
CHECK_EQ(errno, 0);
CHECK_EQ(lseek(fd, -2, SEEK_END), kTestDataSize - 2);
CHECK_EQ(errno, 0);
CHECK_EQ(sys_close(fd), 0);
CHECK_EQ(sys_unlink(temp.path()), 0);
}
TEST(Syscalls, mmap) {
// mapping a length of 0 should return EINVAL.
errno = 0;
CHECK_EQ(mmap(nullptr, 0, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
-1, 0),
MAP_FAILED);
CHECK_EQ(errno, EINVAL);
size_t page_size = getpagesize();
errno = 0;
void* ptr = mmap(nullptr, page_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
CHECK_NE(ptr, MAP_FAILED);
CHECK_EQ(errno, 0);
// Check that memory is mapped.
int fd = open("/dev/zero", O_RDONLY);
CHECK_NE(fd, -1);
CHECK_EQ(read(fd, ptr, page_size), page_size);
CHECK_EQ(munmap(ptr, page_size), 0);
CHECK_EQ(close(fd), 0);
}
TEST(Syscalls, mprotect) {
// Check error reproting.
// mprotect unaligned address should return EINVAL.
errno = 0;
size_t page_size = getpagesize();
CHECK_EQ(
mprotect(reinterpret_cast<void*>(1), page_size, PROT_READ | PROT_WRITE),
-1);
CHECK_EQ(errno, EINVAL);
errno = 0;
void* ptr =
mmap(nullptr, page_size, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
CHECK_NE(ptr, MAP_FAILED);
errno = 0;
CHECK_EQ(mprotect(ptr, page_size, PROT_READ | PROT_WRITE), 0);
CHECK_EQ(errno, 0);
// Check memory is writable.
constexpr size_t kReadSize = 1;
int fd = open("/dev/zero", O_RDONLY);
CHECK_NE(fd, -1);
CHECK_EQ(read(fd, ptr, kReadSize), kReadSize);
// Change permission again.
errno = 0;
CHECK_EQ(mprotect(ptr, page_size, PROT_READ), 0);
CHECK_EQ(errno, 0);
// Check memory is not writable.
CHECK_EQ(read(fd, ptr, kReadSize), -1);
CHECK_EQ(errno, EFAULT);
// Check that syscall accepts an unaligned length and does the right thing.
errno = 0;
CHECK_EQ(mprotect(ptr, page_size - 1, PROT_READ | PROT_WRITE), 0);
CHECK_EQ(errno, 0);
// Memory should be writable now.
CHECK_EQ(read(fd, ptr, kReadSize), kReadSize);
CHECK_EQ(munmap(ptr, page_size), 0);
CHECK_EQ(close(fd), 0);
}
TEST(Syscalls, munmap) {
size_t page_size = getpagesize();
errno = 0;
void* ptr = sys_mmap(nullptr, page_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
CHECK_NE(ptr, MAP_FAILED);
CHECK_EQ(errno, 0);
errno = 0;
CHECK_EQ(munmap(ptr, page_size), 0);
CHECK_EQ(errno, 0);
// Check that memory is not mapped.
int fd = open("/dev/zero", O_RDONLY);
CHECK_NE(fd, -1);
constexpr size_t kReadSize = 1;
CHECK_EQ(read(fd, ptr, kReadSize), -1);
CHECK_EQ(errno, EFAULT);
CHECK_EQ(close(fd), 0);
}
TEST(Syscalls, open) {
// Try opening some well known file.
errno = 0;
int fd = open("/dev/zero", O_RDONLY, 0);
CHECK_NE(fd, -1);
CHECK_EQ(errno, 0);
CHECK_EQ(sys_close(fd), 0);
// Try opening non-existant file.
fd = open("/this does not exist", O_RDONLY);
CHECK_EQ(fd, -1);
CHECK_EQ(errno, ENOENT);
// Test passing mode.
errno = 0;
TempFilePath temp("open");
fd = open(temp.path(), kDefaultOpenFlags, kDefaultCreationMode);
if (fd == -1) {
LOG_ERROR("open()", ErrnoStr(errno));
}
CHECK_NE(fd, -1);
kernel_stat ks;
CHECK_EQ(sys_fstat(fd, &ks), 0);
const mode_t kMask = S_IRWXU | S_IRWXG | S_IRWXO;
CHECK_EQ(ks.st_mode & kMask, kDefaultCreationMode);
CHECK_EQ(sys_close(fd), 0);
CHECK_EQ(sys_unlink(temp.path()), 0);
}
TEST(Syscalls, prctl) {
// Lightly test the interface using PR_GET_DUMPABLE & PR_SET_DUMPABLE.
// Most other functionalities require newer kernels, are platforms specific,
// or do very significant changes that may affect other tests (.e.g SECCOMP).
// Passing of arguments arg3 to arg5 is not exercised.
errno = 0;
int old_dumpable = prctl(PR_GET_DUMPABLE);
CHECK_NE(old_dumpable, -1);
CHECK_EQ(errno, 0);
int new_dumpable = old_dumpable == 0 ? 1 : 0;
CHECK_EQ(prctl(PR_SET_DUMPABLE, new_dumpable), 0);
CHECK_EQ(errno, 0);
CHECK_EQ(prctl(PR_GET_DUMPABLE), new_dumpable);
CHECK_EQ(errno, 0);
CHECK_EQ(prctl(PR_SET_DUMPABLE, 9999), -1);
CHECK_EQ(errno, EINVAL);
// Restore old dumpable setting.
CHECK_EQ(prctl(PR_SET_DUMPABLE, old_dumpable), 0);
CHECK_EQ(errno, EINVAL);
}
TEST(Syscalls, read) {
int fd = sys_open("/dev/zero", O_RDONLY, 0);
CHECK_NE(fd, -1);
constexpr size_t kBufferSize = 20;
char buffer[kBufferSize];
constexpr char kFiller = 'a';
memset(buffer, kFiller, kBufferSize);
errno = 0;
constexpr size_t kReadSize = kBufferSize / 2;
constexpr size_t kOffset = 1;
ssize_t bytes_read = read(fd, buffer + kOffset, kReadSize);
CHECK_EQ(bytes_read, kReadSize);
CHECK_EQ(errno, 0);
// Test that data read as expected and read() does not overwrite.
for (size_t i = 0; i < kBufferSize; ++i) {
const char kExpected =
(i < kOffset) || (i >= kOffset + kReadSize) ? kFiller : 0;
CHECK_EQ(buffer[i], kExpected);
}
CHECK_EQ(sys_close(fd), 0);
}
TEST(Syscalls, sigaltstack) {
// Get old alt-stack.
stack_t old_ss;
CHECK_EQ(sigaltstack(nullptr, &old_ss), 0);
// Allocate a block big enough for a signal stack.
static char alt_stack[64 * 1024] = {0};
// Using a zero-sized stack should fail.
stack_t ss{.ss_sp = alt_stack, .ss_flags = 0, .ss_size = 0};
errno = 0;
CHECK_EQ(sigaltstack(&ss, nullptr), -1);
CHECK_EQ(errno, ENOMEM);
// This should work.
ss.ss_size = sizeof(alt_stack);
errno = 0;
CHECK_EQ(sigaltstack(&ss, nullptr), 0);
// Restore old signal stack. We should read back our stack.
stack_t ss_check;
CHECK_EQ(sigaltstack(&old_ss, &ss_check), 0);
CHECK_EQ(ss_check.ss_sp, alt_stack);
CHECK_EQ(ss_check.ss_size, sizeof(alt_stack));
CHECK_EQ(ss_check.ss_flags, 0);
}
TEST(Syscalls, write) {
TempFilePath temp("write");
int fd = sys_open(temp.path(), kDefaultOpenFlags, kDefaultCreationMode);
CHECK_NE(fd, -1);
constexpr char kTestData[] = "Hello world.";
constexpr size_t kTestDataSize = sizeof(kTestData);
errno = 0;
ssize_t bytes_written = write(fd, kTestData, kTestDataSize);
CHECK_EQ(bytes_written, kTestDataSize);
CHECK_EQ(errno, 0);
// Read back to ensure write() is correct.
char buffer[kTestDataSize];
CHECK_EQ(sys_lseek(fd, 0, SEEK_SET), 0);
CHECK_EQ(sys_read(fd, buffer, kTestDataSize), kTestDataSize);
CHECK_EQ(bcmp(kTestData, buffer, kTestDataSize), 0);
CHECK_EQ(sys_close(fd), 0);
CHECK_EQ(sys_unlink(temp.path()), 0);
}
} // namespace
} // namespace silifuzz
NOLIBC_TEST_MAIN({
RUN_TEST(Syscalls, close);
RUN_TEST(Syscalls, getegid);
RUN_TEST(Syscalls, geteuid);
RUN_TEST(Syscalls, getpid);
RUN_TEST(Syscalls, kill);
RUN_TEST(Syscalls, lseek);
RUN_TEST(Syscalls, mmap);
RUN_TEST(Syscalls, mprotect);
RUN_TEST(Syscalls, munmap);
RUN_TEST(Syscalls, open);
RUN_TEST(Syscalls, prctl);
RUN_TEST(Syscalls, read);
RUN_TEST(Syscalls, sigaltstack);
RUN_TEST(Syscalls, write);
})
|
<?php
namespace Tests\Feature;
use Database\Factories\Authorized_usersFactory;
use Database\Factories\UserFactory;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
class NavigationTest extends TestCase
{
use DatabaseTransactions;
public function test_normal_user_nav_links() {
$user = UserFactory::new()->withoutPrivileges()->create();
$authorized_user = Authorized_usersFactory::new()->create([
'email' => $user->email,
]);
$response = $this->actingAs($user)->get('/home');
$response->assertSee('Home');
$response->assertSee('Report Work Shift');
$response->assertSee('Past Work Shift');
$response1 = $this->actingAs($user)->get('/work-shift');
$response1->assertSee('Home');
$response1->assertSee('Report Work Shift');
$response1->assertSee('Past Work Shift');
$response2 = $this->actingAs($user)->get('/past-work-shift');
$response2->assertSee('Home');
$response2->assertSee('Report Work Shift');
$response2->assertSee('Past Work Shift');
}
public function test_normal_user_cannot_see_supervisor_or_admin_nav_links() {
$user = UserFactory::new()->withoutPrivileges()->create();
$authorized_user = Authorized_usersFactory::new()->create([
'email' => $user->email,
]);
$response = $this->actingAs($user)->get('/home');
$response->assertDontSee('Create News');
$response->assertDontSee('Supervisor');
$response->assertDontSee('Admin');
}
public function test_normal_user_cannot_enter_supervisor_or_admin_links() {
$user = UserFactory::new()->withoutPrivileges()->create();
$authorized_user = Authorized_usersFactory::new()->create([
'email' => $user->email,
]);
$response = $this->actingAs($user)->get('/create-news');
$response->assertStatus(403);
$response1 = $this->actingAs($user)->get('/supervisor');
$response1->assertStatus(403);
$response2 = $this->actingAs($user)->get('/admin');
$response2->assertStatus(403);
}
}
|
// import { configureStore } from '@reduxjs/toolkit';
// import { persistReducer } from "redux-persist";
// import storage from "redux-persist/lib/storage";
// import userReducer from './slices/userSlice';
// import newsReducer from './news/news-slice';
// export const store = configureStore({
// reducer: {
// user: userReducer,
// contacts: newsReducer,
// }
// });
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import {
persistReducer,
persistStore,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";
import userReducer from './slices/userSlice';
import newsReducer from './news/news-slice';
const rootreduser = combineReducers({
user: userReducer,
posts: newsReducer,
});
const persistConfig = {
key: "root",
storage,
};
const persistedReducer = persistReducer(persistConfig, rootreduser);
export const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});
export const persistor = persistStore(store);
|
<?php
/*
* Debugging Tools for weird content
*
* @since 2.4
*/
// if this file is called directly abort
if ( ! defined( 'WPINC' ) ) {
die;
}
class LWTV_Debug {
/**
* Sanitize social media handles
* @param string $usename Username
* @param string $social Social Media Type
* @return string sanitized username
*/
public function sanitize_social( $usename, $social ) {
// Defaults.
$trim = 10;
$regex = '/[^a-zA-Z_.0-9]/';
switch ( $social ) {
case 'instagram': // ex: https://instagram.com/lezwatchtv
$usename = str_replace( 'https://instagram.com/', '', $usename );
$trim = 30;
break;
case 'twitter': // ex: https://twitter.com/lezwatchtv OR https://x.com/lezwatchtv
$usename = str_replace( 'https://twitter.com/', '', $usename );
$usename = str_replace( 'https://x.com/', '', $usename );
$trim = 15;
break;
case 'mastodon': // ex: https://mstdn.social/@lezwatchtv
$regex = '/[^a-zA-Z_.0-9:\/@]/';
$trim = 2000;
break;
}
// Remove all illegal characters.
$clean = preg_replace( $regex, '', trim( $usename ) );
$clean = substr( $clean, 0, $trim );
return $clean;
}
/**
* Clean up the WikiDate
* @param string $date Wiki formatted date: +1968-07-07T00:00:00Z
* @return string LezWatch formatted date: 1968-07-07
*/
public function format_wikidate( $date ) {
$clean = trim( substr( $date, 0, strpos( $date, 'T' ) ), '+' );
return $clean;
}
/**
* Validate IMDB
* @param string $imdb IMDB ID
* @return boolean true/false
*/
public function validate_imdb( $imdb, $type = 'show' ) {
// Defaults
$result = true;
$type = ( ! in_array( $type, array( 'show', 'actor' ), true ) ) ? 'show' : $type;
switch ( $type ) {
case 'show':
$substr = 'tt';
break;
case 'actor':
$substr = 'nm';
break;
default:
$substr = 'tt';
break;
}
// IMDB looks like tt123456 or nm12356
if ( substr( $imdb, 0, 2 ) !== $substr || ! is_numeric( substr( $imdb, 2 ) ) ) {
$result = false;
}
return $result;
}
}
new LWTV_Debug();
require_once 'actors.php';
require_once 'characters.php';
require_once 'shows.php';
require_once 'queers.php';
|
<script>
import axios from "axios";
import {onMount} from "svelte"
import {handleCloseModal} from "../hooks.js"
import CloseSrc from '../../public/icons/close_24.svg';
import { isAddList, pathname, API_URL, allLists, inProgressLists, doneLists } from "../store.js";
import Calendar from "./Calendar.svelte";
let selectedDate = null
pathname.set(window.location.pathname)
let date = new Date()
let initialValue = {
name: "",
completed: false,
dueBy: new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString()
}
console.log(initialValue)
function handleInput(e) {
const name = e.target.name
let value
if (e.target.type === "checkbox") {
value = e.target.checked
} else if (e.target.type === "date") {
value = e.target.value
} else {
value = e.target.value
}
initialValue[name] = value
// console.log(initialValue)
}
function handleCreateFormSubmit(event) {
event.preventDefault();
axios.post(API_URL + "api/v1/to_do_list", initialValue)
.then(res => {
const newList = res.data["list"]
if (pathname === '/completed' && newList.completed === true) {
doneLists.update((currentLists ) => [...currentLists, newList])
} else if (pathname === '/in-progress' && newList.completed === false) {
inProgressLists.update((currentLists ) => [...currentLists, newList])
} else {
allLists.update((currentLists) => [...currentLists, newList])
}
})
.catch(error => console.log(error))
handleCloseAddList()
initialValue = {
name: "",
completed: false,
dueBy: new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString()
}
}
$: disabled = initialValue.name === "" ? true : false
// import { onMount } from "svelte"
// onMount(() => {
// console.log(disabled, initialValue.name);
// });
function handleCloseAddList() {
$isAddList = false
}
let addFormRef
onMount(() => {
const unsubscribe = handleCloseModal(
addFormRef, isAddList
)
return unsubscribe
})
</script>
<div class="modal-container">
<div class="modal-dialog" bind:this={addFormRef}>
<div class="pop-up-header">
<div class="header-title">Create a List!</div>
<button class="close-btn" on:click={handleCloseAddList} on:keydown={handleCloseAddList}>
<img src={CloseSrc} alt="close button"/>
</button>
</div>
<form class="list-form" on:submit={handleCreateFormSubmit}>
<div class="input-container">
<label for="list-name" class="input-label">List Name:</label>
<input
class="list-name-input"
id="list-name"
type="text"
name="name"
bind:value={initialValue.name}
placeholder="What are you going to do?"
on:input={handleInput}
/>
</div>
<div class="input-container">
<label for="due-by" class="input-label">Due Date:</label>
<input
class="date-input"
id="due-by"
type="date"
name="dueBy"
value={initialValue.dueBy.split("T")[0]}
on:input={handleInput}
/>
<!-- <Calendar
selectedDate={selectedDate}
handleInput={handleInput}
date={date}
/> -->
</div>
<div class="input-checkbox">
<label for="check-completed" class="check-label">Completed</label>
<input
class="checkbox-div"
type="checkbox"
name="completed"
bind:checked={initialValue.completed}
id="check-completed"
on:input={handleInput}
/>
</div>
<input type="submit" value="Add"class="add-list-btn" disabled={disabled} />
</form>
</div>
</div>
<style></style>
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BirdMovementScript : MonoBehaviour
{
[SerializeField] private float moveSpeed = 5.0f;
[SerializeField] private float jumpForce = 5.0f;
[SerializeField] private float decelerationSpeed = 5.0f;
[SerializeField] private float increasedMassFactor = 3.0f;
[SerializeField] private float speedChangeThreshold = 2.0f;
[SerializeField] private GameObject MainCamera;
private Rigidbody2D rb;
private float horizontalMovement = 0f;
private float originalMass;
private Vector2 previousVelocity;
void Start()
{
rb = GetComponent<Rigidbody2D>();
originalMass = rb.mass;
}
void Update()
{
HandleMovementInput();
HandleMassInput();
}
void FixedUpdate()
{
HandleHorizontalMovement();
TrackSpeedChange();
}
private void HandleMovementInput()
{
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
horizontalMovement = -1;
}
else if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
horizontalMovement = 1;
}
else
{
horizontalMovement = 0;
}
if (Input.GetKeyUp(KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow) ||
Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D))
{
Jump();
}
}
private void HandleMassInput()
{
if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow))
{
rb.mass *= increasedMassFactor;
}
else if (Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.DownArrow))
{
rb.mass = originalMass;
}
}
private void HandleHorizontalMovement()
{
if (horizontalMovement != 0)
{
rb.velocity = new Vector2(horizontalMovement * moveSpeed, rb.velocity.y);
}
else if (rb.velocity.x != 0)
{
float deceleration = decelerationSpeed * Time.fixedDeltaTime * Mathf.Sign(rb.velocity.x);
if (Mathf.Abs(deceleration) >= Mathf.Abs(rb.velocity.x))
{
rb.velocity = new Vector2(0, rb.velocity.y);
}
else
{
rb.velocity = new Vector2(rb.velocity.x - deceleration, rb.velocity.y);
}
}
}
private void Jump()
{
rb.velocity = new Vector2(rb.velocity.x, 0);
rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
}
private void TrackSpeedChange()
{
Vector2 currentVelocity = rb.velocity;
float speedDifference = (currentVelocity - previousVelocity).magnitude;
if (speedDifference >= speedChangeThreshold)
{
Debug.Log("Significant speed change detected: " + speedDifference);
CameraShake script = MainCamera.GetComponent<CameraShake>();
if (script != null)
{
script.sShake(speedDifference/10);
}
}
previousVelocity = currentVelocity;
}
}
|
import React, { useMemo } from 'react';
import { getShapeInfo } from '../../lib/utils';
const LeftSideBar = ({ allShapes }) => {
const memoizedShapes = useMemo(
() => (
<section className='hidden bg-[#1F2937] md:flex flex-col w-[200px] h-full select-none overflow-y-auto pb-20'>
<h3 className='px-5 py-4 text-xs uppercase border-b pb-1 text-center'>
Layers
</h3>
<div className='flex flex-col'>
{allShapes?.map((shape) => {
const info = getShapeInfo(shape[1]?.type);
return (
<div
key={shape[1]?.objectId}
className='group my-1 flex items-center gap-2 px-5 py-2.5'
>
<img src={info?.icon} alt='Layer' width={16} height={16} />
<h3 className='text-sm font-semibold capitalize'>
{info.name}
</h3>
</div>
);
})}
</div>
</section>
),
[allShapes?.length]
);
return memoizedShapes;
};
export default LeftSideBar;
|
<template>
<div>
<Menu as="div" class="relative">
<MenuButton
v-slot="{ open }"
class="flex items-center justify-center p-1 text-gray-400 rounded-full"
>
<transition mode="out-in" name="fade">
<Icon v-if="open" name="bi:x" size="20" />
<Icon v-else name="bi:three-dots-vertical" size="20" />
</transition>
</MenuButton>
<transition name="menu">
<MenuItems
class="absolute right-0 p-2 mt-2 space-y-2 origin-top-right bg-white divide-y rounded-lg shadow dark:divide-gray-600 dark:bg-slate-700 w-52"
>
<div class="space-y-1">
<MenuItem v-slot="{ active }">
<button
@click="$refs.editFile.openModal(document)"
:class="[active ? 'bg-primary text-white' : 'text-gray-500 dark:text-gray-300']"
class="w-full flex justify-start items-center space-x-3 text-sm p-2.5 rounded-md transition-all"
type="button"
>
<Icon name="bi:pen" size="15" />
<span>Edit</span>
</button>
</MenuItem>
<MenuItem v-slot="{ active }">
<button
@click="$refs.fileDetails.openModal(document)"
:class="[active ? 'bg-primary text-white' : 'text-gray-500 dark:text-gray-300']"
class="w-full flex justify-start items-center space-x-3 text-sm p-2.5 rounded-md transition-all"
type="button"
>
<Icon name="bi:box-arrow-in-up-right" size="15" />
<span>View Details</span>
</button>
</MenuItem>
</div>
<div class="pt-2">
<MenuItem v-slot="{ active }">
<button
@click="deleteDoc()"
:class="[active ? 'bg-red-50 text-red-500' : 'text-gray-500 dark:text-gray-300']"
class="w-full flex justify-start items-center space-x-3 text-sm p-2.5 rounded-md transition-all"
type="button"
>
<Icon name="bi:trash3" size="15" />
<span>Delete</span>
</button>
</MenuItem>
</div>
</MenuItems>
</transition>
</Menu>
<!-- File details action -->
<FileDetails ref="fileDetails" />
<!-- File Edit details action -->
<EditFile ref="editFile" />
</div>
</template>
<script setup>
import { Menu, MenuButton, MenuItems, MenuItem } from "@headlessui/vue";
// declare props
const props = defineProps({
document: {
required: true,
type: Object,
},
});
// bring in function used to removedoc
const { removeDocument } = useDocument();
const deleteDoc = async () => {
let c = confirm("Are you sure?");
if (!c) return;
await removeDocument(props.document.id);
};
</script>
<style></style>
|
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const { createCanvas, loadImage } = require("canvas");
const { writeFileSync } = require("fs");
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var receiptsRouter = require("./routes/receipts");
var categoriesRouter = require("./routes/categories");
var reportsRouter = require("./routes/reports");
var imagesRouter = require("./routes/images");
var accountsRouter = require("./routes/accounts");
var wageTypeRouter = require("./routes/wage-types");
var chargeTypeRouter = require("./routes/charge-types");
var retailersRouter = require("./routes/retailers");
var currenciesRouter = require("./routes/currencies");
var cors = require("cors");
const cv = require("opencv-sigge");
const fs = require('fs');
var app = express();
const Tesseract = require('tesseract.js')
const extractDataFromReceipt = () => {
const imageFile = './kvitto.jpg';
const imageBuffer = fs.readFileSync(imageFile);
Tesseract.recognize(imageFile)
.then(result => {
console.log(result.text);
});
}
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(cors({ origin: true }));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/receipts", receiptsRouter);
app.use("/reports", reportsRouter);
app.use("/images", imagesRouter);
app.use("/categories", categoriesRouter);
app.use("/currencies", currenciesRouter);
app.use("/accounts", accountsRouter);
app.use("/wage-types", wageTypeRouter);
app.use("/retailers", retailersRouter);
app.use("/charge-types", chargeTypeRouter);
app.use(function (req, res, next) {
next(createError(404));
});
app.use(function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<!-- <ul id="friends"></ul> -->
<body>
<div class="container">
<table id="friends" class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>用户名</th>
<th>家乡</th>
<th>性别</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="row">
<form name="friendForm">
<div class="form-group">
<label for="nameInput">用户名</label>
<input type="text" required name="nameInput" class="form-control" id="nameInput" placeholder="请输入用户名">
</div>
<div class="form-group">
<label for="hometownInput">家乡</label>
<input type="text" required name="hometownInput" class="form-control" id="hometownInput" placeholder="请输入家乡">
</div>
<div class="checkbox">
<label>
<input type="radio" checked="checked" name="sex" value="男">男
</label>
<label>
<input type="radio" name="sex" value="女">女
</label>
</div>
<button type="submit" class="btn btn-default">添加</button>
</form>
</div>
</div>
<script>
// const friends=[{
// name:'徐狗',
// hometown:'上饶',
// sex:'男'
// },
// {
// name:'狗子',
// hometown:'抚州',
// sex:'animal'
// },
// {
// name:'丁狗',
// hometown:'瑞金',
// sex:'男'
// },
// {
// name:'涂狗',
// hometown:'中国',
// sex:'男'
// }
// ];
// window.localStorage.setItem('friends-info',JSON.stringify(friends));
window.onload=function(){
function renderFriend(o,i){
return `<tr>
<td>${i}</td>
<td>${o.name}</td>
<td>${o.hometown}</td>
<td>${o.sex}</td>
</tr>`
}
const friends=JSON.parse(localStorage.getItem('friends-info'));
const oUL=document.querySelector('#friends tbody')
document
.forms['friendForm']
.addEventListener('submit',(event)=>{
event.preventDefault();
const name=document.forms['friendForm']["nameInput"].value;
const hometown=document.forms['friendForm']["hometownInput"].value;
const sex=document.forms['friendForm']["sex"].value;
// console.log(name);
console.log(name,hometown,sex);
let o ={name,hometown,sex};
friends.push(o);
localStorage.setItem('friends-info',JSON.stringify(friends));
oUL.innerHTML += renderFriend(o,friends.length+1);
})
// console.log(typeof friends);
let i=0;
for(let friend of friends){
i++
//es6字符串模板符号
oUL.innerHTML += renderFriend(friend,i);
}
}
</script>
</body>
</html>
|
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 알파벳 개수만큼 arr 배열 생성하고
// 알파벳 번호인 인덱스에 ++
String input = sc.next().toUpperCase(); // 대문자로 바꿔주기
int[] arr = new int[26];
// 이중 for문
for (int i = 0; i < input.length(); i++) {
arr[input.charAt(i) - 'A']++; // 'A'가 65이므로, 만약, A일 경우 65-65=0 -> 0번 인덱스에 들어가게 됨.
}
// for문 돌면서 max가 바뀌거나, max와 같은 수가 나오면? cnt++
int max = -1; // 배열은 0부터 시작이므로 초기 max값을 -1로 잡기
char result = '?';
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
result = (char) (i + 'A');
} else if (arr[i] == max) {
result = '?';
}
}
System.out.println(result);
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef __MPLANE_EXTERNAL_IO_H__
#define __MPLANE_EXTERNAL_IO_H__
#include <stdbool.h>
#include <stdint.h>
#include <unistd.h>
#include "MplaneTypes.h"
/** @struct input_s
* @brief Struct representing an input IO
*
* This struct is used to represent an input IO port on the O-RU.
*/
typedef struct input_s {
const char* name;
uint8_t port_in;
bool* line_in;
} input_t;
/** @struct output_s
* @brief Struct representing an output IO
*
* This struct is used to represent an output IO port on the O-RU.
*/
typedef struct output_s {
const char* name;
uint8_t port_out;
} output_t;
/** @struct output_s
* @brief Struct containing a setting to be applied to an output IO
*
* This struct contains a setting, 1 or 0, to an output IO port on the O-RU.
*/
typedef struct output_setting_s {
const char* name;
bool* line_out;
} output_setting_t;
/**
* @struct external_io_s
* @brief Struct for retrieving IO information from a io port
*
* The struct pointers should be set according to the type of the gpio.
* Only one of the pointers should be set for each external_io_t instance.
* If it is an input pin, `input` should be set.
* If it is an output port, `out_setting` should be set.
*/
typedef struct external_io_s {
input_t* input;
output_t* output;
output_setting_t* out_setting;
} external_io_t;
/**
* @defgroup ExternalIOFunctions O-RAN ExternalIO Functions
* @brief External IO functions - O-RAN WG4 M-Plane Spec Chapter 14.5
*
* An O-RU may have any number of External IO ports, e.g. GPIO pins. The
* ExternalIO M-Plane module monitors and controls the ports.
*/
/**
* @brief For inputs, sets the parameter `line_in` with the value of the port
* specified by `name`. For outputs, sets the parameter `line_out` with
* the value of the port specified by `name`.
*
* @param io The struct mutated by this function.
*
* @retval halmplane_error_e::NONE if the external IO value is found
* @retval halmplane_error_e::UNAVAILABLE if the external IO is not found
*
* @ingroup ExternalIOFunctions
*/
halmplane_error_t halmplane_get_io_value(external_io_t* io);
/**
* @brief Sets the output of the port to the specified value.
*
* @param out_setting: The settings applied by this function.
*
* @retval halmplane_error_e::NONE if the external IO value is set
* @retval halmplane_error_e::UNAVAILABLE if the external IO is not set
*
* @ingroup ExternalIOFunctions
*/
halmplane_error_t halmplane_set_io_value(output_setting_t* out_setting);
#endif //__MPLANE_EXTERNAL_IO_H__
|
<html>
<h1>
Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones 2023 Best Book
</h1>
<p>
Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones is a self-help book by James Clear, published in 2018. The book has been translated into more than 40 languages and has sold over 5 million copies worldwide.
In Atomic Habits, Clear argues that small changes can lead to big results over time. He calls these small changes "atomic habits." He also provides a framework for building good habits and breaking bad ones.
<a href="https://amzn.to/3Q9lVVN">Ckeck On Amazon</a>
Clear's framework is based on four laws of behavior change:
Make it obvious. The more visible a cue is, the more likely you are to notice it and act on it.
Make it attractive. The more rewarding a habit is, the more likely you are to stick with it.
Make it easy. The easier a habit is to do, the more likely you are to do it.
Make it satisfying. The more satisfied you are with the outcome of a habit, the more likely you are to repeat it.
Clear provides a number of practical strategies for applying these laws to your own life. For example, he suggests:
Creating a habit stack. This is a series of two or more habits that you chain together. For example, you might start your day by making your bed, brushing your teeth, and reading for five minutes.
Using a habit tracker. This is a simple tool that can help you stay on track with your habits.
Finding an accountability partner. This is someone who can support you on your journey and help you stay motivated.
Atomic Habits is a well-written and informative book that can help you make lasting changes in your life. It is based on sound science and provides practical advice that you can implement immediately.
Here are some of the key takeaways from Atomic Habits:
Habits are the compound interest of self-improvement. Small changes can lead to big results over time.
The problem with most habit-change advice is that it's too focused on motivation. Motivation is fleeting, but habits are persistent.
The key to changing your habits is to focus on your systems, not your goals. Your systems are the processes and routines that you follow every day.
The four laws of behavior change are:
Make it obvious.
Make it attractive.
Make it easy.
Make it satisfying.
You can use these laws to create new habits and break old ones.
Atomic Habits is a great book for anyone who wants to make lasting changes in their life. It is full of practical advice that you can implement immediately.
</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/1cuxg1YluOk?si=F0fCcVKoDuKI0-TI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
<a href="https://amzn.to/3Q9lVVN">Ckeck On Amazon</a>
<p>
Atomic Habits is a self-help book by James Clear that teaches readers how to build good habits and break bad ones. The book is based on the premise that small, incremental changes can lead to big results over time.
Clear's framework for habit change is based on four laws of behavior:
Make it obvious. The more visible a cue is, the more likely you are to notice it and act on it. For example, if you want to drink more water, keep a water bottle on your desk or in your car.
Make it attractive. The more rewarding a habit is, the more likely you are to stick with it. For example, if you want to exercise regularly, find an activity that you enjoy and listen to music or podcasts while you do it.
Make it easy. The easier a habit is to do, the more likely you are to do it. For example, if you want to read more, keep a book on your bedside table so you can easily pick it up before bed.
Make it satisfying. The more satisfied you are with the outcome of a habit, the more likely you are to repeat it. For example, if you want to eat healthier, cook meals at home that you enjoy eating.
Clear also provides a number of practical strategies for applying these laws to your own life. For example, he suggests:
Creating a habit stack. This is a series of two or more habits that you chain together. For example, you might start your day by making your bed, brushing your teeth, and reading for five minutes.
Using a habit tracker. This is a simple tool that can help you stay on track with your habits.
Finding an accountability partner. This is someone who can support you on your journey and help you stay motivated.
Atomic Habits is a well-written and informative book that can help you make lasting changes in your life. It is based on sound science and provides practical advice that you can implement immediately.
Here are some examples of how you can use the four laws of behavior change to build good habits and break bad ones:
Make it obvious. If you want to start exercising regularly, put your workout clothes out the night before so you can easily put them on in the morning. If you want to eat healthier, keep a bowl of fruit on the counter so you're more likely to grab it for a snack.
Make it attractive. If you want to read more, find books that you're interested in and set aside time each day to read. If you want to save more money, set a financial goal and track your progress over time.
Make it easy. If you want to meditate every day, download a meditation app and set a reminder on your phone. If you want to go to bed earlier, set a bedtime alarm and put your phone away an hour before bed.
Make it satisfying. After you finish a workout, reward yourself with a healthy snack or a relaxing activity. After you save a certain amount of money, treat yourself to something you've been wanting.
By following these simple tips, you can start making small changes that will lead to big results over time.
</p>
<a href="https://amzn.to/3Q9lVVN">Ckeck On Amazon</a>
<p>
Atomic Habits is a self-help book by James Clear that teaches readers how to build good habits and break bad ones. The book is based on the premise that small, incremental changes can lead to big results over time.
Clear's framework for habit change is based on four laws of behavior:
Make it obvious. The more visible a cue is, the more likely you are to notice it and act on it. For example, if you want to drink more water, keep a water bottle on your desk or in your car.
Make it attractive. The more rewarding a habit is, the more likely you are to stick with it. For example, if you want to exercise regularly, find an activity that you enjoy and listen to music or podcasts while you do it.
Make it easy. The easier a habit is to do, the more likely you are to do it. For example, if you want to read more, keep a book on your bedside table so you can easily pick it up before bed.
Make it satisfying. The more satisfied you are with the outcome of a habit, the more likely you are to repeat it. For example, if you want to eat healthier, cook meals at home that you enjoy eating.
Clear also provides a number of practical strategies for applying these laws to your own life. For example, he suggests:
Creating a habit stack. This is a series of two or more habits that you chain together. For example, you might start your day by making your bed, brushing your teeth, and reading for five minutes.
Using a habit tracker. This is a simple tool that can help you stay on track with your habits.
Finding an accountability partner. This is someone who can support you on your journey and help you stay motivated.
Atomic Habits is a well-written and informative book that can help you make lasting changes in your life. It is based on sound science and provides practical advice that you can implement immediately.
Here are some additional tips for building good habits and breaking bad ones:
Start small. Don't try to change too many habits at once. Start with one or two habits that you really want to change and focus on those. Once you have those habits under control, you can move on to others.
Be consistent. The key to habit change is consistency. Even if you can only do a small amount each day, it's important to be consistent.
Don't beat yourself up if you slip up. Everyone slips up from time to time. The important thing is to pick yourself up and keep going.
Remember, habit change takes time and effort. But if you are consistent, you can make lasting changes in your life.
</p>
<a href="https://amzn.to/3Q9lVVN">Ckeck On Amazon</a>
<p>
Yes, Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones is a bestseller on Amazon. It has been ranked #1 in the Self-Help category for over 300 weeks. It has also been translated into over 40 languages and has sold over 5 million copies worldwide.
Atomic Habits is popular because it provides a practical and actionable framework for habit change. The book is well-written and easy to understand, and it is full of examples and stories from real people who have used the author's methods to change their own lives.
If you are looking for a book to help you build good habits and break bad ones, I highly recommend Atomic Habits. It is one of the best books on the topic that I have read.
</p>
</html>
|
import { useState, useEffect } from 'react';
import Section from 'components/Section';
import Statistics from 'components/Statistics';
import FeedbackOptions from 'components/FeedbackOptions';
import Notification from 'components/Notification';
import Container from './app.styled';
export const App = () => {
const [good, setGood] = useState(0);
const [neutral, setNeutral] = useState(0);
const [bad, setBad] = useState(0);
const [total, setTotal] = useState(0);
const [positiveFeedback, setPositiveFeedback] = useState(0);
const countTotalFeedback = () => {
setTotal(good + neutral + bad);
};
const countPositiveFeedbackPercentage = () =>
setPositiveFeedback(Number(((good / total) * 100).toFixed(0)));
useEffect(() => {
countTotalFeedback();
countPositiveFeedbackPercentage();
});
const onLeaveFeedback = e => {
switch (e) {
case 'good':
setGood(prevState => prevState + 1);
return;
case 'neutral':
setNeutral(prevState => prevState + 1);
return;
case 'bad':
setBad(prevState => prevState + 1);
return;
default:
return;
}
};
const options = {
good,
neutral,
bad,
};
return (
<Container>
<Section title="Please leave feedback">
<FeedbackOptions
options={Object.keys(options)}
onLeaveFeedback={onLeaveFeedback}
/>
</Section>
<Section title="Statistics">
{total ? (
<Statistics
good={good}
neutral={neutral}
bad={bad}
total={total}
positivePercentage={positiveFeedback}
/>
) : (
<Notification message="There is no feedback" />
)}
</Section>
</Container>
);
};
|
// 5-payment.test.js
const sinon = require('sinon');
const chai = require('chai');
const expect = chai.expect;
const sendPaymentRequestToApi = require('./5-payment');
const Utils = require('./utils');
describe('sendPaymentRequestToApi', function () {
let consoleLogSpy;
beforeEach(function () {
// Create a spy for console.log before each test
consoleLogSpy = sinon.spy(console, 'log');
});
afterEach(function () {
// Restore the spy after each test
consoleLogSpy.restore();
});
it('should log the correct message for totalAmount = 100 and totalShipping = 20', function () {
// Call the function
sendPaymentRequestToApi(100, 20);
// Verify that console.log is called with the correct message
expect(consoleLogSpy.calledWith('The total is: 120')).to.be.true;
// Verify that console.log is only called once
expect(consoleLogSpy.calledOnce).to.be.true;
});
it('should log the correct message for totalAmount = 10 and totalShipping = 10', function () {
// Call the function
sendPaymentRequestToApi(10, 10);
// Verify that console.log is called with the correct message
expect(consoleLogSpy.calledWith('The total is: 20')).to.be.true;
// Verify that console.log is only called once
expect(consoleLogSpy.calledOnce).to.be.true;
});
});
|
import { useEffect, useState } from 'react';
import React from 'react';
import './css/Header.css';
function Header() {
const [word, setWord] = useState('');
const [wordIndex, setWordIndex] = useState(0);
const [letterIndex, setLetterIndex] = useState(0);
const [isEndOfWord, setIsEndOfWord] = useState(false); // New state to track end of word
const addings = ["the free thinkers", "the innovators", "the creators", "you."];
useEffect(() => {
const typeLetter = () => {
const currentWord = addings[wordIndex];
setWord(currentWord.slice(0, letterIndex + 1));
if (letterIndex < currentWord.length - 1) {
setLetterIndex(letterIndex + 1);
} else {
setIsEndOfWord(true); // Reached the end of the word, trigger pause
}
};
const interval = setInterval(() => {
if (!isEndOfWord) {
typeLetter(); // Continue typing
} else {
// Pause for a second at the end of the word
setTimeout(() => {
setWordIndex((wordIndex + 1) % addings.length); // Move to the next word or loop back
setLetterIndex(0); // Reset for the next word
setIsEndOfWord(false); // Reset the end of word flag
}, 1500);
clearInterval(interval); // Clear the typing interval during the pause
}
}, 100);
return () => clearInterval(interval);
}, [wordIndex, letterIndex, isEndOfWord]); // Include isEndOfWord in dependencies
return (
<div className='header-container'>
<div className="treehouse-container">
<div className="treehouse-content">
<img src='treehouse2.png' alt="Treehouse" />
</div>
<div className="badass-words">
<h1>For {word}<span className="cursor">|</span></h1>
</div>
</div>
</div>
);
}
export default Header;
|
import { observer } from "mobx-react-lite";
import { useEffect, useState } from "react";
import { Button, Divider, Dropdown, Header, Segment } from "semantic-ui-react";
import { useStore } from "../../../app/stores/store";
import { NavLink, useHistory, useParams } from 'react-router-dom';
import LoadingComponent from "../../../app/layout/LoadingComponents";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import CustomTextInput from "../../../app/common/form/customTextInput";
import { UserUpdateFormValues } from "../../../app/models/user";
import ToastHelper from "../../../app/helpers/ToastHelper";
import { action } from "mobx";
import CustomMultipleSelectedTextInput from "../../../app/common/form/customMultipleSelectedTextInput";
export default observer(function UserForm() {
const history = useHistory();
const { userStore } = useStore();
const { updateUser, loadUser, loadingInitial, setReturnModel, dropdownOptions } = userStore;
const { id } = useParams<{ id: string }>();
const [user, setUser] = useState<UserUpdateFormValues>(new UserUpdateFormValues());
const validationSchema = Yup.object({
employeeNo: Yup.string().required("Sicil boş geçilemez"),
name: Yup.string().required("İsim boş geçilemez"),
surname: Yup.string().required("Soyad boş geçilemez"),
mail: Yup.string().required("Email kısmı boş geçilemez").email("Email geçerli formatta giriniz"),
operationClaimIds: Yup.array()
});
//explanation mark means it can be undefined
useEffect(() => {
if (id) loadUser(id).then(user => setUser(new UserUpdateFormValues(user)))
}, [id, loadUser]);
function handleFormSubmit(user: UserUpdateFormValues, setSubmitting: any) {
if (!user.id) {
history.push('/users');
ToastHelper.ErrorToast("Kullanıcı seçimi yapmanız gerekiyor!")
}
else {
updateUser(user).then((userReturnModel) => {
setReturnModel(userReturnModel);
if (userReturnModel?.status !== 1)
ToastHelper.ErrorToast(userReturnModel?.message)
else {
setSubmitting(false);
}
})
}
}
if (loadingInitial) return <LoadingComponent content="Kullanıcı işlemleri sayfası yükleniyor.Lütfen bekleyiniz..." />
return (
<Segment style={{ height: window.innerHeight * 0.75 }} clearing>
<Header dividing content={"Kullanıcı Bilgileri"} size="huge" sub color="black" />
<br></br>
<Formik
enableReinitialize
initialValues={user}
onSubmit={(values, { setSubmitting }) => {
handleFormSubmit(values, setSubmitting);
}}
validationSchema={validationSchema}
>
{({ handleSubmit, isValid, isSubmitting, dirty }) => (
<Form className="ui form" onSubmit={handleSubmit} autoComplete="off">
<CustomTextInput name="employeeNo" placeholder="Sicil" disabled />
<CustomTextInput name="name" placeholder="İsim" />
<CustomTextInput name="surname" placeholder="Soyisim" />
<CustomTextInput name="mail" placeholder="Mail" />
<br></br>
<Header dividing content={"Yetki"} size="huge" sub color="black" />
<br></br>
<CustomMultipleSelectedTextInput
name="operationClaimIds"
placeholder="Yetkiler"
fluid={true}
search={true}
selection={true}
options={dropdownOptions}
// onChange={(event,data) => operationDropdownChange(event,data)}
/>
<br></br>
<Button
disabled={isSubmitting || !dirty || !isValid}
loading={isSubmitting}
floated="right"
positive type="submit"
content="Kaydet" />
<Button
as={NavLink} to="/users"
floated="right"
type="button"
content="Geri" />
</Form>
)}
</Formik>
</Segment>
)
})
|
<template lang="pug">
div(:class="$style.archive" ref="wrapper" :style="styles")
div(@click="selectTab($event, 1)" @mouseover="mouseOver($event, 1)" @mouseleave="mouseLeave" :class="[$style.tab, {[$style.active]: isActive === 1}]")
div(:class="$style.inner")
span Categories
div(:class="$style.bg")
transition(@before-enter="beforeEnter" @enter="enter" @before-leave="beforeLeave" @leave="leave")
ul(:class="[$style.content, $style.categories]" v-if="isActive === 1")
li(v-for="category in categories" :key="category.slug")
nuxt-link(:to="'/blog/category/' + category.slug")
span(:class="$style.name") {{category.name}}
span(:class="$style.num") {{category.posts.length}}
div(@click="selectTab($event, 2)" @mouseover="mouseOver($event, 2)" @mouseleave="mouseLeave" :class="[$style.tab, {[$style.active]: isActive === 2}]")
div(:class="$style.inner")
span Tags
div(:class="$style.bg")
transition(@before-enter="beforeEnter" @enter="enter" @before-leave="beforeLeave" @leave="leave")
div(:class="[$style.content, $style.tags]" v-if="isActive === 2")
div(:class="[$style.wrapper]")
nuxt-link(v-for="tag in tags" :to="'/blog/tag/' + tag.slug" :key="tag.slug")
span(:class="$style.name") {{tag.name}}
span(:class="$style.num") {{tag.posts.length}}
div(@click="selectTab($event, 3)" @mouseover="mouseOver($event, 3)" @mouseleave="mouseLeave" :class="[$style.tab, {[$style.active]: isActive === 3}]")
div(:class="$style.inner")
span Yearly
div(:class="$style.bg")
transition(@before-enter="beforeEnter" @enter="enter" @before-leave="beforeLeave" @leave="leave")
ul(:class="[$style.content, $style.yearly]" v-if="isActive === 3")
li(v-for="(posts, year) in yearly")
nuxt-link(:to="'/blog/' + year")
span(:class="$style.name") {{year}}
span(:class="$style.num") {{posts.length}}
div(@click="selectTab($event, 4)" @mouseover="mouseOver($event, 4)" @mouseleave="mouseLeave" :class="[$style.tab, {[$style.active]: isActive === 4}]")
div(:class="$style.inner")
span Monthly
div(:class="$style.bg")
transition(@before-enter="beforeEnter" @enter="enter" @before-leave="beforeLeave" @leave="leave")
div(:class="[$style.content, $style.monthly]" v-if="isActive === 4")
ul(v-for="(monthList, year) in monthly")
li(v-for="(posts, month) in monthList")
nuxt-link(:to="'/blog/' + year + '/' + month")
span(:class="$style.year") {{year}}
span(:class="$style.month") {{month}}
</template>
<script>
import { tags, categories, yearly, monthly } from '../../contents/blog/archives.json'
export default {
components: {
},
data () {
return {
tags,
categories,
yearly,
monthly,
isActive: 0,
activeTabWidth: 0,
activeTabLeftPosition: 0,
style: {
tabWidth: 0,
tabLeftPosition: 0
}
}
},
computed: {
styles () {
return {
'--tabWidth': this.style.tabWidth + 'px',
'--tabLeftPosition': this.style.tabLeftPosition + 'px'
}
}
},
watch: {
'$route' (to, from) {
this.isActive = 0
}
},
mounted () {
this.$nextTick(() => {
const mediaQuery = window.matchMedia(this.$style.small)
this.tabAlignment(mediaQuery)
mediaQuery.addListener(this.tabAlignment)
})
},
methods: {
tabAlignment (mediaQuery) {
if (!mediaQuery) {
return
}
const tabs = this.$el.getElementsByClassName(this.$style.tab);
[...tabs].reduce((leftPos, el) => {
el.style.left = leftPos + 'px'
leftPos += Math.ceil(el.offsetWidth)
return leftPos
}, 0)
},
selectTab (event, num) {
const element = event.path[0]
const wrapperLeft = this.$refs.wrapper.getBoundingClientRect().left
const elementLeft = element.getBoundingClientRect().left
if (this.isActive === num) {
this.isActive = 0
this.activeTabWidth = 0
this.activeTabLeftPosition = 0
} else {
this.isActive = num
this.activeTabWidth = element.offsetWidth
this.activeTabLeftPosition = elementLeft - wrapperLeft
}
},
mouseOver (event, num) {
const element = event.path[0]
const wrapperLeft = this.$refs.wrapper.getBoundingClientRect().left
const elementLeft = element.getBoundingClientRect().left
this.style.tabWidth = element.offsetWidth
this.style.tabLeftPosition = elementLeft - wrapperLeft
},
mouseLeave () {
this.style.tabWidth = this.activeTabWidth
this.style.tabLeftPosition = this.activeTabLeftPosition
},
beforeEnter (el) {
el.style.height = '0'
},
enter (el) {
el.style.height = el.scrollHeight + 'px'
},
beforeLeave (el) {
el.style.height = el.scrollHeight + 'px'
},
leave (el) {
el.style.height = '0'
}
}
}
</script>
<style lang="stylus" module>
.archive
position relative
font-family Rajdhani, sans-serif
width 90%
margin 10px auto
padding-top 34px
+breakpoint(small)
padding-top 0
&:before
content ''
position absolute
top 34px
left var(--tabLeftPosition)
width var(--tabWidth)
height 2px
background #000
transition 0.3s
+breakpoint(small)
background transparent
&:after
display block
content ''
width 100%
border-bottom 1px solid #ddd
.tab
top 0
display table
overflow hidden
position absolute
cursor pointer
+breakpoint(small)
display block
position static
.inner
curor pointer
pointer-events none
position relative
font-size(15px)
font-weight 500
padding 5px 15px 5px 5px
transition 0.3s
.bg
content ''
position absolute
display block
bottom 0px
left 0px
z-index: -1;
background #000
width 100%
height 100%
transform translateY(100%)
transition 0.2s
+breakpoint(small)
transform translateX(calc(-100% - 2px)) translateY(calc(100% - 2px))
span
position relative
padding-left 25px
&::before
transition: all 0.4s cubic-bezier(0.19, 1, 0.22, 1);
position absolute
left 4px
top 0
bottom: 0
margin-top auto
margin-bottom auto
content ''
position absolute
width 8px
height 2px
background-color #000
transform translateY(2px) rotate(45deg)
transform-origin 7px 1px
&::after
transition: all 0.4s cubic-bezier(0.19, 1, 0.22, 1);
position absolute
left 11px
top 0
bottom: 0
margin-top auto
margin-bottom auto
content ''
position absolute
width 8px
height 2px
background-color #000
transform translateY(2px) rotate(-45deg)
transform-origin 1px 1px
&:hover
.bg
+breakpoint(small)
transform translateX(0) translateY(calc(100% - 2px))
&.active
color #fff
.inner
.bg
transform translateY(0)
span
&::before
background #fff
transform translateY(-2px) rotate(-45deg)
&::after
background #fff
transform translateY(-2px) rotate(45deg)
.content
overflow hidden
.categories
li
height 35px
line-height 35px
&:not(:last-child)
border-bottom 1px solid #ddd
a
display flex
justify-content space-between
width 100%
height 100%
padding 0 5px
&:hover
background #f1f1f1
text-decoration none
.name
font-weight 600
color #000
font-size(14px)
.num
font-weight 400
margin-right 0
margin-left auto
color #aaa
font-size(13px)
.tags
.wrapper
display flex
flex-wrap wrap
margin 10px 0
a
display block
background #f1f1f1
height 25px
line-height 25px
padding 0 8px
margin 5px
&:hover
text-decoration none
background #ddd
.name
font-size(13px)
font-weight 500
color #000
margin-right 8px
.num
font-size(12px)
font-weight 400
color #aaa
.yearly
@extend .categories
.monthly
ul
display flex
margin 10px 0
li
margin 5px
width 38px
height 45px
background #f1f1f1
a
animateShatter()
display block
width 100%
height 100%
padding 5px
&:hover
text-decoration none
.year
color #fff
.year
display block
text-align center
font-size(12px)
line-height 12px
font-weight 500
color #aaa
transition 0.3s
.month
display block
text-align center
font-size(18px)
line-height 23px
font-weight 600
margin auto 0
</style>
<style lang="stylus" scoped>
.v-enter-active
transition height 0.4s ease-in-out 0.2s
animation-name js-accordion--anime__opend
animation-delay 0.4s
animation-duration 0.2s
animation-fill-mode both
.v-leave-active
transition height 0.4s ease-in-out
animation-name js-accordion--anime__closed
animation-duration 0.2s
animation-fill-mode both
@keyframes js-accordion--anime__opend
0%
opacity 0
100%
opacity 1
@keyframes js-accordion--anime__closed
0%
opacity 1
100%
opacity 0
</style>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.