text
stringlengths 184
4.48M
|
|---|
import CardTabela from "./CardTabela";
import {useState} from "react";
import axios from "axios";
interface Produto {
id: number;
nome: string;
avaliacao: number;
}
export default function Tabela() {
const [produto, setProduto] = useState("");
const [avaliacao, setAvaliacao] = useState<number | undefined>();
const [produtos, setProdutos] = useState<Produto[]>([]);
const [isLoading, setIsLoading] = useState(false)
const pesquisarProduto = () => {
const pesquisarProdutoAPI = async () => {
try {
setIsLoading(true);
const response = await axios.post(`http://localhost:5000/link`,
{
link : produto,
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const data = await response;
let novoProduto = {
id: produtos.length + 1,
nome: data.data.produto,
avaliacao: data.data.sentimento || 0
};
setProdutos((prevProdutos) => [...prevProdutos, novoProduto]);
setProduto("");
setAvaliacao(undefined);
} catch (error) {
// @ts-ignore
alert("Erro ao buscar produtos:"+error.response.data.message)
}finally {
setIsLoading(false);
}
};
pesquisarProdutoAPI();
};
return (
<div>
<div className="relative">
{isLoading && (
<div className="fixed inset-0 flex items-center justify-center z-50 bg-gray-900 bg-opacity-50">
<div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-gray-300"></div>
</div>
)}
</div>
<div className="relative bg-gray-900 p-5 rounded-lg h-6/12">
<input
type="text"
className="w-full border bg-gray-900 border-gray-300 p-2 rounded-lg mb-4"
placeholder="Digite seu produto..."
value={produto}
onChange={(e) => setProduto(e.target.value)}
/>
<button
className="bg-blue-600 text-white rounded-lg px-4 py-2"
onClick={pesquisarProduto}
>
Pesquisar
</button>
<table className={`w-full mt-10 ${produtos.length > 0 ? 'h-72' : 'h-6/12'}`}>
<thead>
<tr>
<th className="border p-2 py-4">Produto</th>
<th className="border p-2 py-4">Avaliação Média</th>
</tr>
</thead>
<tbody>
{produtos.map((produto) => (
<CardTabela
key={produto.id}
produto={produto.nome}
avaliacao={produto.avaliacao}
/>
))}
</tbody>
</table>
</div>
</div>
);
}
|
use std::fmt::Display;
use serde::{Deserialize, Serialize};
use crate::template::crypto_price::CryptoPrice;
use crate::template::heart::Heart;
use crate::template::meteo::Meteo;
use crate::template::rainbow::Rainbow;
use crate::template::text::Text;
use crate::template::Template;
pub mod bit;
pub mod template;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let yaml = std::fs::read_to_string("sequence.yaml")?;
let sequence: Sequence = serde_yaml::from_str(&yaml).unwrap();
println!("{:?}", sequence);
// No repeat is bugged for now
while sequence.repeat {
for step in &sequence.steps {
let template: Box<dyn Template> = match step.template {
Templates::Rainbow => Box::new(Rainbow {}),
Templates::Hearts => Box::new(Heart {}),
Templates::Text => Box::new(Text::new(step.text.clone().unwrap())),
Templates::Crypto => Box::new(CryptoPrice::new(step.tickers.clone().unwrap())),
Templates::HappyText => Box::new(crate::template::happy_text::HappyText::new(
step.text.clone().unwrap(),
)),
Templates::Meteo => Box::new(Meteo {}),
};
let message = template.render();
let string_message = serde_json::to_string(&message)?;
let address = "http://127.0.01:8000/".to_string() + &string_message;
let _resp = client.post(&address).send().await?;
tokio::time::sleep(tokio::time::Duration::from_secs(step.duration.into())).await;
}
}
Ok(())
}
#[derive(Serialize, Deserialize, Debug)]
struct Sequence {
repeat: bool,
steps: Vec<Step>,
}
#[derive(Serialize, Deserialize, Debug)]
struct Step {
template: Templates,
duration: u16,
text: Option<Vec<String>>,
tickers: Option<Vec<CryptoTickers>>,
}
#[derive(Serialize, Deserialize, Debug)]
enum Templates {
Rainbow,
Hearts,
Text,
Crypto,
HappyText,
Meteo,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum CryptoTickers {
Eth,
Btc,
Sol,
Bnb,
}
impl Display for CryptoTickers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CryptoTickers::Eth => write!(f, "ETH"),
CryptoTickers::Btc => write!(f, "BTC"),
CryptoTickers::Sol => write!(f, "SOL"),
CryptoTickers::Bnb => write!(f, "BNB"),
}
}
}
|
import {Avatar, Box, Button, Divider, Grid, List, ListItem, ListItemIcon, ListItemText, Paper, SxProps, Typography,} from '@mui/material';
import EmailIcon from '@mui/icons-material/Email';
import PhoneIcon from '@mui/icons-material/Phone';
import CakeIcon from '@mui/icons-material/Cake';
import WorkIcon from '@mui/icons-material/Work';
import SchoolIcon from '@mui/icons-material/School';
import {useLoggedUser} from '../../hooks/useCustomQuery';
import Navbar from "../../components/navbar/AppNavBar.tsx";
import {BACKGROUND_LIGHT, PRIMARY_COLOR} from '../../constants/theming.ts';
import {useEffect} from "react";
import {getCv} from "../../api/api.ts";
export default function ProfilePage() {
const {data: user} = useLoggedUser();
useEffect(() => {
console.log(user);
}, [user]);
const getInitials = (name: string | undefined) => {
return name ? name.split(' ').map(n => n[0]).join('').toUpperCase() : '';
};
const formatDate = (dateString: string | undefined) => {
// const options = {year: 'numeric', month: 'long', day: 'numeric'};
return dateString ? new Date(dateString).toLocaleDateString() : '';
};
const iconsSx: SxProps = {
color: PRIMARY_COLOR
};
return (
<>
<Box sx={{
display: 'flex',
flexDirection: 'column',
minHeight: '100vh', // Set to full viewport height
backgroundColor: BACKGROUND_LIGHT,
}}>
<Navbar/>
<Box sx={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
overflow: 'auto',
flexGrow: 1,
}}>
<Paper elevation={3} sx={{
width: '100%',
margin: 0,
borderRadius: 0,
backgroundColor: BACKGROUND_LIGHT,
backdropFilter: 'blur(30px)',
padding: '5vh',
boxSizing: 'border-box',
}}>
<Grid container spacing={2} alignItems="center" justifyContent="center">
<Grid item xs={12} sm={4} display="flex" justifyContent="center">
<Avatar sx={{
width: 120,
height: 120,
fontSize: '4rem',
background: 'radial-gradient(circle, rgba(54,220,154,1) 29%, rgba(197,53,236,1) 100%)'
}}>
{getInitials(user?.name)}
</Avatar>
</Grid>
<Grid item xs={12} sm={8}>
<Typography variant="h5" gutterBottom>{user?.name}</Typography>
<List>
<ListItem>
<ListItemIcon>
<EmailIcon sx={iconsSx}/>
</ListItemIcon>
<ListItemText primary={user?.email}/>
</ListItem>
<ListItem>
<ListItemIcon>
<PhoneIcon sx={iconsSx}/>
</ListItemIcon>
<ListItemText primary={user?.phoneNumber}/>
</ListItem>
<ListItem>
<ListItemIcon>
<CakeIcon sx={iconsSx}/>
</ListItemIcon>
<ListItemText primary={formatDate(user?.birthDate)}/>
</ListItem>
<ListItem>
<ListItemIcon>
<WorkIcon sx={iconsSx}/>
</ListItemIcon>
<ListItemText primary={user?.profile.currentTitle}/>
</ListItem>
</List>
</Grid>
</Grid>
<Divider sx={{my: 2}}/>
<Typography variant="h6" gutterBottom>Studies</Typography>
<List>
{user?.profile.studies.map((study) => (
<ListItem key={study.studyId.toString()}>
<ListItemIcon>
<SchoolIcon sx={iconsSx}/>
</ListItemIcon>
<ListItemText
primary={study.degree}
secondary={`${formatDate(study.startDate)} - ${formatDate(study.endDate)}, ${study.studyLocation}`}
/>
</ListItem>
))}
</List>
<Divider sx={{my: 2}}/>
<Typography variant="h6" gutterBottom>Experiences</Typography>
<List>
{user?.profile.experiences.map((exp) => (
<ListItem key={exp.experienceId.toString()}>
<ListItemText
primary={`${exp.company}, ${exp.position}`}
secondary={`${formatDate(exp.startDate)} - ${formatDate(exp.endDate)}`}
/>
<Typography variant="body2" sx={{mt: 1}}>
Skills: {exp.skills.map((skill) => skill.skillName).join(', ')}
</Typography>
</ListItem>
))}
</List>
<Button variant="outlined" onClick={() => {
console.log("Sending cv request");
user && getCv(user.userId);
}} sx={{
mt: 2,
color: PRIMARY_COLOR,
borderColor: PRIMARY_COLOR,
'&:hover': {
borderColor: PRIMARY_COLOR
}
}}>
See CV
</Button>
</Paper>
</Box>
</Box>
</>
);
}
|
## makeCluster
##
##' Create independant clusters from a sequence of (observed + random)
##' steps.
##'
##' There must be one and only one case per strata. In addition, the
##' sequences must be orderd in ascending order (there is no check on
##' this), and the case and strata should correspond to that order.
##'
##' It is only necessary to provide \code{nclust} to get at least that
##' many clusters (if possible). The argument \code{nloc} can be set
##' instead, if one wants exactly a number of successive steps in a
##' cluster (much faster computation).
##' @title Create independent clusters
##' @param seq A numeric, indicating the continuous sequences of
##' steps. See Details.
##' @param strata A numeric, indicating the strata of each observed
##' and random steps.
##' @param case A numeric, with 1 for observed steps and 0 for random
##' steps.
##' @param ndrop The number of steps to drop between each
##' cluster. They will be NAs in the resulting vector.
##' @param nclust The ideal number of clusters to obtain. See Details.
##' @param nstep The number of steps consisting in a single
##' cluster. See Details.
##' @return A vector of the same length as \code{seq}, \code{strata}
##' and \code{case}, with the cluster number for each step, and three
##' attributes giving the number of clusters (\code{nclust}), the
##' number of successive steps kept per cluster (\code{nstep}) and the
##' number of successive steps dropped between each cluster
##' (\code{ndrop}).
##' @author Mathieu Basille \email{basille@@ase-research.org}
##' @export
##' @examples
##' ## case (1 observed + 9 random)
##' case <- rep(rep(1:0, c(1, 9)), 100)
##' ## 100 stratas of 10 steps (1 observed + 9 random)
##' strata <- rep(1:100, each = 10)
##' ## 5 sequences of 20*10 steps
##' seq <- rep(1:5, each = 200)
##' head(data.frame(case, strata, seq), 22)
##' ## Make at least 15 clusters by dropping 2 steps between each of them
##' makeCluster(seq, strata, case, ndrop = 2, nclust = 15)
##' ## Same result with 'nstep = 7' direcly
##' makeCluster(seq, strata, case, ndrop = 2, nstep = 7)
makeCluster <- function(seq, strata, case, ndrop, nclust = NULL,
nstep = NULL)
{
## Check that there is exactly 1 case for each strata, else stop
tabcase <- table(case, strata)
if (any(tabcase["1", ] != 1))
stop("Some stratas with no or more than one case.")
## One and only one of 'nclust' or 'nstep' must be provided
if ((is.null(nclust) & is.null(nstep)) | (!is.null(nclust) &
!is.null(nstep)))
stop("One, and only one, of 'nclust' or 'nstep' must be provided.")
## Sub-function to create the clusters
cluster <- function(seq, strata, case, ndrop, nstep) {
## Create the pattern [(0*nstep),(NA*ndrop)]
pat <- rep(c(0, NA), times = c(nstep, ndrop))
## Initiate a counter
compt <- 0
## Initiate the 'cluster' vector
clust <- numeric()
## For each sequence, do:
for (i in unique(seq)) {
## How many steps (observed+random) per strata
## corresponding to this sequence?
tabi <- table(strata[seq == i])
## How many clusters can fit in this sequence? ('ceiling'
## because it suffices that a cluster starts)
maxi <- ceiling(sum(seq[case == 1] == i)/(nstep +
ndrop))
## If more than one cluster, repeat the pattern, and set
## the corresponding cluster number to each kept step; cut
## it to the number of cases
if (maxi > 1)
clusti <- (rep(pat, times = maxi) + rep(compt +
1:maxi, each = (nstep + ndrop)))[1:sum(seq[case ==
1] == i)]
## If only one cluster, add 'maxi' (1) to the counter, and
## repeat it as many times as there are cases
else clusti <- rep(compt + maxi, sum(seq[case ==
1] == i))
## Repeat the cluster/case given the number of steps and
## add it to the already existing vector of clusters
clust <- c(clust, rep(clusti, times = tabi))
## Increment the counter using the max number of clusters
compt <- compt + maxi
}
## Return the vector of clusters
return(clust)
}
## If 'clust' is not provided, use 'nstep' directly:
if (is.null(nclust))
clust <- cluster(seq = seq, strata = strata, case = case,
ndrop = ndrop, nstep = nstep)
## Else iterate 'nstep' in 'cluster' until the number of cluster
## is lower than
else {
## Automatic approximate 'nstep'
nstep <- floor(sum(case)/(nclust)) - ndrop
## If `nstep` is smaller than 1, use 1 (max number of clusters)
if (nstep < 1)
nstep <- 1
clust <- cluster(seq = seq, strata = strata, case = case,
ndrop = ndrop, nstep = nstep)
## If the number of clusters is equal or greater than the
## required one, iterate through increasing 'nstep'
if (max(clust, na.rm = TRUE) >= nclust) {
for (i in (nstep + 1):sum(case)) {
clusttmp <- cluster(seq = seq, strata = strata,
case = case, ndrop = ndrop, nstep = i)
## If the number of clusters is no more equal or
## greater than the required one, breaks
if (max(clusttmp, na.rm = TRUE) < nclust) {
break
}
## Else store 'clusttmp' and 'nstep' (and go to the
## next iteration)
else {
clust <- clusttmp
nstep <- i
}
}
}
## Else if the number of clusters is smaller than the required
## one, iterate through decreasing 'nstep'
else {
for (i in (nstep - 1):0) {
clusttmp <- cluster(seq = seq, strata = strata,
case = case, ndrop = ndrop, nstep = i)
## If the number of clusters is no more smaller than
## the required one, breaks
if (max(clusttmp, na.rm = TRUE) >= nclust) {
break
}
## Else store 'clusttmp' and 'nstep' (and go to the
## next iteration)
else {
clust <- clusttmp
nstep <- i
}
}
}
if (max(clust, na.rm = TRUE) < nclust)
stop("Impossible to return that many clusters. Try with a smaller 'nclust'.")
}
## Set 'nclust', 'nstep' and 'ndrop' attributes
attr(clust, "nclust") <- max(clust, na.rm = TRUE)
attr(clust, "nstep") <- nstep
attr(clust, "ndrop") <- ndrop
return(clust)
}
|
<?php
namespace App\Http\Controllers\Subadmin;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
class SubAdminProfileController extends Controller
{
/**
* Store a newly created resource in storage.
* Change password store
*/
public function store(Request $request)
{
$request->validate([
'old_password' => 'required|',
'new_password' => 'required|confirmed',
// 'confirm_password' => 'required|same:new_password',
]);
if (!Hash::check($request->old_password, auth()->user()->getAuthPassword()))
{
return back()->with('error', 'Old password doesn\'t match');
}
//Update new password
User::whereId(auth()->user()->id)->update([
'password' => Hash::make($request->new_password)
]);
return redirect()->back()->with('status', 'Password updated successfully!');
}
/**
* Display the specified resource.
* Display change password form
*/
public function show()
{
return view('subadmin.profile.change_password');
}
/**
* Show the form for editing the specified resource.
*/
public function edit()
{
$data = Auth::user();
return view('subadmin.profile.index', compact('data'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'phone' => 'required',
'address' => 'required',
]);
if ($request->file('photo'))
{
$img = $request->file('photo');
// unlink(public_path('upload/subadmin/profile/'.Auth::user()->photo));
$filename = Str::uuid().'.'.$img->getClientOriginalExtension();
Image::make($img)->resize(200, 200)->save('upload/subadmin/profile/'.$filename);
User::findOrFail(Auth::user()->id)->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'address' => $request->address,
'photo' => $filename
]);
return redirect()->back()->with([
'message' => 'Sub-admin profile updated successfully!',
'alert-type' => 'success'
]);
}
User::findOrFail(Auth::user()->id)->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'address' => $request->address,
]);
return redirect()->back()->with([
'message' => 'Sub-admin profile updated successfully!',
'alert-type' => 'success'
]);
}
}
|
package com.ml.restapi.auth;
import com.ml.restapi.model.User;
import io.jsonwebtoken.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
public class JwtUtil {
//@Autowired
//private Environment environment;
private final String secret_key = "NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3Nl";
;
private long accessTokenValidity = 60*60*1000;
private final JwtParser jwtParser;
private final String TOKEN_HEADER = "Authorization";
private final String TOKEN_PREFIX = "Bearer ";
public JwtUtil(){
this.jwtParser = Jwts.parser().setSigningKey(secret_key);
}
public String createToken(User user) {
Claims claims = Jwts.claims().setSubject(user.getEmail());
claims.put("firstName",user.getFirstName());
claims.put("lastName",user.getLastName());
Date tokenCreateTime = new Date();
Date tokenValidity = new Date(tokenCreateTime.getTime() + TimeUnit.MINUTES.toMillis(accessTokenValidity));
return Jwts.builder()
.setClaims(claims)
.setExpiration(tokenValidity)
.signWith(SignatureAlgorithm.HS256, secret_key)
.compact();
}
private Claims parseJwtClaims(String token) {
return jwtParser.parseClaimsJws(token).getBody();
}
public Claims resolveClaims(HttpServletRequest req) {
try {
String token = resolveToken(req);
if (token != null) {
return parseJwtClaims(token);
}
return null;
} catch (ExpiredJwtException ex) {
req.setAttribute("expired", ex.getMessage());
throw ex;
} catch (Exception ex) {
req.setAttribute("invalid", ex.getMessage());
throw ex;
}
}
public String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(TOKEN_HEADER);
if (bearerToken != null && bearerToken.startsWith(TOKEN_PREFIX)) {
return bearerToken.substring(TOKEN_PREFIX.length());
}
return null;
}
public boolean validateClaims(Claims claims) throws AuthenticationException {
try {
return claims.getExpiration().after(new Date());
} catch (Exception e) {
throw e;
}
}
public String getEmail(Claims claims) {
return claims.getSubject();
}
private List<String> getRoles(Claims claims) {
return (List<String>) claims.get("roles");
}
}
/* This Java code is for a JWT (JSON Web Token) utility class to handle JWT token creation, parsing, and validation.
Some key things this code does:
Defines some constants like:
secret_key - the secret key used to sign the JWT
TOKEN_HEADER - the HTTP header name that will contain the JWT
TOKEN_PREFIX - the prefix before the JWT that identifies it
createToken() method
Generates a signed JWT token containing user claims and an expiration
Uses the HS256 signing algorithm and the defined secret key
parseJwtClaims() method
Parses and returns the JWT claims given a JWT token
resolveClaims() method
Gets the JWT token from the HTTP request
Calls parseJwtClaims() to parse claims
Catches expired or invalid tokens
resolveToken() method
Extracts the JWT token from the HTTP header
validateClaims() method
Checks if the expiration of the claims is in the future
Other helper methods like:
getEmail() - Get email from claims
getRoles() - Get roles from claims
So in summary, it provides reusable methods to handle JWT creation, parsing, validation and extraction in a Spring application. The key purpose is offloading JWT handling from the application code into this reusable utility class. */
|
/**
* Generically represents that may succeed with a value or fail with an error.
* @remarks
* Useful for separating "known errors", which are not truly exceptional, from
* exception handling mechanisms such as promise rejection or `throw`/`catch`.
* That is, throw if something broke, or return a failed `Outcome` if failure is
* a perfectly valid result that might need to be handled in detail.
* For example, a server error that leads to a 500 code is an exceptional
* result; not much can be done except to terminate the attempt. On the other
* hand, "that username is taken" requires special attention to inform the user
* of the details.
*/
export type Outcome<T, E> =
| {
success: true;
value: T;
}
| {
success: false;
error: E;
};
|
package routes
import (
"encoding/json"
"net/http"
"damsil99/car-reservation-app/backend/models"
"damsil99/car-reservation-app/backend/repository"
"damsil99/car-reservation-app/backend/services"
"github.com/gorilla/mux"
)
func RegisterAuthRoutes(r *mux.Router) {
r.HandleFunc("/register", registerUser).Methods("POST")
r.HandleFunc("/login", loginUser).Methods("POST")
}
func registerUser(w http.ResponseWriter, r *http.Request) {
var user models.User
json.NewDecoder(r.Body).Decode(&user)
hashedPassword, err := services.HashPassword(user.Password)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user.Password = hashedPassword
db := models.SetupDB()
defer db.Close()
err = repository.CreateUser(db, user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func loginUser(w http.ResponseWriter, r *http.Request) {
var user models.User
json.NewDecoder(r.Body).Decode(&user)
db := models.SetupDB()
defer db.Close()
storedUser, err := repository.GetUserByUsername(db, user.Username)
if err != nil {
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
return
}
if !services.CheckPasswordHash(user.Password, storedUser.Password) {
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
return
}
token, err := services.GenerateJWT(storedUser)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]string{"token": token})
}
|
var express = require('express');
var app = express();
var bGround = require('fcc-express-bground');
require('dotenv').config()
var bodyParser = require('body-parser')
// --> 7) Mount the Logger middleware here
app.use(function(req, res, next){
console.log(req.method + " " + req.path + " - " + req.ip)
next();
});
// --> 11) Mount the body-parser middleware here
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
/** 1) Meet the node console. */
console.log("Hello World");
/** 2) A first working Express Server */
// app.get("/",function(req,res){
// res.send("Hello Express");
// })
/** 3) Serve an HTML file */
app.get("/",function(req,res){
res.sendFile(__dirname + "/views/index.html");
})
/** 4) Serve static assets */
app.use(express.static(__dirname+"/public"));
app.use("/public",express.static(__dirname+"/public"));
/** 5) serve JSON on a specific route */
// app.get("/json",function(req,res){
// res.json({"message":"Hello json"})
// })
/** 6) Use the .env file to configure the app */
app.get("/json",function(req,res){
var jsonResponse = {"message":"Hello json"};
if (process.env.MESSAGE_STYLE ==="uppercase"){
jsonResponse.message = jsonResponse.message.toUpperCase()
}
res.json(jsonResponse);
})
/** 7) Root-level Middleware - A logger */
// place it before all the routes !
/** 8) Chaining middleware. A Time server */
const middleware = (req, res, next) => {
req.time = new Date().toString();
next();
};
app.get("/now", middleware, (req, res) => {
res.send({
time: req.time
});
});
/** 9) Get input from client - Route parameters */
app.get("/:word/echo",function(req,res){
res.json({echo: req.params.word});
});
/** 10) Get input from client - Query parameters */
// /name?first=<firstname>&last=<lastname>
app.get("/name",function(req,res){
res.json({name : req.query.first +" " + req.query.last})
});
/** 11) Get ready for POST Requests - the `body-parser` */
// place it before all the routes !
/** 12) Get data form POST */
app.post("/name",(req,res) => {
res.json({name : req.body.first +" " + req.body.last})
})
// This would be part of the basic setup of an Express app
// but to allow FCC to run tests, the server is already active
/** app.listen(process.env.PORT || 3000 ); */
//---------- DO NOT EDIT BELOW THIS LINE --------------------
module.exports = app;
|
package com.faith.demo.dto;
import java.util.Date;
import com.faith.demo.entity.Student;
public class RankStudentDto {
//instance variables
private int studentId;
private String studentName;
private int applicationCode;
private String courseName;
private double average;
private double credits;
private int ranks;
private Date approvedDate;
//default constructor
public RankStudentDto() {
super();
// TODO Auto-generated constructor stub
}
//paramatrized constructor
public RankStudentDto(int studentId, String studentName, int applicationCode, String courseName, double average,
double credits, int ranks, Date approvedDate) {
super();
this.studentId = studentId;
this.studentName = studentName;
this.applicationCode = applicationCode;
this.courseName = courseName;
this.average = average;
this.credits = credits;
this.ranks = ranks;
this.approvedDate = approvedDate;
}
//getters and setters
public int getStudentId() {
return studentId;
}
//to string
@Override
public String toString() {
return "RankStudentDto [studentId=" + studentId + ", studentName=" + studentName + ", applicationCode="
+ applicationCode + ", courseName=" + courseName + ", average=" + average + ", credits=" + credits
+ ", ranks=" + ranks + ", approvedDate=" + approvedDate + "]";
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getApplicationCode() {
return applicationCode;
}
public void setApplicationCode(int applicationCode) {
this.applicationCode = applicationCode;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public double getCredits() {
return credits;
}
public void setCredits(double credits) {
this.credits = credits;
}
public int getRanks() {
return ranks;
}
public void setRanks(int ranks) {
this.ranks = ranks;
}
public Date getApprovedDate() {
return approvedDate;
}
public void setApprovedDate(Date approvedDate) {
this.approvedDate = approvedDate;
}
}
|
import {
Drawer,
DrawerBody,
DrawerFooter,
DrawerHeader,
DrawerOverlay,
DrawerContent,
DrawerCloseButton,
Stack,
Box,
Button,
} from '@chakra-ui/react'
import { useDispatch } from 'react-redux'
import { addQuestion } from '../redux/createSurvey'
import {BiAlignLeft, BiImage, BiDotsHorizontalRounded} from 'react-icons/bi'
export default function ComponentsDrawer(props){
const dispatch = useDispatch()
const handleClickOption = (i) => {
dispatch(addQuestion(i))
props.onClose()
}
return(
<Drawer
isOpen={props.isOpen}
placement='right'
onClose={props.onClose}
finalFocusRef={props.btnRef}
>
<DrawerOverlay />
<DrawerContent>
<DrawerCloseButton />
<DrawerHeader>Select a type of question</DrawerHeader>
<DrawerBody>
<Stack>
<Button leftIcon={<BiAlignLeft />} colorScheme='red' variant='solid' onClick={() => handleClickOption({q : "", pa : [{a:"", t:0}, {a:"", t:0}], m:false, t:0})}>
Text Selection
</Button>
<Button leftIcon={<BiImage />} colorScheme={'red'} variant={'solid'} onClick={() => handleClickOption({q : "", pa : [{a:"", t:1}, {a:"", t:1}], m:false, t:1})} >
Image Selection
</Button>
<Button leftIcon={<BiImage />} colorScheme={'red'} variant={'solid'} onClick={() => handleClickOption({q : "", pa : [{a:"", t:0}, {a:"", t:0}], m:true, t:0})} >
Multiple Text Selection
</Button>
<Button leftIcon={<BiImage />} colorScheme={'red'} variant={'solid'} onClick={() => handleClickOption({q : "", pa : [{a:"", t:1}, {a:"", t:1}], m:true, t:1})} >
Multiple Image Selection
</Button>
<Button leftIcon={<BiDotsHorizontalRounded />} colorScheme={'red'} variant={'solid'} onClick={() => handleClickOption({q : "", pa : [{a:"0", t:2}, {a:"10", t:2}], m:false, t:2})} >
Bar Selection
</Button>
</Stack>
</DrawerBody>
<DrawerFooter>
</DrawerFooter>
</DrawerContent>
</Drawer>
)
}
|
<html ng-app="app">
<head>
<title>Hello Controllers in AngularJS</title>
</head>
<body>
<ng-view></ng-view>
<!-- Template -->
<script type="text/ng-template" id="/todos.html">
Search: <input type="text" ng-model="search.name">
{{ remaining() }} of {{ toddos.length }} remaining
<ul>
<li ng-repeat="todo in todos | filter: search track by $index">
<input type="checkbox" ng-model="todo.done" ng-hide="showme">
<a href="#/{{$index}}" ng-hide="showme">{{todo.name}}</a>
<input type="text" ng-model="todo.name" ng-show="showme">
<button ng-click="remove($index)" ng-hide="showme">Remove Item</button>
<button ng-click="showme=true" ng-click="editItem(item)" ng-hide="showme">Edit Item</button>
<button ng-click="showme=false" ng-show="showme" ng-click="saveItem()">Finish Editing</button>
</li>
</ul>
<input type="text" id="newInfo" data-ng-model="todoText">
<button ng-click="update()">Add to Todo</button>
</script>
<script type="text/ng-template" id="/todoDetails.html">
<h1>{{ todo.name }}</h1>
completed: <input type="checkbox" ng-model="todo.done">
note: <textarea>{{ todo.note }}</textarea>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="angular.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-route.min.js" type="text/javascript"></script>
</body>
</html>
|
package com.petsCare.petsCare.pet.controller;
import com.petsCare.petsCare.oAuth2.dto.CustomOAuth2User;
import com.petsCare.petsCare.pet.PetController;
import com.petsCare.petsCare.pet.dto.form.PetDetailForm;
import com.petsCare.petsCare.pet.service.PetBreedService;
import com.petsCare.petsCare.pet.service.PetTypeService;
import com.petsCare.petsCare.user.dto.UserDto;
import com.petsCare.petsCare.pet.dto.form.PetAdoptForm;
import com.petsCare.petsCare.pet.dto.form.PetsForm;
import com.petsCare.petsCare.pet.service.PetService;
import com.petsCare.petsCare.user.entity.User;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.jpa.mapping.JpaMetamodelMappingContext;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static com.nimbusds.common.contenttype.ContentType.IMAGE_JPEG;
import static org.mockito.BDDMockito.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(controllers = {PetController.class}, excludeAutoConfiguration = {SecurityAutoConfiguration.class, OAuth2ClientAutoConfiguration.class})
@MockBean(JpaMetamodelMappingContext.class)
class PetControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
PetService petService;
@MockBean
OAuth2AuthorizedClientService authorizedClientService;
@MockBean
PetTypeService petTypeService;
@MockBean
PetBreedService petBreedService;
@Test
@DisplayName("펫 등록 성공")
void adoptSuccess() throws Exception {
//given
String url = "/pets/adopt";
String petName = "이복댕";
MockMultipartFile thumbnail = new MockMultipartFile("썸네일", "이복댕.png", IMAGE_JPEG.getType(), "이복댕.png".getBytes(StandardCharsets.UTF_8));
String breed = "닥스훈트";
int petGender = 1;
LocalDate petBirth = LocalDate.now();
String loginId = "naver_testMember123";
User user = new User(1L, "local", "testuser", "Test User", "test.jpg", "ROLE_USER", new ArrayList<>());
UserDto userDto = new UserDto(user);
doNothing().when(petService).adopt(any(PetAdoptForm.class), any(UserDto.class));
//when
ResultActions resultActions = mockMvc.perform(multipart(url)
.file(thumbnail)
.with(SecurityMockMvcRequestPostProcessors.oauth2Login().oauth2User(new CustomOAuth2User(new UserDto(user))))
.contentType(MediaType.MULTIPART_FORM_DATA)
.flashAttr("userDto", userDto)
.param("petName", petName)
.param("breedId", "1")
.param("petGender", String.valueOf(petGender))
.param("petBirth", String.valueOf(petBirth))
);
//then
resultActions.andExpectAll(
status().is3xxRedirection(),
redirectedUrl("/")
);
}
@Test
@DisplayName("반려 동물 불러오기 성공")
void petsSuccess() throws Exception {
//given
String url = "/pets";
List<PetsForm> list = new ArrayList<>();
given(petService.showPets(any(UserDto.class)))
.willReturn(list);
User user = new User(1L, "local", "testuser", "Test User", "test.jpg", "ROLE_USER", new ArrayList<>());
UserDto userDto = new UserDto(user);
//when
ResultActions resultActions = mockMvc.perform(get(url)
.flashAttr("userDto", userDto));
//then
resultActions.andExpectAll(
status().isOk()
);
}
@Test
@DisplayName("펫 상세 정보 가져오기")
void petDetailSuccess() throws Exception {
//given
String url = "/pets/1";
given(petService.showPetDetail(any(Long.class)))
.willReturn(any(PetDetailForm.class));
//when
ResultActions resultActions = mockMvc.perform(get(url));
//then
resultActions.andExpectAll(
status().isOk()
);
}
}
|
//
// WatchLandmarkDetail.swift
// 09.Creating-A-watchOS-App(watchOS) Extension
//
// Created by ZJQ on 2020/7/3.
// Copyright © 2020 Apple. All rights reserved.
//
import SwiftUI
struct WatchLandmarkDetail: View {
@EnvironmentObject var userData: UserData
var landmark: Landmark
var landmarkIndex: Int {
userData.landmarks.firstIndex(where: { $0.id == landmark.id })!
}
var body: some View {
ScrollView {
VStack {
CircleImage(image: landmark.image.resizable())
.scaledToFit()
Text(landmark.name)
.font(.headline)
.lineLimit(0)
Toggle(isOn: $userData.landmarks[landmarkIndex].isFavorite) {
Text("Favorite")
}
Divider()
Text(landmark.park)
.font(.caption)
.bold()
.lineLimit(0)
Text(landmark.state)
.font(.caption)
Divider()
WatchMapView(landmark: landmark)
.scaledToFit()
.padding()
}
.padding(16)
}
.navigationBarTitle("Landmarks")
}
}
struct WatchLandmarkDetail_Previews: PreviewProvider {
static var previews: some View {
let userData = UserData()
return Group {
WatchLandmarkDetail(landmark: userData.landmarks[0]).environmentObject(userData)
.previewDevice("Apple Watch Series 4 - 44mm")
WatchLandmarkDetail(landmark: userData.landmarks[1]).environmentObject(userData)
.previewDevice("Apple Watch Series 2 - 38mm")
}
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->enum('type',['Super Admin','Admin','Employee']);
$table->integer('employee_id');
$table->string('mobile');
$table->string('email')->unique();
$table->string('password');
$table->string('image')->nullable();
$table->enum('status',['Active','Inactive']);
$table->string('Role')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('admins');
}
};
|
import { FC, useEffect, useRef, useState } from 'react'
import { useParams } from 'react-router-dom'
import loadingGif from '../../assets/img/loading.gif'
import { useAppDispatch, useAppSelector } from '../../hooks'
import { addItemToCart } from '../../store/slices/cartSlice'
import plus from '../../assets/img/icons/plus-circle.svg'
import minus from '../../assets/img/icons/minus-circle.svg'
import classNames from 'classnames'
import { fetchProduct, productSelector } from '../../store/slices/productSlice'
import { CartItem } from '../../types/cart'
const ProductPage: FC = () => {
const { link } = useParams()
const dispatch = useAppDispatch()
const { loading, item } = useAppSelector(productSelector)
useEffect(() => {
window.scrollTo({ top: 0 })
dispatch(fetchProduct(link))
}, [link])
const [productAmount, setProductAmount] = useState<number>(1)
const productAmountInput = useRef<HTMLInputElement>(null)
const onPlusItem = (): void => {
setProductAmount((prev) => prev + 1)
}
const onMinusItem = (): void => {
if (productAmount > 1) {
setProductAmount((prev) => prev - 1)
}
}
const onChangeAmount = (amount: any) => {
if (!isNaN(Number(amount))) {
setProductAmount(Number(productAmountInput.current?.value))
}
}
const onAddToCart = () => {
const obj: CartItem = {
id: item.id,
name: item.name,
img: item.img,
actualPrice: item.actualPrice,
link: item.link,
quantity: productAmount,
totalPrice: item.actualPrice * productAmount,
}
if (productAmount > 0) {
dispatch(addItemToCart(obj))
}
}
let discount: number = 100 - Math.floor((item.actualPrice * 100) / item.oldPrice)
discount = discount < 0 ? 0 : discount
if (!item.id) {
return (
<div className="product-page">
<div className="product-page__container container">
<div className="product-loading">
<img src={loadingGif} alt="loading" />
</div>
</div>
</div>
)
}
return (
<div className="product-page">
<div className="product-page__container container">
{loading === 'success' ? (
<div className="product">
<div className="product__column">
<div className="product__wrapper">
<img
alt=""
src={require('../../assets/img/products/' + item.img)}
className="product__img"
/>
</div>
<div className="product__description">
{item.description}
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto obcaecati
tempora repellendus earum praesentium, modi officiis dolorum dolor iure, quo
aspernatur iste minus nemo accusamus aut ratione expedita aliquam tempore.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto obcaecati
tempora repellendus earum praesentium, modi officiis dolorum dolor iure, quo
aspernatur iste minus nemo accusamus aut ratione expedita aliquam tempore.
</p>
<ul className="product__description-list">
<li className="product__description-title">Характеристики</li>
<li>Lorem ipsum dolor sit amet consectetur adipisicing.</li>
<li>Lorem ipsum dolor sit amet consectetur adipisicing.</li>
<li>Lorem ipsum dolor sit amet consectetur adipisicing.</li>
<li>Lorem ipsum dolor sit amet consectetur adipisicing.</li>
</ul>
</div>
</div>
<div className="product__column">
<div className="product__info">
<h1 className="product__name">{item.name}</h1>
<div className="product__price">{item.actualPrice} грн.</div>
{discount > 0 ? (
<div className="product__discount">
<div className="product__old-price">{item.oldPrice} грн.</div>
<div className="product__discount-value">Скидка {discount}%</div>
</div>
) : (
''
)}
<div className="product__label">Новинка</div>
<div className="product__amount">
<span>Количество:</span>
<span className="product__amount-container">
<input
type="text"
className="product__amount-input"
value={productAmount}
ref={productAmountInput}
onChange={(e) => onChangeAmount(e.target.value)}
/>
<img
src={plus}
alt=""
className="product__amount-btn product__amount-btn_plus"
onClick={onPlusItem}
/>
<img
src={minus}
alt=""
className="product__amount-btn product__amount-btn_minus"
onClick={onMinusItem}
/>
</span>
</div>
<button
onClick={onAddToCart}
className={classNames(
'product__btn btn-black',
productAmount < 1 ? 'disabled' : ''
)}
>
В корзину
</button>
</div>
</div>
<div className="product__img-md">
<img alt="" src={require('../../assets/img/products/' + item.img)} />
</div>
</div>
) : (
<div className="product-loading">
<img src={loadingGif} alt="loading" />
</div>
)}
</div>
</div>
)
}
export default ProductPage
|
<%= form_with(model: article) do |form| %>
<% if article.errors.any? %>
<div style="color: red">
<h2><%= pluralize(article.errors.count, "error") %> que impide(n) enviar artículo:</h2>
<ul>
<% article.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<h3 class="card-title text-center">Artículo</h3>
<div>
<%= form.label :title, "Título", style: "display: block" %>
<%= form.text_field :title, class:"mb-2" %>
</div>
<div>
<%= form.label :body, "Artículo", style: "display: block" %>
<%= form.text_area :body, class:"mb-2" %>
</div>
<%= form.submit "Enviar", class: "btn btn-outline-light text-light hover-btn mb-3 mt-2 ms-4" do %>
<i class="bi bi-cloud-arrow-up"> Enviar</i>
<% end %>
<%# <%= form.submit "Enviar", class: "btn btn-outline-light text-light hover-btn mb-3" %>
<%# <%= link_to articles_path, class:"text-light btn btn-outline-light hover-btn ms-4" do %>
<%# <i class="bi bi-arrow-counterclockwise"> Volver a Artículos</i>
<% end %>
<% end %>
|
from flask import Flask, request, jsonify
from flask_mysqldb import MySQL
from flask_cors import CORS
app = Flask(__name__)
# Configurações do banco de dados
app.config['MYSQL_HOST'] = 'jobs.visie.com.br'
app.config['MYSQL_USER'] = 'lucasdaniel'
app.config['MYSQL_PASSWORD'] = 'bHVjYXNkYW5p'
app.config['MYSQL_DB'] = 'lucasdaniel'
# Configurar o CORS para permitir solicitações de 'http://localhost:5173'
CORS(app, resources={r"/pessoas/*": {"origins": "http://localhost:5173"}})
mysql = MySQL(app)
# Rota para listar todas as pessoas
@app.route('/pessoas', methods=['GET'])
def listar_pessoas():
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM pessoas')
pessoas = cur.fetchall()
cur.close()
# Converter os dados em um dicionário
pessoas_dict = [{'id_pessoa': pessoa[0], 'nome': pessoa[1], 'data_admissao': pessoa[5]} for pessoa in pessoas]
return jsonify(pessoas_dict)
# Rota para obter uma pessoa por ID
@app.route('/pessoas/<int:id_pessoa>', methods=['GET'])
def obter_pessoa(id_pessoa):
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM pessoas WHERE id_pessoa = %s', (id_pessoa,))
pessoa = cur.fetchone()
cur.close()
if pessoa:
# Criar um dicionário com os campos desejados
pessoa_dict = {
'id_pessoa': pessoa[0],
'nome': pessoa[1],
'rg': pessoa[2],
'cpf': pessoa[3],
'data_nascimento': pessoa[4],
'data_admissao': pessoa[5]
}
return jsonify(pessoa_dict)
else:
return jsonify({'mensagem': 'Pessoa não encontrada'}), 404
# Rota para adicionar uma nova pessoa
@app.route('/pessoas', methods=['POST'])
def adicionar_pessoa():
data = request.get_json()
nome = data['nome']
rg = data['rg']
cpf = data['cpf']
data_admissao = data['data_admissao']
data_nascimento = data.get('data_nascimento', None) # Use get() para lidar com campos opcionais
cur = mysql.connection.cursor()
if data_nascimento is not None:
cur.execute('INSERT INTO pessoas (nome, rg, cpf, data_admissao, data_nascimento) VALUES (%s, %s, %s, %s, %s)', (nome, rg, cpf, data_admissao, data_nascimento))
else:
cur.execute('INSERT INTO pessoas (nome,rg, cpf, data_admissao) VALUES (%s, %s, %s, %s)', (nome, rg, cpf, data_admissao))
mysql.connection.commit()
cur.close()
return jsonify({'mensagem': 'Pessoa adicionada com sucesso'})
@app.route('/pessoas/<int:id_pessoa>', methods=['PUT'])
def atualizar_pessoa(id_pessoa):
data = request.get_json()
nome = data['nome']
rg = data['rg']
cpf = data['cpf']
data_nascimento = data['data_nascimento']
data_admissao = data['data_admissao']
try:
cur = mysql.connection.cursor()
cur.execute('UPDATE pessoas SET nome = %s, rg = %s, cpf = %s, data_nascimento = %s, data_admissao = %s WHERE id_pessoa = %s', (nome, rg, cpf, data_nascimento, data_admissao, id_pessoa))
mysql.connection.commit()
cur.close()
return jsonify({'mensagem': 'Pessoa atualizada com sucesso'})
except Exception as e:
return jsonify({'erro': str(e)})
# Rota para excluir uma pessoa por ID
@app.route('/pessoas/<int:id_pessoa>', methods=['DELETE'])
def excluir_pessoa(id_pessoa):
cur = mysql.connection.cursor()
cur.execute('DELETE FROM pessoas WHERE id_pessoa = %s', (id_pessoa,))
mysql.connection.commit()
cur.close()
return jsonify({'mensagem': 'Pessoa excluída com sucesso'})
if __name__ == '__main__':
app.run(debug=True)
|
import 'package:growthbook_sdk_flutter/src/Model/experiment.dart';
import 'package:growthbook_sdk_flutter/src/Model/experiment_result.dart';
import 'package:json_annotation/json_annotation.dart';
part 'gb_variation_meta.g.dart';
/// Meta info about the variations
@JsonSerializable()
class GBVariationMeta {
GBVariationMeta({
this.key,
this.name,
this.passthrough,
});
final String? key;
final String? name;
final bool? passthrough;
factory GBVariationMeta.fromJson(Map<String, dynamic> value) =>
_$GBVariationMetaFromJson(value);
Map<String, dynamic> toJson() => _$GBVariationMetaToJson(this);
}
/// Used for remote feature evaluation to trigger the `TrackingCallback`
@JsonSerializable()
class GBTrackData {
GBTrackData({
required this.experiment,
required this.experimentResult,
});
final GBExperiment experiment;
final GBExperimentResult experimentResult;
factory GBTrackData.fromJson(Map<String, dynamic> value) =>
_$GBTrackDataFromJson(value);
Map<String, dynamic> toJson() => _$GBTrackDataToJson(this);
}
|
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Business Website</title>
<link rel="stylesheet" href="style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.2.1/css/all.min.css">
<link rel="apple-touch-icon" sizes="180x180" href="images/favicon/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="images/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png">
<link rel="manifest" href="images/favicon/site.webmanifest">
<link rel="mask-icon" href="images/favicon/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff">
</head>
<body>
<!--Navigation Bar-->
<section id="nav-bar">
<nav class="navbar navbar-expand-lg navbar-light">
<div class="container-fluid">
<a class="navbar-brand" href="#slider"><img src="images/Logo.png"></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto justify-content-end">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#slider">HOME</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">ABOUT US</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#services">SERVICES</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#team">OUR TEAM</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#price">PRICE PLANS</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#reviews">REVIEWS</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">CONTACTS</a>
</li>
</ul>
</div>
</div>
</nav>
</section>
<!--Slider-->
<section id="slider">
<div id="carouselExampleAutoplaying" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide-to="1" aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide-to="2" aria-label="Slide 3"></button>
</div>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="images/slide01.jpg" class="d-block img-fluid" alt="First slide">
<div class="carousel-caption">
<h5>Work With Draft Art</h5>
</div>
</div>
<div class="carousel-item">
<img src="images/slide02.jpg" class="d-block img-fluid" alt="Second slide">
<div class="carousel-caption">
<h5>Responsive Websites</h5>
</div>
</div>
<div class="carousel-item">
<img src="images/slide03.jpg" class="d-block img-fluid" alt="Third slide">
<div class="carousel-caption">
<h5>Unique Website Designs</h5>
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</section>
<!--About-->
<section id="about">
<div class="container">
<div class="row">
<div class="col-md-6">
<h2>About Us</h2>
<div class="about-content">
<p>Welcome to Draft Art, your trusted partner in website creation and digital solutions. We are a dedicated team of experts passionate about helping individuals and businesses establish a strong online presence.</p>
</div>
<button type="button" class="btn btn-primary">Read More</button>
</div>
<div class="col-md-6 skills-bar">
<p>Adobe Photoshop</p>
<div class="progress">
<div class="progress-bar" style="width: 80%;">80%</div>
</div>
<p>UI Design</p>
<div class="progress">
<div class="progress-bar" style="width: 85%;">85%</div>
</div>
<p>WordPress</p>
<div class="progress">
<div class="progress-bar" style="width: 75%;">70%</div>
</div>
<p>Graphic Design</p>
<div class="progress">
<div class="progress-bar" style="width: 50%;">50%</div>
</div>
</div>
</div>
</div>
</section>
<!--Services-->
<section id="services">
<div class="container">
<h1>Our Services</h1>
<div class="row services">
<div class="col-md-3 text-center">
<div class="icon"><i class="fas fa-desktop"></i></div>
<h3>Web Development</h3>
<p>Our mission is to empower individuals and
businesses by providing them with high-quality websites.</p>
</div>
<div class="col-md-3 text-center">
<div class="icon"><i class="fas fa-tablet"></i></div>
<h3>App Development</h3>
<p>Our mission is to empower individuals and
businesses by providing them with high-quality websites.</p>
</div>
<div class="col-md-3 text-center">
<div class="icon"><i class="fas fa-line-chart"></i></div>
<h3>Digital Marketing</h3>
<p>Our mission is to empower individuals and
businesses by providing them with high-quality websites.</p>
</div>
<div class="col-md-3 text-center">
<div class="icon"><i class="fas fa-paint-brush"></i></div>
<h3>Graphic Design</h3>
<p>Our mission is to empower individuals and
businesses by providing them with high-quality websites.</p>
</div>
</div>
</div>
</section>
<!--Team Members-->
<section id="team">
<div class="container">
<h1>Our Team</h1>
<div class="row">
<div class="col-md-3 profile-pic text-center">
<div class="img-box">
<img src="images/headshot01.jpg" class="img-responsive">
<ul>
<a href="#"><li><i class="fab fa-facebook"></i></li></a>
<a href="#"><li><i class="fab fa-twitter"></i></li></a>
<a href="#"><li><i class="fab fa-linkedin"></i></li></a>
</ul>
</div>
<h2>John Smith</h2>
<h3>Web Developer</h3>
<p><em>"Turning ideas into digital reality"</em></p>
</div>
<div class="col-md-3 profile-pic text-center">
<div class="img-box">
<img src="images/headshot02.jpg" class="img-responsive">
<ul>
<a href="#"><li><i class="fab fa-facebook"></i></li></a>
<a href="#"><li><i class="fab fa-twitter"></i></li></a>
<a href="#"><li><i class="fab fa-linkedin"></i></li></a>
</ul>
</div>
<h2>Michael Johnson</h2>
<h3>Graphic Designer</h3>
<p><em>"Design is the silent ambassador of your brand"</em></p>
</div>
<div class="col-md-3 profile-pic text-center">
<div class="img-box">
<img src="images/headshot03.jpg" class="img-responsive">
<ul>
<a href="#"><li><i class="fab fa-facebook"></i></li></a>
<a href="#"><li><i class="fab fa-twitter"></i></li></a>
<a href="#"><li><i class="fab fa-linkedin"></i></li></a>
</ul>
</div>
<h2>Emily Davis</h2>
<h3>UX/UI Designer</h3>
<p><em>"Creating intuitive and delightful user experiences"</em></p>
</div>
<div class="col-md-3 profile-pic text-center">
<div class="img-box">
<img src="images/headshot04.jpg" class="img-responsive">
<ul>
<a href="#"><li><i class="fab fa-facebook"></i></li></a>
<a href="#"><li><i class="fab fa-twitter"></i></li></a>
<a href="#"><li><i class="fab fa-linkedin"></i></li></a>
</ul>
</div>
<h2>David Thompson</h2>
<h3>Digital Marketer</h3>
<p><em>"Driving online success through strategic marketing"</em></p>
</div>
</div>
</div>
</section>
<!--Promo-->
<section id="promo">
<div class="container">
<p>Get Free Domain Name and Web Hosting</p>
<a href="#contact" class="btn btn-primary">Contact Us</a>
</div>
</section>
<!--Price Plans-->
<section id="price">
<div class="container">
<h1>Price Plans</h1>
<div class="row">
<div class="col-md-3">
<div class="single-price">
<div class="price-head">
<h2>Free</h2>
<p>0€/<span>Month</span></p>
</div>
<div class="price-content">
<ul>
<li><i class="fa-solid fa-circle-check"></i>5GB Space</li>
<li><i class="fa-solid fa-circle-check"></i>10GB Bandwidth</li>
<li><i class="fa-solid fa-circle-xmark"></i>15 Email Account</li>
<li><i class="fa-solid fa-circle-xmark"></i>Unlimited Domain</li>
<li><i class="fa-solid fa-circle-xmark"></i>Unlimited Support</li>
</ul>
</div>
<div class="price-button">
<a class="buy-btn" href="#">Join Free</a>
</div>
</div>
</div>
<div class="col-md-3">
<div class="single-price">
<div class="price-head">
<h2>Start Up</h2>
<p>10€/<span>Month</span></p>
</div>
<div class="price-content">
<ul>
<li><i class="fa-solid fa-circle-check"></i>10GB Space</li>
<li><i class="fa-solid fa-circle-check"></i>100GB Bandwidth</li>
<li><i class="fa-solid fa-circle-check"></i>15 Email Account</li>
<li><i class="fa-solid fa-circle-xmark"></i>Unlimited Domain</li>
<li><i class="fa-solid fa-circle-xmark"></i>Unlimited Support</li>
</ul>
</div>
<div class="price-button">
<a class="buy-btn" href="#">Buy Now</a>
</div>
</div>
</div>
<div class="col-md-3">
<div class="single-price">
<div class="price-head">
<h2>Business</h2>
<p>50€/<span>Month</span></p>
</div>
<div class="price-content">
<ul>
<li><i class="fa-solid fa-circle-check"></i>20GB Space</li>
<li><i class="fa-solid fa-circle-check"></i>200GB Bandwidth</li>
<li><i class="fa-solid fa-circle-check"></i>50 Email Account</li>
<li><i class="fa-solid fa-circle-check"></i>Unlimited Domain</li>
<li><i class="fa-solid fa-circle-xmark"></i>Unlimited Support</li>
</ul>
</div>
<div class="price-button">
<a class="buy-btn" href="#">Buy Now</a>
</div>
</div>
</div>
<div class="col-md-3">
<div class="single-price">
<div class="price-head">
<h2>Advanced</h2>
<p>100€/<span>Month</span></p>
</div>
<div class="price-content">
<ul>
<li><i class="fa-solid fa-circle-check"></i>500GB Space</li>
<li><i class="fa-solid fa-circle-check"></i>Unlimited Bandwidth</li>
<li><i class="fa-solid fa-circle-check"></i>Unlimited Account</li>
<li><i class="fa-solid fa-circle-check"></i>Unlimited Domain</li>
<li><i class="fa-solid fa-circle-check"></i>Unlimited Support</li>
</ul>
</div>
<div class="price-button">
<a class="buy-btn" href="#">Buy Now</a>
</div>
</div>
</div>
</div>
</div>
</section>
<!--Reviews-->
<section id="reviews">
<div class="container">
<h1>Reviews</h1>
<p class="text-center">Discover what our clients have to say about their experience with our website company.
Our review section showcases the satisfaction and positive feedback we've received from our valued clients. From stunning designs to exceptional service, hear firsthand how we've helped businesses enhance their online presence and achieve success. Read through the reviews and get inspired to join our growing list of happy clients.</p>
<div class="row">
<div class="col-md-4 text-center">
<div class="profile">
<img src="images/review01.jpg" class="user">
<blockquote>I am incredibly impressed with Draft Art's services. They delivered a stunning and user-friendly website for my business. Their attention to detail and professionalism exceeded my expectations. Highly recommended!</blockquote>
<h3>Emma Peterson <span>Marketing Manager</span></h3>
</div>
</div>
<div class="col-md-4 text-center">
<div class="profile">
<img src="images/review02.jpg" class="user">
<blockquote>This company transformed my online presence with their exceptional work. They captured the essence of my brand and created a visually appealing website that perfectly represents my business. I'm thrilled with the results!</blockquote>
<h3>Peter Davis <span>Software Engineer</span></h3>
</div>
</div>
<div class="col-md-4 text-center">
<div class="profile">
<img src="images/review03.jpg" class="user">
<blockquote>Working with Draft Art was a breeze. They understood my requirements and brought my vision to life. The team was responsive, creative, and delivered a website that not only looks great but also performs seamlessly. I couldn't be happier!</blockquote>
<h3>Dalton Ford <span>Business Consultant</span></h3>
</div>
</div>
</div>
</div>
</section>
<!--Get in Touch-->
<section id="contact">
<div class="container">
<h1>Get In Touch</h1>
<div class="row">
<div class="col-md-6">
<form class="Contact-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="tel" class="form-control" placeholder="Phone Number">
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<textarea class="form-control" rows="4" placeholder="Message"></textarea>
</div>
<button type="submit" class="btn btn-primary">Send Message</button>
</form>
</div>
<div class="col-md-6 contact-info">
<div class="follow"><i class="fa-solid fa-location-dot"></i> <b>Address: </b>Random Road, 123-223 - World</div>
<div class="follow"><i class="fa-solid fa-phone-volume"></i><b>Phone: </b>+1 1234567890</div>
<div class="follow"><i class="fa-solid fa-envelope-open-text"></i><b>Email: </b>draftart@example.com</div>
<div class="follow"><label><b>Socials:</b></label>
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-youtube"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
<a href="#"><i class="fab fa-google-plus"></i></a>
</div>
</div>
</div>
</div>
</section>
<!--Footer-->
<footer>
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<p>© 2023 All rights reserved. | Website designed and developed by <strong>Karine Cardoso</strong></p>
</div>
</div>
</div>
</footer>
<script src="script.js"></script>
<script src="smooth-scroll.js"></script>
<script>
var scroll = new SmoothScroll('a[href*="#"]');
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</html>
|
/**
*
*/
package it.unicam.cs.asdl2324.es7;
import java.util.List;
// TODO completare import
/**
* Implementazione del QuickSort con scelta della posizione del pivot fissa.
* L'implementazione è in loco.
*
* @author Template: Luca Tesei, Implementazione: collettiva
* @param <E>
* il tipo degli elementi della sequenza da ordinare.
*
*/
public class QuickSort<E extends Comparable<E>> implements SortingAlgorithm<E> {
private int countCompare;
@Override
public SortingAlgorithmResult<E> sort(List<E> l) {
countCompare = 0;
if (l == null) throw new NullPointerException("Tentativo di ordinare una lista null");
// per ordinare la lista vuota o con un solo elemento non faccio niente
if (l.size() <= 1) return new SortingAlgorithmResult<E>(l, 0);
quickSort(l, 0, l.size() - 1);
return new SortingAlgorithmResult<E>(l, countCompare);
}
private void quickSort(List<E> l, int p, int r) {
// condizione di stop quando p = r
if(p < r) {
int m = partition(l, p, r); // partizione
quickSort(l, p, m-1); // chiamata ricorsiva 1
quickSort(l, m+1, r); // chiamata ricorsiva 2
}
}
private int partition(List<E> l, int p, int r) {
E app;
E pivot = l.get(r);
int i = (p - 1);
// pongo gli elementi < del pivot a sinistra, e gli elementi >= a destra della lista
for(int j = p; j < r; j++) { // il contatore j conta i maggiori uguali e scorre a prescindere
countCompare++;
if(l.get(j).compareTo(pivot) < 0) {
i++; // Il contatore i scorre se trovo un elemento minore del pivot
// che scambio opportunamente con l'elemento j, in quanto deve stare a sinistra
app = l.get(i);
l.set(i, l.get(j));
l.set(j, app);
}
}
// Aggiusto il pivot
app = l.get(i+1);
l.set(i+1, pivot);
l.set(r, app);
return (i + 1); // ritorno la posizione del pivot
}
@Override
public String getName() {
return "QuickSort";
}
}
|
import { Navbar } from "@/components/Organisms/Navbar";
import { Footer } from "@/components/Organisms/Footer";
import "./globals.css";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "@fortawesome/fontawesome-svg-core/styles.css";
import { config } from "@fortawesome/fontawesome-svg-core";
// import {CookieContextProvider} from "@/contexts/CookieContext"
config.autoAddCss = false;
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Unscripted Fiasco",
description: "Just another blog about tech and stuff, but with a twist",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const svgBackgroundCss = `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" viewBox="0 0 700 700" width="700" height="700" opacity="0.87"><defs><filter id="nnnoise-filter" x="-20%" y="-20%" width="140%" height="140%" filterUnits="objectBoundingBox" primitiveUnits="userSpaceOnUse" color-interpolation-filters="linearRGB"><feTurbulence type="turbulence" baseFrequency="0.091" numOctaves="4" seed="15" stitchTiles="stitch" x="0%" y="0%" width="100%" height="100%" result="turbulence"></feTurbulence><feSpecularLighting surfaceScale="24" specularConstant="0.2" specularExponent="20" lighting-color="%23ffffff" x="0%" y="0%" width="100%" height="100%" in="turbulence" result="specularLighting"><feDistantLight azimuth="3" elevation="100"></feDistantLight></feSpecularLighting></filter></defs><rect width="700" height="700" fill="%23000000ff"></rect><rect width="700" height="700" fill="%23ffffff" filter="url(%23nnnoise-filter)"></rect></svg>')`;
const bodyStyles = {
backgroundImage: svgBackgroundCss,
backgroundSize: "cover",
backgroundAttachment: "fixed", // Mantener el fondo estático
};
const contentContainerStyles = {
backgroundColor: "transparent",
position: "relative" as const,
zIndex: 1,
};
return (
// <CookieContextProvider>
<html lang="en" className="bg-[#000000ff] text-white" style={bodyStyles}>
<body className={inter.className}>
<Navbar />
<div style={contentContainerStyles}>{children}</div>
<Footer />
</body>
</html>
// </CookieContextProvider>
);
}
|
<template>
<!-- oms 订单管理 - 全部订单 - 详情页 - 添加、修改产品 -->
<el-form ref="formRef"
v-loading="updating"
:model="form"
:rules="rules"
size="mini"
label-width="100px"
class="form-col"
>
<el-row>
<el-col :span="12">
<el-form-item label="SKU编码" prop="pmsSku">
<el-input v-model="form.pmsSku" type="text" @change="pmsSkuChange">
<div slot="append" class="text-center text-primary">
<el-button type="text" @click="analyzeSku">解析</el-button>
</div>
</el-input>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="发货数量" prop="productQuantity">
<el-input v-model="form.productQuantity" v-input.positive.numeric.!0 maxlength="9" type="text" />
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-row>
<el-form-item label="SKU名称" prop="productsName">
<el-input v-model="form.productsName" type="text" disabled />
</el-form-item>
<el-form-item label="销售单价" prop="productSalePrice">
<el-input v-model="form.productSalePrice" v-input.positive.!0 :maxlength="/\.{1}/.test(form.productSalePrice)?9:8" placeholder="保留两位小数" type="text">
<span slot="suffix" style="color:#606266;">USD</span>
</el-input>
<span class="fs-6 text-danger">Note:销售单价如果非USD请自己换算为美元币种填入</span>
</el-form-item>
<el-form-item label="PMS成本价格" prop="skuCost">
<el-input v-model="form.skuCost" v-input.positive type="text" disabled>
<span slot="suffix" style="color:#606266;">RMB</span>
</el-input>
</el-form-item>
<el-form-item label="发货仓库" prop="warehouseCode">
<wareCascader :show-all-levels="false" :virtual-rule-data="virtualRuleData" class="w-100" :value.sync="form.warehouseCode" @changeFn="getSkuStock" />
</el-form-item>
</el-row>
</el-col>
<el-col :span="12">
<el-form-item label="SKU图片" prop="productPicUrl">
<el-image :src="form.productPicUrl" style="width:160px;height:160px" />
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-form-item label="当前库存量" prop="stock">
<el-input v-model="form.stock" v-input.positive.numeric type="text" disabled />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="关联订单Item" prop="platformProductId">
<el-select
v-model="form.platformProductId"
clearable
placeholder="请选择关联订单Item"
class="w-100"
>
<el-option v-for="(item, i) in orderItemList"
:key="i"
:label="item.fullName"
:value="item.combId"
/>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-form-item label="添加原因类型" prop="reasonType">
<el-select
v-model="form.reasonType"
clearable
placeholder="请选择添加原因类型"
class="w-100"
@change="reasonTypeChanged"
>
<el-option v-for="item in reasonTypeList"
:key="item.value"
:label="item.label"
:value="+item.value"
/>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="在线SKU编码" prop="originalSkuCode">
<el-input v-model="form.originalSkuCode" disabled type="text" />
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="具体原因" prop="reasonDetail">
<el-input v-model="form.reasonDetail" type="textarea" :autosize="{minRows:2,maxRows:4}" />
</el-form-item>
</el-col>
</el-row>
<div class="text-end">
<el-button size="mini" @click="close(false)">取消</el-button>
<el-button v-if="isCanUpdate" type="primary" size="mini" @click="updateOrderGood">确定</el-button>
</div>
</el-form>
</template>
<script>
import { getItemList, getOrderGood, analyzeSku, updateOrderGood, getSkuStock } from '@/api/orderManagement'
import { getPackageGood, updatePackageGood } from '@/api/packageDetails'
import { getDict } from '@/api/common/dict'
import wareCascader from '@/views/components/wareCascader/index.vue'
export default {
name: 'UpdateProduct',
components: { wareCascader },
props: {
row: Object,
omOrderId: String,
packageCode: String,
detailsType: String,
proSkuItemList: Array,
isNewProduct: Boolean, // 是否是包裹详情的新增产品
storeCode: String,
virtualRuleData: Object
},
data() {
const pmsSkuValidator = (rule, value, callback) => {
if (value === '') {
callback(new Error('SKU编码不能为空'))
} else if (this.hasPmsSkuChanged) {
callback(new Error('SKU编码已修改,请重新解析'))
} else {
callback()
}
}
const psPriceValidator = (rule, value, callback) => {
if (value === '') {
callback(new Error('销售单价不能为空'))
} else if (+value === 0) {
callback(new Error('销售单价金额不能为0'))
} else if (!/^\d+.?\d{0,2}$/.test(value)) {
callback(new Error('销售单价最多保留2位小数'))
} else {
callback()
}
}
return {
hasPmsSkuChanged: false,
orderItemList: [],
reasonTypeList: [],
form: {
pmsSku: '',
productQuantity: '',
productsName: '',
productPicUrl: '',
productSalePrice: '',
skuCost: '',
stock: '',
warehouseCode: [],
platformProductId: '',
originalSkuCode: '',
originalSkuName: '',
reasonType: '',
reasonDetail: '',
grossWeight: '',
developLeadUserId: '',
logisticsProperty: '',
omOrderGoodId: '',
discount: '',
productsTransactionNum: null
},
rules: {
pmsSku: [{ required: true, validator: pmsSkuValidator, trigger: 'blur' }],
productQuantity: [{ required: true, message: '请输入发货数量', trigger: 'blur' }],
productSalePrice: [{ required: true, validator: psPriceValidator, trigger: 'blur' }],
warehouseCode: [{ required: true, message: '请选择发货仓库' }],
productsName: [{ required: true, message: '请解析SKU编码获取SKU名称' }],
platformProductId: [{ required: true, message: '请选择关联订单Item' }],
originalSkuCode: [{ required: true, message: '请选择在线SKU编码' }],
reasonType: [{ required: true, message: '请选择添加原因类型' }],
reasonDetail: [{ required: true, message: '请输入具体原因' }]
},
updating: false,
isCanUpdate: true
}
},
computed: {
idAndItems() {
return {
id: this.form.platformProductId,
list: this.orderItemList
}
}
},
watch: {
'form.platformProductId'(val) {
if (val === '') {
this.form.originalSkuCode = ''
this.form.originalSkuName = ''
this.form.productsTransactionNum = null
return
}
this.dealItem(val, this.orderItemList)
}
},
created() {
const { row: { id, pmsSku, warehouseCode }, isNewProduct, omOrderId, detailsType } = this
if (id || isNewProduct) { // 有id或isNewProduct为true则为修改进来的,需要回显数据
this.getGoods(id)
this.getSkuStock(pmsSku, warehouseCode)
const unwatch = this.$watch('idAndItems', ({ id, list }) => {
if (id && list.length) {
this.isCanUpdate = this.dealItem(id, list)
this.isCanUpdate || this.$message.error('在线SKU或者平台产品ID已被修改,无法进行修改产品操作')
unwatch()
}
})
}
if (detailsType === 'package') this.rules.warehouseCode = null
this.getList(omOrderId)
},
methods: {
dealItem(val, list) {
const data = (list || []).find(item => item.combId === val)
if (data !== undefined) {
this.form.originalSkuCode = data.originalSkuCode
this.form.originalSkuName = data.originalSkuName
this.form.productsTransactionNum = data.productsTransactionNum
}
return data !== undefined
},
getSkuStock(pmsSku = this.form.pmsSku, wareHouseCode = this.form.warehouseCode) {
wareHouseCode = wareHouseCode.toString()
if (pmsSku === '' || wareHouseCode === '') return
getSkuStock({ pmsSku, wareHouseCode, storeCode: this.storeCode }).then(res => {
this.form.stock = res.data
})
},
getList(omOrderId) {
getItemList(omOrderId).then(res => {
this.orderItemList = (res.data ?? []).map(item => {
const { originalSkuName, platformProductId, originalSkuCode } = item
const fullName = (originalSkuName ?? '').length > 50 ? `${originalSkuName.slice(0, 50)}...(${platformProductId})` : `${originalSkuName}(${platformProductId})`
return Object.assign(item, { fullName, combId: platformProductId + originalSkuCode })
})
if (res?.data?.length) {
this.rules.platformProductId = [{ required: true, message: '请选择关联订单Item' }]
this.rules.originalSkuCode = [{ required: true, message: '请选择在线SKU编码' }]
} else {
this.rules.platformProductId = null
this.rules.originalSkuCode = null
}
})
getDict('reason_type', 'oms').then(data => {
this.reasonTypeList = data
})
},
reasonTypeChanged(val) {
const list = this.reasonTypeList
for (let i = 0; i < list.length; i++) {
if (val === +list[i].value) {
this.form.reasonTypeName = list[i].label
return
}
}
},
pmsSkuChange() {
this.hasPmsSkuChanged = true
this.reShow()
},
reShow(data = {}) {
if (this.detailsType === 'package') { // 包裹详情不再调接口,需保存数据于本地
Object.assign(this.form, data)
}
const arr = ['pmsSku', 'productQuantity', 'productSalePrice', 'warehouseCode', 'platformProductId', 'originalSkuCode', 'originalSkuName', 'reasonType', 'reasonDetail', 'omOrderGoodId']
Object.keys(this.form).forEach(key => {
switch (true) {
case arr.includes(key):
if (data?.[key] !== undefined && data?.[key] !== null) {
if (key === 'reasonType' && data.reasonType === -1) {
this.form.reasonType = ''
break
} else if (key === 'warehouseCode') {
this.form[key] = data[key] ? data[key].split(',') : []
break
} else if (key === 'productSalePrice') {
this.form[key] = Number(data[key]).toFixed(2)
break
} else if (key === 'platformProductId') {
this.form[key] = data[key] + data.originalSkuCode
break
}
this.form[key] = data[key]
}
break
case key === 'stock':
break
default:
this.form[key] = data?.[key]
break
}
})
},
updateOrderGood() {
this.$refs.formRef.validate((bool, obj) => {
const { updating, row: { id }, packageCode, form, orderItemList, detailsType, omOrderId } = this
if (!bool || updating) return
this.updating = true
const isAdd = !id && !this.isNewProduct
let [originalSkuName, platformProductId, platOrderId] = ['', '', '']
orderItemList && orderItemList.forEach(item => {
if (item.combId === this.form.platformProductId) {
originalSkuName = item.originalSkuName
platformProductId = item.platformProductId
platOrderId = item.platOrderId
}
})
const params = { id, packageCode, ...form, originalSkuName, platformProductId, platOrderId }
params.warehouseCode = params.warehouseCode.toString()
if (detailsType === 'order') {
params.omOrderId = omOrderId
delete params.packageCode
delete params.omOrderGoodId
} else { // 包裹详情页, 先保存数据到本地,此处不调用接口
params.packageCode ??= packageCode // 新增的商品需要带上packageCode
if (isAdd) {
const ifExist = this.proSkuItemList.includes(params.pmsSku + params.platformProductId)
if (ifExist) {
setTimeout(() => {
this.updating = false
this.$message.error('已存在该商品,请勿重复添加')
}, 400)
return
}
}
setTimeout(() => {
this.updating = false
this.$message.success('操作成功,请勿刷新当前页面')
this.close(true, params)
}, 400)
return
}
this.getQuery(updateOrderGood, updatePackageGood, params, isAdd)
.then((res) => {
this.$message.success(res.msg)
this.close(true)
}).finally(() => {
this.updating = false
})
})
},
analyzeSku() {
const { pmsSku } = this.form
if (this.updating) return
if (pmsSku === '') {
return this.$message.error('SKU编码不能为空')
}
this.updating = true
analyzeSku(pmsSku).then(({ data }) => {
if (data === null) this.$message.error('解析失败')
else this.$message.success('解析成功')
this.getSkuStock()
this.reShow(data)
this.hasPmsSkuChanged = false
this.$refs.formRef.clearValidate('pmsSku')
}).finally(() => {
this.updating = false
})
},
getGoods(id) {
const { detailsType, row } = this
if (detailsType === 'package') {
return this.reShow(row)
}
this.getQuery(getOrderGood, getPackageGood, id).then(res => {
this.reShow(res.data)
})
},
getQuery(orderFn, packageFn, ...arg) {
const { detailsType } = this
return { order: orderFn, package: packageFn }[detailsType](...arg)
},
close(isUpdate = false, data) {
this.$parent.$emit('close', isUpdate, data)
}
}
}
</script>
|
// SPDX-License-Identifier: ISC
pragma solidity 0.7.5;
pragma abicoder v2;
import "../IAdapter.sol";
import "../../lib/uniswapv2/NewUniswapV2.sol";
import "../../lib/curve/Curve.sol";
import "../../lib/aavee2/Aavee2.sol";
import "../../lib/weth/WethExchange.sol";
import "../../lib/curve/CurveV2.sol";
import "../../lib/dodov2/DODOV2.sol";
import "../../lib/mstable/MStable.sol";
import "../../lib/curveFork/CurveV1ForkAdapter.sol";
import "../../lib/balancerv2/BalancerV2.sol";
import "../../lib/kyberdmm/KyberDmm.sol";
import "../../lib/zeroxv4/ZeroxV4.sol";
import "../../lib/jarvis/Jarvis.sol";
import "../../lib/uniswapv3/UniswapV3.sol";
/*
* @dev This contract will route calls to dexes according to the following indexing:
* 1- AAVEE2
* 2- Wmatic
* 3- Curve
* 4- UniswapV2Forks
* 5- CurveV2
* 6- MStable
* 7- CurveV1ForkAdapter
* 8- DODOV2
* 9- BalancerV2
* 10- KyberDmm
* 11- 0xV4
* 12- Jarvis
* 13- UniswapV3
*/
contract PolygonAdapter01 is
IAdapter,
NewUniswapV2,
Curve,
Aavee2,
WethExchange,
CurveV2,
MStable,
CurveV1ForkAdapter,
DODOV2,
BalancerV2,
KyberDmm,
ZeroxV4,
Jarvis,
UniswapV3
{
using SafeMath for uint256;
/*solhint-disable no-empty-blocks*/
constructor(
uint16 _aaveeRefCode,
address _aaveeLendingPool,
address _aaveeWethGateway,
address _weth,
uint256 _dodoV2SwapLimitOverhead,
address _dodoV2Erc20ApproveProxy
)
public
WethProvider(_weth)
DODOV2(_dodoV2SwapLimitOverhead, _dodoV2Erc20ApproveProxy)
Aavee2(_aaveeRefCode, _aaveeLendingPool, _aaveeWethGateway)
{}
/*solhint-enable no-empty-blocks*/
function initialize(bytes calldata) external override {
revert("METHOD NOT IMPLEMENTED");
}
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256,
Utils.Route[] calldata route
) external payable override {
for (uint256 i = 0; i < route.length; i++) {
if (route[i].index == 1) {
swapOnAaveeV2(fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].payload);
} else if (route[i].index == 2) {
swapOnWETH(fromToken, toToken, fromAmount.mul(route[i].percent).div(10000));
} else if (route[i].index == 3) {
swapOnCurve(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 4) {
swapOnUniswapV2Fork(fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].payload);
} else if (route[i].index == 5) {
swapOnCurveV2(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 6) {
swapOnMStable(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 7) {
swapOnCurveV1Fork(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 8) {
//swap on DODOV2
swapOnDodoV2(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 9) {
swapOnBalancerV2(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 10) {
swapOnKyberDmm(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 11) {
//swap on 0xV4
swapOnZeroXv4(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 12) {
//swap on Jarvis
swapOnJarvis(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else if (route[i].index == 13) {
//swap on uniswapv3
swapOnUniswapV3(
fromToken,
toToken,
fromAmount.mul(route[i].percent).div(10000),
route[i].targetExchange,
route[i].payload
);
} else {
revert("Index not supported");
}
}
}
}
|
import mongoose from 'mongoose'
import { Types } from 'mongoose'
import { updateIfCurrentPlugin } from 'mongoose-update-if-current'
import { Type } from 'typescript'
interface storeAttrs {
title: string
description?: string
summary?: string
goodKind?: number
madeIn?: number
material?: string
width?: number
length?: number
height?: number
weight?: number
photoNum?: number
photos?: [string]
availableQuantity?: number
ratingsAverage?: number
ratingsQuantity?: number
comments?: [
{
id?: Types.ObjectId
name?: string
message?: string
rate?: number
createdAt?: Date
}
]
price?: number
hasDiscount?: boolean
discountKind?: number
discountedPrice?: number
hasMag?: boolean
magLink?: string
createdBy?: Types.ObjectId
createdAt?: Date
}
interface storeDoc extends mongoose.Document {
title: string
description?: string
summary?: string
goodKind?: number
madeIn?: number
material?: string
width?: number
length?: number
height?: number
weight?: number
photoNum?: number
photos?: [string]
availableQuantity?: number
ratingsAverage?: number
ratingsQuantity?: number
comments?: [
{
id?: Types.ObjectId
name?: string
message?: string
rate?: number
createdAt?: Date
}
]
price?: number
hasDiscount?: boolean
discountKind?: number
discountedPrice?: number
hasMag?: boolean
magLink?: string
createdBy?: Types.ObjectId
createdAt?: Date
version: number
}
interface storeModel extends mongoose.Model<storeDoc> {
build(attrs: storeAttrs): storeDoc
}
const storeSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
unique: true,
},
description: {
type: String,
required: false,
},
summary: {
type: String,
required: false,
},
goodKind: {
type: Number,
required: false,
},
madeIn: {
type: Number,
required: false,
},
width: {
type: Number,
required: false,
},
length: {
type: Number,
required: false,
},
height: {
type: Number,
required: false,
},
weight: {
type: Number,
required: false,
},
material: {
type: String,
required: false,
},
photoNum: {
type: Number,
required: false,
},
photos: [
{
type: String,
required: false,
},
],
availableQuantity: {
type: Number,
required: false,
},
ratingsAverage: {
type: Number,
required: true,
default: 0,
},
ratingsQuantity: {
type: Number,
required: true,
default: 0,
},
comments: [
{
id: Types.ObjectId,
name: String,
message: String,
rate: Number,
createdAt: Date,
},
],
price: {
type: Number,
required: false,
},
hasDiscount: {
type: Boolean,
required: true,
default: false,
},
discountKind: {
type: Number,
required: false,
},
discountedPrice: {
type: Number,
required: false,
},
hasMag: {
type: Boolean,
},
magLink: {
type: String,
required: false,
},
createdBy: {
type: Types.ObjectId,
required: false,
},
createdAt: {
type: Date,
required: true,
default: Date.now,
},
},
{
toJSON: {
transform(doc, ret) {
ret.id = ret._id
delete ret._id
},
},
}
)
storeSchema.set('versionKey', 'version')
storeSchema.plugin(updateIfCurrentPlugin)
storeSchema.statics.build = (attrs: storeAttrs) => {
return new Store(attrs)
}
const Store = mongoose.model<storeDoc, storeModel>('Store', storeSchema)
export { Store }
|
<template>
<div class="resto-group__wrapper mb-5">
<div class="row">
<div class="col-md-4 mb-4" v-for="resto in localResto" :key="resto.id">
<card-component>
<template slot="title">
{{ resto.name }}
</template>
<template slot="body">
<div class="d-flex align-items-center">
<img src="pin.svg" class="icon-size m-1">
{{ resto.location }}
</div>
<div class="d-flex align-items-center">
<img src="umbrella.svg" class="icon-size m-1">
{{ resto.tables }}
</div>
<br>
<a v-bind:href="resto.slug" class="card-link ml-1">Menu</a>
<a v-bind:href="resto.ordersSlug" class="card-link ml-1">Orders</a>
</template>
</card-component>
</div>
<div class="col-md-4" v-if="showAddForm">
<card-component>
<template slot="title">Add New Resturant</template>
<template slot="body">
<div class="d-flex justify-content-center align-items-center">
<img src="more.svg" class="plus-icon-size m-1" @click="handleAddNewResturant">
</div>
</template>
</card-component>
<Modal name="add-new-resto" height="400px">
<div class="container-padding">
<resto-add-form @modalCancel="handleCancelResto" @addRestoEvent="handleAddResto"></resto-add-form>
</div>
</Modal>
</div>
</div>
</div>
</template>
<script>
import RestoAddForm from './RestoAddForm';
import axios from 'axios';
export default {
components: {
RestoAddForm
},
props: ['restos'],
created() {
this.localResto = this.restos
},
computed : {
showAddForm(){
return (this.localResto.length < 5) ? true : false
}
},
data(){
return {
localResto : []
}
},
methods: {
handleAddNewResturant(){
this.$modal.show('add-new-resto');
},
handleAddResto(resto_data){
axios.post('/api/resto', resto_data).then(response=>this.localResto.unshift(response.data))
this.$modal.hide('add-new-resto');
},
handleCancelResto(){
this.$modal.hide('add-new-resto');
}
}
}
</script>
|
import { Avatar, Box, Skeleton, Typography } from '@mui/material';
import { useEffect, useState, useCallback } from 'react';
import { useParams } from 'react-router-dom';
import SpotifyWebApi from 'spotify-web-api-node';
import SongTable from '../components/SongTable/SongTable';
interface Props {
spotifyApi: SpotifyWebApi;
token: string;
}
interface PlaylistInfo {
image: string;
name: string;
}
interface Status {
isLoading: boolean;
isError: Error | null;
}
interface CustomTrackObjectFull extends SpotifyApi.TrackObjectFull {
contextUri: string;
position: number;
}
interface Song extends CustomTrackObjectFull {}
const Playlist = ({ spotifyApi, token }: Props) => {
const [playlistInfo, setPlaylistInfo] = useState<PlaylistInfo | undefined>();
const [songs, setSongs] = useState<CustomTrackObjectFull[]>([]);
const [status, setStatus] = useState<Status>({ isLoading: false, isError: null });
const { id: idParam } = useParams<{ id: string }>();
const id = idParam ?? '';
const formatSongData = useCallback(
(songs: SpotifyApi.PlaylistTrackObject[]) => {
return songs.map((song, i: number) => {
const track = song.track as CustomTrackObjectFull;
track.contextUri = `spotify:playlist:${id}`;
track.position = i;
return track;
});
},
[id]
);
useEffect(() => {
const getData = async () => {
setStatus((prev) => ({ ...prev, isLoading: true }));
try {
const playlistDetail = await spotifyApi.getPlaylist(id);
const playlistData = playlistDetail.body;
setPlaylistInfo({
image: playlistData.images[0].url,
name: playlistData.name
});
const { tracks } = playlistData;
const formattedSongs = formatSongData(tracks.items);
setSongs(formattedSongs);
} catch (error) {
setStatus((prev) => ({ ...prev, isError: error as Error }));
} finally {
setStatus((prev) => ({ ...prev, isLoading: false }));
}
};
if (id) {
getData();
}
}, [formatSongData, id, spotifyApi, token]);
return (
<Box id="Playlist__page" sx={{ bgcolor: 'background.paper', flex: 1, overflowY: 'auto' }}>
<Box
p={{ xs: 3, md: 4 }}
sx={{
width: '100%',
background: 'linear-gradient(0deg, #121212 0%, #1bd76060 100%);',
display: 'flex',
justifyContent: 'flex-start',
alignItems: { xs: 'flex-start', md: 'flex-end', xl: 'center' },
gap: 3,
boxSizing: 'border-box',
flexDirection: { xs: 'column', md: 'row' }
}}
>
{status.isLoading ? (
<Skeleton
variant="rectangular"
sx={{
width: { sx: '100%', md: 235 },
height: { sx: '100%', md: 235 }
}}
/>
) : (
<Avatar
src={playlistInfo?.image}
variant="square"
alt={playlistInfo?.name}
sx={{
boxShadow: 15,
width: { sx: '100%', md: 235 },
height: { sx: '100%', md: 235 }
}}
/>
)}
<Box>
<Typography sx={{ fontSize: 12, fontWeight: 'bold', color: 'text.primary' }}>Playlist</Typography>
{status.isLoading ? (
<Skeleton
variant="text"
sx={{
fontSize: { xs: 42, md: 72 },
width: 200
}}
/>
) : (
<Typography
sx={{
fontSize: { xs: 42, md: 72 },
fontWeight: 'bold',
color: 'text.primary'
}}
>
{playlistInfo?.name}
</Typography>
)}
</Box>
</Box>
<SongTable songs={songs} loading={status.isLoading} spotifyApi={spotifyApi} />
</Box>
);
};
export default Playlist;
|
import styled, { css } from "styled-components";
interface StyledButtonStandartProps {
primary?: boolean;
outlined?: boolean;
display?: "flex";
alignItems?: "start" | "center" | "end";
justify?: "start" | "center" | "end";
type?: "submit";
}
export const StyledButtonStandart = styled.button.attrs((props) => ({
type: props.type || "button",
}))<StyledButtonStandartProps>`
font-size: 16px;
font-weight: 600;
line-height: 22px;
border-radius: 8px;
text-align: center;
cursor: pointer;
${({ display, justify, alignItems }) => {
switch (display) {
case "flex":
return css`
display: flex;
justify-content: ${justify || "center"};
align-items: ${alignItems || "center"};
`;
default:
return css`
display: block;
`;
}
}};
${(props) =>
props.primary &&
css`
color: ${({ theme }) => theme.colors.white};
background-color: ${({ theme }) => theme.colors.primary};
border: 2px solid ${({ theme }) => theme.colors.primary};
`}
${(props) =>
props.outlined &&
css`
color: ${({ theme }) => theme.colors.primary};
background-color: transparent;
border: 2px solid ${({ theme }) => theme.colors.primary};
`}
`;
|
/// <reference types="cypress"/>
describe('Work with Popup', () =>{
it('Deve testar popup diretamente', () =>{
cy.visit('https://wcaquino.me/cypress/frame.html')
cy.get('#otherButton').click()
cy.on('window:alert', msg =>{
expect(msg).to.be.equal('Click OK!')
})
})
it.only('Deve verificar se o popup foi invocado', () =>{
cy.visit('https://wcaquino.me/cypress/componentes.html')
cy.window().then(win =>{
cy.stub(win, 'open').as('winOpen')
})
cy.get('#buttonPopUp').click()
cy.get('@winOpen').should('be.called') //aqui ele procura pelo nome que demos ao stub, e valida com o should
})
//vamos testar o iframe com link, primeiro vamos ver se o link está apontando para o endereço correto
describe.only('Work with popup with link', ()=>{
beforeEach(() =>{
cy.visit('https://wcaquino.me/cypress/componentes.html')
})
it('Check popup url', () =>{
cy.contains('Popup2')
.should('have.prop', 'href')
.and('equal', 'https://wcaquino.me/cypress/frame.html')
})
//aqui vamos set uma variável como endereço do link, para não quebrar o test qdo o link for alterado
it('Should access popup dinamically', ()=>{
cy.contains('Popup2').then($a =>{
const href = $a.prop('href')
cy.visit(href)
cy.get('#tfield').type('Funcionou!')
})
})
//vamos retirar o _blank para o link não abrir em outra pagina, de outra forma para testarmos com invoke
it('Should force link on same page', () =>{
cy.contains('Popup2')
.invoke('removeAttr', 'target') //pedindo para remover o atributo target
.click()
cy.get('#tfield').type('Funcionou...')
})
})
})
|
import axios from "axios";
import { useEffect, useState } from "react"
import { schema } from "../formSchema/schema";
import * as yup from "yup";
import { useLoaderData } from "react-router-dom";
import { useLocalStorage } from "./useLocalStorage";
export const initialState = {
fname : "",
lname : "",
email : "",
message : "",
}
export const initialStateForStatus = {
submitted : false,
submitting : false,
info : {error : false, msg : null},
}
export const useForm = (initialState, initialStateForStatus, key) => {
const [data,setData] = useLocalStorage(initialState,key);
const [status,setStatus] = useState(initialStateForStatus);
const [disabled,setDisabled] = useState(true);
const [errorData,setErrorData] = useState({
fname : "",
lname : "",
email : "",
message : "",
});
const [showMessage,setShowMessage] = useState(false)
useEffect(()=> {
schema.isValid(data).then(valid=> setDisabled(!valid))
},[data])
const formFieldValidation = (name,value) => {
yup.reach(schema,name).validate(value).then(()=>
setErrorData({...errorData, [name] : ""})
)
.catch(err=> setErrorData({...errorData, [name] : err.errors[0]}))
}
const changeHandler = (name,value) => {
formFieldValidation(name,value);
setData({...data, [name] : value});
}
const submissionHandler = (e) => {
e.preventDefault();
setStatus({...status, submitting : true});
axios.post("https://formspree.io/f/mleylajq",data)
.then(()=> {
setStatus(initialStateForStatus)
setShowMessage(true);
setStatus({...status, info : {...status.info, msg : "Thanks for reaching out. I will be in contact soon!"}})
})
.catch(err=> {
setShowMessage(true);
setStatus({...status, [status.info.msg] : err.message})
})
.finally(()=> {
setData(initialState);
} )
}
const closeShowMessage = () => {
window.localStorage.clear();
setStatus(initialStateForStatus);
setShowMessage(false);
}
return [data,changeHandler,submissionHandler,status,showMessage,closeShowMessage,errorData,disabled]
}
|
/*******************************************************************************
* Copyright 2017 DataRPM
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package com.datarpm.sigma.event.core;
import java.io.IOException;
import com.datarpm.sigma.event.core.channel.EventChannel;
import com.datarpm.sigma.event.core.channel.EventChannelFactory;
/**
* @author vishal
*
*/
public class EventEngine implements EventEngineDef {
public static final EventEngine INSTANCE = new EventEngine();
private EventChannel eventChannel;
private EventEngine() {
try {
eventChannel = new EventChannelFactory().createChannel();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public void generateEvent(Event event) {
eventChannel.publishEvent(event);
}
@Override
public RegistryId addListner(final EventMatchFilter matchFilter, final EventCallBack callback) {
RegistryId registryId = new RegistryId();
eventChannel.registerListner(registryId, new EventCallBack() {
@Override
public void onEvent(Event event) {
if (matchFilter.allow(event.getHeader())) {
callback.onEvent(event);
}
}
});
return registryId;
}
@Override
public void removeListner(RegistryId registryId) {
eventChannel.removeListner(registryId);
}
}
|
package be.kdg.twitterandroid.services;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.io.IOException;
import be.kdg.twitterandroid.config.Constants;
import be.kdg.twitterandroid.services.exceptions.NotAllowedException;
import be.kdg.twitterandroid.services.exceptions.NotFoundException;
import be.kdg.twitterandroid.services.exceptions.RateLimitExceededException;
import be.kdg.twitterandroid.services.exceptions.UnauthorizedException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer;
import se.akerfeldt.okhttp.signpost.SigningInterceptor;
/**
* Created by Maarten on 14/01/2016.
*/
public class TwitterServiceFactory {
private static TweetService tweetService;
private static UserService userService;
private static Retrofit retrofit;
private TwitterServiceFactory() {
}
public static void setOAuthTokens(String token, String tokenSecret) {
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(
Constants.API_KEY,
Constants.API_SECRET
);
consumer.setTokenWithSecret(token, tokenSecret);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new SigningInterceptor(consumer))
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
System.out.println(String.format("[%d] %s", response.code(), request.url()));
switch (response.code()) {
case 328:
case 403:
throw new NotAllowedException();
case 401:
throw new UnauthorizedException();
case 404:
throw new NotFoundException();
case 429:
throw new RateLimitExceededException();
}
return response;
}
})
.build();
retrofit = new Retrofit.Builder()
.baseUrl(Constants.API_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
public static void setOAuthTokensFromSharedPreferences(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
setOAuthTokens(prefs.getString("token", null), prefs.getString("tokenSecret", null));
}
public static synchronized TweetService getTweetService() {
if (tweetService == null) tweetService = retrofit.create(TweetService.class);
return tweetService;
}
public static synchronized UserService getUserService() {
if (userService == null) userService = retrofit.create(UserService.class);
return userService;
}
}
|
import * as fal from "npm:@fal-ai/serverless-client";
import { loadEnv } from "../shared/util.ts";
import * as log from "../shared/logger.ts";
const env = loadEnv();
if (!env.FAL_API_KEY) log.warn("No FAL_API_KEY in .env file");
fal.config({
credentials: env.FAL_API_KEY,
});
import { Application, Router } from "https://deno.land/x/oak@v12.6.1/mod.ts";
import { makeImage } from "../shared/openai.ts";
import { createExitSignal, staticServer } from "../shared/server.ts";
const app = new Application();
const router = new Router();
// Function to transform prompt to sketch-style based on iteration
function transformToSketchPrompt(prompt, iteration) {
if (iteration === 1) {
return `A simple, low-fidelity sketch of ${prompt} drawn as if by a designer
or artist during the initial iteration stage. The sketch should be executed
with a light gray pencil imitating a sketch book aeshtic. The sketch should
feature the basics, reflecting the simplicity and roughness typical of a first
draft sketch.`;
} else if (iteration === 2) {
return `make a second skecth based on the first iteration of the sketch ${prompt}`; // More detailed or refined sketch for the second iteration
}
return prompt;
}
// Modified DALL•E route to handle iterations
router.get("/api/dalle", async (ctx) => {
const originalPrompt = ctx.request.url.searchParams.get("prompt");
const iteration = parseInt(ctx.request.url.searchParams.get("iteration") || "1");
const sketchPrompt = transformToSketchPrompt(originalPrompt, iteration);
console.log("Sketch Prompt for iteration", iteration, ":", sketchPrompt);
const result = await makeImage(sketchPrompt);
ctx.response.body = result;
});
// Install routes
app.use(router.routes());
app.use(router.allowedMethods());
// Set up to serve static files from public
app.use(staticServer);
// Tell the user we are about to start
console.log("\nListening on http://localhost:8000");
// Start the web server
await app.listen({ port: 8000, signal: createExitSignal() });
|
import { BadRequestException, Injectable } from '@nestjs/common';
import { IngredientsRepository } from '../repositories';
import { CreateIngredientDto } from '../dto';
import { isDuplicatedKeyError } from '@app/common';
@Injectable()
export class IngredientsService {
constructor(private readonly ingredientsRepository: IngredientsRepository) {}
async getIngredientByName(name: string) {
return this.ingredientsRepository.findOne({ name });
}
async createIngredient(createIngredientDto: CreateIngredientDto) {
try {
return await this.ingredientsRepository.create(createIngredientDto);
} catch (error) {
if (isDuplicatedKeyError(error)) {
throw new BadRequestException(
'Ingredient with this name already exists',
);
}
}
}
}
|
package cafe.lunarconcerto.matrixcafe.api.common;
public enum ApplicationState {
/**
* 初始化状态,
* <p>
* 该状态为起始状态, 启动应用程序时自动进入该状态,
* 初始化完成后程序进入 {@link ApplicationState#STANDBY} 状态.
* 在该状态下, 系统运行各类初始化工作.
*/
INITIALIZING,
/**
* 待命状态,
* <p>
* 在该状态下, 系统维持正常运行,
* 但不进行消息处理, 此时可以进行设置等.
*/
STANDBY,
/**
* 工作状态,
* <p>
* 在该状态下, 系统正常的接收以及处理消息
*/
WORKING,
/**
* 错误状态,
* <p>
* 该状态下, 系统处于运行状态, 并尽可能输出错误日志
*/
ERROR,
/**
* 调试状态
* <p>
* TODO
*/
DEBUG,
/**
* 关闭状态,
* <p>
* 该状态为终结状态.
* 该状态下,
* 系统开始进行关闭逻辑, 最后执行程序退出.
*/
CLOSING
}
|
//
// TeamUserVC.swift
// Almnabr
//
// Created by MacBook on 19/10/2021.
// Copyright © 2021 Samar Akkila. All rights reserved.
//
import UIKit
import DPLocalization
import FontAwesome_swift
import DropDown
class TeamUserVC: UIViewController {
@IBOutlet weak var lblPosition: UILabel!
@IBOutlet weak var viewPosition: UIView!
@IBOutlet weak var btnPosition: UIButton!
@IBOutlet weak var imgDropPosition: UIImageView!
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var table: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var viewsearch: UIView!
@IBOutlet weak var img_nodata: UIImageView!
@IBOutlet weak var tableHeightConstraint:NSLayoutConstraint!
var StrTitle:String = ""
var StrSubMenue:String = ""
var StrPosition:String = ""
var SearchKey:String = ""
var pageNumber = 1
var total:Int = 0
var allItemDownloaded = false
var MenuObj:MenuObj?
var SubMenuObj:MenuObj?
var arr_data:[projectQuotObj] = []
var arr_Position:[ModuleObj] = []
var arr_PositionLabel:[String] = []
var arr_NoData:[String] = ["No items found".localized()]
let dropUpmage = UIImage.fontAwesomeIcon(name: .chevronUp , style: .solid, textColor: .gray, size: CGSize(width: 40, height: 40))
let dropDownmage = UIImage.fontAwesomeIcon(name: .chevronDown , style: .solid, textColor: .gray, size: CGSize(width: 40, height: 40))
override public func viewDidLoad() {
super.viewDidLoad()
configGUI()
get_TeamUsers_data(showLoading: true, loadOnly: true)
get_Position()
}
func configNavigation() {
_ = self.navigationController?.preferredStatusBarStyle
self.view.backgroundColor = "FFFFFF".getUIColor() //F0F4F8
navigationController?.navigationBar.barTintColor = .red
addNavigationBarTitle(navigationTitle: StrTitle)
}
func configGUI() {
//self.viewPosition.setBorderGray()
self.viewPosition.setBorderGrayWidthCorner(1, 20)
self.lblPosition.text = "txt_Position".localized()
self.lblPosition.font = .kufiRegularFont(ofSize: 15)
btnPosition.isHidden = true
//self.mainView.setBorderGray()
self.img_nodata.isHidden = false
searchBar.delegate = self
self.imgDropPosition.image = dropDownmage
table.dataSource = self
table.delegate = self
let nib = UINib(nibName: "TeamUserTVCell", bundle: nil)
table.register(nib, forCellReuseIdentifier: "TeamUserTVCell")
}
func get_TeamUsers_data(showLoading: Bool, loadOnly: Bool){
if showLoading {
self.showLoadingActivity()
}
let search:String = SearchKey.replacingOccurrences(of: " ", with: "%20").trim()
APIController.shard.sendRequestGetAuth(urlString: "PMypAe3X1IuW3jx/\(projects_profile_id)/\(projects_work_area_id)/\(pageNumber)/10?searchKey=\(search)&positions=\(StrPosition)" ) { (response) in
if self.pageNumber == 1 {
self.arr_data.removeAll()
}
let status = response["status"] as? Bool
if loadOnly {
self.table.reloadData()
}
let page = response["page"] as? [String:Any]
if status == true{
if let records = response["records"] as? NSArray{
for i in records {
let dict = i as? [String:Any]
let obj = projectQuotObj.init(dict!)
self.arr_data.append(obj)
}
let pageObj = PageObj(page!)
if self.arr_data.count == 0 {
self.img_nodata.isHidden = false
}else{
self.img_nodata.isHidden = true
}
if pageObj.total_pages > self.pageNumber {
self.allItemDownloaded = false
}else{
self.allItemDownloaded = true
}
self.table.reloadData()
self.hideLoadingActivity()
}
}else{
self.hideLoadingActivity()
self.img_nodata.isHidden = false
}
}
}
func get_Position(){
self.showLoadingActivity()
APIController.shard.sendRequestGetAuth(urlString: "/366484fd45" ) { (response) in
let status = response["status"] as? Bool
if status == true{
if let list = response["records"] as? NSArray{
for i in list {
let dict = i as? [String:Any]
let obj = ModuleObj.init(dict!)
self.arr_Position.append(obj)
self.arr_PositionLabel.append(obj.label)
}
self.hideLoadingActivity()
}
}
self.hideLoadingActivity()
}
}
@IBAction func btnPosition_Click(_ sender: Any) {
self.imgDropPosition.image = dropUpmage
let vc :PickerVC = AppDelegate.mainSB.instanceVC()
vc.arr_data = arr_PositionLabel
vc.isModalInPresentation = true
vc.modalPresentationStyle = .overFullScreen
vc.definesPresentationContext = true
vc.delegate = {name , index in
if name == self.arr_PositionLabel[index] {
self.lblPosition.text = name
let i = self.arr_Position[index]
self.StrPosition = i.value
self.btnPosition.isHidden = false
self.imgDropPosition.image = self.dropDownmage
self.get_TeamUsers_data(showLoading: true, loadOnly: true)
}
}
self.present(vc, animated: true, completion: nil)
}
@IBAction func btnPositionDelete_Click(_ sender: Any) {
self.lblPosition.text = "txt_Position".localized()
self.btnPosition.isHidden = true
self.StrPosition = ""
get_TeamUsers_data(showLoading: true, loadOnly: true)
}
}
extension TeamUserVC: UITableViewDelegate , UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr_data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TeamUserTVCell", for: indexPath) as! TeamUserTVCell
let obj = arr_data[indexPath.item]
let Name = "\(obj.label)"
let Title = "Title".localized() + ": \(obj.teamtitle)"
let Positions = "\(obj.position)"
let Role = "Role".localized() + " \(obj.project_user_group_mention_key)"
let writer = "By".localized() + ": \(obj.writer)"
let Date = "\(obj.project_user_group_created_datetime)"
let maincolor = "#1A3665".getUIColor()
cell.lblName.text = Name
cell.lblPosition.text = Positions
cell.lblWriter.text = writer
cell.lblDate.text = Date
let Titleattribute: NSAttributedString = Title.attributedStringWithColor(["Title"], color: maincolor)
cell.lblTitle.attributedText = Titleattribute
let Roleattributed: NSAttributedString = Role.attributedStringWithColor(["Role".localized()], color: maincolor)
cell.lblRole.attributedText = Roleattributed
let writerattributed: NSAttributedString = writer.attributedStringWithColor(["writer".localized()], color: maincolor)
cell.lblWriter.attributedText = writerattributed
cell.viewBack.setRounded(12)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableView.tag == 0 {
print(indexPath.section)
if indexPath.row == arr_data.count - 1 {
updateNextSet()
print("next step")
}
}
}
func updateNextSet(){
print("On Completetion")
if !allItemDownloaded {
pageNumber = pageNumber + 1
get_TeamUsers_data(showLoading: false, loadOnly: false)
}
}
}
extension TeamUserVC:UISearchBarDelegate {
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.SearchKey = searchBar.text!
get_TeamUsers_data(showLoading: false, loadOnly: false)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//searchBar.resignFirstResponder()
self.SearchKey = searchBar.text!
get_TeamUsers_data(showLoading: false, loadOnly: false)
searchBar.resignFirstResponder()
}
}
|
# BankEase: Modern Online Banking Solution
BankEase is a modern and user-friendly online banking solution that aims to simplify your financial management. It provides a seamless and secure experience for users to manage their accounts, transactions, and more.
## Features
### 1. Account Overview
Easily view all your accounts at a glance, including balances, recent transactions, and account details.
```python
# Sample code for retrieving account overview
from bankease import BankEase
# Initialize the BankEase object with user credentials
bank = BankEase(username='your_username', password='your_password')
# Get account overview
account_overview = bank.get_account_overview()
# Display account information
print(account_overview)
```
### 2. Transaction History
Retrieve and analyze your transaction history with powerful filtering options.
```python
# Sample code for retrieving transaction history
from bankease import BankEase
# Initialize the BankEase object with user credentials
bank = BankEase(username='your_username', password='your_password')
# Get transaction history
transactions = bank.get_transaction_history(account_id='your_account_id', start_date='2023-01-01', end_date='2023-12-31')
# Display transaction history
print(transactions)
```
### 3. Fund Transfers
Initiate fund transfers between your accounts or to other accounts seamlessly.
```python
# Sample code for initiating fund transfer
from bankease import BankEase
# Initialize the BankEase object with user credentials
bank = BankEase(username='your_username', password='your_password')
# Initiate fund transfer
transfer_result = bank.transfer_funds(from_account='your_source_account', to_account='your_destination_account', amount=100.00, description='Payment for services')
# Display transfer result
print(transfer_result)
```
### 4. Bill Payments
Effortlessly pay your bills with BankEase's integrated bill payment system.
```python
# Sample code for paying bills
from bankease import BankEase
# Initialize the BankEase object with user credentials
bank = BankEase(username='your_username', password='your_password')
# Pay a bill
bill_payment_result = bank.pay_bill(bill_id='your_bill_id', amount=50.00)
# Display bill payment result
print(bill_payment_result)
```
### Installation
To use BankEase in your project, simply install it via pip:
```bash
pip install bankease
```
### Security
BankEase prioritizes the security of your financial information. All communication is encrypted using industry-standard protocols.
### About Me
I'm Biomedical Laboratory Scientist who started learning Software Engineering without computer background, now I'm in final stage of foundation program in full stack software engineering program with my effort of doing hard things for better future.
I have started from nowhere without knowing where to start and which file to create first, which programming languages to be used or any technical tools to be used but now I'm ready for doing anything new in software engineering.
In Portfolio project as solo developer, I have learned many things about time management, working on different things in short time, to work in extra-time in order to finish on time. Generally, I have learned about how to face the problem and how to solve it in a certain time.
LinkedIn: https://www.linkedin.com/in/jeandamn
Instagram: https://lnkd.in/dGTg2pJu
Twitter (X): https://lnkd.in/dt-qCJ9H
Facebook: https://lnkd.in/dQHVZg52
YouTube: https://lnkd.in/dVGRReSd
BankEase: https://lnkd.in/dP-NFp5U
|
import { useCallback, useEffect, useRef, useState } from "react"
interface ClickAndDragArgs {
callback: ({ x, y, event }: { x?: number; y?: number; event?: MouseEvent }) => void
}
interface ClickAndDrag {
isDragging: boolean
ref: React.MutableRefObject<any>
}
export function useClickAndDrag({ callback }: ClickAndDragArgs): ClickAndDrag {
const ref = useRef<any>(null)
const [isDragging, setIsDragging] = useState<boolean>(false)
const handleMouseDown = useCallback(
(event: MouseEvent) => {
event.stopPropagation()
event.preventDefault()
setIsDragging(true)
callback({ x: event.clientX, y: event.clientY, event })
},
[callback]
)
const handleMouseMove = useCallback(
(event: MouseEvent) => {
event.stopPropagation()
event.preventDefault()
if (isDragging) {
callback({ x: event.clientX, y: event.clientY, event })
}
},
[callback, isDragging]
)
const handleMouseUp = useCallback(() => {
if (isDragging) {
setIsDragging(false)
}
}, [isDragging])
useEffect(() => {
const node = ref.current
if (node) {
node.addEventListener("mousedown", handleMouseDown)
window.addEventListener("mousemove", handleMouseMove)
window.addEventListener("mouseup", handleMouseUp)
return () => {
node.removeEventListener("mousedown", handleMouseDown)
window.removeEventListener("mousemove", handleMouseMove)
window.removeEventListener("mouseup", handleMouseUp)
}
}
}, [handleMouseDown, handleMouseMove, handleMouseUp])
return {
isDragging,
ref,
}
}
|
import logging
import xml.etree.ElementTree as ET
from typing import Tuple
import requests
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from spaceone.core.connector import BaseConnector
from spaceone.core.error import ERROR_AUTHENTICATE_FAILURE, ERROR_NOT_FOUND
_LOGGER = logging.getLogger(__name__)
class SamlConnector(BaseConnector):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.saml_settings = {}
def init(self, options: dict) -> dict:
"""Checks the connection using the SAML metadata URL.
Args:
options: 'dict'
'protocol': 'str',
'identity_provider': 'str',
'icon': 'str',
'metadata_url': 'str',
Returns:
'metadata': 'dict'
"""
protocol = options.get("protocol", "saml")
identity_provider = options.get("identity_provider")
icon = options.get("icon")
metadata_url = options.get("metadata_url")
xml_data = self._fetch_xml(metadata_url)
_, _, sso_url = self._parse_idp_xml(xml_data)
idp_name = self._get_idp_name(identity_provider)
metadata = {
"identity_provider": identity_provider,
"protocol": protocol,
"icon": icon,
"idp_name": idp_name,
"sso_url": sso_url,
}
return metadata
def authorize(self, params: dict, metadata_url: str, domain_id: str) -> dict:
"""Authorizes the user using SAML.
Args:
'params': 'dict',
'metadata_url': 'str',
'domain_id': 'str',
Returns:
'user_info': 'dict'
Raises:
ERROR_AUTHENTICATE_FAILURE: If authentication fails
"""
self._set_saml_settings(params, metadata_url, domain_id)
auth = OneLogin_Saml2_Auth(
params,
self.saml_settings,
)
auth.process_response()
errors = auth.get_errors()
if not errors and auth.is_authenticated():
user_info = self._get_user_info_from_auth(auth)
return user_info
_LOGGER.error(
f"[authorize] ERROR_AUTHENTICATE_FAILURE: {errors}",
)
raise ERROR_AUTHENTICATE_FAILURE(
message=f"ERROR_AUTHENTICATE_FAILURE: {errors}"
)
@staticmethod
def _get_user_info_from_auth(auth: OneLogin_Saml2_Auth) -> dict:
"""Extracts user information from the SAML authentication response.
Args:
'auth': 'OneLogin_Saml2_Auth'
Returns:
'user_info': 'dict'
'user_id': 'str'
"""
try:
name_id = auth.get_nameid()
user_info = {"user_id": name_id}
return user_info
except Exception as e:
_LOGGER.error(f"[_get_user_info_from_auth] ERROR_NOT_FOUND: {e}")
raise ERROR_NOT_FOUND(message=f"ERROR_NOT_FOUND: {e}")
def _set_saml_settings(
self,
params: dict,
metadata_url: str,
domain_id: str,
) -> None:
"""Sets the SAML settings using the metadata URL and domain ID.
Args:
'params': 'dict',
'metadata_url': 'str',
'sp_metadata_url': 'str',
'domain_id': 'str',
"""
idp_xml_data = self._fetch_xml(metadata_url)
entity_id, idp_x509_certificate, sso_url = self._parse_idp_xml(idp_xml_data)
http_host = params.get("http_host")
acs_url = f"https://{http_host}/console-api/extension/auth/saml/{domain_id}"
self.saml_settings = {
"strict": True,
"debug": True,
"idp": {
"entityId": entity_id,
"singleSignOnService": {
"url": sso_url,
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
},
"x509cert": idp_x509_certificate,
},
"sp": {
"entityId": domain_id,
"assertionConsumerService": {
"url": acs_url,
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
},
# "x509cert": sp_x509_certificate,
},
"security": {
"wantAssertionsSigned": True,
"wantNameId": True,
"wantAttributeStatement": False,
},
}
@staticmethod
def _fetch_xml(metadata_url: str) -> bytes:
"""Fetches the XML data from the metadata URL.
Args:
'metadata_url': 'str'
Returns:
'xml': 'bytes'
Raises:
ERROR_NOT_FOUND: If the metadata URL is not found
"""
try:
response = requests.get(metadata_url)
response.raise_for_status()
return response.content
except Exception as e:
_LOGGER.error(f"[init] ERROR_NOT_FOUND: {e}")
raise ERROR_NOT_FOUND(message=f"ERROR_NOT_FOUND: {e}")
@staticmethod
def _parse_idp_xml(xml_data: bytes) -> Tuple[str, str, str]:
"""Parses the XML data to extract entity ID, x509 certificate, and SSO URL.
Args:
'xml_data': 'bytes'
Returns:
('entity_id': 'str', 'x509_certificate': 'str', 'sso_url': 'str'): 'tuple'
"""
root = ET.fromstring(xml_data)
ns = {
"md": "urn:oasis:names:tc:SAML:2.0:metadata",
"ds": "http://www.w3.org/2000/09/xmldsig#",
}
entity_id = root.attrib["entityID"]
x509_certificate = root.find(".//ds:X509Certificate", ns).text
sso_service = root.find(".//md:SingleSignOnService", ns)
sso_url = None
if sso_service is not None:
sso_url = sso_service.attrib["Location"]
return entity_id, x509_certificate, sso_url
@staticmethod
def _get_idp_name(identity_provider: str) -> str:
"""Generates a name for the identity provider.
Args:
'identity_provider': 'str'
Returns:
'idp_name': 'str'
"""
idp_name = {
"okta": "Okta",
"frontegg": "Frontegg",
"auth0": "Auth0",
"one_login": "OneLogin",
"pops": "Megazone PoPs",
"ping_identity": "Ping Identity",
"workos": "WorkOS",
"keycloak": "Keycloak",
"microsoft_entra_id": "Microsoft Entra ID",
}
idp_name = idp_name.get(identity_provider, identity_provider.capitalize())
return idp_name
|
package com.siuliano.photoappbum.ui.main.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.siuliano.photoappbum.databinding.ItemPhotoBinding
import com.siuliano.photoappbum.interfaces.CustomClickListener
import com.siuliano.photoappbum.models.Photo
import com.siuliano.photoappbum.ui.main.callback.PhotoCallback
class PhotoAdapter(
private val listener : CustomClickListener
) : RecyclerView.Adapter<PhotoViewHolder>() {
private var photoList : List<Photo> = ArrayList()
init {
PhotoCallback.bind(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemPhotoBinding.inflate(inflater, parent,false)
return PhotoViewHolder(binding, listener)
}
override fun onBindViewHolder(holder: PhotoViewHolder, position: Int) {
holder.bind(photoList[position])
}
override fun getItemCount(): Int {
return photoList.size
}
fun setPhotos(newList: List<Photo>) {
val oldList = photoList
photoList = newList
notifyChanges(oldList, photoList)
}
private fun notifyChanges(oldList: List<Photo>, newList: List<Photo>) {
val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
}, false)
diff.dispatchUpdatesTo(PhotoCallback)
}
}
|
// # Primitive Data Type (call by value )
// 7 types: String, Number, Boolean, Null, Undefined, Symbol
const score = 100;
const scoreValue = 100.3;
const isLoggedIn = false;
const outSideTemp = null;
let userEmail;
const id = Symbol('123');
const anotherId = Symbol('123');
// console.log(id === anotherId);
// # Non-Primitive Data Type (call by reference)
// Array, Objects, Functions
const heros = ['V', 'JungKook', 'Suga', 'J-Hope', 'Jimin', 'Rm', 'Jin'];
const myObj = {
name:"Jiya",
age: 24,
}
const myFunction = function(){
console.log("Hello Jiya");
}
// myFunction()
/*
1 Stack (Primitve) Whenever a variable is declared, it receives a copy
2 Heap (Non-Primitive) When a variable is allocated in the heap, it receives a reference to its original value
*/
let myName = "Jiya";
let anotherName = myName;
anotherName = "Khushboo";
// console.log(myName);
// console.log(anotherName);
let userOne = {
email: "user@goggle.com",
upi: "user@ybl"
}
let userTwo = userOne
userTwo.email = "jiya@google.com"
console.log(userOne.email);
console.log(userTwo.email);
|
package ru.ancap.algorithm.walkthrough;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.junit.jupiter.api.Test;
import ru.ancap.algorithm.walkthrough.classic.RegionWalkthroughOperator;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
public class WalkthroughTest {
@Test
public void testOnePath() {
Walkthrough<Integer> walkthrough = new Walkthrough<>(
0,
(target, previous) -> {
if (target > 10) return StepResult.DENY;
else return StepResult.ALLOW;
},
new NodeMethodApplier<>() {
@Override
public Set<Integer> neighbors(Integer int_) {
return Set.of(int_+1);
}
@Override
public boolean equals(Integer one, Integer other) {
return one.equals(other);
}
}
);
WalkthroughResult<Integer> result = walkthrough.walkthrough();
assertNotNull(result);
assertEquals(11, result.collected().size(), result.collected().toString());
assertTrue(result.collected().contains(10), result.collected().toString());
assertFalse(result.collected().contains(11), result.collected().toString());
}
@Accessors(fluent = true) @Getter
@ToString(exclude = {"color", "neighbors"}) @EqualsAndHashCode(exclude = {"color", "neighbors"})
@RequiredArgsConstructor
public static class Node {
private final String identity;
private final NodeColor color;
private final Set<Node> neighbors;
public Node(String identity) {
this(identity, Set.of());
}
public Node(String identity, Set<Node> neighbors) {
this(identity, NodeColor.BLUE, neighbors);
}
public Node(String identity, NodeColor color) {
this(identity, color, Set.of());
}
public static final NodeMethodApplier<Node> METHOD_APPLIER = new NodeMethodApplier<>() {
@Override
public Set<Node> neighbors(Node node) {
return node.neighbors();
}
@Override
public boolean equals(Node one, Node other) {
return one.equals(other);
}
};
}
public enum NodeColor {
BLUE,
RED
}
private final Node graph = new Node(
"base",
Set.of(
new Node(
"left",
Set.of(
new Node("left left"),
new Node("left middle", Set.of(new Node("left middle inner", NodeColor.RED))),
new Node("left right")
)
),
new Node("right", Set.of(new Node("right inner", NodeColor.RED, Set.of(new Node("right inner inner")))))
)
);
@Test
public void testGraph() {
Node base = this.graph;
Walkthrough<Node> walkthrough = new Walkthrough<>(
base,
(target, previous) -> StepResult.ALLOW,
Node.METHOD_APPLIER
);
WalkthroughResult<Node> result = walkthrough.walkthrough();
assertNotNull(result);
assertEquals(9, result.collected().size(), result.collected().toString());
assertTrue(result.collected().contains(new Node("right inner")), result.collected().toString());
}
@Test
public void testRegion() {
Node base = this.graph;
Walkthrough<Node> walkthrough = new Walkthrough<>(
base,
new RegionWalkthroughOperator<>(node -> node.color() == NodeColor.BLUE),
Node.METHOD_APPLIER
);
// Act
WalkthroughResult<Node> result = walkthrough.walkthrough();
// Assert
assertNotNull(result);
assertEquals(6, result.collected().size(), result.collected().toString());
assertTrue(result.collected().contains(new Node("right")), result.collected().toString());
assertFalse(result.collected().contains(new Node("left middle inner")), result.collected().toString());
assertFalse(result.collected().contains(new Node("right inner inner")), result.collected().toString());
}
}
|
/*
* Gadget Driver for CarPlay
*
* Copyright (C) 2017 zjinnova, Inc.
* Author: guwenbiao <guwenbiao@zjinnova.com>
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/utsname.h>
#include <linux/platform_device.h>
#include <linux/usb/ch9.h>
#include <linux/usb/composite.h>
#include <linux/usb/gadget.h>
#include "gadget_chips.h"
#include "u_ether.c"
#include "f_fs.c"
#include "f_ncm.c"
#include "f_iap.c"
MODULE_AUTHOR("guwenbiao");
MODULE_DESCRIPTION("CarPlay Composite USB Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION("1.0");
static const char longname[] = "Gadget CarPlay";
/* Default vendor and product IDs, overridden by userspace */
#define VENDOR_ID 0x2207
#define PRODUCT_ID 0x2910
/* f_midi configuration */
#define MIDI_INPUT_PORTS 1
#define MIDI_OUTPUT_PORTS 1
#define MIDI_BUFFER_SIZE 256
#define MIDI_QUEUE_LENGTH 32
enum{
#ifdef CONFIG_CARPLAY_ANDROID
ZJ_FALSE = 2,
ZJ_TRUE = 3,
#else
ZJ_FALSE = 0,
ZJ_TRUE = 1,
#endif
};
struct carplay_usb_function {
char *name;
void *config;
struct device *dev;
char *dev_name;
struct device_attribute **attributes;
/* for carplay_dev.enabled_functions */
struct list_head enabled_list;
/* Optional: initialization during gadget bind */
int (*init)(struct carplay_usb_function *, struct usb_composite_dev *);
/* Optional: cleanup during gadget unbind */
void (*cleanup)(struct carplay_usb_function *);
/* Optional: called when the function is added the list of
* enabled functions */
void (*enable)(struct carplay_usb_function *);
/* Optional: called when it is removed */
void (*disable)(struct carplay_usb_function *);
int (*bind_config)(struct carplay_usb_function *,
struct usb_configuration *);
/* Optional: called when the configuration is removed */
void (*unbind_config)(struct carplay_usb_function *,
struct usb_configuration *);
/* Optional: handle ctrl requests before the device is configured */
int (*ctrlrequest)(struct carplay_usb_function *,
struct usb_composite_dev *,
const struct usb_ctrlrequest *);
};
struct carplay_dev {
struct carplay_usb_function **functions;
struct list_head enabled_functions;
struct usb_composite_dev *cdev;
struct device *dev;
void (*setup_complete)(struct usb_ep *ep,
struct usb_request *req);
bool enabled;
int disable_depth;
struct mutex mutex;
bool connected;
bool sw_connected;
struct work_struct work;
char ffs_aliases[256];
};
static struct class *carplay_class;
static struct carplay_dev *_carplay_dev;
static int carplay_bind_config(struct usb_configuration *c);
static void carplay_unbind_config(struct usb_configuration *c);
/* string IDs are assigned dynamically */
#define STRING_MANUFACTURER_IDX 0
#define STRING_PRODUCT_IDX 1
#define STRING_SERIAL_IDX 2
static char manufacturer_string[256];
static char product_string[256];
static char serial_string[256];
/* String Table */
static struct usb_string strings_dev[] = {
[STRING_MANUFACTURER_IDX].s = manufacturer_string,
[STRING_PRODUCT_IDX].s = product_string,
[STRING_SERIAL_IDX].s = serial_string,
{ } /* end of list */
};
static struct usb_gadget_strings stringtab_dev = {
.language = 0x0409, /* en-us */
.strings = strings_dev,
};
static struct usb_gadget_strings *dev_strings[] = {
&stringtab_dev,
NULL,
};
static struct usb_device_descriptor device_desc = {
.bLength = sizeof(device_desc),
.bDescriptorType = USB_DT_DEVICE,
.bcdUSB = __constant_cpu_to_le16(0x0200),
.bDeviceClass = USB_CLASS_PER_INTERFACE,
.idVendor = __constant_cpu_to_le16(VENDOR_ID),
.idProduct = __constant_cpu_to_le16(PRODUCT_ID),
.bcdDevice = __constant_cpu_to_le16(0xffff),
.bNumConfigurations = 1,
};
static struct usb_configuration carplay_config_driver = {
.label = "carplay",
.unbind = carplay_unbind_config,
.bConfigurationValue = 1,
.bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
.MaxPower = 1, /* 500ma */
};
static void carplay_work(struct work_struct *data)
{
struct carplay_dev *dev = container_of(data, struct carplay_dev, work);
struct usb_composite_dev *cdev = dev->cdev;
char *disconnected[2] = { "USB_STATE=DISCONNECTED", NULL };
char *connected[2] = { "USB_STATE=CONNECTED", NULL };
char *configured[2] = { "USB_STATE=CONFIGURED", NULL };
char **uevent_envp = NULL;
unsigned long flags;
spin_lock_irqsave(&cdev->lock, flags);
if (cdev->config)
uevent_envp = configured;
else if (dev->connected != dev->sw_connected)
uevent_envp = dev->connected ? connected : disconnected;
dev->sw_connected = dev->connected;
spin_unlock_irqrestore(&cdev->lock, flags);
if (uevent_envp) {
kobject_uevent_env(&dev->dev->kobj, KOBJ_CHANGE, uevent_envp);
pr_info("%s: sent uevent %s\n", __func__, uevent_envp[0]);
} else {
pr_info("%s: did not send uevent (%d %d %p)\n", __func__,
dev->connected, dev->sw_connected, cdev->config);
}
}
static void carplay_enable(struct carplay_dev *dev)
{
struct usb_composite_dev *cdev = dev->cdev;
if (WARN_ON(!dev->disable_depth))
return;
if (--dev->disable_depth == 0) {
usb_add_config(cdev, &carplay_config_driver,
carplay_bind_config);
usb_gadget_connect(cdev->gadget);
}
}
static void carplay_disable(struct carplay_dev *dev)
{
struct usb_composite_dev *cdev = dev->cdev;
if (dev->disable_depth++ == 0) {
usb_gadget_disconnect(cdev->gadget);
/* Cancel pending control requests */
usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
usb_remove_config(cdev, &carplay_config_driver);
}
}
/*-------------------------------------------------------------------------*/
/* Supported functions initialization */
struct functionfs_config {
bool opened;
bool enabled;
struct ffs_data *data;
};
static int ffs_function_init(struct carplay_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct functionfs_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return functionfs_init();
}
static void ffs_function_cleanup(struct carplay_usb_function *f)
{
functionfs_cleanup();
kfree(f->config);
}
static void ffs_function_enable(struct carplay_usb_function *f)
{
struct carplay_dev *dev = _carplay_dev;
struct functionfs_config *config = f->config;
config->enabled = true;
/* Disable the gadget until the function is ready */
if (!config->opened)
carplay_disable(dev);
}
static void ffs_function_disable(struct carplay_usb_function *f)
{
struct carplay_dev *dev = _carplay_dev;
struct functionfs_config *config = f->config;
config->enabled = false;
/* Balance the disable that was called in closed_callback */
if (!config->opened)
carplay_enable(dev);
}
static int ffs_function_bind_config(struct carplay_usb_function *f,
struct usb_configuration *c)
{
struct functionfs_config *config = f->config;
return functionfs_bind_config(c->cdev, c, config->data);
}
static ssize_t
ffs_aliases_show(struct device *pdev, struct device_attribute *attr, char *buf)
{
struct carplay_dev *dev = _carplay_dev;
int ret;
mutex_lock(&dev->mutex);
ret = sprintf(buf, "%s\n", dev->ffs_aliases);
mutex_unlock(&dev->mutex);
return ret;
}
static ssize_t
ffs_aliases_store(struct device *pdev, struct device_attribute *attr,
const char *buf, size_t size)
{
struct carplay_dev *dev = _carplay_dev;
char buff[256];
mutex_lock(&dev->mutex);
if (dev->enabled) {
mutex_unlock(&dev->mutex);
return -EBUSY;
}
strlcpy(buff, buf, sizeof(buff));
strlcpy(dev->ffs_aliases, strim(buff), sizeof(dev->ffs_aliases));
mutex_unlock(&dev->mutex);
return size;
}
static DEVICE_ATTR(aliases, S_IRUGO | S_IWUSR, ffs_aliases_show,
ffs_aliases_store);
static struct device_attribute *ffs_function_attributes[] = {
&dev_attr_aliases,
NULL
};
static struct carplay_usb_function ffs_function = {
#ifdef CONFIG_CARPLAY_ANDROID
.name = "Zadb",
#else
.name = "adb",
#endif
.init = ffs_function_init,
.enable = ffs_function_enable,
.disable = ffs_function_disable,
.cleanup = ffs_function_cleanup,
.bind_config = ffs_function_bind_config,
.attributes = ffs_function_attributes,
};
static int functionfs_ready_callback(struct ffs_data *ffs)
{
struct carplay_dev *dev = _carplay_dev;
struct functionfs_config *config = ffs_function.config;
int ret = 0;
mutex_lock(&dev->mutex);
ret = functionfs_bind(ffs, dev->cdev);
if (ret)
goto err;
config->data = ffs;
config->opened = true;
if (config->enabled)
carplay_enable(dev);
err:
mutex_unlock(&dev->mutex);
return ret;
}
static void functionfs_closed_callback(struct ffs_data *ffs)
{
struct carplay_dev *dev = _carplay_dev;
struct functionfs_config *config = ffs_function.config;
mutex_lock(&dev->mutex);
if (config->enabled)
carplay_disable(dev);
config->opened = false;
config->data = NULL;
if (!WARN_ON(!ffs->gadget))
dev->cdev->next_string_id -= ffs->strings_count;
functionfs_unbind(ffs);
mutex_unlock(&dev->mutex);
}
static void *functionfs_acquire_dev_callback(const char *dev_name)
{
return 0;
}
static void functionfs_release_dev_callback(struct ffs_data *ffs_data)
{
}
static int iap_function_init(struct carplay_usb_function *f,
struct usb_composite_dev *c)
{
return iAP_setup();
}
static void iap_function_cleanup(struct carplay_usb_function *f)
{
iAP_cleanup();
}
static int iap_function_bind_config(struct carplay_usb_function *f,
struct usb_configuration *c)
{
int status;
printk("iap_function_bind_config\n");
status = iAP_bind_config(c);
if (status)
printk(KERN_DEBUG "could not bind iAP config\n");
return 0;
}
static void iap_function_unbind_config(struct carplay_usb_function *f,
struct usb_configuration *c)
{
}
static struct carplay_usb_function iap_function = {
.name = "iap",
.init = iap_function_init,
.cleanup = iap_function_cleanup,
.bind_config = iap_function_bind_config,
.unbind_config = iap_function_unbind_config,
};
/* ncm */
struct ncm_function_config {
u8 ethaddr[ETH_ALEN];
struct eth_dev *dev;
};
static int ncm_function_init(struct carplay_usb_function *f, struct usb_composite_dev *c)
{
f->config = (void *)kzalloc(sizeof(struct ncm_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return 0;
}
static void ncm_function_cleanup(struct carplay_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
static int ncm_function_bind_config(struct carplay_usb_function *f,
struct usb_configuration *c)
{
struct ncm_function_config *ncm = f->config;
int ret;
if (!ncm) {
pr_err("%s: ncm config is null\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
ncm->ethaddr[0], ncm->ethaddr[1], ncm->ethaddr[2],
ncm->ethaddr[3], ncm->ethaddr[4], ncm->ethaddr[5]);
ncm->dev = gether_setup_name(c->cdev->gadget, ncm->ethaddr, "usb");
if (IS_ERR(ncm->dev))
return PTR_ERR(ncm->dev);
ret = ncm_bind_config(c, ncm->ethaddr, ncm->dev);
if (ret) {
pr_err("%s: ncm bind config failed err:%d", __func__, ret);
gether_cleanup(ncm->dev);
return ret;
}
return 0;
}
static void ncm_function_unbind_config(struct carplay_usb_function *f,
struct usb_configuration *c)
{
struct ncm_function_config *ncm = f->config;
gether_cleanup(ncm->dev);
}
static ssize_t ncm_ethaddr_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct carplay_usb_function *f = dev_get_drvdata(dev);
struct ncm_function_config *ncm = f->config;
return snprintf(buf, PAGE_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x\n",
ncm->ethaddr[0], ncm->ethaddr[1], ncm->ethaddr[2],
ncm->ethaddr[3], ncm->ethaddr[4], ncm->ethaddr[5]);
}
static ssize_t ncm_ethaddr_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct carplay_usb_function *f = dev_get_drvdata(dev);
struct ncm_function_config *ncm = f->config;
if (sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x\n",
(int *)&ncm->ethaddr[0], (int *)&ncm->ethaddr[1],
(int *)&ncm->ethaddr[2], (int *)&ncm->ethaddr[3],
(int *)&ncm->ethaddr[4], (int *)&ncm->ethaddr[5]) == 6)
return size;
return -EINVAL;
}
static DEVICE_ATTR(ncm_ethaddr, S_IRUGO | S_IWUSR, ncm_ethaddr_show,
ncm_ethaddr_store);
static struct device_attribute *ncm_function_attributes[] = {
&dev_attr_ncm_ethaddr,
NULL
};
static struct carplay_usb_function ncm_function = {
.name = "ncm",
.init = ncm_function_init,
.cleanup = ncm_function_cleanup,
.bind_config = ncm_function_bind_config,
.unbind_config = ncm_function_unbind_config,
.attributes = ncm_function_attributes,
};
static struct carplay_usb_function *supported_functions[] = {
&ffs_function,
&iap_function,
&ncm_function,
NULL
};
static int carplay_init_functions(struct carplay_usb_function **functions,
struct usb_composite_dev *cdev)
{
struct carplay_dev *dev = _carplay_dev;
struct carplay_usb_function *f;
struct device_attribute **attrs;
struct device_attribute *attr;
int err;
int index = 0;
for (; (f = *functions++); index++) {
f->dev_name = kasprintf(GFP_KERNEL, "f_%s", f->name);
f->dev = device_create(carplay_class, dev->dev,
MKDEV(0, index), f, f->dev_name);
if (IS_ERR(f->dev)) {
pr_err("%s: Failed to create dev %s", __func__,
f->dev_name);
err = PTR_ERR(f->dev);
goto err_create;
}
if (f->init) {
err = f->init(f, cdev);
if (err) {
pr_err("%s: Failed to init %s", __func__,
f->name);
goto err_out;
}
}
attrs = f->attributes;
if (attrs) {
while ((attr = *attrs++) && !err)
err = device_create_file(f->dev, attr);
}
if (err) {
pr_err("%s: Failed to create function %s attributes",
__func__, f->name);
goto err_out;
}
}
return 0;
err_out:
device_destroy(carplay_class, f->dev->devt);
err_create:
kfree(f->dev_name);
return err;
}
static void carplay_cleanup_functions(struct carplay_usb_function **functions)
{
struct carplay_usb_function *f;
while (*functions) {
f = *functions++;
if (f->dev) {
device_destroy(carplay_class, f->dev->devt);
kfree(f->dev_name);
}
if (f->cleanup)
f->cleanup(f);
}
}
static int
carplay_bind_enabled_functions(struct carplay_dev *dev,
struct usb_configuration *c)
{
struct carplay_usb_function *f;
int ret;
list_for_each_entry(f, &dev->enabled_functions, enabled_list) {
ret = f->bind_config(f, c);
if (ret) {
pr_err("%s: %s failed", __func__, f->name);
return ret;
}
}
return 0;
}
static void
carplay_unbind_enabled_functions(struct carplay_dev *dev,
struct usb_configuration *c)
{
struct carplay_usb_function *f;
list_for_each_entry(f, &dev->enabled_functions, enabled_list) {
if (f->unbind_config)
f->unbind_config(f, c);
}
}
static int carplay_enable_function(struct carplay_dev *dev, char *name)
{
struct carplay_usb_function **functions = dev->functions;
struct carplay_usb_function *f;
while ((f = *functions++)) {
if (!strcmp(name, f->name)) {
list_add_tail(&f->enabled_list,
&dev->enabled_functions);
return 0;
}
}
return -EINVAL;
}
/*-------------------------------------------------------------------------*/
/* /sys/class/carplay/carplay%d/ interface */
static ssize_t
functions_show(struct device *pdev, struct device_attribute *attr, char *buf)
{
struct carplay_dev *dev = dev_get_drvdata(pdev);
struct carplay_usb_function *f;
char *buff = buf;
mutex_lock(&dev->mutex);
list_for_each_entry(f, &dev->enabled_functions, enabled_list)
buff += sprintf(buff, "%s,", f->name);
mutex_unlock(&dev->mutex);
if (buff != buf)
*(buff-1) = '\n';
return buff - buf;
}
static ssize_t
functions_store(struct device *pdev, struct device_attribute *attr,
const char *buff, size_t size)
{
struct carplay_dev *dev = dev_get_drvdata(pdev);
char *name;
char buf[256], *b;
char aliases[256], *a;
int err;
int is_ffs;
int ffs_enabled = 0;
mutex_lock(&dev->mutex);
if (dev->enabled) {
mutex_unlock(&dev->mutex);
return -EBUSY;
}
INIT_LIST_HEAD(&dev->enabled_functions);
strlcpy(buf, buff, sizeof(buf));
b = strim(buf);
while (b) {
name = strsep(&b, ",");
if (!name)
continue;
is_ffs = 0;
strlcpy(aliases, dev->ffs_aliases, sizeof(aliases));
a = aliases;
while (a) {
char *alias = strsep(&a, ",");
if (alias && !strcmp(name, alias)) {
/*is_ffs = 1;*/
break;
}
}
if (is_ffs) {
if (ffs_enabled)
continue;
err = carplay_enable_function(dev, "ffs");
if (err)
pr_err("android_usb: Cannot enable ffs (%d)",
err);
else
ffs_enabled = 1;
continue;
}
err = carplay_enable_function(dev, name);
if (err)
pr_err("android_usb: Cannot enable '%s' (%d)",
name, err);
}
mutex_unlock(&dev->mutex);
return size;
}
static ssize_t enable_show(struct device *pdev, struct device_attribute *attr,
char *buf)
{
struct carplay_dev *dev = dev_get_drvdata(pdev);
return sprintf(buf, "%d\n", dev->enabled);
}
static ssize_t enable_store(struct device *pdev, struct device_attribute *attr,
const char *buff, size_t size)
{
struct carplay_dev *dev = dev_get_drvdata(pdev);
struct usb_composite_dev *cdev = dev->cdev;
struct carplay_usb_function *f;
int enabled = 0;
if (!cdev)
return -ENODEV;
mutex_lock(&dev->mutex);
sscanf(buff, "%d", &enabled);
if (enabled == ZJ_TRUE && !dev->enabled) {
/*
* Update values in composite driver's copy of
* device descriptor.
*/
cdev->desc.idVendor = device_desc.idVendor;
cdev->desc.idProduct = device_desc.idProduct;
cdev->desc.bcdDevice = device_desc.bcdDevice;
cdev->desc.bDeviceClass = device_desc.bDeviceClass;
cdev->desc.bDeviceSubClass = device_desc.bDeviceSubClass;
cdev->desc.bDeviceProtocol = device_desc.bDeviceProtocol;
list_for_each_entry(f, &dev->enabled_functions, enabled_list) {
if (f->enable)
f->enable(f);
}
carplay_enable(dev);
dev->enabled = true;
} else if (enabled == ZJ_FALSE && dev->enabled) {
carplay_disable(dev);
list_for_each_entry(f, &dev->enabled_functions, enabled_list) {
if (f->disable)
f->disable(f);
}
dev->enabled = false;
} else {
pr_err("android_usb: already %s\n",
dev->enabled ? "enabled" : "disabled");
}
mutex_unlock(&dev->mutex);
return size;
}
static ssize_t state_show(struct device *pdev, struct device_attribute *attr,
char *buf)
{
struct carplay_dev *dev = dev_get_drvdata(pdev);
struct usb_composite_dev *cdev = dev->cdev;
char *state = "DISCONNECTED";
unsigned long flags;
if (!cdev)
goto out;
spin_lock_irqsave(&cdev->lock, flags);
if (cdev->config)
state = "CONFIGURED";
else if (dev->connected)
state = "CONNECTED";
spin_unlock_irqrestore(&cdev->lock, flags);
out:
return sprintf(buf, "%s\n", state);
}
#define DESCRIPTOR_ATTR(field, format_string) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return sprintf(buf, format_string, device_desc.field); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
int value; \
if (sscanf(buf, format_string, &value) == 1) { \
device_desc.field = value; \
return size; \
} \
return -1; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
#define DESCRIPTOR_STRING_ATTR(field, buffer) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return sprintf(buf, "%s", buffer); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
if (size >= sizeof(buffer)) \
return -EINVAL; \
return strlcpy(buffer, buf, sizeof(buffer)); \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
DESCRIPTOR_ATTR(idVendor, "%04x\n")
DESCRIPTOR_ATTR(idProduct, "%04x\n")
DESCRIPTOR_ATTR(bcdDevice, "%04x\n")
DESCRIPTOR_ATTR(bDeviceClass, "%d\n")
DESCRIPTOR_ATTR(bDeviceSubClass, "%d\n")
DESCRIPTOR_ATTR(bDeviceProtocol, "%d\n")
DESCRIPTOR_STRING_ATTR(iManufacturer, manufacturer_string)
DESCRIPTOR_STRING_ATTR(iProduct, product_string)
DESCRIPTOR_STRING_ATTR(iSerial, serial_string)
static DEVICE_ATTR(functions, S_IRUGO | S_IWUSR, functions_show,
functions_store);
static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, enable_show, enable_store);
static DEVICE_ATTR(state, S_IRUGO, state_show, NULL);
static struct device_attribute *carplay_usb_attributes[] = {
&dev_attr_idVendor,
&dev_attr_idProduct,
&dev_attr_bcdDevice,
&dev_attr_bDeviceClass,
&dev_attr_bDeviceSubClass,
&dev_attr_bDeviceProtocol,
&dev_attr_iManufacturer,
&dev_attr_iProduct,
&dev_attr_iSerial,
&dev_attr_functions,
&dev_attr_enable,
&dev_attr_state,
NULL
};
/*-------------------------------------------------------------------------*/
/* Composite driver */
static int carplay_bind_config(struct usb_configuration *c)
{
struct carplay_dev *dev = _carplay_dev;
int ret = 0;
ret = carplay_bind_enabled_functions(dev, c);
if (ret)
return ret;
return 0;
}
static void carplay_unbind_config(struct usb_configuration *c)
{
struct carplay_dev *dev = _carplay_dev;
carplay_unbind_enabled_functions(dev, c);
}
static int carplay_bind(struct usb_composite_dev *cdev)
{
struct carplay_dev *dev = _carplay_dev;
struct usb_gadget *gadget = cdev->gadget;
int id, ret;
/* Save the default handler */
dev->setup_complete = cdev->req->complete;
/*
* Start disconnected. Userspace will connect the gadget once
* it is done configuring the functions.
*/
usb_gadget_disconnect(gadget);
ret = carplay_init_functions(dev->functions, cdev);
if (ret)
return ret;
/* Allocate string descriptor numbers ... note that string
* contents can be overridden by the composite_dev glue.
*/
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_MANUFACTURER_IDX].id = id;
device_desc.iManufacturer = id;
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_PRODUCT_IDX].id = id;
device_desc.iProduct = id;
/* Default strings - should be updated by userspace */
strncpy(manufacturer_string, "Carplay", sizeof(manufacturer_string)-1);
strncpy(product_string, "Carplay", sizeof(product_string) - 1);
strncpy(serial_string, "0123456789ABCDEF", sizeof(serial_string) - 1);
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_SERIAL_IDX].id = id;
device_desc.iSerialNumber = id;
device_desc.bcdDevice = cpu_to_le16(get_default_bcdDevice());
usb_gadget_set_selfpowered(gadget);
dev->cdev = cdev;
return 0;
}
static int carplay_usb_unbind(struct usb_composite_dev *cdev)
{
struct carplay_dev *dev = _carplay_dev;
cancel_work_sync(&dev->work);
carplay_cleanup_functions(dev->functions);
return 0;
}
/* HACK: Carplay needs to override setup for accessory to work */
static int (*composite_setup_func)(struct usb_gadget *gadget, const struct usb_ctrlrequest *c);
static int
carplay_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *c)
{
struct carplay_dev *dev = _carplay_dev;
struct usb_composite_dev *cdev = get_gadget_data(gadget);
struct usb_request *req = cdev->req;
struct carplay_usb_function *f;
int value = -EOPNOTSUPP;
unsigned long flags;
req->zero = 0;
req->length = 0;
req->complete = dev->setup_complete;
gadget->ep0->driver_data = cdev;
list_for_each_entry(f, &dev->enabled_functions, enabled_list) {
if (f->ctrlrequest) {
value = f->ctrlrequest(f, cdev, c);
if (value >= 0)
break;
}
}
if (value < 0)
value = composite_setup_func(gadget, c);
spin_lock_irqsave(&cdev->lock, flags);
if (!dev->connected) {
dev->connected = 1;
schedule_work(&dev->work);
} else if (c->bRequest == USB_REQ_SET_CONFIGURATION &&
cdev->config) {
schedule_work(&dev->work);
}
spin_unlock_irqrestore(&cdev->lock, flags);
return value;
}
static void carplay_disconnect(struct usb_composite_dev *cdev)
{
struct carplay_dev *dev = _carplay_dev;
dev->connected = 0;
schedule_work(&dev->work);
}
static struct usb_composite_driver carplay_usb_driver = {
.name = "carplay_usb",
.dev = &device_desc,
.strings = dev_strings,
.bind = carplay_bind,
.unbind = carplay_usb_unbind,
.disconnect = carplay_disconnect,
.max_speed = USB_SPEED_HIGH,
};
static int carplay_create_device(struct carplay_dev *dev)
{
struct device_attribute **attrs = carplay_usb_attributes;
struct device_attribute *attr;
int err;
dev->dev = device_create(carplay_class, NULL,
MKDEV(0, 0), NULL, "android0");
if (IS_ERR(dev->dev))
return PTR_ERR(dev->dev);
dev_set_drvdata(dev->dev, dev);
while ((attr = *attrs++)) {
err = device_create_file(dev->dev, attr);
if (err) {
device_destroy(carplay_class, dev->dev->devt);
return err;
}
}
return 0;
}
static int __init init(void)
{
struct carplay_dev *dev;
int err;
carplay_class = class_create(THIS_MODULE, "android_usb");
if (IS_ERR(carplay_class))
return PTR_ERR(carplay_class);
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
err = -ENOMEM;
goto err_dev;
}
dev->disable_depth = 1;
dev->functions = supported_functions;
INIT_LIST_HEAD(&dev->enabled_functions);
INIT_WORK(&dev->work, carplay_work);
mutex_init(&dev->mutex);
err = carplay_create_device(dev);
if (err) {
pr_err("%s: failed to create carplay device %d", __func__, err);
goto err_create;
}
_carplay_dev = dev;
err = usb_composite_probe(&carplay_usb_driver);
if (err) {
pr_err("%s: failed to probe driver %d", __func__, err);
goto err_probe;
}
/* HACK: exchange composite's setup with ours */
composite_setup_func = carplay_usb_driver.gadget_driver.setup;
carplay_usb_driver.gadget_driver.setup = carplay_setup;
return 0;
err_probe:
device_destroy(carplay_class, dev->dev->devt);
err_create:
kfree(dev);
err_dev:
class_destroy(carplay_class);
return err;
}
late_initcall(init);
static void __exit cleanup(void)
{
usb_composite_unregister(&carplay_usb_driver);
class_destroy(carplay_class);
kfree(_carplay_dev);
_carplay_dev = NULL;
}
module_exit(cleanup);
|
import { Route, BrowserRouter as Router, Switch } from "react-router-dom";
import Header from "../common/header/Header";
import Home from "../home/Home"
import About from "../about/About"
import Blog from "../blog/Blog"
import Pricing from "../home/pricing/Pricing"
import Services from "../services/services"
import Contact from "../contact/Contact"
import Footer from "../common/footer/Footer";
const Pages = () => {
return (
<div>
<Router>
<Header />
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/about" component={About}/>
<Route exact path="/blog" component={Blog}/>
<Route exact path="/pricing" component={Pricing}/>
<Route exact path="/services" component={Services}/>
<Route exact path="/contact" component={Contact}/>
</Switch>
<Footer/>
</Router>
</div>
);
};
export default Pages;
|
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="Описание" content="Студия веб-дизайна" />
<title>Студия</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css"
/>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<!-- Шапка сайта -->
<header>
<a class="logo" lang="en" href="./index.html"> <span class="accent">Web</span>Studio</a>
<nav>
<!-- Навигация на другие страницы -->
<ul class="site-nav list">
<li><a class="link current" href="./index.html">Студия</a></li>
<li><a class="link" href="./portfolio.html">Портфолио</a></li>
<li><a class="link" href="./contacts.html">Контакты</a></li>
</ul>
</nav>
<ul class="list">
<li>
<a class="contacts" lang="en" href="mailto:info@devstudio.com">info@devstudio.com</a>
</li>
<li><a class="contacts" href="tel:+380961111111">+38 096 111 11 11</a></li>
</ul>
</header>
<main>
<!-- Герой -->
<section class="hero">
<h1 class="hero-title">Эффективные решения <br />для вашего бизнеса</h1>
<button class="hero-button" type="button">Заказать услугу</button>
</section>
<!-- Особенности -->
<section>
<h2 class="features-header">Особенности</h2>
<ul class="features list">
<li>
<h3 class="features-title">Внимание к деталям</h3>
<p class="features-description">
Идейные соображения, а также начало повседневной работы по формированию позиции.
</p>
</li>
<li>
<h3 class="features-title">Пунктуальность</h3>
<p class="features-description">
Задача организации, в особенности же рамки и место обучения кадров влечет за собой.
</p>
</li>
<li>
<h3 class="features-title">Планирование</h3>
<p class="features-description">
Равным образом консультация с широким активом в значительной степени обуславливает.
</p>
</li>
<li>
<h3 class="features-title">Современные технологии</h3>
<p class="features-description">
Значимость этих проблем настолько очевидна, что реализация плановых заданий.
</p>
</li>
</ul>
</section>
<!-- Чем мы занимаемся -->
<section>
<h2 class="work-name">Чем мы занимаемся</h2>
<ul class="work list">
<li>
<img src="./images/box1.jpg" alt="Человек работает за компьютером" width="370" />
</li>
<li>
<img
src="./images/box2.jpg"
alt="Человек с телефоном работает за компьтером"
width="370"
/>
</li>
<li>
<img src="./images/box3.jpg" alt="Планшет в руках" width="370" />
</li>
</ul>
</section>
<!-- Наша команда -->
<section class="team">
<h2 class="our-team">Наша команда</h2>
<ul class="team list">
<li>
<img src="./images/img1.jpg" alt="Человек в очках смеется" width="270" />
<h3 class="team-members">Игорь Демьяненко</h3>
<p lang="en" class="members-position">Product Designer</p>
</li>
<li>
<img src="./images/img2.jpg" alt="Девушка в очках" width="270" />
<h3 class="team-members">Ольга Репина</h3>
<p lang="en" class="members-position">Frontend Developer</p>
</li>
<li>
<img src="./images/img3.jpg" alt="Мужчина в рубашке смеется" width="270" />
<h3 class="team-members">Николай Тарасов</h3>
<p lang="en" class="members-position">Marketing</p>
</li>
<li>
<img src="./images/img4.jpg" alt="Мужчина в очках улыбается" width="270" />
<h3 class="team-members">Михаил Ермаков</h3>
<p lang="en" class="members-position">UI Designer</p>
</li>
</ul>
</section>
</main>
<footer class="footer">
<a class="logo-footer" lang="en" href="./index.html">
<span class="accent-footer">Web</span>Studio</a
>
<ul class="list">
<li>
<a class="address1" href="https://goo.gl/maps/uJRSsjhDMDkQPGBL8"
>г. Киев, пр-т Леси Украинки, 26</a
>
</li>
<li><a class="address" lang="en" href="mailto:info@example.com">info@example.com</a></li>
<li><a class="address" href="tel:+380991111111">+38 099 111 11 11</a></li>
</ul>
</footer>
</body>
</html>
|
const assert = require('assert');
const mongoose = require('mongoose');
const User = require('../src/user');
const Comment = require('../src/comment');
const BlogPost = require('../src/blogPost');
describe('Associations', () => {
let joe, blogPost, comment;
beforeEach((done) => {
joe = new User({ name: 'joe' });
blogPost = new BlogPost({ title: 'hello', content: 'hi there'}),
comment = new Comment({ content: 'congrats on the post' })
joe.blogPosts.push(blogPost);
blogPost.comments.push(comment);
comment.user = joe; // association to joe - that simple
Promise.all([joe.save(), blogPost.save(), comment.save()])
.then(() => done())
});
// it('saves a relation between a user and a blogpost', (done) => {
// User.findOne({ name: 'joe' })
// .populate('blogPosts')
// .then((user) => {
// assert(user.blogPosts[0].title === 'hello')
// done();
// });
// });
it('saves a full relation graph', (done) => {
User.findOne({ name: 'joe' })
.populate({
path: 'blogPosts',
populate: {
path: 'comments',
// model: 'comment',
populate: {
path: 'user',
// model: 'user'
}
}
})
.then((user) => {
assert(user.name === 'joe')
assert(user.blogPosts[0].title === 'hello')
assert(user.blogPosts[0].content === 'hi there')
assert(user.blogPosts[0].comments[0].content === 'congrats on the post')
assert(user.blogPosts[0].comments[0].user.name === 'joe')
done();
})
})
// it('saves a full relation graph', (done) => {
// User.findOne({ name: 'joe' })
// .populate({
// path: 'blogPosts',
// populate: {
// path: 'comments',
// model: 'comment',
// populate: {
// path: 'user',
// model: 'user'
// }
// }
// })
// .then((user) => {
// console.log(user);
// assert(user.name === 'Joe');
// assert(user.blogPosts[0].title === 'JS is Great');
// assert(user.blogPosts[0].comments[0].content === 'Congrats on great post');
// assert(user.blogPosts[0].comments[0].user.name === 'Joe');
// done();
// });
// });
});
|
import React, { useEffect, useState } from 'react';
import { StyleSheet, TouchableOpacity, ScrollView, TextInput, ActivityIndicator} from 'react-native';
import { MaterialCommunityIcons, Feather, AntDesign } from '@expo/vector-icons';
import { format } from 'date-fns'
import { Text, View } from '../../components/Themed';
import { CardStyle } from '../../style/CardStyle';
import { TaskDatetimeStatus } from '../../enum/TaskDatetimeStatus.enum';
import { ColorStyle } from '../../style/ColorStyle';
import { environment } from '../../environment';
import { TaskDetailModel, TaskListSortByProcessModel } from '../../model/Task.model';
import { TaskProcess } from '../../enum/TaskProcess.enum';
import { ViewStyle } from '../../style/ViewStyle';
import { TextStyle } from '../../style/TextStyle';
import Colors from '../../constants/Colors';
import { RootStackScreenProps } from '../../types';
export default function TaskLocationScreen({ navigation, route }: RootStackScreenProps<'TaskLocation'>) {
const [taskList, setTaskList] = useState<Array<TaskListSortByProcessModel>>([])
const [keyword, onChangeKeyword] = useState<string>('')
const [isLoading, setIsLoading] = useState<boolean>(true);
const { locationId } = route.params;
useEffect(() => {
const getTaskList = () => {
setIsLoading(true);
const url = keyword
? `${environment.apiRaUrl}/api/Task/GetTaskListByLocationId?locationId=${locationId}&keyword=${keyword.trim()}`
: `${environment.apiRaUrl}/api/Task/GetTaskListByLocationId?locationId=${locationId}`
fetch(url, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((res) => {
setTaskList(res.data);
setIsLoading(false);
})
.catch((error) => {
console.error(error);
});
};
getTaskList();
}, [keyword]);
const ContentElement = (contentItem: TaskDetailModel, i: number) => {
return(
<View key={`task-${contentItem.process}-${i}`}>
<TouchableOpacity onPress={()=> navigation.navigate('TaskDetailContainer', { taskId: contentItem.taskId, taskProcess: contentItem.process }) }>
<View style={ getCardColorClass(contentItem.datetimeStatus) }>
<Text style={styles.TextHeader} numberOfLines={2}>{ contentItem.taskTitle }</Text>
<View style={styles.DatetimeWrapper}>
<MaterialCommunityIcons name="calendar-clock" size={20}
color={ getTextColor(contentItem.datetimeStatus) }
style={{ marginRight: 5 }} />
<Text style={[styles.TextContent,
{ color: getTextColor(contentItem.datetimeStatus) }]}>
{ format(new Date(contentItem.dueDate), 'dd/MM/yyyy HH:mm') }
</Text>
</View>
</View>
</TouchableOpacity>
</View>
)
}
const TaskElementList = taskList?.map((content: TaskListSortByProcessModel, index: number) => {
return (
<View key={'element-' + index}>
<Text style={[TextStyle.Heading, { fontSize: 16, marginTop: 15 }]}>
{ getProcessLabel(content.taskProcess) }
</Text>
{
content.taskList.map((task, index) => {
return ContentElement(task, index);
})
}
</View>
)
})
return (
<View style={styles.Container}>
<View style={[ViewStyle.ColumnContainer, { marginBottom: 10 }]}>
<View style={styles.SearchWrapper}>
{/* search */}
<View style={styles.InputWrapper}>
<Feather name='search' style={{marginHorizontal:5}} size={20} color={'#6c6c6c'} />
<TextInput
style={styles.InputText}
onChangeText={(searchTerm) => onChangeKeyword(searchTerm)}
value={keyword}
placeholder='พ.ร.บ/กฎหมาย'
/>
</View>
</View>
{/* task list */}
<View style={[ViewStyle.RowContainer, { paddingHorizontal: 0 }]}>
<ScrollView contentContainerStyle={{ flexGrow: 1 }}>
{ isLoading ? <LoadingElement/>: taskList ? TaskElementList : <></> }
</ScrollView>
</View>
</View>
</View>
);
}
const getCardColorClass = (status: TaskDatetimeStatus) => {
switch(status) {
case TaskDatetimeStatus.Overdue:
return CardStyle.Danger;
case TaskDatetimeStatus.Today:
return CardStyle.Warning;
case TaskDatetimeStatus.Remain:
return CardStyle.Grey;
}
}
const getTextColor = (status: TaskDatetimeStatus) => {
switch(status) {
case TaskDatetimeStatus.Overdue:
return ColorStyle.Danger.color;
case TaskDatetimeStatus.Today:
return ColorStyle.Warning.color;
case TaskDatetimeStatus.Remain:
return ColorStyle.Grey.color;
}
}
const getProcessLabel = (process: TaskProcess) => {
switch(process) {
case TaskProcess.Relevant:
return 'ประเมินความเกี่ยวข้อง';
case TaskProcess.ApproveRelevant:
return 'รออนุมัติความเกี่ยวข้อง';
case TaskProcess.Consistance:
return 'ประเมินความสอดคล้อง';
case TaskProcess.ApproveConsistance:
return 'รออนุมัติความสอดคล้อง';
case TaskProcess.Response:
return 'รอดำเนินการให้สอดคล้อง';
case TaskProcess.ApproveResponse:
return 'รออนุมัติการปฏิบัติให้สอดคล้อง'
}
}
const LoadingElement = () => {
return (
<View style={ViewStyle.LoadingWrapper}>
<ActivityIndicator color={Colors.light.tint} size="large" />
<Text style={TextStyle.Loading}>Loading</Text>
</View>
)
}
const styles = StyleSheet.create({
Container: {
flex: 1,
flexGrow:1,
paddingHorizontal: 10,
flexDirection: 'row',
alignItems: 'flex-start',
justifyContent: 'center',
paddingTop: 10,
},
TypeText: {
fontSize: 16,
marginTop: 10,
color: '#6c6c6c',
fontFamily: 'Mitr_500Medium'
},
AssignText: {
fontSize: 16,
color: '#4a4a4a',
justifyContent: 'center',
fontFamily: 'Mitr_500Medium'
},
DatetimeWrapper: {
marginTop: 2,
flexDirection: 'row',
backgroundColor: 'transparent'
},
TextHeader: {
fontSize: 18,
fontFamily: 'Mitr_500Medium',
color: '#000',
},
TextContent: {
fontSize: 13,
fontFamily: 'Mitr_400Regular',
color: '#000',
},
SearchWrapper: {
flexDirection: 'row',
alignItems: 'center',
marginHorizontal: 5,
marginRight: 10,
height: 50,
},
InputWrapper:{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
height: 40,
width: '100%',
backgroundColor: '#eeeeee',
borderRadius: 20,
},
InputText: {
fontSize: 18,
fontFamily: 'Mitr_400Regular',
height: 40,
width:'100%',
},
Filter:{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
ModalContainer: {
flex: 1,
justifyContent: "flex-start",
alignItems: 'flex-start',
marginTop: 90,
backgroundColor: '#fff',
padding: 20,
borderRadius: 15,
},
FilterWrapper: {
flexDirection:'row',
alignItems:'center',
justifyContent:'space-between',
width:'100%',
backgroundColor: '#fff',
},
FilterCardSelected: {
backgroundColor: '#d2f7ed',
borderColor: 'green',
borderRadius:20,
borderWidth:1,
padding:5,
paddingHorizontal:20,
marginVertical:10,
},
FilterCardUnselected: {
backgroundColor: 'transparent',
borderColor: 'gray',
borderRadius:20,
borderWidth:1,
padding:5,
paddingHorizontal:20,
marginVertical:10,
},
});
|
package transport
import (
"fmt"
"net/http"
"github.com/defiweb/go-eth/hexutil"
)
const (
// Standard errors:
ErrCodeUnauthorized = 1
ErrCodeActionNotAllowed = 2
ErrCodeExecutionError = 3
ErrCodeParseError = -32700
ErrCodeInvalidRequest = -32600
ErrCodeMethodNotFound = -32601
ErrCodeInvalidParams = -32602
ErrCodeInternalError = -32603
// Common non-standard errors:
ErrCodeGeneral = -32000
ErrCodeLimitExceeded = -32005
// Erigon errors:
ErigonErrCodeGeneral = -32000
ErigonErrCodeNotFound = -32601
ErigonErrCodeUnsupportedFork = -38005
// Nethermind errors:
NethermindErrCodeMethodNotSupported = -32004
NethermindErrCodeLimitExceeded = -32005
NethermindErrCodeTransactionRejected = -32010
NethermindErrCodeExecutionError = -32015
NethermindErrCodeTimeout = -32016
NethermindErrCodeModuleTimeout = -32017
NethermindErrCodeAccountLocked = -32020
NethermindErrCodeUnknownBlockError = -39001
// Infura errors:
InfuraErrCodeInvalidInput = -32000
InfuraErrCodeResourceNotFound = -32001
InfuraErrCodeResourceUnavailable = -32002
InfuraErrCodeTransactionRejected = -32003
InfuraErrCodeMethodNotSupported = -32004
InfuraErrCodeLimitExceeded = -32005
InfuraErrCodeJSONRPCVersionNotSupported = -32006
// Alchemy errors:
AlchemyErrCodeLimitExceeded = 429
// Blast errors:
BlastErrCodeAuthenticationFailed = -32099
BlastErrCodeCapacityExceeded = -32098
BlastErrRateLimitReached = -32097
)
type HTTPErrorCode interface {
// HTTPErrorCode returns the HTTP status code.
HTTPErrorCode() int
}
type RPCErrorCode interface {
// RPCErrorCode returns the JSON-RPC error code.
RPCErrorCode() int
}
type RPCErrorData interface {
// RPCErrorData returns the JSON-RPC error data.
RPCErrorData() any
}
// RPCError is an JSON-RPC error.
type RPCError struct {
Code int // Code is the JSON-RPC error code.
Message string // Message is the error message.
Data any // Data associated with the error.
}
// NewRPCError creates a new RPC error.
//
// If data is a hex-encoded string, it will be decoded.
func NewRPCError(code int, message string, data any) *RPCError {
if bin, ok := decodeHexData(data); ok {
data = bin
}
return &RPCError{
Code: code,
Message: message,
Data: data,
}
}
// Error implements the error interface.
func (e *RPCError) Error() string {
return fmt.Sprintf("RPC error: %d %s", e.Code, e.Message)
}
// RPCErrorCode implements the ErrorCode interface.
func (e *RPCError) RPCErrorCode() int {
return e.Code
}
// RPCErrorData implements the ErrorData interface.
func (e *RPCError) RPCErrorData() any {
return e.Data
}
// HTTPError is an HTTP error.
type HTTPError struct {
Code int // Code is the HTTP status code.
Err error // Err is an optional underlying error.
}
// NewHTTPError creates a new HTTP error.
func NewHTTPError(code int, err error) *HTTPError {
return &HTTPError{
Code: code,
Err: err,
}
}
// Error implements the error interface.
func (e *HTTPError) Error() string {
if e.Err == nil {
return fmt.Sprintf("HTTP error: %d %s", e.Code, http.StatusText(e.Code))
}
return fmt.Sprintf("HTTP error: %d %s: %s", e.Code, http.StatusText(e.Code), e.Err)
}
// HTTPErrorCode implements the HTTPErrorCode interface.
func (e *HTTPError) HTTPErrorCode() int {
return e.Code
}
// decodeHexData decodes hex-encoded data if present.
func decodeHexData(data any) (any, bool) {
hex, ok := data.(string)
if !ok {
return nil, false
}
if !hexutil.Has0xPrefix(hex) {
return nil, false
}
bin, err := hexutil.HexToBytes(hex)
if err != nil {
return nil, false
}
return bin, true
}
|
Q) OUT OF TABLE WITH CADIDATE ID AND THEIR SKILLS , YOU HAVE TO SELECT THE CANDIDATES WHO HAVE 3 SKILLS
SQL , PYTHON AND TABLEAU. IF CANDIDATES HAVE THESE 3 SKILLS ALONG WITH OTHERS IS GOOD , IF THEY ONLY HAVE THESE 3 SKILLS
WHICH IS ALSO FINE. BUT NOT HAVING 1 SKILLS OUT OF THREE WILL MLEAD TO REJECTION
123 : TABLEAU
234 : SQL
123 : PYTHON
123 : SQL
234 : R
567 : POWERBI
SOLUTION : THIS PROBLEM CAN BE SOLVED USING 2 METHODS
METHOD 1 : WE WILL USE CTE WHICH WILL HAVE ROWS RELATED TO SQL , PYTHON , TABLEAU. AFTER THAT WE WILL APPLY GROUP BY
WITH CTE AS
(SELECT *
FROM TABLE
WHERE SKILLS
IN ('SQL' , 'PYTHON' , 'TABLEAU')),
CTE_TWO AS
(SELECT
ID , COUNT(*) AS TOTAL_COUNT
FROM CTE
GROUP BY 1)
SELECT ID FROM CTE_TWO WHERE TOTAL_COUNT = 3
METHOD 2: IN THIS METHOD WE WILL BE USING THE STRING _AGG FUNCTION
WITH CTE AS (
SELECT
ID ,
STRING_AGG('SKILLS' , ',' ORDER BY SKILLS) AS ALL_SKILLS
FROM TABLE
GROUP BY ID)
SELECT
ID
FROM CTE
WHERE ALL_SKILLS LIKE '%SQL , PYTHON , TABLEAU%' ;
|
import React, { useContext } from 'react';
import {
IonChip,
IonContent,
IonPage
} from '@ionic/react';
import Carousel from '../components/Carousel';
import { MyContext } from '../context/data.context';
import Toolbar from '../components/Toolbar';
import Menu from '../components/Menu';
import { useHistory } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '../Interface/rootState';
const Home: React.FC = () => {
const { electronics, jewelery, man, woman } = useContext(MyContext)
const navigation = useHistory();
const {isAuthenticated, user } = useSelector((state: RootState) => state.auth);
return (
<>
<Menu />
<IonPage id='main-content'>
<Toolbar text={'Home'} />
<IonContent className="ion-padding" fullscreen>
{isAuthenticated ? <><h5>Hello {user?.firstname}😊!</h5> <hr style={{ backgroundColor: '#3880ff' }} /></> : ''}
<div className='flex flex-row align-center space-between mb-1'>
<h5>Electronics</h5>
<IonChip className='flex' onClick={() => navigation.push('/electronics')}>See more</IonChip>
</div>
<Carousel products={electronics} />
<div className='flex flex-row align-center space-between mb-1'>
<h5>Jewelery</h5>
<IonChip className='flex' onClick={() => navigation.push('/jewelery')}>See more</IonChip>
</div>
<Carousel products={jewelery} />
<div className='flex flex-row align-center space-between mb-1'>
<h5>Men's clothing</h5>
<IonChip className='flex' onClick={() => navigation.push('/man')}>See more</IonChip>
</div>
<Carousel products={man} />
<div className='flex flex-row align-center space-between mb-1'>
<h5>Women's clothing</h5>
<IonChip className='flex' onClick={() => navigation.push('/woman')}>See more</IonChip>
</div>
<Carousel products={woman} />
</IonContent>
</IonPage>
</>
);
}
export default Home
|
/**
* Bio component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.com/docs/use-static-query/
*/
import * as React from "react"
import { useStaticQuery, graphql } from "gatsby"
import { StaticImage } from "gatsby-plugin-image"
import { Link } from "gatsby"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { library } from "@fortawesome/fontawesome-svg-core"
import { faTwitter, faGithub } from "@fortawesome/free-brands-svg-icons"
library.add(faTwitter, faGithub)
const Bio = () => {
const data = useStaticQuery(graphql`
query BioQuery {
site {
siteMetadata {
author {
name
summary
}
social {
twitter
github
}
}
}
}
`)
// Set these values by editing "siteMetadata" in gatsby-config.js
const author = data.site.siteMetadata?.author
const social = data.site.siteMetadata?.social
return (
<div className="bio">
<StaticImage
className="bio-avatar"
layout="fixed"
formats={["AUTO", "WEBP", "AVIF"]}
src="../images/profile-pic.png"
width={50}
height={50}
quality={95}
alt="Profile picture"
/>
{author?.name && (
<p>
Written by{" "}
<Link to="/about-me">
<strong>{author.name}</strong>
</Link>{" "}
<br /> {author?.summary || null}
<br />
<a href={`https://twitter.com/${social?.twitter || ``}`}>
<FontAwesomeIcon icon={["fab", "twitter"]} />
</a>
{` `}
<a href={`https://github.com/${social?.github}`}>
<FontAwesomeIcon icon={["fab", "github"]} />
</a>
</p>
)}
</div>
)
}
export default Bio
|
const { expect } = require('chai');
const { ethers } = require('hardhat');
const { getVersion } = require('../scripts/util');
const { parseEther } = require('ethers/lib/utils');
describe('Test Ownable', function () {
let memori;
let owner;
let user;
beforeEach(async function () {
[owner, user] = await ethers.getSigners();
const Memori = await ethers.getContractFactory(getVersion());
memori = await Memori.deploy();
});
it('Test owner', async function () {
expect(await memori.owner()).to.equal(owner.address);
});
it('Test transfer ownsership', async function () {
const tx = await memori.connect(owner).transferOwnership(user.address);
tx.wait();
expect(await memori.owner()).to.equal(user.address);
});
});
|
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdlib.h>
#include <stdio.h>
#define WINDOW_WIDTH (1280)
#define WINDOW_HEIGHT (480)
SDL_Window* window;
SDL_Renderer* renderer;
int should_quit = 0;
int bullet_alive;
float bullet_position[2];
SDL_Texture* bullet_texture;
int bullet_texture_w;
int bullet_texture_h;
int initialize_sdl() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
puts("SDL_Init failed");
return -1;
}
window = SDL_CreateWindow(
"sdl-demo", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
if (!window) {
puts("SDL_CreateWindow failed");
return -1;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
puts("IMG_Init failed");
return -1;
}
SDL_Surface* bullet_surface = IMG_Load("./bullet.png");
if (!bullet_surface) {
puts("IMG_Load failed");
return -1;
}
bullet_texture = SDL_CreateTextureFromSurface(renderer, bullet_surface);
if (!bullet_texture) {
puts("SDL_CreateTextureFromSurface failed");
return -1;
}
bullet_texture_w = bullet_surface->w;
bullet_texture_h = bullet_surface->h;
SDL_FreeSurface(bullet_surface);
return 1;
}
void try_create_bullet() {
if (bullet_alive)
return;
bullet_alive = 420;
bullet_position[0] = 10 + (rand() % ((WINDOW_WIDTH / 2) - 300));
bullet_position[1] = 50 + (rand() % (WINDOW_HEIGHT - 100));
}
void update_bullet() {
if (!bullet_alive)
return;
SDL_Rect quad = {
bullet_position[0], bullet_position[1],
bullet_texture_w / 40, bullet_texture_h/ 40};
SDL_RenderCopy(renderer, bullet_texture, 0, &quad);
bullet_position[0] += 10;
bullet_alive -= 1;
printf("bullet x: %.2f (%s-screen)\n",
bullet_position[0], bullet_position[0] < WINDOW_WIDTH ? "on" : "off");
}
void handle_events() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT)
should_quit = 1;
else if(event.type == SDL_MOUSEBUTTONDOWN) {
if (event.button.button == SDL_BUTTON_LEFT) {
try_create_bullet();
}
}
}
}
int main(int argc, char** argv) {
if (initialize_sdl() < 0) {
printf("failed to initialize sdl");
return -1;
}
while (!should_quit) {
handle_events();
SDL_SetRenderDrawColor(renderer, 0xDD, 0xEE, 0xEE, 0x55);
SDL_RenderClear(renderer);
update_bullet();
SDL_RenderPresent(renderer);
}
return 0;
}
|
import os
import imageio
import folium
from folium import raster_layers
from streamlit_folium import folium_static
import streamlit as st
from PIL import Image
import numpy as np
import rasterio as rio
import cv2
from branca.colormap import linear
def get_image_coordinates(tiff_path):
with rio.open(tiff_path) as src:
bounds = [[src.bounds.bottom, src.bounds.left], [src.bounds.top, src.bounds.right]]
return bounds
def interpolate_images(img1, img2, steps, bounds1, bounds2):
interpolated_images = []
for alpha in np.linspace(0, 1, steps):
interpolated_img = cv2.addWeighted(img1, 1 - alpha, img2, alpha, 0)
interpolated_bounds = [
[bounds1[0][0] * (1 - alpha) + bounds2[0][0] * alpha, bounds1[0][1] * (1 - alpha) + bounds2[0][1] * alpha],
[bounds1[1][0] * (1 - alpha) + bounds2[1][0] * alpha, bounds1[1][1] * (1 - alpha) + bounds2[1][1] * alpha]
]
interpolated_images.append((interpolated_img, interpolated_bounds))
return interpolated_images
def create_gif(image_folder, gif_name, interpolation_steps=20):
images = []
bounds_list = []
for filename in os.listdir(image_folder):
if filename.endswith(".tif"):
img_path = os.path.join(image_folder, filename)
img = Image.open(img_path)
img_resized = img.resize((200, 200))
images.append(np.array(img_resized))
bounds_list.append(get_image_coordinates(img_path))
# Créer des images intermédiaires pour une transition plus douce
interpolated_images = []
for i in range(len(images) - 1):
interpolated_images.extend(interpolate_images(images[i], images[i + 1], interpolation_steps, bounds_list[i], bounds_list[i + 1]))
# Enregistrez la séquence d'images en tant que GIF en boucle continue
gif_images, gif_bounds = zip(*interpolated_images)
imageio.mimsave(gif_name, gif_images, duration=1.0 / interpolation_steps, loop=0)
return gif_bounds
def app():
st.title("Timelapse")
# Liste des options
options = ["visitors", "moroccans", "foreigners"]
# Sélection de l'utilisateur
user_choice = st.selectbox("Choose an attribute :", options)
if user_choice == "visitors":
image_folder = 'donnee/visitors'
c = linear.viridis.scale(0, 70)
c.caption = 'Visitors'
elif user_choice == "moroccans":
image_folder = 'donnee/moroccans'
c = linear.viridis.scale(0, 50)
c.caption = 'Moroccans'
else:
image_folder = 'donnee/foreigners'
c = linear.viridis.scale(0, 20)
c.caption = 'Foreigners'
# Chemin pour enregistrer le GIF
gif_path = f'donnee\{user_choice.lower()}\gif.gif'
# Créer le GIF à partir des images TIFF avec une durée de 1 seconde entre chaque image
gif_bounds = create_gif(image_folder, gif_path, interpolation_steps=10)
# Récupérer le chemin d'accès à la première image TIFF
first_tiff_path = os.path.join(image_folder, os.listdir(image_folder)[0])
# Créer la carte
my_map = folium.Map(location=[30.5,-6.2], zoom_start=5, tiles='OpenStreetMap')
# Ajouter une superposition GIF
gif_overlay = raster_layers.ImageOverlay(
gif_path,
bounds=gif_bounds[0],
opacity=0.8,
).add_to(my_map)
c.add_to(my_map)
# Afficher la carte sur Streamlit
st.markdown(f"This map includes a timelapse for the {user_choice}.")
# Utiliser folium_static pour afficher la carte Folium sur Streamlit
folium_static(my_map,width=1000, height=800)
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Busca Binária</title>
</head>
<body>
<h2>Busca Binária em um Vetor de 100 Posições</h2>
<label for="numero">Número a ser buscado (0-99):</label>
<input type="number" id="numero" min="0" max="99">
<button onclick="realizarBusca()">Buscar</button>
<div id="output"></div>
<script>
function buscaBinaria(vetor, elementoBuscado) {
let comparacoes = 0;
let inicio = 0;
let fim = vetor.length - 1;
while (inicio <= fim) {
comparacoes++;
let meio = Math.floor((inicio + fim) / 2);
if (vetor[meio] === elementoBuscado) {
return { indice: meio, comparacoes: comparacoes };
} else if (vetor[meio] < elementoBuscado) {
inicio = meio + 1;
} else {
fim = meio - 1;
}
}
return { indice: -1, comparacoes: comparacoes };
}
function realizarBusca() {
let numeroBuscado = parseInt(document.getElementById("numero").value);
if (isNaN(numeroBuscado)) {
alert("Por favor, insira um número válido.");
return;
}
let vetor = [];
for (let i = 0; i < 100; i++) {
vetor.push(i);
}
let resultado = buscaBinaria(vetor, numeroBuscado);
let output = document.getElementById("output");
output.innerHTML = "";
if (resultado.indice !== -1) {
output.innerHTML += "<p>Número buscado: " + numeroBuscado + "</p>";
output.innerHTML += "<p>Índice do número: " + resultado.indice + "</p>";
output.innerHTML += "<p>Número de comparações: " + resultado.comparacoes + "</p>";
} else {
output.innerHTML = "<p>O número não foi encontrado no vetor.</p>";
}
}
</script>
</body>
</html>
|
---
title: ID サービスでの削除
description: このドキュメントでは、Experience Platform での ID データの削除や、ID グラフがどのような影響を受ける可能性があるかを明確にするために使用できる様々なメカニズムの概要を説明します。
exl-id: 0619d845-71c1-4699-82aa-c6436815d5b3
source-git-commit: 05a7b73da610a30119b4719ae6b6d85f93cdc2ae
workflow-type: tm+mt
source-wordcount: '1198'
ht-degree: 100%
---
# ID サービスでの削除
Adobe Experience Platform ID サービスでは、個々のユーザーのすべてのデバイスやシステムにわたって ID を確定的にリンクすることで ID グラフを生成します。ID グラフのリンクは、マークされた 2 つ以上の ID がデータの同じ行内で受信されると確立されます。
リアルタイム顧客プロファイルで ID グラフを活用して、顧客の属性や行動の包括的な単一ビューを作成することで、インパクトの強い個人的なデジタルエクスペリエンスをデバイスではなく人物にリアルタイムで提供できるようになります。
このドキュメントでは、Experience Platform での ID データの削除や、ID グラフがどのような影響を受ける可能性があるかを明確にするために使用できる様々なメカニズムの概要を説明します。
## はじめに
以下のドキュメントでは、Experience Platform の次の機能について説明しています。
* [ID サービス](home.md):デバイスやシステム間で ID を橋渡しすることで、個々の顧客とその行動をより確実に把握することができます。
* [ID グラフ](./ui/identity-graph-viewer.md):ID グラフは、特定の顧客の異なる ID 間の関係のマップで、顧客が様々なチャネルでブランドとどのようにやり取りするかを視覚的に表現します。
* [ID 名前空間](namespaces.md):ID 名前空間は ID サービスのコンポーネントで、ID の関連先コンテキストのインジケーターとして機能します。例えば、「name<span>@email.com」の値をメールアドレスとして識別したり、「443522」を数値 CRM ID として識別したりします。
* [カタログサービス](../catalog/home.md):データレイク内のデータ系列、メタデータ、ファイル記述、ディレクトリおよびデータセットを調べます。
* [データハイジーン](../hygiene/home.md):データセットの自動的な有効期限切れをスケジュールするか、1 つのデータセットまたはすべてのデータセットから個々のレコードを削除することで、保存されている消費者データを管理します。
* [Adobe Experience Platform Privacy Service](../privacy-service/home.md):すべての Adobe Experience Cloud アプリケーションにわたって、顧客自身の個人データのアクセス、販売のオプトアウトまたは削除を求める顧客リクエストを管理します。
* [リアルタイム顧客プロファイル](../profile/home.md):複数のソースから集約されたデータに基づいて、統合された顧客プロファイルをリアルタイムに提供します。
## 単一 ID の削除
単一 ID の削除リクエストでは、グラフ内の ID を削除できるので、ID 名前空間に関連付けられている単一のユーザー ID に結びついているリンクが削除されます。[Privacy Service](../privacy-service/home.md) から提供されるメカニズムは、顧客からのデータ削除リクエストや、EU 一般データ保護規則(GDPR)などのプライバシー規制への準拠といったユースケースに使用することができます。
以下の節では、Experience Platform で単一の ID 削除リクエストに使用できるメカニズムの概要を説明します。
### Privacy Service での単一 ID 削除
Privacy Service では、EU 一般データ保護規則(GDPR)やカリフォルニア州消費者プライバシー法(CCPA)などのプライバシー規制で規定されている個人データのアクセス、販売のオプトアウトまたは削除を求める顧客のリクエストを処理します。Privacy Service を使用すると、API または UI を使用してジョブリクエストを送信できます。Experience Platform が Privacy Service から削除リクエストを受信すると、リクエストが受信され、影響を受けるデータに削除マークが付けられた旨の確認を Platform が Privacy Service に送信します。個々 ID の削除は、指定した名前空間や ID 値に基づいて行われます。 さらに、指定した組織に関連付けられているすべてのサンドボックスに対して削除が行われます。詳しくは、[ID サービスでのプライバシーリクエストの処理](privacy.md)に関するガイドを参照してください。
Privacy Service での単一 ID 削除の分類を次の表に示します。
| 単一 ID 削除 | Privacy Service |
| --- | --- |
| 許可されているユースケース | データプライバシーリクエスト(GDPR、CCPA)のみ。 |
| 推定待ち時間 | 数日から数週間 |
| 影響を受けるサービス | Privacy Service での単一 ID 削除では、データを ID サービス、リアルタイム顧客プロファイル、データレイクのどれから削除するかを選択できます。 |
| 削除パターン | ID サービスから ID を削除します。 |
{style="table-layout:auto"}
## データセットの削除
以下の節では、Experience Platform 内のデータセットおよび関連する ID リンクの削除に使用できるメカニズムの概要を説明します。
### カタログサービスでのデータセットの削除
カタログサービスを使用すると、データセット削除のリクエストを送信できます。カタログサービスを使用してデータセットを削除する方法について詳しくは、[カタログサービス API を使用したオブジェクトの削除](../catalog/api/delete-object.md)に関するガイドを参照してください。また、Platform UI を使用して、データセット削除のリクエストを送信することもできます。 詳しくは、[データセットユーザーガイド](../catalog/datasets/user-guide.md#delete-a-dataset)を参照してください。
### データハイジーンにおけるデータセットの有効期限
Adobe Experience Platform UI の[[!UICONTROL データハイジーン]ワークスペース](../hygiene/ui/overview.md)では、データセットの有効期限をスケジュールできます。データセットが有効期限に達すると、データレイク、ID サービスおよびリアルタイム顧客プロファイルは別個のプロセスを開始して、それぞれのサービスからデータセットの内容を削除します。詳しくは、[[!UICONTROL データハイジーン]ワークスペースを使用したデータセットの有効期限の管理](../hygiene/ui/dataset-expiration.md)に関するガイドを参照してください。
カタログサービスとデータハイジーンにおけるデータセット削除の違いの分類を次の表に示します。
| データセットの削除 | カタログサービス | データハイジーン |
| --- | --- | --- |
| 許可されているユースケース | Platform における完全なデータセットとそれらに関連する ID 情報を削除します。 | Experience Platform に保存されているデータの管理。 |
| 推定待ち時間 | 数日 | 数日 |
| 影響を受けるサービス | カタログサービスによるデータセット削除では、ID サービス、リアルタイム顧客プロファイルおよびデータレイクからデータが削除されます。 | データハイジーンによるデータセット削除では、ID サービス、リアルタイム顧客プロファイルおよびデータ レイクからデータが削除されます。 |
| 削除パターン | 特定のデータセットによって確立されたリンク済み ID を ID サービスから削除します。 | 有効期限スケジュールに基づいて、特定のデータセットによって確立されたリンク済み ID を ID サービスから削除します。 |
{style="table-layout:auto"}
## 削除後の ID グラフの様々な状態
すべての ID グラフ削除の結果、削除リクエストで指定しているとおりに、2 つ以上の ID 間のリンクが削除されます。データセット削除リクエストの場合、指定したデータセットによって確立されたすべての ID リンクが削除され、ID はグラフから削除される場合と削除されない場合があります。単一 ID 削除リクエストの場合、指定した ID の ID リンクが削除されるので、ID 値そのものがすべての ID グラフから削除されます。別の ID へのリンクが 1 つもない ID は、ID サービスには保存されません。
削除が ID グラフの状態に与える可能性のある影響の概要を以下に示します。
| ID グラフの状態 | 説明 |
| --- | --- |
| 部分更新 | グラフの部分更新は、削除リクエストが正常に処理された後、少なくとも 2 つの ID がグラフ内でリンクされたままになっている場合に行われます。削除後、残りの ID リンクは相互に接続されたままになるか、削除された ID によっては 2 つ以上の別個のグラフに分割される可能性があります。 |
| 完全削除 | グラフが存在するには、リンクされた ID が少なくとも 2 つ必要です。したがって、削除リクエストの結果、グラフ内の既存のリンクがすべて削除される場合、グラフは完全に削除されます。 |
| 変更なし | グラフのどのメンバーにも関連付けられていない ID またはデータセットが特定の削除リクエストに含まれている場合、グラフは影響を受けません。また、削除されなかった別のリンクによってリンクが確立された場合、削除リクエストによってデータセットまたは ID とデータセットの組み合わせ間のリンクが削除されても、グラフは更新されません。つまり、2 つの異なるデータセットにリンクが存在する場合、一方のデータセットのみ削除されるので、グラフは更新されません。 |
{style="table-layout:auto"}
## 次の手順
このドキュメントでは、Experience Platform での ID とデータセットの削除に使用できる様々なメカニズムについて説明しました。このドキュメントでは、ID とデータセットの削除が ID グラフに与える可能性のある影響についても説明しました。ID サービスについて詳しくは、[ID サービスの概要](home.md)を参照してください。
<!--
You can use [Data hygiene](../hygiene/home.md) for data cleansing, removing anonymous data, or data minimization for the data that you have collected.
### Single identity deletion in the [!UICONTROL Data Hygiene] workspace
The [[!UICONTROL Data Hygiene] workspace](../hygiene/ui/overview.md) in the Platform UI allows you to delete consumer records that are participating in Identity Service and Real-Time Customer Profile. For a comprehensive guide on using the [!UICONTROL Data Hygiene] workspace, see the tutorial on [deleting consumer records](../hygiene/ui/record-delete.md).
The table below provides a breakdown of differences between single identity deletion in Privacy Service and Data hygiene:
| Single identity deletion | Privacy Service | Data hygiene |
| --- | --- | --- |
| Accepted use cases | Data privacy requests (GDPR, CCPA) only. | Management of data stored in Experience Platform. |
| Estimated latency | Days to weeks | Days |
| Services impacted | Single identity deletion in Privacy Service allows you to select whether data will be deleted from Identity Service, Real-Time Customer Profile, or data lake. | Single identity deletion in Data hygiene deletes the selected data across Identity Service, Real-Time Customer Profile, and data lake. |
| Deletion patterns | Delete an identity from Identity Service. | Delete an identity from Identity Service. |
-->
|
<div class="container">
<div class="row">
<div class="col-md-12">
<h3>Add Dish</h3>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form [formGroup]="dishForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="dishName">Dish Name</label>
<input type="text" class="form-control" id="dishName" formControlName="dishName">
<div *ngIf="dishForm.get('dishName')?.invalid && (dishForm.get('dishName')?.dirty || dishForm.get('dishName')?.touched)" class="text-danger mt-1">
<div *ngIf="dishForm.get('dishName')?.errors?.['required']">Dish Name is required</div>
</div>
</div>
<div class="form-group">
<label for="dishDescription">Dish Description</label>
<textarea class="form-control" id="dishDescription" formControlName="dishDescription"></textarea>
<div *ngIf="dishForm.get('dishDescription')?.invalid && (dishForm.get('dishDescription')?.dirty || dishForm.get('dishDescription')?.touched)" class="text-danger mt-1">
<div *ngIf="dishForm.get('dishDescription')?.errors?.['required']">Dish Description is required</div>
</div>
</div>
<div class="form-group">
<label for="dishPrice">Dish Price</label>
<input type="number" class="form-control" id="dishPrice" formControlName="dishPrice">
<div *ngIf="dishForm.get('dishPrice')?.invalid && (dishForm.get('dishPrice')?.dirty || dishForm.get('dishPrice')?.touched)" class="text-danger mt-1">
<div *ngIf="dishForm.get('dishPrice')?.errors?.['required']">Dish Price is required</div>
</div>
</div>
<div class="form-group">
<label for="dishImage">Dish Image URL</label>
<input type="text" class="form-control" id="dishImage" formControlName="dishImage">
<div *ngIf="dishForm.get('dishImage')?.invalid && (dishForm.get('dishImage')?.dirty || dishForm.get('dishImage')?.touched)" class="text-danger mt-1">
<div *ngIf="dishForm.get('dishImage')?.errors?.['required']">Dish Image is required</div>
</div>
</div>
<div class="form-group">
<label for="dishImage">Nature</label>
<input type="text" class="form-control" id="dishImage" formControlName="nature">
<div *ngIf="dishForm.get('nature')?.invalid && (dishForm.get('nature')?.dirty || dishForm.get('nature')?.touched)" class="text-danger mt-1">
<div *ngIf="dishForm.get('nature')?.errors?.['required']">nature is required</div>
</div>
</div>
<!-- <div class="form-group">
<input type="hidden" id="dishCategory" formControlName="dishCategory" [value]="categoryId">
</div> -->
<div class="form-group">
<button type="submit" class="btn btn-primary" >Submit</button>
<!-- <button type="submit" class="btn btn-primary" >Submit</button> -->
</div>
</form>
</div>
</div>
</div>
|
---
title: "Another Look at Fruitflies"
author: ""
date: "Last Updated: July 30, 2015"
output:
html_document:
fig_height: 3
fig_width: 5
word_document:
fig_height: 3
fig_width: 5
---
```{r include=FALSE}
# Don't delete this chunk if you are using the mosaic package
# This loads the mosaic and dplyr packages
require(mosaic)
```
```{r include=FALSE}
# Some customization. You can alter or delete as desired (if you know what you are doing).
# This changes the default colors in lattice plots.
trellis.par.set(theme=theme.mosaic())
# knitr settings to control how R chunks work.
require(knitr)
opts_chunk$set(
tidy=FALSE, # display code as typed
size="small" # slightly smaller font for code
)
# This loads the mosaic data sets. (Could be deleted if you are not using them.)
require(mosaicData)
require(Stat2Data)
```
This corresponds to a series of examples in Chapter 7, starting with Example 7.4 on p. 332.
## The Data
In Chapter 5, we used the `FruitFlies` dataset to examine whether or not the mean lifespan of male fruit flies depended on the kind of mate(s) it resided with.
```{r}
data(FruitFlies)
head(FruitFlies)
```
Earlier, we found that mean lifespans of male fruit flies differed depending on the number/type of females it resided with.
```{r}
m1 <- lm(Longevity ~ Treatment, data=FruitFlies)
anova(m1)
```
## Multiple Comparisons
* Review: Run Fisher's LSD to see which pairs of treatments are determined to have significantly different means at an alpha level of 0.05.
SOLUTION:
```{r}
```
* Use the Bonferroni correction to see which pairs of treatments are determined to have significantly different means at an alpha level of 0.05. What do you conclude?
SOLUTION:
```{r}
```
* What is the relationship between the p-values in the two tables above?
SOLUTION:
* Use Tukey's HSD to see which pairs of treatments are determined to have significantly different means at an alpha level of 0.05. What do you conclude?
SOLUTION:
```{r}
```
## 2 Sample Comparisons
Now, we will consider a subset of the dataset which contains 25 fruit flies in the 8 virgins group and the 25 fruit flies living alone and consider the similarities betwen regression and a two-sample comparison of means.
* Use the `filter()` function to create a new dataset, called `FruitFlies1` which only contains the 2 groups of interest.
SOLUTION:
```{r}
```
* Compute the sample mean of each group.
SOLUTION:
```{r}
```
* Produce a dot plot (using `dotPlot()`) like Figure 7.8 to illustrate the difference in lifespans of the two different groups.
SOLUTION:
```{r}
```
* Perform a **pooled** two-sample t-test on the data. What do you conclude?
SOLUTION:
```{r}
```
* Perform an ANOVA to address the same question. What do you discover?
SOLUTION:
```{r}
```
* Fit a regression model using `Treatment = "none"` as the reference level. Show the regression summary.
SOLUTION:
```{r}
```
* Compare the results of the linear regression (and its associated ANOVA table) to the results of the pooled 2-sample t-test.
SOLUTION:
## Back to the Entire Sample
* Fit a regression model using `Treatment = "none"` as the reference level. Show the regression summary.
SOLUTION:
```{r}
```
* What do you learn from the p-values in the linear model summary above? What do you learn from the p-value in the ANOVA table?
SOLUTION:
```{r}
```
|
import { centerOfMass, polygon } from "@turf/turf";
import axios from "axios";
import { useEffect, useRef } from "react";
import { Marker, GeoJSON, useMapEvents, Popup, useMap } from "react-leaflet";
import { useStore, actions } from "../store";
import "../styles/App.css";
import proj4 from "proj4";
function GeoJsonLayers() {
const [state, dispatch] = useStore();
const {
dataGeoJson,
dataGeoJsonCNSDD,
dataGeoJsonQHCT,
dataGeoJsonDCCB,
fileCoords,
displayQHPK,
displayQHSDD,
displayKHSDD,
displayBDG,
dataGeoJsonDCCBofBDG,
dataGeoJsonRanhOfBDG,
dataDCCBofBDG,
displayDCCBofBDG,
} = state;
const dataRef = useRef();
const cnsddRef = useRef();
const qhctRef = useRef();
const dccbRef = useRef();
const dccbOfBDGRef = useRef();
const ranhOfBDGRef = useRef();
const map = useMap();
const mapClick = useMapEvents({
click(event) {
const { lat, lng } = event.latlng;
if (displayBDG) {
postDataBDG(lat, lng);
mapClick.flyTo({ lat, lng }, 15);
} else {
postData(lat, lng);
mapClick.flyTo({ lat, lng }, 18);
}
},
});
useEffect(() => {
if (!fileCoords.length) {
return;
} else {
postCoords(fileCoords);
map.flyToBounds(changeCoordsToWGS84(fileCoords), 14);
dispatch(actions.setFileCoords([]));
}
}, [fileCoords]);
const changeCoordsToWGS84 = (coords) => {
let vn2000 =
"+proj=tmerc +lat_0=0 +lon_0=105.75 +k=0.9999 +x_0=500000 +y_0=0 +ellps=WGS84 +towgs84=-191.90441429,-39.30318279,-111.45032835,-0.00928836,0.01975479,-0.00427372,0.252906278 +units=m +no_defs +type=crs";
let wgs84 = "+proj=longlat +datum=WGS84 +no_defs +type=crs";
let swapCoords = coords.map((arr) => {
arr.reverse();
return arr;
});
const wgs84Coords = swapCoords.map((arr) => proj4(vn2000, wgs84, arr));
return wgs84Coords.map((arr) => {
arr.reverse();
return arr;
});
};
const postCoords = async (coords) => {
try {
if (!coords.length) {
return;
} else {
dispatch(actions.setIsLoading(true));
dispatch(actions.setDisplaySearch(false));
const response = await axios({
method: "POST",
url: "https://sqhkt-qlqh.tphcm.gov.vn/computing/930/api/v3.5/a-z/maqh/762",
data: {
ToaDo: `[${coords.map((arr) => `[${arr}]`)}]`,
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
dispatch(actions.setDisplayDataInformation(true));
dispatch(actions.setData(response.data));
dispatch(actions.setDataGeoJson(JSON.parse(response.data.QHPK)));
dispatch(actions.setIsLoading(false));
}
} catch (error) {
dispatch(actions.setIsLoading(false));
console.log(error);
}
};
const postData = async (lat, lng) => {
try {
dispatch(actions.setDataGeoJsonCNSDD([]));
dispatch(actions.setDisplayCNSDD(false));
dispatch(actions.setIsLoading(true));
const response = await axios({
method: "POST",
url: "https://sqhkt-qlqh.tphcm.gov.vn/computing/930/api/v3.5/a-z/maqh/762",
data: {
Lat: lat,
Lon: lng,
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
dispatch(actions.setDisplayDataInformation(true));
dispatch(actions.setData(response.data));
checkShowMap(response.data);
dispatch(actions.setIsLoading(false));
} catch (error) {
dispatch(actions.setIsLoading(false));
console.log(error);
}
};
const postDataBDG = async (lat, lng) => {
try {
dispatch(actions.setDisplayDCCBofBDG(false));
dispatch(actions.setDisplayFullMapBDG(false));
dispatch(actions.setIsLoading(true));
const response = await axios({
method: "POST",
url: "https://sqhkt-qlqh.tphcm.gov.vn/api/doan/ranhqhpk",
data: {
Lat: lat,
Lon: lng,
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
dispatch(actions.setDisplayDataInformation(true));
checkShowMap(response.data);
dispatch(actions.setIsLoading(false));
} catch (error) {
dispatch(actions.setIsLoading(false));
console.log(error);
}
};
const checkShowMap = (data) => {
if (displayQHPK) {
return dispatch(actions.setDataGeoJson(JSON.parse(data.QHPK)));
}
if (displayKHSDD) {
return dispatch(actions.setDataGeoJson(JSON.parse(data.KHSDD)));
}
if (displayQHSDD) {
return dispatch(actions.setDataGeoJson(JSON.parse(data.QHSDD)));
}
if (displayBDG) {
let arrayDCCB = [];
let geoData = {
coordinates: [],
type: "MultiPolygon",
};
data.forEach((objData) => {
dispatch(actions.setData(objData));
geoData.coordinates = JSON.parse(objData.Ranh);
objData.DCCB.forEach((dccb) => {
let geoDataDCCB = {
geometry: { coordinates: [], type: "MultiPolygon" },
type: "Feature",
};
geoDataDCCB.geometry.coordinates = JSON.parse(dccb.Ranh);
arrayDCCB.push(geoDataDCCB);
});
});
dispatch(actions.setDataGeoJsonDCCBofBDG(arrayDCCB));
dispatch(actions.setDataGeoJsonRanhOfBDG(geoData));
}
};
useEffect(() => {
if (displayDCCBofBDG) {
let swapArr = JSON.parse(dataDCCBofBDG.Ranh)[0][0].map((arr) =>
arr.reverse()
);
map.flyToBounds(swapArr, 14);
}
}, [displayDCCBofBDG]);
useEffect(() => {
if (dataRef.current) {
dataRef.current.clearLayers(); // remove old data
dataRef.current.addData(dataGeoJson); // might need to be geojson.features
}
}, [dataRef, dataGeoJson]);
useEffect(() => {
if (cnsddRef.current) {
cnsddRef.current.clearLayers(); // remove old data
cnsddRef.current.addData(dataGeoJsonCNSDD); // might need to be geojson.features
}
}, [cnsddRef, dataGeoJsonCNSDD]);
useEffect(() => {
if (qhctRef.current) {
qhctRef.current.clearLayers(); // remove old data
qhctRef.current.addData(dataGeoJsonQHCT); // might need to be geojson.features
}
}, [qhctRef, dataGeoJsonQHCT]);
useEffect(() => {
if (dccbRef.current) {
dccbRef.current.clearLayers(); // remove old data
dccbRef.current.addData(dataGeoJsonDCCB); // might need to be geojson.features
}
}, [dccbRef, dataGeoJsonDCCB]);
useEffect(() => {
if (ranhOfBDGRef.current) {
ranhOfBDGRef.current.clearLayers(); // remove old data
ranhOfBDGRef.current.addData(dataGeoJsonRanhOfBDG); // might need to be geojson.features
}
}, [ranhOfBDGRef, dataGeoJsonRanhOfBDG]);
useEffect(() => {
if (dccbOfBDGRef.current) {
dccbOfBDGRef.current.clearLayers(); // remove old data
dccbOfBDGRef.current.addData(dataGeoJsonDCCBofBDG); // might need to be geojson.features
}
}, [dccbOfBDGRef, dataGeoJsonDCCBofBDG]);
const handleGetColor = (feature) => {
return {
color: "rgb(" + feature.properties.rgbcolor + ")",
fillColor: "rgb(" + feature.properties.rgbcolor + ")",
fill: true,
fillOpacity: 1,
};
};
const handleCenterMap = (marker) => {
const centerPoint = centerOfMass(polygon(marker.geometry.coordinates[0]));
const [longitude, latitude] = centerPoint.geometry.coordinates;
return [latitude, longitude];
};
const handleGeoJson = (dataGeo, ref, color) =>
dataGeo && <GeoJSON ref={ref} data={dataGeo} style={{ color: color }} />;
return (
<>
{dataGeoJson && (
<>
{dataGeoJson.map((marker, index) => (
<>
<Marker
key={index}
position={handleCenterMap(marker)}
interactive={true}
icon={L.divIcon({
html: `
<img src="src/img/marker.png" width="40" height="40"">
<div class="number">${index + 1}</div>
</img>`,
className: "leaflet-marker-icon",
iconAnchor: [20, 40],
})}
>
<Popup>
<span>{index + 1}</span>
</Popup>
</Marker>
</>
))}
<GeoJSON ref={dataRef} data={dataGeoJson} style={handleGetColor} />
</>
)}
{/* Layer of Chức Năng Sử Dụng Đất */}
{handleGeoJson(dataGeoJsonCNSDD, cnsddRef, "red")}
{/* Layer of Quy Hoach Chi Tiet */}
{handleGeoJson(dataGeoJsonQHCT, qhctRef, "#FF334F")}
{/* Layer of Dieu Chinh Cuc Bo */}
{handleGeoJson(dataGeoJsonDCCB, dccbRef, "#FF334F")}
{/* Layer of Ranh BDG */}
{handleGeoJson(dataGeoJsonRanhOfBDG, ranhOfBDGRef, "black")}
{/* Layer of Ranh DCCB => BDG */}
{handleGeoJson(dataGeoJsonDCCBofBDG, dccbOfBDGRef, "red")}
</>
);
}
export default GeoJsonLayers;
|
/* Tools20022 - API for ISO 20022
* Copyright (C) 2017 Tools20022.com - László Bukodi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.tools20022.repository.area.catm;
import com.tools20022.metamodel.MMMessageBuildingBlock;
import com.tools20022.metamodel.MMMessageDefinition;
import com.tools20022.metamodel.MMMessageDefinitionIdentifier;
import com.tools20022.metamodel.MMRegistrationStatus;
import com.tools20022.repository.area.TerminalManagementArchive;
import com.tools20022.repository.msg.ContentInformationType12;
import com.tools20022.repository.msg.Header27;
import com.tools20022.repository.msg.ManagementPlan5;
import com.tools20022.repository.msgset.ISOArchive;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
import java.util.Objects;
import java.util.Optional;
import javax.xml.bind.annotation.*;
/**
* Terminal maintenance actions to be performed by a point of interaction (POI).
* <p>
* <strong>Constant fields:</strong>
* <ul>
* <li>
* {@linkplain com.tools20022.metamodel.MMMessageDefinition#getMessageDefinitionIdentifier
* messageDefinitionIdentifier} = {@code catm.002.001.05}</li>
* <li>{@linkplain com.tools20022.metamodel.MMMessageDefinition#getBusinessArea
* businessArea} =
* {@linkplain com.tools20022.repository.area.TerminalManagementArchive
* TerminalManagementArchive}</li>
* <li>
* {@linkplain com.tools20022.metamodel.MMMessageDefinition#getMessageBuildingBlock
* messageBuildingBlock} =
* <ul>
* <li>
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV05#mmHeader
* ManagementPlanReplacementV05.mmHeader}</li>
* <li>
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV05#mmManagementPlan
* ManagementPlanReplacementV05.mmManagementPlan}</li>
* <li>
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV05#mmSecurityTrailer
* ManagementPlanReplacementV05.mmSecurityTrailer}</li>
* </ul>
* </li>
* <li>{@linkplain com.tools20022.metamodel.MMMessageDefinition#getMessageSet
* messageSet} =
* <ul>
* <li>{@linkplain com.tools20022.repository.msgset.ISOArchive ISOArchive}</li>
* </ul>
* </li>
* <li>{@linkplain com.tools20022.metamodel.MMMessageDefinition#getRootElement
* rootElement} = "Document"</li>
* <li>{@linkplain com.tools20022.metamodel.MMMessageDefinition#getXmlTag
* xmlTag} = "MgmtPlanRplcmnt"</li>
* <li>{@linkplain com.tools20022.metamodel.MMRepositoryConcept#getName name} =
* "ManagementPlanReplacementV05"</li>
* <li>{@linkplain com.tools20022.metamodel.MMRepositoryConcept#getDefinition
* definition} =
* "Terminal maintenance actions to be performed by a point of interaction (POI)."
* </li>
* <li>
* {@linkplain com.tools20022.metamodel.MMRepositoryConcept#getRegistrationStatus
* registrationStatus} =
* com.tools20022.metamodel.MMRegistrationStatus.REGISTERED</li>
* <li>{@linkplain com.tools20022.metamodel.MMModelEntity#getNextVersions
* nextVersions} =
* <ul>
* <li>
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV06
* ManagementPlanReplacementV06}</li>
* </ul>
* </li>
* <li>{@linkplain com.tools20022.metamodel.MMModelEntity#getPreviousVersion
* previousVersion} =
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV04
* ManagementPlanReplacementV04}</li>
* </ul>
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "ManagementPlanReplacementV05", propOrder = {"header", "managementPlan", "securityTrailer"})
public class ManagementPlanReplacementV05 {
final static private AtomicReference<MMMessageDefinition> mmObject_lazy = new AtomicReference<>();
@XmlElement(name = "Hdr", required = true)
protected Header27 header;
/**
*
<p>
* <strong>Constant fields:</strong>
* <ul>
* <li>
* {@linkplain com.tools20022.metamodel.MMMessageBuildingBlock#getComplexType
* complexType} = {@linkplain com.tools20022.repository.msg.Header27
* Header27}</li>
* <li>{@linkplain com.tools20022.metamodel.MMMessageConstruct#getXmlTag
* xmlTag} = "Hdr"</li>
* <li>{@linkplain com.tools20022.metamodel.MMRepositoryConcept#getName
* name} = "Header"</li>
* <li>
* {@linkplain com.tools20022.metamodel.MMRepositoryConcept#getDefinition
* definition} =
* "Set of characteristics related to the transfer of the management plan."</li>
* <li>
* {@linkplain com.tools20022.metamodel.MMRepositoryConcept#getRegistrationStatus
* registrationStatus} =
* com.tools20022.metamodel.MMRegistrationStatus.PROVISIONALLY_REGISTERED</li>
* <li>{@linkplain com.tools20022.metamodel.MMModelEntity#getNextVersions
* nextVersions} =
* <ul>
* <li>
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV06#mmHeader
* ManagementPlanReplacementV06.mmHeader}</li>
* </ul>
* </li>
* <li>
* {@linkplain com.tools20022.metamodel.MMModelEntity#getPreviousVersion
* previousVersion} =
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV04#mmHeader
* ManagementPlanReplacementV04.mmHeader}</li>
* </ul>
*/
public static final MMMessageBuildingBlock<ManagementPlanReplacementV05, Header27> mmHeader = new MMMessageBuildingBlock<ManagementPlanReplacementV05, Header27>() {
{
xmlTag = "Hdr";
registrationStatus = MMRegistrationStatus.PROVISIONALLY_REGISTERED;
name = "Header";
definition = "Set of characteristics related to the transfer of the management plan.";
nextVersions_lazy = () -> Arrays.asList(ManagementPlanReplacementV06.mmHeader);
previousVersion_lazy = () -> ManagementPlanReplacementV04.mmHeader;
maxOccurs = 1;
minOccurs = 1;
complexType_lazy = () -> Header27.mmObject();
}
@Override
public Header27 getValue(ManagementPlanReplacementV05 obj) {
return obj.getHeader();
}
@Override
public void setValue(ManagementPlanReplacementV05 obj, Header27 value) {
obj.setHeader(value);
}
};
@XmlElement(name = "MgmtPlan", required = true)
protected ManagementPlan5 managementPlan;
/**
*
<p>
* <strong>Constant fields:</strong>
* <ul>
* <li>
* {@linkplain com.tools20022.metamodel.MMMessageBuildingBlock#getComplexType
* complexType} = {@linkplain com.tools20022.repository.msg.ManagementPlan5
* ManagementPlan5}</li>
* <li>{@linkplain com.tools20022.metamodel.MMMessageConstruct#getXmlTag
* xmlTag} = "MgmtPlan"</li>
* <li>{@linkplain com.tools20022.metamodel.MMRepositoryConcept#getName
* name} = "ManagementPlan"</li>
* <li>
* {@linkplain com.tools20022.metamodel.MMRepositoryConcept#getDefinition
* definition} =
* "Sequence of terminal maintenance actions to be performed by a point of interaction (POI)."
* </li>
* <li>
* {@linkplain com.tools20022.metamodel.MMRepositoryConcept#getRegistrationStatus
* registrationStatus} =
* com.tools20022.metamodel.MMRegistrationStatus.PROVISIONALLY_REGISTERED</li>
* <li>{@linkplain com.tools20022.metamodel.MMModelEntity#getNextVersions
* nextVersions} =
* <ul>
* <li>
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV06#mmManagementPlan
* ManagementPlanReplacementV06.mmManagementPlan}</li>
* </ul>
* </li>
* <li>
* {@linkplain com.tools20022.metamodel.MMModelEntity#getPreviousVersion
* previousVersion} =
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV04#mmManagementPlan
* ManagementPlanReplacementV04.mmManagementPlan}</li>
* </ul>
*/
public static final MMMessageBuildingBlock<ManagementPlanReplacementV05, ManagementPlan5> mmManagementPlan = new MMMessageBuildingBlock<ManagementPlanReplacementV05, ManagementPlan5>() {
{
xmlTag = "MgmtPlan";
registrationStatus = MMRegistrationStatus.PROVISIONALLY_REGISTERED;
name = "ManagementPlan";
definition = "Sequence of terminal maintenance actions to be performed by a point of interaction (POI).";
nextVersions_lazy = () -> Arrays.asList(ManagementPlanReplacementV06.mmManagementPlan);
previousVersion_lazy = () -> ManagementPlanReplacementV04.mmManagementPlan;
maxOccurs = 1;
minOccurs = 1;
complexType_lazy = () -> ManagementPlan5.mmObject();
}
@Override
public ManagementPlan5 getValue(ManagementPlanReplacementV05 obj) {
return obj.getManagementPlan();
}
@Override
public void setValue(ManagementPlanReplacementV05 obj, ManagementPlan5 value) {
obj.setManagementPlan(value);
}
};
@XmlElement(name = "SctyTrlr")
protected ContentInformationType12 securityTrailer;
/**
*
<p>
* <strong>Constant fields:</strong>
* <ul>
* <li>
* {@linkplain com.tools20022.metamodel.MMMessageBuildingBlock#getComplexType
* complexType} =
* {@linkplain com.tools20022.repository.msg.ContentInformationType12
* ContentInformationType12}</li>
* <li>{@linkplain com.tools20022.metamodel.MMMessageConstruct#getXmlTag
* xmlTag} = "SctyTrlr"</li>
* <li>{@linkplain com.tools20022.metamodel.MMRepositoryConcept#getName
* name} = "SecurityTrailer"</li>
* <li>
* {@linkplain com.tools20022.metamodel.MMRepositoryConcept#getDefinition
* definition} =
* "Trailer of the message containing a MAC or a digital signature."</li>
* <li>
* {@linkplain com.tools20022.metamodel.MMRepositoryConcept#getRegistrationStatus
* registrationStatus} =
* com.tools20022.metamodel.MMRegistrationStatus.PROVISIONALLY_REGISTERED</li>
* <li>{@linkplain com.tools20022.metamodel.MMModelEntity#getNextVersions
* nextVersions} =
* <ul>
* <li>
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV06#mmSecurityTrailer
* ManagementPlanReplacementV06.mmSecurityTrailer}</li>
* </ul>
* </li>
* <li>
* {@linkplain com.tools20022.metamodel.MMModelEntity#getPreviousVersion
* previousVersion} =
* {@linkplain com.tools20022.repository.area.catm.ManagementPlanReplacementV04#mmSecurityTrailer
* ManagementPlanReplacementV04.mmSecurityTrailer}</li>
* </ul>
*/
public static final MMMessageBuildingBlock<ManagementPlanReplacementV05, Optional<ContentInformationType12>> mmSecurityTrailer = new MMMessageBuildingBlock<ManagementPlanReplacementV05, Optional<ContentInformationType12>>() {
{
xmlTag = "SctyTrlr";
registrationStatus = MMRegistrationStatus.PROVISIONALLY_REGISTERED;
name = "SecurityTrailer";
definition = "Trailer of the message containing a MAC or a digital signature.";
nextVersions_lazy = () -> Arrays.asList(ManagementPlanReplacementV06.mmSecurityTrailer);
previousVersion_lazy = () -> ManagementPlanReplacementV04.mmSecurityTrailer;
maxOccurs = 1;
minOccurs = 0;
complexType_lazy = () -> ContentInformationType12.mmObject();
}
@Override
public Optional<ContentInformationType12> getValue(ManagementPlanReplacementV05 obj) {
return obj.getSecurityTrailer();
}
@Override
public void setValue(ManagementPlanReplacementV05 obj, Optional<ContentInformationType12> value) {
obj.setSecurityTrailer(value.orElse(null));
}
};
final static public MMMessageDefinition mmObject() {
mmObject_lazy.compareAndSet(null, new MMMessageDefinition() {
{
registrationStatus = MMRegistrationStatus.REGISTERED;
name = "ManagementPlanReplacementV05";
definition = "Terminal maintenance actions to be performed by a point of interaction (POI).";
nextVersions_lazy = () -> Arrays.asList(ManagementPlanReplacementV06.mmObject());
previousVersion_lazy = () -> ManagementPlanReplacementV04.mmObject();
messageSet_lazy = () -> Arrays.asList(ISOArchive.mmObject());
rootElement = "Document";
xmlTag = "MgmtPlanRplcmnt";
businessArea_lazy = () -> TerminalManagementArchive.mmObject();
messageBuildingBlock_lazy = () -> Arrays.asList(com.tools20022.repository.area.catm.ManagementPlanReplacementV05.mmHeader, com.tools20022.repository.area.catm.ManagementPlanReplacementV05.mmManagementPlan,
com.tools20022.repository.area.catm.ManagementPlanReplacementV05.mmSecurityTrailer);
messageDefinitionIdentifier_lazy = () -> new MMMessageDefinitionIdentifier() {
{
businessArea = "catm";
messageFunctionality = "002";
version = "05";
flavour = "001";
}
};
}
@Override
public Class<?> getInstanceClass() {
return ManagementPlanReplacementV05.class;
}
});
return mmObject_lazy.get();
}
public Header27 getHeader() {
return header;
}
public ManagementPlanReplacementV05 setHeader(Header27 header) {
this.header = Objects.requireNonNull(header);
return this;
}
public ManagementPlan5 getManagementPlan() {
return managementPlan;
}
public ManagementPlanReplacementV05 setManagementPlan(ManagementPlan5 managementPlan) {
this.managementPlan = Objects.requireNonNull(managementPlan);
return this;
}
public Optional<ContentInformationType12> getSecurityTrailer() {
return securityTrailer == null ? Optional.empty() : Optional.of(securityTrailer);
}
public ManagementPlanReplacementV05 setSecurityTrailer(ContentInformationType12 securityTrailer) {
this.securityTrailer = securityTrailer;
return this;
}
@XmlRootElement(name = "Document", namespace = "urn:iso:std:iso:20022:tech:xsd:catm.002.001.05")
static public class Document {
@XmlElement(name = "MgmtPlanRplcmnt", required = true)
public ManagementPlanReplacementV05 messageBody;
}
}
|
# Tabla de factura compra detalle
## Campos:
### numfac
* Tipo de dato: int
* Tamaño: 3 dígitos
* Llave primaria: si
* Llave foránea: si
* Tabla foránea: [factcprae](./06%20Factura%20Compra%20Encabezado.md)
* Campo foránea: [numfac](./06%20Factura%20Compra%20Encabezado.md#numfac)
### idprod
* Tipo de dato: int
* Tamaño: 3 dígitos
* Llave primaria: si
* Llave foránea: si
* Tabla foránea: [productos](./02%20Productos.md)
* Campo foránea: [id](./02%20Productos.md#id)
### cantidad
* Tipo de dato: int
* Tamaño: 5 dígitos
### precio
* Tipo de dato: decimal
* Tamaño: 7 dígitos, 2 decimales
## Creación de la tabla:
``` sql
CREATE TABLE `empresax`.`factcprad`
(
`numfac` INT(3) NOT NULL,
`idprod` INT(3) NOT NULL,
`cantidad` INT(5) NULL,
`precio` DECIMAL(7, 2) NULL,
PRIMARY KEY (`numfac`, `idprod`),
INDEX `numFac_idx` (`numfac` ASC) VISIBLE,
INDEX `idProd_idx` (`idprod` ASC) VISIBLE,
CONSTRAINT `numFacFactCpraD`
FOREIGN KEY (`numfac`)
REFERENCES `empresax`.`factcprae` (`numfac`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idProdFactCpraD`
FOREIGN KEY (`idprod`)
REFERENCES `empresax`.`productos` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
```
[ver sql](./sql/07%20Factura%20Compra%20Detalle.sql)
## Contenido de la tabla:
| numfac | idprod | cantidad | precio |
|--------|--------|----------|--------|
| 001 | 001 | 1 | 100 |
| 001 | 002 | 2 | 200 |
| 002 | 001 | 1 | 100 |
| 002 | 002 | 1 | 200 |
| 002 | 003 | 1 | 300 |
[ver csv](./csv/07%20Factura%20Compra%20Detalle.csv)
<p align="center">
<a href="./05%20Factura%20Compra%20Encabezado.md">Regresar</a> |
<a href="../README.md">Inicio</a> |
<a href="./06%20Factura%20Compra%20Detalle.md">Siguiente</a>
</p>
|
<div class="post_bd post">
<p>
<strong>setpci命令</strong>是一个查询和配置PCI设备的使用工具。
</p>
<h3>
语法<br/>
</h3>
<pre>
setpci(选项)(参数)</pre>
<h3>
选项<br/>
</h3>
<pre>
-v:显示指令执行的细节信息;
-f:当没有任何操作需要完成时,不显示任何信息;
-D:测试模式,并不真正将配置信息写入寄存器;
-d:仅显示给定厂商和设备的信息;
-s:仅显示指定总线、插槽上的设备或设备上的功能块信息。</pre>
<h3>
参数<br/>
</h3>
<ul>
<li>
PCI设备:指定要配置的PCI设备;
</li>
<li>
操作:指定要完成的配置操作。
</li>
</ul>
<h3>
实例<br/>
</h3>
<p>
Linux下调节笔记本屏幕亮度方法:
</p>
<p>
首先进入终端输入<span class="wp_keywordlink"><a href="http://man.linuxde.net/lspci" target="_blank" title="lspci命令">lspci</a></span>命令,列出各种设备的地址:
</p>
<pre>
<span style="color:#B22222;">lspci</span>
00:00.0 <span class="wp_keywordlink"><a href="http://man.linuxde.net/host" target="_blank" title="host命令">host</a></span> bridge: Intel Corporation Mobile 945GM/PM/GMS, 943/940GML and 945GT Express Memory Controller Hub (<span class="wp_keywordlink"><a href="http://man.linuxde.net/rev" target="_blank" title="rev命令">rev</a></span> 03)
00:02.0 VGA compatible controller: Intel Corporation Mobile 945GM/GMS, 943/940GML Express Integrated Graphics Controller (rev 03)
00:02.1 Display controller: Intel Corporation Mobile 945GM/GMS/GME, 943/940GML Express Integrated Graphics Controller (rev 03)
00:1b.0 Audio device: Intel Corporation N10/ICH 7 Family High Definition Audio Controller (rev 02)
00:1c.0 PCI bridge: Intel Corporation N10/ICH 7 Family PCI Express Port 1 (rev 02)
00:1c.1 PCI bridge: Intel Corporation N10/ICH 7 Family PCI Express Port 2 (rev 02)
......</pre>
<p>
发现00:02.0是VGA设备,于是我们修改它的属性:
</p>
<pre>
<span class="wp_keywordlink"><a href="http://man.linuxde.net/sudo" target="_blank" title="sudo命令">sudo</a></span> setpci -s 00:02.0 F4.B=FF</pre>
<p>
解释一下:
</p>
<ul>
<li>
<strong>setpci</strong> 是修改设备属性的命令。
</li>
<li>
<strong>-s</strong> 表示接下来输入的是设备的地址。
</li>
<li>
<strong>00:02.0</strong> VGA设备地址(<总线>:<接口>.<功能>)。
</li>
<li>
<strong>F4</strong> 要修改的属性的地址,这里应该表示“亮度”。
</li>
<li>
<strong>.B</strong> 修改的长度(B应该是字节(Byte),还有<span class="wp_keywordlink"><a href="http://man.linuxde.net/w" target="_blank" title="w命令">w</a></span>(应该是Word,两个字节)、L(应该是Long,4个字节))。
</li>
<li>
<strong>=FF</strong> 要修改的值(可以改)。
</li>
</ul>
<p>
我这里00是最暗,FF是最亮,不同的电脑可能不一样。比如说我嫌FF太闪眼了,我就可以:
</p>
<pre>
sudo setpci -s 00:02.0 F4.B=CC</pre>
</div>
|
package validator_ext
import (
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
"strings"
)
const MustInSeq = "#"
func mustIn(fl validator.FieldLevel) bool {
s := fl.Field().String()
if s == "" {
return true
}
arr := strings.Split(fl.Param(), MustInSeq)
for _, v := range arr {
if v == s {
return true
}
}
return false
}
func registerMustInEn(validate *validator.Validate, trans ut.Translator) {
validate.RegisterTranslation(MUST_IN, trans, func(ut ut.Translator) error {
return ut.Add(MUST_IN, "[{0}] must in [{1}]", true)
}, func(ut ut.Translator, fe validator.FieldError) string {
t, _ := ut.T(MUST_IN, strings.ToLower(fe.Field()), fe.Param())
return t
})
}
func registerMustInZh(validate *validator.Validate, trans ut.Translator) {
validate.RegisterTranslation(MUST_IN, trans, func(ut ut.Translator) error {
return ut.Add(MUST_IN, "【{0}】必须在【{1}】", true)
}, func(ut ut.Translator, fe validator.FieldError) string {
t, _ := ut.T(MUST_IN, strings.ToLower(fe.Field()), fe.Param())
return t
})
}
|
/// Custom exception class to handle various Firebase authentication-related errors
class DFirebaseAuthException implements Exception {
/// The error code associated with the exception
final String code;
/// Constructor that takes an error code
DFirebaseAuthException(this.code);
///Get the corresponding error messages based on the error code
String get message {
switch (code) {
case 'email-already-in-use':
return 'The email address is already registered. Please use a different email.';
case 'invalid-email':
return 'The email address is invalid. Please use a different email.';
case 'weak-password':
return 'The password used is weak. Please use a different password.';
case 'user-disabled':
return 'Your account is disabled. Please contact support.';
case 'user-not-found':
return 'User not found.';
case 'wrong-password':
return 'The password entered is wrong. Please use the correct password.';
case 'invalid-verification-code':
return 'Invalid verification code. Enter the correct code or resend.';
case 'invalid-verification-id':
return 'Invalid verification id.';
case 'quota-exceeded':
return 'Quota exceeded.';
case 'email-already-exists':
return 'Email already exists. Please use a different email.';
case 'provider-already-linked':
return 'Provider already linked. Please login.';
default:
return 'An unexpected Firebase error Occurred. Please try again';
}
}
}
|
import java.util.ArrayList;
import java.util.List;
public class The_liskov_substitution_principle {
// The Liskov Substitution Principle / Prinsip Substitusi Liskov
/*
* Substitusi adalah prinsip dalam pemrograman berorientasi objek yang
* diperkenalkan oleh Barbara Liskov pada konferensi tahun 1987
* keynote yang menyatakan bahwa, jika kelas B adalah subkelas dari kelas A,
* maka di mana pun A diharapkan, B dapat digunakan sebagai gantinya:
*/
/*
* class A {...}
* class B extends A {...}
* public void method(A obj) {...}
* A a = new B(); // Assignment OK
* method(new B()); // Passing as parameter OK
*/
/*
* Hal ini juga berlaku jika tipenya adalah antarmuka, yang tidak memerlukan
* hubungan hierarki antar objek:
* interface Foo {
* void bar();
* }
* class A implements Foo {
* void bar() {...}
* }
* class B implements Foo {
* void bar() {...}
* }
* List<Foo> foos = new ArrayList<>();
* foos.add(new A()); // OK
* foos.add(new B()); // OK
*/
// Sekarang daftar tersebut berisi objek yang tidak berasal dari hierarki kelas
// yang sama
public static void main(String[] args) {
// List<Foo> foos = new ArrayList<>();
// A a = new A();
// B b = new B();
// foos.add(a); // OK
// foos.add(b); // OK
// // Memanggil metode bar() dari setiap objek dalam List
// for (Foo foo : foos) {
// foo.bar();
// }
}
}
|
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ctmap/widgets/components/Button/Button.dart';
import 'package:ctmap/widgets/components/Button/TextButton.dart';
import 'package:ctmap/assets/colors/colors.dart';
import 'package:ctmap/assets/icons/icons.dart';
import 'package:ctmap/pages/screens/Profile/edit_profile.dart';
import 'package:ctmap/pages/screens/Authentication/forgot_password.dart';
import 'package:ctmap/state_management/user_state.dart';
class Profile extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header
Container(
color: AppColors.red,
height: 86,
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Tài Khoản',
style: TextStyle(fontSize: 28, color: AppColors.primaryWhite),
),
],
),
),
Container(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
CircleAvatar(
radius: 50,
// You can add image or avatar here
),
SizedBox(height: 10),
Text(
ref.watch(userStateProvider).userName,
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: AppColors.red,
),
),
Text(
ref.watch(userStateProvider).email,
style: TextStyle(
fontSize: 14,
color: AppColors.black,
),
),
],
),
),
// Body
Expanded(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomButton(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditProfile()),
);
},
btnText: 'Chỉnh sửa thông tin',
icon: AppIcons.edit,
btnColor: null, // Màu trong suốt
btnTextColor: AppColors.black, // Màu chữ
iconColor: AppColors.black.withOpacity(0.5),
borderRadius: 0,
fontSize: 16,
),
CustomButton(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ForgotPassword()),
);
},
btnText: 'Đổi mật khẩu',
icon: AppIcons.lock,
btnColor: null,
btnTextColor: AppColors.black,
iconColor: AppColors.black.withOpacity(0.5),
borderRadius: 0,
fontSize: 16,
),
CustomButton(
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Trợ giúp',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: AppColors.red)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Nếu có lỗi hoặc trục trặc kĩ thuật xin liên hệ CSKH.'),
SizedBox(height: 10),
Text('Email: 21521509@gmail.com'),
],
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Đóng',
style: TextStyle(color: AppColors.red),
),
),
],
);
},
);
},
btnText: 'Trợ giúp',
icon: AppIcons.help,
btnColor: null,
btnTextColor: AppColors.black,
iconColor: AppColors.black.withOpacity(0.5),
borderRadius: 0,
fontSize: 16,
),
],
),
),
SizedBox(height: 20),
Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: CustomButton(
onTap: () {
ref.read(userStateProvider.notifier).logOut();
Navigator.pushReplacementNamed(context, '/login');
},
btnText: 'Đăng xuất',
icon: AppIcons.logout,
btnColor: null,
btnTextColor: AppColors.black,
iconColor: AppColors.black.withOpacity(0.5),
borderRadius: 0,
fontSize: 16,
),
),
],
),
),
),
],
),
);
}
}
|
function solve() {
let form = document.querySelector(`form`);
let collectionOfSongs = document.querySelector(`.all-hits-container`)
let savedSongs = document.querySelector(`.saved-container`);
let likesParagraph = document.querySelector(`.likes p`)
form.addEventListener(`submit`,onSubmit);
function onSubmit(event){
event.preventDefault()
let genre = document.getElementById(`genre`).value;
let name = document.getElementById(`name`).value;
let author = document.getElementById(`author`).value;
let date = document.getElementById(`date`).value;
let data = {
genre,
name,
author,
date
}
let div = document.createElement(`div`);
if(Object.values(data).some(v=>v===``)){
return;
}
div.classList.add(`hits-info`)
div.innerHTML=`
<img src="./static/img/img.png">
<h2>Genre: ${data.genre}</h2>
<h2>Name: ${data.name}</h2>
<h2>Author: ${data.author}</h2>
<h3>Date: ${data.date}</h3>
<button class="save-btn">Save song</button>
<button class="like-btn">Like song</button>
<button class="delete-btn">Delete</button>
`
let saveBtn = div.querySelector(`.save-btn`);
let likeBtn = div.querySelector(`.like-btn`);
let deleteBtn = div.querySelector(`.delete-btn`);
saveBtn.addEventListener(`click`,onSave);
likeBtn.addEventListener(`click`,onLike);
deleteBtn.addEventListener(`click`,onDelete);
collectionOfSongs.appendChild(div);
function onSave(event){
let parent = event.target.parentElement;
let div = document.createElement(`div`);
div.classList.add(`hits-info`)
div.innerHTML=`
<img src="./static/img/img.png">
<h2>Genre: ${data.genre}</h2>
<h2>Name: ${data.name}</h2>
<h2>Author: ${data.author}</h2>
<h3>Date: ${data.date}</h3>
<button class="delete-btn">Delete</button>
`
let deleteBtn = div.querySelector(`.delete-btn`);
deleteBtn.addEventListener(`click`,onDelete);
parent.remove();
savedSongs.appendChild(div);
}
function onLike(event){
let likes = Number(likesParagraph.textContent.split(` `)[2]);
likesParagraph.textContent = `Total Likes: ${likes+1}`
event.target.disabled =`true`
}
function onDelete(event){
let parent = event.target.parentElement;
parent.remove();
}
form.reset();
}
}
|
%Function which creates a single gabor patch (orientation in deg)
function gaborPatch = createSingleGabor(orientation, gaborWidth)
%Defining useful variable
gaborWidth = gaborWidth - 1;
standDev = 10;
frequency = 0.03; %cycles per pixel
phase = 0;
%Convert units
angle = orientation*(pi/180);
radPerPixel = frequency*2*pi;
%Creating a mesh grid to create the gabor patch
widthArray = (-gaborWidth/2):(gaborWidth/2);
[X, Y] = meshgrid(widthArray, widthArray);
%Creating ramp function and gaussian blur
rampFunction = sin(angle)*X + cos(angle)*Y;
gaussianBlur = exp(-((X/standDev).^2)-((Y/standDev).^2));
%Create the Gabor Patch
Grating = sin(radPerPixel*rampFunction - phase);
Gabor = Grating.*gaussianBlur;
%Creating image from Gaussian Patch
gaborPatch = uint8(Gabor*255 + 128);
%Show the patch (optional)
%figure;
%imshow(gaborPatch);
%title(["Orientation: ", num2str(orientation)])
end
|
classdef joystick < handle
% JOYSTICK Create a Joystick object.
%
% myjoystick = joystick(obj) creates a joystick object.
% Copyright 2016-2018 The MathWorks, Inc.
properties (Constant)
Name = 'Raspberry Pi Sense HAT Joystick';
end
properties(Hidden,Access = private)
Map = containers.Map();
Initialized = false;
Opened = false;
Hw
evDevAddress
end
properties (Constant,Access = private)
%JOYSTICK REQUESTS
REQUEST_JOYSTICK_INIT = 7001;
REQUEST_JOYSTICK_READ = 7002;
AvailableButton = {'up','down','left','right','center'};
end
methods
function obj = joystick(hw)
validateattributes(hw,{'raspi.internal.raspiOnline','raspi.internal.raspiDesktop'},{'nonempty'},'','hardware')
obj.Hw = hw;
if isUsed(obj, obj.Name)
error(message('raspi:utils:SenseHATInUse','joystick'));
end
joystickInit(obj);
markUsed(obj,obj.Name);
obj.Initialized = true;
end
%Joystick read
function buttonpress = readJoystick(obj,varargin)
% buttonpress = readJoystick(obj) reads the state of
% the joystick. readJoystick returns a value between 0 and 5
% depending on the state of the joystick.
% Possible states of the joystick are:
% * 0 - joystick not pressed.
% * 1 - center
% * 2 - left
% * 3 - up
% * 4 - right
% * 5 - down
%
% buttonpress = readJoystick(sensehatObj, buttonPosition)
% reads whether the specified buttonposition on the joystick is
% being pressed, and returns the status as a logical value.
% * 0 - not pressed
% * 1 - pressed
narginchk(1,2);
sendRequest(obj.Hw,obj.REQUEST_JOYSTICK_READ,obj.evDevAddress);
buttonpress = recvResponse(obj.Hw);
if nargin > 1
option = validatestring(varargin{1},obj.AvailableButton);
switch option
case 'center'
buttonpress = (buttonpress == 1);
case 'left'
buttonpress = (buttonpress == 2);
case 'up'
buttonpress = (buttonpress == 3);
case 'right'
buttonpress = (buttonpress == 4);
case 'down'
buttonpress = (buttonpress == 5);
end
end
end
end
methods (Access = protected)
function joystickInit(obj)
obj.Hw.sendRequest(obj.REQUEST_JOYSTICK_INIT);
evDevName = char(recvResponse(obj.Hw));
evDevName = strrep(evDevName,'/sys/class/input/','/dev/input/');
evDevName = strrep(evDevName,'/device/name',char(0));
obj.evDevAddress = evDevName;
end
function ret = isUsed(obj, name)
if isKey(obj.Map, obj.Hw.DeviceAddress) && ...
ismember(name, obj.Map(obj.Hw.DeviceAddress))
ret = true;
else
ret = false;
end
end
function markUsed(obj, name)
if isKey(obj.Map, obj.Hw.DeviceAddress)
used = obj.Map(obj.Hw.DeviceAddress);
obj.Map(obj.Hw.DeviceAddress) = union(used, name);
else
obj.Map(obj.Hw.DeviceAddress) = {name};
end
end
function markUnused(obj, name)
if isKey(obj.Map, obj.Hw.DeviceAddress)
used = obj.Map(obj.Hw.DeviceAddress);
obj.Map(obj.Hw.DeviceAddress) = setdiff(used, name);
end
end
end
methods
function delete(obj)
if obj.Initialized
obj.markUnused(obj.Name)
end
end
end
end
|
//
// SetupMode.swift
// MCPS-iOS
//
// Created by Yuta on 2023/11/25.
//
import Foundation
import SwiftUI
import RealmSwift
struct CPSetupModeView: View {
@ObservedObject var viewModel = CPSetupLogViewModel()
@ObservedObject private var m5 = M5ViewController()
init() {
m5.initializeCBCentralManager()
print("initialized")
}
var body: some View {
VStack {
Spacer()
Text("設営モード")
.bold()
List {
Section(header: Text("設置済み")) {
HStack {
Text("ID").bold()
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
Text("場所").bold()
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
Text("設置時刻").bold()
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
}
ForEach(viewModel.setupLogs, id: \.id) { setupLog in
if setupLog.isSet == true{
HStack {
Text(setupLog.id)
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
Text("(xxx, yyy, zzz)")
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
Text(setupLog.eventTime.description)
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
}
}
Text("あなたは今(xxx, yyy, zzz)にいます。\nここに設置しますか?")
.multilineTextAlignment(.center)
List {
Section(header: Text("未設置")) {
HStack {
Text("ID").bold()
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
Text("").bold()
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
}
// 各Personオブジェクトに対して、行を構築します。
ForEach(viewModel.setupLogs, id: \.id) { setupLog in
if setupLog.isSet == false{
HStack {
Text(setupLog.id)
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
Button(action: {
print(viewModel.setupLogs)
print("button tapped.")
// setupLog.isSet = true
print(viewModel.setupLogs)
let jsonText = "{type: 'SETUP', typeNo: '1.0', latitude: '1.1111', longitude: '2.2222', altitude: '3.3333'}"
_ = m5.sendString(sendText: jsonText)
}){
Text("設置する")
}
.buttonStyle(BlueRoundButtonStyle())
}
}
}
}
}
}
}
}
class CPSetupLogViewModel: ObservableObject {
@Published var setupLogs: [CPSetupLog]
init() {
setupLogs = []
let log1 = CPSetupLog(id: "aaa", isSet: true, location: CPLocation(), eventTime: Date())
let log2 = CPSetupLog(id: "bbb", isSet: false, location: CPLocation(), eventTime: Date())
let log3 = CPSetupLog(id: "ccc", isSet: false, location: CPLocation(), eventTime: Date())
setupLogs.append(log1)
setupLogs.append(log2)
setupLogs.append(log3)
}
}
|
/*Задача 1
Объекты позволяют описать и сгруппировать характеристики объектов реального мира -
пользователя, книги, продукта магазина, чего угодно. Объекты ещё называют
словарями, то есть они содержат термины (свойства) и их определения (значения).
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
public: true,
rating: 8.38,
};
Для объявления используются фигурные скобки {} - литерал объекта. При создании
объекту можно добавить свойства, каждое из которых описывается парами ключ:значение.
Ключ ещё называют именем свойства и это всегда строка. Значением свойства могут
быть любые типы: примитивы, массивы, объекты, були, функции и т. п. Свойства
разделяются запятой.
Присвой переменной apartment объект описывающий квартиру со следующими
характеристиками:
imgUrl - фотография, значение "https://via.placeholder.com/640x480";
descr - описание, значение "Spacious apartment in the city center";
rating - рейтинг, значение 4;
price - цена, значение 2153;
tags - метаинформация, массив ["premium", "promoted", "top"].*/
// const apartment = {
// imgUrl: "https://via.placeholder.com/640x480",
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// tags: ["premium", "promoted", "top"],
// };
/*Задача 2
Значением свойства может быть другой объект. Это используется для хранения
вложенных и группированных данных.
Например, статистика пользователя социальной сети состоит из количества
последователей, просмотров и лайков, и хранить эти данные удобнее всего в
виде объекта. Тоже самое с местоположением, отдельно страна и город.
В будущем это можно будет использовать для поиска пользователей по стране,
городу, минимальному или максимальному количеству последователей и т. д.
const user = {
name: "Jacques Gluke",
tag: "jgluke",
location: {
country: "Jamaica",
city: "Ocho Rios",
},
stats: {
followers: 5603,
views: 4827,
likes: 1308,
},
};
Дополни объект квартиры свойством owner, значением которого будет объект с
информацией о владельце. Добавь ему следующие свойства:
name - имя владельца, значение "Henry";
phone - телефон, значение "982-126-1588";
email - почта, значение "henry.carter@aptmail.com".
Объявлена переменная apartment
Значение переменной apartment это объект
У объекта переменной apartment присутствуют свойства imgUrl, descr, rating,
price и tag со значениями
В объекте apartment есть свойство owner
Значение свойства owner это объект
В объекте owner есть свойство name
Значение свойства name это "Henry"
В объекте owner есть свойство phone
Значение свойства phone это "982-126-1588"
В объекте owner есть свойствао email
Значение свойства email это "henry.carter@aptmail.com"*/
// const apartment = {
// imgUrl: "https://via.placeholder.com/640x480",
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// tags: ["premium", "promoted", "top"],
// owner: {
// name: "Henry",
// phone: "982-126-1588",
// email: "henry.carter@aptmail.com",
// }
// };
/*Задача 3
Первый способ получить доступ к свойству объекта это синтаксис
обьект.ключ_свойства. Синтаксис «через точку» используется в большинстве
случаев и подходит тогда, когда мы заранее знаем имя (ключ) свойства
к которому хотим получить доступ.
На место обращения будет возвращено значение свойства с таким именем.
Если в объекте нет свойства с таким именем, на место обращения вернётся undefined.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
public: true,
rating: 8.38,
};
const bookTitle = book.title;
console.log(bookTitle); // "The Last Kingdom"
const bookGenres = book.genres;
console.log(bookGenres); // ["historical prose", "adventure"]
const bookPrice = book.price;
console.log(bookPrice); // undefined
Дополни код присвоив объявленным переменным выражения обращения к соответствующим
свойствам обьекта apartment.
aptRating - рейтинг;
aptDescr - описание;
aptPrice - цена;
aptTags - теги.*/
// const apartment = {
// imgUrl: "https://via.placeholder.com/640x480",
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// tags: ["premium", "promoted", "top"],
// };
// const apartmentRating = apartment.rating;
// console.log(apartmentRating);
// const apartmentDescr = apartment.descr;
// console.log(apartmentDescr);
// const apartmentPrice = apartment.price;
// console.log(apartmentPrice);
// const apartmentTags = apartment.tags;
// console.log(apartmentTags);
/*Задача 4
const user = {
name: "Jacques Gluke",
tag: "jgluke",
location: {
country: "Jamaica",
city: "Ocho Rios",
},
hobbies: ["swiming", "music", "sci-fi"],
};
Для доступа к вложенным свойствам используется цепочка обращений «через точку». Например,
если необходимо получить значение страны пользователя, записываем user.location.country,
где user.location это обращение (путь) к объекту в свойстве location, а user.locaton.
country обращение к свойству country в этом объекте. То есть, «точка» указывает следующую
вложенность.
const location = user.location;
console.log(location); // Объект location
const country = user.location.country;
console.log(country); // "Jamaica"
Если значение свойства это массив, то в нашем примере user.hobbies - обращение к этому
массиву. Далее, можно получить доступ к его элементам через квадратные скобки и индекс
или использовать свойства и методы.
const hobbies = user.hobbies;
console.log(hobbies); // ["swiming", "music", "sci-fi"]
const firstHobby = user.hobbies[0];
console.log(firstHobby); // "swiming"
const numberOfHobbies = user.hobbies.length;
console.log(numberOfHobbies); // 3
Дополни код присвоив объявленным переменным выражения обращения к соответствующим
свойствам обьекта apartment.
ownerName - имя владельца;
ownerPhone - телефон владельца;
ownerEmail - почта владельца;
numberOfTags - количество элементов массива в свойстве tags;
firstTag - первый элемент массива в свойстве tags;
lastTag - последний элемент массива в свойстве tags.
Объявлена переменная apartment с помощью const
Значение переменной apartment это объект
Объявлена переменная ownerName с помощью const
Значение переменной ownerName это строка "Henry"
Объявлена переменная ownerPhone с помощью const
Значение переменной ownerPhone это "982-126-1588"
Объявлена переменная ownerEmail с помощью const
Значение переменной ownerEmail это "henry.carter@aptmail.com"
Объявлена переменная numberOfTags с помощью const
Значение переменной numberOfTags это 3
Объявлена переменная firstTag с помощью const
Значение переменной firstTag это "premium"
Объявлена переменная lastTag с помощью const
Значение переменной lastTag это "top"*/
// const apartment = {
// imgUrl: "https://via.placeholder.com/640x480",
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// tags: ["premium", "promoted", "top"],
// owner: {
// name: "Henry",
// phone: "982-126-1588",
// email: "henry.carter@aptmail.com",
// },
// };
// const ownerName = apartment.owner.name;
// console.log(ownerName);
// const ownerPhone = apartment.owner.phone;
// console.log(ownerPhone);
// const ownerEmail = apartment.owner.email;
// console.log(ownerEmail);
// const numberOfTags = apartment.tags.length;
// console.log(numberOfTags);
// const firstTag = apartment.tags[0];
// console.log(firstTag);
// const lastTag = apartment.tags[2];
// console.log(lastTag);
/*Задача 5
Второй способ получить доступ к свойству объекта это синтаксис обьект["ключ_свойства"].
Похоже на обращение к элементу массива с отличием в том, что в скобках указывается не
индекс элемента, а имя свойства как строка.
Синтаксис «квадратных скобок» используется значительно реже. Как правило в случаях когда
имя свойства заранее неизвестно или оно хранится в переменной (как значение параметра
функции, например).
На место обращения будет возвращено значение свойства с таким именем.
Если в объекте нет свойства с таким именем, на место обращения вернётся undefined.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
public: true,
rating: 8.38,
};
const bookTitle = book["title"];
console.log(bookTitle); // "The Last Kingdom"
const bookGenres = book["genres"];
console.log(bookGenres); // ["historical prose", "adventure"]
const propKey = "author";
const bookAuthor = book[propKey];
console.log(bookAuthor); // "Bernard Cornwell"
Дополни код присвоив объявленным переменным выражения обращения к соответствующим
свойствам
обьекта apartment используя синтаксис «квадратных скобок».
aptRating - рейтинг;
aptDescr - описание;
aptPrice - цена;
aptTags - теги.*/
// const apartment = {
// imgUrl: "https://via.placeholder.com/640x480",
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// tags: ["premium", "promoted", "top"],
// };
// const aptRating = apartment["rating"];
// console.log(aptRating);
// const aptDescr = apartment["descr"];
// console.log(aptDescr);
// const aptPrice = apartment["price"];
// console.log(aptPrice);
// const aptTags = apartment["tags"];
// console.log(aptTags);
/*Задача 6
После того, как объект создан, значение его свойств можно изменить. Для этого
необходимо обратиться к ним по имени, например, «через точку», и присвоить новое
значение.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
public: true,
rating: 8.38,
};
book.rating = 9;
book.public = false;
book.genres.push("drama");
console.log(book.rating); // 9
console.log(book.public); // false
console.log(book.genres); // ["historical prose", "adventure", "drama"]
Дополни код обновив значения свойств объекта apartment:
цену в свойстве price на 5000;
рейтинг квартиры в свойстве rating на 4.7;
имя владельца во вложенном свойстве name на "Henry Sibola";
массив тегов в свойстве tags добавив в конец строку "trusted".*/
// const apartment = {
// imgUrl: "https://via.placeholder.com/640x480",
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// tags: ["premium", "promoted", "top"],
// owner: {
// name: "Henry",
// phone: "982-126-1588",
// email: "henry.carter@aptmail.com",
// },
// };
// apartment.price = 5000;
// console.log(apartment.price);
// apartment.rating = 4.7;
// console.log(apartment.rating);
// apartment.owner.name = "Henry Sibola";
// console.log(apartment.owner.name);
// apartment.tags.push("trusted");
// console.log(apartment.tags);
/*Задача 7
Операция добавления нового свойства после создания объекта ничем не отличается от
изменения значения уже существующего свойства. Если при записи значения по имени,
такого свойства в объекте нет, оно будет создано.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
public: true,
rating: 8.38,
};
book.pageCount = 836;
book.originalLanguage = "en";
book.translations = ["ua", "ru"];
console.log(book.pageCount); // 836
console.log(book.originalLanguage); // "en"
console.log(book.translations); // ["ua", "ru"]
Добавь объекту apartment несколько новых свойств:
area - площадь в квадратных метрах, число 60;
rooms - количество комнат, число 3;
location - местоположение квартиры, обьект со следующими вложенными свойствами;
country - страна, строка "Jamaica";
city - город, строка "Kingston".*/
// const apartment = {
// imgUrl: "https://via.placeholder.com/640x480",
// descr: "Spacious apartment in the city center",
// rating: 4.7,
// price: 5000,
// tags: ["premium", "promoted", "top", "trusted"],
// owner: {
// name: "Henry Sibola",
// phone: "982-126-1588",
// email: "henry.carter@aptmail.com",
// },
// };
// apartment.area = 60;
// console.log(apartment.area);
// apartment.rooms = 3;
// console.log(apartment.rooms);
// apartment.location = { country: "Jamaica", city: "Kingston" };
// console.log(apartment.location);
/*Задача 8
Иногда, при создании объекта, значение свойства необходимо взять из переменной или
параметра функции с таким же именем, как и само свойство.
Синтаксис в следующем примере слишком громоздкий, потому что приходится дублировать
имя свойства и имя переменной, в которой хранится необходимое значение.
const name = "Генри Сибола";
const age = 25;
const user = {
name: name,
age: age,
};
console.log(user.name); // "Генри Сибола"
console.log(user.age); // 25
Синтаксис коротких свойств (shorthand properties) решает эту проблему, позволяя
использовать имя переменной как имя свойства, а её значение как значение свойства.
const name = "Генри Сибола";
const age = 25;
const user = {
name,
age,
};
console.log(user.name); // "Генри Сибола"
console.log(user.age); // 25
То есть, при объявлении объекта достаточно указать только имя свойства, а значение
будет взято из переменной с аналогичным именем.
Дополни код объявления объекта так, чтобы у него были свойства name, price, image и
tags со значениями из переменных с аналогичными именами. Обязательно используй синтаксис
коротких свойств.*/
// const name = "Repair Droid";
// const price = 2500;
// const image = "https://via.placeholder.com/640x480";
// const tags = ["on sale", "trending", "best buy"];
// const product = {
// name,
// price,
// image,
// tags,
// };
// console.log(product.name);
// console.log(product.price);
// console.log(product.image);
// console.log(product.tags);
/*Задача 9
Бывают ситуации, когда при объявлении обьекта необходимо добавить свойство с
именем, которое мы заранее не знаем, потому что оно хранится как значение
переменной или как результат выполнения функции.
Раньше для этого необходимо было сначала создать объект, а потом добавлять
свойства через квадратные скобки, что не совсем удобно.
const propName = "name";
const user = {
age: 25
};
user[propName] = "Генри Сибола";
console.log(user.name); // "Генри Сибола"
Синтаксис вычисляемых свойств (computed properties) помогает избежать лишнего кода
и в некоторых случаях упростить его. Значением вычисляемого свойства может быть любое
валидное выражение.
const propName = "name";
const user = {
age: 25,
// Имя этого свойства будет взято из значения переменной propName
[propName]: "Генри Сибола"
};
console.log(user.name); // "Генри Сибола"
Дополни код объявления объекта credentials так, чтобы в результате у него были
два свойства: email и password, имена которых хранятся в переменных emailInputName
и passwordInputName.
Значением свойства email должна быть строка "henry.carter@aptmail.com", а значением
свойства password - строка "jqueryismyjam".*/
// const emailInputName = "email";
// const passwordInputName = "password";
// const credentials = {
// [emailInputName]: "henry.carter@aptmail.com",
// [passwordInputName]: "jqueryismyjam",
// };
// console.log(credentials.email);
// console.log(credentials.password);
/*Задача 10
ЦИКЛ FOR...IN
В отличии от массива или строки, объект - это не итерируемая сущность, то есть его
нельзя перебрать циклами for или for...of. Для перебора объектов используется
специальный цикл for...in, который перебирает ключи объекта object.
for (key in object) {
// инструкции
}
Переменная key доступная только в теле цикла. На каждой итерации в неё будет
записано значение ключа (имя) свойства. Для того чтобы получить значение свойства
с таким ключом (именем), используется синтаксис квадратных скобок.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
rating: 8.38,
};
for (const key in book) {
// Ключ
console.log(key);
// Значение свойства с таким ключом
console.log(book[key]);
}
Перебери объект apartment используя цикл for...in и запиши в массив keys все его ключи,
а в массив values все значения его свойств.
Объявлена переменная apartment
Значение переменной apartment это объект
Объявлена переменная keys
Значение переменной keys это массив ["descr", "rating", "price"]
Объявлена переменная values
Значение переменной values это массив ["Spacious apartment in the city center", 4, 2153]*/
// const apartment = {
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// };
// const keys = [];
// const values = [];
// for (const key in apartment) {
// keys.push(key);
// values.push(apartment[key]);
// }
// console.log(keys);
// console.log(values);
/*Задача 11
Разберём концепцию собственных и несобственных свойств объекта и научимся правильно
использовать цикл for...in.
const animal = {
legs: 4,
};
const dog = Object.create(animal);
dog.name = "Mango";
console.log(dog); // {name: 'Mango'}
console.log(dog.name); // 'Mango'
console.log(dog.legs); // 4
Метод Object.create(animal) создаёт и возвращает новый объект, связывая его с объектом
animal. Поэтому можно получить значение свойства legs обратившись к нему как dog.legs,
хотя его нет в объекте dog - это несобственное свойство из объекта animal.
Оператор in, который используется в цикле for...in, не делает различия между
собственными и несобственными свойствами объекта. Эта особенность мешает, так как мы
всегда хотим перебрать только собственные свойства. Для того чтобы узнать есть в
объекте собственное свойство или нет, используется метод hasOwnProperty(key), который
возвращает true или false.
// ❌ Возвращает true для всех свойств
console.log("name" in dog); // true
console.log("legs" in dog); // true
// ✅ Возвращает true только для собственных свойств
console.log(dog.hasOwnProperty("name")); // true
console.log(dog.hasOwnProperty("legs")); // false
Поэтому при переборе циклом for...in необходимо на каждой итерации добавить проверку на
собственное свойство. Даже если сейчас мы уверены в том что у объекта нет несобственных
свойств, это оградит от возможных ошибок в будущем.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
rating: 8.38,
};
for (const key in book) {
// Если это собственное свойство - выполняем тело if
if (book.hasOwnProperty(key)) {
console.log(key);
console.log(book[key]);
}
// Если это не собственное свойство - ничего не делаем
}
Выполни рефакторинг решения предыдущего задания добавив в цикл for...in проверку на
собственное свойство.*/
// const keys = [];
// const values = [];
// const advert = {
// service: "apt",
// };
// const apartment = Object.create(advert);
// apartment.descr = "Spacious apartment in the city center";
// apartment.rating = 4;
// apartment.price = 2153;
// for (const key in apartment) {
// if (apartment.hasOwnProperty(key)) {
// keys.push(key);
// values.push(apartment[key]);
// }
// }
// console.log(keys);
// console.log(values);
/*Задача 12
ЗАДАЧА. ПОДСЧЁТ СВОЙСТВ
Напиши функцию countProps(object), которая считает и возвращает
количество собственных свойств объекта в параметре object.
Используй переменную propCount для хранения количества свойств
объекта.
Объявлена функция countProps(object)
Вызов countProps({}) возвращает 0
Вызов countProps({ name: "Mango", age: 2 }) возвращает 2
Вызов countProps({ mail: "poly@mail.com", isOnline: true,
score: 500 }) возвращает 3
Функция подсчитывает только собственные свойства объекта*/
// function countProps(object) {
// let propCount = 0;
// for (const count in object) {
// if (object.hasOwnProperty(count)) {
// propCount += 1;
// }
// }
// console.log(propCount);
// return propCount;
// }
// countProps({});
// countProps({ name: "Mango", age: 2 });
// countProps({ mail: "poly@mail.com", isOnline: true, score: 500 });
/*Задача 13
МЕТОД OBJECT.KEYS()
У встроенного класса Object есть несколько полезных методов для
работы с объектами. Первый из них это Object.keys(obj),
который принимает объект и возвращает массив ключей его
собственных свойств. Если в объекте нет свойств, метод вернёт
пустой массив.
const book = {
title: "The Last Kingdom",
genres: ["historical prose", "adventure"],
rating: 8.38,
};
const keys = Object.keys(book);
console.log(keys); // ['title', 'author', 'genres', 'rating']
Скомбинировав результат Object.keys() и цикл for...of можно удобно
перебрать собственные свойства объекта, не прибегая к использованию
архаического цикла for...in с проверками принадлежности свойств.
const book = {
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
rating: 8.38,
};
const keys = Object.keys(book);
for (const key of keys) {
// Ключ
console.log(key);
// Значение свойства
console.log(book[key]);
}
Мы перебираем массив ключей объекта и на каждой итерации получаем
значение свойства с таким ключом.
Перебери объект apartment используя метод Object.keys() и цикл for...of. Запиши в переменную keys массив ключей собственных свойств объекта apartment, и добавь в массив values все значения его свойств.*/
// const apartment = {
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// };
// const values = [];
// // Change code below this line
// const keys = Object.keys(apartment);
// console.log(keys);
// for (const key of keys) {
// values.push(apartment[key]);
// }
// console.log(values);
/*Задача 14*/
// function countProps(object) {
// const keys = Object.keys(object);
// console.log(keys.length);
// return keys.length
// }
// countProps({});
// countProps({ name: "Mango", age: 2 });
// countProps({ mail: "poly@mail.com", isOnline: true, score: 500 });
/*Задача 15*/
// const apartment = {
// descr: "Spacious apartment in the city center",
// rating: 4,
// price: 2153,
// };
// const keys = Object.keys(apartment);
// console.log(keys);
// const values = Object.values(apartment);
// console.log(values);
/*Задача 16*/
// function countTotalSalary(salaries) {
// let totalSalary = 0;
// const keys = Object.values(salaries);
// for ( const key of keys) {
// totalSalary += key;
// }
// console.log(totalSalary);
// return totalSalary;
// }
// countTotalSalary({});
// countTotalSalary({ mango: 100, poly: 150, alfred: 80 });
// countTotalSalary({ kiwi: 200, poly: 50, ajax: 150 });
/*Задача 17*/
// const colors = [
// { hex: "#f44336", rgb: "244,67,54" },
// { hex: "#2196f3", rgb: "33,150,243" },
// { hex: "#4caf50", rgb: "76,175,80" },
// { hex: "#ffeb3b", rgb: "255,235,59" },
// ];
// const hexColors = [];
// const rgbColors = [];
// for (const color of colors) {
// hexColors.push(color.hex);
// rgbColors.push(color.rgb)
// }
// console.log(hexColors);
// console.log(rgbColors);
/*Задача 18*/
// const products = [
// { name: "Radar", price: 1300, quantity: 4 },
// { name: "Scanner", price: 2700, quantity: 3 },
// { name: "Droid", price: 400, quantity: 7 },
// { name: "Grip", price: 1200, quantity: 9 },
// ];
// function getProductPrice(productName) {
// for (const product of products) {
// if (productName === product.name) {
// console.log(product.price);
// return product.price;
// }
// }
// console.log(null);
// return null;
// }
// getProductPrice("Radar");
// getProductPrice("Grip");
// getProductPrice("Scanner");
// getProductPrice("Droid");
// getProductPrice("Engine");
/*Задача 19*/
// const products = [
// { name: "Radar", price: 1300, quantity: 4 },
// { name: "Scanner", price: 2700, quantity: 3 },
// { name: "Droid", price: 400, quantity: 7 },
// { name: "Grip", price: 1200, quantity: 9 },
// ];
// function getAllPropValues(propName) {
// let value = [];
// for (const product of products) {
// if (product.hasOwnProperty(propName)) {
// value.push(product[propName]);
// }
// }
// console.log(value);
// return value;
// }
// getAllPropValues("name");
// getAllPropValues("quantity");
// getAllPropValues("price");
// getAllPropValues("category");
/*Задача 20*/
// const products = [
// { name: "Radar", price: 1300, quantity: 4 },
// { name: "Scanner", price: 2700, quantity: 3 },
// { name: "Droid", price: 400, quantity: 7 },
// { name: "Grip", price: 1200, quantity: 9 },
// ];
// function calculateTotalPrice(productName) {
// let totalPrice = 0;
// for ( const product of products) {
// if (productName === product.name) {
// totalPrice = product.price * product.quantity;
// }
// }
// console.log(totalPrice)
// return totalPrice;
// }
// calculateTotalPrice("Blaster");
// calculateTotalPrice("Radar");
// calculateTotalPrice("Droid");
// calculateTotalPrice("Grip");
// calculateTotalPrice("Scanner");
/*Задача 21*/
// const highTemperatures = {
// yesterday: 28,
// today: 26,
// tomorrow: 33,
// };
// const {yesterday, today, tomorrow} = highTemperatures;
// const meanTemperature = (yesterday + today + tomorrow) / 3;
// console.log(meanTemperature);
/*Задача 22
Для того чтобы избежать присвоения undefined при деструктуризации
несуществующих свойств, можно задать переменным значения по умолчанию,
которые будут присвоены только в случае когда в объекте нет свойства с
таким именем.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
};
// Добавим картинку обложки если её нет в объекте книги
const {
title,
coverImage = "https://via.placeholder.com/640/480",
author,
} = book;
console.log(title); // "The Last Kingdom"
console.log(author); // "Bernard Cornwell"
console.log(coverImage); // "https://via.placeholder.com/640/480"
В прогнозе максимальных температур также может быть необязательное
свойство icon - иконка погоды. Замени объявления переменных yesterday,
today, tomorrow и icon одной операцией деструктуризации свойств объекта
highTemperatures. Задай значение по умолчанию для icon - строку
"https://www.flaticon.com/svg/static/icons/svg/2204/2204346.svg".*/
// const highTemperatures = {
// yesterday: 28,
// today: 26,
// tomorrow: 33,
// };
// const {
// yesterday,
// today,
// tomorrow,
// icon = "https://www.flaticon.com/svg/static/icons/svg/2204/2204346.svg",
// } = highTemperatures;
// const meanTemperature = (yesterday + today + tomorrow) / 3;
// console.log(yesterday);
// console.log(today);
// console.log(tomorrow);
// console.log(icon);
/*Задача 23
При деструктуризации можно изменить имя переменной в которую
распаковывается значение свойства. Сначала пишем имя свойства из
которого хотим получить значение, после чего ставим двоеточие и пишем
имя переменной в которую необходимо поместить значение этого свойства.
const firstBook = {
title: "Последнее королевство",
coverImage:
"https://images-na.ssl-images-amazon.com/images/I/51b5YG6Y1rL.jpg",
};
const {
title: firstTitle,
coverImage: firstCoverImage = "https://via.placeholder.com/640/480",
} = firstBook;
console.log(firstTitle); // Последнее королевство
console.log(firstCoverImage); // https://images-na.ssl-images-amazon.com/images/I/51b5YG6Y1rL.jpg
const secondBook = {
title: "Сон смешного человека",
};
const {
title: secondTitle,
coverImage: secondCoverImage = "https://via.placeholder.com/640/480",
} = secondBook;
console.log(secondTitle); // Сон смешного человека
console.log(secondCoverImage); // https://via.placeholder.com/640/480
Такая запись читается как «Создать переменную firstTitle, в которую
поместить значение свойства title из объекта firstBook» и т. д.
Замени объявления переменных highYesterday, highToday, highTomorrow и
highIcon одной операцией деструктуризации свойств объекта
highTemperatures. Задай значение по умолчанию для highIcon - строку
"https://www.flaticon.com/svg/static/icons/svg/2204/2204346.svg".*/
// const highTemperatures = {
// yesterday: 28,
// today: 26,
// tomorrow: 33,
// };
// const {
// yesterday: highYesterday,
// today: highToday,
// tomorrow: highTomorrow,
// icon :highIcon = "https://www.flaticon.com/svg/static/icons/svg/2204/2204346.svg",
// } = highTemperatures;
// const meanTemperature = (highYesterday + highToday + highTomorrow) / 3;
// console.log(highYesterday);
// console.log(highToday);
// console.log(highTomorrow);
// console.log(highIcon);
/*Задача 24
ДЕСТРУКТУРИЗАЦИЯ В ЦИКЛАХ
При переборе массива объектов циклом for...of получаются множественные обращения к
свойствам объекта.
const books = [
{
title: "The Last Kingdom",
author: "Bernard Cornwell",
rating: 8.38,
},
{
title: "Beside Still Waters",
author: "Robert Sheckley",
rating: 8.51,
},
];
for (const book of books) {
console.log(book.title);
console.log(book.author);
console.log(book.rating);
}
Для того, чтобы сократить количество повторений, можно деструктуризировать свойства
объекта в локальные переменные в теле цикла.
for (const book of books) {
const { title, author, rating } = book;
console.log(title);
console.log(author);
console.log(rating);
}
Если в объекте немного свойств, деструктуризацию можно выполнить прямо в месте
объявления переменной book.
for (const { title, author, rating } of books) {
console.log(title);
console.log(author);
console.log(rating);
}
Выполни рефакторинг цикла for...of так, чтобы в нём использовалась деструктуризация
объекта..*/
// const colors = [
// { hex: "#f44336", rgb: "244,67,54" },
// { hex: "#2196f3", rgb: "33,150,243" },
// { hex: "#4caf50", rgb: "76,175,80" },
// { hex: "#ffeb3b", rgb: "255,235,59" },
// ];
// const hexColors = [];
// const rgbColors = [];
// for (const { hex, rgb } of colors) {
// hexColors.push(hex);
// rgbColors.push(rgb);
// }
// console.log(hexColors);
// console.log(rgbColors);
/*Задача 25*/
// const forecast = {
// today: {
// low: 28,
// high: 32,
// icon: "https://www.flaticon.com/svg/static/icons/svg/861/861059.svg",
// },
// tomorrow: {
// low: 27,
// high: 31,
// },
// };
// const {
// today:
// {low: lowToday,
// high: highToday,
// icon: todayIcon = "https://www.flaticon.com/svg/static/icons/svg/861/861059.svg"},
// tomorrow:
// {low: lowTomorrow,
// high: highTomorrow,
// icon: tomorrowIcon = "https://www.flaticon.com/svg/static/icons/svg/2204/2204346.svg"}} = forecast;
// console.log(lowToday);
// console.log(highToday);
// console.log(todayIcon);
// console.log(lowTomorrow);
// console.log(highTomorrow);
// console.log(tomorrowIcon);
/*Задача 26*/
// function calculateMeanTemperature(forecast) {
// const {
// today:
// {low: todayLow,
// high: todayHigh},
// tomorrow:
// {low: tomorrowLow,
// high: tomorrowHigh}} = forecast;
// console.log((todayLow + todayHigh + tomorrowLow + tomorrowHigh) / 4);
// return (todayLow + todayHigh + tomorrowLow + tomorrowHigh) / 4;
// }
// calculateMeanTemperature({
// today: { low: 28, high: 32 },
// tomorrow: { low: 25, high: 29 }
// });
// calculateMeanTemperature({
// today: { low: 37, high: 40 },
// tomorrow: { low: 33, high: 38 }
// });
/*Задача 27*/
// const scores = [89, 64, 42, 17, 93, 51, 26];
// const bestScore = (Math.max(...scores));
// const worstScore = (Math.min(...scores));
// console.log(bestScore);
// console.log(worstScore);
/*Задача 28*/
// const firstGroupScores = [64, 42, 93];
// const secondGroupScores = [89, 14, 51, 26];
// const thirdGroupScores = [29, 47, 18, 97, 81];
// // Change code below this line
// const allScores = [...firstGroupScores, ...secondGroupScores, ...thirdGroupScores];
// const bestScore = (Math.max(...allScores));
// const worstScore = (Math.min(...allScores));
// console.log(allScores);
// console.log(bestScore);
// console.log(worstScore);
/*Задача 29*/
// const defaultSettings = {
// theme: "light",
// public: true,
// withPassword: false,
// minNumberOfQuestions: 10,
// timePerQuestion: 60,
// };
// const overrideSettings = {
// public: false,
// withPassword: true,
// timePerQuestion: 30,
// };
// const finalSettings = { ...defaultSettings, ...overrideSettings };
// console.log(finalSettings);
/*Задача 30*/
// function makeTask(data) {
// const completed = false;
// const category = "General";
// const priority = "Normal";
// console.log({
// category: category,
// priority: priority,
// ...data,
// completed: completed,
// });
// return {
// category: category,
// priority: priority,
// ...data,
// completed: completed,
// };
// }
// makeTask({});
// makeTask({
// category: "Homemade", priority: "Low", text:
// "Take out the trash"
// });
// makeTask({ category: "Finance", text: "Take interest" });
// makeTask({ priority: "Low", text: "Choose shampoo" });
// makeTask({ text: "Buy bread" });
/*Задача 31*/
// function add(...args) {
// let sum = 0;
// for (let arg of args) {
// sum += arg
// };
// console.log(sum);
// return sum;
// }
// add(15, 27);
// add(12, 4, 11, 48);
// add(32, 6, 13, 19, 8);
// add(74, 11, 62, 46, 12, 36);
/*Задача 32*/
// function addOverNum(firstNumber, ...args) {
// let total = 0;
// for (const arg of args) {
// if(arg > firstNumber){ total += arg}
// }
// console.log(total);
// return total;
// }
// addOverNum(50, 15, 27);
// addOverNum(10, 12, 4, 11, 48, 10, 8);
// addOverNum(15, 32, 6, 13, 19, 8);
// addOverNum(20, 74, 11, 62, 46, 12, 36);
/*Задача 33*/
// function findMatches(numbers, ... args) {
// const matches = []; // Don't change this line
// for (const number of args)
// if (numbers.includes(number)) {
// matches.push(number);
// }
// console.log(matches);
// return matches;
// }
// findMatches([1, 2, 3, 4, 5], 1, 8, 2, 7);
// findMatches([4, 89, 17, 36, 2], 8, 17, 89, 27, 2);
// findMatches([10, 24, 41, 6, 9, 19], 24, 11, 9, 23, 41);
// findMatches([63, 11, 8, 29], 4, 7, 16);
/*Задача 34*/
// const bookShelf = {
// books: ["The last kingdom", "The guardian of dreams"],
// getBooks() {
// console.log("Returning all books");
// return "Returning all books";
// },
// addBook(bookName) {
// console.log(`Adding book ${bookName}`);
// return `Adding book ${bookName}`;
// },
// removeBook(bookName) {
// console.log(`Deleting book ${bookName}`);
// return `Deleting book ${bookName}`
// },
// updateBook(oldName, newName) {
// console.log(`Updating book ${oldName} to ${newName}`);
// return `Updating book ${oldName} to ${newName}`
// },
// }
// bookShelf.getBooks();
// bookShelf.addBook("Haze");
// bookShelf.removeBook("Red sunset");
/*Задача 35*/
// const bookShelf = {
// books: ["The last kingdom", "Haze", "The guardian of dreams"],
// updateBook(oldName, newName) {
// const bookIndex = this.books.indexOf(oldName)
// this.books.splice(bookIndex, 1, newName);
// },
// };
/*Задача 36*/
// const atTheOldToad = {
// potions: [],
// };
/*Задача 38*/
// const atTheOldToad = {
// potions: ["Speed potion", "Dragon breath", "Stone skin"],
// addPotion(potionName) {
// this.potions.push(potionName);
// },
// };
/*Задача 39*/
// const atTheOldToad = {
// potions: ["Speed potion", "Dragon breath", "Stone skin"],
// removePotion(potionName) {
// const potionIndex = this.potions.indexOf(potionName);
// this.potions.splice(potionIndex, 1)
// },
// };
/*Задача 40*/
// const atTheOldToad = {
// potions: ["Speed potion", "Dragon breath", "Stone skin"],
// updatePotionName(oldName, newName) {
// const toadIndex = this.potions.indexOf(oldName)
// this.potions.splice(toadIndex, 1, newName);
// },
// };
/*Задача 41*/
// const atTheOldToad = {
// potions: [
// { name: "Speed potion", price: 460 },
// { name: "Dragon breath", price: 780 },
// { name: "Stone skin", price: 520 },
// ],
// // Change code below this line
// getPotions() {
// return this.potions;
// },
// addPotion(newPotion) {
// for (const potion of this.potions) {
// if (potion.name === newPotion.name) {
// return `Error! Potion ${newPotion.name} is already in your inventory!`;
// }
// }
// this.potions.push(newPotion);
// },
// removePotion(potionName) {
// for (const potion of this.potions) {
// if (potion.name === potionName) {
// const potionIndex = this.potions.indexOf(potion);
// if (potionIndex === -1) {
// return `Potion ${potionName} is not in inventory!`;
// }
// this.potions.splice(potionIndex, 1);
// }
// }
// },
// updatePotionName(oldName, newName) {
// for (const potion of this.potions) {
// if (potion.name === oldName) {
// potion.name = newName;
// }
// }
// },
// };
// Отримати дані з API і вивести їх на сторінку
//https://reqres.in/
// fetch('https://reqres.in/api/users/2', {
// method: 'PUT',
// body: JSON.stringify(
// {
// "name": "morpheus",
// "job": "zion resident"
// }
// )
// })
// .then(response => response.json())
// .then(response => console.log(response));
|
package com.adammcneilly.pocketleague.data.event.impl
import com.adammcneilly.pocketleague.core.models.Event
import com.adammcneilly.pocketleague.data.event.api.EventListRequest
import com.adammcneilly.pocketleague.data.event.api.LocalEventService
import com.adammcneilly.pocketleague.data.local.sqldelight.PocketLeagueDB
import com.adammcneilly.pocketleague.data.local.sqldelight.mappers.toEvents
import com.adammcneilly.pocketleague.data.local.sqldelight.mappers.toLocalEvent
import com.adammcneilly.pocketleague.data.local.sqldelight.mappers.toLocalEventStage
import com.adammcneilly.pocketleague.sqldelight.EventWithStage
import com.squareup.sqldelight.runtime.coroutines.asFlow
import com.squareup.sqldelight.runtime.coroutines.mapToList
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
/**
* An implementation of [LocalEventService] that requests and stores information
* from the supplied [database].
*/
class SQLDelightEventService(
private val database: PocketLeagueDB,
) : LocalEventService {
override suspend fun insert(
data: List<Event>,
) {
database.transaction {
data.forEach { event ->
database
.localEventQueries
.insertFullEventObject(event.toLocalEvent())
event.stages.forEach { stage ->
database
.localEventStageQueries
.insertFullEventStage(stage.toLocalEventStage(event.id))
}
}
}
}
override fun stream(
request: EventListRequest,
): Flow<List<Event>> {
val eventQueries = database.localEventQueries
val selectQuery = when (request) {
is EventListRequest.AfterDate -> {
eventQueries.selectAfterDate(request.dateUtc)
}
is EventListRequest.Id -> {
eventQueries.selectById(request.eventId.id)
}
is EventListRequest.OnDate -> {
eventQueries.selectOnDate(request.dateUtc)
}
}
return selectQuery
.asFlow()
.mapToList()
.map(List<EventWithStage>::toEvents)
}
}
|
---
layout: post
title: "[Bronze I] 단어순서 뒤집기 - 12605"
date: 2022-12-28 10:40:42 +0900
categories: c++
---
## Introduction
성능 요약
메모리: 2028 KB, 시간: 0 ms
분류
자료 구조(data_structures), 파싱(parsing), 스택(stack), 문자열(string)
문제 설명
스페이스로 띄어쓰기 된 단어들의 리스트가 주어질때, 단어들을 반대 순서로 뒤집어라. 각 라인은 w개의 영단어로 이루어져 있으며, 총 L개의 알파벳을 가진다. 각 행은 알파벳과 스페이스로만 이루어져 있다. 단어 사이에는 하나의 스페이스만 들어간다.
입력
첫 행은 N이며, 전체 케이스의 개수이다.
N개의 케이스들이 이어지는데, 각 케이스는 스페이스로 띄어진 단어들이다. 스페이스는 라인의 처음과 끝에는 나타나지 않는다. N과 L은 다음 범위를 가진다.
N = 5
1 ≤ L ≤ 25
출력
각 케이스에 대해서, 케이스 번호가 x일때 "Case #x: " 를 출력한 후 그 후에 이어서 단어들을 반대 순서로 출력한다.
## Link
[Link of the question](https://www.acmicpc.net/problem/12605)
## Code Block
```c++
#include <bits/stdc++.h>
using namespace std;
int n;
string reversing(string a){
stack<string> s;
string tmp;
string ans;
int size = a.size();
for(int i = 0; i < size; i++){
tmp = tmp + a[i];
if(i == size - 1){
tmp = tmp + ' ';
}
if(a[i] == ' ' || i == size - 1){
s.push(tmp);
tmp.clear();
}
}
while(!s.empty()){
ans = ans + s.top();
s.pop();
}
return ans;
}
int main(){
cin >> n;
cin.ignore();
for(int i = 0; i < n; i++){
string sen;
getline(cin,sen);
sen = reversing(sen);
cout << "Case #" << i + 1 << ": " << sen << '\n';
}
}
```
## Demonstration
Description ommited due to low difficulty.
|
namespace UglyToad.PdfPig.Graphics.Operations.PathConstruction
{
using System.IO;
/// <inheritdoc />
/// <remarks>
/// Append a rectangle to the current path as a complete subpath.
/// </remarks>
public class AppendRectangle : IGraphicsStateOperation
{
/// <summary>
/// The symbol for this operation in a stream.
/// </summary>
public const string Symbol = "re";
/// <inheritdoc />
public string Operator => Symbol;
/// <summary>
/// The x coordinate of the lower left corner.
/// </summary>
public double LowerLeftX { get; }
/// <summary>
/// The y coordinate of the lower left corner.
/// </summary>
public double LowerLeftY { get; }
/// <summary>
/// The width of the rectangle.
/// </summary>
public double Width { get; }
/// <summary>
/// The height of the rectangle.
/// </summary>
public double Height { get; }
/// <summary>
/// Create a new <see cref="AppendRectangle"/>.
/// </summary>
/// <param name="x">The x coordinate of the lower left corner.</param>
/// <param name="y">The y coordinate of the lower left corner.</param>
/// <param name="width">The width of the rectangle.</param>
/// <param name="height">The height of the rectangle.</param>
public AppendRectangle(double x, double y, double width, double height)
{
LowerLeftX = x;
LowerLeftY = y;
Width = width;
Height = height;
}
/// <inheritdoc />
public void Run(IOperationContext operationContext)
{
operationContext.Rectangle(LowerLeftX, LowerLeftY, Width, Height);
}
/// <inheritdoc />
public void Write(Stream stream)
{
stream.WriteDouble(LowerLeftX);
stream.WriteWhiteSpace();
stream.WriteDouble(LowerLeftY);
stream.WriteWhiteSpace();
stream.WriteDouble(Width);
stream.WriteWhiteSpace();
stream.WriteDouble(Height);
stream.WriteWhiteSpace();
stream.WriteText(Symbol);
stream.WriteNewLine();
}
/// <inheritdoc />
public override string ToString()
{
return $"{LowerLeftX} {LowerLeftY} {Width} {Height} {Symbol}";
}
}
}
|
import { useState, useRef, useEffect } from 'react';
import { useAuth } from '../../context/AuthContext';
import { useLocation, useNavigate } from 'react-router-dom';
import { ERROR_MESSAGES } from './enums';
import validator from 'validator';
import {
Button,
TextField,
Link,
Box,
IconButton,
Typography,
CircularProgress,
Backdrop,
Alert,
Snackbar,
Toolbar,
Card,
CardContent,
Grid,
Avatar,
Divider,
Container
} from '@mui/material';
import GoogleIcon from '@mui/icons-material/Google';
import SendIcon from '@mui/icons-material/Send';
import { auth, provider } from './firebaseConfig';
import { signInWithPopup, signU,sendPasswordResetEmail } from 'firebase/auth';
import { Dialog, DialogActions, DialogContent, DialogTitle } from '@mui/material';
import ShoppingCart from '@mui/icons-material/ShoppingCart';
const AuthForm = () => {
const formRef = useRef();
const emailInputRef = useRef();
const passwordInputRef = useRef();
const emailPassReset = useRef();
const displayNameInputRef = useRef();
const photoUrlInput = useRef();
const navigate = useNavigate();
const { signIn,signInWithGoogleAuth, signUp, isUserSignedIn } = useAuth();
const [isLogin, setIsLogin] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [isShownModal, setIsShownModal] = useState(false);
const [showError, setShowError] = useState(false);
const [errorMessage, setErrorMessage] = useState(ERROR_MESSAGES.PROCESS_COULD_NOT_FINISH);
const [showResetPasswordValidation, setShowResetPasswordValidation] = useState(false);
const [showSnackBar, setShowSnackBar] = useState(false);
const [snackBarMessage, setSnackBarMessage] = useState({});
const [showInputErrors, setShowInputErrors] = useState({
email: false,
password: false,
displayName: false
});
const [photoURL, setPhotoURL] = useState('');
const location = useLocation();
const switchAuthModeHandler = () => {
setIsLogin((prevState) => !prevState);
};
const submitHandler = async (event) => {
event.preventDefault();
const email = emailInputRef.current.value.trim();
const password = passwordInputRef.current.value.trim();
const displayName = displayNameInputRef.current
? displayNameInputRef.current.value.trim()
: true;
const emailInputError = email === '';
const passwordInputError = password === '';
const displayNameError = displayName === '';
setShowInputErrors({
email: emailInputError,
password: passwordInputError,
displayName: displayNameError
});
if (emailInputError || passwordInputError || displayNameError) {
return;
}
setIsLoading(true);
const payload = { email, password };
try {
if (isLogin) {
await signIn(payload);
} else {
await signUp({ ...payload, displayName, photoFile: photoUrlInput.current.files[0] });
}
setIsLoading(false);
navigate(location.state ? location.state.redirect : '/');
} catch (ex) {
if (ex.response && ex.response.status === 400) {
let errorMessage;
Object.keys(ERROR_MESSAGES).forEach((message) => {
if (ex.response.data.error.message.indexOf(message) !== -1) {
errorMessage = message;
return;
}
});
errorMessage = errorMessage ? ERROR_MESSAGES[errorMessage] : ERROR_MESSAGES.GENERIC;
setErrorMessage(errorMessage);
}
setIsLoading(false);
setShowError(true);
}
};
const signInWithGoogle = async () => {
setIsLoading(true);
try {
const data = await signInWithPopup(auth, provider);
await signInWithGoogleAuth(data._tokenResponse);
navigate('/');
setIsLoading(false);
} catch (ex) {
if (ex.response && ex.response.status === 400) {
let errorMessage;
Object.keys(ERROR_MESSAGES).forEach((message) => {
if (ex.response.data.error.message.indexOf(message) !== -1) {
errorMessage = message;
return;
}
});
errorMessage = errorMessage ? ERROR_MESSAGES[errorMessage] : ERROR_MESSAGES.GENERIC;
setErrorMessage(errorMessage);
}
setIsLoading(false);
setShowError(true);
}
};
const passwordReset = async () => {
const email = emailPassReset.current.value;
if (!email || !validator.isEmail(email)) {
setShowResetPasswordValidation(true);
return;
}
try {
await sendPasswordResetEmail(auth, email);
setIsShownModal(false);
setSnackBarMessage({
severity: 'success',
message: 'Password reset link was sent to: ' + email
});
setShowSnackBar(true);
} catch (ex) {
let message;
switch (ex.code) {
case 'auth/invalid-email':
message = ERROR_MESSAGES.INVALID_EMAIL;
break;
case 'auth/user-not-found':
message = ERROR_MESSAGES.USER_NOT_FOUND;
break;
default:
message = ERROR_MESSAGES.PROCESS_COULD_NOT_FINISH;
break;
}
setSnackBarMessage({
severity: 'error',
message: 'Password reset failed:' + message
});
setShowSnackBar(true);
}
};
const showModal = () => {
setIsShownModal(true);
};
const closeModal = () => {
setIsShownModal(false);
};
useEffect(() => {
setShowError(false);
formRef.current.reset();
setPhotoURL('');
}, [isLogin]);
useEffect(() => {
if (isUserSignedIn()) {
navigate({ pathname: '/' });
}
}, [isUserSignedIn, navigate]);
const handlePhotoSelect = () => {
const fileName = photoUrlInput.current.files[0].name;
setPhotoURL(fileName);
};
const handleClearPhotoURL = () => {
photoUrlInput.current.value = '';
setPhotoURL('');
};
return (
<>
<Toolbar></Toolbar>
<Container maxWidth={'50vw'} sx={{ height: 'calc(100vh - 64px)' }}>
<Grid
container
direction={'row'}
alignItems={'center'}
justifyContent={'center'}
height={'100%'}>
<Card elevation={3} sx={{ width: '750px' }}>
<Box padding={2} color={'white'} bgcolor={'var(--main-app-blue)'}>
<Box display={'flex'} justifyContent={'center'} alignItems={'center'}>
<Avatar
sx={{
width: 40,
height: 40,
bgcolor: '#385074'
}}>
<ShoppingCart fontSize="medium"></ShoppingCart>
</Avatar>
<Typography variant="h4" fontWeight={'bold'} marginLeft={2}>
Store.io
</Typography>
</Box>
</Box>
<Divider></Divider>
<CardContent>
<form onSubmit={submitHandler} id="loginForm" ref={formRef}>
<Box display={'flex'} alignItems={'center'} flexDirection={'column'}>
{(() => {
if (isLogin) {
return (
<>
<Typography variant="h3" marginBottom={1} fontWeight={'bold'}>
Hello again!
</Typography>
<Typography color={'gray'} fontWeight={'bold'} fontSize={'0.8em'}>
Welcome back, you have been missed!
</Typography>
</>
);
} else {
return (
<>
<Typography variant="h3" marginBottom={1} fontWeight={'bold'}>
Thank you for joining us!
</Typography>
<Typography color={'gray'} fontWeight={'bold'} fontSize={'0.8em'}>
We’re looking forward to a long and prosperous relationship.
</Typography>
</>
);
}
})()}
</Box>
<Box component="main">
<Box marginTop={4} display="flex" flexDirection={'column'} alignItems={'center'}>
{isLoading && (
<>
<Backdrop
open={true}
sx={{
color: '#fff',
zIndex: (theme) => theme.zIndex.drawer + 1
}}></Backdrop>
<CircularProgress
sx={{
position: 'absolute',
width: '100%',
height: '100%',
zIndex: (theme) => theme.zIndex.drawer + 1
}}
size={'8em'}></CircularProgress>
</>
)}
<Box marginBottom={1} display={'flex'} flexDirection={'column'} width={'70%'}>
{!isLogin && (
<Grid container>
<Grid item xs={6}>
<TextField
id="display-name-input"
label="Display name*"
sx={{ marginBottom: 2 }}
inputRef={displayNameInputRef}
error={showInputErrors.displayName}
helperText={
showInputErrors.displayName ? ERROR_MESSAGES.DISPLAY_NAME_EMPTY : ''
}></TextField>
</Grid>
<Grid item xs={6}>
<Box display="flex" flexDirection={'row'} position={'relative'}>
<TextField
id="photoUrl"
label="Profile Picture"
variant="outlined"
type={'button'}
inputProps={{
accept: 'image/*'
}}
onClick={() => photoUrlInput.current.click()}
value={photoURL}
fullWidth></TextField>
<Button
sx={{
position: 'absolute',
right: 0,
bottom: 0,
height: '100%',
borderRadius: 0,
boxShadow: 'none',
padding: 0
}}
variant="contained"
color="mainButton"
onClick={handleClearPhotoURL}>
Clear
</Button>
</Box>
<TextField
type={'file'}
sx={{ display: 'none' }}
inputProps={{ accept: 'image/*' }}
onChange={handlePhotoSelect}
inputRef={photoUrlInput}></TextField>
</Grid>
</Grid>
)}
<TextField
id="outlined-input-email"
label="Email"
type="Email"
autoComplete="email"
inputRef={emailInputRef}
sx={{
marginBottom: 2
}}
error={showInputErrors.email}
helperText={showInputErrors.email ? ERROR_MESSAGES.EMAIL_EMPTY : ''}
/>
<TextField
id="outlined-input-pass"
label="Password"
type="password"
autoComplete="current-password"
inputRef={passwordInputRef}
error={showInputErrors.password}
helperText={showInputErrors.password ? ERROR_MESSAGES.WEAK_PASSWORD : ''}
/>
<Box
display={'flex'}
flexDirection={'row'}
justifyContent={'space-between'}
marginBottom={3}>
<Typography variant="caption" id="forPass" onClick={showModal}>
<Link sx={{ cursor: 'pointer' }}>
{isLogin ? 'Forgot password?' : ''}
</Link>
</Typography>
<Typography onClick={switchAuthModeHandler} variant="caption">
{isLogin ? 'Not a member? ' : 'Already a member? '}
<Link sx={{ cursor: 'pointer' }}>{isLogin ? 'Sign up' : 'Sign in'}</Link>
</Typography>
</Box>
<Button
type="submit"
variant="contained"
color="mainButton"
id="signIn"
endIcon={<SendIcon />}
fullWidth>
{isLogin ? 'SIGN IN' : 'SIGN UP'}
</Button>
</Box>
<Dialog open={isShownModal} onClose={closeModal}>
<DialogTitle bgcolor={'mainColor.main'} color={'mainColor.text'}>
Reset Your Password
</DialogTitle>
<DialogContent>
<Typography variant="body1" marginTop={1} fontWeight={500}>
Please enter your email address, further instructions will be sent to this
email address.
</Typography>
<Box component={'form'}>
<TextField
error={showResetPasswordValidation}
helperText={
showResetPasswordValidation
? 'Please enter a valid email address!'
: ''
}
autoComplete="false"
autoFocus
required
margin="dense"
id="name"
label="Email Address"
type="email"
fullWidth
variant="standard"
inputRef={emailPassReset}
/>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={closeModal} color="mainButton">
Cancel
</Button>
<Button onClick={passwordReset} color="mainButton">
Send
</Button>
</DialogActions>
</Dialog>
<Box textAlign={'center'}>
<Typography>Or {isLogin ? 'sign in' : 'sign up'} with:</Typography>
<IconButton onClick={signInWithGoogle} color="primary">
<GoogleIcon id="google" fontSize={'large'}></GoogleIcon>
</IconButton>
</Box>
{showError && (
<Alert severity="error" variant="filled" sx={{ width: '50%', marginTop: 1 }}>
{errorMessage}
</Alert>
)}
<Snackbar
open={showSnackBar}
onClose={() => setShowSnackBar(false)}
autoHideDuration={3000}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center'
}}>
<Alert
severity={snackBarMessage.severity}
variant="filled"
sx={{ width: '100%', marginTop: 3 }}>
{snackBarMessage.message}
</Alert>
</Snackbar>
</Box>
</Box>
</form>
</CardContent>
</Card>
</Grid>
</Container>
</>
);
};
export default AuthForm;
|
/***********************************************************************************
* *
* quiGLy - quick GL prototyping *
* *
* Copyright (C) 2015-2018 University of Muenster, Germany. *
* Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
* For a list of authors please refer to the file "CREDITS.txt". *
* *
* This file is part of the quiGLy software package. quiGLy is free software: *
* you can redistribute it and/or modify it under the terms of the GNU General *
* Public License version 2 as published by the Free Software Foundation. *
* *
* quiGLy is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR *
* A PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License in the file *
* "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
* *
* For non-commercial academic use see the license exception specified in the file *
* "LICENSE-academic.txt". To get information about commercial licensing please *
* contact the authors. *
* *
***********************************************************************************/
#ifndef ZIPARCHIVE_H
#define ZIPARCHIVE_H
#include <minizip/zip.h>
#include <minizip/unzip.h>
#include <QString>
namespace ysm
{
/**
* @brief Small helper class to work with Zip archives
*/
class ZipArchive
{
public:
enum ArchiveMode
{
ModePack,
ModeUnpack,
};
public:
// Construction
explicit ZipArchive();
virtual ~ZipArchive();
public:
// Archive handling
/**
* @brief Opens the specified archive, creating it if necessary
*/
bool openZip(QString zipFile, ArchiveMode mode);
/**
* @brief Closes the currently opened zip file
*/
void closeZip();
// File handling
/**
* @brief Adds the specified file to the archive
*/
bool addFile(QString fileName, QString zipDir);
/**
* @brief Adds the specified directory to the archive
*/
bool addDirectory(QString dirName, QString baseDir = "");
/**
* @brief Extracts the contents of the archive to @p destDir
* Note: Existing files will be overwritten
*/
bool unpackContents(QString destDir);
private:
/**
* @brief Unpacks the current file to @p destDir
*/
bool unpackFile(QString destDir, QString fileName, unsigned int fileSize);
private:
zipFile _zipFile{nullptr};
unzFile _unzipFile{nullptr};
};
}
#endif
|
#include "3-calc.h"
#include <stdio.h>
/**
* main - calculate
* @argc: the number of args passed
* @argv: the array of arguments
* Return: 0
*/
int main(int argc, char **argv)
{
int (*op_func)(int, int), f, s;
if (argc != 4)
{
printf("Error\n");
exit(98);
}
f = atoi(argv[1]);
s = atoi(argv[3]);
op_func = get_op_func(argv[2]);
if (op_func == NULL)
{
printf("Error\n");
exit(99);
}
if (s == 0 && (argv[2][0] == '/' || argv[2][0] == '%'))
{
printf("Error\n");
exit(100);
}
printf("%d\n", op_func(f, s));
return (0);
}
|
package client;
import common.Player;
/**
* Client used for a TicTacToe game using a TCP connection that all
* clients will extend.
*
* @author Zach Eanes
* @version 11/03/2023
*/
public abstract class DefaultGameClient implements GameClient{
/** default port number for the client to connect to */
public static final int DEFAULT_PORT = 8080;
/** default host name for the client to connect to */
public static final String DEFAULT_HOST = "localhost";
/** port number for the client to connect to */
private int port;
/** host name for the client to connect to */
private String host;
/** player for the client */
private Player player;
/**
* Constructor for the DefaultGameClient class with a provided port number
* and host name.
*
* @param port the port number for the client to connect to
* @param host the host name for the client to connect to
* @param player the player for the client
*/
public DefaultGameClient(int port, String host, Player player) {
this.port = port;
this.host = host;
this.player = player;
}
/**
* Constructor for the DefaultGameClient class with a provided port number.
*
* @param port the port number for the client to connect to
* @param player the player for the client
*/
public DefaultGameClient(int port, Player player) { this(port, DEFAULT_HOST, player); }
/**
* Constructor for the DefaultGameClient class with a provided host name.
*
* @param host the host name for the client to connect to
* @param player the player for the client
*/
public DefaultGameClient(String host, Player player) { this(DEFAULT_PORT, host, player); }
/**
* Constructor for the DefaultGameClient class with a given player.
*
* @param player the player for the client
*/
public DefaultGameClient(Player player) { this(DEFAULT_PORT, DEFAULT_HOST, player); }
/**
* Causes the game client to connect to the server and play the game.
*
* @throws GameClientException if an error occurs while connecting to the server
*/
@Override
public abstract void connect() throws GameClientException;
/** Getter method for the port number */
public int getPort() { return port; }
/** setter method for the port number */
public void setPort(int port) { this.port = port; }
/** Getter method for the host name */
public String getHost() { return host; }
/** Setter method for the host name */
public void setHost(String host) { this.host = host; }
/** Getter method for the player */
public Player getPlayer() { return player; }
/** Setter method for the player */
public void setPlayer(Player player) { this.player = player; }
}
|
import 'package:assalomproject/core/common_models/error_model.dart';
import 'package:assalomproject/views/main_page/data/api/common_request.dart';
import 'package:assalomproject/views/main_page/data/models/payment_types_model.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
part 'payment_event.dart';
part 'payment_state.dart';
class PaymentBloc extends Bloc<PaymentEvent, PaymentState> {
PaymentBloc() : super(PaymentInitial()) {
on<PaymentOrder>(makePayment);
}
Future<void> makePayment(
PaymentOrder event, Emitter<PaymentState> emit) async {
emit(PaymentInitial());
final response = await CommonRequests.payForOrder(event.id);
if (response is PaymentTypesModel) {
emit(PaymentSuccess(paymentTypesModel: response));
print("GET PAYMENIT ${response}");
} else if (response is ErrorModel) {
emit(PaymentFail(errorModel: response));
print("GET PAYMENIT ERROR");
}
}
}
|
/*
* Copyright (C) 2015 Edward Raff
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jsat.linear.distancemetrics;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import jsat.linear.*;
import jsat.utils.SystemInfo;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Edward Raff
*/
public class MinkowskiDistanceTest
{
static private ExecutorService ex;
static private Vec zero;
static private Vec ones;
static private Vec half;
static private Vec inc;
static private List<Vec> vecs;
static private double[][] expectedP2;
static private double[][] expectedP1;
static private double[][] expectedP1p5;
public MinkowskiDistanceTest()
{
}
@BeforeClass
public static void setUpClass()
{
ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores);
}
@AfterClass
public static void tearDownClass()
{
ex.shutdown();
}
@Before
public void setUp()
{
zero = new DenseVector(5);
ones = new DenseVector(5);
ones.mutableAdd(1.0);
half = new DenseVector(5);
half.mutableAdd(0.5);
inc = new DenseVector(5);
for(int i = 0; i < inc.length(); i++)
inc.set(i, i);
vecs = Arrays.asList(zero, ones, half, inc);
expectedP2 = new double[][]
{
{ 0.0 , 2.2360679775 , 1.11803398875 , 5.47722557505 , },
{ 2.2360679775 , 0.0 , 1.11803398875 , 3.87298334621 , },
{ 1.11803398875 , 1.11803398875 , 0.0 , 4.60977222865 , },
{ 5.47722557505 , 3.87298334621 , 4.60977222865 , 0.0 , },
};
expectedP1 = new double[][]
{
{ 0 , 5 , 2.5 , 10 , },
{ 5 , 0 , 2.5 , 7 , },
{ 2.5 , 2.5 , 0.0 , 8.5 , },
{ 10 , 7 , 8.5 , 0 , },
};
expectedP1p5 = new double[][]
{
{ 0.0 , 2.92401773821 , 1.46200886911 , 6.61786032327 , },
{ 2.92401773821 , 0.0 , 1.46200886911 , 4.64919159806 , },
{ 1.46200886911 , 1.46200886911 , 0.0 , 5.54151812966 , },
{ 6.61786032327 , 4.64919159806 , 5.54151812966 , 0.0 , },
};
}
@After
public void tearDown()
{
}
@Test
public void testDist_Vec_Vec()
{
System.out.println("dist");
MinkowskiDistance dist = new MinkowskiDistance(2.5);
List<Double> cache = dist.getAccelerationCache(vecs);
List<Double> cache2 = dist.getAccelerationCache(vecs, ex);
if(cache != null)
{
assertEquals(cache.size(), cache2.size());
for(int i = 0; i < cache.size(); i++)
assertEquals(cache.get(i), cache2.get(i), 0.0);
assertTrue(dist.supportsAcceleration());
}
else
{
assertNull(cache2);
assertFalse(dist.supportsAcceleration());
}
try
{
dist.dist(half, new DenseVector(half.length()+1));
fail("Distance between vecs should have erred");
}
catch (Exception ex)
{
}
for(int rounds = 0; rounds < 3; rounds++)
{
//some code so that dense on dense, dense on sparse, and sparse on sparse all get run
if(rounds == 1)
for(int i = 0; i <vecs.size(); i+=2)
vecs.set(i, new SparseVector(vecs.get(i)));
else if(rounds == 2)
for(int i = 1; i <vecs.size(); i+=2)
vecs.set(i, new SparseVector(vecs.get(i)));
for (int i = 0; i < vecs.size(); i++)
for (int j = 0; j < vecs.size(); j++)
{
MinkowskiDistance d = dist.clone();
d.setP(2.0);
assertEquals(2.5, dist.getP(), 0.0);
assertEquals(expectedP2[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8);
assertEquals(expectedP2[i][j], d.dist(i, j, vecs, cache), 1e-8);
assertEquals(expectedP2[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8);
assertEquals(expectedP2[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8);
d.setP(1.0);
assertEquals(expectedP1[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8);
assertEquals(expectedP1[i][j], d.dist(i, j, vecs, cache), 1e-8);
assertEquals(expectedP1[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8);
assertEquals(expectedP1[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8);
d.setP(1.5);
assertEquals(expectedP1p5[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8);
assertEquals(expectedP1p5[i][j], d.dist(i, j, vecs, cache), 1e-8);
assertEquals(expectedP1p5[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8);
assertEquals(expectedP1p5[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8);
}
}
}
@Test
public void testMetricProperties()
{
System.out.println("isSymmetric");
EuclideanDistance instance = new EuclideanDistance();
assertTrue(instance.isSymmetric());
assertTrue(instance.isSubadditive());
assertTrue(instance.isIndiscemible());
}
@Test
public void testMetricBound()
{
System.out.println("metricBound");
EuclideanDistance instance = new EuclideanDistance();
assertTrue(instance.metricBound() > 0);
assertTrue(Double.isInfinite(instance.metricBound()));
}
}
|
@5BasicConcepts
1. Authentication
- Define who you are
1) Knowledge based authentication: pw, pinCode, SecretQuestions
2) Possession based authentication: TxtMsg, KeyCards, Badges, TokenDevice
3) MultiFactor Authentication: Knowledge + Possession
2. Authorization
- Are you allowed to do this? YN
3. Principal
- Currently loggedIn user
- 1 request can have only 1 principal
4. Granted Authority
5. Roles
- Group of Authorities
@AddSpringSecurityToSpringBootProject
1. spring-boot-starter-security
: dependency that make springSecurity available
2. add dependency classpath below in a pom.xml(Mvn project)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3. SS automatically adds sign-in function.
4.HowDoesItWork?
1. As one of 'filters' for every request, it intercepts every requests.
2. SS's default behavior
1) Adds mandatory authentication for all URLs (skip some of urls eg.error page)
2) Adds login form, logout
3) Handles login error
4) Creates a user and sets a default password
*You can override the default user at <application.properties> with setting as below.
spring.security.user.name=customizedName
spring.security.user.password=hello
@How to configure <Authentication>
1. AuthenticationManager : doing authenticate()
2. AuthenticationManagerBuilder : build up AM
AMB: What type of Auth?
user: In-Memory Auth, please!
AMB: Tell me the userName, PW, and Role
3. Steps
1) Get hold of AuthenticationManagerBuilder
- SpringSecurityApp has a Class 'WebSecurityConfigurerAdapter', which has a configure(AuthenticationManagerBuilder auth)
- You have to extend that class and override configure(AuthMgrBldr),
without it, SSApp will call the default configure.
- put annotation @EnableWebSecurity on the extended class
2) Set the configuration on it
4) add passwordEncoder
3) example:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("sexysoo")
.password("sexy")
.roles("USER")
.and()
.withUser("admin")
.password("admin")
.roles("ADMIN");
}
@Bean
public PasswordEncoder getPasswordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
4. logout: localhost:8080/logout
@How to configure <Authorization>
1. override method "configure(HttpSecurity http)" from "WebSecurityConfigurerAdapter"
2. authorize request begins with ".authorizeRequest()"
3. define role according to the path with the form of : <path> ~ <allowedRoles>
4. example:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasAnyRole("ADMIN", "USER")
.antMatchers("/").permitAll()
.and().formLogin();
}
@How does SpringSecurity work behind
1. filter > (Authentication~credentials) > AuthenticationManager.authenticate()
2. > AuthenticationProvider.authenticate()
> AuthenticationProvider.supports() > UserDetailsService.loadUserByUserName()
3. > AuthenticationManager.authenticate() > (Authentication ~ principal) > filter
|
import Header from '../components/Header'
import Footer from '../components/Footer'
import InfoCard from '../components/InfoCard'
import { useRouter } from 'next/dist/client/router'
import { format } from 'date-fns'
import Map from '../components/Map'
import { searchResults } from '../data/searchResultData'
const Search = () => {
const router = useRouter()
const { location, startDate, endDate, numGuests } = router.query
const formattedStartDate = format(new Date(startDate), 'MMMM dd yy')
const formattedEndDate = format(new Date(endDate), 'MMMM dd yy')
const range = `${formattedStartDate} - ${formattedEndDate}`
return (
<div>
<Header placeholder={`${location} | ${range} | ${numGuests} guests`} />
<main className='flex'>
<section className='flex-grow pt-14 px-6'>
<p className='text-xs'>
300+ Stays - {range} - for {numGuests} guests
</p>
<h1 className='text-3xl font-semibold mt-2 mb-6'>
Stays in {location}
</h1>
<div className='hidden lg:inline-flex mb-5 space-x-3 text-gray-800 whitespace-nowrap'>
<p className='button'>Cancellation Flexibility</p>
<p className='button'>Type of Place</p>
<p className='button'>Price</p>
<p className='button'>Rooms and Beds</p>
<p className='button'>More Filters</p>
</div>
<div className='flex flex-col'>
{searchResults?.map(result => (
<InfoCard
key={result.title}
img={result.img}
location={result.location}
title={result.title}
description={result.description}
star={result.star}
price={result.price}
total={result.total}
/>
))}
</div>
</section>
<section className='hidden xl:inline-flex xl:min-w-[600px]'>
<Map searchResults={searchResults} />
</section>
</main>
<Footer />
</div>
)
}
export default Search
export async function getServerSideProps() {
const testSearchResults = await fetch('https://links.papareact.com/isz').then(
res => res.json()
)
return {
props: {
testSearchResults,
},
}
}
|
<template>
<div v-motion-slide-visible-top>
<video ref="video" @ended="handleVideoEnd" autoplay muted>
<source :src="videoSource" type="video/webm" />
Your browser does not support the video tag.
</video>
</div>
</template>
<script lang="ts" setup>
import { ref, watchEffect } from "vue";
// Replace 'your_video.webm' with the actual path to your video file
const videoSource = ref("src/assets/videos/Comp 1.webm");
const videoRef = ref(null);
const handleVideoEnd = () => {
const video = videoRef.value;
if (video) {
// Reverse playback
video.playbackRate = -1;
// Restart video from the end
video.currentTime = video.duration - 0.01;
// Play the reversed video
video.play();
}
};
// Watch for changes in videoSource and restart the video
watchEffect(() => {
const video = videoRef.value;
if (video) {
// Set playback rate back to normal
video.playbackRate = 1;
// Restart video from the beginning
video.currentTime = 0;
// Play the video
video.play();
}
});
</script>
|
package cmd
import (
"github.com/WileESpaghetti/go-uptimerobot-v2/uptime_robot"
"os"
"github.com/spf13/cobra"
)
var (
apiKey string
apiClient *uptime_robot.Client
)
// flags
const (
FlagApiKey = "api-key"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "uptimerobot",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
rootCmd.PersistentFlags().StringVar(&apiKey, FlagApiKey, "", "config file (default is $HOME/.uptimerobot.yaml)")
cobra.OnInitialize(func() {
apiClient = uptime_robot.NewClient(apiKey)
})
}
|
import React from 'react';
import './ReviewItem.css';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faTrashAlt } from '@fortawesome/free-solid-svg-icons'
const ReviewItem = ({ product, handleRemoveFromCart }) => {
const { id, img, name, price, quantity } = product;
const totalPrice = price * quantity;
return (
<div className='review-item'>
<img src={img} alt="" />
<div>
<h2 className='title'>{name}</h2>
<p className='price'>Price: <span className='orange-text'>${price}</span></p>
<p className='quantity'>Quantity: <span className='orange-text'>{quantity}</span></p>
</div>
<span onClick={() => handleRemoveFromCart(id)} className='review-trash'><FontAwesomeIcon icon={faTrashAlt} /></span>
</div>
);
};
export default ReviewItem;
|
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:weather_app/json_model.dart';
class DataService{
Future<WeatherResponse> getWeather(String city) async{
//https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
final queryParameters = {'q': city, 'appid': 'a6f1bbd28c0153cf4521d65b6c7818d6', 'units': 'imperial'};
final uri = Uri.https('api.openweathermap.org', '/data/2.5/weather', queryParameters);
final response = await http.get(uri);
final json = jsonDecode(response.body);
return WeatherResponse.fromJson(json);
}
}
|
.TH MH-MAIL 5 RAND
.SH NAME
mh-mail \- Message format for MH
.SH DESCRIPTION
.I MH,
the Rand message-handling system, processes messages in
a particular format. It should be noted that neither
the Berkeley mailer nor the Bell mail program produces
message files in precisely the correct format for
.I mh.
.PP
Each user possesses a mail drop box which initially receives
all messages processed by
.I deliver(8).
.I Inc(1)
will read from that drop box and incorporate the new messages
found there into the user's own mail folders. The mail drop
box consists of one or more messages. To facilitate the
separation of messages, each message begins and ends with
a line consisting of nothing but four Control-A (octal 001)
characters.
.PP
Each message consists of two parts: a header, consisting of
one or more header lines, and a body, containing the actual
text of the message. These parts are separated by an empty
line, i.e. two consecutive Newline characters.
Within MH, the header and body may be separated by a line
consisting of dashes.
.PP
Each header item can be viewed as a single logical line of ASCII
characters.
If the text of a header item extends across several
real lines, the continuation lines are indicated by leading
spaces or tabs.
.PP
Each header item is called a component and is composed of a
keyword or name, along with associated text.
The keyword begins at the
left margin, may contain spaces or tabs, may not exceed 63
characters, and is terminated by a colon (:).
Certain
components (as identified by their keywords) must follow rigidly
defined formats in their text portions.
.PP
The text for most formatted components (e.g., ``Date:'' and ``Message-Id:'')
is produced automatically.
The only ones entered by the
user are address fields such as ``To:'', ``cc:'', etc.
ARPA addresses
are assigned mailbox names and host computer specifications.
The
rough format is ``mailbox at host'', such as ``Borden at Rand-Unix''.
Multiple addresses are separated by commas.
A missing host is
assumed to be the local host.
.PP
Following is a list of header components that are considered
meaningful to various MH programs.
.TP 15
.I Component
.I Usage
.br
.TP
Date:
Added by
.I deliver(8),
contains date and time of delivery.
.br
.ns
.TP
From:
Added by
.I deliver(8),
contains the userid of the sender. But see "Sender:"
.br
.ns
.TP
Sender:
Added by
.I deliver(8)
in the event that the user has supplied a "From:" line,
contains the userid of the sender.
.br
.ns
.TP
To:
Contains address of recipient of message.
.br
.ns
.TP
cc:
Contains addresses of additional recipients.
.br
.ns
.TP
Bcc:
Still more recipients. However, the Bcc line is not
copied onto the message as delivered, so these recipients
are not listed.
.br
.ns
.TP
fcc:
Causes
.I deliver(8)
to copy the message into the specified folder.
.br
.ns
.TP
Subject:
Sender's commentary. It is displayed by
.I scan(1).
.br
.ns
.TP
Message-ID:
A unique message identifier glued on by
.I deliver
if the
.B \-msgid
flag is set.
.br
.ns
.TP
In-Reply-To:
A commentary line added by
.I repl(1)
when replying to a message.
.br
.ns
.TP
Replied:
Reply date added by
.I repl(1)
under the "annotate" option.
.br
.ns
.TP
Forwarded:
Forwarding date added by
.I forw(1)
under the "annotate" option.
.br
.ns
.TP
Distribute-to:
New recipients for a redistributed message processed
by
.I dist(1).
.br
.ns
.TP
Distribute-cc:
Still more recipients. See "cc:".
.br
.ns
.TP
Distribute-bcc:
Even more recipients. See "bcc:.
.br
.ns
.TP
Distribute-fcc:
Copy distributed message into a folder. See "fcc:".
.br
.ns
.TP
Distribute-from:
Added when redistributing a message.
.br
.ns
.TP
Distribution-date:
Is to distribute-from as Date: is to From:.
.br
.ns
.TP
Distribution-id:
Added if msgid option is in effect.
.br
.ns
.TP
Distributed:
Annotation for
.I dist(1)
.SH FILES
/usr/spool/mail/*
.SH SEE ALSO
\fIThe MH Message Handling System: User's Manual\fR
by B. Borden, R. Gaines, and N. Shapiro
.br
\fIStandard for the Format of ARPA Network Test Messages\fR
by D. Crocker, J. Vittal, K. Pogran, and D. Henderson, Jr.
|
import {
AxiosPromise,
AxiosRequestConfig,
AxiosResponse,
Method as AxiosMethod,
} from 'axios'
import useAxios from 'axios-hooks'
import { ServerConfigContainer } from 'containers/ConfigContainer'
import { useMyAxios } from 'hooks/useMyAxios'
import { Instance, LogData, System } from 'types/backend-types'
const getConfig = (id: string, method: AxiosMethod, authEnabled: boolean) => {
const config: AxiosRequestConfig = {
url: `/api/v1/instances/${id}`,
method: method,
withCredentials: authEnabled,
}
return config
}
const useFetchStatus = () => {
const { authEnabled } = ServerConfigContainer.useContainer()
const { axiosManualOptions } = useMyAxios()
const [, execute] = useAxios({}, axiosManualOptions)
/**
* Fetches status of an instance from the backend after a timeout
*
* @param id instance id
* @returns
*/
const fetchStatus = (id: string) => {
const config = getConfig(id, 'get', authEnabled)
const promise = new Promise<string>((resolve) => {
setTimeout(async () => {
const response = execute(config).then(
async (resp: AxiosResponse<Instance>) => {
return resp.data.status
},
)
resolve(response)
}, 2000)
})
return promise
}
return fetchStatus
}
const useToggleInstance = () => {
const { authEnabled } = ServerConfigContainer.useContainer()
const fetchStatus = useFetchStatus()
const { axiosManualOptions } = useMyAxios()
const [, execute] = useAxios({}, axiosManualOptions)
const toggleInstance = async (id: string, operation: string) => {
const config = getConfig(id, 'patch', authEnabled)
const promiseResp = execute({
...config,
data: { operation: operation },
}).then(async (resolved: AxiosResponse<Instance>) => {
return await fetchStatus(resolved.data.id)
})
return promiseResp
}
return toggleInstance
}
const useInstances = () => {
const { authEnabled } = ServerConfigContainer.useContainer()
const { axiosManualOptions } = useMyAxios()
const [, execute] = useAxios({}, axiosManualOptions)
const toggleInstance = useToggleInstance()
const startInstance = async (id: string) => {
return await toggleInstance(id, 'start')
}
const stopInstance = async (id: string) => {
return await toggleInstance(id, 'stop')
}
const stopAllInstances = (system: System) => {
system.instances.forEach((instance) => toggleInstance(instance.id, 'stop'))
}
const startAllInstances = (system: System) => {
system.instances.forEach((instance) => toggleInstance(instance.id, 'start'))
}
const getInstanceLogs = (
id: string,
timeout: number,
startLine?: number,
endLine?: number,
): AxiosPromise<string> => {
const config: AxiosRequestConfig<LogData> = {
url: `/api/v1/instances/${id}/logs`,
method: 'get',
withCredentials: authEnabled,
params: {
start_line: startLine,
end_line: endLine,
timeout: timeout,
},
}
return execute(config)
}
const downloadLogs = (id: string): AxiosPromise<Blob> => {
const config: AxiosRequestConfig = {
url: `/api/v1/instances/${id}/logs`,
method: 'get',
withCredentials: authEnabled,
responseType: 'blob',
}
return execute(config)
}
return {
startInstance,
stopInstance,
startAllInstances,
stopAllInstances,
getInstanceLogs,
downloadLogs,
}
}
export { useInstances }
|
package enums.task3;
public enum TemperatureConvert {
C_F('C', 'F', new Converter() {
@Override
public float convert(float tempIn) {
return (tempIn * 9 / 5) + 32;
}
}),
/* C_F('C', 'F', temp -> temp * 9 / 5 + 32)*/
C_K('C', 'K', new Converter() {
@Override
public float convert(float tempIn) {
return tempIn + 273.15f;
}
});
char input;
char output;
Converter converter;
TemperatureConvert(char input, char output, Converter converter) {
this.input = input;
this.output = output;
this.converter = converter;
}
public static float convertTemperatura(char a, char b, float temperature){
for (TemperatureConvert temperatureConvert : TemperatureConvert.values()){
if(temperatureConvert.input == a && temperatureConvert.output == b){
return temperatureConvert.converter.convert(temperature);
}
}
return Float.MIN_VALUE;
}
}
|
import { Request, Response } from "express";
import {
createDataResponse,
createErrorResponse,
} from "../../utilities/createResponse.js";
import getUserFromToken from "../../utilities/getUserFromToken.js";
import { JwtPayload } from "../user/getUser.js";
import prisma from "../../utilities/prisma.js";
import { PaginationMetaData } from "./getAllCommunities.js";
const getJoinedCommunitiesByUserId = async (req: Request, res: Response) => {
try {
let currentPage = 1; //these two fields must come from frontend
let pageSize = 3;
const token = req.headers.authorization?.split(" ")[1];
if (!token) return createErrorResponse(res, "Invalid token", 403);
const { id } = getUserFromToken(token) as JwtPayload;
const communities = await prisma.community.findMany({
where: {
members: {
some: {
user: id,
},
},
},
select: {
id: true,
name: true,
slug: true,
communityUser: {
select: {
id: true,
name: true,
},
},
created_at: true,
updated_at: true,
},
});
const total = await prisma.community.count({
where: {
members: {
some: {
user: id,
},
},
},
});
const pages = Math.ceil(total / pageSize);
const page = Math.min(Math.max(currentPage, 1), pages); // Ensure page is within valid range
const meta: PaginationMetaData = {
total,
pages,
page,
};
return createDataResponse(
res,
communities.map((c) => {
return {
...c,
owner: c.communityUser,
communityUser: undefined,
};
}),
meta
);
} catch (err) {
const error = err as Error;
return createErrorResponse(res, error.message);
}
};
export default getJoinedCommunitiesByUserId;
|
TT <- 100
# Белый шум
set.seed(123) # задаем начальное число для датчика
eps <- rnorm(TT, sd=2)
#plot(eps, type = "l")
#plot(eps, type = "b")
plot.ts(eps) # график для временных рядов
abline(h=0, col="blue")
acf(eps) # АКФ для белого шума, случайно болтается без какой то системы
# AR - авторегрессия
phi <- 0.8
x <- eps[1] # t=1
for (t in 2:TT) {
x[t] <- phi * x[t-1] + eps[t]
}
#x <- x + 10 # если хотим среднее 10
plot.ts(x) # график для временных рядов
abline(h=0, col="blue")
acf(x, lag.max=90) # убывает, но случайно уходит в отриц. область
phi <- -0.8 # орицательная корреляция между соседними наблюдениями
x <- eps[1] # t=1
for (t in 2:TT) {
x[t] <- phi * x[t-1] + eps[t]
}
plot.ts(x) # график для временных рядов
abline(h=0, col="blue")
acf(x, lag.max=30)
phi <- 1 # случайное блуждание
x <- eps[1] # t=1
for (t in 2:TT) {
x[t] <- phi * x[t-1] + eps[t]
}
plot.ts(x) # график для временных рядов
abline(h=0, col="blue")
acf(x, lag.max=20)
# задание с курсом доллара
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
df <- read.csv("usd_volume.txt")
#summary(df$X.VOL.)
df <- data.frame(date=df$X.DATE., x = df$X.VOL.)
df$date <- as.Date(as.character(df$date), "%Y%m%d") # as.character преобразует в строчку числа
df <- df[df$x != 0, ]
# Лаги будем создавать внутри фрейма
TT <- nrow(df)
df <- within(df, # within - внутри датафрейма работаем.
{x1 <- c(x[1], x[-TT]) # 1-й лаг
x2 <- c(x1[1], x1[-TT]) # второй
x3 <- c(x2[1], x2[-TT])
x4 <- c(x3[1], x3[-TT])}
)
min(df$x)
plot(df$x ~ df$date, type="l")
acf(df$x) # автокорреляционная функция не угасает, медленно убывает. Похоже на нестационарность.
acf(df$x)[1] # первая автокорреляция
# Авторегрессия 1 порядка
reg1 <- lm(x ~ x1, data=df)
#plot.ts(resid(reg1)[1:50])
summary(reg1) # коэф. автокорреляции 0.688
reg2 <- lm(x ~ x1+x2, data=df)
summary(reg2)
reg3 <- lm(x ~ x1+x2+x3, data=df)
summary(reg3) # коэф. автокорреляции 0.688
reg4 <- lm(x ~ x1+x2+x3+x4, data=df)
summary(reg4)
library(lmtest)
library(sandwich) # ковар. матрица
coeftest(reg4, vcov=vcovHAC) # все коэф. значимы, все лаги нужны, укоротить нельзя.
# тест бройша-годфри
bgtest(reg4) # LM-test, 1 лаг был добавлен, p значение маленькое, 0 гипотезу отклоняем
bgtest(reg4, order=5) # жестко отклоняем
|
//
// IncomeTableViewController.swift
// BudgetView
//
// Created by Stef Castillo on 3/2/23.
//
import UIKit
class IncomeTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//MARK: - Outlets
@IBOutlet weak var incomeTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
CoreDataManager.shared.requestIncome()
incomeTableView.delegate = self
incomeTableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
CoreDataManager.shared.requestIncome()
incomeTableView.reloadData()
}
// override func viewDidAppear(_ animated: Bool) {
// super.viewDidAppear(animated)
// incomeTableView.reloadData()
// }
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CoreDataManager.shared.income.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "incomeCell", for: indexPath) as? IncomeTableViewCell
else { return UITableViewCell()}
let deposit = CoreDataManager.shared.income[indexPath.row]
cell.configure(with: deposit)
return cell
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footer = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 60))
footer.backgroundColor = UIColor(red: 59/255, green: 159/255, blue: 111/255, alpha: 1.0)
let titleLabel = UILabel(frame: CGRect(x: 15, y: 10, width: tableView.frame.width - 30, height: 20))
titleLabel.textAlignment = .center
// let screenWidth = UIScreen.main.bounds.width
let amountTotal = UILabel(frame: CGRect(x: 0, y: titleLabel.frame.maxY + 10, width: tableView.frame.width, height: 30))
footer.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleLabel.textColor = .white
titleLabel.text = "Monthly Income"
titleLabel.font = UIFont.systemFont(ofSize: 20)
amountTotal.font = UIFont.systemFont(ofSize: 20)
amountTotal.textColor = .white
amountTotal.textAlignment = .center
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
amountTotal.text = "$" + (formatter.string(from: NSNumber(value: CoreDataManager.shared.totalIncome())) ?? "0.00")
footer.layer.cornerRadius = 10
footer.addSubview(titleLabel)
footer.addSubview(amountTotal)
return footer
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let income = CoreDataManager.shared.income[indexPath.row]
CoreDataManager.shared.deleteIncome(income: income)
tableView.reloadData()
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toEditIncomeTransaction" {
guard let indexPath = incomeTableView.indexPathForSelectedRow,
let destinationVC = segue.destination as? AddTransactionViewController else { return }
let transactionToSend = CoreDataManager.shared.income[indexPath.row]
destinationVC.editTransaction = transactionToSend
destinationVC.isIncomeType = true
}
else if segue.identifier == "toTransactionVC" {
guard let destinationVC = segue.destination as? AddTransactionViewController else {
return
}
destinationVC.isIncomeType = true
}
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Campus - 360</title>
<link rel="stylesheet" href="style.css" />
<!-- Fontawesome Link for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" />
</head>
<body>
<!-- Header Start -->
<header>
<nav class="navbar container flex">
<h2 class="logo"><a href="/">CAMPUS - 360</a></h2>
<input type="checkbox" id="menu-toggler"/>
<label for="menu-toggler" id="hamburger-btn">
<i class="fa-solid fa-bars"></i>
</label>
<ul class="nav-links flex">
<li><a href="#home">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#contact">Contact Us</a></li>
<li><a href="https://mitujjain.ac.in/">Website</a></li>
</ul>
</nav>
</header>
<!-- Header End -->
<!-- HomePage Start -->
<section class="homepage" id="home">
<div class="content flex">
<div class="text">
<h1>Discover Your Future With Us</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum, quidem.</p>
</div>
<a href="#services">Our Services</a>
</div>
</section>
<!-- HomePage End -->
<!-- Service Start -->
<section class="services" id="services">
<div class="container">
<div class="section-title">
<h2>Our Services</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing.</p>
</div>
<ul class="cards flex">
<li class="card">
<img src="images/ExamPortalLogo.png" alt="ExamPortalLogo"/>
<h3>Online Exam Portal</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque inventore odit consectetur veniam temporibus tempore.</p>
</li>
<li class="card">
<img src="/images/Attendance_img.jpg" alt="Attendance_img"/>
<h3>Smart Attendance System</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque inventore odit consectetur veniam temporibus tempore.</p>
</li>
<li class="card">
<img src="images/Online_Class_img.jpg" alt="Online_Class_img"/>
<h3>Online Class Facility</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque inventore odit consectetur veniam temporibus tempore.</p>
</li>
</ul>
</div>
</section>
<!-- Service End -->
<!-- About Us Start -->
<section class="about" id="about">
<div class="container">
<div class="section-title">
<h2>About Us</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing.</p>
</div>
<div class="row company-info">
<h3>What We Offer</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatibus ipsum officiis animi, quia rem quod!</p>
<h3>Our Vision</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatibus ipsum officiis animi, quia rem quod!</p>
<div class="row team">
<h3>Our Team</h3>
<ul>
<li>John-Doe - Founder and CEO</li>
<li>Liam-Johnson - CTO</li>
<li>Oliver-Clark - Manager</li>
<li>Henry-Martinez - Lead and Product Development</li>
</ul>
</div>
</div>
</div>
</section>
<!-- About Us End -->
<!-- Contact -->
<section class="contact" id="contact">
<div class="container">
<div class="section-title">
<h2>Contact Us</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing.</p>
</div>
</div>
<div class="row flex">
<div class="col information">
<div class="contact-details">
<p><i class="fas fa-map-marker-alt"></i>New Delhi, India</p>
<p><i class="fas fa-envelope"></i>abc123@gmail.com</p>
<p><i class="fas fa-phone"></i>+91 - 1234567890</p>
<p><i class="fas fa-clock"></i>Monday - Friday: 9:00 AM - 5:00 PM</p>
<p><i class="fas fa-clock"></i>Saturday: 10:00 AM - 3:00 PM</p>
<p><i class="fas fa-clock"></i>Sunday - Closed</p>
<p><i class="fas fa-globe"></i>www.abcxyz.com</p>
</div>
</div>
<div class="col form">
<form action="#">
<input type="text" placeholder="Name*" required>
<input type="email" placeholder="Email*" required>
<textarea placeholder="Message*" required></textarea>
<button id="submit" type="submit">Send Message</button>
</form>
</div>
</div>
</section>
<!-- Footer Start -->
<footer class="footer">
<div class="container">
<span>Copyright © 2024 All Rights Reserved</span>
<br>
<span>Made By 𝓘𝓷𝓭𝓲𝓪𝓷 𝓓𝓮𝓿𝓮𝓵𝓸𝓹𝓮𝓻</span>
</div>
</footer>
<!-- Footer End -->
</body>
</html>
|
package Esercizio1;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {
int[] array = new int[5];
Random random = new Random();
for (int i = 0; i < 5; i++) {
array[i] = random.nextInt(1, 10) + 1;
}
System.out.println("Array iniziale: " + Arrays.toString(array));
Scanner scanner = new Scanner(System.in);
while (true) {
try {
System.out.print("Inserisci un numero: ");
int numeroInserito = scanner.nextInt();
if (numeroInserito == 0) {
break;
}
System.out.print("Inserisci una posizione (0-4): ");
int position = scanner.nextInt();
if (position < 0 || position > 4) {
throw new IllegalArgumentException("Posizione non valida");
}
array[position] = numeroInserito;
System.out.println("Nuovo stato dell'array: " + Arrays.toString(array));
} catch (IllegalArgumentException errore) {
System.out.println("Errore: " + errore.getMessage());
} catch (Exception errore) {
System.out.println("Errore: input non valido");
scanner.nextLine();
}
}
System.out.println("fine");
scanner.close();
}
}
|
/*
*
* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
* *
* * 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 org.opensingular.lib.commons.table;
import org.junit.Before;
import org.junit.Test;
import org.opensingular.lib.commons.views.format.ViewOutputExcel;
public class TableToolSimpleExcelTest extends TableToolSimpleBaseTest {
private TableOutputExcel tableOutputExcel;
private ViewOutputExcel viewOutputExcel;
public TableToolSimpleExcelTest() {
setOpenGeneratedFiles(false);
}
@Before
public void setUp() throws Exception {
viewOutputExcel = new ViewOutputExcel("X");
tableOutputExcel = new TableOutputExcel(viewOutputExcel);
}
@Test
@Override
public void testSimpleTable() {
testSimpleTable_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
@Test
@Override
public void testSimpleTable_withInvisibleColumn() {
testSimpleTable_withInvisibleColumn_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
@Test
@Override
public void testSimpleTable_dontShowTitle() {
testSimpleTable_dontShowTitle_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
@Test
@Override
public void testSimpleTable_empty1() {
testSimpleTable_empty1_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
@Test
@Override
public void testSimpleTable_empty2() {
testSimpleTable_empty2_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
@Test
@Override
public void testSimpleTable_withSuperTitle() {
testSimpleTable_withSuperTitle_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
@Test
@Override
public void testSimpleTable_withTotalizationLine1() {
testSimpleTable_withTotalizationLine1_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
@Test
@Override
public void testSimpleTable_withTotalizationLine2() {
testSimpleTable_withTotalizationLine2_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
@Test
@Override
public void testSimpleTable_withSuperTitleAndTotalization() {
testSimpleTable_withSuperTitleAndTotalization_build().generate(tableOutputExcel);
writeAndOpenIfEnabled();
}
public void writeAndOpenIfEnabled() {
generateFileAndShowOnDesktopForUser("xlsx", out -> {
viewOutputExcel.write(out);
});
}
}
|
#version 410 core
out vec4 FragColor;
in vec3 fragWorldPos;
in vec3 fragNormal;
in vec2 fragTexCoords;
struct PointLight {
vec4 position;
vec4 color;
};
// --- Uniforms
// Lights data
#define NUM_POINT_LIGHTS 4
uniform Scene_Lights {
PointLight pointLights[NUM_POINT_LIGHTS];
vec4 viewPos;
} scene;
// Material Textures
uniform sampler2D albedoMap;
uniform sampler2D metallicRoughnessMap;
// uniform sampler2D roughnessMap;
uniform sampler2D aoMap;
uniform sampler2D normalMap;
const float PI = 3.14;
// Forward declarations
vec3 fresnelSchlick(float cosTheta, vec3 F0);
float DistributionGGX(vec3 N, vec3 H, float roughness);
float GeometrySchlickGGX(float NdotV, float roughness);
float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness);
vec3 getNormalFromMap()
{
vec3 tangentNormal = texture(normalMap, fragTexCoords).xyz * 2.0 - 1.0;
vec3 Q1 = dFdx(fragWorldPos);
vec3 Q2 = dFdy(fragWorldPos);
vec2 st1 = dFdx(fragTexCoords);
vec2 st2 = dFdy(fragTexCoords);
vec3 N = normalize(fragNormal);
vec3 T = normalize(Q1*st2.t - Q2*st1.t);
vec3 B = -normalize(cross(N, T));
mat3 TBN = mat3(T, B, N);
return normalize(TBN * tangentNormal);
}
void main() {
// vec3 albedo = pow(texture(albedoMap, fragTexCoords).rgb, vec3(2.2));
vec3 albedo = texture(albedoMap, fragTexCoords).rgb;
float metallic = texture(metallicRoughnessMap, fragTexCoords).b;
float roughness = texture(metallicRoughnessMap, fragTexCoords).g;
float ao = texture(aoMap, fragTexCoords).r;
// vec3 norm = normalize(fragNormal); // N
vec3 norm = getNormalFromMap();
vec3 N = norm;
vec3 viewDir = normalize(vec3(scene.viewPos) - fragWorldPos); // V
vec3 V = viewDir;
vec3 F0 = vec3(0.04);
F0 = mix(F0, albedo, metallic);
vec3 Lo = vec3(0.0);
for (int i = 0; i < 4; ++i) {
vec3 lightVec = normalize(vec3(scene.pointLights[i].position) - fragWorldPos); // L
vec3 L = lightVec;
vec3 halfway = normalize(viewDir + lightVec); // H
vec3 H = halfway;
float distance = length(vec3(scene.pointLights[i].position) - fragWorldPos);
float attenuation = 1.0 / (distance * distance);
vec3 radiance = vec3(scene.pointLights[i].color) * attenuation;
// cook-torrance brdf
float NDF = DistributionGGX(norm, halfway, roughness);
float G = GeometrySmith(norm, viewDir, lightVec, roughness);
// vec3 F = fresnelSchlick(max(dot(halfway, viewDir), 0.0), F0);
vec3 F = fresnelSchlick(clamp(dot(H, V), 0.0, 1.0), F0);
vec3 numerator = NDF * G * F;
float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0) + 0.0001;
vec3 specular = numerator / denominator;
vec3 kS = F;
vec3 kD = vec3(1.0) - kS;
kD *= 1.0 - metallic;
// add to outgoing radiance Lo
float NdotL = max(dot(N, L), 0.0);
Lo += (kD * albedo / PI + specular) * radiance * NdotL;
// Lo += radiance;
}
vec3 ambient = vec3(0.03) * albedo * ao;
vec3 color = ambient + Lo; //ambient + Lo;
color = color / (color + vec3(1.0));
color = pow(color, vec3(1.0/2.2));
FragColor = vec4(color, 1.0);
// FragColor = vec4(1.0);
// FragColor = vec4(scene.pointLights[0].position);
// FragColor = vec4(albedo, 1.0);
// FragColor = vec4(pbr.metallic, pbr.roughness, pbr.ao, 1.0);
// FragColor = vec4(fragTexCoords, 0.0, 1.0);
}
/* The below are from https://learnopengl.com/PBR/Lighting */
vec3 fresnelSchlick(float cosTheta, vec3 F0) {
return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
}
float DistributionGGX(vec3 N, vec3 H, float roughness) {
float a = roughness*roughness;
float a2 = a*a;
float NdotH = max(dot(N, H), 0.0);
float NdotH2 = NdotH*NdotH;
float num = a2;
float denom = (NdotH2 * (a2 - 1.0) + 1.0);
denom = PI * denom * denom;
return num / denom;
}
float GeometrySchlickGGX(float NdotV, float roughness)
{
float r = (roughness + 1.0);
float k = (r*r) / 8.0;
float num = NdotV;
float denom = NdotV * (1.0 - k) + k;
return num / denom;
}
float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness)
{
float NdotV = max(dot(N, V), 0.0);
float NdotL = max(dot(N, L), 0.0);
float ggx2 = GeometrySchlickGGX(NdotV, roughness);
float ggx1 = GeometrySchlickGGX(NdotL, roughness);
return ggx1 * ggx2;
}
|
package com.example.superherowithcoroutines
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class MyRecycleViewAdapter(private val superhero: List<SuperheroResponse>?) :
RecyclerView.Adapter<MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val listItemViewHolder = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item_layout, parent, false)
return MyViewHolder(listItemViewHolder)
}
override fun getItemCount(): Int = superhero?.size!!
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.title.text = superhero?.get(position)?.name
holder.work.text = superhero?.get(position)?.work?.occupation
Glide.with(holder.itemView)
.load(superhero?.get(position)?.images?.xs)
.into(holder.image)
holder.itemView.setOnClickListener {
val mainActivity = it.context as AppCompatActivity
val detailsFragment = DetailsFragment()
detailsFragment.setSuperHero(superhero?.get(position))
mainActivity.supportFragmentManager.beginTransaction()
.add(R.id.list, detailsFragment)
.addToBackStack("Details_Fragment")
.commit()
}
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title: TextView = itemView.findViewById(R.id.superheroName)
val work: TextView = itemView.findViewById(R.id.superheroDesc)
val image: ImageView = itemView.findViewById(R.id.superheroImage)
}
|
package main
import (
"database/sql"
"fmt"
"html/template"
"log"
"net/http"
"os"
)
var db *sql.DB
func rollHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles("simple_list.html")
if err != nil {
log.Fatal(err)
}
books, err := dbGetCars()
if err != nil {
log.Fatal(err)
}
t.Execute(w, books)
}
}
func addAutoHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles("simple_form.html")
if err != nil {
log.Fatal(err)
}
t.Execute(w, nil)
} else {
r.ParseForm()
name := r.Form.Get("name")
country := r.Form.Get("country")
year := r.Form.Get("year")
price := r.Form.Get("price")
err := dbAddCar(name, country, year, price)
if err != nil {
log.Fatal(err)
}
}
}
func searchAutoHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles("simple_search.html")
if err != nil {
log.Fatal(err)
}
t.Execute(w, nil)
} else {
t, err := template.ParseFiles("simple_search.html")
r.ParseForm()
name := r.Form.Get("name")
cars, err := dbSearchCar(name)
if err != nil {
log.Fatal(err)
}
t.Execute(w, cars)
}
}
func GetPort() string {
var port = os.Getenv("PORT")
if port == "" {
port = "4747"
fmt.Println(port)
}
return ":" + port
}
func main() {
err := dbConnect()
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", rollHandler)
http.HandleFunc("/add", addAutoHandler)
http.HandleFunc("/search", searchAutoHandler)
log.Fatal(http.ListenAndServe(GetPort(), nil))
}
|
Эффективность техники сканирования портов
Эффективность техники измеряется в ее:
Скорости
Скрытности
Качестве результатов
Как повысить эффективность техники
1. Для оптимизации скорости сканирования — можно использовать шаблоны управления временем с помощью ключа -Т. Возможные варианты: paranoid(0), sneaky(1), polite(2), normal(3), aggressive(4) и insane(5).
Первые два помогают уклоняться от идентификации атакующего. 2 режим замедляет сканирование. 3 режим — по умолчанию, то есть никакой оптимизации не будет по данному ключу. 4 режим ускоряет сканирование. 5 режим очень быстро сканирует, но есть вероятность в потере точности при сканировании.
Пример: nmap -Т4 <example.com>.
Также возможна ситуация, когда нужно получить быстрый и максимально информативный результат сканирования сетевых портов. Для этого можно использовать ключ --top-ports <количество_портов>. Данный ключ сканирует заданное количество портов по рейтингу их популярности. Так же можно использовать ключ -F, который позволяет использовать сетевые пакеты минимального объёма. Ещё возможна ситуация, когда нас интересует лишь конкретные порты узла. Для этого можно использовать ключ -p <номер_порта>.
Список популярных сетевых портов
На сетевых периметрах часто встречаются UDP-сервисы DNS (53), NTP (123), SNMP (161), VPN (500, 1194, 4500), RDG (3391). Реже встречаются сервисные службы типа echo (7), discard (9), chargen (19), а также DAYTIME (13), TFTP (69), SIP (5060), сервисы NFS (2049), RPC (111, 137-139, 761 и др.), СУБД (1434).
Расширенный список:
21 — ftp
22 — ssh
23 — telnet
80, 8000, 8001, 8002, 8004, 8006, 8007, 8008, 8080, 8888 — http
88 — kerberos
139 — netbios
143 — imap
389 — ldap
443, 8443, 9443 — https
445 — smb
623, 49152 — ipmi
636 — ldaps
873 — rsync
1099 — websphere
1433, 1434 — mssql
1500 — tivoli_storage_manager
1540, 1541 — 1С
2001, 2010 — ibm_http
2181 — zookeeper
2222 — ansible
2375, 2376 — docker
2379 — k8s etcd
2809, 9043, 9060, 9080, 9501, 9502, 9503 — websphere
5558, 5559 — websphere_java_messaging_serevice
7873 — websphere_rds_client
8879 — websphere_soap
3306 — mysql
3389 — rdp
4678 — cisco smart install
4899 — radmin
5800 — 5810,5900,5901 — vnc
5432, 5433 — postgresql
5555 — hp_data_protector
5557 — citrix
5666 — nagious
8291 — mikrotik
10050, 10051 — zabbix
7001 — weblogic
9000 — clickhouse
27017, 27018 — mongodb
50013 — sap
1521 — 1527 — oracle
3200 — 3299 — sap
4786 — cisco_smart_install
9200, 9300 — elasticsearch
5985, 5986 — winrm
50070 — hdfs_ui
6443 — k8s
8111 — click_house
8500, 8501 — consul
8200, 8201 — vault
10250, 10255 — k8s
Увеличению скорости сканирования способствует флаг -n, который говорит, что не надо преобразовывать адреса обнаруженных узлов в DNS - адреса.
********************* important ***************************
2. Для лучшей скрытности сканирования — в локальных сетях можно использовать ключ -spoof-mac для изменения MAC адреса атакующего узла и флаг -S для изменения его IP адреса.
3. Качество результатов
Если стоит задача проверить все возможные номера сетевых портов, то следует использовать ключ -p-.
********************* important ***************************
Если очень много информации о результате сканирования, то для удобства изучения можно перенаправить вывод информации в текстовый файл с помощью ключа -oN <имя_файла>
Если есть список IP адресов, которые подлежат проверке состояния их сетевых портов, то можно использовать ключ -iL <имя_файла>, где в качестве имени файла передаётся файл с нужными IP адресами.
4. Комбинации
Улучшить технику сканирования можно за счёт использования сильных сторон тех или иных инструментов и комбинирования их между собой.
Пример: nmap сканирует сетевые порты довольно медленно, но качественно, с помощью этого инструмента можно уточнять состояния портов. Но перед этим можно просканировать узел или узлы с помощью намного более быстрого инструмента — masscan и после этого лишь уточнить достоверность его результатов сканирования с помощью nmap.
У nmap есть свой набор скриптов, которые способны дать определённую информацию при сканировании. Они делятся на следующие типы: safe, (intrusive), malware, version, discovery, vuln, auth и default. Что бы при сканировании работал какой — то конкретный скрипт или группа скриптов, то следует запускать с ключом —script.
Пример: sudo nmap --script <категории - скриптов>|<директория>|<имя_файла>|all <example.com>.
Также, возможно, некоторым скриптам нужно передавать значения. Это делается следующим образом: —script-args <имя1>=<значение1>, <имя2>={<имя3>=<значение3>}, <имя4>=<значение4>. Данные скрипты позволяют выполнять параллельные действия над сканируемыми сетевыми портами.
Также для улучшения техники сканирования можно комбинировать различные ключи, которые позволяют эффективнее исследовать большую совокупность узлов за один раз:
********************* important ***************************
Ключ -sV позволяет узнать версию используемых служб.
Ключ -sL позволяет определить имя сетевого узла, сканирование которого и происходит.
Ключ -v выводит подробную информацию о результатах сканирования.
Ключ -6 позволит использовать при сканировании IPv6 вместо IPv4.
Ключ -Pn позволяет отключить проверки доступности узла с помощьюICMPпакетов, так как некоторые FireWall настроены на откидывание данных пакетов, в следствии чего не удастся просканировать узел. Однако данный ключ замедляет сканирование системы.
Также можно использовать нестандартные методики сканирования для улучшения результата, например, сканирование с помощью кастомизации флагов: данный тип сканирования родился из особенностей реализации протоколов по соглашению RFC. Суть метода в том, что открытие/закрытие порта можно выявить с помощью особенности: любой пакет, не содержащий установленного бита SYN, RST или ACK, повлечет за собой отправку RST в ответ в случае, если порт закрыт, или не повлечет никакого ответа, если порт открыт. Если ни один из этих битов не установлен, то любая комбинация трех оставшихся (FIN, PSH и URG) будет являться правильной. В nmap для этого используются следующие ключи:
Null сканирование (-sN): не устанавливаются никакие биты (Флагов в TCP заголовке 0).
FIN сканирование (-sF): устанавливается только TCP FIN бит.
Xmas сканирование (-sX): устанавливаются FIN, PSH и URG флаги.
TCP ACK сканирование (-sA): данный тип сканирование направлен на изучение особенностей реагирования Firewall. Если порт не фильтруется, то будет возвращаться TCP ответ с флагом RST.
TCP Window сканирование (-sW): данный тип сканирование похож сутью работы на TCP ACK, но при этом способен отпределять, закрыт или открыт порт за счёт анализа поля TCP Window в RST ответе. В некоторых системах открытые порты используют положительное значение этого поля (даже в RST пакетах), а закрытые — нулевое.
TCP сканирование Мэймона (-sM): этот тип сканирования носит имя своего первооткрывателя, Уриела Мэймона. Техника практически такая же, как и при NULL, FIN и Xmas сканированиях, только в качестве запросов используются запросы FIN/ACK. Согласно RFC 793 (TCP), в ответ на такой запрос должен быть сгенерирован RST пакет, если порт открыт или закрыт. Однако многие BSD системы просто отбрасывают пакет, если порт открыт.
Зомби сканирование (-sI): данный метод сканирование позволяет полностью анонимно просканировать узел на информацию о состояние портов, так как сканирование происходит от лица другого узла.
FTP bounce сканирование (-b): данный метод сканирования основан на возможности одного FTP сервера обмениваться файлами с другим FTP сервером. Этот метод позволяет достигнуть анонимности, но сейчас крайне мало шансов, что он сработает, так как многие FTP сервера пере конфигурированы так, что они не могут отправлять между собой файлы.
5. Дополнительные материалы
Ссылка на официальную документацию: https://nmap.org/man/ru/
|
require 'spec_helper'
require 'timecop'
require 'active_support/core_ext/time' # So we can use Time.zone.today
require 'app/facades/listing_dance_classes'
RSpec.describe ListingDanceClasses do
class FakeDanceClassFinder
def by_day
[]
end
end
before do
Time.zone = 'Europe/London'
stub_const('DanceClassFinder', FakeDanceClassFinder)
end
describe '#days' do
it 'has monday as the first day' do
item = described_class.new.days.first
expect(item.as_id).to eq 'monday'
expect(item.title).to eq 'Monday'
end
it "includes monday's dance classes" do
monday_dance_classes = double('monday dance classes')
tuesday_dance_classes = double('tuesday dance classes')
fake_dance_class_finder = instance_double('DanceClassFinder')
allow(fake_dance_class_finder).to receive(:by_day).and_return(
1 => monday_dance_classes,
2 => tuesday_dance_classes
)
item = described_class.new(fake_dance_class_finder).days.first
expect(item.classes).to eq monday_dance_classes
end
it 'has tuesday as the second day' do
item = described_class.new.days[1]
expect(item.as_id).to eq 'tuesday'
expect(item.title).to eq 'Tuesday'
end
it "includes tuesday's dance classes" do
monday_dance_classes = double('monday dance classes')
tuesday_dance_classes = double('tuesday dance classes')
fake_dance_class_finder = instance_double('DanceClassFinder')
allow(fake_dance_class_finder).to receive(:by_day).and_return(
1 => monday_dance_classes,
2 => tuesday_dance_classes
)
item = described_class.new(fake_dance_class_finder).days[1]
expect(item.classes).to eq tuesday_dance_classes
end
it 'has wednesday as the third day' do
item = described_class.new.days[2]
expect(item.as_id).to eq 'wednesday'
expect(item.title).to eq 'Wednesday'
end
it "includes wednesday's dance classes" do
monday_dance_classes = double('monday dance classes')
wednesday_dance_classes = double('wednesday dance classes')
fake_dance_class_finder = instance_double('DanceClassFinder')
allow(fake_dance_class_finder).to receive(:by_day).and_return(
1 => monday_dance_classes,
3 => wednesday_dance_classes
)
item = described_class.new(fake_dance_class_finder).days[2]
expect(item.classes).to eq wednesday_dance_classes
end
it 'has thursday as the 4th day' do
item = described_class.new.days[3]
expect(item.as_id).to eq 'thursday'
expect(item.title).to eq 'Thursday'
end
it "includes thursday's dance classes" do
monday_dance_classes = double('monday dance classes')
thursday_dance_classes = double('thursday dance classes')
fake_dance_class_finder = instance_double('DanceClassFinder')
allow(fake_dance_class_finder).to receive(:by_day).and_return(
1 => monday_dance_classes,
4 => thursday_dance_classes
)
item = described_class.new(fake_dance_class_finder).days[3]
expect(item.classes).to eq thursday_dance_classes
end
it 'has friday as the 5th day' do
item = described_class.new.days[4]
expect(item.as_id).to eq 'friday'
expect(item.title).to eq 'Friday'
end
it "includes friday's dance classes" do
monday_dance_classes = double('monday dance classes')
friday_dance_classes = double('friday dance classes')
fake_dance_class_finder = instance_double('DanceClassFinder')
allow(fake_dance_class_finder).to receive(:by_day).and_return(
1 => monday_dance_classes,
5 => friday_dance_classes
)
item = described_class.new(fake_dance_class_finder).days[4]
expect(item.classes).to eq friday_dance_classes
end
it 'has saturday as the 6th day' do
item = described_class.new.days[5]
expect(item.as_id).to eq 'saturday'
expect(item.title).to eq 'Saturday'
end
it "includes saturday's dance classes" do
monday_dance_classes = double('monday dance classes')
saturday_dance_classes = double('saturday dance classes')
fake_dance_class_finder = instance_double('DanceClassFinder')
allow(fake_dance_class_finder).to receive(:by_day).and_return(
1 => monday_dance_classes,
6 => saturday_dance_classes
)
item = described_class.new(fake_dance_class_finder).days[5]
expect(item.classes).to eq saturday_dance_classes
end
it 'has sunday as the last day' do
item = described_class.new.days[6]
expect(item.as_id).to eq 'sunday'
expect(item.title).to eq 'Sunday'
end
it "includes sunday's dance classes" do
monday_dance_classes = double('monday dance classes')
sunday_dance_classes = double('sunday dance classes')
fake_dance_class_finder = instance_double('DanceClassFinder')
allow(fake_dance_class_finder).to receive(:by_day).and_return(
1 => monday_dance_classes,
0 => sunday_dance_classes
)
item = described_class.new(fake_dance_class_finder).days[6]
expect(item.classes).to eq sunday_dance_classes
end
it 'exposes when the day is today' do
black_monday = Date.new(1987, 10, 19)
Timecop.freeze(black_monday) do
item = described_class.new.days.first
expect(item.today?).to eq true
end
end
it 'exposes when the day is not today' do
black_monday = Date.new(1987, 10, 19)
Timecop.freeze(black_monday) do
item = described_class.new.days[1]
expect(item.today?).to eq false
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.