text
stringlengths 184
4.48M
|
---|
//
// PetEggModel.swift
// CollectionCreatures Watch App
//
// Created by Nick Gordon on 9/22/23.
//
import Foundation
import SwiftUI
enum Rarity {
case noEgg
case uncommon
case rare
case ultraRare
}
struct EggModel: Identifiable, Hashable, Equatable {
var id = UUID()
var eggTop:String = "commonEggtop"
var eggBottom:String = "commonEggBottom"
var wholeEgg:String = "uncommonEgg"
var eggRarity:Rarity
var caloriesNeeded: Int
var currentCaloriesBanked:Int = 0
var isCurrentlySelected: Bool = false
init(id: UUID = UUID(), eggRarity: Rarity) {
self.id = id
self.eggRarity = eggRarity
switch eggRarity {
case .uncommon:
self.eggTop = "commonEggTop"
self.caloriesNeeded = 500
self.eggBottom = "commonEggBottom"
self.wholeEgg = "uncommonEgg"
case .rare:
self.caloriesNeeded = 1500
self.wholeEgg = "rareEgg"
case .ultraRare:
self.caloriesNeeded = 3000
self.wholeEgg = "ultraRareEgg"
self.eggTop = "ultraRareEggTop"
self.eggBottom = "ultraRareEggBottom"
case .noEgg:
// self.eggColor = ""
self.caloriesNeeded = 2000
}
}
static let exampleCommon = EggModel(eggRarity: .ultraRare)
static let exampleUncommon = EggModel(eggRarity: .uncommon)
static let exampleRare = EggModel(eggRarity: .rare)
static let noEggSelected = EggModel(eggRarity: .noEgg)
} |
import React from "react";
import "./Definitions.css";
const Definitions = ({ word, meanings, category, Dark }) => {
return (
<div className="meanings">
<div className="audio">
{meanings[0] && word && category === "en" && (
<audio
src={meanings[0].phonetics[0] && meanings[0].phonetics[0].audio}
style={{
backgroundColor: "#fff",
borderRadius: "10px",
}}
controls
>
Your Browser does not support audio element.
</audio>
)}
</div>
{word === "" ? (
<span className="subTitle">Start by typing a word in Search</span>
) : (
meanings.map((mean) =>
mean.meanings.map((item) =>
item.definitions.map((def) => (
<div
className="singleMean"
style={{
backgroundColor: Dark ? "white" : "#282c34",
color: Dark ? "black" : "white",
}}
>
<b>{def.definition}</b>
{def.example && (
<div>
<b>Example : </b>
{def.example}
</div>
)}
{def.synonyms && (
<div>
<b>Synonyms : </b>
{def.synonyms + ", "}
</div>
)}
</div>
))
)
)
)}
</div>
);
};
export default Definitions; |
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using Practica2023.Business;
using Practica2023.Business.Contracts;
using Practica2023.Data.Repositories;
using Practica2023.Helpers;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Add JWT authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<ICategoryRepository, CategoryRepository>();
builder.Services.AddTransient<IConnectionString>(x => new ConnectionString(builder.Configuration.GetConnectionString("DefaultConnectionString")));
builder.Services.AddTransient<IProductRepository, ProductRepository>();
builder.Services.AddTransient<IConnectionString>(x => new ConnectionString(builder.Configuration.GetConnectionString("DefaultConnectionString")));
builder.Services.AddTransient<IAdminRepository, AdminRepository>();
builder.Services.AddTransient<IConnectionString>(x => new ConnectionString(builder.Configuration.GetConnectionString("DefaultConnectionString")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(x => x.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run(); |
const gameBoard = document.querySelector("#gameBoard");
const ctx = gameBoard.getContext("2d");
const scoreText = document.querySelector("#scoreText");
const resetBtn = document.querySelector("#resetBtn")
const gameWidth = gameBoard.width;
const gameHeight = gameBoard.height;
const boardBackground = "white";
const snakeColor = "wheat";
const snakeBorder="black";
const foodColor = "red";
const unitSize = 25;
let running = false;
let xVelocity = unitSize;
let yVelocity =0;
let foodX;
let foodY;
let score =0;
let snake =[
{x:unitSize*4,y:0},
{x:unitSize*3,y:0},
{x:unitSize*2,y:0},
{x:unitSize,y:0},
{x:0,y:0}
];
window.addEventListener("keydown",changeDirection);
resetBtn.addEventListener("click",resetGame);
gameStart()
function gameStart(){
running = true;
scoreText.textContent = score;
createFood();
drawFood();
nextTick();
}
function nextTick(){
if(running){
setTimeout(()=>{
clearBoard();
drawFood();
moveSnake();
drawSnake();
checkGameOver();
nextTick();
}, 100)
}else{
displayGameOver()
}
}
function clearBoard(){
ctx.fillStyle=boardBackground;
ctx.fillRect(0,0,gameWidth,gameHeight)
}
function createFood(){
function randomFood(min,max){
const randNum =Math.round((Math.random()*(max-min)+min)/unitSize)*unitSize
return randNum;
}
foodX =randomFood(0,gameWidth-unitSize)
foodY =randomFood(0,gameWidth-unitSize)
}
function drawFood() {
ctx.fillStyle =foodColor;
ctx.fillRect(foodX,foodY,unitSize,unitSize)
}
function moveSnake(){
const head={x:snake[0].x + xVelocity,
y:snake[0].y + yVelocity};
snake.unshift(head)
if(snake[0].x ==foodX && snake[0].y==foodY){
score+=1;
scoreText.textContent=score;
createFood();
}else{
snake.pop();
}
}
function drawSnake(){
ctx.fillStyle = snakeColor;
ctx.strokeStyle = snakeBorder;
snake.forEach((snakePart)=>{
ctx.fillRect(snakePart.x, snakePart.y,unitSize,unitSize)
ctx.strokeRect(snakePart.x, snakePart.y,unitSize,unitSize)
})
}
function changeDirection(event){
const keyPressed = event.keyCode;
const LEFT =37
const UP = 38
const RIGHT = 39
const DOWN = 40
const goingUp =(yVelocity == -unitSize);
const goingDown = (yVelocity == unitSize);
const goingRight = (xVelocity == unitSize);
const goingLeft = (xVelocity == -unitSize);
switch(true){
case(keyPressed == LEFT && !goingRight):
xVelocity = -unitSize;
yVelocity = 0
break;
case(keyPressed == UP && !goingDown):
xVelocity = 0;
yVelocity = -unitSize
break;
case(keyPressed == RIGHT && !goingLeft):
xVelocity = unitSize;
yVelocity = 0
break;
case(keyPressed == DOWN && !goingUp):
xVelocity = 0;
yVelocity = unitSize;
break;
}
}
function checkGameOver(){
switch(true){
case (snake[0].x <0):
running =false;
break;
case (snake[0].x >=gameWidth):
running =false;
break;
case (snake[0].y <0):
running =false;
break;
case (snake[0].y >=gameHeight):
running =false;
break;
}
for (let i = 1; i < snake.length; i+=1){
if(snake[i].x == snake[0].x && snake[i].y == snake[0].y) {
running = false
}
}
}
function displayGameOver(){
ctx.font="50px MV Boli"
ctx.fillStyle ="black"
ctx.textAlign = "center"
ctx.fillText("GAME OVER!!!", gameWidth/2, gameHeight/2)
running =false
}
function resetGame(){
score = 0;
xVelocity = unitSize;
yVelocity = 0;
snake =[
{x:unitSize*4,y:0},
{x:unitSize*3,y:0},
{x:unitSize*2,y:0},
{x:unitSize,y:0},
{x:0,y:0}
];
gameStart()
}
function changeDir(clicked_id){
const id = clicked_id
const goingUp =(yVelocity == -unitSize);
const goingDown = (yVelocity == unitSize);
const goingRight = (xVelocity == unitSize);
const goingLeft = (xVelocity == -unitSize);
switch(true){
case(id == "left" && !goingRight):
xVelocity = -unitSize;
yVelocity = 0
break;
case(id == "up" && !goingDown):
xVelocity = 0;
yVelocity = -unitSize
break;
case(id == "right" && !goingLeft):
xVelocity = unitSize;
yVelocity = 0
break;
case(id == "down" && !goingUp):
xVelocity = 0;
yVelocity = unitSize;
break;
}
} |
import { Link, Outlet } from "react-router-dom";
import { useParams } from "react-router-dom";
import React, { useEffect, useState } from "react";
import getPostDetails from "../getRequests/getPostDetails";
import Moment from "moment";
import addIcon from "../../assets/add.png";
const PostDetails = ({ currentUser, postViewed }) => {
const { postDetails, error, loading } = getPostDetails(postViewed);
if (error) return <p>A Network Error has occurred. </p>;
if (loading) return <p>Loading...</p>;
return (
<div className="page">
<h1 className="pageTitle">Post Details</h1>
{currentUser ? (
<div className="postDetails">
<br />
<div className="postDetailTitleBox">
<h2>Title:</h2>
<h2 className="postDetailTitle">{postDetails.post.title}</h2>
</div>
<div className="postDetailTextBox">
<h2>Post:</h2>
<h2 className="postDetailText">{postDetails.post.text}</h2>
</div>
<br />
<div className="postDetailCommentBox">
<div className="headerBox">
<Link className="addButtonBox" to="/blog/newComment">
<img
src={addIcon}
alt="link to update profile"
className="addIcon"
/>
</Link>
<h2 className="tableHeader">Comments:</h2>
</div>
<div className="tableBox">
<table className="commentsTable">
<thead>
<tr>
<th>User</th>
<th>Created</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
{postDetails.comments.map((comment, index) => {
let timestamp = comment.timestamp;
timestamp = Moment(timestamp).format("MM/DD/YY");
return (
<tr key={comment._id}>
<td>{comment.user.username}</td>
<td>{timestamp}</td>
<td>{comment.text}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
) : (
<div className="signInMessage">
<p>Must be Signed In to view this page</p>
<div className="signInUp">
<Link to="/blog/sign-in" className="signInButton">
Sign In
</Link>
<Link to="/blog/sign-up" className="signInButton">
Sign Up
</Link>
</div>
</div>
)}
</div>
);
};
export default PostDetails; |
import { Duration, RemovalPolicy, Stack, StackProps } from 'aws-cdk-lib';
import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb';
import {
Architecture,
Code,
Function as LambdaFunction,
LayerVersion,
Runtime,
} from 'aws-cdk-lib/aws-lambda';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { RetentionDays } from 'aws-cdk-lib/aws-logs';
import { Bucket } from 'aws-cdk-lib/aws-s3';
import { BucketDeployment, Source } from 'aws-cdk-lib/aws-s3-deployment';
import { Construct } from 'constructs';
import { HttpApi, HttpMethod } from '@aws-cdk/aws-apigatewayv2-alpha';
import { HttpLambdaIntegration } from '@aws-cdk/aws-apigatewayv2-integrations-alpha';
import {
LambdaIntegration,
RestApi,
EndpointType,
} from 'aws-cdk-lib/aws-apigateway';
export interface HttpApis {
apiG: string;
arn: string;
url: string;
}
export class Csv2DDBStack extends Stack {
public functions: LambdaFunction[];
public httpApisA: HttpApis[] = [];
public httpApisB: HttpApis[] = [];
public httpApisC: HttpApis[] = [];
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const fileSize = 100; // 100 or 1000
const table = new Table(this, 'SalesTable', {
billingMode: BillingMode.PAY_PER_REQUEST,
partitionKey: { name: 'pk', type: AttributeType.STRING },
removalPolicy: RemovalPolicy.DESTROY,
sortKey: { name: 'sk', type: AttributeType.STRING },
tableName: 'Sales',
});
const bucket = new Bucket(this, 'SalesCsvBucket', {
autoDeleteObjects: true,
removalPolicy: RemovalPolicy.DESTROY,
});
new BucketDeployment(this, 'SalesCsvDeployment', {
destinationBucket: bucket,
sources: [Source.asset(`${__dirname}/../assets`)],
});
const lambdaProps = {
architecture: Architecture.ARM_64,
bundling: { minify: true, sourceMap: true, externalModules: [] },
environment: {
BUCKET_NAME: bucket.bucketName,
BUCKET_KEY: `${fileSize} Sales Records.csv`,
NODE_OPTIONS: '--enable-source-maps',
TABLE_NAME: table.tableName,
},
logRetention: RetentionDays.ONE_DAY,
memorySize: 512,
runtime: Runtime.NODEJS_14_X,
timeout: Duration.minutes(1),
};
const csv2ddbSdk2 = new NodejsFunction(this, 'csv2ddb-sdk2', {
...lambdaProps,
bundling: { ...lambdaProps.bundling },
description: `Reads ${fileSize} rows of CSV and writes to DynamoDB. Installs full aws-sdk v2.`,
entry: `${__dirname}/../fns/csv2ddb-sdk2.ts`,
functionName: 'csv2ddb-sdk2',
});
const csv2ddbSdk2Clients = new NodejsFunction(
this,
'csv2ddb-sdk2-clients',
{
...lambdaProps,
bundling: { ...lambdaProps.bundling },
description: `Reads ${fileSize} rows of CSV and writes to DynamoDB. Installs only clients from aws-sdk v2.`,
entry: `${__dirname}/../fns/csv2ddb-sdk2-clients.ts`,
functionName: 'csv2ddb-sdk2-clients',
}
);
const csv2ddbSdk2Native = new NodejsFunction(this, 'csv2ddb-sdk2-native', {
...lambdaProps,
bundling: { ...lambdaProps.bundling, externalModules: ['aws-sdk'] },
description: `Reads ${fileSize} rows of CSV and writes to DynamoDB. Uses native aws-sdk v2.`,
entry: `${__dirname}/../fns/csv2ddb-sdk2.ts`,
functionName: 'csv2ddb-sdk2-native',
});
const sdkLayer = new LayerVersion(this, 'SdkLayer', {
code: Code.fromAsset(`${__dirname}/../node_modules/aws-sdk`),
});
const csv2ddbSdk2Layer = new NodejsFunction(this, 'csv2ddb-sdk2-layer', {
...lambdaProps,
bundling: { ...lambdaProps.bundling, externalModules: ['aws-sdk'] },
description: `Reads ${fileSize} rows of CSV and writes to DynamoDB. Uses layer aws-sdk v2.`,
entry: `${__dirname}/../fns/csv2ddb-sdk2.ts`,
functionName: 'csv2ddb-sdk2-layer',
layers: [sdkLayer],
});
const csv2ddbSdk3 = new NodejsFunction(this, 'csv2ddb-sdk3', {
...lambdaProps,
bundling: { ...lambdaProps.bundling },
description: `Reads ${fileSize} rows of CSV and writes to DynamoDB. Uses modular aws sdk v3.`,
entry: `${__dirname}/../fns/csv2ddb-sdk3.ts`,
functionName: 'csv2ddb-sdk3',
});
this.functions = [
csv2ddbSdk2,
csv2ddbSdk2Clients,
csv2ddbSdk2Native,
csv2ddbSdk2Layer,
csv2ddbSdk3,
];
const httpApi = new HttpApi(this, 'BenchmarksHttpApi');
const restEdgeApi = new RestApi(this, 'BenchmarksRestEdgeApi', {
endpointConfiguration: { types: [EndpointType.EDGE] },
});
const restRegionalApi = new RestApi(this, 'BenchmarksRestRegionalApi', {
endpointConfiguration: { types: [EndpointType.REGIONAL] },
});
const restEdge = restEdgeApi.root.addResource('rest');
const restRegional = restRegionalApi.root.addResource('rest');
this.functions.forEach((fn) => {
bucket.grantRead(fn);
table.grantWriteData(fn);
const httpIntegration = new HttpLambdaIntegration(
`${fn.node.id}-httpIntegration`,
fn
);
const restIntegration = new LambdaIntegration(fn);
const httpRoute = httpApi.addRoutes({
integration: httpIntegration,
methods: [HttpMethod.GET],
path: `/http/${fn.node.id}`,
});
const restEdgeResource = restEdge.addResource(fn.node.id);
const restRegionalResource = restRegional.addResource(fn.node.id);
restEdgeResource.addMethod('GET', restIntegration);
restRegionalResource.addMethod('GET', restIntegration);
this.httpApisA.push({
url: `${httpApi.url}http/${fn.node.id}`,
arn: fn.functionArn,
apiG: 'HttpApi',
});
this.httpApisB.push({
url: `${restEdgeApi.url}rest/${fn.node.id}`,
arn: fn.functionArn,
apiG: 'RestEdgeApi',
});
this.httpApisC.push({
url: `${restRegionalApi.url}rest/${fn.node.id}`,
arn: fn.functionArn,
apiG: 'RestRegionalApi',
});
});
}
} |
import os
import django
import pdfplumber
import datetime
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "exam.settings")
django.setup()
from exam_schedule.models import ExamSchedule
pdf_path = r'H:\Uni work\Assignment\exam routine\exam\Final Schedule Fall 2023.pdf'
all_extracted_data = [] # To store data from all pages
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
tables = page.extract_tables()
for table in tables:
header = table[0] # Assuming the first row contains column headers
data = table[1:] # Remaining rows contain the data
if not all_extracted_data: # If it's the first page, just append all the data
for row in data:
if len(row) == len(header):
data_dict = {header[i]: row[i] for i in range(len(header))}
all_extracted_data.append(data_dict)
else:
data = data[1:] # Skip the header row on subsequent pages
for row in data:
if len(row) == len(header):
data_dict = {header[i]: row[i] for i in range(len(header))}
all_extracted_data.append(data_dict)
# Now you have a list of dictionaries containing the extracted data from all pages
# You can process and populate your Django database with this combined data
# for data in all_extracted_data:
# print(data) # This will print each row as a dictionary
for data in all_extracted_data:
data_dict = {
'sl': data['SL.'].strip(), # Use lowercase field names
'course': data['Course'].strip(),
'section': data['Section'].strip(),
'mid_date': datetime.datetime.strptime(data['Final Date'], '%d-%b-%y').date(),
'start_time': datetime.datetime.strptime(data['Start Time'], '%I:%M %p').time(),
'end_time': datetime.datetime.strptime(data['End Time'], '%I:%M %p').time(),
'room': data['Room.'].strip(),
'mode': data['Mode'].strip(),
}
exam_schedule = ExamSchedule(**data_dict)
exam_schedule.save() |
import * as Yup from 'yup';
const phoneRegExp = /^[7-9]\d{9}$/
const gstRegExp = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/;
export const PrescriptionSchema = Yup.object({
customerInfo:Yup.object().shape({
phoneNo: Yup.string().min(10,"Phone number must contains 10 numbers").max(12,"Phone number must contains less then 12 numbers").matches(phoneRegExp, 'Phone number is not valid').required("Please Enter Phone Number"),
customerName: Yup.string().min(3).max(25).required("Please Enter Customer Name"),
gstNumber: Yup.string()
.matches(gstRegExp, 'Invalid GST number'),
companyName: Yup.string().min(3).max(25),
line1:Yup.string(),
line2:Yup.string(),
customerNotes:Yup.string(),
}),
paitentInfo: Yup.object().shape({
paitentName: Yup.string().min(3, "Paitent's name must be at least 3 characters").max(25),
paitentPhoneNo: Yup.string().min(10, "Phone number must contain 10 numbers").max(12, "Phone number must contain less than 10 numbers").matches(phoneRegExp, 'Paitent Phone number is not valid'),
paitentEmail: Yup.string().email("Email must be a valid Email"),
paitentsBirthDate: Yup.date().nullable(),
paitentsAge: Yup.number().nullable(),
gender: Yup.string().oneOf(['male', 'female']),
}),
prescriptionInfo: Yup.object().shape({
cosmeticOption: Yup.string().oneOf(['Eyeware', 'Contact Lenses']),
doctorName: Yup.string().min(3).max(25),
prescriptionTime: Yup.string().nullable(),
LensType: Yup.string().oneOf(['Eyeware Prescription', 'Contact Lens Prescription', 'Transpose Prescription']),
cardDescription: Yup.string(),
}),
LenseNumbers: Yup.object().test(
'atLeastOneInputRequired',
'At least one input field is required',
(value) => {
const hasInput = Object.values(value).some((subObject) => {
return Object.values(subObject).some((subValue) => {
return Object.values(subValue).some((inputValue) => inputValue !== '');
});
});
return hasInput;
}
),
LenseUseType:Yup.array().min(1, 'Please select at least one hobby'),
prescriptionNotes:Yup.string(),
}) |
import React, {useEffect, useState} from 'react';
import "./auth.scss";
import Loader from "../../components/Loading/Loader";
import {Button, Card} from "@mui/material";
import {Link, useNavigate} from "react-router-dom";
import {BiLogIn} from "react-icons/bi";
import {TiUserAddOutline} from "react-icons/ti";
import {useDispatch} from "react-redux";
import {toast} from "react-toastify";
import {loginUser, registerUser, validateEmail} from "../../api/authService";
import {SET_LOGIN, SET_NAME} from "../../redux/features/auth/authSlice";
const Auth = () => {
const [isLoading, setIsLoading] = useState(false);
const [isSignUp, setIsSignUp] = useState(false);
const navigate = useNavigate();
const dispatch = useDispatch();
const [formData, setFormData] = useState({
name: "",
email: "",
password: "",
password2: ""
});
const {name, email, password, password2} = formData;
const switchMode = () => {
setIsSignUp((prevIsSignUp) => !prevIsSignUp);
}
const switchModeForgot = () => {
setIsSignUp((prevIsSignUp) => !prevIsSignUp);
navigate("/forgot");
}
const login = async (e) => {
e.preventDefault();
if (!email || !password) {
return toast.error("All fields are required");
}
if (!validateEmail(email)) {
return toast.error("Please enter a valid email");
}
setIsLoading(true);
try {
if (isSignUp) {
if (!name || !password2) {
return toast.error("All fields are required");
}
if (password !== password2) {
return toast.error("Passwords do not match");
}
const userData = { name, email, password };
await registerUser(userData);
} else {
await loginUser({ email, password });
}
await dispatch(SET_LOGIN(true));
await dispatch(SET_NAME(name));
navigate("/dashboard");
} catch (error) {
setIsLoading(false);
toast.error(error.response.data.message || "An error occurred");
}
};
const handleInputChange = (e) => {
const {name, value} = e.target;
setFormData({...formData, [name]: value});
}
return (
<>
<div className={"content"}>
<img src={`/img/reg2.jpg`} alt={"bg"}
style={{width: "100%", height: "100vh", position: "absolute", opacity: "0.6"}}
/>
<div className="home"><Link to={"/"}><img src="/img/home.png" alt=""/></Link></div>
<div className={`container`}>
{isLoading && <Loader/>}
<Card sx={{
minWidth: 600,
width: "50%",
height: "450px",
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(60%, 20%)"
}}>
<div>
<div className="bi">
{isSignUp ? <TiUserAddOutline size={35} color="#999"/> :
<BiLogIn size={35} color="#999"/>}
</div>
<h1>{isSignUp ? "Sign Up" : "Sign In"}</h1>
<form onSubmit={login} className={"form"}>
{!isSignUp &&
<><input
type='text'
placeholder="Email"
name="email"
value={email}
onChange={handleInputChange}
/>
<input
type="password"
placeholder="Password"
name="password"
value={password}
onChange={handleInputChange}
/></>
}
{isSignUp && (
<>
<input
type='text'
placeholder="Email"
name="email"
value={email}
onChange={handleInputChange}
/>
<input
type="text"
placeholder="Name"
name="name"
value={name}
onChange={handleInputChange}
/>
<input
type="password"
placeholder="Password"
name="password"
value={password}
onChange={handleInputChange}
/>
<input
type="password"
placeholder="Confirm Password"
name="password2"
value={password2}
onChange={handleInputChange}
/>
</>
)}
<Button type="submit" className="btnLogin" variant={"contained"}>
Submit
</Button>
<Button onClick={switchMode} className={"btnReg"}>
{isSignUp ? "Already have an account ? Sign In " : "Don't have an account ? Sign Up"}
</Button>
<Button onClick={switchModeForgot} className={"btnReg"}>
{isSignUp ? "Don't have an account ? Sign Up" : "Forgot Password ? Forgot Password "}
</Button>
</form>
</div>
</Card>
</div>
</div>
</>
);
};
export default Auth;; |
# can2040-rust
This is a port of [can2040 in C](https://github.com/KevinOConnor/can2040). Based on this, we can enable CAN on RP2040 with Rust.
## Run CAN demo
### Demo devices
- RP2040 dev board
- Waveshare SN65HVD230 board (CAN-board): [[Waveshare SN65HVD230](https://www.amazon.com/SN65HVD230-CAN-Board-Communication-Development/dp/B00KM6XMXO/ref=sr_1_2?crid=2I4ZLTIPIB93Q&keywords=SN65HVD230+waveshare&qid=1696911860&sprefix=sn65hvd230+waveshar%2Caps%2C146&sr=8-2)]
- USB-CAN Adapter (USB): [[Amazon](https://www.amazon.com/PRIZOM-Converter-Debugger-Analyzer-Candlelight/dp/B0CD6QFQXH/ref=sr_1_6?crid=2TGJJD1KV2Z36&keywords=CANable&qid=1696911666&sprefix=canable%2Caps%2C353&sr=8-6&th=1)]
### Wiring
- RP2040 GPIO 26 <=> CAN RX
- RP2040 GPIO 27 <=> CAN TX
- RP2040 GND <=> CAN GND
- RP2040 3V3 <=> CAN 3V3
- CAN CAN-H <=> USB CAN-H
- CAN CAN-L <=> USB CAN-L
### Run can2040_demo
The demo is run on Linux, using a relatively low baud rate of 10_000. After debugging, you can choose a higher baud rate yourself.
#### Make USB ready
Plug the USB into your computer and make sure the corresponding socket is enabled (here it corresponds to socket can0).
```shell
sudo ip link set down can0 && \
sudo ip link set can0 type can bitrate 10000 && \
sudo ip link set up can0
```
Then, run the following command to monitor the messages on the CAN bus for debugging:
```shell
candump can0
```
#### Run Can2040_demo on RP2040.
Make sure all the wiring is correct, and if you adjust the GPIOs, make sure the corresponding GPIOs in the code are adjusted as well. Once everything is ready, you can run the following command, and you should see RP2040 continuously sending CAN frames to the USB:
```shell
cargo run --release --example can2040_demo
```
#### Send to test the receive
Run the following command on your computer and make sure the RP2040 console window receives the information:
```shell
cansend can0 123#DEADBEEF12345678
```
### Some tips
- A logic analyzer can be connected to CAN-H / L in differential mode to obtain the correct CAN signals. The connection method is to connect CAN-H to the signal and CAN-L to GND.
- A dual-channel oscilloscope can also be connected to CAN-H/L to view the differential signal.
- Global common ground is not required. Even if the obtained signal is interfered with, SN65HVD230 can still extract the normal CAN signal for TX/RX. |
import "@testing-library/jest-dom";
import { MongoClient } from "mongodb";
import { formatInput } from "../app/page.js";
import { extractKeywords } from "../app/page.js";
import { generateCache } from "../app/page.js";
const { PythonShell } = require("python-shell");
/**
* This file contains testing for Trending Topics and caching using Jest, a JS testing framework (currently 60% code coverage)
* Each function is tested with one describe block, with multiple tests inside each using Jest's expect()
* Individual tests are implemented with it()
*
* beforeAll() and afterAll() are run before and after tests to connect and disconnect to a test database
*/
const connectionString =
"mongodb+srv://team8s:[email protected]/?retryWrites=true&w=majority";
let client;
let database;
let collection;
let dataArray;
beforeAll(async () => {
//runs before all tests, establish a connection to the MongoDB server
client = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await client.connect();
database = client.db("testing"); //specific smaller database with some test data and a separate cache
collection = database.collection("2022-09-28"); //test data
dataArray = await collection.find().toArray(); //all data from the test collection in an array
});
afterAll(async () => {
//runs after all tests are finished, closes connection
await client.close();
});
describe("formatInput", () => {
//private posts contain the string "zzz", these posts should be removed
it("removes all private posts", () => {
let outputString = formatInput(dataArray);
expect(outputString).toEqual(expect.not.stringContaining("zzz"));
});
it("removes all images", () => {
//images shouldn't be included
let outputString = formatInput(dataArray);
expect(outputString).toEqual(expect.not.stringContaining(".png"));
expect(outputString).toEqual(expect.not.stringContaining(".jpg"));
});
it("removes all newlines", () => {
//newline shouldn't be included
let outputString = formatInput(dataArray);
expect(outputString).toEqual(expect.not.stringContaining("\n"));
});
it("behaves correctly with no input", () => {
let outputString = formatInput([]);
expect(outputString).toEqual("");
});
});
describe("extractKeywords", () => {
//testing extracting keywords with machine learning
it("outputs keywords with multiple occurrences", () => {
let outputString = formatInput(dataArray);
let topPhrases = extractKeywords(outputString);
for (keyword in topPhrases) {
expect(outputString.split(keyword).length - 1).toBeGreaterThan(1); //keywords occur more than once in the input
}
});
it("handles empty string input", async () => {
let topPhrases = await extractKeywords("");
expect(topPhrases).toEqual([]);
});
it("handles empty input", async () => {
let topPhrases = await extractKeywords();
expect(topPhrases).toEqual([]);
}); //currently doesn't pass bc ["undefined",] is returned
it("handles Python script error", async () => {
//we create a python shell to run the keyword extractor, this tests if it throws an error
const mockRun = jest
.spyOn(PythonShell, "run")
.mockRejectedValue(new Error("simulated Python error")); //mock a Python shell error
let extractedKeywords;
try {
extractedKeywords = await extractKeywords(formatInput(dataArray));
} catch (error) {
expect(error.message).toBe("simulated Python error"); //expect to recieve the mocked error
} finally {
mockRun.mockRestore(); //clear mocks
}
expect(extractedKeywords).toBeUndefined(); //expect no output
});
});
describe("generateCache", () => {
//testing caching which is used all features, not just Trending Topics
it("adds data to cache database if its not already there", async () => {
let cacheCollection = client.db("testing").collection("test-cache"); //get cache (should be empty)
let postCollection = client.db("testing").collection("2022-09-28"); //get testing data
await generateCache(cacheCollection, postCollection, "2022-09-28"); //generate a cache for '2022-09-28'
let cache = await cacheCollection.find();
expect(cache).not.toBeNull(); //check that something was added to cache
await cacheCollection.deleteMany({}); //clear testing cache for the next tests
});
it("calls with incorrect date format are not added to cache", async () => {
//check that incorrect date format doesn't add to a cache
let cacheCollection = client.db("testing").collection("test-cache");
let postCollection = client.db("testing").collection("2022-09-28");
await generateCache(cacheCollection, postCollection, "9-28-22"); //'9-28-22' is an incorrect date format, the 9 needs a 0 in front
let cache = await cacheCollection.find();
expect(cache).toBeNull(); //should be empty
await cacheCollection.deleteMany({});
});
/*
it('adds data with correct date range', async () => { //check that the posts added to the cache are in the correct range
let cacheCollection = client.db('testing').collection('test-cache')
let postCollection = client.db('testing').collection('2022-10-01')
await generateCache(cacheCollection, postCollection, '2022-10-01')
let comparisonDate = new Date('2022-10-01').getTime() - (1000 * 60 * 60 * 24 * 15);
let cache = await cacheCollection.find()
let arr = await cache.toArray();
for (let doc of arr) {
let dateInt = new Date(doc.collectionDate).getTime() - (1000 * 60 * 60 * 24 * 15);
expect(dateInt).toBeGreaterThan(comparisonDate)
}
await cacheCollection.deleteMany({})
});*/
}); |
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>courses</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<style>
*{
padding: 0;
margin: 0;
font-family: sans-serif;
border: 0;
}
body {
background-image: url("https://ltdfoto.ru/images/2023/02/04/Ali-FON-2-2.jpg");
height: 100vh;
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
.btn{
text-align: right;
display: inline-block;
vertical-align: middle;
padding: 8px 16px;
background: #151D39;
border-radius: 8px;
font-family: inherit;
font-size: 5px;
text-decoration: none;
color: #fff;
}
.btn--md{
font-size: 30px;
}
</style>
</head>
<body>
<table class="table table-dark table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Course Name</th>
<th scope="col">Duration Month</th>
<th scope="col">Company Name</th>
<!-- <th scope="col">Groups</th>-->
<!-- <th scope="col">teacher</th>-->
<th scope="col">Update</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="course:${courses}">
<td th:text="${course.id}"></td>
<td th:text="${course.courseName}"></td>
<td th:text="${course.durationMonth}"></td>
<td th:text="${course.company.companyName}">Company Name</td>
<!-- <td><a th:href="@{/courses/groups/{id}(id=${course.getId()})}">Groups</a></td>-->
<!-- <td><a th:text="${course.teacher()}">Teacher</a></td>-->
<td><a th:href="@{/courses/update/{id}(id=${course.id})}">update</a></td>
<td><form th:method="delete" th:action="@{/courses/delete/{id}(id=${course.getId})}"
><input type="submit" value="delete"></form>
</td>
</tr>
</tbody>
</table>
<a class="btn btn--md" href="/courses/addCourse">
<img src="https://ltdfoto.ru/images/2023/02/04/15.png" alt="15.png" border="0" height="100" />
</a>
<br><br>
<a class="btn btn--md" href="/">
<img src="https://ltdfoto.ru/images/2023/02/04/16.png" alt="16.png" border="0" height="100" />
</a>
</body>
</html> |
package agenda;
import java.util.*;
/**
* Classe que cria uma agenda com varios contatos e realiza metodos apartir
* deles, como cadastrar um contato, exibir, listar, adicionar favoritos, listar
* eles e exibir.
*
* @author Rayane bezerra
*/
public class Agenda {
/**
* nome do contato.
*/
private String nome;
/**
* sobrenome do contato.
*/
private String sobreNome;
/**
* posicao que o contato deve ser adicionado no array de contatos.
*/
private int posicao;
/**
* telefone do contato.
*/
private String telefone;
/**
* array onde sera adicionado os contatos, que pertece a classe Contato.
*/
private Contato[] contatos;
/**
* array de 10 posicoes, onde sera armazenado os contatos favoritos.
*/
private Contato[] favoritos = new Contato[10];
/**
* Constroi um array contatos com 100 posices apartir de contatos.
*
* @param contatos recebe array de contatos.
*/
public Agenda() {
this.contatos = new Contato[100];
}
/**
* O metodo ira verificar se uma posicao e valida para cadastro ou nao. Para ser
* valida precisa estar entre 1 e 100, inclusive esses.
*
* @param posicao recebe a posicao no formato int..
* @return Caso a posicao esteja no intervalo entre 1 e 100, com ambos estendo
* incluidos retornara true, caso contrario retornara false.
*/
public boolean verificaPosicao(int posicao) {
return posicao > 0 && posicao < 101;
}
/**
* metodo que verifica se nome e sobrenome de um contato ja cadastrado, e igual
* a um novo contato que se deseja cadastrar. Mesmo que o contato esteja em
* posicao diferente, se o nome e sobrenome for o mesmo, ele e considerado
* igual.
*
* @param nome recebe o nome do contato no formato String.
* @param sobreNome recebe nome do sobrenome no formato String.
* @return true caso os contatos tenham nome e sobrenome iguais, caso o
* contrario retornara false.
*/
public boolean verificaNomeIguais(String nome, String sobreNome) {
String nomeAux = nome;
String sobrenomeAux = sobreNome;
for (int i = 0; i < contatos.length; i++) {
if (contatos[i] != null) {
if (contatos[i].getNome().equals(nomeaux) && contatos[i].getsobreNome().equals((sobrenomeaux))) {
return true;
}
}
}
return false;
}
/**
* O metodo cadastra um contato na agenda. Ele ira pegar a posicao que deseja
* ser cadastra e alocara o nome, sobrenome e telefone nessa posicao. Vale
* lembrar que so sera possivel cadastrar um contato caso a posicao seja valida.
*
* @param posicao recebe a posicao no formato int.
* @param nome recebe o nome do contato no formato String.
* @param sobreNome recebe o sobrenome do contato no formato String.
* @param telefone recebe o telefone do contato no formato String.
* @return "CADASTRO REALIZADO" caso o cadastro ocorra. "CONTATO JA CADASTRADO"
* caso o contato que se deseja cadastrar, ja esteja cadastrado.
* "POSICAO INVALIDA" caso a posicao que se deseja cadastrar seja
* invalida.
*/
public String cadastraContato(int posicao, String nome, String sobreNome, String telefone) {
String status = "POSICAO INVALIDA" + System.lineSeparator(); ;
if (verificaPosicao(posicao) && (verificaNomeIguais(nome, sobreNome) == false) {
Contato contato = new Contato(nome, sobreNome, telefone);
contatos[posicao - 1] = contato;
status = "CADASTRO REALIZADO" + System.lineSeparator();
} else {
status = "CONTATO JA CADASTRADO" + System.lineSeparator();
}
}
return status;
}
/**
* Método que exibi um contato, apartir da sua posicao na lista de contatos.
*
* @param posicao recebe a posicao no formato int.
* @return retorna o contato na formatacao " nome + sobrenome + telefone" caso a
* posicao inserida seja valida, no caso da posicao nao ser valida
* retorna a seguinte mensagem "POSICAO INVALIDA".
*/
public String exibeContato(int posicao) {
if (verificaPosicao(posicao) && contatos[posicao - 1] != null) {
if (favoritos[posicao - 1] != null
&& favoritos[posicao - 1].getNomeCompleto().equals(contatos[posicao - 1].getNomeCompleto())) {
return "<3" + " " + favoritos[posicao - 1].getNomeCompleto() + System.lineSeparator() + contatos[posicao - 1].getTelefone();
} else {
return contatos[posicao - 1].toString();
}
}
return "POSICAO INVALIDA!" + System.lineSeparator();
}
/**
* Metodo que lista todos os contatos existente na lista de contatos.
*
* @return todos os contatos da lista na seguinte formatacao " posicao + nome +
* sobrenome.
*/
public String listaContatos() {
String listaDosContatos = "";
for (int i = 0; i < contatos.length; i++) {
if (contatos[i] != null) {
listaDosContatos += i + 1 + " - " + contatos[i].getNomeCompleto() + System.lineSeparator();
}
}
return listaDosContatos;
}
/**
* metodo que adiciona contato em uma lista de favoritos.
*
* @param contato recebe contato
* @param posicao recebe a posicao que o contato deve ser favoritado na lista
* posicao
* @return uma string dizendo "CONTATO FAVORITO NA POSICAO" + posicao, caso o
* contato seja favoritado com sucesso.
*/
public String adicionaFavoritos(int contato, int posicao) {
favoritos[posicao - 1] = contatos[contato - 1];
return "CONTATO FAVORITADO NA POSIÇÃO " + posicao + "!";
}
/**
* Metodo que verifica se um contato ja esta na lista de favoritos.
*
* @return o metodo retornara true caso o contato ja esteja na lista de
* favoritos, e false caso nao esteja.
*/
public boolean verificaFavoritos() {
for (int i = 0; i < favoritos.length; i++) {
if (favoritos[i] != null && favoritos[i].getNomeCompleto().equals(contatos[i].getNomeCompleto())) {
return true;
}
}
return false;
}
/**
* Metodo que lista um favorito.
*
* @return contato favorito no formato " posicao + nome + sobrenome .
*/
public String favoritos() {
String listaFavoritos = "";
for (int i = 0; i < favoritos.length; i++) {
if (contatos[i] != null && favoritos[i] != null) {
listaFavoritos += i + 1 + " - " + favoritos[i].getNomeCompleto() + System.lineSeparator();
}
}
return listaFavoritos;
}
/**
* Metodo que remove um contato do array de contatos.
*
* @param posicao recebe a posicao no formato int.
* @return metodo que retornara "POSICAO INVALIDA" caso a posicao que o contato
* seja removido nao exista. caso isso nao ocorra, retornara apenas um
* System.lineSeparator().
*/
public String removeContato(int posicao) {
if (contatos[posicao - 1] == null) {
return "POSICAO INVALIDA" + System.lineSeparator();
}
contatos[posicao - 1] = null;
return System.lineSeparator();
}
} |
import 'package:flutter/material.dart';
class PasswordField extends StatefulWidget {
const PasswordField({
this.fieldKey,
this.hintText,
this.labelText,
this.helperText,
this.onSaved,
this.validator,
this.onFieldSubmitted,
this.textInputAction,
});
final Key fieldKey;
final String hintText;
final String labelText;
final String helperText;
final FormFieldSetter<String> onSaved;
final FormFieldValidator<String> validator;
final ValueChanged<String> onFieldSubmitted;
final TextInputAction textInputAction;
@override
_PasswordFieldState createState() => new _PasswordFieldState();
}
class _PasswordFieldState extends State<PasswordField> {
bool _obscureText = true;
@override
Widget build(BuildContext context) {
return new TextFormField(
key: widget.fieldKey,
obscureText: _obscureText,
maxLength: 16,
onSaved: widget.onSaved,
validator: widget.validator,
textInputAction: widget.textInputAction,
onFieldSubmitted: widget.onFieldSubmitted,
decoration: new InputDecoration(
border: const UnderlineInputBorder(),
filled: true,
icon: Icon(
Icons.lock,
color: Colors.blueAccent,
),
hintText: widget.hintText,
labelText: widget.labelText,
helperText: widget.helperText,
suffixIcon: new GestureDetector(
onTap: () {
setState(() {
_obscureText = !_obscureText;
});
},
child: new Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
color: Colors.orange),
),
),
);
}
} |
import connectToDB from "@/database";
import User from "@/model/user";
import { compare } from "bcryptjs";
import Joi from "joi";
import jwt from "jsonwebtoken";
import { NextResponse } from "next/server";
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().required(),
});
export const dynamic = "force-dynamic";
export async function POST(req) {
connectToDB();
const { email, password } = await req.json();
const { error } = schema.validate({email, password});
if (error) {
return NextResponse.json({
success: false,
message: error.details[0],
});
}
try {
const checkUser = await User.findOne({ email });
if (!checkUser) {
return NextResponse.json({
success: false,
message: "user not exist with given email",
});
}
const checkPassword = await compare(password, checkUser.password);
if (!checkPassword) {
return NextResponse.json({
success: false,
message: "wrong password",
});
}
const token = jwt.sign(
{
id: checkUser._id,
email: checkUser?.email,
role: checkUser?.role,
},
"default_secret_key",
{ expiresIn: "1d" }
);
const finalData = {
token,
user:{
name: checkUser.name,
email: checkUser.email,
role: checkUser.role,
_id: checkUser._id,}
};
return NextResponse.json({
success: true,
message: "login Successfull",
finalData,
});
} catch (e) {
console.log("error in webside while login");
return NextResponse.json({
success: false,
message: "some thing went wrong please try again latter",
});
}
} |
---
title: "\"[Updated] 2024 Approved Heating Up Your YouTube Videos with Top Winter Backdrops\""
date: 2024-06-06T13:47:28.800Z
updated: 2024-06-07T13:47:28.800Z
tags:
- ai video
- ai youtube
categories:
- ai
- youtube
description: "\"This Article Describes [Updated] 2024 Approved: Heating Up Your YouTube Videos with Top Winter Backdrops\""
excerpt: "\"This Article Describes [Updated] 2024 Approved: Heating Up Your YouTube Videos with Top Winter Backdrops\""
keywords: "Winter Video Heat,Snowy Backdrop Boost,Cold Season Editing,Chilly Scenery Gain,Winter YT Enhancement,Frosty Backgrounds,Icy Edits Popularity"
thumbnail: https://thmb.techidaily.com/77f34903e1df34b362b3683a958e0b57f8d631d69cf5a5eaeee681f0ad029756.jpg
---
## Heating Up Your YouTube Videos with Top Winter Backdrops
There’s something special about wintertime that makes us all want to get as cozy and as warm as possible. When you’re a YouTube creator, you should definitely take advantage of this desire and use a YouTube background video designed specifically with this in mind.
In this guide, we’ll go over how to get or make such a background and show you five incredible examples you can use now.
**YouTube Video Background** Creating realistic video scenes at your will is easy to complete with Filmora green screen removal.
[Create Video Backgrounds](https://tools.techidaily.com/wondershare/filmora/download/) [Create Video Backgrounds](https://tools.techidaily.com/wondershare/filmora/download/) [Learn Green Screen](https://tools.techidaily.com/wondershare/filmora/download/)

## What Is a YouTube Video Background?
A **YouTube video background** is a simple image or video that sits in place at the back of your videos. It’s just a simple background that can greatly impact your brand, presence, and style as a creator.
Even something as small as your **YouTube video thumbnail background** can strongly impact your results.
Obviously, choosing the right **custom YouTube background** is important. And, now that it’s winter, this requires a special approach.
## Why Are Seasonal Backgrounds Effective?
There are several important reasons why a seasonal YouTube video background or photo, and other elements are very effective and engage us more.
The main reasons include:
* Creates a meaningful connection;
* Boosts engagement with fellow winter lovers;
* Builds a better brand;
* Enhances everyone’s mood, especially during the holidays.
So, whenever you can and whenever there is an opportunity, don’t be afraid to use a seasonal **YouTube video background download**.
## Factors to Consider When Choosing a Background for YouTube Videos
Now, before we dive into the examples themselves and the tutorial on how to make the best backgrounds yourself, here are several factors you must consider before proceeding.
### Content Relevance
As a video creator, you must ensure to be consistent with your elements. This includes your **background tune for YouTube videos.** For example, if you’re talking about books in your video, including a bookshelf in the winter background makes all the difference.
### Audience Appeal
If you already have an audience, regardless of its size, you should definitely consider what they like and don’t like. You should then leverage this information to create highly appealing content for them and adjust your background scenery accordingly.
### Lighting and Visibility
Another thing you must ensure is to keep your background simple and not too distracting. Remember, even though you have the **best background for YouTube videos**, you still need to realize that it’s not the main focus of the video. It’s just there to make it better.
### Personal Branding
If you want to improve your brand identity and get your name known by more people, incorporate your logo, name, or something similar in the background. It will have a small but meaningful impact, and it’s easy to do.
### Editing
If you plan to shoot a YouTube live background and not some stock images or videos, then you must make sure it has enough headroom for editing later on. The best option here is to use a **green screen background for YouTube videos**.
## **5 Winter YouTube Background Ideas**
It’s finally time to have a look at some examples of highly effective and engaging YouTube video backgrounds for the winter season.
Enjoy!
* Snowy Landscape

* Festive Holiday Decor

* Cozy Indoor Settings

* Winter Cityscapes

* Animated Winter Scenes

## How to Create or Source Winter Backgrounds
If you want to make your own winter backgrounds or simply edit the ones you have, the most effective way is to use a beginner-friendly video editing platform, such as [Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit)
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later
This type of platform has all the necessary tools, templates, and presets for professionals to use but all of it is packed in a very easy-to-use interface that anyone can get the hang of.
Just follow these steps and you’ll have the perfect winter **background for YouTube** in no time.
##### Step 1
Download and install the Filmora video editing tool.
##### Step 2
Run the program and click on **“**New Project”. No need to create an account for this.

##### Step 3
Click on “Stock Media” and then type in “winter” in the Search Bar.

##### Step 4
Select your favorite background clip and drag it down to the Timeline.
That’s it! You won’t believe how many video clips you can use, all of which are extremely high-quality. As a result, you’ll have a professional video for free.
Now, if you want, you can freely edit these backgrounds as you wish. You can mess around with them as much as you want, use various tools to edit, and make the perfect result.
And don’t worry, if you mess up the background and don’t know how to restore it, just delete it from the timeline and drag it again from the Stock Media tab. It will be as good as new.
Once you’re done, simply export it and you’re done.
## Integrating Your Background Into Videos
Finally, once you have the perfect YouTube studio background, it’s time to glue it to your video and upload this masterpiece.
In order to do this, you will need to use a video editing platform once again. This is not optional as there is no other way to merge these clips.
Luckily, you now have Filmora downloaded and can easily make it happen.
So, here’s how to combine everything.
##### Step 1
Start up a New Project in Filmora.
##### Step 2
Click on **“**My Media” and then click in the middle of the small box to upload your background and your video clips.

##### Step 3
After uploading all the files, simply drag everything in a separate Track down on the Timeline.
##### Step 4
Export and upload to YouTube. That’s it!
## Summary
You’re now ready to make some outstanding Winter YouTube videos and bless everyone with amazing scenery and backgrounds that will make their hearts warm up. Not only do you have infinite backgrounds to choose from, you also know how to perfectly blend them in any of your videos.
Enjoy!
[Create Video Backgrounds](https://tools.techidaily.com/wondershare/filmora/download/) [Create Video Backgrounds](https://tools.techidaily.com/wondershare/filmora/download/) [Learn Green Screen](https://tools.techidaily.com/wondershare/filmora/download/)

## What Is a YouTube Video Background?
A **YouTube video background** is a simple image or video that sits in place at the back of your videos. It’s just a simple background that can greatly impact your brand, presence, and style as a creator.
Even something as small as your **YouTube video thumbnail background** can strongly impact your results.
Obviously, choosing the right **custom YouTube background** is important. And, now that it’s winter, this requires a special approach.
## Why Are Seasonal Backgrounds Effective?
There are several important reasons why a seasonal YouTube video background or photo, and other elements are very effective and engage us more.
The main reasons include:
* Creates a meaningful connection;
* Boosts engagement with fellow winter lovers;
* Builds a better brand;
* Enhances everyone’s mood, especially during the holidays.
So, whenever you can and whenever there is an opportunity, don’t be afraid to use a seasonal **YouTube video background download**.
## Factors to Consider When Choosing a Background for YouTube Videos
Now, before we dive into the examples themselves and the tutorial on how to make the best backgrounds yourself, here are several factors you must consider before proceeding.
### Content Relevance
As a video creator, you must ensure to be consistent with your elements. This includes your **background tune for YouTube videos.** For example, if you’re talking about books in your video, including a bookshelf in the winter background makes all the difference.
### Audience Appeal
If you already have an audience, regardless of its size, you should definitely consider what they like and don’t like. You should then leverage this information to create highly appealing content for them and adjust your background scenery accordingly.
### Lighting and Visibility
Another thing you must ensure is to keep your background simple and not too distracting. Remember, even though you have the **best background for YouTube videos**, you still need to realize that it’s not the main focus of the video. It’s just there to make it better.
### Personal Branding
If you want to improve your brand identity and get your name known by more people, incorporate your logo, name, or something similar in the background. It will have a small but meaningful impact, and it’s easy to do.
### Editing
If you plan to shoot a YouTube live background and not some stock images or videos, then you must make sure it has enough headroom for editing later on. The best option here is to use a **green screen background for YouTube videos**.
## **5 Winter YouTube Background Ideas**
It’s finally time to have a look at some examples of highly effective and engaging YouTube video backgrounds for the winter season.
Enjoy!
* Snowy Landscape

* Festive Holiday Decor

* Cozy Indoor Settings

* Winter Cityscapes

* Animated Winter Scenes

## How to Create or Source Winter Backgrounds
If you want to make your own winter backgrounds or simply edit the ones you have, the most effective way is to use a beginner-friendly video editing platform, such as [Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit)
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later
This type of platform has all the necessary tools, templates, and presets for professionals to use but all of it is packed in a very easy-to-use interface that anyone can get the hang of.
Just follow these steps and you’ll have the perfect winter **background for YouTube** in no time.
##### Step 1
Download and install the Filmora video editing tool.
##### Step 2
Run the program and click on **“**New Project”. No need to create an account for this.

##### Step 3
Click on “Stock Media” and then type in “winter” in the Search Bar.

##### Step 4
Select your favorite background clip and drag it down to the Timeline.
That’s it! You won’t believe how many video clips you can use, all of which are extremely high-quality. As a result, you’ll have a professional video for free.
Now, if you want, you can freely edit these backgrounds as you wish. You can mess around with them as much as you want, use various tools to edit, and make the perfect result.
And don’t worry, if you mess up the background and don’t know how to restore it, just delete it from the timeline and drag it again from the Stock Media tab. It will be as good as new.
Once you’re done, simply export it and you’re done.
## Integrating Your Background Into Videos
Finally, once you have the perfect YouTube studio background, it’s time to glue it to your video and upload this masterpiece.
In order to do this, you will need to use a video editing platform once again. This is not optional as there is no other way to merge these clips.
Luckily, you now have Filmora downloaded and can easily make it happen.
So, here’s how to combine everything.
##### Step 1
Start up a New Project in Filmora.
##### Step 2
Click on **“**My Media” and then click in the middle of the small box to upload your background and your video clips.

##### Step 3
After uploading all the files, simply drag everything in a separate Track down on the Timeline.
##### Step 4
Export and upload to YouTube. That’s it!
## Summary
You’re now ready to make some outstanding Winter YouTube videos and bless everyone with amazing scenery and backgrounds that will make their hearts warm up. Not only do you have infinite backgrounds to choose from, you also know how to perfectly blend them in any of your videos.
Enjoy!
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## Inside Look at YouTube's Creator Studio Interface
YouTube Creator Studio is a powerful tool for content creators. It allows you to manage and optimize YouTube channels for better performance. With YouTube studio monetization features, you can keep track of your revenues. The creator study also allows you to manage your videos and see how well they are performing. This article explores the monetization Youtube Studio in detail, including how to access and use it.
**YouTube-Ready Video Editor** A top choice for many creators looking to outperform their competitors on YouTube!
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More](https://tools.techidaily.com/wondershare/filmora/download/)

## **Part 1\. Introduction to YouTube Studio: Definition and Uses**
Every creator is aware of YouTube Studio com monetization as a tool for managing YouTube. However, how much can you say about channel monetization YouTube Studio? Let’s have a look at what you need to know:
### **What is YouTube Studio?**

YouTube Studio is a tool that allows creators and other users to manage their channels. Formerly known as YouTube Creator Studio, the tool helps you to edit and monitor the performance of your videos, You can also view and reply to comments, or even schedule content.
### **Uses of YouTube Studio**
YouTube Studio is an essential tool for creators and brands. It helps them manage their presence on YouTube. Individuals can also grow their channels and track the progress they have made. Other people also use YouTube Studio as a hub to get a snapshot of their channel’s performance. It makes it easier to manage videos and offer opportunities for monetizing content through the YouTube Partner Program (YPP). The features that creators can access via the studio include:
* **Manage the channel:** YouTube Studio allows creators to customize their channel's appearance, branding, description, and layout.
* **Editing of videos**: Options for editing videos in the Studio include details, end screens, thumbnails, uploading videos, subtitles, and adding or managing playlists.
* **View your performance**: Detailed insights are available about the performance of the videos, audience demographics, watch time, and more.
* **YouTube Monetization**: All the tools and settings for monetizing your videos and Shorts on YouTube are found on the Studio.
* **Manage your comments:** The comments section of the Studio allows you to view and reply to comments on your videos.
## **Part 2\. Master Your YouTube Presence: Essential Steps to Dominate Creator Studio**
Getting started with YouTube Creator Studio is simple. Log in to your YouTube, and click on the profile pic at the right corner of the page. Then select YouTube Studio from the dropdown menu.
### **Step-by-Step Guide for Using YouTube Creator Studio**
Beginners may find it a bit tricky to navigate the YouTube Creator Studio. There are a lot of tools to explore, each with a unique function. Let’s break down the essentials to get you started.
* [Step 1: Navigating the YouTube Studio](#step1)
* [Step 2: Exploring the Creator Dashboard](#step2)
* [Step 3: Manage Your Content](#step3)
* [Step 4: Monitoring Channel Performance](#step4)
* [Step 5: Review Your Studio Monetization Tab](#step5)
#### **Step 1: Navigating the YouTube Studio**

To launch the YouTube Creator Studio, head over to studio.youtube.com and sign in. Then click on your profile pic and select YouTube Studio. On the left-hand side of the Studio screen, browse to navigate the features.
#### **Step 2: Exploring the Creator Dashboard**

The YouTube Creator Studio Dashboard provides all the handy information needed to create a growth strategy for your channel. You will see the analytics of your top videos and a summary of your views. You will also see your current subscribers watch time, and more:
* Review how your most recent video is performing
* Review personalized suggestions to grow your channel
* Check recent comments and respond appropriately
* Watch the latest updates from the YouTube team
* Look at important notifications to avoid copyright violations or monetization issues on time
* Explore the audio library to gain access to free soundtracks and music
#### **Step 3: Manage Your Content**

Click on the Content tab on the dashboard. Manage your content by editing or just reviewing the performance of each video. You can also create playlists linked to the videos to choose watch time.
#### **Step 4: Monitoring Channel Performance**

The YouTube Creator Studio Analytics provides a summary of your video metrics and reports. This will help you figure out what is working. The analytics also point out what needs to be improved to gain more views. Be sure to check views and watch time to get an accurate picture of the channel’s performance.
#### **Step 5: Review Your Studio Monetization Tab**

The monetization tab shows the monetization status of your channel. On the left side of the dashboard, click Earn to access this feature. After being accepted to the YPP, you can make money from advertising revenue, merch shelf, channel membership, and the fan-funded program. Before monetization, this page shows how far you are to meet the eligibility criteria.
### **Importance of Verifying the YouTube Channel**
After uploading your videos to YouTube Creator Studio, you need to optimize each for monetization. This ensures that the algorithm works in your favor. It is also important to create an AdSense Account and link it to your channel. This will:
* Increase your level of credibility because a verified YouTube channel is seen as more trustworthy by viewers
* Protect you and your channel from impersonation by preventing other users from creating fake accounts under your name.
* Unlock additional features such as the ability to lie stream in HD and customer the channel layout.
Linking your AdSense to the Account is also a crucial step towards getting paid for your creation on YouTube. It ensures that your earnings get to you. After joining the YPP, you are allowed to change your linked AdSense account if you already have one. You can also monetize more than one channel using the same AdSense account, and keep track of your earnings.
## **Part 3\.** [**Create YouTube-Ready Videos with Wondershare Filmora**](https://tools.techidaily.com/wondershare/filmora/download/)
The success of your YouTube channel largely depends on the quality of the videos uploaded. You need video editing software that will make your creator studio attractive even before opening individual videos. Wondershare Filmora is a top choice for many creators looking to outperform their competitors on YouTube. Explore the range of possibilities with Filmora ranging from creative video effects to stunning text animations.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit)
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later
Making YouTube-ready videos with Filmora is quick and easy. You need to have great footage to start with. Then, explore the editing features that will make the video stand out. Let’s have a look at the steps involved:
* [Step 1: Launch Filmora](#filmora1)
* [Step 2: Create a New Project and Import Files](#filmora2)
* [Step 3: Organize Your Project Material](#filmora3)
* [Step 4: Place Files on the Timeline](#filmora4)
* [Step 5: Apply Visual Effects](#filmora5)
* [Step 6: Conduct the Color Correction Process](#filmora6)
* [Step 7: Export and Share](#filmora7)
### **Step 1:** **Launch Filmora**
Launch Filmora by double-clicking the desktop icon. On the welcome window, select the aspect ratio you want to use.

### **Step 2: Create a New Project and Import Files**
After launching Filmora, click **New Project** on the welcome screen. Once the editor loads, import the media files from the options provided.

### **Step 3: Organize Your Project Material**
Manage the files you will be using in the editing project. The My Album option allows you to organize the file using different criteria such as type or purpose.

### **Step 4: Place Files on the Timeline**
Time to start editing your video. Place the video and audio files on the timeline while removing the redundant parts. Use the drag-and-drop feature to edit the clips, one at a time, cutting out unneeded footage to have a clear story.

### **Step 5: Apply Visual Effects**
After removing the unwanted parts from the video clips, detach the audio and video files. Insert transitions between clips, add music, and use other visual effects on Filmora to make the video more exciting.

### **Step 6: Conduct the Color Correction Process**
The effects icon gives you access to filters and overlays to make your video colors more vivid. Select the filters of choice, and drag and drop it to where you want to use on the timeline.

### **Step 7: Export and Share**
Once you are satisfied with the video outcome, export it in MP4 format, ready for upload on YouTube. Save it in your local drive, and upload it to YouTube via the Creator Studio.

## **Conclusion**
The YouTube Creator Studio allows you to manage your channel and content in a central location. You get access to all the essential features, including analytics and content editing. Also, manage the monetization of your videos and reply to comments. Good video editing software will play a crucial role in building your channel. We recommend exploring video editing features on Wondershare Filmora to make better videos for your channels. With most tasks now optimized, editing videos with Filmora is now easier and fun.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More](https://tools.techidaily.com/wondershare/filmora/download/)

<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<span class="atpl-alsoreadstyle">Also read:</span>
<div><ul>
<li><a href="https://eaxpv-info.techidaily.com/updated-in-2024-free-easy-and-fast-youtubes-best-subtitle-getters/"><u>[Updated] In 2024, Free, Easy and Fast YouTube's Best Subtitle Getters</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/updated-in-2024-flv-video-unification-techniques/"><u>[Updated] In 2024, FLV Video Unification Techniques</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/updated-hasty-methods-for-mixed-up-youtube-playback-sequence-for-2024/"><u>[Updated] Hasty Methods for Mixed-Up YouTube Playback Sequence for 2024</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/2024-approved-youtube-shorts-profits-and-content-creator-payments/"><u>2024 Approved YouTube Shorts Profits & Content Creator Payments</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/updated-from-creation-to-consumption-igtv-vs-youtube-explained-for-you-for-2024/"><u>[Updated] From Creation to Consumption IGTV Vs. YouTube Explained for You for 2024</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/new-in-2024-from-visionary-to-victory-channel-command-school/"><u>[New] In 2024, From Visionary to Victory Channel Command School</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/updated-trend-driven-infographics-the-leaders-in-23/"><u>[Updated] Trend-Driven Infographics The Leaders in '23</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/updated-in-2024-harnessing-the-power-of-filmora-for-youtube-video-promotions/"><u>[Updated] In 2024, Harnessing the Power of Filmora for YouTube Video Promotions</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/updated-choosing-your-best-gif-creator-a-comparative-analysis-for-2024/"><u>[Updated] Choosing Your Best GIF Creator A Comparative Analysis for 2024</u></a></li>
<li><a href="https://on-screen-recording.techidaily.com/new-real-time-recording-faceoff-obs-vs-shadowplay/"><u>[New] Real-Time Recording Faceoff OBS Vs ShadowPlay</u></a></li>
<li><a href="https://facebook-record-videos.techidaily.com/2024-approved-youtube-conversion-made-simple-learn-how-without-spending-a-dime/"><u>2024 Approved YouTube Conversion Made Simple – Learn How Without Spending a Dime</u></a></li>
<li><a href="https://extra-approaches.techidaily.com/2024-approved-open-markets-close-plans-strategy-inception/"><u>2024 Approved Open Markets, Close Plans Strategy Inception</u></a></li>
<li><a href="https://some-approaches.techidaily.com/the-evolution-of-burst-mode-in-gopro-cameras-for-2024/"><u>The Evolution of Burst Mode in GoPro Cameras for 2024</u></a></li>
<li><a href="https://youtube-clips.techidaily.com/new-cultivating-productive-collaboration-a-pathway-to-effective-collab-videos/"><u>[New] Cultivating Productive Collaboration A Pathway to Effective Collab Videos</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/rising-above-internet-naysayers-and-detractors-for-2024/"><u>Rising Above Internet Naysayers and Detractors for 2024</u></a></li>
<li><a href="https://extra-guidance.techidaily.com/updated-revolutionize-online-sessions-with-essential-zoom-transformations/"><u>[Updated] Revolutionize Online Sessions with Essential Zoom Transformations</u></a></li>
<li><a href="https://location-social.techidaily.com/in-2024-4-feasible-ways-to-fake-location-on-facebook-for-your-samsung-galaxy-a15-4g-drfone-by-drfone-virtual-android/"><u>In 2024, 4 Feasible Ways to Fake Location on Facebook For your Samsung Galaxy A15 4G | Dr.fone</u></a></li>
<li><a href="https://screen-mirroring-recording.techidaily.com/new-in-2024-best-virtual-racing-for-cyclists/"><u>[New] In 2024, Best Virtual Racing for Cyclists</u></a></li>
<li><a href="https://howto.techidaily.com/super-easy-ways-to-deal-with-infinix-zero-30-5g-unresponsive-screen-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Super Easy Ways To Deal with Infinix Zero 30 5G Unresponsive Screen | Dr.fone</u></a></li>
</ul></div> |
import { PrismaClient } from '@prisma/client';
import { relationshipTypeSeederData } from './data';
export async function relationshipTypeSeed(prisma: PrismaClient): Promise<void> {
try {
console.info('Seeding table relationship_type...');
for (const data of relationshipTypeSeederData) {
await prisma.relationshipType.upsert({
where: { id: data.id },
update: data,
create: data,
});
}
console.info('Data inserted with success on the table relationship_type.');
} catch (error) {
console.error('An error occurred during seeding of table relationship_type.', error);
throw error;
}
} |
package hexlet.code.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import hexlet.code.model.TaskStatus;
import hexlet.code.model.User;
import hexlet.code.repository.TaskStatusRepository;
import hexlet.code.repository.UserRepository;
import hexlet.code.utils.UserUtil;
import net.datafaker.Faker;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@SpringBootTest
@AutoConfigureMockMvc
public class TaskStatusControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private UserUtil userUtil;
@Autowired
private UserRepository userRepository;
@Autowired
private TaskStatusRepository taskStatusRepository;
@Autowired
private ObjectMapper om;
@Autowired
private Faker faker;
private User testUser;
private String plainPassword;
private SecurityMockMvcRequestPostProcessors.JwtRequestPostProcessor token;
@BeforeEach
public void setUp() {
User testUser = userUtil.makeUser();
plainPassword = userUtil.getPlainPassword();
userRepository.save(testUser);
token = jwt().jwt(builder -> builder.subject(testUser.getEmail()));
}
@Test
public void testShowTaskStatuses() throws Exception {
MockHttpServletResponse response = mockMvc.perform(
get("/api/task_statuses")
.with(token)
).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getContentAsString())
.contains("draft", "to_review", "to_be_fixed", "to_publish");
}
@Test
public void testShowTaskStatus() throws Exception {
MockHttpServletResponse response = mockMvc.perform(
get("/api/task_statuses/1")
.with(token)
).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getContentAsString())
.contains("draft");
}
@Test
public void testUpdateTaskStatus() throws Exception {
TaskStatus taskStatus = new TaskStatus();
taskStatus.setName(faker.name().name());
MockHttpServletResponse response = mockMvc.perform(
put("/api/task_statuses/1")
.with(token)
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsString(taskStatus))
).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getContentAsString()).contains(taskStatus.getName());
}
@Test
public void testDeleteTaskStatus() throws Exception {
MockHttpServletResponse response = mockMvc.perform(
delete("/api/task_statuses/5")
.with(token)
).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(204);
response = mockMvc.perform(
get("/api/task_statuses")
.with(token)
).andReturn().getResponse();
assertThat(response.getContentAsString()).doesNotContain("published");
}
@Test
public void testCreateTaskStatus() throws Exception {
TaskStatus taskStatus = new TaskStatus();
taskStatus.setName(faker.name().name());
taskStatus.setSlug(faker.name().name());
MockHttpServletResponse response = mockMvc.perform(
post("/api/task_statuses")
.with(token)
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsString(taskStatus))
).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(201);
assertThat(response.getContentAsString()).contains(taskStatus.getName());
}
} |
#![allow(dead_code)]
/*
278. 第一个错误的版本
简单
相关标签
相关企业
你是产品经理,目前正在带领一个团队开发新的产品。不幸的是,你的产品的最新版本没有通过质量检测。由于每个版本都是基于之前的版本开发的,所以错误的版本之后的所有版本都是错的。
假设你有 n 个版本 [1, 2, ..., n],你想找出导致之后所有版本出错的第一个错误的版本。
你可以通过调用 bool isBadVersion(version) 接口来判断版本号 version 是否在单元测试中出错。实现一个函数来查找第一个错误的版本。你应该尽量减少对调用 API 的次数。
示例 1:
输入:n = 5, bad = 4
输出:4
解释:
调用 isBadVersion(3) -> false
调用 isBadVersion(5) -> true
调用 isBadVersion(4) -> true
所以,4 是第一个错误的版本。
示例 2:
输入:n = 1, bad = 1
输出:1
提示:
1 <= bad <= n <= 231 - 1
*/
struct Solution;
// The API isBadVersion is defined for you.
// isBadVersion(version:i32)-> bool;
// to call it use self.isBadVersion(version)
impl Solution {
pub fn first_bad_version(&self, n: i32) -> i32 {
let (mut left, mut right) = (1_i64, n as i64);
while left <= right {
let mid = (left + right) >> 1;
if self.isBadVersion(mid as i32) {
right = mid - 1;
} else {
left = mid + 1;
}
}
left as i32
}
#[allow(unused_variables)]
#[allow(non_snake_case)]
fn isBadVersion(&self, version: i32) -> bool {
todo!()
}
} |
# InvestmentsTransactionsOverride
Specify the list of investments transactions on the account.
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**date** | **LocalDate** | Posting date for the transaction. Must be formatted as an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) date. | |
|**name** | **String** | The institution's description of the transaction. | |
|**quantity** | **BigDecimal** | The number of units of the security involved in this transaction. Must be positive if the type is a buy and negative if the type is a sell. | |
|**price** | **BigDecimal** | The price of the security at which this transaction occurred. | |
|**fees** | **BigDecimal** | The combined value of all fees applied to this transaction. | [optional] |
|**type** | **String** | The type of the investment transaction. Possible values are: `buy`: Buying an investment `sell`: Selling an investment `cash`: Activity that modifies a cash position `fee`: A fee on the account `transfer`: Activity that modifies a position, but not through buy/sell activity e.g. options exercise, portfolio transfer | |
|**currency** | **String** | Either a valid `iso_currency_code` or `unofficial_currency_code` | |
|**security** | [**SecurityOverride**](SecurityOverride.md) | | [optional] | |
public class MethodOverloadingDemo {
// Void -->nothing to return
// MOverloading--> with in the class. static and instance methods can overloaded
/*
* public void add(int a, int b) {
* System.out.println("(int, int)"+(a+b)); }
*
* public void add(long a, long b) {
* System.out.println("(long, long)"+(a+b)); }
*/
MethodOverloadingDemo getInstance(){
return this;
}
public void add(int a, long b) {
System.out.println("(int, long)" + (a + b));
this.add(b, a);
add(this);
System.out.println(getInstance().hashCode());
}
public void add(MethodOverloadingDemo demo) {
System.out.println("Metod ");
}
public void add(long a, int b) {
System.out.println("(long, int)" + (a + b));
}
/*
* public void add(double a, double b) { System.out.println(a + b); }
*/
public void add(int a, int b, int c) {
System.out.println(a + b + c);
}
public static void main(String[] args) {// 10.90+20.80
MethodOverloadingDemo demo = new MethodOverloadingDemo();
demo.add(10, 10L);// static method calling with in the same class
System.out.println(demo.hashCode());
//add(10L, 10);
// add(10.90,20.80);//31.70
// add(10,10,10);
}
} |
import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import tokenUtils from '@/utils/TokenUtils'
class HttpFileClient {
protected readonly instance: AxiosInstance;
public constructor() {
this.instance = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
headers: {
'contentType': 'application/json;charset=UTF-8;'
},
responseType: 'blob'
});
this.instance.interceptors.request.use(
request => {
if (request.headers) {
request.headers['Authorization'] = tokenUtils.getAccessToken();
}
return request;
},
error => {
return Promise.reject(error);
}
);
const interceptor = this.instance.interceptors.response.use(
response => {
return response;
},
error => {
const data = error.response.data;
const originalRequest = error.config;
if (error.response.status === 401 && data.message.indexOf('expiredToken') > -1) {
const config = {
headers: { 'Authorization': tokenUtils.getRefreshToken() }
}
return axios.post(
'/api/security/reissue-token', {}, config
).then(res => {
tokenUtils.setToken(res.data);
})
.then(() => Promise.resolve(this.instance(originalRequest)))
.catch(err => {
console.log('fail refreshToken', err);
})
} else if (error.response.status === 500 && data.message.indoexOf('invalidToken') > -1) {
window.location.href = '/security/login';
} else if (data.message.length > 0) {
return data;
} else {
return Promise.reject(error);
}
}
)
}
post(url: string, data?: any, config?:AxiosRequestConfig<any>) {
return this.instance.post(url, data, config);
}
get(url: string, config?:AxiosRequestConfig<any>) {
//console.log("---- httpfileclient.get")
return this.instance.get(url, config);
}
}
export default new HttpFileClient(); |
#pragma once
#include "checkML.h"
#include "Vector2D.h"
#include "Texture.h"
#include "Ball.h"
#include "MovingObject.h"
using namespace std;
// Clase PADDLE que hereda de MOVINGOBJECT
class PlayState;
class Paddle : public MovingObject
{
private:
int rightLimit = 0;
int leftLimit = 0;
PlayState* game = nullptr;
public:
// Constructora de la clase
Paddle(Vector2D p, int h, int w, Texture* t, PlayState* g, Vector2D d, int rL, int lL, double s) : MovingObject(p, h, w, t, d, s), game(g), rightLimit(rL), leftLimit(lL) {};
// Getter
int getWidth() { return w; };
// Metodos publicos de la clase
virtual void update();
virtual void loadFromFile(ifstream& loadFile);
virtual void saveToFile(ofstream& saveFile);
void handleEvent(SDL_Event event);
bool collides(SDL_Rect ballRect, Vector2D& collisionVector, const Vector2D& dir);
void setPos(Vector2D p) { pos = p; };
void setWidth(int width) { w = width; };
void restartPaddle() { pos = Vector2D((double)((WIN_WIDTH / 2) - 50), (double)WIN_HEIGHT - 100); w = PADDLE_WIDTH; h = PADDLE_HEIGHT; };
protected:
Vector2D collision(const SDL_Rect& ballRect, const SDL_Rect& collision, const Vector2D& dir);
}; |
public class IPhoneCharger { // Adaptee
public String charge() {
return "USB-A 3V";
}
}
public interface Charger { // Target
public String charge();
}
class AdapterToChargeSamsung implements Charger { // Adapter
private IPhoneCharger iphone;
public AdapterToChargeSamsung(IPhoneCharger iphone) {
this.iphone = iphone;
}
@Override
public String charge() {
return iphone.charge() + " Adapted from IPhone to Samsung";
}
}
public class Main {
public static void main(String[] args) {
// Create an instance of IPhoneCharger
IPhoneCharger iphoneCharger = new IPhoneCharger();
// Create an adapter to charge a Samsung device using the IPhoneCharger
AdapterToChargeSamsung adapter = new AdapterToChargeSamsung(iphoneCharger);
// Charge the Samsung device using the adapter
String samsungChargeResult = adapter.charge();
// Display the result
System.out.println("Charging Result for Samsung: " + samsungChargeResult);
}
} |
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { Tile } from './tile.js';
import models from './models.js';
export class AssetManager {
textureLoader = new THREE.TextureLoader();
gltfLoader = new GLTFLoader();
modelLoader = new GLTFLoader();
cubeGeometry = new THREE.BoxGeometry(1.01, 1, 1.01);
meshes = {};
/* Texture library */
// Credit: https://opengameart.org/content/free-urban-textures-buildings-apartments-shop-fronts
textures = {
// grass: this.loadTexture('/textures/grass.png'),
base: this.loadTexture('/textures/fiveTone.jpg'),
};
puffs = [
0, 0.09765625, 0.1953125, 0.29296875, 0.390625, 0.48828125, 0.5859375, 0.68359375, 0.78125,
0.87890625, 0.9765625, 1.07421875,
];
constructor(onLoad) {
this.modelCount = Object.keys(models).length;
this.loadedModelCount = 0;
for (const [name, meta] of Object.entries(models)) {
this.loadModel(name, meta);
}
this.onLoad = onLoad;
}
/**
* Load the 3D models
* @param {string} url The URL of the model to load
*/
loadModel(
name,
{
filename,
scale = 1,
entrance_marker_x,
entrance_marker_z,
exit_marker_x,
exit_marker_z,
yPos,
xPos,
zPos,
},
) {
const texture = this.textures.base;
this.textures.base.minFilter = texture.magFilter = THREE.NearestFilter;
this.modelLoader.load(
`/${filename}`,
(glb) => {
const mesh = glb.scene;
mesh.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
if (child.material !== undefined) {
let oldMat = child.material;
let newMat = new THREE.MeshToonMaterial({
color: oldMat.color,
gradientMap: texture,
});
child.material = newMat;
}
});
mesh.position.set(0, 0, 0);
mesh.scale.set(scale, scale, scale);
mesh.userData = {
entrance_marker_x,
entrance_marker_z,
exit_marker_x,
exit_marker_z,
yPos,
xPos,
zPos,
};
this.meshes[name] = mesh;
// Once all models are loaded
this.loadedModelCount++;
if (this.loadedModelCount == this.modelCount) {
this.onLoad();
}
},
(xhr) => {
// console.log(`${name} ${(xhr.loaded / xhr.total) * 100}% loaded`);
},
(error) => {
console.error(error);
},
);
}
getMesh(name) {
const mesh = this.meshes[name].clone();
// Clone materials so each object has a unique material
// This is so we can set the modify the texture of each
// mesh independently (e.g. highlight on mouse over,
// abandoned buildings, etc.))
mesh.traverse((child) => {
if (child.isMesh) {
child.material = child.material.clone();
}
});
return mesh;
}
/**
* Creates a new mesh for a ground tile
* @param {Tile} tile
* @returns {THREE.Mesh}
*/
createGroundMesh(tile) {
const material = new THREE.MeshLambertMaterial({ color: 0x0b8008 });
const mesh = new THREE.Mesh(this.cubeGeometry, material);
mesh.userData = tile;
mesh.position.set(tile.x, -0.5, tile.y);
mesh.receiveShadow = true;
return mesh;
}
/**
* Creates a new building mesh
* @param {Tile} tile The tile the building sits on
* @returns {THREE.Mesh | null}
*/
createBuildingMesh(tile, city, scene) {
if (!tile?.building) return null;
if (tile?.trees !== null && tile?.trees.length > 0) {
// we need to remove the trees
for (let i = 0; i < tile.trees.length; i++) {
scene.remove(tile.trees[i]);
}
}
switch (tile.building?.type) {
case 'residential':
case 'commercial':
case 'industrial':
return this.createZoneMesh(tile, city);
case 'police':
return this.createUtilityMesh(tile, city, 'police');
case 'fire':
return this.createUtilityMesh(tile, city, 'fire');
case 'hospital':
return this.createUtilityMesh(tile, city, 'hospital');
case 'power':
return this.createUtilityMesh(tile, city, 'power');
case 'water':
return this.createUtilityMesh(tile, city, 'water');
default:
console.warn(`Mesh type ${tile.building?.type} is not recognized.`);
return null;
}
}
/**
* Creates a new mesh for a zone
* @param {Tile} tile The tile that the zone sits on
* @returns {THREE.Mesh} A mesh object
*/
createZoneMesh(tile, city) {
const zone = tile.building;
const modelName = `${zone.type}-${zone.style}${zone.level}`;
// If zone is not yet developed, show it as under construction
if (!zone.developed) {
let cubeGeometry = new THREE.BoxGeometry(1, 0.025, 1);
let material = undefined;
if (zone.type === 'residential') {
material = new THREE.MeshLambertMaterial({ color: 0x00ff00 });
} else if (zone.type === 'commercial') {
material = new THREE.MeshLambertMaterial({ color: 0x0000ff });
} else if (zone.type === 'industrial') {
material = new THREE.MeshLambertMaterial({ color: 0xffff00 });
}
const mesh = new THREE.Mesh(cubeGeometry, material);
mesh.position.set(zone.x, 0, zone.y);
mesh.userData = tile;
return mesh;
}
let mesh = this.getMesh(modelName);
tile.building.entrance_marker = {
x: mesh.userData.entrance_marker_x,
z: mesh.userData.entrance_marker_z,
};
tile.building.exit_marker = { x: mesh.userData.exit_marker_x, z: mesh.userData.exit_marker_z };
// check if needs rotation
let connections = this.getConnections(tile, city);
if (connections.connectionsCount > 0) {
if (connections.connections.left) {
let connectedTile = city.getTile(tile.x + 1, tile.y);
if (connectedTile.road) {
tile.building.rotation = 90;
mesh.rotateY((Math.PI / 2) * 1);
}
} else if (connections.connections.right) {
let connectedTile = city.getTile(tile.x - 1, tile.y);
if (connectedTile.road) {
tile.building.rotation = 270;
mesh.rotateY((Math.PI / 2) * 3);
}
} else if (connections.connections.down) {
let connectedTile = city.getTile(tile.x, tile.y - 1);
if (connectedTile.road) {
tile.building.rotation = 180;
mesh.rotateY((Math.PI / 2) * 2);
}
} else {
tile.building.rotation = 0;
}
}
mesh.position.set(zone.x + mesh.userData.xPos, mesh.userData.yPos, zone.y + mesh.userData.zPos);
mesh.userData = tile;
let markerGeom = new THREE.BoxGeometry(0.1, 0.1, 0.1);
let markerMat = new THREE.MeshLambertMaterial({ color: 0xffff00 });
let markerMesh = new THREE.Mesh(markerGeom, markerMat);
markerMesh.position.set(tile.building.entrance_marker.x, 0.16, tile.building.entrance_marker.z);
markerMesh.visible = false;
mesh.add(markerMesh);
tile.markerMesh = markerMesh;
tile.meshPosition = mesh.position;
if (zone.type === 'industrial') {
if (tile.smoke === null) {
let smoke = new THREE.Group();
var material = new THREE.MeshLambertMaterial({
color: 0xffffff,
});
for (var i = 0; i < this.puffs.length; i++)
smoke.add(new THREE.Mesh(new THREE.IcosahedronGeometry(5, 0), material));
for (var i = 0; i < smoke.children.length; i++) {
smoke.children[i].geometry.computeVertexNormals();
smoke.children[i].position.setX(Math.random() * 0.1);
smoke.children[i].position.setZ(Math.random() * 0.1);
smoke.children[i].rotation.x = Math.random();
smoke.children[i].rotation.y = Math.random();
smoke.children[i].rotation.z = Math.random();
}
smoke.name = 'smoke';
tile.smoke = smoke;
smoke.position.set(tile.x - 0.25, 1, tile.y + 0.25);
if (tile.building.rotation === 0) {
smoke.position.set(tile.x + 0.17, 1, tile.y - 0.3);
} else if (tile.building.rotation === 90) {
smoke.position.set(tile.x - 0.3, 1, tile.y - 0.25);
} else if (tile.building.rotation === 180) {
smoke.position.set(tile.x - 0.25, 1, tile.y + 0.25);
} else if (tile.building.rotation === 270) {
smoke.position.set(tile.x + 0.22, 1, tile.y + 0.17);
} else {
tile.smoke = null;
}
}
}
if (zone.abandoned) {
for (let i = 0; i < mesh.children[0].children.length; i++) {
mesh.children[0].children[i].material.color.set(0x231709);
}
}
return mesh;
}
createUtilityMesh(tile, city, type) {
let modelName = `police-1`;
const zone = tile.building;
if (type === 'police') {
modelName = `police-1`;
} else if (type === 'fire') {
modelName = 'fire-1';
} else if (type === 'hospital') {
modelName = 'hospital-1';
} else if (type === 'power') {
modelName = 'power-1';
} else if (type === 'water') {
modelName = 'water-1';
}
let mesh = this.getMesh(modelName);
tile.building.entrance_marker = {
x: mesh.userData.entrance_marker_x,
z: mesh.userData.entrance_marker_z,
};
tile.building.exit_marker = { x: mesh.userData.exit_marker_x, z: mesh.userData.exit_marker_z };
// check if needs rotation
let connections = this.getConnections(tile, city);
if (connections.connectionsCount > 0) {
if (connections.connections.left) {
let connectedTile = city.getTile(tile.x + 1, tile.y);
if (connectedTile.road) {
tile.building.rotation = 270;
mesh.rotateY((Math.PI / 2) * 3);
}
} else if (connections.connections.right) {
let connectedTile = city.getTile(tile.x - 1, tile.y);
if (connectedTile.road) {
tile.building.rotation = 90;
mesh.rotateY((Math.PI / 2) * 1);
}
} else if (connections.connections.down) {
} else {
let connectedTile = city.getTile(tile.x, tile.y + 1);
if (connectedTile.road) {
tile.building.rotation = 180;
mesh.rotateY((Math.PI / 2) * 2);
}
}
}
mesh.position.set(zone.x + mesh.userData.xPos, mesh.userData.yPos, zone.y + mesh.userData.zPos);
mesh.userData = tile;
if (type === 'power') {
if (tile.smoke === null) {
let smoke = new THREE.Group();
var material = new THREE.MeshLambertMaterial({
color: 0xffffff,
});
for (var i = 0; i < this.puffs.length; i++)
smoke.add(new THREE.Mesh(new THREE.IcosahedronGeometry(10, 0), material));
for (var i = 0; i < smoke.children.length; i++) {
smoke.children[i].geometry.computeVertexNormals();
smoke.children[i].position.setX(Math.random() * 0.1);
smoke.children[i].position.setZ(Math.random() * 0.1);
smoke.children[i].rotation.x = Math.random();
smoke.children[i].rotation.y = Math.random();
smoke.children[i].rotation.z = Math.random();
}
smoke.name = 'smoke';
let smoke2 = smoke.clone();
smoke.position.set(tile.x - 1.125, 0.75, tile.y);
smoke2.position.set(tile.x - 1.125, 0.75, tile.y - 0.75);
let smoke3 = new THREE.Group();
for (var i = 0; i < this.puffs.length; i++)
smoke3.add(new THREE.Mesh(new THREE.IcosahedronGeometry(5, 0), material));
for (var i = 0; i < smoke.children.length; i++) {
smoke3.children[i].geometry.computeVertexNormals();
smoke3.children[i].position.setX(Math.random() * 0.1);
smoke3.children[i].position.setZ(Math.random() * 0.1);
smoke3.children[i].rotation.x = Math.random();
smoke3.children[i].rotation.y = Math.random();
smoke3.children[i].rotation.z = Math.random();
}
let smoke4 = smoke3.clone();
smoke3.position.set(tile.x + 0.225, 1.6, tile.y - 0.1);
smoke4.position.set(tile.x - 0.225, 1.6, tile.y - 0.1);
tile.smoke = [smoke, smoke2, smoke3, smoke4];
// if (tile.building.rotation === 0) {
// smoke.position.set(tile.x + 0.17, 1, tile.y - 0.3);
// } else if (tile.building.rotation === 90) {
// smoke.position.set(tile.x - 0.3, 1, tile.y - 0.25);
// } else if (tile.building.rotation === 180) {
// smoke.position.set(tile.x - 0.25, 1, tile.y + 0.25);
// } else if (tile.building.rotation === 270) {
// smoke.position.set(tile.x + 0.22, 1, tile.y + 0.17);
// } else {
// tile.smoke = null;
// }
}
} else if (type === 'water') {
let smoke = new THREE.Group();
var material = new THREE.MeshLambertMaterial({
color: 0xffffff,
});
for (var i = 0; i < this.puffs.length; i++)
smoke.add(new THREE.Mesh(new THREE.IcosahedronGeometry(5, 0), material));
for (var i = 0; i < smoke.children.length; i++) {
smoke.children[i].geometry.computeVertexNormals();
smoke.children[i].position.setX(Math.random() * 0.1);
smoke.children[i].position.setZ(Math.random() * 0.1);
smoke.children[i].rotation.x = Math.random();
smoke.children[i].rotation.y = Math.random();
smoke.children[i].rotation.z = Math.random();
}
smoke.name = 'smoke';
smoke.position.set(tile.x + 0.125, 1, tile.y - 0.15);
tile.smoke = smoke;
}
let markerGeom = new THREE.BoxGeometry(0.1, 0.1, 0.1);
let markerMat = new THREE.MeshLambertMaterial({ color: 0xffff00 });
let markerMesh = new THREE.Mesh(markerGeom, markerMat);
markerMesh.position.set(tile.building.entrance_marker.x, 0.16, tile.building.entrance_marker.z);
markerMesh.visible = false;
mesh.add(markerMesh);
tile.markerMesh = markerMesh;
tile.meshPosition = mesh.position;
return mesh;
}
getConnections(tile, city) {
const neighbours = tile.getNeighbours(city);
let connectionsCount = 0;
let connections = {
left: undefined,
right: undefined,
up: undefined,
down: undefined,
};
for (let i = 0; i < neighbours.length; i++) {
if (neighbours[i]?.road) {
connectionsCount++;
if (neighbours[i].x < tile.x) connections.right = true;
if (neighbours[i].x > tile.x) connections.left = true;
if (neighbours[i].y < tile.y) connections.down = true;
if (neighbours[i].y > tile.y) connections.up = true;
}
}
return {
connectionsCount,
connections,
};
}
createTreeMesh(treeType, tile, scene) {
const texture = new THREE.TextureLoader().load('/textures/fiveTone.jpg');
texture.minFilter = texture.magFilter = THREE.NearestFilter;
if (treeType === 1) {
this.gltfLoader.load('/models/Nature/Tree1.glb', (gltf) => {
const mesh = gltf.scene;
mesh.scale.set(1.5, 1.5, 1.5);
mesh.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
mesh.traverse((node) => {
if (node.material !== undefined) {
let oldMat = node.material;
let newMat = new THREE.MeshToonMaterial({
color: oldMat.color,
gradientMap: texture,
});
node.material = newMat;
}
});
let minx = tile.x - 0.45;
let maxx = tile.x + 0.45;
let miny = tile.y - 0.45;
let maxy = tile.y + 0.45;
let x = Math.random() * (maxx - minx) + minx;
let z = Math.random() * (maxy - miny) + miny;
mesh.position.set(x, -0.18, z);
tile.trees.push(mesh);
scene.add(mesh);
});
} else {
this.gltfLoader.load('/models/Nature/Tree2.glb', (gltf) => {
const mesh = gltf.scene;
mesh.scale.set(1.5, 1.5, 1.5);
mesh.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
mesh.traverse((node) => {
if (node.material !== undefined) {
let oldMat = node.material;
let newMat = new THREE.MeshToonMaterial({
color: oldMat.color,
gradientMap: texture,
});
node.material = newMat;
}
});
let minx = tile.x - 0.45;
let maxx = tile.x + 0.45;
let miny = tile.y - 0.45;
let maxy = tile.y + 0.45;
let x = Math.random() * (maxx - minx) + minx;
let z = Math.random() * (maxy - miny) + miny;
mesh.position.set(x, -0.05, z);
tile.trees.push(mesh);
scene.add(mesh);
});
}
}
/**
* Loads the texture at the specified URL
* @param {string} url
* @returns {THREE.Texture} A texture object
*/
loadTexture(url) {
const tex = this.textureLoader.load(url);
tex.wrapS = THREE.RepeatWrapping;
tex.wrapT = THREE.RepeatWrapping;
tex.repeat.set(1, 1);
tex.colorSpace = THREE.SRGBColorSpace;
return tex;
}
getModel(modelName) {
return this.models[modelName].clone();
}
} |
use crate::msgfmt::markup_username_with_link;
use teloxide::prelude::*;
use teloxide::types::ParseMode;
/// 处理用户对另一个用户的模拟指令行为
///
/// 当用户发送类似 `/do_sth` 的消息时,机器人会回复类似 `@user1 do_sth 了 @user2` 的消息
/// 若消息不符合条件时,此函数会返回 None。此外,发送失败时不会传递错误到上游
pub(crate) async fn handle_user_do_sth_to_another(bot: &Bot, msg: &Message) -> Option<()> {
let from_user = msg.from();
let reply_user = msg.reply_to_message().and_then(|reply| reply.from());
let text = msg.text();
if text.is_none() || from_user.is_none() || reply_user.is_none() {
return None;
}
let text = text.unwrap();
if text.starts_with("/") && text.find("@").is_none() {
let act = text.strip_prefix("/");
if act.is_none() {
return None;
}
let acts: Vec<&str> = act.unwrap().split_ascii_whitespace().into_iter().collect();
if acts.len() == 0 || acts[0] == "me" {
return None;
}
let mut text = format!(
"{} {}了 {}",
markup_username_with_link(from_user.unwrap()),
acts[0],
markup_username_with_link(reply_user.unwrap())
);
if acts.len() > 1 {
text.push_str(&format!(" {}", acts[1]));
}
let res = bot
.send_message(msg.chat.id, text)
.parse_mode(ParseMode::MarkdownV2)
.await;
if res.is_err() {
log::error!("failed to send message: {:?}", res.err());
}
// TODO 统计行为次数
return Some(());
}
return None;
} |
import React, { useState } from 'react'
import { Button } from '../../components'
import { useParams } from 'react-router-dom'
import { apiResetPassword } from '../../apis/user'
import { toast } from 'react-toastify'
import withBase from '../../hocs/withBase'
import path from '../../ultils/path'
const ResetPassword = ({navigate}) => {
const [password, setpassword] = useState('')
const { token } = useParams()
const handleResetPassword = async () => {
const response = await apiResetPassword({ password, token })
if(response.success){
setpassword('')
toast.success(response.message)
navigate(`/${path.LOGIN}`)
}
}
return (
<div className="absolute top-0 left-0 bottom-0 right-0 flex-col bg-white flex items-center py-8 z-50">
<div className="flex flex-col gap-4">
<label htmlFor="password">Enter your new password:</label>
<div className="flex items-center justify-center mt-2 w-full gap-2">
<input type="text" id="password"
className="2-[800px] pb-2 border-b placeholder:text-sm p-1 mr-2"
placeholder="Type here"
value={password}
onChange={e => setpassword(e.target.value)}
/>
<Button
handleOnClick={handleResetPassword}
style='px-4 py-2 rounded-md text-white bg-blue-500 text-semibold my-2'>
Submit
</Button>
</div>
</div>
</div>
)
}
export default withBase(ResetPassword) |
import React, { SyntheticEvent, useEffect, useState } from "react";
import { FiCode, FiMail } from "react-icons/fi";
import {
BsInstagram,
BsLinkedin,
BsStackOverflow,
BsTwitter,
BsWhatsapp,
} from "react-icons/bs";
import { FaGithub } from "react-icons/fa";
import { SiHashnode } from "react-icons/si";
import { AiOutlineGoogle } from "react-icons/ai";
import axios from "axios";
import Main from "@/Layouts/Main";
import { Head, useForm } from "@inertiajs/react";
import { Toaster, toast } from "react-hot-toast";
const Contact = () => {
const messageLimit: number = 1024;
const { data, setData, processing, errors, reset, post } = useForm({
name: "",
email: "",
message: "",
});
useEffect(() => {
if (Object.keys(errors).length === 0 && data.message.length > 0) {
toast.success("Your message has been sent!");
reset();
return;
}
}, [processing]);
const sendMessage = (e: SyntheticEvent<HTMLFormElement>) => {
e.preventDefault();
post(route("contact"));
};
return (
<Main>
<Toaster />
<Head title="Get in touch!" />
<section className="px-5 py-32" id="about">
<div className="container mx-auto flex gap-3 flex-col">
<div>
<h2 className="font-bold text-4xl w-fit flex flex-col">
<span>Contact</span>
<hr className="w-1/5 border-2 ml-auto" />
</h2>
</div>
<p>Get in touch with me!</p>
<div className="flex flex-col gap-3 lg:flex-row lg:gap-32 w-full">
<form
onSubmit={sendMessage}
method="POST"
className="w-full"
>
<h3 className="text-xl font-bold mb-1">
Send Me a Message
</h3>
<div className="mb-3">
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
value={data.name}
onChange={(e) =>
setData("name", e.target.value)
}
className="rounded w-full bg-white text-neutral-900 outline-none focus:border-blue-300 border-2 border-white p-1"
/>
{errors.name && (
<small className="block text-red-400 text-sm">
{errors.name}
</small>
)}
</div>
<div className="mb-3">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
value={data.email}
onChange={(e) =>
setData("email", e.target.value)
}
className="rounded w-full bg-white text-neutral-900 outline-none focus:border-blue-300 border-2 border-white p-1"
/>
{errors.email && (
<small className="block text-red-400 text-sm">
{errors.email}
</small>
)}
</div>
<div className="mb-3">
<label htmlFor="message">Message</label>
<textarea
value={data.message}
onChange={(e) =>
setData("message", e.target.value)
}
className="rounded w-full bg-white text-neutral-900 outline-none focus:border-blue-300 border-2 border-white p-1"
id="message"
/>
<small
className={
"block text-neutral-100 text-sm transition-colors" +
(messageLimit - data.message.length < 0
? " text-red-400"
: "")
}
>
{messageLimit - data.message.length}
</small>
{errors.message && (
<small className="block text-red-400 text-sm">
{errors.message}
</small>
)}
</div>
<button
type="submit"
className="rounded bg-blue-200 text-blue-800 hover:bg-blue-300 transition-colors w-full px-4 py-2"
disabled={processing}
>
Send Message
</button>
</form>
<div className="flex flex-col gap-2 w-full">
<h4 className="font-bold text-xl mb-1">
Social Links
</h4>
<a
href="mailto:[email protected]"
className="flex items-center justify-center w-fit hover:text-purple-400"
>
<FiMail className="mr-2" /> [email protected]
</a>
<a
href="https://wa.me/923105322294"
className="flex items-center justify-center w-fit hover:text-green-400"
>
<BsWhatsapp className="mr-2" /> Business Number
</a>
<a
href="https://linkedin.com/in/raahimfareed"
className="flex items-center justify-center w-fit hover:text-blue-400"
>
<BsLinkedin className="mr-2" /> @raahimfareed
</a>
<a
href="https://instagram.com/raahimwho"
className="flex items-center justify-center w-fit hover:text-blue-400"
>
<BsInstagram className="mr-2" /> @raahimwho
</a>
<a
href="https://twitter.com/raahimwho"
className="flex items-center justify-center w-fit hover:text-sky-400"
>
<BsTwitter className="mr-2" /> @raahimwho
</a>
<a
href="https://github.com/raahimfareed"
className="flex items-center justify-center w-fit hover:text-slate-500"
>
<FaGithub className="mr-2" /> @raahimfareed
</a>
<a
href="https://hashnode.com/@raahim"
className="flex items-center justify-center w-fit hover:text-blue-400"
>
<SiHashnode className="mr-2" /> @raahim
</a>
<a
href="https://stackoverflow.com/users/12987360/raahim-fareed"
className="flex items-center justify-center w-fit hover:text-orange-400"
>
<BsStackOverflow className="mr-2" />{" "}
@raahimfareed
</a>
<a
href="https://gdsc.community.dev/u/mb3qvy/"
className="flex items-center justify-center w-fit hover:text-rose-400"
>
<AiOutlineGoogle className="mr-2" /> GDSC
Profile
</a>
<a
href="https://codeforces.com/profile/raahimfareed"
className="flex items-center justify-center w-fit hover:text-amber-400"
>
<FiCode className="mr-2" /> CodeForces
</a>
</div>
</div>
</div>
</section>
</Main>
);
};
export default Contact; |
<template>
<meta charset="utf-8">
<answers/>
<ScoreBoard :contador='this.contador' :pontosComputador = 'this.pontosComputador'/>
<div>
<template v-if="this.question">
<h1 v-html=" this.question "></h1>
<template v-for="item in answers" :key="item.answers">
<input
:disabled="this.answersSubmmited"
type="radio"
name ="options"
:value="item"
v-model="this.choose_answer"
>
<label>{{item }}</label><br>
</template>
<button v-if="!this.answersSubmmited" @click="this.submitAnswer()"
class="send" type="button">Send</button>
</template>
<section v-if="this.answersSubmmited" class="result">
<h4 v-if="this.choose_answer == this.correctAnswer"
v-html=" '✅ A resposta é ' + this.correctAnswer + ' Parabéns você acertou.'">
</h4>
<h4 v-else
v-html = "'❌ I´m sorry,you picked the wrong answer.The coorect is ' + this.correctAnswer + '.'"></h4>
<button @click="this.getNewQuestion()" class="send" type="button">
Próxima questao
</button>
</section>
</div>
</template>
<script>
import ScoreBoard from '@/components/ScoreBoard.vue'
export default {
name: 'App',
components: {
ScoreBoard
},
data(){
return {
question:undefined,
incorrectAnswers: undefined,
correctAnswer: undefined,
choose_answer:undefined,
answersSubmmited:false,
contador: 0,
pontosComputador: 0,
}
},
computed:{
answers(){
var answers = JSON.parse(JSON.stringify(this.incorrectAnswers));
answers.splice(Math.round(Math.random() * answers.length) , 0, this.correctAnswer);
return answers;
}
},
methods:{
submitAnswer(){
if(!this.choose_answer){
alert("Escolha uma opcão");
}else{
this.answersSubmmited = true;
if(this.choose_answer == this.correctAnswer){
this.contador++;
}else{
this.pontosComputador++;
}
}
},
getNewQuestion(){
this.answersSubmmited = false;
this.choose_answer = undefined;
this.question = undefined;
this.axios
.get("https://opentdb.com/api.php?amount=1&category=18")
.then((res) => {
this.question =res.data.results[0].question;
this.incorrectAnswers =res.data.results[0].incorrect_answers;
this.correctAnswer =res.data.results[0].correct_answer;
//console.log(res.data.results[0])
})
.catch((error) => {
console.log(error);
});
}
},
created(){
this.getNewQuestion();
}
}
</script>
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin: 60px auto;
max-width: 960px;
input[type-radio]{
margin: 12px 4px;
}
button.send{
margin-top:12px;
height: 40px;
min-width: 120px;
padding: 0 16px;
color:#fff;
background-color: #1867c0;
border: 1px solid #1867c0;
cursor: pointer;
}
}
</style> |
class RegisterResponse {
RegisterResponse({
this.status,
this.token,
this.data,});
RegisterResponse.fromJson(dynamic json) {
status = json['status'];
token = json['token'];
data = json['data'] != null ? Data.fromJson(json['data']) : null;
}
String? status;
String? token;
Data? data;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['status'] = status;
map['token'] = token;
if (data != null) {
map['data'] = data?.toJson();
}
return map;
}
}
class Data {
Data({
this.firstName,
this.lastName,
this.email,
this.password,
this.phone,
this.photo,
this.id,
this.v,});
Data.fromJson(dynamic json) {
firstName = json['firstName'];
lastName = json['lastName'];
email = json['email'];
password = json['password'];
phone = json['phone'];
photo = json['photo'] != null ? Photo.fromJson(json['photo']) : null;
id = json['_id'];
v = json['__v'];
}
String? firstName;
String? lastName;
String? email;
String? password;
String? phone;
Photo? photo;
String? id;
num? v;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['firstName'] = firstName;
map['lastName'] = lastName;
map['email'] = email;
map['password'] = password;
map['phone'] = phone;
if (photo != null) {
map['photo'] = photo?.toJson();
}
map['_id'] = id;
map['__v'] = v;
return map;
}
}
class Photo {
Photo({
this.url,
this.publicId,});
Photo.fromJson(dynamic json) {
url = json['url'];
publicId = json['public_id'];
}
String? url;
String? publicId;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['url'] = url;
map['public_id'] = publicId;
return map;
}
} |
<template>
<v-snackbar
v-model="snackbar"
:color="notification.type"
:value="true"
:light="notification.isLight"
bottom
right
>
<v-icon class="mr-2">{{ notification.icon }}</v-icon>
{{ notification.message }}
<template v-slot:action="{ attrs }">
<v-btn v-bind="attrs" @click.stop="snackbar = false" icon>
<v-icon>mdi-close</v-icon>
</v-btn>
</template>
</v-snackbar>
</template>
<script>
import { mapActions } from 'vuex'
export default {
name: 'NotificationBar',
props: {
notification: {
type: Object,
required: true,
},
},
computed: {
notificationType() {
return this.notification.type
},
},
data: () => ({
snackbar: false,
timeout: null,
}),
created() {
this.snackbar = true
},
mounted() {
this.timeout = setTimeout(() => this.remove(this.notification), 3000)
},
beforeDestroy() {
this.snackbar = false
clearTimeout(this.timeout)
},
methods: mapActions('notification', ['remove']),
}
</script> |
import React, { Component } from 'react';
import styled, { ThemeProvider, injectGlobal } from 'styled-components';
import Meta from '../components/Meta';
const theme = {
black: '#393939',
grey: '#3A3A3A',
lightgrey: '#E1E1E1',
offWhite: '#EDEDED',
maxWidth: '1000px',
};
const StyledPage = styled.div`
background: white;
color: ${props => props.theme.black};
`
const Inner = styled.div`
max-width: ${props => props.theme.maxWidth};
margin: 0 auto;
padding: 2rem;
`
class Page extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<StyledPage>
<Meta />
<Inner>{this.props.children}</Inner>
</StyledPage>
</ThemeProvider>
);
}
}
export default Page; |
@using E_Commerce.Core.Data;
@model RegisterVM
@{
ViewData["Title"] = "Sign up View";
}
<div class="row">
<div class="col-md-6 offset-3">
<p><h4>Sign up to new account</h4></p>
@if (TempData["Error"] != null)
{
<div class="col-md-12 offset-2 alert-danger">
<span><b>Sorry!</b>-@TempData["Error"]</span>
</div>
}
<div class="row">
<div class="col-md-8 offset-2">
<form asp-action="Register"asp-controller="Account">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SurName" class="control-label"></label>
<input asp-for="SurName" class="form-control" />
<span asp-validation-for="SurName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmailAddress" class="control-label"></label>
<input asp-for="EmailAddress" class="form-control" />
<span asp-validation-for="EmailAddress" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PhoneNumber" class="control-label"></label>
<input asp-for="PhoneNumber" class="form-control" />
<span asp-validation-for="PhoneNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="IdentityNumber" class="control-label"></label>
<input asp-for="IdentityNumber" class="form-control" />
<span asp-validation-for="IdentityNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="City" class="control-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Country" class="control-label"></label>
<input asp-for="Country" class="form-control" />
<span asp-validation-for="Country" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ZipCode" class="control-label"></label>
<input asp-for="ZipCode" class="form-control" />
<span asp-validation-for="ZipCode" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ConfirmPassword" class="control-label"></label>
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="SignUp" class="btn btn-outline-success float-end" />
<a class="btn btn-outline-secondary" asp-controller="Movies" asp-action="Index">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div> |
import { useContext, useState } from 'react'
import logo from '../../assets/B2Bit_logo.png'
import { Container, HeaderImage, LoginCard, Wrapper } from './styles'
import { InputBlock } from '../../components/InputBlock';
import { Button } from '../../components/Button';
import { sendCredentialsLoginRequest } from '../../utils/sendCredentialsLoginRequest';
import { UserData } from '../../Types/UserData';
import { TokenData } from '../../Types/TokenData';
import { UserContext } from '../../contexts/UserContext';
import { useNavigate } from 'react-router-dom';
import toast, { Toaster } from 'react-hot-toast';
export function Login() {
const [emailInput, setEmailInput] = useState('');
const [passwordInput, setPasswordInput] = useState('');
const { setUserData } = useContext(UserContext);
const navigate = useNavigate();
const handleSubmit = async() => {
try{
const requestResponse = await sendCredentialsLoginRequest(emailInput, passwordInput)
const fetchedUserData :UserData = requestResponse.user;
const fetchedTokenData :TokenData = requestResponse.tokens;
handleLoginSuccess(fetchedUserData, fetchedTokenData);
}catch (error) {
handleLoginFailure();
}
}
function handleLoginSuccess(fetchedUserData :UserData, fetchedTokenData :TokenData){
setUserData!(fetchedUserData)
localStorage.setItem('accessToken', fetchedTokenData.access);
localStorage.setItem('isLoggedIn', 'true');
navigate('/user');
}
function handleLoginFailure(){
toast.error("Invalid credentials. Please try again.");
}
return (
<Container>
<LoginCard>
<Toaster />
<Wrapper>
<HeaderImage src={logo} />
<InputBlock
input={emailInput}
setInput={setEmailInput}
blockLabel='E-mail'
inputType='email'
placeholderText='[email protected]'
/>
<InputBlock
input={passwordInput}
setInput={setPasswordInput}
blockLabel='Password'
inputType='password'
placeholderText='your password'
/>
<Button
onClick={() => handleSubmit()}
text='Sign In'
/>
</Wrapper>
</LoginCard>
</Container>
)
} |
import express from 'express'
import render from 'preact-render-to-string'
import { Router } from 'wouter-preact'
import staticLocationHook from 'wouter-preact/static-location'
import { config as clientConfig } from './sample/artificialturf'
import { App } from './src/app'
// basic HTTP server via express:
const app = express()
const webpack = require('webpack')
const config = require('./webpack.config.js')
const compiler = webpack(config)
const webpackDevMiddleware = require('webpack-dev-middleware')
const htmlTemplate = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My site</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<link rel="shortcut icon" href="/asset/favicon.ico" />
<link rel="apple-touch-icon" href="/asset/icon/apple-touch-icon.png" />
<script type="text/javascript" src="/keyweb-bundle.js"></script>
<!-- <script type="text/javascript" src="/keyweb-vendors.js"></script> -->
</head>
<body>
<div id="root"></div>
</body>
</html>`
app.use(
webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
}),
)
// app.use(express.static(path.resolve(__dirname, './dist')))
app.use(express.static('./public'))
const PORT = 8080
// on each request, render and return a component:
app.get('/*', (req, res, next) => {
if (req.originalUrl.startsWith('/asset')) return next()
const html = render(
<Router hook={staticLocationHook(req.path)}>
<App config={clientConfig as any} />
</Router>,
)
// TODO: SEO for html content
if (!htmlTemplate) {
return res.status(500).send('Oops, better luck next time!')
}
return res.send(htmlTemplate.replace('<div id="root"></div>', `<div id="root">${html}</div>`))
})
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`)
}) |
=== WP Voting ===
Contributors: tristanmin
Donate link: http://www.wpclue.com/
Tags: plugin, voting
Requires at least: 3.0
Tested up to: 3.2.1
Stable tag: 1.8
Site owner to add voting functionality to the blog posts.
== Description ==
A plugin to site owner to add voting functionality to the blog posts.
Using the power of the ajax, voter can have instant voting and update to top voted widget.
It doesn't matter voter is logged in or not. Public voting is done by tracking their IP address.
It isn't end here. Blog owner will have complete control over those voting feature as well as using custom
vote button and vote text.
Features
1. Control voting feature via voting on/off (admin feature)
2. Control allow or disallow post author to vote his own posts (admin feature)
3. Control allow or disallow public voting (admin feature)
4. Customise vote and voted text (admin feature)
5. Customise vote and voted buttons images (admin feature)
6. Customise alert message for non logged in users (admin feature)
7. Voting logs for site administrator (admin feature)
8. Sort voting logs by vote count or voted date (admin feature)
9. Show current vote count and vote button on frontend templates
10. Compitible with almost all of the themes. You just need to call required function from your template
11. Total vote count widget
12. Top voted widget
13. Now public voting supported.
14. Now shortcode supported. e.g. [wpvoting]
15. Top voted posts list shortcode
Features in future releases
1. Export to CSV for admin voting logs
2. Registered user voting logs
3. Re-implement backend voting log list with WP_List_Table class
Note-1: Kindly please rate this plugin or vote the compatibility. So I could review it and improve the quality of this plugin. Appreciate your help!
Resources
http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/
http://www.onextrapixel.com/2009/06/22/how-to-add-pagination-into-list-of-records-or-wordpress-plugin/
http://www.onextrapixel.com/2009/07/01/how-to-design-and-style-your-wordpress-plugin-admin-panel/
http://planetozh.com/blog/2009/09/top-10-most-common-coding-mistakes-in-wordpress-plugins/
http://wordpress.org/extend/plugins/vote-it-up/
http://wordpress.org/extend/plugins/shortcodes-ultimate/
== Installation ==
1. Upload `wpv-voting` folder to `/wp-content/plugins/` directory
2. Activate the plugin through the 'Plugins' menu in WordPress
3. Go to Voting menu >> Voting Options and turn on the voting feature
4. You may add the custom alert message for non logged in users
5. You can use shortcode `[wpvoting]` directly in your posts content < OR >
6. Add `if(function_exists('wpv_voting_display_vote')) wpv_voting_display_vote(get_the_ID());` between the wordpress loop of your theme templates such as category.php or single.php
7. You may also use shortcodes or widgets
Shortcode usage
-- vote button --
`[wpvoting]`
-- top voted list --
`[wpv-top-voted show="10" nopostmsg="Nothing to show yet!"]`
Note: This plugin will create two tables in your wordpress database
== Frequently Asked Questions ==
Please check it out my blog http://www.wpclue.com/development/plugins/wordpress-voting-plugin/
== Screenshots ==
1. Sample vote count and voting button (logged in user)
2. After vote or post author view
3. Default alert message for un-logged in user
4. Sample admin voting logs
5. Admin voting options panel
== Changelog ==
= 1.0 =
* The first release of the plugin.
= 1.1 =
* Fixed broken images
= 1.2 =
* Added allow or disallow post author to vote his own posts feature
= 1.2.1 =
* Fixed voting on/off options not getting selected state after initial plugin activate
* Fixed allow post author to vote his own posts options not getting selected state after initial plugin activate
* Fixed allow post author to vote his own posts options not getting deleted after deactivate the plugin
= 1.3 =
* Added custom vote text feature
* Added custom voted text feature
* Added custom vote button feature
* Added custom voted button feature
= 1.4 =
* Added shortcode support
* Tested compability with WordPress 3.2.1
= 1.4.1 =
* Fixed the broken admin css
= 1.4.2 =
* Added reset all voting
= 1.5 =
* Added total vote count widget
* Re-design admin voting options page
= 1.5.1 =
* Added db version to options tbl for next release (public voting)
= 1.6 =
* Added public voting feature (unregistered / non-logged in users voting)
= 1.7 =
* Added top vote widget
* Add safe-guard javascript pop-up confirmation box for "Reset All" button
* Implemented proper un-installation (Now deactivate won't delete db tables and settings)
* Bug fix (two or more users voting from same computer can't vote)
= 1.8 =
* Added top voted list shortcode
* Added wpv_voting_get_display_vote function to overcome vote button is keep showing at the top of the post
* Now wpv_voting_display_vote will just echo out the wpv_voting_get_display_vote return
* Vote button implementation is moved to wpv_voting_get_display_vote
* Fixed vote button is keep showing at the top of the post when user uses [wpvoting] shortcode
* Fixed minor CSS rule
* Fixed minor spacing issue in javascript |
package ru.ssau.tk.Lilpank.Crate_to_practic.Point.task1_16;
import ru.ssau.tk.Lilpank.Crate_to_practic.Point.Point;
import ru.ssau.tk.Lilpank.Crate_to_practic.task1_18.Resettable;
import java.util.Objects;
public class NamedPoint extends Point implements Resettable {
public String name;
public NamedPoint() {
this(0, 0, 0, "Origin");
}
public NamedPoint(double x, double y, double z) {
super(x, y, z);
}
public NamedPoint(double x, double y, double z, String name) {
super(x, y, z);
this.name = name;
}
@Override
public String toString() {
if (Objects.equals(null, name)) return super.toString();
return name + ": " + super.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void reset() {
name = "Absent";
}
} |
import React, { useContext } from "react";
import {
HStack,
Text,
Stack,
useColorModeValue,
Divider,
IconButton,
useToast,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalFooter,
ModalBody,
ModalCloseButton,
Button,
useDisclosure,
} from "@chakra-ui/react";
import dateFormat from "dateformat";
import { DeleteIcon } from "@chakra-ui/icons";
import { UserContext } from "../../context";
import axios from "axios";
const Comment = ({
commentId,
author,
authorName,
body,
date,
fetchComments,
}) => {
const [user] = useContext(UserContext);
const toast = useToast();
const { isOpen, onOpen, onClose } = useDisclosure();
const handleDelete = () => {
axios
.delete(`https://teamcyd.herokuapp.com/comments/${commentId}`)
.then((res) => {
onClose();
toast({
title: "Successfully deleted the comment",
description: "",
status: "success",
duration: 2000,
isClosable: true,
});
fetchComments();
})
.catch((err) => {
console.log(err);
toast({
title: "Unable to delete the comment",
description: err.response.data.errors[0],
status: "error",
duration: 2000,
isClosable: true,
});
});
};
return (
<>
<Stack py={2}>
<HStack direction={"column"} spacing={0} fontSize={"xs"}>
<Text
fontWeight={600}
color={useColorModeValue("blue.400", "red.400")}
textAlign={"center"}
>
{authorName}
</Text>
<Text
color={useColorModeValue("gray.700", "white.300")}
fontSize={"xs"}
px={2}
>
{dateFormat(date, "mmmm dS, yyyy, h:MM TT")}
</Text>
{author === user.user.id && (
<IconButton
onClick={onOpen}
size={"xs"}
aria-label="delete"
icon={<DeleteIcon />}
/>
)}
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Delete Comment</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Text>{"Are your sure you want to delete the comment?"}</Text>
</ModalBody>
<ModalFooter>
<Button
colorScheme={"red"}
onClick={() => handleDelete()}
mr={3}
>
Delete
</Button>
<Button onClick={onClose}>Cancel</Button>
</ModalFooter>
</ModalContent>
</Modal>
</HStack>
<Text
color={useColorModeValue("gray.700", "white.300")}
fontSize={"sm"}
>
{body}
</Text>
</Stack>
<Divider />
</>
);
};
export default Comment; |
use crate::db::ExtensionVersionConstraints;
use crate::{db::NewExtensionVersion, AppState, Error, Result};
use anyhow::{anyhow, Context as _};
use aws_sdk_s3::presigning::PresigningConfig;
use axum::{
extract::{Path, Query},
http::StatusCode,
response::Redirect,
routing::get,
Extension, Json, Router,
};
use collections::HashMap;
use rpc::{ExtensionApiManifest, GetExtensionsResponse};
use semantic_version::SemanticVersion;
use serde::Deserialize;
use std::{sync::Arc, time::Duration};
use time::PrimitiveDateTime;
use util::{maybe, ResultExt};
pub fn router() -> Router {
Router::new()
.route("/extensions", get(get_extensions))
.route("/extensions/updates", get(get_extension_updates))
.route("/extensions/:extension_id", get(get_extension_versions))
.route(
"/extensions/:extension_id/download",
get(download_latest_extension),
)
.route(
"/extensions/:extension_id/:version/download",
get(download_extension),
)
}
#[derive(Debug, Deserialize)]
struct GetExtensionsParams {
filter: Option<String>,
#[serde(default)]
max_schema_version: i32,
}
async fn get_extensions(
Extension(app): Extension<Arc<AppState>>,
Query(params): Query<GetExtensionsParams>,
) -> Result<Json<GetExtensionsResponse>> {
let extensions = app
.db
.get_extensions(params.filter.as_deref(), params.max_schema_version, 500)
.await?;
if let Some(query) = params.filter.as_deref() {
let count = extensions.len();
tracing::info!(query, count, "extension_search")
}
Ok(Json(GetExtensionsResponse { data: extensions }))
}
#[derive(Debug, Deserialize)]
struct GetExtensionUpdatesParams {
ids: String,
min_schema_version: i32,
max_schema_version: i32,
min_wasm_api_version: SemanticVersion,
max_wasm_api_version: SemanticVersion,
}
async fn get_extension_updates(
Extension(app): Extension<Arc<AppState>>,
Query(params): Query<GetExtensionUpdatesParams>,
) -> Result<Json<GetExtensionsResponse>> {
let constraints = ExtensionVersionConstraints {
schema_versions: params.min_schema_version..=params.max_schema_version,
wasm_api_versions: params.min_wasm_api_version..=params.max_wasm_api_version,
};
let extension_ids = params.ids.split(',').map(|s| s.trim()).collect::<Vec<_>>();
let extensions = app
.db
.get_extensions_by_ids(&extension_ids, Some(&constraints))
.await?;
Ok(Json(GetExtensionsResponse { data: extensions }))
}
#[derive(Debug, Deserialize)]
struct GetExtensionVersionsParams {
extension_id: String,
}
async fn get_extension_versions(
Extension(app): Extension<Arc<AppState>>,
Path(params): Path<GetExtensionVersionsParams>,
) -> Result<Json<GetExtensionsResponse>> {
let extension_versions = app.db.get_extension_versions(¶ms.extension_id).await?;
Ok(Json(GetExtensionsResponse {
data: extension_versions,
}))
}
#[derive(Debug, Deserialize)]
struct DownloadLatestExtensionPathParams {
extension_id: String,
}
#[derive(Debug, Deserialize)]
struct DownloadLatestExtensionQueryParams {
min_schema_version: Option<i32>,
max_schema_version: Option<i32>,
min_wasm_api_version: Option<SemanticVersion>,
max_wasm_api_version: Option<SemanticVersion>,
}
async fn download_latest_extension(
Extension(app): Extension<Arc<AppState>>,
Path(params): Path<DownloadLatestExtensionPathParams>,
Query(query): Query<DownloadLatestExtensionQueryParams>,
) -> Result<Redirect> {
let constraints = maybe!({
let min_schema_version = query.min_schema_version?;
let max_schema_version = query.max_schema_version?;
let min_wasm_api_version = query.min_wasm_api_version?;
let max_wasm_api_version = query.max_wasm_api_version?;
Some(ExtensionVersionConstraints {
schema_versions: min_schema_version..=max_schema_version,
wasm_api_versions: min_wasm_api_version..=max_wasm_api_version,
})
});
let extension = app
.db
.get_extension(¶ms.extension_id, constraints.as_ref())
.await?
.ok_or_else(|| anyhow!("unknown extension"))?;
download_extension(
Extension(app),
Path(DownloadExtensionParams {
extension_id: params.extension_id,
version: extension.manifest.version.to_string(),
}),
)
.await
}
#[derive(Debug, Deserialize)]
struct DownloadExtensionParams {
extension_id: String,
version: String,
}
async fn download_extension(
Extension(app): Extension<Arc<AppState>>,
Path(params): Path<DownloadExtensionParams>,
) -> Result<Redirect> {
let Some((blob_store_client, bucket)) = app
.blob_store_client
.clone()
.zip(app.config.blob_store_bucket.clone())
else {
Err(Error::Http(
StatusCode::NOT_IMPLEMENTED,
"not supported".into(),
))?
};
let DownloadExtensionParams {
extension_id,
version,
} = params;
let version_exists = app
.db
.record_extension_download(&extension_id, &version)
.await?;
if !version_exists {
Err(Error::Http(
StatusCode::NOT_FOUND,
"unknown extension version".into(),
))?;
}
let url = blob_store_client
.get_object()
.bucket(bucket)
.key(format!(
"extensions/{extension_id}/{version}/archive.tar.gz"
))
.presigned(PresigningConfig::expires_in(EXTENSION_DOWNLOAD_URL_LIFETIME).unwrap())
.await
.map_err(|e| anyhow!("failed to create presigned extension download url {e}"))?;
Ok(Redirect::temporary(url.uri()))
}
const EXTENSION_FETCH_INTERVAL: Duration = Duration::from_secs(5 * 60);
const EXTENSION_DOWNLOAD_URL_LIFETIME: Duration = Duration::from_secs(3 * 60);
pub fn fetch_extensions_from_blob_store_periodically(app_state: Arc<AppState>) {
let Some(blob_store_client) = app_state.blob_store_client.clone() else {
log::info!("no blob store client");
return;
};
let Some(blob_store_bucket) = app_state.config.blob_store_bucket.clone() else {
log::info!("no blob store bucket");
return;
};
let executor = app_state.executor.clone();
executor.spawn_detached({
let executor = executor.clone();
async move {
loop {
fetch_extensions_from_blob_store(
&blob_store_client,
&blob_store_bucket,
&app_state,
)
.await
.log_err();
executor.sleep(EXTENSION_FETCH_INTERVAL).await;
}
}
});
}
async fn fetch_extensions_from_blob_store(
blob_store_client: &aws_sdk_s3::Client,
blob_store_bucket: &String,
app_state: &Arc<AppState>,
) -> anyhow::Result<()> {
log::info!("fetching extensions from blob store");
let mut next_marker = None;
let mut published_versions = HashMap::<String, Vec<String>>::default();
loop {
let list = blob_store_client
.list_objects()
.bucket(blob_store_bucket)
.prefix("extensions/")
.set_marker(next_marker.clone())
.send()
.await?;
let objects = list.contents.unwrap_or_default();
log::info!("fetched {} object(s) from blob store", objects.len());
for object in &objects {
let Some(key) = object.key.as_ref() else {
continue;
};
let mut parts = key.split('/');
let Some(_) = parts.next().filter(|part| *part == "extensions") else {
continue;
};
let Some(extension_id) = parts.next() else {
continue;
};
let Some(version) = parts.next() else {
continue;
};
if parts.next() == Some("manifest.json") {
published_versions
.entry(extension_id.to_owned())
.or_default()
.push(version.to_owned());
}
}
if let (Some(true), Some(last_object)) = (list.is_truncated, objects.last()) {
next_marker.clone_from(&last_object.key);
} else {
break;
}
}
log::info!("found {} published extensions", published_versions.len());
let known_versions = app_state.db.get_known_extension_versions().await?;
let mut new_versions = HashMap::<&str, Vec<NewExtensionVersion>>::default();
let empty = Vec::new();
for (extension_id, published_versions) in &published_versions {
let known_versions = known_versions.get(extension_id).unwrap_or(&empty);
for published_version in published_versions {
if known_versions
.binary_search_by_key(&published_version, |known_version| known_version)
.is_err()
{
if let Some(extension) = fetch_extension_manifest(
blob_store_client,
blob_store_bucket,
&extension_id,
&published_version,
)
.await
.log_err()
{
new_versions
.entry(&extension_id)
.or_default()
.push(extension);
}
}
}
}
app_state
.db
.insert_extension_versions(&new_versions)
.await?;
log::info!(
"fetched {} new extensions from blob store",
new_versions.values().map(|v| v.len()).sum::<usize>()
);
Ok(())
}
async fn fetch_extension_manifest(
blob_store_client: &aws_sdk_s3::Client,
blob_store_bucket: &String,
extension_id: &str,
version: &str,
) -> Result<NewExtensionVersion, anyhow::Error> {
let object = blob_store_client
.get_object()
.bucket(blob_store_bucket)
.key(format!("extensions/{extension_id}/{version}/manifest.json"))
.send()
.await?;
let manifest_bytes = object
.body
.collect()
.await
.map(|data| data.into_bytes())
.with_context(|| {
format!("failed to download manifest for extension {extension_id} version {version}")
})?
.to_vec();
let manifest =
serde_json::from_slice::<ExtensionApiManifest>(&manifest_bytes).with_context(|| {
format!(
"invalid manifest for extension {extension_id} version {version}: {}",
String::from_utf8_lossy(&manifest_bytes)
)
})?;
let published_at = object.last_modified.ok_or_else(|| {
anyhow!("missing last modified timestamp for extension {extension_id} version {version}")
})?;
let published_at = time::OffsetDateTime::from_unix_timestamp_nanos(published_at.as_nanos())?;
let published_at = PrimitiveDateTime::new(published_at.date(), published_at.time());
let version = semver::Version::parse(&manifest.version).with_context(|| {
format!("invalid version for extension {extension_id} version {version}")
})?;
Ok(NewExtensionVersion {
name: manifest.name,
version,
description: manifest.description.unwrap_or_default(),
authors: manifest.authors,
repository: manifest.repository,
schema_version: manifest.schema_version.unwrap_or(0),
wasm_api_version: manifest.wasm_api_version,
published_at,
})
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.beam.sdk.io.solr;
import ObjectReleaseTracker.OBJECTS;
import Pipeline.PipelineExecutionException;
import SolrException.ErrorCode;
import SolrException.ErrorCode.SERVICE_UNAVAILABLE;
import SolrIO.ConnectionConfiguration;
import SolrIO.RetryConfiguration;
import SolrIO.Write;
import SolrIO.Write.WriteFn.RETRY_ATTEMPT_LOG;
import SolrTestCaseJ4.SuppressSSL;
import ThreadLeakScope.Scope;
import com.carrotsearch.ant.tasks.junit4.dependencies.com.google.common.collect.ImmutableSet;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.testing.ExpectedLogs;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFnTester;
import org.apache.beam.sdk.values.PCollection;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.cloud.SolrCloudTestCase;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.util.ObjectReleaseTracker;
import org.joda.time.Duration;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A test of {@link SolrIO} on an independent Solr instance.
*/
@ThreadLeakScope(Scope.NONE)
@SolrTestCaseJ4.SuppressSSL
public class SolrIOTest extends SolrCloudTestCase {
private static final Logger LOG = LoggerFactory.getLogger(SolrIOTest.class);
private static final String SOLR_COLLECTION = "beam";
private static final int NUM_SHARDS = 3;
private static final long NUM_DOCS = 400L;
private static final int NUM_SCIENTISTS = 10;
private static final int BATCH_SIZE = 200;
private static final int DEFAULT_BATCH_SIZE = 1000;
private static AuthorizedSolrClient<CloudSolrClient> solrClient;
private static ConnectionConfiguration connectionConfiguration;
@Rule
public TestPipeline pipeline = TestPipeline.create();
@Rule
public final transient ExpectedLogs expectedLogs = ExpectedLogs.none(SolrIO.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testBadCredentials() throws IOException {
thrown.expect(SolrException.class);
String zkAddress = cluster.getZkServer().getZkAddress();
SolrIO.ConnectionConfiguration connectionConfiguration = ConnectionConfiguration.create(zkAddress).withBasicCredentials("solr", "wrongpassword");
try (AuthorizedSolrClient solrClient = connectionConfiguration.createClient()) {
SolrIOTestUtils.insertTestDocuments(SolrIOTest.SOLR_COLLECTION, SolrIOTest.NUM_DOCS, solrClient);
}
}
@Test
public void testRead() throws Exception {
SolrIOTestUtils.insertTestDocuments(SolrIOTest.SOLR_COLLECTION, SolrIOTest.NUM_DOCS, SolrIOTest.solrClient);
PCollection<SolrDocument> output = pipeline.apply(SolrIO.read().withConnectionConfiguration(SolrIOTest.connectionConfiguration).from(SolrIOTest.SOLR_COLLECTION).withBatchSize(101));
PAssert.thatSingleton(output.apply("Count", Count.globally())).isEqualTo(SolrIOTest.NUM_DOCS);
pipeline.run();
}
@Test
public void testReadWithQuery() throws Exception {
SolrIOTestUtils.insertTestDocuments(SolrIOTest.SOLR_COLLECTION, SolrIOTest.NUM_DOCS, SolrIOTest.solrClient);
PCollection<SolrDocument> output = pipeline.apply(SolrIO.read().withConnectionConfiguration(SolrIOTest.connectionConfiguration).from(SolrIOTest.SOLR_COLLECTION).withQuery("scientist:Franklin"));
PAssert.thatSingleton(output.apply("Count", Count.globally())).isEqualTo(((SolrIOTest.NUM_DOCS) / (SolrIOTest.NUM_SCIENTISTS)));
pipeline.run();
}
@Test
public void testWrite() throws Exception {
List<SolrInputDocument> data = SolrIOTestUtils.createDocuments(SolrIOTest.NUM_DOCS);
SolrIO.Write write = SolrIO.write().withConnectionConfiguration(SolrIOTest.connectionConfiguration).to(SolrIOTest.SOLR_COLLECTION);
pipeline.apply(Create.of(data)).apply(write);
pipeline.run();
long currentNumDocs = SolrIOTestUtils.commitAndGetCurrentNumDocs(SolrIOTest.SOLR_COLLECTION, SolrIOTest.solrClient);
assertEquals(SolrIOTest.NUM_DOCS, currentNumDocs);
QueryResponse response = SolrIOTest.solrClient.query(SolrIOTest.SOLR_COLLECTION, new SolrQuery("scientist:Lovelace"));
assertEquals(((SolrIOTest.NUM_DOCS) / (SolrIOTest.NUM_SCIENTISTS)), response.getResults().getNumFound());
}
@Test
public void testWriteWithMaxBatchSize() throws Exception {
SolrIO.Write write = SolrIO.write().withConnectionConfiguration(SolrIOTest.connectionConfiguration).to(SolrIOTest.SOLR_COLLECTION).withMaxBatchSize(SolrIOTest.BATCH_SIZE);
// write bundles size is the runner decision, we cannot force a bundle size,
// so we test the Writer as a DoFn outside of a runner.
try (DoFnTester<SolrInputDocument, Void> fnTester = DoFnTester.of(new SolrIO.Write.WriteFn(write))) {
List<SolrInputDocument> input = SolrIOTestUtils.createDocuments(SolrIOTest.NUM_DOCS);
long numDocsProcessed = 0;
long numDocsInserted = 0;
for (SolrInputDocument document : input) {
fnTester.processElement(document);
numDocsProcessed++;
// test every 100 docs to avoid overloading Solr
if ((numDocsProcessed % 100) == 0) {
// force the index to upgrade after inserting for the inserted docs
// to be searchable immediately
long currentNumDocs = SolrIOTestUtils.commitAndGetCurrentNumDocs(SolrIOTest.SOLR_COLLECTION, SolrIOTest.solrClient);
if ((numDocsProcessed % (SolrIOTest.BATCH_SIZE)) == 0) {
/* bundle end */
assertEquals("we are at the end of a bundle, we should have inserted all processed documents", numDocsProcessed, currentNumDocs);
numDocsInserted = currentNumDocs;
} else {
/* not bundle end */
assertEquals("we are not at the end of a bundle, we should have inserted no more documents", numDocsInserted, currentNumDocs);
}
}
}
}
}
/**
* Test that retries are invoked when Solr returns error. We invoke this by calling a non existing
* collection, and use a strategy that will retry on any SolrException. The logger is used to
* verify expected behavior.
*/
@Test
public void testWriteRetry() throws Throwable {
thrown.expect(IOException.class);
thrown.expectMessage("Error writing to Solr");
// entry state of the release tracker to ensure we only unregister newly created objects
@SuppressWarnings("unchecked")
Set<Object> entryState = ImmutableSet.copyOf(OBJECTS.keySet());
SolrIO.Write write = SolrIO.write().withConnectionConfiguration(SolrIOTest.connectionConfiguration).withRetryConfiguration(RetryConfiguration.create(3, Duration.standardMinutes(3)).withRetryPredicate(new SolrIOTestUtils.LenientRetryPredicate())).to("wrong-collection");
List<SolrInputDocument> data = SolrIOTestUtils.createDocuments(SolrIOTest.NUM_DOCS);
pipeline.apply(Create.of(data)).apply(write);
try {
pipeline.run();
} catch (final Pipeline e) {
// Hack: await all worker threads completing (BEAM-4040)
int waitAttempts = 30;// defensive coding
while ((SolrIOTestUtils.namedThreadIsAlive("direct-runner-worker")) && ((waitAttempts--) >= 0)) {
SolrIOTest.LOG.info("Pausing to allow direct-runner-worker threads to finish");
Thread.sleep(1000);
}
// remove solrClients created by us as there are no guarantees on Teardown here
for (Object o : OBJECTS.keySet()) {
if ((o instanceof SolrZkClient) && (!(entryState.contains(o)))) {
SolrIOTest.LOG.info("Removing unreleased SolrZkClient");
ObjectReleaseTracker.release(o);
}
}
// check 2 retries were initiated by inspecting the log before passing on the exception
expectedLogs.verifyWarn(String.format(RETRY_ATTEMPT_LOG, 1));
expectedLogs.verifyWarn(String.format(RETRY_ATTEMPT_LOG, 2));
throw e.getCause();
}
fail("Pipeline should not have run to completion");
}
/**
* Tests predicate performs as documented.
*/
@Test
public void testDefaultRetryPredicate() {
assertTrue(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new IOException("test")));
assertTrue(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrServerException("test")));
assertTrue(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.CONFLICT, "test")));
assertTrue(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.SERVER_ERROR, "test")));
assertTrue(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "test")));
assertTrue(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.INVALID_STATE, "test")));
assertTrue(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.UNKNOWN, "test")));
assertTrue(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new org.apache.solr.client.solrj.impl.HttpSolrClient.RemoteSolrException("localhost", SERVICE_UNAVAILABLE.code, "test", new Exception())));
assertFalse(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.BAD_REQUEST, "test")));
assertFalse(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.FORBIDDEN, "test")));
assertFalse(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.NOT_FOUND, "test")));
assertFalse(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.UNAUTHORIZED, "test")));
assertFalse(RetryConfiguration.DEFAULT_RETRY_PREDICATE.test(new SolrException(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "test")));
}
/**
* Tests batch size default and changed value.
*/
@Test
public void testBatchSize() {
SolrIO.Write write1 = SolrIO.write().withConnectionConfiguration(SolrIOTest.connectionConfiguration).withMaxBatchSize(SolrIOTest.BATCH_SIZE);
assertTrue(((write1.getMaxBatchSize()) == (SolrIOTest.BATCH_SIZE)));
SolrIO.Write write2 = SolrIO.write().withConnectionConfiguration(SolrIOTest.connectionConfiguration);
assertTrue(((write2.getMaxBatchSize()) == (SolrIOTest.DEFAULT_BATCH_SIZE)));
}
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 30
void err_handling(char *message);
void read_routine(int sock, char *buf);
void write_routine(int sock, char *buf);
int main(int argc, char *argv[])
{
int sock;
pid_t pid;
char buf[BUF_SIZE];
struct sockaddr_in serv_addr;
if(argc != 3)
{
printf("Usage : %s <IP> <port> \n", argv[0]);
exit(1);
}
sock = socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port = htons(atoi(argv[2]));
if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1)
{
err_handling("connect() error");
}
pid = fork();
if(pid == 0)
{
write_routine(sock, buf);
}
else
{
read_routine(sock, buf);
}
close(sock);
return 0;
}
void read_routine(int sock, char *buf)
{
while(1)
{
int str_len = read(sock, buf, BUF_SIZE);
if(str_len == 0)
{
return;
}
buf[str_len] = 0;
printf("Message from server: %s", buf);
}
}
void write_routine(int sock, char *buf)
{
while(1)
{
fgets(buf, BUF_SIZE, stdin);
if(!strcmp(buf, "q\n") || !strcmp(buf, "Q\n"))
{
shutdown(sock, SHUT_WR);
return;
}
write(sock, buf, strlen(buf));
}
}
void err_handling(char *message)
{
fputs(message, stderr);
putc('\n', stderr);
exit(1);
} |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sensors_plus/sensors_plus.dart';
import 'snake.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
],
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sensors Demo',
theme: ThemeData(
useMaterial3: true,
colorSchemeSeed: const Color(0x9f4376f8),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, this.title});
final String? title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static const Duration _ignoreDuration = Duration(milliseconds: 20);
static const int _snakeRows = 20;
static const int _snakeColumns = 20;
static const double _snakeCellSize = 10.0;
UserAccelerometerEvent? _userAccelerometerEvent;
AccelerometerEvent? _accelerometerEvent;
GyroscopeEvent? _gyroscopeEvent;
MagnetometerEvent? _magnetometerEvent;
DateTime? _userAccelerometerUpdateTime;
DateTime? _accelerometerUpdateTime;
DateTime? _gyroscopeUpdateTime;
DateTime? _magnetometerUpdateTime;
int? _userAccelerometerLastInterval;
int? _accelerometerLastInterval;
int? _gyroscopeLastInterval;
int? _magnetometerLastInterval;
final _streamSubscriptions = <StreamSubscription<dynamic>>[];
Duration sensorInterval = SensorInterval.normalInterval;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sensors Plus Example'),
elevation: 4,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(width: 1.0, color: Colors.black38),
),
child: SizedBox(
height: _snakeRows * _snakeCellSize,
width: _snakeColumns * _snakeCellSize,
child: Snake(
rows: _snakeRows,
columns: _snakeColumns,
cellSize: _snakeCellSize,
),
),
),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Table(
columnWidths: const {
0: FlexColumnWidth(4),
4: FlexColumnWidth(2),
},
children: [
const TableRow(
children: [
SizedBox.shrink(),
Text('X'),
Text('Y'),
Text('Z'),
Text('Interval'),
],
),
TableRow(
children: [
const Padding(
padding: EdgeInsets.symmetric(vertical: 8.0),
child: Text('UserAccelerometer'),
),
Text(_userAccelerometerEvent?.x.toStringAsFixed(1) ?? '?'),
Text(_userAccelerometerEvent?.y.toStringAsFixed(1) ?? '?'),
Text(_userAccelerometerEvent?.z.toStringAsFixed(1) ?? '?'),
Text(
'${_userAccelerometerLastInterval?.toString() ?? '?'} ms'),
],
),
TableRow(
children: [
const Padding(
padding: EdgeInsets.symmetric(vertical: 8.0),
child: Text('Accelerometer'),
),
Text(_accelerometerEvent?.x.toStringAsFixed(1) ?? '?'),
Text(_accelerometerEvent?.y.toStringAsFixed(1) ?? '?'),
Text(_accelerometerEvent?.z.toStringAsFixed(1) ?? '?'),
Text('${_accelerometerLastInterval?.toString() ?? '?'} ms'),
],
),
TableRow(
children: [
const Padding(
padding: EdgeInsets.symmetric(vertical: 8.0),
child: Text('Gyroscope'),
),
Text(_gyroscopeEvent?.x.toStringAsFixed(1) ?? '?'),
Text(_gyroscopeEvent?.y.toStringAsFixed(1) ?? '?'),
Text(_gyroscopeEvent?.z.toStringAsFixed(1) ?? '?'),
Text('${_gyroscopeLastInterval?.toString() ?? '?'} ms'),
],
),
TableRow(
children: [
const Padding(
padding: EdgeInsets.symmetric(vertical: 8.0),
child: Text('Magnetometer'),
),
Text(_magnetometerEvent?.x.toStringAsFixed(1) ?? '?'),
Text(_magnetometerEvent?.y.toStringAsFixed(1) ?? '?'),
Text(_magnetometerEvent?.z.toStringAsFixed(1) ?? '?'),
Text('${_magnetometerLastInterval?.toString() ?? '?'} ms'),
],
),
],
),
),
Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Update Interval:'),
SegmentedButton(
segments: [
ButtonSegment(
value: SensorInterval.gameInterval,
label: Text('Game\n'
'(${SensorInterval.gameInterval.inMilliseconds}ms)'),
),
ButtonSegment(
value: SensorInterval.uiInterval,
label: Text('UI\n'
'(${SensorInterval.uiInterval.inMilliseconds}ms)'),
),
ButtonSegment(
value: SensorInterval.normalInterval,
label: Text('Normal\n'
'(${SensorInterval.normalInterval.inMilliseconds}ms)'),
),
const ButtonSegment(
value: Duration(milliseconds: 500),
label: Text('500ms'),
),
const ButtonSegment(
value: Duration(seconds: 1),
label: Text('1s'),
),
],
selected: {sensorInterval},
showSelectedIcon: false,
onSelectionChanged: (value) {
setState(() {
sensorInterval = value.first;
userAccelerometerEventStream(
samplingPeriod: sensorInterval);
accelerometerEventStream(samplingPeriod: sensorInterval);
gyroscopeEventStream(samplingPeriod: sensorInterval);
magnetometerEventStream(samplingPeriod: sensorInterval);
});
},
),
],
),
],
),
);
}
@override
void dispose() {
super.dispose();
for (final subscription in _streamSubscriptions) {
subscription.cancel();
}
}
@override
void initState() {
super.initState();
_streamSubscriptions.add(
userAccelerometerEventStream(samplingPeriod: sensorInterval).listen(
(UserAccelerometerEvent event) {
final now = DateTime.now();
setState(() {
_userAccelerometerEvent = event;
if (_userAccelerometerUpdateTime != null) {
final interval = now.difference(_userAccelerometerUpdateTime!);
if (interval > _ignoreDuration) {
_userAccelerometerLastInterval = interval.inMilliseconds;
}
}
});
_userAccelerometerUpdateTime = now;
},
onError: (e) {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text("Sensor Not Found"),
content: Text(
"It seems that your device doesn't support User Accelerometer Sensor"),
);
});
},
cancelOnError: true,
),
);
_streamSubscriptions.add(
accelerometerEventStream(samplingPeriod: sensorInterval).listen(
(AccelerometerEvent event) {
final now = DateTime.now();
setState(() {
_accelerometerEvent = event;
if (_accelerometerUpdateTime != null) {
final interval = now.difference(_accelerometerUpdateTime!);
if (interval > _ignoreDuration) {
_accelerometerLastInterval = interval.inMilliseconds;
}
}
});
_accelerometerUpdateTime = now;
},
onError: (e) {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text("Sensor Not Found"),
content: Text(
"It seems that your device doesn't support Accelerometer Sensor"),
);
});
},
cancelOnError: true,
),
);
_streamSubscriptions.add(
gyroscopeEventStream(samplingPeriod: sensorInterval).listen(
(GyroscopeEvent event) {
final now = DateTime.now();
setState(() {
_gyroscopeEvent = event;
if (_gyroscopeUpdateTime != null) {
final interval = now.difference(_gyroscopeUpdateTime!);
if (interval > _ignoreDuration) {
_gyroscopeLastInterval = interval.inMilliseconds;
}
}
});
_gyroscopeUpdateTime = now;
},
onError: (e) {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text("Sensor Not Found"),
content: Text(
"It seems that your device doesn't support Gyroscope Sensor"),
);
});
},
cancelOnError: true,
),
);
_streamSubscriptions.add(
magnetometerEventStream(samplingPeriod: sensorInterval).listen(
(MagnetometerEvent event) {
final now = DateTime.now();
setState(() {
_magnetometerEvent = event;
if (_magnetometerUpdateTime != null) {
final interval = now.difference(_magnetometerUpdateTime!);
if (interval > _ignoreDuration) {
_magnetometerLastInterval = interval.inMilliseconds;
}
}
});
_magnetometerUpdateTime = now;
},
onError: (e) {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text("Sensor Not Found"),
content: Text(
"It seems that your device doesn't support Magnetometer Sensor"),
);
});
},
cancelOnError: true,
),
);
}
} |
<?php
namespace Controllers;
use MVC\Router;
use Model\Propiedad;
use Model\vendedores;
use Intervention\Image\ImageManagerStatic as Image;
class PropiedadController {
public static function index(Router $router) {
estaAutenticado();
$ext = true;
$propiedades = Propiedad::all();
$vendedor = vendedores::all();
//? Muestra mensaje condicional
$resultado = $_GET['resultado'] ?? null;
$router->render('propiedades/admin', [
'propiedades' => $propiedades,
'resultado' => $resultado,
'vendedores' => $vendedor,
'ext' => $ext
]);
}
public static function crear(Router $router) {
estaAutenticado();
$ext = true;
$propiedad = new Propiedad;
$vendedor = vendedores::all();
$errores = Propiedad::getErrores();
//? Ejecutar codigo despues de enviar formulario
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//! Crea una nueva instancia
$propiedad = new Propiedad($_POST['propiedad']);
//! Subida de archivos
//? Generar nombre unico
$nombreImagen = md5(uniqid(rand(), true)) . ".jpg";
//! Setear la imagen
//? Realiza un resize a la imagen con intervention
if ($_FILES['propiedad']['tmp_name']['imagen']) {
$image = Image::make($_FILES['propiedad']['tmp_name']['imagen'])->fit(800, 600);
$propiedad->setImagen($nombreImagen);
}
//! Validar para poder escribir en el servidor
$errores = $propiedad->validar();
if (empty($errores)) {
//? Crear la carpeta para subir imagenes
if (!is_dir(CARPETA_IMAGENES)) {
mkdir(CARPETA_IMAGENES);
}
//? Guarda imagen en el servidor
$image->save(CARPETA_IMAGENES . $nombreImagen);
//? Guarda en la DB
$propiedad->guardar();
}
}
$router->render('propiedades/crear', [
'propiedad' => $propiedad,
'vendedores' => $vendedor,
'errores' => $errores,
'ext' => $ext
]);
}
public static function actualizar(Router $router) {
estaAutenticado();
$id = validarORedireccionar('/admin');
$ext = true;
$propiedad = Propiedad::find($id);
$errores = Propiedad::getErrores();
$vendedor = vendedores::all();
//? Ejecutar codigo despues de enviar formulario
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//? Asignar los atributos
$args = $_POST['propiedad'];
$propiedad->sincronizar($args);
//? Validacion
$errores = $propiedad->validar();
//! Subida de archivos
//? Generar nombre unico
$nombreImagen = md5( uniqid( rand(), true ) ) . ".jpg";
//? Realiza un resize a la imagen con intervention
if($_FILES['propiedad']['tmp_name']['imagen']) {
$image = Image::make($_FILES['propiedad']['tmp_name']['imagen'])->fit(800,600);
$propiedad->setImagen($nombreImagen);
}
//? Revisar que el array de errores este vacio
if(empty($errores)) {
if ($_FILES['propiedad']['tmp_name']['imagen']) {
//! Almacenar imagen
$image->save(CARPETA_IMAGENES . $nombreImagen);
}
//! Insertar en la base de datos
$propiedad->guardar();
}
}
$router->render('propiedades/actualizar', [
'errores' => $errores,
'propiedad' => $propiedad,
'vendedores' => $vendedor,
'ext' => $ext
]);
}
public static function eliminar() {
estaAutenticado();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//? Validar id
$id = $_POST['id'];
$id = filter_var($id, FILTER_VALIDATE_INT);
if($id) {
$tipo = $_POST['tipo'];
if (validarContenido($tipo)) {
//? Obtener los datos de la propiedad
$propiedad = Propiedad::find($id);
$propiedad->eliminar();
}
}
}
}
} |
import React, { useState } from 'react';
import ExpenseItem from './ExpenseItem';
import Card from '../UI/Card';
import './Expenses.css';
import ExpensesFilter from './ExpensesFilter';
import ExpensesList from './ExpensesList';
import ExpensesChart from './ExpensesChart';
const Expenses = (props) => {
const [filteredYear, setFilteredYear] = useState('2020');
const filterChangeHandler = (selectedYear) => {
setFilteredYear(selectedYear);
};
const filterExpenses = props.items.filter((expenseData) => {
return expenseData.date.getFullYear().toString() === filteredYear;
});
return (
<li>
<Card className="expenses">
<ExpensesFilter
selected={filteredYear}
onChangeFilter={filterChangeHandler}
/>
<ExpensesChart expenses={filterExpenses} />
<ExpensesList filterExpenses={filterExpenses} />
</Card>
</li>
);
};
export default Expenses; |
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package network
import (
"fmt"
"slices"
"strings"
"time"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/tags"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
)
func dataSourceIpGroups() *pluginsdk.Resource {
return &pluginsdk.Resource{
Read: dataSourceIpGroupsRead,
Timeouts: &pluginsdk.ResourceTimeout{
Read: pluginsdk.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
},
"resource_group_name": commonschema.ResourceGroupNameForDataSource(),
"location": commonschema.LocationComputed(),
"ids": {
Type: pluginsdk.TypeList,
Computed: true,
Elem: &pluginsdk.Schema{Type: pluginsdk.TypeString},
},
"names": {
Type: pluginsdk.TypeList,
Computed: true,
Elem: &pluginsdk.Schema{Type: pluginsdk.TypeString},
},
"tags": tags.SchemaDataSource(),
},
}
}
// Find IDs and names of multiple IP Groups, filtered by name substring
func dataSourceIpGroupsRead(d *pluginsdk.ResourceData, meta interface{}) error {
// Establish a client to handle i/o operations against the API
client := meta.(*clients.Client).Network.IPGroupsClient
// Create a context for the request and defer cancellation
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
// Get resource group name from data source
resourceGroupName := d.Get("resource_group_name").(string)
// Make the request to the API to download all IP groups in the resource group
allGroups, err := client.ListByResourceGroup(ctx, resourceGroupName)
if err != nil {
return fmt.Errorf("error listing IP groups: %+v", err)
}
// Establish lists of strings to append to, set equal to empty set to start
// If no IP groups are found, an empty set will be returned
names := []string{}
ids := []string{}
// Filter IDs list by substring
for _, ipGroup := range allGroups.Values() {
if ipGroup.Name != nil && strings.Contains(*ipGroup.Name, d.Get("name").(string)) {
names = append(names, *ipGroup.Name)
ids = append(ids, *ipGroup.ID)
}
}
// Sort lists of strings alphabetically
slices.Sort(names)
slices.Sort(ids)
// Set resource ID, required for Terraform state
// Since this is a multi-resource data source, we need to create a unique ID
// Using the ID of the resource group
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
id := commonids.NewResourceGroupID(subscriptionId, resourceGroupName)
d.SetId(id.ID())
// Set names
err = d.Set("names", names)
if err != nil {
return fmt.Errorf("error setting names: %+v", err)
}
// Set IDs
err = d.Set("ids", ids)
if err != nil {
return fmt.Errorf("error setting ids: %+v", err)
}
// Return nil error
return nil
} |
@extends('admin.layout.master')
@section('content')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
New Admin
</h1>
<ol class="breadcrumb">
<li><a href="admin"><i class="fa fa-dashboard"></i> Dashboard</a></li>
<li><a href="admin/admin_module/">Manage Admins</a></li>
<li class="active">Create</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="box">
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label class="control-label col-sm-2">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Enter name" name="name" required value="{{ old('name') }}">
@if($errors->first('name')) <p class="text-danger">{{ $errors->first('name') }}</p> @endif
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Role</label>
<div class="col-sm-10">
<select class="form-control" name="role" required>
<option value="" selected disabled>--- Choose ---</option>
@foreach($data as $value)
<option value="{{ $value->id }}" {{ old('role')==$value->id ? 'selected':'' }}>{{ $value->title }}</option>
@endforeach
</select>
@if($errors->first('role')) <p class="text-danger">{{ $errors->first('role') }}</p> @endif
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Enter username" name="username" required value="{{ old('username') }}">
@if($errors->first('username')) <p class="text-danger">{{ $errors->first('username') }}</p> @endif
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" placeholder="Enter password" name="password" required value="{{ old('password') }}">
@if($errors->first('password')) <p class="text-danger">{{ $errors->first('password') }}</p> @endif
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Active</label>
<div class="col-sm-10">
<select class="form-control" name="active" required>
<option value="1" {{ old('active','1') == '1'?'selected':'' }}>Yes</option>
<option value="0" {{ old('active') == '0'?'selected':'' }}>No</option>
</select>
@if($errors->first('active')) <p class="text-danger">{{ $errors->first('active') }}</p> @endif
</div>
</div>
</div>
<div class="box-footer text-right">
<a class="btn btn-primary pull-left" href="admin/admin_module/">Back</a>
<button type="submit" class="btn btn-success">Save</button>
</div>
</form>
</div>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<script>
$(document).ready(function() {
$('[name="icon"]').select2({
templateResult: setIcon,
templateSelection: setIcon
});
});
function setIcon (option) {
if (!option.id) { return option.text; }
var $option = $('<span><i class="fa fa-'+option.text+'" style="width:30px"></i> '+option.text+'</span>');
return $option;
}
</script>
@endsection |
import React, { useState, useRef, useMemo } from 'react';
import { Switch, Route, Link, Redirect } from 'react-router-dom';
import { Layout, Menu } from '@arco-design/web-react';
import { IconMenuFold, IconMenuUnfold } from '@arco-design/web-react/icon';
import { useDispatch, useSelector } from 'react-redux';
import qs from 'query-string';
import Navbar from '../components/NavBar';
import Footer from '../components/Footer';
import LoadingBar from '../components/LoadingBar';
import { routes, defaultRoute } from '../routes';
import { isArray } from '../utils/is';
import history from '../history';
import useLocale from '../utils/useLocale';
import { ReducerState } from '../redux';
import getUrlParams from '../utils/getUrlParams';
import lazyload from '../utils/lazyload';
import styles from './style/layout.module.less';
const MenuItem = Menu.Item;
const SubMenu = Menu.SubMenu;
const Sider = Layout.Sider;
const Content = Layout.Content;
/** #### 获取左侧边栏, 名称、key、图标、路径 (处理routes,处理pages下indextsx) */
function getFlattenRoutes() {
const res = [];
function travel(_routes) {
_routes.forEach((route) => {
if (route.componentPath) {
route.component = lazyload(() => import(`../pages/${route.componentPath}`));
res.push(route);
}
if(isArray(route.children) && route.children.length){
travel(route.children)
}
});
}
travel(routes);
return res;
}
/** #### 处理 侧边栏Menu里面的内容 */
function renderRoutes(locale) {
const nodes = [];
function travel(_routes, level) {
return _routes.map((route) => {
const titleDom = (<>{route.icon} {locale[route.name] || route.name}</>); // 侧边栏名根据route去匹配
// 网站设置子菜单
if (route.component && (!isArray(route.children) || (isArray(route.children) && !route.children.length))) {
if (level > 1) {
return <MenuItem key={route.key}>{titleDom}</MenuItem>;
}
if (!route.hide) {
nodes.push(
<MenuItem key={route.key}>
{/* <Link to={`/${route.key}`}>{titleDom} 一</Link> */}
<Link to={`/${route.key}`}>{titleDom}</Link>
</MenuItem>
);
}
}
// 网站设置子菜单
if (isArray(route.children) && route.children.length) {
if (level > 1) {
// 这个level表示,children下包含children,子菜单下的子菜单
return (
<SubMenu key={route.key} title={titleDom}>
{travel(route.children, level + 1)}
</SubMenu>
);
}
nodes.push(
<SubMenu key={route.key} title={titleDom}>
{travel(route.children, level + 1)}
{/* <MenuItem key="1">test</MenuItem> */}
</SubMenu>
);
}
});
}
travel(routes, 1);
// console.log(nodes);
// 所以Menu的结构为:
// <Menu>
// <MenuItem>Welcome</MenuItem>
// <MenuItem>Articles</MenuItem>
// <SubMenu>
// <MenuItem>HomeConfig</MenuItem>
// <MenuItem>AsideConfig</MenuItem>
// </SubMenu>
// </Menu>
return nodes;
}
/** #### TODO: 界面布局 */
function PageLayout() {
const locale = useLocale(); // 一套中文,一套英文 GlobalContext:全局Text解构出locale
const urlParams = getUrlParams(); // console.log(urlParams ? '存在':'不存在')
const pathname = history.location.pathname; // /about /user
const currentComponent = qs.parseUrl(pathname).url.slice(1); // 字符串截取
const defaultSelectedKeys = [currentComponent || defaultRoute]; // Menu菜单默认Selectkeys: ['about' || 'welcome']
const [selectedKeys, setSelectedKeys] = useState<string[]>(defaultSelectedKeys); // 高亮Menu项,根据地址栏选中 || 点击选中
const { collapsed, settings } = useSelector((state: ReducerState) => state.global);
const navbarHeight = 60;
const menuWidth = collapsed ? 48 : settings.menuWidth;
const showNavbar = settings.navbar && urlParams.navbar !== false;
const showMenu = settings.menu && urlParams.menu !== false;
const showFooter = settings.footer && urlParams.footer !== false;
/** #### 处理后的路由,根据路由匹配内容 */
const flattenRoutes = useMemo(() => getFlattenRoutes() || [], []);
const loadingBarRef = useRef(null); // 进度条Ref
/** #### 点击菜单MenuItem后处理 */
function onClickMenuItem(key) {
const currentRoute = flattenRoutes.find((r) => r.key === key);
const component = currentRoute.component;
const preload = component.preload();
loadingBarRef.current.loading();
preload.then(() => {
setSelectedKeys([key]);
history.push(currentRoute.path ? currentRoute.path : `/${key}`);
loadingBarRef.current.success();
});
}
const dispatch = useDispatch();
function toggleCollapse() { dispatch({ type: 'TOGGLE_COLLAPSED', payload: !collapsed }); }
const paddingLeft = showMenu ? { paddingLeft: menuWidth } : {};
const paddingTop = showNavbar ? { paddingTop: navbarHeight } : {};
const paddingStyle = { ...paddingLeft, ...paddingTop };
return (
<Layout className={styles.layout}>
<LoadingBar ref={loadingBarRef} />
{showNavbar && (<div className={styles.layoutNavbar}> <Navbar /> </div>)}
<Layout>
{showMenu && (
// Sider:https://arco.design/react/components/layout
// 展开关闭侧边栏
<Sider
className={styles.layoutSider}
width={menuWidth}
collapsed={collapsed}
onCollapse={toggleCollapse}
trigger={null}
collapsible
breakpoint="xl"
style={paddingTop}
>
<div className={styles.menuWrapper}>
{/* TODO: 展开关闭菜单(有属性children) */}
<Menu collapse={collapsed} onClickMenuItem={onClickMenuItem} selectedKeys={selectedKeys} autoOpen={false}>
{renderRoutes(locale)}
</Menu>
</div>
<div className={styles.collapseBtn} onClick={toggleCollapse}>{collapsed ? <IconMenuUnfold /> : <IconMenuFold />}</div>
</Sider>
)}
<Layout className={styles.layoutContent} style={paddingStyle}>
<Content>
<Switch>
{flattenRoutes.map((route, index) => <Route exact key={index} path={`/${route.key}`} component={route.component} />)}
<Redirect push to={`/${defaultRoute}`} />
</Switch>
</Content>
{showFooter && <Footer />}
</Layout>
</Layout>
</Layout>
);
}
export default PageLayout; |
# projects/models.py
from django.db import models
from users.models import CustomUser
class Publication(models.Model):
"""
Publication includes Observation(s) and belongs to Project(s).
"""
title = models.TextField()
year = models.IntegerField()
doi = models.CharField(max_length=100)
biosamples = models.ManyToManyField('BioSample',
related_name='publications')
def __str__(self):
return f"Publication {self.id}, {self.doi}"
class Project(models.Model):
"""
Project includes Experiment(s).
"""
name = models.CharField(max_length=100)
registration_date = models.DateField()
description = models.TextField()
owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE,
related_name='projects')
publications = models.ManyToManyField(Publication,
related_name='projects')
biosamples = models.ManyToManyField('BioSample', related_name='projects')
def __str__(self):
return f"Project {self.name}"
class Experiment(models.Model):
"""
Experiment includes Observation(s).
"""
project = models.ForeignKey(Project, on_delete=models.CASCADE,
related_name='experiments')
name = models.CharField(max_length=100)
date = models.DateField()
def __str__(self):
return f"Experiment {self.name} from {self.project.name}"
class Colony(models.Model):
"""
Colony includes BioSample(s).
"""
name = models.CharField(max_length=100)
species = models.CharField(max_length=100)
country = models.CharField(max_length=3)
latitude = models.FloatField()
longitude = models.FloatField()
def __str__(self):
return f"Colony {self.name} of {self.species} from {self.country} ({self.latitude}, {self.longitude})"
class BioSample(models.Model):
"""
BioSample includes Observation(s).
"""
name = models.CharField(max_length=100)
collection_date = models.DateField()
colony = models.ForeignKey(Colony, on_delete=models.CASCADE,
related_name='biosamples')
def __str__(self):
return f"BioSample {self.id} {self.name} of Colony {self.colony.id}"
class Observation(models.Model):
"""
Observation belongs to Experiment.
"""
experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE,
related_name='observations')
biosample = models.ForeignKey(BioSample, on_delete=models.CASCADE,
related_name='observations')
condition = models.CharField(max_length=100)
temperature = models.IntegerField()
timepoint = models.IntegerField()
pam_value = models.FloatField(null=True, blank=True)
def __str__(self):
return f"Observation {self.id} of Biosample {self.biosample.id} {self.biosample.name}"
def save(self, *args, **kwargs):
# Ensure pam_value is not None before rounding
if self.pam_value is not None:
self.pam_value = round(self.pam_value, 3)
super().save(*args, **kwargs)
class ThermalTolerance(models.Model):
"""
Represents Thermal Tolerance for a Colony under specific Condition and Timepoint.
"""
colony = models.ForeignKey(Colony, on_delete=models.CASCADE,
related_name='thermal_tolerances')
observations = models.ManyToManyField(Observation,
related_name='thermal_tolerances')
abs_thermal_tolerance = models.FloatField(null=True, blank=True)
rel_thermal_tolerance = models.FloatField(null=True, blank=True)
# Internal attribute
_sst_clim_mmm = models.FloatField(null=True, blank=True)
@property
def condition(self):
if self.observations.exists():
observations_conditions = [observation.condition for observation in
self.observations.all()]
if all(item == observations_conditions[0] for item in
observations_conditions):
return observations_conditions[0]
else:
return None
@property
def timepoint(self):
if self.observations.exists():
observations_timepoints = [observation.timepoint for observation in
self.observations.all()]
if all(item == observations_timepoints[0] for item in
observations_timepoints):
return observations_timepoints[0]
else:
return None
def save(self, *args, **kwargs):
# Ensure abs_thermal_tolerance is not None before rounding
if self.abs_thermal_tolerance is not None:
self.abs_thermal_tolerance = round(self.abs_thermal_tolerance, 2)
if self._sst_clim_mmm is not None:
self._sst_clim_mmm = round(self._sst_clim_mmm, 2)
if self.abs_thermal_tolerance is not None and self._sst_clim_mmm is not None:
self.rel_thermal_tolerance = round(
self.abs_thermal_tolerance - self._sst_clim_mmm,
2)
super().save(*args, **kwargs)
def __str__(self):
return f"Thermal Tolerance for Colony {self.colony.name} under {self.condition}, {self.timepoint}"
class UserCart(models.Model):
owner = models.OneToOneField(CustomUser, on_delete=models.CASCADE,
related_name='cart')
items = models.ManyToManyField('Colony', related_name='carts')
def __str__(self):
return f"UserCart of {self.owner.username}, {self.colonies.count()} colonies" |
import React, { FC } from "react";
import { StyleSheet, Text, View } from "react-native";
import type { TileItem } from "../lib/tile-item";
import type { MeldItem } from "../lib/meld-item";
import { Tile } from "./Tile";
export const Melds: FC<{
melds: MeldItem[];
handleClick: (i: number) => void;
}> = ({ melds, handleClick }) => {
if (!melds || melds.length <= 0) {
return null;
}
const arr: TileItem[][] = [];
for (const item of melds) {
if (item.type === "pon") {
const pon: TileItem[] = [];
const t = item.tile;
pon.push(t);
pon.push(t);
pon.push(t);
arr.push(pon);
}
if (item.type === "chii") {
const chii: TileItem[] = [];
const t = item.tile;
chii.push(t);
chii.push({ type: t.type, n: t.n + 1 });
chii.push({ type: t.type, n: t.n + 2 });
arr.push(chii);
}
if (item.type === "kan") {
const kan: TileItem[] = [];
const t = item.tile;
kan.push(t);
kan.push(t);
kan.push(t);
kan.push(t);
arr.push(kan);
}
}
return (
<View style={styles.container}>
{arr.map((meld, i) => {
return (
<View style={styles.block} key={i}>
{meld.map((t, j) => (
<Tile
t={t}
key={`${i}_${j}`}
handleClick={() => {
handleClick(i);
}}
/>
))}
</View>
);
})}
</View>
);
};
const styles = StyleSheet.create({
container: {
flexDirection: "row",
flexWrap: "wrap",
},
block: {
flexDirection: "row",
flexWrap: "wrap",
marginRight: 5,
},
}); |
package logic
import (
"context"
"fmt"
"testing"
"github.com/lazybark/go-testing-authservice/pkg/ds"
"github.com/lazybark/go-testing-authservice/pkg/helpers"
"github.com/lazybark/go-testing-authservice/pkg/sec"
"github.com/stretchr/testify/require"
)
func TestUserLogin(t *testing.T) {
udata := ds.GetRandomUserData()
jwtSecret := "jwtSecret"
ip := "192.168.0.1"
password := udata.PasswordHash
pwdHash, err := hashPasswordString(udata.PasswordHash, 10)
require.NoError(t, err)
udata.PasswordHash = pwdHash
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dbContainer, dsn, err := helpers.NewTestContainerDatabase(ctx)
require.NoError(t, err)
t.Cleanup(func() { dbContainer.Terminate(ctx) })
stor := &ds.DataStorageUsers{}
err = stor.Connect(ctx, dsn)
require.NoError(t, err)
t.Cleanup(func() { stor.Close() })
err = stor.Migrate(ctx)
require.NoError(t, err)
uid, err := stor.CreateUser(ctx, udata)
require.NoError(t, err)
require.NotEmpty(t, uid)
wrongResults := map[string]struct {
login string
password string
expect error
}{
"empty login": {login: "", password: password, expect: ErrEmptyFields},
"empty password": {login: udata.Login, password: "", expect: ErrEmptyFields},
"wrong login": {login: "wrong", password: password, expect: ErrUnknownUser},
"wrong password": {login: udata.Login, password: "wrong", expect: ErrUnknownUser},
}
// Must NOT run in parallel
for name, tCase := range wrongResults {
t.Run(name, func(t *testing.T) {
tCase := tCase
name := name
loginData := UserLoginData{
Login: tCase.login,
Password: tCase.password,
}
token, err := UserLogin(loginData, stor, ip, 10, jwtSecret)
require.Error(t, err, name)
require.ErrorIs(t, err, tCase.expect)
require.Nil(t, token, name)
})
}
correctLoginData := UserLoginData{
Login: udata.Login,
Password: password,
}
// Now correct password
token, err := UserLogin(correctLoginData, stor, ip, 10, jwtSecret)
require.NoError(t, err, "correct data")
require.NotNil(t, token, "correct data")
valid, err := checkToken(token.AuthToken, jwtSecret)
require.NoError(t, err, "correct data")
require.True(t, valid, "correct data")
valid, err = checkToken(token.RefreshToken, jwtSecret)
require.NoError(t, err, "correct data")
require.True(t, valid, "correct data")
// Now let's block the user
incorrectLoginData := UserLoginData{
Login: udata.Login,
Password: "wrong",
}
for i := 0; i < 10; i++ {
_, _ = UserLogin(incorrectLoginData, stor, ip, 10, jwtSecret)
}
token, err = UserLogin(correctLoginData, stor, ip, 10, jwtSecret)
require.Error(t, err, "correct data")
require.ErrorIs(t, err, ErrUserBlocked)
require.Nil(t, token, "correct data")
}
// internal functions => error
func TestUserLogin_errors(t *testing.T) {
udata := ds.GetRandomUserData()
jwtSecret := "jwtSecret"
ip := "192.168.0.1"
password := udata.PasswordHash
pwdHash, err := hashPasswordString(udata.PasswordHash, 10)
require.NoError(t, err)
udata.PasswordHash = pwdHash
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dbContainer, dsn, err := helpers.NewTestContainerDatabase(ctx)
require.NoError(t, err)
t.Cleanup(func() { dbContainer.Terminate(ctx) })
stor := &ds.DataStorageUsers{}
err = stor.Connect(ctx, dsn)
require.NoError(t, err)
t.Cleanup(func() { stor.Close() })
err = stor.Migrate(ctx)
require.NoError(t, err)
uid, err := stor.CreateUser(ctx, udata)
require.NoError(t, err)
require.NotEmpty(t, uid)
correctLoginData := UserLoginData{
Login: udata.Login,
Password: password,
}
// formJWT => error
origFJ := formJWT
t.Cleanup(func() {
formJWT = origFJ
})
formJWT = func(uid string, sid string, uname string, email string, jwtSecret string) (*sec.Token, error) {
return nil, fmt.Errorf("some_error")
}
token, err := UserLogin(correctLoginData, stor, ip, 10, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
// addUserSession => error
origAUS := addUserSession
t.Cleanup(func() {
addUserSession = origAUS
})
addUserSession = func(_ UserLogicWorker, ctx context.Context, uid string) (sid string, err error) {
return "", fmt.Errorf("some_error")
}
token, err = UserLogin(correctLoginData, stor, ip, 10, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
// mustChangePassword => error
origMCP := mustChangePassword
t.Cleanup(func() {
mustChangePassword = origMCP
})
mustChangePassword = func(_ UserLogicWorker, ctx context.Context, uid string) error {
return fmt.Errorf("some_error")
}
token, err = UserLogin(correctLoginData, stor, ip, 10, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
// blockUserLogin => error
origBUL := blockUserLogin
t.Cleanup(func() {
blockUserLogin = origBUL
})
blockUserLogin = func(_ UserLogicWorker, ctx context.Context, uid string) error {
return fmt.Errorf("some_error")
}
token, err = UserLogin(correctLoginData, stor, ip, 10, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
// addFailedLoginAttempt => error
origALA := addFailedLoginAttempt
t.Cleanup(func() {
addFailedLoginAttempt = origALA
})
addFailedLoginAttempt = func(_ UserLogicWorker, ctx context.Context, uid string, ip string) (total int, err error) {
return 0, fmt.Errorf("some_error")
}
token, err = UserLogin(correctLoginData, stor, ip, 10, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
// comparePasswordStrings => error
origCPS := comparePasswordStrings
t.Cleanup(func() {
comparePasswordStrings = origCPS
})
comparePasswordStrings = func(hashedPwd string, plainPwd string) (bool, error) {
return false, fmt.Errorf("some_error")
}
token, err = UserLogin(correctLoginData, stor, ip, 10, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
}
// internal functions => error with !pwd.Valid
func TestUserLogin_errors_add_failed_attempt(t *testing.T) {
udata := ds.GetRandomUserData()
jwtSecret := "jwtSecret"
ip := "192.168.0.1"
password := udata.PasswordHash
pwdHash, err := hashPasswordString(udata.PasswordHash, 10)
require.NoError(t, err)
udata.PasswordHash = pwdHash
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dbContainer, dsn, err := helpers.NewTestContainerDatabase(ctx)
require.NoError(t, err)
t.Cleanup(func() { dbContainer.Terminate(ctx) })
stor := &ds.DataStorageUsers{}
err = stor.Connect(ctx, dsn)
require.NoError(t, err)
t.Cleanup(func() { stor.Close() })
err = stor.Migrate(ctx)
require.NoError(t, err)
uid, err := stor.CreateUser(ctx, udata)
require.NoError(t, err)
require.NotEmpty(t, uid)
correctLoginData := UserLoginData{
Login: udata.Login,
Password: password,
}
// comparePasswordStrings => false
origCPS := comparePasswordStrings
t.Cleanup(func() {
comparePasswordStrings = origCPS
})
comparePasswordStrings = func(hashedPwd string, plainPwd string) (bool, error) {
return false, nil
}
// addFailedLoginAttempt => error
origALA := addFailedLoginAttempt
t.Cleanup(func() {
addFailedLoginAttempt = origALA
})
addFailedLoginAttempt = func(_ UserLogicWorker, ctx context.Context, uid string, ip string) (total int, err error) {
return 0, fmt.Errorf("some_error")
}
token, err := UserLogin(correctLoginData, stor, ip, 0, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
}
// internal functions => error with !pwd.Valid
func TestUserLogin_errors_block_user_login(t *testing.T) {
udata := ds.GetRandomUserData()
jwtSecret := "jwtSecret"
ip := "192.168.0.1"
password := udata.PasswordHash
pwdHash, err := hashPasswordString(udata.PasswordHash, 10)
require.NoError(t, err)
udata.PasswordHash = pwdHash
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dbContainer, dsn, err := helpers.NewTestContainerDatabase(ctx)
require.NoError(t, err)
t.Cleanup(func() { dbContainer.Terminate(ctx) })
stor := &ds.DataStorageUsers{}
err = stor.Connect(ctx, dsn)
require.NoError(t, err)
t.Cleanup(func() { stor.Close() })
err = stor.Migrate(ctx)
require.NoError(t, err)
uid, err := stor.CreateUser(ctx, udata)
require.NoError(t, err)
require.NotEmpty(t, uid)
correctLoginData := UserLoginData{
Login: udata.Login,
Password: password,
}
// comparePasswordStrings => false
origCPS := comparePasswordStrings
t.Cleanup(func() {
comparePasswordStrings = origCPS
})
comparePasswordStrings = func(hashedPwd string, plainPwd string) (bool, error) {
return false, nil
}
// addFailedLoginAttempt => error
origALA := addFailedLoginAttempt
t.Cleanup(func() {
addFailedLoginAttempt = origALA
})
addFailedLoginAttempt = func(_ UserLogicWorker, ctx context.Context, uid string, ip string) (total int, err error) {
return 1, nil
}
// blockUserLogin => error
origBUL := blockUserLogin
t.Cleanup(func() {
blockUserLogin = origBUL
})
blockUserLogin = func(_ UserLogicWorker, ctx context.Context, uid string) error {
return fmt.Errorf("some_error")
}
token, err := UserLogin(correctLoginData, stor, ip, 1, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
}
// internal functions => error with !pwd.Valid
func TestUserLogin_errors_must_change_pwd(t *testing.T) {
udata := ds.GetRandomUserData()
jwtSecret := "jwtSecret"
ip := "192.168.0.1"
password := udata.PasswordHash
pwdHash, err := hashPasswordString(udata.PasswordHash, 10)
require.NoError(t, err)
udata.PasswordHash = pwdHash
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dbContainer, dsn, err := helpers.NewTestContainerDatabase(ctx)
require.NoError(t, err)
t.Cleanup(func() { dbContainer.Terminate(ctx) })
stor := &ds.DataStorageUsers{}
err = stor.Connect(ctx, dsn)
require.NoError(t, err)
t.Cleanup(func() { stor.Close() })
err = stor.Migrate(ctx)
require.NoError(t, err)
uid, err := stor.CreateUser(ctx, udata)
require.NoError(t, err)
require.NotEmpty(t, uid)
correctLoginData := UserLoginData{
Login: udata.Login,
Password: password,
}
// comparePasswordStrings => false
origCPS := comparePasswordStrings
t.Cleanup(func() {
comparePasswordStrings = origCPS
})
comparePasswordStrings = func(hashedPwd string, plainPwd string) (bool, error) {
return false, nil
}
// mustChangePassword => error
origMCP := mustChangePassword
t.Cleanup(func() {
mustChangePassword = origMCP
})
mustChangePassword = func(_ UserLogicWorker, ctx context.Context, uid string) error {
return fmt.Errorf("some_error")
}
token, err := UserLogin(correctLoginData, stor, ip, 0, jwtSecret)
require.Error(t, err)
require.Nil(t, token)
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Filtros</title>
</head>
<body>
<div id="app">
<!-- o que vem antes do pipe é passado como argumento no filtro -->
{{ title | upper }}<br>
<span>Reverso</span>
<p>{{ title | reverse }}</p>
</div>
<script src="https://unpkg.com/vue/dist/vue.js" ></script>
<script>
var app = new Vue({
el: '#app',
data: {
title: 'TreinaWEB'
},
filters: {
upper: function(text){
return text.toUpperCase();
},
reverse: function(text){
return text.split('').reverse().join('')
}
}
})
</script>
</body>
</html> |
#include "lists.h"
#include <string.h>
#include <stdlib.h>
/**
* add_nodeint - adds a new node at the beginning of a listint_t list.
* @head: a pointer to the head of the listint_t list
* @n: the integer to be added to the listint_t list
*
* Return: address of the new element, or NULL if fails
*/
listint_t *add_nodeint(listint_t **head, const int n)
{
listint_t *new_node;
new_node = malloc(sizeof(listint_t));
if (new_node == NULL)
return (NULL);
new_node->n = n;
new_node->next = *head;
*head = new_node;
return (new_node);
} |
import { useState, useEffect } from "react";
import {apiService} from "../../api/apiservice";
interface Feed {
_id: string;
name: string;
url: string;
color: string;
}
export const useFeeds = () => {
const [feeds, setFeeds] = useState<Feed[]>([]);
const fetchFeeds = async () => {
try {
const response = await apiService.get("/rss/feeds"); // Adjust the API endpoint as per your backend
setFeeds(response);
} catch (error) {
console.error("Error fetching RSS feeds:", error);
}
};
useEffect(() => {
fetchFeeds();
}, []);
const addFeed = async (name: string, url: string, color: string) => {
try {
await apiService.post("/rss/add-feed", { name, url, color }); // Adjust the API endpoint as per your backend
fetchFeeds(); // Refresh the feeds after adding a new one
} catch (error) {
throw new Error("Failed to add RSS feed");
}
};
const deleteFeed = async (id: string) => {
try {
await apiService.delete(`/rss/${id}`); // Adjust the API endpoint as per your backend
fetchFeeds(); // Refresh the feeds after deleting one
} catch (error) {
throw new Error("Failed to delete RSS feed");
}
};
return { feeds, addFeed, deleteFeed };
}; |
use bcrypt::{hash, verify};
use serde::{Deserialize, Serialize};
use diesel::prelude::*;
use crate::db::establish_connection;
use crate::schema::users;
#[derive(Serialize, Deserialize, Debug)]
#[derive(Queryable, Selectable)]
#[diesel(table_name = users)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct UserModel{
pub id: i32,
pub name: String,
pub email: String,
password: String,
pub company_name: String
}
impl UserModel{
pub fn hash_password(&mut self){
self.password = hash(&self.password, 20).unwrap();
}
pub fn compare_password(&self, password: &String) -> bool{
verify(password, &self.password.as_str()).unwrap()
}
pub fn get_password(&self) -> String{
self.password.clone()
}
pub fn set_password(&mut self, password: String){
self.password = password;
}
}
#[derive(Insertable)]
#[diesel(table_name = users)]
pub struct NewUser {
pub name: String,
pub email: String,
password: String,
pub company_name: String,
}
impl NewUser{
pub fn create_user(&self) -> bool{
use crate::schema::users::dsl::*;
let mut conn: SqliteConnection = establish_connection();
diesel::insert_into(users).values(self).execute(&mut conn).expect("error inserting User");
true
}
} |
import Bookshelf from "bookshelf";
import { EkoTokenReport } from "../models/ekotoken-report.model";
import { mailClient } from "./email.service";
import { sdk as FelaSdk } from "./fela.service";
import writeXlsxFile from 'write-excel-file/node';
import { dbConnection } from "./db.service";
import { Stream } from "stream";
export const fetchReportRequests = async () => {
return await EkoTokenReport.fetchAll().then((q) => q.where(
"status", "=", 0).fetch()).then(((r) => r.models || []));
}
export const fetchReport = async (request: Bookshelf.Model<any>) => {
const params: any = {};
if (request.attributes.query_params) {
const [startDate, endDate] = request.attributes.query_params.split("|");
params.startDate = startDate;
params.endDate = endDate
}
try {
console.log("FetchReport params", params);
const result = await FelaSdk.get("/custom/mtnEkotokenReport", {
params
});
if (!result.data || !result.data.data)
return [];
return result.data.data;
} catch (error) {
console.log("Error while fetching report", error);
return [];
}
}
export const excelSchema = [
// Column #1
{
column: 'Description',
type: String,
value: (report: any) => report.description
},
// Column #2
{
column: 'Channel Name',
type: String,
value: (report: any) => report.channelName
},
// Column #3
{
column: 'Service',
type: String,
value: (report: any) => report.service
},
// Column #4
{
column: 'Recipient',
type: String,
value: (report: any) => report.recipient
},
// Column #5
{
column: 'Network',
type: String,
value: (report: any) => report.network
},
// Column #6
{
column: 'Amount',
type: Number,
format: '#,##0.00',
value: (report: any) => Number(report.amount)
},
// Column #7
{
column: 'Merchant Ref',
type: String,
value: (report: any) => report.merchantRef
},
// Column #8
{
column: 'Confirm Code',
type: String,
value: (report: any) => report.confirmCode
},
// Column #9
{
column: 'Created At',
type: Date,
format: 'mm/dd/yyyy hh:mm:ss',
value: (report: any) => new Date(report.createdAt)
}
]
export const reportToExcel = async (reportId: any, report: any[] = []) => {
console.log("processing report #" + reportId, report.length);
if (!report || (Array.isArray(report) && report.length == 0)) return null;
return await writeXlsxFile(report, { schema: excelSchema }) as Stream;
};
export const sendReport = async (request: Bookshelf.Model<any>, report: any[], excel: any) => {
if (excel) return await sendReportWithExcel(request, report, excel);
return await sendEmptyReport(request, report);
}
export const generateEmptyReportBody = (request: Bookshelf.Model<any>) =>
`<div style ="background-color:white; border:1px solid black; border-radius:5px; text-align:center">
<h2>Hi ${request.attributes.created_by}</h2>
<p>Your request for selected date range ${request.attributes.query_params.split("|")} returns empty report</p>
<p>Request id ${request.attributes.Id}</p>
</div>
`;
export const sendEmptyReport = async (request: Bookshelf.Model<any>, report: any[]) => {
return new Promise((resolve, reject) => mailClient.sendMail({
to: process.env.RECIPIENT_MAIL || request.attributes.recipient_email,
subject: "Ekotoken Report #" + request.attributes.Id,
html: generateEmptyReportBody(request),
from: process.env.MAIL_FROM,
replyTo: process.env.MAIL_REPLY_TO,
}, (error, info) => {
if (error) return reject(error);
resolve(info);
}));
}
export const generateReportWithExcelBody = (request: Bookshelf.Model<any>) =>
`<div style ="background-color:white; border:1px solid black; border-radius:5px; text-align:center">
<h2>Hi ${request.attributes.created_by}</h2>
<p>Your report is ready</p>
<p>Request id ${request.attributes.Id}</p>
</div>`;
export const sendReportWithExcel = async (request: Bookshelf.Model<any>, report: any[], excel: any) => {
const prefix = process.env.EKOTOKEN_REPORT_FILE_PREFIX || "Ekotoken-mtn-vas-sales-report-";
return new Promise((resolve, reject) => mailClient.sendMail({
to: process.env.RECIPIENT_MAIL || request.attributes.recipient_email,
subject: "Ekotoken Report #" + request.attributes.Id,
html: generateReportWithExcelBody(request),
attachments: [
{
filename: prefix + request.attributes.query_params.replace("|", "-") + "-" + request.attributes.Id + ".xlsx",
content: excel,
}
],
from: process.env.MAIL_FROM,
replyTo: process.env.MAIL_REPLY_TO,
}, (error, info) => {
if (error) return reject(error);
resolve(info);
}));
}
export const queueReportTask = (request: Bookshelf.Model<any>) => new Promise<void>((resolve) => queueMicrotask(async () => {
try {
const report = await fetchReport(request);
const excel = await reportToExcel(request.attributes.Id, report);
const info = await sendReport(request, report, excel);
console.log("Report sent info:", info);
request.set("status", 1);
await updateReportRequestStatus(request.attributes.Id, 1);
} catch (error) {
console.log("Error while processing request", error);
await updateReportRequestStatus(request.attributes.Id, 0);
}
resolve()
}))
export const updateReportRequestStatus = (id: number, status: number) => dbConnection(process.env.EKOTOKEN_REPORT_TABLE)
.where("id", "=", id)
.update({ status, });
export const generateReport = async () => {
if (process.env.TEST_CONTROL_ID) {
await updateReportRequestStatus(Number(process.env.TEST_CONTROL_ID), 0);
}
const requests = await fetchReportRequests();
const tasks: Promise<void>[] = [];
if (requests.length == 0) {
console.log("Empty Generate Report Request Tasks");
}
for (const request of requests) {
console.log("processing request", request.attributes);
await updateReportRequestStatus(request.attributes.Id, 2);
tasks.push(queueReportTask(request));
}
await Promise.all(tasks);
}
export default {
fetchReport,
generateReport
} |
import {
BadRequestException,
Body,
Controller,
Delete,
ForbiddenException,
Get,
NotFoundException,
NotImplementedException,
Param,
Patch,
Post,
Put,
Query,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import { ChatService } from './chat.service';
import { AuthenticatedGuard } from '../auth/guards/authenticated.guard';
import { Request, Response } from 'express';
import { AddToChatDto } from './dto/controller/add-to-chat.input';
import { UsersService } from '../users/users.service';
import { ApiTags } from '@nestjs/swagger';
import { PrismaError } from 'prisma-error-enum';
import { CreateGroupDto } from './dto/controller/create-group.input';
import {
ChatNotFoundError,
EmptyNewMembersError,
MemberNotInChat,
WrongChatTypeError,
} from './chat.service.error';
import { RemoveFromChatDto } from './dto/controller/remove-from-chat.input';
import { ChatMemberGuard } from './guards/chat-member.guard';
import { ChatAdminGuard } from './guards/chat-admin.guard';
import { GetMessagesOptionsDto } from './dto/controller/get-messages-options.input';
@ApiTags('Chat')
@Controller('chat')
export class ChatController {
constructor(
private readonly chatService: ChatService,
private readonly usersService: UsersService,
) {}
@Get('private/:userId')
@UseGuards(AuthenticatedGuard)
async getPrivate(@Param('userId') userId: string, @Req() req: Request) {
if (req.user.id == userId) throw new BadRequestException();
try {
return await this.chatService.getPrivate(req.user.id, userId);
} catch (error) {
if (error.code == PrismaError.RecordsNotFound)
throw new NotFoundException();
throw error;
}
}
@Patch('private/:id/members/add')
@UseGuards(AuthenticatedGuard, ChatMemberGuard)
async addToPrivate(
@Req() req: Request,
@Param('id') id: string,
@Body() data: AddToChatDto,
) {
if (data.membersToAdd.includes(req.user.id))
throw new BadRequestException();
try {
return await this.chatService.addToPrivate(
id,
req.user.id,
data.membersToAdd,
);
} catch (error) {
if (error instanceof ChatNotFoundError)
throw new NotFoundException(error);
if (error instanceof WrongChatTypeError)
throw new BadRequestException(error);
if (error.code == PrismaError.RecordsNotFound)
throw new NotFoundException(error);
throw error;
}
}
@Get('')
@UseGuards(AuthenticatedGuard)
getMyChats(@Req() req: Request) {
return this.chatService.getChats(req.user.id);
}
@Get(':id')
@UseGuards(AuthenticatedGuard)
async getChat(@Param('id') id: string, @Req() req: Request) {
const chat = await this.chatService.getChat(id);
if (!chat) throw new NotFoundException();
if (!chat.members.map((m) => m.id).includes(req.user.id))
throw new ForbiddenException();
return chat;
}
@Post('group')
@UseGuards(AuthenticatedGuard)
async createGroup(@Req() req: Request, @Body() data: CreateGroupDto) {
return this.chatService.createGroup(data.newMembers.concat(req.user.id), [
req.user.id,
]);
}
@Patch('group/:id/members/add')
@UseGuards(AuthenticatedGuard, ChatAdminGuard)
async addToGroup(
@Param('id') id: string,
@Req() req: Request,
@Body() data: AddToChatDto,
) {
if (data.membersToAdd.length == 0) throw new BadRequestException();
try {
return await this.chatService.addToGroup(
id,
req.user.id,
data.membersToAdd,
);
} catch (error) {
if (error instanceof ChatNotFoundError)
throw new NotFoundException(error);
if (error instanceof WrongChatTypeError)
throw new BadRequestException(error);
if (error instanceof EmptyNewMembersError)
throw new BadRequestException(error);
if (error.code == PrismaError.RecordsNotFound)
throw new NotFoundException(error);
throw error;
}
}
@Patch('group/:id/members/remove')
@UseGuards(AuthenticatedGuard, ChatAdminGuard)
async removeFromGroup(
@Param('id') id: string,
@Req() req: Request,
@Body() data: RemoveFromChatDto,
) {
if (data.membersToRemove.length == 0) throw new BadRequestException();
try {
return await this.chatService.removeFromGroup(
id,
req.user.id,
data.membersToRemove,
);
} catch (error) {
if (error instanceof ChatNotFoundError)
throw new NotFoundException(error);
if (error instanceof WrongChatTypeError)
throw new BadRequestException(error);
if (error instanceof MemberNotInChat)
throw new BadRequestException(error);
if (error.code == PrismaError.RecordsNotFound)
throw new NotFoundException(error);
throw error;
}
}
@Delete('group/:id')
@UseGuards(AuthenticatedGuard, ChatAdminGuard)
async deleteGroup(@Param('id') id: string) {
try {
return await this.chatService.deleteGroup(id);
} catch (error) {
if (error instanceof ChatNotFoundError)
throw new NotFoundException(error);
if (error instanceof WrongChatTypeError)
throw new BadRequestException(error);
throw error;
}
}
@Get(':id/messages')
async getMessages(
@Param('id') chatId: string,
@Query() query: GetMessagesOptionsDto,
) {
return await this.chatService.getMessages(
chatId,
query.number,
query.cursor,
);
}
@Get(':id/attachments')
@UseGuards(AuthenticatedGuard, ChatMemberGuard)
async getAttachments(
@Param('id') id: string,
@Query('marker') marker: string = undefined,
) {
return this.chatService.attachments(id).get(marker);
}
@Put(':id/attachments/:filename')
@UseGuards(AuthenticatedGuard, ChatMemberGuard)
putAttachment(
@Param('id') id: string,
@Param('filename') filename: string,
@Req() req: Request,
) {
return this.chatService
.attachments(id)
.getCommandLink()
.put(req.user.id, filename);
}
@Get(':id/attachments/:filekey')
@UseGuards(AuthenticatedGuard, ChatMemberGuard)
async getAttachment(
@Param('id') id: string,
@Param('filekey') filekey: string,
@Res({ passthrough: true }) res: Response,
) {
// TODO: Check if throw error on object not found
res.redirect(
await this.chatService.attachments(id).getCommandLink().get(filekey),
);
}
@Delete(':id/attachments/:userId/:filename')
@UseGuards(AuthenticatedGuard, ChatMemberGuard)
async deleteAttachment() {
throw new NotImplementedException();
}
} |
/*
* Copyright 2023 HM Revenue & Customs
*
* 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 v3.models.request.submitBsas.foreignProperty
import play.api.libs.json.{JsObject, Json}
import shared.UnitSpec
class ForeignPropertyIncomeSpec extends UnitSpec {
val model: ForeignPropertyIncome =
ForeignPropertyIncome(totalRentsReceived = Some(1.12), premiumsOfLeaseGrant = Some(2.12), otherPropertyIncome = Some(3.12))
val emptyModel: ForeignPropertyIncome = ForeignPropertyIncome(None, None, None)
"reads" when {
"passed mtd json" should {
"return the corresponding model" in {
Json
.parse(
"""
|{
| "totalRentsReceived": 1.12,
| "premiumsOfLeaseGrant": 2.12,
| "otherPropertyIncome": 3.12
|}
|""".stripMargin)
.as[ForeignPropertyIncome] shouldBe model
}
}
"passed an empty JSON" should {
"return an empty model" in {
JsObject.empty.as[ForeignPropertyIncome] shouldBe emptyModel
}
}
}
"writes" when {
"passed a model" should {
"return the downstream JSON" in {
Json.toJson(model) shouldBe
Json.parse(
"""
|{
| "rent": 1.12,
| "premiumsOfLeaseGrant": 2.12,
| "otherPropertyIncome": 3.12
|}
|""".stripMargin)
}
}
"passed an empty model" should {
"return an empty JSON" in {
Json.toJson(emptyModel) shouldBe JsObject.empty
}
}
}
} |
#ifndef QUICKWAVE_PLL
#define QUICKWAVE_PLL
#include <stdbool.h>
#include <complex.h>
#include "filter.h"
#include "oscillator.h"
#include "pid.h"
/**
* @brief
* Phase-locked loop.
* A numerically controlled oscillator is iteratively adjusted until its phase and frequency are aligned with an input signal.
* Can be used as a sort of continuous sinusoid fit.
*/
typedef struct {
Pid loop_filter;
Oscillator nco;
} PhaseLockedLoop;
/**
* @brief
* Constructs a phase-locked loop.
* @param nco_initial Initial numerically controlled oscillator (NCO) state
* @param loop_filter Loop filter function
* @param filter_context Context data to pass to loop filter when it is called. Can store filter state objects, etc.
* @return Phase-locked loop
*/
PhaseLockedLoop pll_make(
Oscillator vco_initial,
Pid loop_filter
);
/**
* @brief
* Evaluates a phase-locked loop (PLL)
* @param input Next input signal value
* @param pll PLL to evaluate
* @return Numerically-controlled oscillator (NCO) state
*/
Oscillator pll_evaluate(double input, PhaseLockedLoop *pll);
/**
* @brief
* Resets phase-locked loop (PLL) to an initial state
* @param nco_initial State to reset NCO to
* @param pll PLL to reset
*/
void pll_reset(Oscillator vco_initial, PhaseLockedLoop *pll);
/**
* @brief
* Creates a type 2 PLL loop filter
* @param noise_bandwidth Normalized noise bandwidth
* @param damping_coefficient Damping coefficient
* @return loop filter
*/
Pid pll_loop_filter_make(double noise_bandwidth, double damping_coefficient);
#endif |
import type { AlertLevel, AlertGroupDefinition } from '@nsf-open/ember-ui-foundation/constants';
import Component from '@ember/component';
import { layout, classNames, className, attribute } from '@ember-decorators/component';
import { computed } from '@ember/object';
import { isArray } from '@ember/array';
import { AlertGroups, AlertLevelKeys } from '@nsf-open/ember-ui-foundation/constants';
import { getCorrectedAlertLevel } from '@nsf-open/ember-ui-foundation/lib/MessageManager';
import { listenTo } from '@nsf-open/ember-ui-foundation/utils';
import template from './template';
/**
* A block notification banner, also commonly referred to as a "page-level alert". There are four
* variants of banner:
*
* * success
* * warning
* * danger
* * secondary (informational)
*
* Single alert messages, and arrays of strings are both supported by the component's inline form.
*
* ```handlebars
*
* {{ui-alert "success" "Hurray, it worked! An array of strings would have worked here too!"}}
* ```
*
* Block content is also supported. To keep consistency across the platform, you will need to place
* the alert's "title" yourself.
*
* ```handlebars
* <UiAlert @variant="success" as |Alert|>
* <p><Alert.title /> Great job team!</p>
* </UiAlert>
*
* {{#ui-alert "success" as |alert|}}
* {{alert.title plural=true}}
*
* <ul>
* <li>Task A worked!</li>
* <li>Task B rocked!</li>
* </ul>
* {{/ui-alert}}
* ```
*
* @yield ({ title: UiAlertTitle }) Alert
* */
@classNames('alert')
@layout(template)
export default class UiAlert extends Component {
public static readonly positionalParams = ['variant', 'content'];
public readonly ariaRole = 'alert';
/**
* The style of alert banner to create. For historical reasons and maximum cross-compatibility
* there are a number for aliases for each variant.
*
* - success, successes
* - warning, warnings
* - danger, error, errors, alert
* - info, informational, informationals, secondary
* - default, muted
*/
public variant?: AlertLevelKeys;
/**
* The text content of the alert banner. If provided and array of multiple strings
* they will be formatted as an unordered list in the order supplied. This may also be
* set as the second positional parameter of the component.
*/
public content?: string | string[];
/**
* The value of the element's `data-test-ident` attribute, if required. By default,
* it will be a string that follows the pattern "context-message-${variant}".
*/
@attribute('data-test-ident')
@listenTo('defaultTestId')
public testId?: string;
/**
* An object whose keys are AlertLevel strings and corresponding value is an object
* which can contain `icon`, `singular` and `plural` strings and will be used to
* create the alert heading. Levels that are not defined here will fall back to the
* defaults.
*/
public alertGroups?: Record<AlertLevel, AlertGroupDefinition>;
@computed('variant')
protected get defaultTestId() {
return `context-message-${this.variant}`;
}
@className()
@computed('correctVariant')
protected get variantClassName() {
return `alert-${this.correctVariant}`;
}
@computed('content.[]')
protected get pluralize() {
return isArray(this.content) && this.content.length > 1;
}
@computed('pluralize', 'content.[]')
protected get oneContentItem() {
return isArray(this.content) ? this.content[0] : this.content;
}
@computed('variant')
protected get correctVariant() {
return getCorrectedAlertLevel(this.variant || '');
}
@computed('correctVariant', 'alertGroups')
protected get groupOptions() {
if (this.correctVariant) {
return this.alertGroups?.[this.correctVariant] ?? AlertGroups[this.correctVariant];
}
return {};
}
} |
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar'
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Product } from './product-create/product.model';
import { Observable } from 'rxjs';
import { url } from 'node:inspector';
@Injectable({
providedIn: 'root',
})
export class ProductService {
baseUrl = "http://localhost:3001/products"
constructor(
private snackBar: MatSnackBar,
private http: HttpClient,
) { }
showMessage(msg: string): void {
this.snackBar.open(msg, 'X', {
duration: 3000,
horizontalPosition: "right",
verticalPosition: "top",
})
}
create(product: Product): Observable<Product> {
return this.http.post<Product>(this.baseUrl, product)
}
read(): Observable<Product[]> {
return this.http.get<Product[]>(this.baseUrl)
}
readById(id: string | null): Observable<Product> {
const url = `${this.baseUrl}/${id}`
return this.http.get<Product>(url)
}
update(product: Product): Observable<Product> {
const url = `${this.baseUrl}/${product.id}`
return this.http.put<Product>(url, product)
}
delete(id: any): Observable<Product> {
const url = `${this.baseUrl}/${id}`
return this.http.delete<Product>(url)
}
} |
import { CSSProperties, PropsWithChildren } from "react";
import { motion } from "framer-motion";
import c from "clsx";
interface AlbumArtProps extends PropsWithChildren {
albumArtUrl: string;
flip: boolean;
}
const albumArtFaceClassName = "absolute w-full h-full";
const backfaceHidden: CSSProperties = { backfaceVisibility: "hidden" };
const albumArtSize = "400px";
const AlbumArt: React.FC<AlbumArtProps> = ({ albumArtUrl, flip, children }) => {
return (
<div
className="relative"
style={{ width: albumArtSize, height: albumArtSize }}
>
{/* Front face of the album */}
<motion.div
initial={false}
animate={{
rotateY: flip ? 180 : 0,
rotateZ: flip ? 50 : 0
}}
className={c(albumArtFaceClassName)}
style={backfaceHidden}
>
<img src={albumArtUrl} alt="Album art" />
</motion.div>
{/* Back face of the album */}
<motion.div
initial={false}
animate={{
rotateY: flip ? 0 : 180,
rotateZ: flip ? 0 : 50
}}
className={c(
albumArtFaceClassName,
"flex justify-center items-center bg-neutral-900 text-neutral-100 font-bold text-5xl p-4 text-center"
)}
style={backfaceHidden}
>
{children}
</motion.div>
</div>
);
};
export default AlbumArt; |
<div class="sub-header-box with-data">
<div class="wrap">
<div class="line-item">
<div class="left-item title-wrap">
<label>{{ticketLabel}}</label>
<app-editable-title [value]="ticketTitle"
[light]="true"
[readonly]="true"
(changeValue)="titleVal($event)"></app-editable-title>
</div>
<div class="right-item">
<div class="el"
*ngFor="let item of ticketUsers">
<div class="small-user-box">
<app-image class="avatar-wrap"
[size]="36"
[type]="item.avatarType"
[imageUrl]="item.avatar"
[imageAlt]="item.name"
[initialColor]="item.initialColor"
[initial]="item.initial"></app-image>
<span>{{item.name}}</span>
<em>{{item.position}}</em>
</div>
</div>
<div class="el label-el">
<app-label [backgroundStyle]="label.color">{{label.value}}</app-label>
</div>
<div class="el button-el settings-placeholder">
<app-dd-menu [options]="pageSettings"
[light]="true"
(select)="selectPageSettings($event)"></app-dd-menu>
</div>
</div>
</div>
<div class="info-elements">
<ul>
<li *ngFor="let item of infoList">
<em>{{item.label}}</em>
<span>{{item.value}}</span>
</li>
</ul>
</div>
</div>
</div>
<div class="content">
<section class="main-content">
<div class="row top-level">
<div class="col-8">
<div class="messages">
<div class="message-form">
<mat-form-field class="full-width"
[ngClass]="readonly? 'readonly': ''">
<textarea matInput
rows="1"
autosize
placeholder="Add reply"
[(ngModel)]="newMessage"
[readonly]="readonly"
(focus)="focusMessage=true"></textarea>
</mat-form-field>
<div class="line-item form-hidden"
*ngIf="focusMessage">
<ul class="attachments-list">
<li *ngFor="let el of arrayFiles">
<a routerLink="{{el.path}}">
<i class="material-icons">attach_file</i>
<span>{{el.fileName}}</span>
</a>
<app-dd-menu class="attachments-list-settings"
[options]="attachmentSettings"
(select)="attachmentSettingsFunction($event, el)"></app-dd-menu>
</li>
</ul>
<div class="left-item">
<div class="attach-button">
<a class="attach-link"
(click)="file.click()">
<i class="material-icons">add_circle</i>
<span>Attachments</span>
</a>
<input type="file"
#file
multiple
class="hidden"
(change)="onChange($event)">
</div>
</div>
<div class="right-item">
<div class="el">
<button mat-raised-button
(click)="sendMessage(newMessage)"
color="primary">Reply</button>
</div>
</div>
</div>
</div>
<div class="messages-list">
<div class="item"
*ngFor="let item of messages">
<div class="avatar-wrap">
<app-image [size]="40"
[type]="item.icon.type"
[initial]="item.icon.initials"
[initialColor]="item.icon.color"
[imageUrl]="item.icon.photo"
[imageAlt]="item.name"></app-image>
<i *ngIf="item.icon.guru"
class="custom-icons icon-guru"></i>
</div>
<div class="message">
<strong>{{item.name}}</strong>
<em>{{item.date}}</em>
<p>{{item.message}}</p>
<ul class="attachments-list">
<li *ngFor="let el of item.attach">
<a routerLink="{{el.path}}">
<i class="material-icons">attach_file</i>
<span>{{el.fileName}}</span>
</a>
<app-dd-menu class="attachments-list-settings"
[options]="attachmentSettings"
(select)="attachmentMessageSettingsFunction($event, item, el)"></app-dd-menu>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="col-4">
<div class="form-title">
<h3>Attachments</h3>
</div>
<ul class="attachments-list">
<li *ngFor="let item of attachments">
<a routerLink="{{item.path}}">
<i class="material-icons">attach_file</i>
<span>{{item.fileName}}</span>
</a>
<app-dd-menu class="attachments-list-settings"
[options]="attachmentSettings"
(select)="attachmentSettingsFunction($event, item)"></app-dd-menu>
</li>
</ul>
</div>
</div>
</section>
</div> |
package com.bonboncompany.p4.ui.add;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.bonboncompany.p4.data.MeetingRepository;
import com.bonboncompany.p4.data.model.Room;
import com.bonboncompany.p4.util.SingleLiveEvent;
import java.time.LocalTime;
public class AddMeetingViewModel extends ViewModel {
private final MeetingRepository meetingRepository ;
private final MutableLiveData<Boolean> isSaveButtonEnabledMutableLiveData = new MutableLiveData<>(false);
private final SingleLiveEvent<Void> closeActivitySingleLiveEvent = new SingleLiveEvent<>();
private Room selectedRoom;
public AddMeetingViewModel(@NonNull MeetingRepository meetingRepository) {
this.meetingRepository = meetingRepository;
}
// activate add button !
public MutableLiveData<Boolean> getIsSaveButtonEnabledLiveData() {
return isSaveButtonEnabledMutableLiveData;
}
public void onTopicChanged(String topic) {
isSaveButtonEnabledMutableLiveData.setValue(!topic.isEmpty());
}
// single event close activity
public SingleLiveEvent<Void> getCloseActivitySingleLiveEvent() {
return closeActivitySingleLiveEvent;
}
//method creation
public void onAddButtonClicked(
@NonNull String topic,
@Nullable LocalTime time,
@Nullable Room room,
@NonNull String participantMail
) {
meetingRepository.addMeeting(topic, time, room, participantMail);
closeActivitySingleLiveEvent.call();
}
public void onRoomSelected (Room selectedItem){
selectedRoom = selectedItem;
}
} |
//
// LibraryViewController.swift
// SupremeNow
//
// Created by Marissa Kalkar on 2/24/21.
//
import UIKit
import FirebaseFirestore
class LibraryViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
//Set the arrayOfFavorites as the user default with key "myArray". Accesible across all classes
var arrayOfFavorites = UserDefaults.standard.stringArray(forKey: "myArray") ?? []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "theCell")! as UITableViewCell
//myCell.textLabel!.text = arrayOfFavorites[indexPath.row]
myCell.textLabel!.text = "hello"
return myCell
}
//function for handling a favorite. Here we store the favorite into a user default array and set it.
func handleMarkAsFavorite() {
let myCell = tableView.dequeueReusableCell(withIdentifier: "theCell")! as UITableViewCell
print("Marked as favorite")
arrayOfFavorites.append(myCell.textLabel?.text ?? "null")
UserDefaults.standard.set(arrayOfFavorites, forKey: "myArray")
print(arrayOfFavorites.count)
}
//https://programmingwithswift.com/uitableviewcell-swipe-actions-with-swift/
func tableView(_ tableView: UITableView,trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let favorite = UIContextualAction(style: .normal,
title: "Favorite") { [weak self] (action, view, completionHandler) in
self?.handleMarkAsFavorite()
completionHandler(true)
}
favorite.backgroundColor = .systemGreen
let configuration = UISwipeActionsConfiguration(actions: [favorite])
return configuration
}
//on the click of a favorites view we want to push a new view controller that shows details about the case
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("clicked for details")
// let selectedCase = (tableView, cellForRowAt: 0)
let storyBoard : UIStoryboard = UIStoryboard(name: "DetailView", bundle:nil)
let detailViewController = storyBoard.instantiateViewController(withIdentifier: "DetailView") as! DetailViewController
self.present(detailViewController, animated:true, completion:nil)
}
override func viewWillAppear(_ animated: Bool) {
arrayOfFavorites = UserDefaults.standard.stringArray(forKey: "myArray") ?? []
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
arrayOfFavorites = UserDefaults.standard.stringArray(forKey: "myArray") ?? []
tableView.reloadData()
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "theCell")
tableView.dataSource = self
print("in library")
}
} |
// import { useRouter } from "next/router";
import EventContent from "../../components/event-detail/event-content";
import EventLogistics from "../../components/event-detail/event-logistics";
import EventSummary from "../../components/event-detail/event-summary";
// import { getEventById } from "../../dummy-data";
import Head from "next/head";
import ErrorAlert from "../../components/ui/error-alert/error-alert";
import { getEventById, getFeaturedEvents } from "../../helpers/api-util";
const EventDetailedPage = ({ event }) => {
if (!event) {
return (
<>
<Head>
<title>Event Details — Events</title>
</Head>
<div className="center">
<p>Loading...</p>
</div>
</>
);
}
return (
<>
<Head>
<title>{event.title} — Events </title>
<meta name="description" content={event.description} />
</Head>
<EventSummary title={event.title} />
<EventLogistics
date={event.date}
address={event.location}
image={event.image}
imageAlt={event.title}
/>
<EventContent>
<p>{event.description}</p>
</EventContent>
</>
);
};
export async function getStaticProps(context) {
const eventId = context.params.eventId;
const event = await getEventById(eventId);
return {
props: {
event,
},
revalidate: 60,
};
}
export async function getStaticPaths() {
// const allEvents = await getAllEvents();
const featuredEvent = await getFeaturedEvents();
const paths = featuredEvent.map(event => ({
params: { eventId: event.id },
}));
return {
paths: paths,
fallback: "blocking",
};
}
export default EventDetailedPage; |
from django.contrib import admin
from .models import ImagePost, Comment
from django_summernote.admin import SummernoteModelAdmin
@admin.register(ImagePost)
class PostAdmin(SummernoteModelAdmin):
list_display = ('title', 'user', 'slug', 'status', 'created_on')
search_fields = ['title', 'content', 'user']
prepopulated_fields = {'slug': ('title',)}
list_filter = ('status', 'created_on', 'user')
summernote_fields = ('content',)
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('name', 'text', 'image_post', 'created_on', 'approved')
list_filter = ('approved', 'created_on')
search_fields = ('name', 'email', 'body')
actions = ['approve_comments']
def approve_comments(self, request, queryset):
queryset.update(approved=True) |
"use client";
import {
Card,
CardContent,
CardFooter,
CardHeader,
} from "@/components/ui/card";
import { Header } from "./header";
import { Social } from "./social";
import { BackButton } from "./back-button";
interface Props {
children: React.ReactNode;
headerLabel: string;
backButtonLabel: string;
backButtonHref: string;
showSocial?: boolean;
}
export const CardWrapper = ({
children,
backButtonHref,
backButtonLabel,
headerLabel,
showSocial,
}: Props) => {
return (
<Card className="w-[400px] shadow-md">
<CardHeader>
<Header label={headerLabel} />
</CardHeader>
<CardContent>{children}</CardContent>
{showSocial && (
<CardFooter>
<Social />
</CardFooter>
)}
<CardFooter>
<BackButton label={backButtonLabel} href={backButtonHref} />
</CardFooter>
</Card>
);
}; |
import "./App.css";
import Navbar from "./components/Navbar";
import Username from "./components/Username";
import Email from "./components/Email";
import Phone from "./components/Phone";
import { useState } from "react";
import { useSelector } from "react-redux";
function App() {
const user = useSelector((state) => state.user.value);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState(0);
const [disable, setDisable] = useState(false);
const loginButton = () => {
if (user.name !== "" && user.email !== "" && user.phone >= 100000000000) {
setName(user.name);
setEmail(user.email);
setPhone(user.phone);
setDisable(false);
} else {
setDisable(true);
alert("Must fill all of the form fields")
}
};
return (
<main className="flex flex-row justify-center h-svh">
<div className="flex flex-col w-full">
<Navbar name={name} email={email} phone={phone} />
<div className="flex flex-row w-full justify-center">
<div className="w-3/4 border rounded-lg p-5 m-5 shadow-2xl">
<Username />
<Email />
<Phone />
<div className="flex flex-col justify-center items-center">
<button
// disabled={disable}
className="bg-blue-400 px-5 py-2 shadow-md rounded-lg hover:bg-blue-300"
onClick={() => {
loginButton();
}}
>
Login
</button>
<div
className={`text-red-500 text-sm mt-3 ${
disable ? "flex" : "hidden"
}`}
>
Must fill all of the form fields
</div>
</div>
</div>
</div>
</div>
</main>
);
}
export default App; |
################################################################################
#IN THIS DO FILE: TABLES AND FIGURES TO DISPLAY RESULTS FROM SIMULATION.
#THIS FILE IS VERY MUCH AT ITS BEGINNING STILL; ANY MODIFICATION IS WELCOME.
################################################################################
##LOAD PACKAGES, SET DIRECTORY, LOAD RESULTS
################################################################################
library(tidyverse)
library(openxlsx)
library(cowplot)
library(lcmm)
rm(list=ls())
#set ggplot2 theme for consistency
theme_set(theme_bw())
#starting populations
sp <- readRDS("startingpopulations")
#languages
languages <- unique(sp$language)
#intergenerational transmission, slope, & population number
int.nb <- readRDS("xitr")
#simulation results
results <- bind_rows(
readRDS("first25_30runs"),
readRDS("last26_3runs"))
results <- bind_rows(
readRDS("first25_30runs"))
################################################################################
#LANGUAGE PROFILES
################################################################################
#number of speakers by year
simres <- results %>% group_by(period,language,run) %>% summarise(alive=sum(alive),births=sum(births))
#plot
ggplot(simres,aes(period,alive,group=run))+
geom_line()+
facet_wrap(.~language,scales="free")
ggplot(filter(simres,period==2100))+
geom_histogram(aes(alive))+
facet_wrap(.~language,scales="free")
max(simres$period)
#5 year periods
simres$period5 <- floor((simres$period-1)/5)*5+1
#language number (1 to n)
int.nb$number <- 1:length(int.nb$language)
#take 25 smallest languages
first25 <- int.nb %>% arrange(speaker) %>% slice(1:25)
#or 26 largest
last26 <- int.nb %>% arrange(speaker) %>% slice(26:51)
#Function to create plots########################################
plots <- function(n){
##name
name <- last26$language[n]
#projection results
projection <- filter(simres,language==name)
#average across runs
projection <- left_join(projection,projection %>% group_by(period) %>% summarise(average=mean(alive)),by="period")
#rate of intergenational transmission
projection <- left_join(projection,projection %>% group_by(period5) %>% summarise(itr=mean(births)/mean(alive)*1000),by="period5")
#age distribution
agedist <- filter(sp,language==name)
agedist$speaker <- round(agedist$speaker)
#initial size
size1 <- round(filter(int.nb,language==name)$speaker)
#final size
size2 <- unique(round(filter(projection,period==2100)$average))
minyr2100 <- min(filter(projection,period==2100)$alive)
maxyr2100 <- max(filter(projection,period==2100)$alive)
#dormancy
dormancy <- round(length(filter(projection,period==2100,alive==0)$language)/max(projection$run),2)
#plot trends
trends <- ggplot(projection,aes(period,alive,group=run))+
geom_line(color="grey")+
geom_line(aes(period,average))+
theme_bw()+
xlab("Year")+
ylab("Number of speakers")
#plot age distribution
pyramid <- ggplot(agedist,aes(age,speaker))+
geom_col()+
coord_flip()+
theme_bw()+
ylab("Number of speakers")+
xlab("Age")+
scale_x_continuous(breaks=c(seq(0,100,20)))
#plot intergenerational transmission rate
itr <- ggplot(projection,aes(period5,itr))+
geom_line()+
theme_bw()+
xlab("Year")+
ylab("Rate (x 1,000)")+
scale_y_continuous(limits=c(0,25))
info <- paste(name,"\nSpeakers in 2016: ",size1,"\nSpeakers in 2100: ",size2," (",minyr2100,"-",maxyr2100,")\nDormancy risk in 2100: ",dormancy,sep="")
#arrange in grid
plot_grid(trends,pyramid,NULL,itr,
labels=c("Trends",
"Distribution by age in year 2016",
info,
"Intergenerational transmission rate"),
ncol=2,rel_heights=c(3,2))
ggsave(paste(name,".tiff",sep=""),height=7,width=12)
}
lapply(1:26,function(x) plots(x))
#######################################################################################################
############################################################
#Estimate trajectories
############################################################
#average across runs and inital speaker number in the year 2016
trajectories <- left_join(simres %>% group_by(period5,language) %>% summarise(average=mean(alive)),
simres %>% group_by(language) %>% filter(period==2016) %>% summarise(alive2016=mean(alive)))
#proportion of initial number over time
trajectories$proportion <- round(trajectories$average / trajectories$alive2016 *100, 1)
#add language number
trajectories$nb <- rep(1:51,85/5)
#reconvert year to years after 2016
trajectories$period0 <- trajectories$period5-2016
#visualize pathways
ggplot(trajectories,aes(period5,proportion,group=nb))+
geom_line()
#model with splines and 3 groups
model3splines <- lcmm(proportion ~ period0, random = ~ period0, subject = 'nb',
mixture = ~ period0, ng = 3, idiag = TRUE, data=trajectories,
link="splines")
#mixutre model with splines and 4 groups
model4splines <- lcmm(proportion ~ period0, random = ~ period0, subject = 'nb',
mixture = ~ period0, ng = 4, idiag = TRUE, data=trajectories,
link="splines")
#mixutre model with splines and 5 groups
model5splines <- lcmm(proportion ~ period0, random = ~ period0, subject = 'nb',
mixture = ~ period0, ng = 5, idiag = TRUE, data=trajectories,
link="splines")
#Compare models
model3splines
model4splines
model5splines
#the model with 3 groups fits best; put in data frame
results <- data.frame(period0=seq(0,80,5))
results.raw <- predictY(model3splines, newdata=results, var.time="period0", draws = T)
results <- data.frame(period5=rep(seq(2016,2096,5),3),
predicted=results.raw$pred[1:(17*3)],
lower=results.raw$pred[(17*3+1):(17*3*2)],
upper=results.raw$pred[(17*3*2+1):(17*3*3)],
group=rep(c("1","2","3"),each=17))
#assign the groups in the initial data
trajectories$group <- as.character(rep(model3splines$pprob[,2],17))
#merge the two sets
results <- left_join(results,select(trajectories,period5,proportion,group,nb))
#plot
ggplot(results)+
geom_line(aes(period5,proportion,group=nb),color="grey")+
geom_line(aes(period5,predicted,group=group,color=group),size=1.5)+
geom_line(aes(period5,lower,group=group,color=group),linetype="dashed")+
geom_line(aes(period5,upper,group=group,color=group),linetype="dashed")+
ylab("Change in the number of speakers\n(% of the initial population size)")+
xlab("Year")
ggsave("trajectories.tiff",height=6,width=8)
#breakdown by group
table(model3splines$pprob[,2])
#######################################################################################
#Attempt considering each run for each language
#######################################################################################
#new data set with proportion of speakers to number in 2016
trajectories <- simres %>% ungroup() %>% select(-period) %>% distinct(period5,language,run,.keep_all=T)
initial <- simres %>% ungroup() %>% filter(period==2016) %>% rename(initial=alive) %>% select(language,initial) %>% distinct()
trajectories <- left_join(trajectories,initial,by="language")
trajectories$proportion <- trajectories$alive/trajectories$initial
#add language number
trajectories$nb <- rep(1:(25*30),17)
#reconvert year to years after 2016
trajectories$period0 <- trajectories$period5-2016
ggplot(trajectories,aes(period5,proportion,group=nb))+
geom_line()
#model with splines and 3 groups
model3splines <- lcmm(proportion ~ period0, random = ~ period0, subject = 'nb',
mixture = ~ period0, ng = 3, idiag = TRUE, data=trajectories,
link="splines")
#put in data frame
results <- data.frame(period0=seq(0,80,5))
results.raw <- predictY(model3splines, newdata=results, var.time="period0", draws = T)
results <- data.frame(period5=rep(seq(2016,2096,5),3),
predicted=results.raw$pred[1:(17*3)],
lower=results.raw$pred[(17*3+1):(17*3*2)],
upper=results.raw$pred[(17*3*2+1):(17*3*3)],
group=rep(c("1","2","3"),each=17))
#assign the groups in the initial data
trajectories$group <- as.character(rep(model3splines$pprob[,2],17))
#merge the two sets
results <- left_join(results,select(trajectories,period5,proportion,group,nb))
#plot
ggplot(results)+
geom_line(aes(period5,predicted,group=group,color=group),size=1)+
geom_line(aes(period5,proportion,group=nb),color="grey")+
geom_line(aes(period5,lower,group=group,color=group),linetype="dashed")+
geom_line(aes(period5,upper,group=group,color=group),linetypea="dashed")+
ylab("Change in the number of speakers \n (proportional to the initial population size)")+
xlab("Year")
#breakdown by group
table(model3splines$pprob[,2]) |
//package ch7;
//
///*[]
//1.상속관계
//2.부모와 자식관계에서
//ㄴ2.1맴버변수가 이름이 동일한 경우
// - 참조변수가 부모인 경우 => 부모의 맴버변수
// - 참조변수가 자식인 경우 => 자식의 맴버변수
// ㄴ-->>맴버볌수는 덮어써지고
//ㄴ2.2오버라이드 된 메소드가 있는경우
// - 참조변수가 부모인 경우 => 자식의 오버라이드 메소드
// - 참조변수가 자식인 경우 => 자식의 오버라이드 메소드
// ㄴ-->>메소드는 덮어써지고
// */
//
//
////부모 class 만들기
//class Parent2 {
//
// int x = 100; //2.1의 케이스인 =>인스턴스변수
//
// void method() { //2.2의 케이스
// System.out.println("Parent Method");
// }
//
//}
//
////자식 class 만들기
//class Child2 extends Parent2 {
//
// int x = 200; //2.1의 케이스인 =>인스턴스변수
//
// //위의 조건을 이용해서 객체를 생성
// //자식객체를 생성하는데, 부모타입과 자식타입 각각생성
// //=>동일한 객체이지만, 참조변수의 타입이 부모, 자식의 경우.
// public class BindingTest {
//
// public static void main(String[] args) {
//
// Parent2 p = new Child2();
// //부모타입의 자식객체
// Child2 c = new Child2();
// //자식타입의 자식객체
//
// //참조변수를 이용해서 위의 2.1, 2.2의 조건을 실행
//
// //참조변수가 부모타입
// System.out.println("p.x(부모) = " + p.x);
// p.method();
//
// //참조변수가 자식타입
// System.out.println("c.x(자식) = " + c.x);
// c.method(); //<<--오버라이드 된것
// }
//
// void method() { //2.2의 케이스인 => 메소드 오버라이딩
// System.out.println("Chile Method");
// }
//
// }
//} |
import React, { useState, useEffect } from "react";
import PokemonDetail from "./PokemonDetail";
import PokemonList from "./Pokemonlist";
function Dashboard() {
const [pokemons, setPokemon] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => setPokemon(data));
}, []);
return (
<div className="container">
<div className="row mt-2">
<div className="col-lg-4">
{pokemons.map((user) => {
return <PokemonList user={user} />;
})}
</div>
<div className="col-lg-8"></div>
</div>
</div>
);
}
export default Dashboard; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Peter Jeon - Personal Portfolio</title>
<!--
- favicon
-->
<link rel="shortcut icon" href="./assets/images/logo.ico" type="image/x-icon">
<!--
- custom css link
-->
<link rel="stylesheet" href="./assets/css/style.css">
<!--
- google font link
-->
<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=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
</head>
<body>
<!--
- #MAIN
-->
<main>
<!--
- #SIDEBAR
-->
<aside class="sidebar" data-sidebar>
<div class="sidebar-info">
<figure class="avatar-box">
<img src="./assets/images/me.png" alt="Peter Jeon" width="80">
</figure>
<div class="info-content">
<h1 class="name" title="Peter Jeon">Peter Jeon</h1>
<p class="title">Web developer</p>
</div>
<button class="info_more-btn" data-sidebar-btn>
<span>Show Contacts</span>
<ion-icon name="chevron-down"></ion-icon>
</button>
</div>
<div class="sidebar-info_more">
<div class="separator"></div>
<ul class="contacts-list">
<li class="contact-item">
<div class="icon-box">
<ion-icon name="mail-outline"></ion-icon>
</div>
<div class="contact-info">
<p class="contact-title">Email</p>
<a href="mailto:[email protected]" class="contact-link">[email protected]</a>
</div>
</li>
<li class="contact-item">
<div class="icon-box">
<ion-icon name="calendar-outline"></ion-icon>
</div>
<div class="contact-info">
<p class="contact-title">Birthday</p>
<time datetime="1982-06-23">June 27, 1998</time>
</div>
</li>
<li class="contact-item">
<div class="icon-box">
<ion-icon name="location-outline"></ion-icon>
</div>
<div class="contact-info">
<p class="contact-title">Location</p>
<address>Prince Edward, 258 Prince Edward Rd W, Hong Kong</address>
</div>
</li>
</ul>
<div class="separator"></div>
<ul class="social-list">
<li class="social-item">
<a href="#" class="social-link">
<ion-icon name="logo-facebook"></ion-icon>
</a>
</li>
<li class="social-item">
<a href="#" class="social-link">
<ion-icon name="logo-twitter"></ion-icon>
</a>
</li>
<li class="social-item">
<a href="#" class="social-link">
<ion-icon name="logo-instagram"></ion-icon>
</a>
</li>
<li class="social-item">
<a href="#" class="social-link">
<ion-icon name="logo-github"></ion-icon>
</a>
</li>
<li class="social-item">
<a href="#" class="social-link">
<ion-icon name="logo-skype"></ion-icon>
</a>
</li>
</ul>
</div>
</aside>
<!--
- #main-content
-->
<div class="main-content">
<!--
- #NAVBAR
-->
<nav class="navbar">
<ul class="navbar-list">
<li class="navbar-item">
<button class="navbar-link active" data-nav-link>About</button>
</li>
<li class="navbar-item">
<button class="navbar-link" data-nav-link>Resume</button>
</li>
<li class="navbar-item">
<button class="navbar-link" data-nav-link>Portfolio</button>
</li>
</ul>
</nav>
<!--
- #ABOUT
-->
<article class="about active" data-page="about">
<header>
<h2 class="h2 article-title">About me</h2>
</header>
<section class="about-text">
<p>
I am a talented and professional Full Stack Developer with over 7 years of rich experience and background in web development.
</p>
<p>
Versatile Full Stack Developer with a solid foundation in both frontend and backend development.
Proficient in a wide range of programming languages and frameworks, including JavaScript, Python, HTML, CSS, React, Node.js, and Django.
Experienced in designing and implementing scalable and secure web applications from concept to deployment.
Skilled in database management, RESTful API development, and cloud deployment using platforms.
Strong problem-solving abilities and a passion for delivering high-quality code that meets client requirements.
Excellent communication and collaboration skills, working effectively in cross-functional teams.
Continuously learning and adapting to new technologies to stay at the forefront of the rapidly evolving development landscape.
</p>
</section>
<!--
- service
-->
<section class="service">
<h3 class="h3 service-title">What i'm doing</h3>
<ul class="service-list">
<li class="service-item">
<div class="service-icon-box">
<img src="./assets/images/icon-dev.svg" alt="Web development icon" width="40">
</div>
<div class="service-content-box">
<h4 class="h4 service-item-title">Web development</h4>
<p class="service-item-text">
High-quality development of sites at the professional level.
</p>
</div>
</li>
<li class="service-item">
<div class="service-icon-box">
<img src="./assets/images/icon-app.svg" alt="mobile app icon" width="40">
</div>
<div class="service-content-box">
<h4 class="h4 service-item-title">Mobile apps</h4>
<p class="service-item-text">
Professional development of applications for iOS and Android.
</p>
</div>
</li>
<li class="service-item">
<div class="service-icon-box">
<img src="./assets/images/icon-photo.svg" alt="camera icon" width="40">
</div>
<div class="service-content-box">
<h4 class="h4 service-item-title">Applications</h4>
<p class="service-item-text">
I make high-quality applications of any feature at a professional level.
</p>
</div>
</li>
</ul>
</section>
<!--
- testimonials
-->
<section class="testimonials">
<h3 class="h3 testimonials-title">Testimonials</h3>
<ul class="testimonials-list has-scrollbar">
<li class="testimonials-item">
<div class="content-card" data-testimonials-item>
<figure class="testimonials-avatar-box">
<img src="./assets/images/daniel lewis.png" alt="Daniel lewis" width="60" data-testimonials-avatar>
</figure>
<h4 class="h4 testimonials-item-title" data-testimonials-title>Daniel lewis</h4>
<div class="testimonials-text" data-testimonials-text>
<p>
Peter is a real expert with Web Development.
He did a great job with translating our site, and he went the extra mile to help with a lot of other things.
Therefore, I definitely recommend working with him!
</p>
</div>
</div>
</li>
<li class="testimonials-item">
<div class="content-card" data-testimonials-item>
<figure class="testimonials-avatar-box">
<img src="./assets/images/Jessica miller.png" alt="Jessica miller" width="60" data-testimonials-avatar>
</figure>
<h4 class="h4 testimonials-item-title" data-testimonials-title>Jessica miller</h4>
<div class="testimonials-text" data-testimonials-text>
<p>
Peter quick and high-quality work within a very limited time!
Thank you so much for all the working adjustments, will definitely collaborate in the future again!
</p>
</div>
</div>
</li>
<li class="testimonials-item">
<div class="content-card" data-testimonials-item>
<figure class="testimonials-avatar-box">
<img src="./assets/images/Emily Brawn.png" alt="Emily evans" width="60" data-testimonials-avatar>
</figure>
<h4 class="h4 testimonials-item-title" data-testimonials-title>Emily Brawn</h4>
<div class="testimonials-text" data-testimonials-text>
<p>
Peter did a great job. The project was done in good quality and in the agreed terms.
All the feedback was implemented. I recommend hiring him for your projects.
</p>
</div>
</div>
</li>
<li class="testimonials-item">
<div class="content-card" data-testimonials-item>
<figure class="testimonials-avatar-box">
<img src="./assets/images/Henry William.png" alt="Henry william" width="60" data-testimonials-avatar>
</figure>
<h4 class="h4 testimonials-item-title" data-testimonials-title>Henry william</h4>
<div class="testimonials-text" data-testimonials-text>
<p>
Overall great developer who is willing to help you with your projects.
Happy with their availability and communication considering the time zone difference!
</p>
</div>
</div>
</li>
</ul>
</section>
<!--
- testimonials modal
-->
<div class="modal-container" data-modal-container>
<div class="overlay" data-overlay></div>
<section class="testimonials-modal">
<button class="modal-close-btn" data-modal-close-btn>
<ion-icon name="close-outline"></ion-icon>
</button>
<div class="modal-img-wrapper">
<figure class="modal-avatar-box">
<img src="./assets/images/avatar-1.png" alt="Daniel lewis" width="80" data-modal-img>
</figure>
<img src="./assets/images/icon-quote.svg" alt="quote icon">
</div>
<div class="modal-content">
<h4 class="h3 modal-title" data-modal-title>Daniel lewis</h4>
<span class="feedback">Feedback</span>
<div data-modal-text>
<p>
Peter-Jeon
</p>
</div>
</div>
</section>
</div>
<!--
- clients
-->
<section class="clients">
<h3 class="h3 clients-title">Clients</h3>
<ul class="clients-list has-scrollbar">
<li class="clients-item">
<a href="#">
<img src="./assets/images/logo-1-color.png" alt="client logo">
</a>
</li>
<li class="clients-item">
<a href="#">
<img src="./assets/images/logo-2-color.png" alt="client logo">
</a>
</li>
<li class="clients-item">
<a href="#">
<img src="./assets/images/logo-3-color.png" alt="client logo">
</a>
</li>
<li class="clients-item">
<a href="#">
<img src="./assets/images/logo-4-color.png" alt="client logo">
</a>
</li>
<li class="clients-item">
<a href="#">
<img src="./assets/images/logo-5-color.png" alt="client logo">
</a>
</li>
<li class="clients-item">
<a href="#">
<img src="./assets/images/logo-6-color.png" alt="client logo">
</a>
</li>
</ul>
</section>
</article>
<!--
- #RESUME
-->
<article class="resume" data-page="resume">
<header>
<h2 class="h2 article-title">Resume</h2>
</header>
<section class="timeline">
<div class="title-wrapper">
<div class="icon-box">
<ion-icon name="book-outline"></ion-icon>
</div>
<h3 class="h3">Education</h3>
</div>
<ol class="timeline-list">
<li class="timeline-item">
<h4 class="h4 timeline-item-title">The Hong Kong University of Science and Technology</h4>
<span>Bachelor's Degree in Computer Science</span>
<p class="timeline-text">
I learned a lot about computer science and web fields in university and participated in a lot of web development with the university team.
During university, I gained a lot of experience, foundation, and skills, and received a bachelor's degree.
</p>
</li>
<li></li>
</ol>
</section>
<section class="timeline">
<div class="title-wrapper">
<div class="icon-box">
<ion-icon name="book-outline"></ion-icon>
</div>
<h3 class="h3">Experience</h3>
</div>
<ol class="timeline-list">
<li class="timeline-item">
<h4 class="h4 timeline-item-title">Full Stack Developer</h4>
<span>07/2020 - 08/2023 | ALLUA LIMITED | Hong Kong</span>
<p class="timeline-text">
Conducted comprehensive code reviews for a team of 12 developers, identifying and addressing bugs and architectural improvements,
resulting in a 30% reduction in production issues and improved overall code quality.
A transportation service system based on transportation apps and Google Maps focusing on mobile app development using React Native.
Maximize application efficiency, data quality, scope, operability and flexibility.
Improved customer service by 90% by developing a new management panel for our purchasing agency business.
</p>
</li>
<li class="timeline-item">
<h4 class="h4 timeline-item-title">Frontend Developer | Full Stack Developer</h4>
<span>08/2016 - 06/2020 | VISICHAIN | Hong Kong</span>
<p class="timeline-text">
I achieved a lot during that time, including increasing the number of active users on the website by 60% and increasing page views to 1.5 million page views per month.
Also, implemented an inventory management system that reduced data capture time by 80% and the number of errors by 40%.
</p>
</li>
<li></li>
</ol>
</section>
<section class="skill">
<h3 class="h3 skills-title">My skills</h3>
<ul class="skills-list content-card">
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">React</h5>
<data value="80">95%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 95%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">React Native</h5>
<data value="70">80%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 80%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">NodeJS</h5>
<data value="90">90%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 90%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">ExpressJS</h5>
<data value="90">90%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 90%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">VueJS</h5>
<data value="90">80%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 80%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">NextJS</h5>
<data value="90">80%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 80%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">JavaScript</h5>
<data value="50">95%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 95%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">TypeScript</h5>
<data value="50">85%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 85%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">MySQL | PostgreSQL | MongoDB</h5>
<data value="50">75%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 75%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">Database Management</h5>
<data value="50">75%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 75%;"></div>
</div>
</li>
<li class="skills-item">
<div class="title-wrapper">
<h5 class="h5">Material UI | TailWindCSS</h5>
<data value="50">85%</data>
</div>
<div class="skill-progress-bg">
<div class="skill-progress-fill" style="width: 85%;"></div>
</div>
</li>
</ul>
</section>
</article>
<!--
- #PORTFOLIO
-->
<article class="portfolio" data-page="portfolio">
<header>
<h2 class="h2 article-title">Portfolio</h2>
</header>
<section class="projects">
<ul class="filter-list">
<li class="filter-item">
<button class="active" data-filter-btn>All</button>
</li>
<li class="filter-item">
<button data-filter-btn>Applications</button>
</li>
<li class="filter-item">
<button data-filter-btn>Web development</button>
</li>
</ul>
<div class="filter-select-box">
<button class="filter-select" data-select>
<div class="select-value" data-selecct-value>Select category</div>
<div class="select-icon">
<ion-icon name="chevron-down"></ion-icon>
</div>
</button>
<ul class="select-list">
<li class="select-item">
<button data-select-item>All</button>
</li>
<li class="select-item">
<button data-select-item>Web design</button>
</li>
<li class="select-item">
<button data-select-item>Applications</button>
</li>
<li class="select-item">
<button data-select-item>Web development</button>
</li>
</ul>
</div>
<ul class="project-list">
<li class="project-item active" data-filter-item data-category="web development">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-1.jpg" alt="finance" loading="lazy">
</figure>
<h3 class="project-title">Finance</h3>
<p class="project-category">Web development</p>
</a>
</li>
<li class="project-item active" data-filter-item data-category="web development">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-2.png" alt="orizon" loading="lazy">
</figure>
<h3 class="project-title">Orizon</h3>
<p class="project-category">Web development</p>
</a>
</li>
<li class="project-item active" data-filter-item data-category="web development">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-3.jpg" alt="fundo" loading="lazy">
</figure>
<h3 class="project-title">Fundo</h3>
<p class="project-category">Web development</p>
</a>
</li>
<li class="project-item active" data-filter-item data-category="applications">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-4.png" alt="brawlhalla" loading="lazy">
</figure>
<h3 class="project-title">Brawlhalla</h3>
<p class="project-category">Applications</p>
</a>
</li>
<li class="project-item active" data-filter-item data-category="applications">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-10.png" alt="chair selling" loading="lazy">
</figure>
<h3 class="project-title">Chair Selling</h3>
<p class="project-category">Applications</p>
</a>
</li>
<li class="project-item active" data-filter-item data-category="web development">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-6.png" alt="metaspark" loading="lazy">
</figure>
<h3 class="project-title">MetaSpark</h3>
<p class="project-category">Web development</p>
</a>
</li>
<li class="project-item active" data-filter-item data-category="web development">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-7.png" alt="summary" loading="lazy">
</figure>
<h3 class="project-title">Summary</h3>
<p class="project-category">Web development</p>
</a>
</li>
<li class="project-item active" data-filter-item data-category="applications">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-8.jpg" alt="task manager" loading="lazy">
</figure>
<h3 class="project-title">Task Manager</h3>
<p class="project-category">Applications</p>
</a>
</li>
<li class="project-item active" data-filter-item data-category="web development">
<a href="#">
<figure class="project-img">
<div class="project-item-icon-box">
<ion-icon name="eye-outline"></ion-icon>
</div>
<img src="./assets/images/project-9.png" alt="arrival" loading="lazy">
</figure>
<h3 class="project-title">Arrival</h3>
<p class="project-category">Web development</p>
</a>
</li>
</ul>
</section>
</article>
</div>
</main>
<!--
- custom js link
-->
<script src="./assets/js/script.js"></script>
<!--
- ionicon link
-->
<script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script>
</body>
</html> |
class AlumnoDaw {
constructor(nombre, apellido, email, edad) {
this._nombre = nombre;
this._apellido = apellido;
this._email = email;
this._edad = edad;
}
get nombre() {
return this._nombre;
}
set nombre(nuevoNombre) {
this._nombre = nuevoNombre;
}
get apellido() {
return this._apellido;
}
set apellido(nuevoApellido) {
this._apellido = nuevoApellido;
}
get email() {
return this._email;
}
set email(nuevoEmail) {
this._email = nuevoEmail;
}
get edad() {
return this._edad;
}
set edad(nuevaEdad) {
if (nuevaEdad >= 0) {
this._edad = nuevaEdad;
} else {
console.log("La edad no puede ser un valor negativo.");
}
}
}
const alumno = new AlumnoDaw("Manolo", "Gomez", "[email protected]", 45);
console.log("Nombre:", alumno.nombre);
console.log("Apellido:", alumno.apellido);
console.log("Email:", alumno.email);
console.log("Edad:", alumno.edad);
alumno.nombre = "Luis";
alumno.apellido = "Gómez";
alumno.email = "[email protected]";
alumno.edad = 30;
console.log("Nombre modificado:", alumno.nombre);
console.log("Apellido modificado:", alumno.apellido);
console.log("Email modificado:", alumno.email);
console.log("Edad modificado:", alumno.edad); |
#RUN: %fish %s
# Verify zombies are not left by disown (#7183, #5342)
# Do this first to avoid colliding with the other disowned processes below, which may
# still be running at the end of the script
sleep 0.2 &
disown
sleep 0.2
echo Trigger process reaping
sleep 0.1
#CHECK: Trigger process reaping
# The initial approach here was to kill the PID of the sleep process, which should
# be gone by the time we get here. Unfortunately, kill from procps on pre-2016 distributions
# does not print an error for non-existent PIDs, so instead look for zombies in this session.
# There could already be zombies from previous tests run in this session or a test could be run
# simultaneously that causes a zombie to spawn, so limit the output only to processes started by
# this fish instance.
if not contains (uname) SunOS
ps -o ppid,stat
else
ps -o ppid,s
end | string match -e $fish_pid | string match '*Z*'
# Verify disown can be used with last_pid, even if it is separate from the pgroup.
# This should silently succeed.
command true | sleep 0.5 &
disown $last_pid
jobs -q
echo $status
#CHECK: 1
sleep 5 &
sleep 5 &
jobs -c
#CHECK: Command
#CHECK: sleep
#CHECK: sleep
jobs -q
echo $status
#CHECK: 0
bg -23 1 2>/dev/null
or echo bg: invalid option -23 >&2
#CHECKERR: bg: invalid option -23
fg 3
#CHECKERR: fg: No suitable job: 3
bg 3
#CHECKERR: bg: Could not find job '3'
sleep 1 &
disown
jobs -c
#CHECK: Command
#CHECK: sleep
#CHECK: sleep
jobs 1
echo $status
#CHECK: 1
#CHECKERR: jobs: No suitable job: 1
jobs foo
echo $status
#CHECK: 2
#CHECKERR: jobs: 'foo' is not a valid process id
jobs -q 1
echo $status
#CHECK: 1
jobs -q foo
echo $status
#CHECK: 2
#CHECKERR: jobs: 'foo' is not a valid process id
disown foo
#CHECKERR: disown: 'foo' is not a valid job specifier
disown (jobs -p)
or exit 0
# Verify `jobs` output within a function lists background jobs
# https://github.com/fish-shell/fish-shell/issues/5824
function foo
sleep 0.2 &
jobs -c
end
foo
# Verify we observe job exit events
sleep 1 &
set sleep_job $last_pid
function sleep_done_$sleep_job --on-job-exit $sleep_job
/bin/echo "sleep is done"
functions --erase sleep_done_$sleep_job
end
sleep 2
# Verify `jobs -l` works and returns the right status codes
# https://github.com/fish-shell/fish-shell/issues/6104
jobs --last --command
echo $status
#CHECK: Command
#CHECK: sleep
#CHECK: sleep is done
#CHECK: 1
sleep 0.2 &
jobs -lc
echo $status
#CHECK: Command
#CHECK: sleep
#CHECK: 0
function foo
function caller --on-job-exit caller
echo caller
end
echo foo
end
function bar --on-event bar
echo (foo)
end
emit bar
#CHECK: foo
#CHECK: caller
# We can't rely on a *specific* pgid being assigned,
# but we can rely on it not being fish's.
command true &
set -l truepid $last_pid
test $truepid != $fish_pid || echo true has same pid as fish
# Job exit events work even after the job has exited!
sleep .5
function thud --on-job-exit $truepid
echo "thud called"
end
# CHECK: thud called |
// custom
import React from "react";
import * as THREE from "three";
import {useRef, useState, useMemo, useEffect, Suspense} from "react";
import {useFrame} from "@react-three/fiber";
import {Text, OrbitControls} from "@react-three/drei";
import {LayerMaterial, Base, Depth, Fresnel} from 'lamina'
const skills = [
"JavaScript",
"TypeScript",
"gatsby",
"REST",
"HTML",
"CSS",
"React",
"Three.js",
"R3F",
"GraphQL",
"Flask",
"Socket",
"SQL",
"webGL",
"C++",
"Python",
"mbed",
"ROS",
"Java",
"Swift",
"Firebase",
"OpenGL",
"OpenCV",
"Korean",
"Teamwork",
"Algorithms",
"Data Structure",
"Creativity",
"UX/UI",
"Research",
"Interaction Design",
"OOP",
"Adobe",
"Git",
"HCI",
"HRI",
];
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let returnedSkills = [];
function randomSkill() {
if (returnedSkills.length === skills.length) { // check if all skills have been returned
returnedSkills = []; // reset the array of previously returned skills
}
let availableSkills = skills.filter((skill) => ! returnedSkills.includes(skill));
if (availableSkills.length === 0) {
return "No more skills left";
}
let randomIndex = getRandomInt(availableSkills.length);
let randomSkill = availableSkills[randomIndex];
returnedSkills.push(randomSkill);
return randomSkill;
}
function Word({
children,
...props
}) {
const color = new THREE.Color();
const fontProps = {
font: "/../static/Inter-Bold.woff",
fontSize: 2.5,
letterSpacing: -0.05,
lineHeight: 1,
"material-toneMapped": false
};
const ref = useRef();
const [hovered, setHovered] = useState(false);
const over = (e) => (e.stopPropagation(), setHovered(true));
const out = () => setHovered(false);
// Change the mouse cursor on hover
useEffect(() => {
if (hovered) {
document.body.style.cursor = "pointer";
}
return() => (document.body.style.cursor = "auto");
}, [hovered]);
// Tie component to the render-loop
useFrame(({camera}) => { // Make text face the camera
ref.current.quaternion.copy(camera.quaternion);
ref.current.material.color.lerp(color.set(hovered ? "#1C77C3" : "white"), 0.1);
});
return (
<Text ref={ref}
onPointerOver={over}
onPointerOut={out}
{...props}
{...fontProps}
children={children}/>
);
}
function Cloud({
count = 4,
radius = 20
}) { // Create a count x count random words with spherical distribution
const words = useMemo(() => {
const temp = [];
const spherical = new THREE.Spherical();
const phiSpan = Math.PI / (count + 1);
const thetaSpan = (Math.PI * 2) / count;
for (let i = 1; i < count + 1; i++) {
for (let j = 0; j < count; j++) {
temp.push([
new THREE.Vector3().setFromSpherical(spherical.set(radius, phiSpan * i, thetaSpan * j)),
randomSkill(),
]);
}
}
return temp;
}, [count, radius]);
return words.map(([
pos, word
], index) => (
<Word key={index}
position={pos}
children={word}/>
));
}
export default function Experience() {
const atom = useRef();
const atom1 = useRef();
const atom2 = useRef();
const atom3 = useRef();
const atom4 = useRef();
const props = {
base: {
value: '#ff4eb8'
},
colorA: {
value: '#00ffff'
},
colorB: {
value: '#ff8f00'
}
}
useFrame(({camera, clock}) => {
atom.current.position.x = Math.sin(clock.elapsedTime) * 21
atom.current.position.y = -Math.cos(clock.elapsedTime) * 21
atom.current.position.z = Math.sin(clock.elapsedTime) * 21
atom1.current.position.x = Math.cos(clock.elapsedTime+5) * 21
atom1.current.position.y = Math.sin(clock.elapsedTime) * 21
atom1.current.position.z = Math.sin(clock.elapsedTime+2) * 21
atom2.current.position.x = Math.cos(clock.elapsedTime) * 21
atom2.current.position.z = -Math.sin(clock.elapsedTime-9) * 21
atom3.current.position.x = Math.sin(clock.elapsedTime-3) * 21
atom3.current.position.y = -Math.cos(clock.elapsedTime+4) * 21
atom3.current.position.z = Math.sin(clock.elapsedTime+2) * 21
atom4.current.position.x = -Math.cos(clock.elapsedTime+5) * 21
atom4.current.position.y = -Math.sin(clock.elapsedTime) * 21
atom4.current.position.z = Math.sin(clock.elapsedTime+2) * 21
});
return (
<>
<ambientLight intensity={0.4}/>
<fog attach="fog"
args={
["#202020", 0, 80]
}/>
<Cloud count={8}
radius={20}/>
<mesh ref={atom}
position={
[22, 0, 0]
}>
<sphereBufferGeometry args={
[.5, 12, 12]
}/>
<meshBasicMaterial color="hotpink"/>
</mesh>
<mesh ref={atom1}
position={
[22, 0, 0]
}>
<sphereBufferGeometry args={
[.5, 12, 12]
}/>
<meshBasicMaterial color="hotpink"/>
</mesh>
<mesh ref={atom2}
position={
[22, 0, 0]
}>
<sphereBufferGeometry args={
[.5, 12, 12]
}/>
<meshBasicMaterial color="hotpink"/>
</mesh>
<mesh ref={atom3}
position={
[22, 0, 0]
}>
<sphereBufferGeometry args={
[.5, 12, 12]
}/>
<meshBasicMaterial color="hotpink"/>
</mesh>
<mesh ref={atom4}
position={
[22, 0, 0]
}>
<sphereBufferGeometry args={
[.5, 12, 12]
}/>
<meshBasicMaterial color="hotpink"/>
</mesh>
<OrbitControls enableZoom={false}/>
</>
);
} |
import os
import pickle
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class SpellChecker:
def __init__(self):
self.root = TrieNode()
self.load_dictionary()
def load_dictionary(self):
dictionary_file = 'dictionary.txt'
if os.path.exists(dictionary_file):
with open(dictionary_file, 'rb') as file:
self.root = pickle.load(file)
def save_dictionary(self):
dictionary_file = 'dictionary.txt'
with open(dictionary_file, 'wb') as file:
pickle.dump(self.root, file)
def insert_word(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def search_word(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end_of_word
def suggest_corrections(self, word):
suggestions = []
self._suggest_corrections(self.root, word, "", suggestions)
return suggestions
def _suggest_corrections(self, node, remaining, current, suggestions):
if node.is_end_of_word:
suggestions.append(current)
for char, child_node in node.children.items():
self._suggest_corrections(child_node, remaining, current + char, suggestions)
def modify_dictionary(self, word, add=True):
if add:
self.insert_word(word)
else:
# Remove word from the dictionary
self._remove_word(self.root, word, 0)
def _remove_word(self, node, word, index):
if index == len(word):
node.is_end_of_word = False
return len(node.children) == 0
char = word[index]
child_node = node.children[char]
if self._remove_word(child_node, word, index + 1):
del node.children[char]
return len(node.children) == 0
if __name__ == "__main__":
spell_checker = SpellChecker()
while True:
user_input = input("Enter a potentially misspelled word (q to quit): ")
if user_input.lower() == 'q':
break
if spell_checker.search_word(user_input):
print("The word is spelled correctly.")
else:
suggestions = spell_checker.suggest_corrections(user_input)
print("Suggestions:", suggestions)
modify_dict = input("Do you want to add this word to the dictionary? (y/n): ").lower()
if modify_dict == 'y':
spell_checker.modify_dictionary(user_input)
spell_checker.save_dictionary()
print("Word added to the dictionary.")
elif modify_dict == 'n':
print("Word not added to the dictionary.")
else:
print("Invalid input. Word not added to the dictionary.") |
import os
import logging
import zipfile
from bs4 import BeautifulSoup
from config import local_directory
from config import extracted_path
from config import expected_inn
from custom_logger import LoggerConfig
class FileProcessor:
def __init__(self, zip_path=None):
# Конструктор класса, принимает логгер для записи сообщений
# Конфигурация логгера для ведения журнала событий
# self.zip_path = local_directory
self.zip_path = zip_path
self.extracted_path = extracted_path
self.expected_inn = expected_inn
self.expected_inn = expected_inn # Инициализация expected_inn здесь
self.extracted_path = extracted_path
self.logger = logging.getLogger(__name__) # Получение логгера для текущего модуля
LoggerConfig.configure_logger(self.logger) # Настройка логгера согласно конфигурации
# В вашем методе process_file
def process_file(self, *args):
# zip_path - путь к ZIP-архиву, который нужно распаковать
# extracted_path - директория, куда будет распакован содержимое архива
# expected_inn - ожидаемое значение INN для проверки в XML файле
# Открытие и распаковка ZIP-архива в указанную директорию
with zipfile.ZipFile(self.zip_path, 'r') as zip_ref:
zip_ref.extractall(self.extracted_path)
# Поиск XML файла в распакованной директории
xml_file = next((f for f in os.listdir(self.extracted_path) if f.endswith('.xml')), None)
if xml_file:
# Если XML файл найден, формируем полный путь к файлу
xml_path = os.path.join(self.extracted_path, xml_file)
# Переменная для хранения результата проверки условия
condition_met = False
# Открытие XML файла и его чтение с использованием BeautifulSoup для парсинга
with open(xml_path, 'r', encoding='utf-8') as file:
soup = BeautifulSoup(file, 'xml')
# Вызов функции condition_check для проверки соответствия содержимого XML файла ожидаемому значению INN
condition_met = self.condition_check(soup, self.expected_inn)
# Файл xml_path теперь закрыт, так как мы вышли из блока with
if condition_met:
# Если условие выполнено, удаляем ZIP-архив
os.remove(self.zip_path)
self.logger.info(f'Archive deleted: {self.zip_path}')
else:
# Если условие не выполнено, удаляем распакованный XML файл и ZIP-архив
os.remove(xml_path)
os.remove(self.zip_path)
self.logger.info(f'\nXML file deleted: {xml_path}\nArchive deleted: {self.zip_path}')
else:
# Если XML файл не найден, записываем ошибку в лог
self.logger.error(f'No XML file found in the archive: {self.zip_path}')
def condition_check(self, soup):
# Находим тег <inn> в документе XML
inn_tag = soup.find('inn')
# Проверяем, существует ли тег и равно ли его содержимое (как строка) ожидаемому значению (также как строка)
return inn_tag is not None and inn_tag.text == str(self.expected_inn)
# Определение локальной директории для сохранения скачанных файлов
# zip_path = local_directory
# Создание экземпляра класса и вызов метода process_file
my_instance = FileProcessor()
my_instance.process_file()
# Определение локальной директории для сохранения скачанных файлов
# local_directory = r'C:\Users\wangr\OneDrive\Документы\тест'
# def condition_check(soup, expected_inns):
# # Находим тег <inn> в документе XML
# inn_tag = soup.find('inn')
# # Проверяем, существует ли тег и содержится ли его содержимое в списке ожидаемых значений INN
# return inn_tag is not None and inn_tag.text in map(str, expected_inns) |
// Package imports
import React from 'react';
import { useParams } from 'react-router-dom';
import { useQuery } from 'react-query';
// Local imports
import { getEvent } from '../services/index';
import { Container, Spinner } from 'react-bootstrap';
import RecipeContainer from './RecipeContainer';
import IQuery from '../interfaces/Query.interface';
import { IEvent } from '../interfaces/Events.interface';
export default function EventDetails () {
const { id } = useParams();
const { data: event, status }: IQuery<IEvent> = useQuery(
'event',
() => getEvent(id!),
{ enabled: !!id }
);
// Loading handling
if (status === 'loading') return <Spinner animation='border' />;
return (
<>
{event &&
<Container>
<h1 className='bg-warning rounded'>
{event.type} With {
event.members.map((member, i) =>
i === event.members.length - 1
? member
: `${member}, `
)
}
</h1>
<h2>When: </h2>
<h3>{event.date.slice(0, 10)} at {event.date.slice(11)}</h3>
<h2>Menu:</h2>
{event.menu.length > 0 && <RecipeContainer recipes={event.menu} />}
</Container>
}
</>
);
} |
## AUTHOR: Aaron Nicolson
## AFFILIATION: Signal Processing Laboratory, Griffith University.
##
## This Source Code Form is subject to the terms of the Mozilla Public
## License, v. 2.0. If a copy of the MPL was not distributed with this
## file, You can obtain one at http://mozilla.org/MPL/2.0/.
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Activation, Add, Dense, \
LayerNormalization, LSTM, Masking, ReLU, TimeDistributed
import numpy as np
class ResLSTM:
"""
Residual long short-term memory network. Frame-wise layer normalisation is
used.
"""
def __init__(
self,
inp,
n_outp,
n_blocks,
d_model,
sigmoid_outp,
unroll=False,
):
"""
Argument/s:
inp - input placeholder.
n_outp - number of output nodes.
n_blocks - number of residual blocks.
d_model - model size.
unroll - unroll recurrent state (can't be used as sequence length
changes).
sigmoid_outp - use a sigmoid output activation.
"""
self.n_outp = n_outp
self.d_model = d_model
self.unroll = unroll
seq_mask = Masking(mask_value=0.0).compute_mask(inp)
x = self.feedforward(inp)
for _ in range(n_blocks): x = self.block(x, seq_mask)
self.outp = Dense(self.n_outp)(x)
if sigmoid_outp: self.outp = Activation('sigmoid')(self.outp)
def block(self, inp, seq_mask):
"""
Residual LSTM block.
Argument/s:
inp - input placeholder.
seq_mask - sequence mask.
Returns:
residual - output of block.
"""
lstm = LSTM(self.d_model, unroll=self.unroll)(inp, mask=seq_mask)
residual = Add()([inp, lstm])
return residual
def feedforward(self, inp):
"""
Feedforward layer.
Argument/s:
inp - input placeholder.
Returns:
act - output of feedforward layer.
"""
ff = Dense(self.d_model, use_bias=False)(inp)
norm = LayerNormalization(axis=2, epsilon=1e-6)(ff)
act = ReLU()(norm)
return act |
from django.db import models
from ckeditor.fields import RichTextField
from core.catalog.models import Sofa
class Question(models.Model):
"""
Description of Questions Model of Service App
"""
question = models.CharField(verbose_name='Вопрос', max_length=500)
answer = RichTextField(verbose_name='Ответ', config_name='default')
order = models.PositiveIntegerField(default=0, editable=False, db_index=True, verbose_name="Порядок")
def __str__(self):
return self.question
class Meta:
verbose_name = 'вопрос'
verbose_name_plural = 'Часто задаваемые вопросы'
ordering = ['order', ]
class Review(models.Model):
"""
Description of Reviews Model of Service App
"""
author = models.CharField(verbose_name='Имя автора', max_length=500)
review = RichTextField(verbose_name='Отзыв', config_name='default')
order = models.PositiveIntegerField(default=0, db_index=True, verbose_name="Порядок")
sofa = models.ForeignKey(Sofa, on_delete=models.SET_NULL, null=True, blank=True, related_name='reviews', verbose_name="Диван")
author_photo = models.FileField(verbose_name='Фото автора', upload_to='core/service/reviews/', max_length=500, blank=True)
published = models.BooleanField(verbose_name='Опубликовано', default=True)
def __str__(self):
return self.author
class Meta:
verbose_name = 'отзыв'
verbose_name_plural = 'Отзывы'
ordering = ['order', ]
class ReviewPhoto(models.Model):
"""
Description of ReviewsPhoto Model of Service App
"""
field = models.ForeignKey(Review, related_name='photos', on_delete=models.CASCADE)
photo = models.FileField(verbose_name='Фото', upload_to='core/service/reviews/', max_length=500)
order = models.PositiveIntegerField(default=0, db_index=True, verbose_name="Порядок")
def __str__(self):
return self.field.author
class Meta:
verbose_name = 'Фото отзыва'
verbose_name_plural = 'Фото отзывов'
ordering = ['order', ]
class PopularModel(models.Model):
"""
Description of PopularModel Model of Service App
"""
order = models.PositiveIntegerField(default=0, db_index=True, verbose_name="Порядок")
sofa = models.ForeignKey(Sofa, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Диван")
def __str__(self):
return self.sofa.name
class Meta:
verbose_name = 'популярная модель'
verbose_name_plural = 'Популярные модели'
ordering = ['order', ]
class Order(models.Model):
"""
Description of Order Model of Service App
"""
name = models.CharField(verbose_name='Имя', max_length=250)
number = models.CharField(verbose_name='Номер телефона', max_length=40)
message = models.TextField(verbose_name='Какая мебель нужна?', blank=True)
project_version = models.CharField(verbose_name='Версия приложения', blank=True, max_length=10)
created = models.DateTimeField(verbose_name='Создано', auto_now_add=True)
user_agent = models.CharField(verbose_name='UserAgent', blank=True, max_length=2000)
screen_resolution = models.CharField(verbose_name='Разрешение экрана', blank=True, max_length=100)
browser_language = models.CharField(verbose_name='Язык браузера', blank=True, max_length=100)
timezone = models.CharField(verbose_name='Временная зона', blank=True, max_length=100)
cookie = models.TextField(verbose_name='Cookie', blank=True, max_length=5000)
def __str__(self):
return f'{self.name} - {self.message} - {self.created}'
class Meta:
verbose_name = 'заявка с сайта'
verbose_name_plural = 'Заявки с сайта' |
import '../styles/CatProfile.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import '@fortawesome/fontawesome-free/css/all.min.css';
import {useParams} from 'react-router-dom';
import {Carousel} from 'react-responsive-carousel';
import 'react-responsive-carousel/lib/styles/carousel.min.css';
import {useState, useEffect} from 'react';
import {useAuth} from "../AuthContext";
import CatsProfilePopup from "../components/CatsProfilePopup";
import {loadCatImage} from '../utils/ImageLoader';
const CatProfile = ({showHeartButton}) => {
const {isLoggedIn, user} = useAuth();
const {catId} = useParams();
const [cat, setCat] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [favorites, setFavorites] = useState(new Set());
const [heartClicked, setHeartClicked] = useState(false);
const [showLoginPrompt, setShowLoginPrompt] = useState(false);
useEffect(() => {
const fetchCatData = async () => {
try {
const catResponse = await fetch(`http://localhost:8080/readCat?id=${catId}`);
if (!catResponse.ok) {
throw new Error(`Network response was not ok: ${catResponse.statusText}`);
}
const catData = await catResponse.json();
setCat(catData);
setLoading(false);
} catch (error) {
console.error('Error fetching data:', error);
setError(error.message);
setLoading(false);
}
};
fetchCatData();
}, [catId]);
useEffect(() => {
const fetchFavorites = async (secretKey) => {
try {
const response = await fetch(`http://localhost:8080/user/favorites?secretKey=${secretKey}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const favoriteCatIds = new Set(data.map(cat => cat.id));
setFavorites(favoriteCatIds);
setHeartClicked(favoriteCatIds.has(Number(catId))); // Set initial heartClicked state
console.log('Favorite cat IDs:', favoriteCatIds); // Debugging line
console.log('Current cat ID:', catId); // Debugging line
console.log('Is current cat in favorites:', favoriteCatIds.has(Number(catId))); // Debugging line
} catch (error) {
console.error('Error fetching favorite cats:', error);
}
};
if (isLoggedIn && user && user.secretKey) {
fetchFavorites(user.secretKey);
}
}, [isLoggedIn, user, catId]);
const handleHeartClick = async (e) => {
e.preventDefault();
e.stopPropagation();
if (isLoggedIn && user) {
const isFavorite = favorites.has(Number(catId));
const url = new URL(isFavorite ? "http://localhost:8080/user/removeFavorite" : "http://localhost:8080/user/addFavorite");
url.searchParams.append("secretKey", user.secretKey);
url.searchParams.append("catId", catId);
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
setFavorites(prev => {
const updatedFavorites = new Set(prev);
if (isFavorite) {
updatedFavorites.delete(Number(catId));
} else {
updatedFavorites.add(Number(catId));
}
return updatedFavorites;
});
setHeartClicked(!isFavorite);
} else {
console.error(`Failed to ${isFavorite ? 'remove' : 'add'} favorite`);
}
} catch (error) {
console.error(`Error ${isFavorite ? 'removing' : 'adding'} favorite:`, error);
}
} else {
setShowLoginPrompt(true);
}
};
const formatText = (text) => {
return text.toLowerCase().replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase());
};
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
if (!cat) {
return <div>No cat found</div>;
}
return (
<div className="container-fluid full-width-container mt-3">
<div className="row">
<div className="col-md-12">
<div className="cat-name-box">
<div className="box-name-text">
<row>
{cat.name}
{showHeartButton && (
<button
type="button"
className="profile-heart-button"
style={{color: heartClicked ? 'black' : 'white', zIndex: 1}}
onClick={handleHeartClick}
>
<i className={heartClicked ? 'fas fa-heart' : 'far fa-heart'}></i>
</button>
)}
</row>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-md-12">
<div className="row">
<div className="col-md-12">
<div className="image-slider-box">
<Carousel
showThumbs={false}
showIndicators={true}
infiniteLoop={true}
swipeable={true}
>
{cat.imageNames.map((image, index) => {
const imagePath = loadCatImage(image);
console.log(`Loading image: ${image}, Path: ${imagePath}`);
return (
imagePath && (
<div key={index}>
<img src={imagePath} alt={`Slide ${index + 1}`}
style={{height: '310px', width: 'auto'}}/>
</div>
)
);
})}
</Carousel>
</div>
</div>
</div>
</div>
</div>
<div className="container-fluid full-width-container mt-3">
<div className="row">
<div className="col-md-12">
<div className="about-box">
<h5 className="box-title">About</h5>
<p className="box-text">{cat.about}</p>
</div>
</div>
</div>
<div className="container-fluid full-width-container mt-3">
<div className="row">
<div className="col-md-6">
<div className="smaller-box">
<h5 className="box-title">Characteristics</h5>
<p className="box-text">Gender: {formatText(cat.gender)}</p>
<p className="box-text">Breed: {cat.breed.split('_').map(word => word.charAt(0) + word.slice(1).toLowerCase()).join(' ')}</p>
<p className="box-text">Age: {cat.age}</p>
<p className="box-text">Indoor Cat: {cat.isIndoorCat ? 'Yes' : 'No'}</p>
<p className="box-text">Color: {formatText(cat.color)}</p>
<p className="box-text">Size: {formatText(cat.size)}</p>
<p className="box-text">Coat Length: {formatText(cat.coatLength)}</p>
<p className="box-text">Can live with: {formatText(cat.canLiveWith)}</p>
<p className="box-text">Disease: {cat.disease ? formatText(cat.disease) : 'None'}</p>
</div>
</div>
<div className="col-md-6">
<div className="smaller-box">
<h5 className="box-title">Shelter</h5>
{cat.shelter && (
<>
<p className="box-text">Name: {cat.shelter.name}</p>
<p className="box-text">Region: {formatText(cat.shelter.region)}</p>
<p className="box-text">Address: {cat.shelter.address}</p>
<p className="box-text">
Website: <a href={cat.shelter.website} target="_blank"
rel="noopener noreferrer">{cat.shelter.website}</a>
</p>
<p className="box-text">E-mail: {cat.shelter.email}</p>
<p className="box-text">Phone: {cat.shelter.phone}</p>
</>
)}
</div>
</div>
</div>
</div>
</div>
<CatsProfilePopup showLoginPrompt={showLoginPrompt} setShowLoginPrompt={setShowLoginPrompt}/>
</div>
);
}
export default CatProfile; |
package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategorySercive;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author whx
* @create 2022-07-21 14:46
*/
@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {
@Autowired
private SetmealDishService setmealDishService;
@Autowired
private SetmealService setmealService;
@Autowired
private CategorySercive categorySercive;
@PostMapping
public R<String> save(@RequestBody SetmealDto setmealDto){
log.info("套餐信息:{}",setmealDto);
setmealService.saveWithDish(setmealDto);
return R.success("新增套餐成功");
}
/**
* 套餐分页查询
* @param page
* @param pageSize
* @param name
* @return
*/
@GetMapping("/page")
public R<Page> page(int page, int pageSize, String name){
//分页构造器对象
Page<Setmeal> pageInfo = new Page<>(page,pageSize);
Page<SetmealDto> dtoPage = new Page<>();
LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
//添加查询条件,根据name进行like模糊查询
queryWrapper.like(name != null,Setmeal::getName,name);
//添加排序条件,根据更新时间降序排列
queryWrapper.orderByDesc(Setmeal::getUpdateTime);
setmealService.page(pageInfo,queryWrapper);
//对象拷贝
BeanUtils.copyProperties(pageInfo,dtoPage,"records");
List<Setmeal> records = pageInfo.getRecords();
List<SetmealDto> list = records.stream().map((item) -> {
SetmealDto setmealDto = new SetmealDto();
//对象拷贝
BeanUtils.copyProperties(item,setmealDto);
//分类id
Long categoryId = item.getCategoryId();
//根据分类id查询分类对象
Category category = categorySercive.getById(categoryId);
if(category != null){
//分类名称
String categoryName = category.getName();
setmealDto.setCategoryName(categoryName);
}
return setmealDto;
}).collect(Collectors.toList());
dtoPage.setRecords(list);
return R.success(dtoPage);
}
/**
* 删除套餐
* @param ids
* @return
*/
@DeleteMapping
public R<String> delete(@RequestParam List<Long> ids){
log.info("ids:{}",ids);
setmealService.removeWithDish(ids);
return R.success("套餐数据删除成功");
}
@GetMapping("/list")
public R<List<Setmeal>> list(Setmeal setmeal) {
log.info("setmeal:{}", setmeal);
//条件构造器
LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(StringUtils.isNotEmpty(setmeal.getName()), Setmeal::getName, setmeal.getName());
queryWrapper.eq(setmeal.getCategoryId()!=null, Setmeal::getCategoryId, setmeal.getCategoryId());
queryWrapper.eq(setmeal.getStatus()!=null, Setmeal::getStatus, setmeal.getStatus());
queryWrapper.orderByDesc(Setmeal::getUpdateTime);
return R.success(setmealService.list(queryWrapper));
}
/**
* 根据ids批量起售禁售套餐
* @param status
* @param ids
* @return
*/
@PostMapping("status/{status}")
public R<String> stopSale(@PathVariable int status,@RequestParam List<Long> ids){
setmealService.updateSale(status,ids);
return R.success("成功禁售套餐");
}
/**
* 根据查看套餐分类信息
* @param id
* @return
*/
@GetMapping("/{id}")
public R<SetmealDto> update(@PathVariable Long id){
SetmealDto setmealDto = setmealService.getByIdWithDish(id);
return R.success(setmealDto);
}
/**
* 修改套餐
* @param
* @return
*/
@PutMapping
public R<String> update(@RequestBody SetmealDto setmealDto){
setmealService.updateWithdish(setmealDto);
return R.success("修改套餐成功");
}
} |
// import 'dart:async';
//
// import 'package:validators/validators.dart';
//
// import 'constants.dart';
//
// ///validators for stream
// /// if the validation satisfy then data will be added in stream else add error in stream
//
// mixin Validators {
// var emailValidator =
// StreamTransformer<String, String>.fromHandlers(handleData: (email, sink) {
// if (isEmail(email)) {
// sink.add(email);
// } else {
// sink.addError(Constants.EMAIL_NOT_VALID);
// }
// });
//
// var usernameValidator = StreamTransformer<String, String>.fromHandlers(
// handleData: (username, sink) {
// if (username.length > 0) {
// sink.add(username);
// } else {
// sink.addError(Constants.USERNAME_NOT_VALID);
// }
// });
//
// var passwordValidator = StreamTransformer<String, String>.fromHandlers(
// handleData: (password, sink) {
// if (password.length >= 6) {
// sink.add(password);
// } else {
// sink.addError(Constants.PASSWORD_LENGTH);
// }
// });
//
// var mobileValidator = StreamTransformer<String, String>.fromHandlers(
// handleData: (mobile, sink) {
// if (isInt(mobile)) {
// if (mobile.length == 10) {
// sink.add(mobile);
// } else {
// sink.addError(Constants.INVALID_MOBILE_NUM);
// }
// }
// });
//
// var nameValidator =
// StreamTransformer<String, String>.fromHandlers(handleData: (name, sink) {
// if (name.isNotEmpty) {
// sink.add(name);
// } else {
// sink.addError(Constants.INVALID_NAME);
// }
// });
// } |
// import axie from "../tile.jpeg";
import { Link } from "react-router-dom";
import { useState } from "react";
// import { GetIpfsUrlFromPinata } from "../utils"
import {
Button,
Dialog,
Card,
CardBody,
CardFooter,
Typography,
Input,
Checkbox,
} from "@material-tailwind/react";
import MarketplaceJSON from "../Marketplace.json";
function NFTTile(data) {
const newTo = {
pathname: "/nftPage/" + data.data.tokenId,
};
const ethers = require("ethers");
const [open, setOpen] = useState(false);
const handleOpen = () => setOpen((cur) => !cur);
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
//Pull the deployed contract instance
let contract = new ethers.Contract(
MarketplaceJSON.address,
MarketplaceJSON.abi,
signer,
);
return (
<Card className="mt-6 w-96">
<CardBody className="items-center">
<Typography variant="h5" color="blue-gray" className="mb-2">
{data.data.tokenId}
</Typography>
<Typography>{data.data.address}</Typography>
<Typography>{data.data.mandal}</Typography>
<Typography>{data.data.district}</Typography>
<Typography>{data.data.wardno}</Typography>
<Typography>{data.data.blockno}</Typography>
<Typography>{data.data.price} ETH</Typography>
</CardBody>
<Link to={newTo}>
<CardFooter className="pt-0">
<Button color="purple">Read More</Button>
</CardFooter>
</Link>
<Button onClick={handleOpen}>Read More</Button>
<Dialog
size="lg"
open={open}
handler={handleOpen}
className="bg-transparent shadow-none"
>
<Card className="mx-auto w-full max-w-[24rem]">
<CardBody className="flex flex-col gap-4">
<Typography variant="h3" color="blue-gray">
Token ID : {data.data.tokenId}
</Typography>
<Typography variant="lead">
Address : {data.data.address}
</Typography>
<Typography variant="lead">Mandal : {data.data.mandal}</Typography>
<Typography variant="lead">
District : {data.data.district}
</Typography>
<Typography variant="lead">Ward No. : {data.data.wardno}</Typography>
<Typography variant="lead">
Block No. : {data.data.blockno}
</Typography>
<Typography variant="lead" className="truncate">
Owner : {data.data.owner}
</Typography>
<Typography variant="lead" className="truncate">
Seller : {data.data.seller}
</Typography>
<Typography variant="h3">Price : {data.data.price} ETH</Typography>
</CardBody>
<CardFooter className="pt-0">
<Button
variant="gradient"
onClick={handleOpen}
>
List NFT
</Button>
</CardFooter>
</Card>
</Dialog>
</Card>
);
}
export default NFTTile; |
import { useState, useEffect } from "react"
import { Grid } from "@mui/material"
import Deck from "./deck/PlainDeck"
import PlayerCardData from "./cardData/PlayerCardData"
import ComputerCardData from "./cardData/ComputerCardData"
import DeckCardData from "./cardData/DeckCardData"
let playerDeck, computerDeck, playerCard, computerCard
function StartGame() {
const deck = new Deck()
deck.shuffle()
const deckMidpoint = Math.ceil(deck.numberOfCards / 2)
playerDeck = new Deck(deck.cards.slice(0, deckMidpoint))
computerDeck = new Deck(deck.cards.slice(deckMidpoint, deck.numberOfCards))
playerCard = playerDeck.pop()
computerCard = computerDeck.pop()
}
StartGame()
export default function SetTwo() {
const [topcard, setTopcard] = useState(() => {
return true
})
const [nextdeck, setNextdeck] = useState(() => {
return true
})
useEffect(() => {
playerCard = playerDeck.pop()
computerCard = computerDeck.pop()
if (playerDeck.numberOfCards === 0) {
StartGame()
setNextdeck(!nextdeck)
}
}, [topcard, nextdeck])
const flipCards = () => setTopcard(!topcard)
// Card size
let cardsize = {
radius: "14px",
cardWidthL: "70%",
cardWidthPsm: "32%",
cardWidthP: "40%",
cardWidthPmd: "26%",
}
return (
<>
<Grid
container
sx={{
"@media (orientation: portrait)": {
display: "grid",
// gridTemplateColumns: "1fr",
gridTemplate: "repeat(3, 1fr) / 1fr",
gap: 3,
},
"@media (orientation: landscape)": {
display: "grid",
gridTemplate: "1fr / repeat(3, 1fr)",
gap: 5,
px: 5,
},
}}
>
<Grid
item
sx={{ perspective: "1000px", transformStyle: "preserve-3d" }}
>
{topcard && (
<PlayerCardData
playerCard={playerCard}
nextdeck={nextdeck}
{...cardsize}
/>
)}
{!topcard && (
<PlayerCardData
playerCard={playerCard}
nextdeck={nextdeck}
{...cardsize}
/>
)}
</Grid>
<Grid item sx={{ perspective: "1000px" }}>
<DeckCardData
flipCards={flipCards}
nextdeck={nextdeck}
{...cardsize}
/>
</Grid>
<Grid
item
sx={{ perspective: "1000px", transformStyle: "preserve-3d" }}
>
{topcard && (
<ComputerCardData
computerCard={computerCard}
nextdeck={nextdeck}
{...cardsize}
/>
)}
{!topcard && (
<ComputerCardData
computerCard={computerCard}
nextdeck={nextdeck}
{...cardsize}
/>
)}
</Grid>
</Grid>
</>
)
} |
---
API: 2.1
OpenSesame: 3.3.12
Platform: nt
---
set width 1024
set uniform_coordinates yes
set title "Visual search"
set subject_parity even
set subject_nr 0
set start experiment
set sound_sample_size -16
set sound_freq 48000
set sound_channels 2
set sound_buf_size 1024
set sampler_backend psycho
set round_decimals 2
set mouse_backend psycho
set keyboard_backend psycho
set height 768
set fullscreen no
set form_clicks no
set foreground white
set font_underline no
set font_size 18
set font_italic no
set font_family mono
set font_bold no
set experiment_path "C:\\Users\\Gebruiker\\Documents\\Teaching_AY2223_S2\\Experimentation\\OpenSesame_Exercises\\s8_visual_search"
set disable_garbage_collection yes
set description "A template containing a practice and an experimental phase"
set coordinates uniform
set compensation 0
set color_backend psycho
set clock_backend psycho
set canvas_backend psycho
set bidi yes
set background black
define loop block_loop
set source_file ""
set source table
set skip 0
set repeat 1
set order random
set offset no
set item trial_sequence
set description "A single block of trials"
set cycles 18
set continuous no
set column_order ""
set break_if_on_first yes
set break_if never
setcycle 0 condition conjunction
setcycle 0 set_size 1
setcycle 0 target_present present
setcycle 1 condition feature_shape
setcycle 1 set_size 1
setcycle 1 target_present present
setcycle 2 condition feature_color
setcycle 2 set_size 1
setcycle 2 target_present present
setcycle 3 condition conjunction
setcycle 3 set_size 5
setcycle 3 target_present present
setcycle 4 condition feature_shape
setcycle 4 set_size 5
setcycle 4 target_present present
setcycle 5 condition feature_color
setcycle 5 set_size 5
setcycle 5 target_present present
setcycle 6 condition conjunction
setcycle 6 set_size 15
setcycle 6 target_present present
setcycle 7 condition feature_shape
setcycle 7 set_size 15
setcycle 7 target_present present
setcycle 8 condition feature_color
setcycle 8 set_size 15
setcycle 8 target_present present
setcycle 9 condition conjunction
setcycle 9 set_size 1
setcycle 9 target_present absent
setcycle 10 condition feature_shape
setcycle 10 set_size 1
setcycle 10 target_present absent
setcycle 11 condition feature_color
setcycle 11 set_size 1
setcycle 11 target_present absent
setcycle 12 condition conjunction
setcycle 12 set_size 5
setcycle 12 target_present absent
setcycle 13 condition feature_shape
setcycle 13 set_size 5
setcycle 13 target_present absent
setcycle 14 condition feature_color
setcycle 14 set_size 5
setcycle 14 target_present absent
setcycle 15 condition conjunction
setcycle 15 set_size 15
setcycle 15 target_present absent
setcycle 16 condition feature_shape
setcycle 16 set_size 15
setcycle 16 target_present absent
setcycle 17 condition feature_color
setcycle 17 set_size 15
setcycle 17 target_present absent
run trial_sequence
define sequence block_sequence
set flush_keyboard yes
set description "A sequence containing a single block of trials followed by feedback to the participant"
run instructions always
run reset_feedback always
run block_loop always
run feedback always
define inline_script correct_response_script
set description "Executes Python code"
set _run ""
___prepare__
if var.target_present == 'present':
var.correct_response = 'right'
elif var.target_present == 'absent':
var.correct_response = 'left'
else:
raise Exception('target_present should be absent or present, not %s' % var.target)
__end__
define sketchpad end_of_experiment
set start_response_interval no
set duration keypress
set description "A sketchpad notifying the participant that the experiment is finished"
draw textline center=1 color=white font_bold=no font_family=mono font_italic=no font_size=18 html=yes show_if=always text="Press any key to exit" x=0 y=0 z_index=0
define sequence experiment
set flush_keyboard yes
set description "The main sequence of the experiment"
run experimental_loop always
run end_of_experiment always
define loop experimental_loop
set source_file ""
set source table
set skip 0
set repeat 1
set order random
set offset no
set item block_sequence
set description "A loop containing one or more experimental blocks"
set cycles 4
set continuous no
set column_order practice
set break_if_on_first yes
set break_if never
setcycle 0 target_shape square
setcycle 0 target_color yellow
setcycle 1 target_shape circle
setcycle 1 target_color yellow
setcycle 2 target_shape square
setcycle 2 target_color blue
setcycle 3 target_shape circle
setcycle 3 target_color blue
run block_sequence
define feedback feedback
set reset_variables yes
set duration keypress
set description "Provides feedback to the participant"
draw textline center=1 color=white font_bold=no font_family=mono font_italic=no font_size=18 html=yes show_if=always text="Your average response time was [avg_rt]ms<br /><br />Your accuracy was [acc]%<br /><br />Press any key to continue" x=0 y=0 z_index=0
define sketchpad fixation_dot
set start_response_interval no
set duration 500
set description "Displays stimuli"
draw fixdot color=white show_if=always style=default x=0 y=0 z_index=0
define sketchpad green_dot
set duration 500
set description "Displays stimuli"
draw fixdot color=green show_if=always style=default x=0 y=0 z_index=0
define sketchpad instructions
set start_response_interval no
set duration keypress
set description "A sketchpad containing the instructions for the participant"
draw textline center=1 color=white font_bold=no font_family=mono font_italic=no font_size=18 html=yes show_if=always text="INSTRUCTIONS<br /><br />Search for the [target_color] [target_shape]" x=-32 y=-160 z_index=0
draw textline center=1 color=white font_bold=no font_family=mono font_italic=no font_size=18 html=yes show_if=always text="Press the right-arrow key if you find it<br />Press the left-arrow key if you don't<br /><br />Press any key to begin" x=0 y=160 z_index=0
draw rect color="[target_color]" fill=1 h=120 penwidth=1 show_if="[target_shape] = square" w=120 x=-64.0 y=-64.0 z_index=0
draw circle color="[target_color]" fill=1 penwidth=1 r=60 show_if="[target_shape] = circle" x=0.0 y=0.0 z_index=0
define keyboard_response keyboard_response
set timeout infinite
set flush yes
set event_type keypress
set duration keypress
set description "Collects keyboard responses"
define logger logger
set description "Logs experimental data"
set auto_log yes
define sketchpad red_dot
set duration 500
set description "Displays stimuli"
draw fixdot color=red show_if=always style=default x=0 y=0 z_index=0
define reset_feedback reset_feedback
set description "Resets the feedback variables, such as 'avg_rt' and 'acc'"
define inline_script search_display_script
set description "Executes Python code"
set _run "c.show()"
___prepare__
import random
def draw_shape(c, x, y, color, shape):
"""
Draws a single shape.
Arguments:
c: A Canvas.
x: An x coordinate.
y: A y coordinate.
color: A color (yellow or blue)
shape: A shape (square or circle)
"""
if shape == 'square':
c += Rect(x=x-25, y=y-25, w=50, h=50, color=color, fill=True)
elif shape == 'circle':
c += Circle(x=x, y=y, r=25, color=color, fill=True)
else:
raise Exception('Invalid shape: %s' % shape)
if color not in ['yellow', 'blue']:
raise Exception('Invalid color: %s' % color)
def draw_feature_color_distractor(c, x, y):
"""
Draws a single distractor in the feature-color condition: an object that
has a different color from the target, but can have any shape.
Arguments:
c: A Canvas.
x: An x coordinate.
y: A y coordinate.
"""
shapes = ['circle', 'square']
shape = random.choice(shapes)
if var.target_color == 'yellow':
color = 'blue'
elif var.target_color == 'blue':
color = 'yellow'
else:
raise Exception('Invalid target_color: %s' % var.target_color)
draw_shape(c, x, y, color=color, shape=shape)
def draw_feature_shape_distractor(c, x, y):
"""
Draws a single distractor in the feature-shape condition: an object that
has a different shape from the target, but can have any color.
Arguments:
c: A Canvas.
x: An x coordinate.
y: A y coordinate.
"""
colors = ['yellow', 'blue']
color = random.choice(colors)
if var.target_shape == 'circle':
shape = 'square'
elif var.target_shape == 'square':
shape = 'circle'
else:
raise Exception('Invalid target_shape: %s' % var.target_shape)
draw_shape(c, x, y, color=color, shape=shape)
def draw_conjunction_distractor(c, x, y):
"""
Draws a single distractor in the conjunction condition: an object that
can have any shape and color, but cannot be identical to the target.
arguments:
c: A Canvas.
x: An x coordinate.
y: A y coordinate.
"""
conjunctions = [
('yellow', 'circle'),
('blue', 'circle'),
('yellow', 'square'),
('blue', 'square'),
]
conjunctions.remove( (var.target_color, var.target_shape) )
color, shape = random.choice(conjunctions)
draw_shape(c, x, y, color=color, shape=shape)
def draw_distractor(c, x, y):
"""
Draws a single distractor.
Arguments:
c: A Canvas.
x: An x coordinate.
y: A y coordinate.
"""
if var.condition == 'conjunction':
draw_conjunction_distractor(c, x, y)
elif var.condition == 'feature_shape':
draw_feature_shape_distractor(c, x, y)
elif var.condition == 'feature_color':
draw_feature_color_distractor(c, x, y)
else:
raise Exception('Invalid condition: %s' % var.condition)
def draw_target(c, x, y):
"""
Draws the target.
arguments:
c: A Canvas.
x: An x coordinate.
y: A y coordinate.
"""
draw_shape(c, x, y, color=var.target_color, shape=var.target_shape)
def draw_canvas():
"""
Draws the search canvas.
Returns:
A Canvas.
"""
c = Canvas()
xy_list = xy_random(n=var.set_size, width=500, height=500, min_dist=75)
if var.target_present == 'present':
x, y = xy_list.pop()
draw_target(c, x, y)
elif var.target_present != 'absent':
raise Exception(
'Invalid value for target_present %s' % var.target_present)
for x, y in xy_list:
draw_distractor(c, x, y)
return c
c = draw_canvas()
__end__
define sequence trial_sequence
set flush_keyboard yes
set description "A single trial"
run correct_response_script always
run fixation_dot always
run search_display_script always
run keyboard_response always
run green_dot "[correct] = 1"
run red_dot "[correct] = 0"
run logger always |
import React, {useEffect} from 'react';
import {useDispatch, useSelector} from "react-redux";
import styles from './GroupsTrack.module.css'
import {addTrackTime} from "../../../store/groupSlice";
const GroupsTrack = ({className}) => {
const selector = useSelector(state => state.tasks)
const groups = useSelector(state => state.groups.groups)
const dispatch = useDispatch()
const tasks = selector.tasks
const complete = selector.completedTasks
const msToHms = require('ms-to-hms')
function filterArr() {
const allTask = [...tasks, ...complete]
let filterArr = allTask.filter(task => task.groupName)
return filterArr.map(task => ({track: task.trackTime, group: task.groupName.value, color: task.groupName.color}))
}
const calcTime = (arr) => {
const uniqueArr = [];
for (let i = 0; i<arr.length; i++) {
const group = uniqueArr.find(elem => elem.group == arr[i].group)
if(group) {
group.track += arr[i].track
} else {
uniqueArr.push(arr[i])
}
}
return uniqueArr
}
console.log(filterArr())
return (
<div className={className}>
<div className={styles.title}>Затраченное время на группы</div>
<div className={styles.allGroups}>
{
filterArr().length !=0 ? calcTime(filterArr()).map(group => group.group && (
<div className={styles.groups}>
<div style={{background: group.color}} className={styles.color}></div>
<div className={styles.name}>{group.group}</div>
<div className={styles.track}>{msToHms(group.track)}</div>
</div>
)) : <div className={styles.noGroups}>Пока у вас нет задач с группами</div>
}
</div>
</div>
);
};
export default GroupsTrack; |
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
use App\Models\ProductSku;
class OrderRequest extends Request
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'address_id' => [
'required',
Rule::exists('user_addresses', 'id')->where('user_id', $this->user()->id),
],
'items' => 'required|array',
'items.*.sku_id' => [
'required',
function ($attribute, $value, $fail) {
if (! $sku = ProductSku::find($value)) {
return $fail('该商品不存在');
}
if (! $sku->product->on_sale) {
return $fail('该商品已下架');
}
if ($sku->stock === 0) {
return $fail('该商品已售完');
}
// 获取当前索引
preg_match('/items\.(\d+)\.sku_id/', $attribute, $m);
$index = $m[1];
// 根据索引找到用户所提交的购买数量
$amount = $this->items[$index]['amount'];
if ($amount > $sku->stock) {
return $fail('该商品库存不足');
}
},
],
'items.*.amount' => 'required|integer|min:1',
];
}
public function attributes()
{
return [
'address_id' => '收货地址',
'items' => '购物车商品',
'items.*.amount' => '商品数量',
];
}
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.obrii.mit.dp2021.ahafonova;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet(name = "UserFormServlet", urlPatterns = {"/form"})
/**
*
* @author mahafonova
*/
public class UserFormServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet UserFormServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet UserFormServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("form.jsp").forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User user = new User(
request.getParameter("name"),
request.getParameter("gender"),
request.getParameterValues("language"),
request.getParameter("country")
);
request.setAttribute("user", user);
request.getRequestDispatcher("submited.jsp").forward(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
} |
import React from "react";
import { Product, FooterBanner, HeroBanner } from "../components";
import { client } from "../lib/client";
const Home = ({ products, bannerData }) => {
console.log(products);
return (
<div>
<HeroBanner heroBanner={bannerData.length && bannerData[0]} />
<div className="products-heading">
<h2>Best Seller Products</h2>
<p className="text-3xl font-bold underline">
Speaker there are many variations passages
</p>
</div>
<div className="products-container">
{products?.map((product) => (
<Product key={product._id} product={product} />
))}
</div>
<FooterBanner footerBanner={bannerData && bannerData[0]} />
</div>
);
};
export const getServerSideProps = async () => {
const query = '*[_type=="product"]';
const products = await client.fetch(query);
const bannerQuery = '*[_type=="banner"]';
const bannerData = await client.fetch(bannerQuery);
return {
props: { products, bannerData },
};
};
export default Home; |
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
// C17 = 3 (В усіх питальних реченнях заданого тексту знайти та надрукувати без
//повторень слова заданої довжини.)
public static void main(String[] args) {
Text text = new Text("This is test line. Wait, is it long long enough long? I guess yes!");
int num = 4;
System.out.println("Use predefined data?");
char ans = getAns();
if (ans == 'y') {
System.out.println("Entered text: \n" + text);
System.out.println("Words length to find: " + num);
System.out.println("Result:");
System.out.println(text.getDistinctWords(num));
} else {
System.out.println("Enter your text, then number of character. This program will retrieve words with given length from question sentences in text.");
System.out.println("Text: ");
text = new Text(getText());
System.out.println("Number: ");
num = getNum();
System.out.println(text.getDistinctWords(num));
}
}
private static char getAns() {
char ans = 0;
boolean validInput;
Scanner sc = new Scanner(System.in);
do {
validInput = true;
try {
System.out.print("Enter 'y' or 'n': ");
ans = sc.nextLine().charAt(0);
if (ans != 'y' && ans != 'n') {
System.out.println("Invalid input. Please enter 'y' or 'n'.");
validInput = false;
}
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Answer must not be empty");
validInput = false;
}
} while (!validInput);
return ans;
}
private static String getText() {
String ans;
boolean validInput;
Scanner sc = new Scanner(System.in);
do {
validInput = true;
ans = sc.nextLine();
if (ans == null || ans.isEmpty()) {
System.out.println("Invalid input. Please enter some text.");
validInput = false;
}
} while (!validInput);
return ans;
}
private static int getNum() {
int ans = 0;
boolean validInput;
Scanner sc = new Scanner(System.in);
do {
validInput = true;
try {
ans = sc.nextInt();
if (ans < 1) {
System.out.println("Too short. Please enter number that is equal or greater than 1.");
validInput = false;
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter number that is equal or greater than 1.");
validInput = false;
sc.nextLine();
}
} while (!validInput);
return ans;
}
} |
console.log("Estruturas Condicionais")
// Utiizando IF e else
var senha = 1234 ; // declaração - alterar aqui para teste
var usuario = "admin";// declaração - alterar aqui para teste
if (senha ===1234 && usuario ==="admin"){
console.log("Seja bem vindo " + usuario);
}
else {
console.log("Usuário ou Senha inválido");
}
// Novamente exemplo com IF e Else
var saldo = 1000
var saque = 1000
if(saque>saldo){
console.log("Saldo indisponível para saque");
}
else{
console.log("Operação realizada com sucesso! Aguarde a contagem das notas");
}
// Novamente exemplo com IF e Else
var saldo = 1000;
var saque = 10;
var bloqueada = true;
if(saque>saldo || bloqueada){ // utilizando condicional OU/OR bloqueada iniciou com TRUE não é necessário usar =
console.log("Saldo Indisponível para saque ou conta bloqueada");
}
else{
console.log("Operação realizada com sucesso! Aguarde a contagem das notas");
}
//Exemplo com ELSEIF
var opcao = 4;
if (opcao ===1){
console.log("Financeiro");
}
else if(opcao ===2){
console.log("Faturamento");
}
else if(opcao===3){
console.log("Comercial");
}
else{
throw new Error("Opção inválida"); // lançar novo erro - qdo o erro finaliza o programa/não trata
}
// Exemplo usando SWICH, CASE e BREAK
var opcao = 3;
switch(opcao){
case 1 :
console.log("Financiamentos")
break;
case 2 :
console.log("Agendamento");
break;
case 3 || 4:
console.log("Atendimento");
break;
default:
console.log("Opção inválida")
}
// Utilizando Ternário(somente utiliza qdo possue 2 opções)
var idade = 13
idade>=18 ? console.log("Olá usuário"): console.log("Você não pode acessar - Menor de 18 anos");
//Mesma questão, dentro de um console
var idade = 13
console.log(idade>=18 ?("Olá usuário"):("Você não pode acessar - Menor de 18 anos"));
// Mesma questão - em código limpo
function ValidaIdade(idade) {
if (idade>=18) return "Olá usuário"; // Como a primeira linha é falsa, passará para segunda
return "Você não pode acessar - Menor de 18 anos"// Depois de RETURN não é mais feito leitura do codigo, portanto valida...substitui um SENÃO / ELSE IF
}
console.log(ValidaIdade(13)); |
/**
* Small script to help profile expensive parts of the coverage planner.
*
* @author Charlie Street
*/
#include "coverage_plan/mod/imac.h"
#include "coverage_plan/mod/imac_belief_sampler.h"
#include "coverage_plan/util/seed.h"
#include <Eigen/Dense>
#include <chrono>
#include <iostream>
#include <memory>
#include <random>
#include <stdlib.h>
/**
* Time the map update code, as this is likely to be expensive.
*/
void profileMapUpdate() {
std::shared_ptr<IMac> imac{
std::make_shared<IMac>("../../data/prelim_exps/five_heavy")};
std::unique_ptr<IMacBeliefSampler> sampler{
std::make_unique<IMacBeliefSampler>()};
// Generate initial matrix from IMacExecutor
std::unique_ptr<IMacExecutor> exec{std::make_unique<IMacExecutor>(imac)};
Eigen::MatrixXi map{exec->restart()};
// Time the test
auto start{std::chrono::high_resolution_clock::now()};
for (int i{0}; i < 1000000; ++i) {
map = sampler->sampleFromBelief(imac->forwardStep(map.cast<double>()));
}
auto stop{std::chrono::high_resolution_clock::now()};
auto duration{
std::chrono::duration_cast<std::chrono::microseconds>(stop - start)};
std::cout << "Time elapsed: " << duration.count() << " microseconds\n";
}
/**
* Time the performance of different RNGs.
*/
void profileRNG() {
// Test 1: mt19937_64
std::mt19937_64 gen64{SeedHelpers::genRandomDeviceSeed()};
std::uniform_real_distribution<> dist64{0, 1};
auto start{std::chrono::high_resolution_clock::now()};
for (int i{0}; i < 1000000000; ++i) {
double num{dist64(gen64)};
}
auto stop{std::chrono::high_resolution_clock::now()};
auto duration{
std::chrono::duration_cast<std::chrono::microseconds>(stop - start)};
std::cout << "MT19937_64 - Time elapsed: " << duration.count()
<< " microseconds\n";
// Test 2: mt19937
std::mt19937 gen32{SeedHelpers::genRandomDeviceSeed()};
std::uniform_real_distribution<> dist32{0, 1};
start = std::chrono::high_resolution_clock::now();
for (int i{0}; i < 1000000000; ++i) {
double num{dist32(gen32)};
}
stop = std::chrono::high_resolution_clock::now();
duration =
std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "MT19937 - Time elapsed: " << duration.count()
<< " microseconds\n";
// Test 3: rand
srand(SeedHelpers::genRandomDeviceSeed());
start = std::chrono::high_resolution_clock::now();
for (int i{0}; i < 1000000000; ++i) {
int num{rand()};
}
stop = std::chrono::high_resolution_clock::now();
duration =
std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "rand - Time elapsed: " << duration.count() << " microseconds\n";
// Test 4: rand_r
unsigned int seed{SeedHelpers::genRandomDeviceSeed()};
start = std::chrono::high_resolution_clock::now();
for (int i{0}; i < 1000000000; ++i) {
seed = rand_r(&seed);
}
stop = std::chrono::high_resolution_clock::now();
duration =
std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "rand_r - Time elapsed: " << duration.count()
<< " microseconds\n";
// Test 5: linear_congruential_engine
std::linear_congruential_engine<std::uint_fast32_t, 48271, 0, 2147483647>
genLcg{SeedHelpers::genRandomDeviceSeed()};
std::uniform_real_distribution<> distLcg{0, 1};
start = std::chrono::high_resolution_clock::now();
for (int i{0}; i < 1000000000; ++i) {
double num{distLcg(genLcg)};
}
stop = std::chrono::high_resolution_clock::now();
duration =
std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "LCG - Time elapsed: " << duration.count() << " microseconds\n";
// Test 6: Subtract with carry
std::ranlux48 genSwc{SeedHelpers::genRandomDeviceSeed()};
std::uniform_real_distribution<> distSwc{0, 1};
start = std::chrono::high_resolution_clock::now();
for (int i{0}; i < 1000000000; ++i) {
double num{distSwc(genSwc)};
}
stop = std::chrono::high_resolution_clock::now();
duration =
std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "SWC - Time elapsed: " << duration.count() << " microseconds\n";
// NOTE: Beware, the compiler is doing some silly stuff here which makes the
// last two run in 0 microseconds. Its clearly removing the unused code
// The map update test where the generator in imac_executor.h is tested
// is a more accurate test
}
int main() { profileMapUpdate(); } |
import com.codeborne.selenide.*;
import com.codeborne.selenide.testng.SoftAsserts;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import java.io.FileNotFoundException;
import static com.codeborne.selenide.AssertionMode.SOFT;
import static com.codeborne.selenide.ClickOptions.usingDefaultMethod;
import static com.codeborne.selenide.CollectionCondition.texts;
import static com.codeborne.selenide.Condition.*;
import static com.codeborne.selenide.Configuration.*;
import static com.codeborne.selenide.Selectors.*;
import static com.codeborne.selenide.Selenide.*;
import static java.time.Duration.ofSeconds;
@Listeners({SoftAsserts.class})
public class SelenideTests {
public SelenideTests(){
Configuration.timeout=10000;
Configuration.browser = "chrome";
// ChromeOptions options = new ChromeOptions();
// options.addArguments("start-maximized");
Configuration.browserSize="1920x1080";
baseUrl="http://the-internet.herokuapp.com";
reportsFolder = "src/main/resources/Reports";
downloadsFolder="src/main/resources/images";
}
@Test
public void screenshot() {
open(baseUrl);
$(byText("sfgdhs")).shouldHave(visible).click();
// sleep(4000);
}
@Test
public void selniumVsSelenide() {
//selenium
// driver.get("https://www.lambdatest.com/selenium-playground/checkbox-demo");
// WebElement checkBox = driver.findElement(By.id("isAgeSelected"));
// checkBox.click();
// System.out.println("Clicked on the Checkbox");
//
// WebElement successMessage = driver.findElement(By.id("txtAge"));
// String expectedMessage = successMessage.getText();
// System.out.println(expectedMessage);
// driver.quit();
//selenide
open("https://www.lambdatest.com/selenium-playground/checkbox-demo");
$("#isAgeSelected").click();
SelenideElement successText = $("#txtAge");
successText.should(appear);
successText.shouldHave(exactText("Checked"));
successText.shouldHave(text("ked"));
//sleep(4000);
}
@Test
public void selectors() {
open("https://www.lambdatest.com/selenium-playground/checkbox-demo");
$("#isAgeSelected").click();
$(byText("Checked")).shouldBe(appear);
$(withText("cked")).should(appear);
sleep(4000);
}
@Test
public void className() {
open("https://demo.guru99.com/test/selenium-xpath.html");
$(".thick-heading").shouldHave(exactText("Tutorials Library"));
$(by("title", "SQL")).shouldBe(visible);
SelenideElement agile = $(byTitle("Agile Testing"));
agile.shouldBe(visible);
$(byValue("LOGIN")).shouldNotHave(exactValue("test"));
SelenideElement test = $(byName("btnReset"));
test.click();
sleep(4000);
}
@Test
public void chainableSelectors(){
open("/tables");
System.out.println($(byTagName("tr"),2).$(byTagName("td"),3).getText());
//same
System.out.println($(byXpath("//*[@id=\"table2\"]/tbody/tr[2]/td[4]")).getText());
$("#table1").find("tbody").$(byTagName("tr"),2).findAll("td")
.forEach(el -> System.out.println(el.getText()));
System.out.println($("#table1").find("tbody").findAll("tr").size());
}
@Test
public void basicCommandsAndTimeout() {
open("/dynamic_controls");
SelenideElement enableButton= $(By.cssSelector("#input-example button"));
SelenideElement message = $("#message");
enableButton.click();
System.out.println(message.getText());
System.out.println(enableButton.getText());
enableButton.shouldHave(text("Disable")); //timeout works
}
@Test
public void keyPressesExample() {
open("/key_presses");
actions().sendKeys(Keys.ESCAPE).perform();
sleep(4000);
open("https://www.google.com");
SelenideElement search = $x("//*[@id=\"APjFqb\"]");
search.setValue("test automation");
search.sendKeys(Keys.CONTROL, "A");
sleep(3000);
search.sendKeys(Keys.DELETE);
sleep(3000);
}
@Test
public void elementsCollection() {
open("/add_remove_elements/");
for (int i = 0; i <4 ; i++) {
$(byText("Add Element")).click();
}
ElementsCollection deleteButtons = $$(By.cssSelector("#elements button"));
deleteButtons.shouldHave(texts("delete", "delete"));
System.out.println(deleteButtons.size());
SelenideElement test = deleteButtons.first();
System.out.println(test.getText());
sleep(3000);
deleteButtons.last().click();
sleep(3000);
$$(byText("Delete")).forEach(el -> el.click());
sleep(3000);
}
@Test
public void checkConditions() {
open("/inputs");
$(".example input").setValue("3");
$(".example input").shouldBe(not(empty));
sleep(3000);
}
@Test
public void handleDropDowns(){
open("/dropdown");
$("#dropdown").selectOption("Option 1");
$("#dropdown").getSelectedOption().shouldHave(matchText("ption 1"),value("1"));
}
@Test
public void fileDownload() throws FileNotFoundException {
open("/download");
$(byText("logo.png")).download();
}
@Test
public void softAssert() {
SoftAssert softAssert = new SoftAssert();
open("https://demo.guru99.com/test/selenium-xpath.html");
softAssert.assertEquals($(".thick-heading").getText(), "incorrect text", "message");
SelenideElement agile = $(byTitle("Agile Testing"));
System.out.println($(".thick-heading").getText());
agile.shouldBe(visible);
softAssert.assertAll();
}
@Test
public void soft(){
Configuration.assertionMode = SOFT;
open("/dropdown");
$("#dropdown").selectOption("Option 1");
$("#dropdown").getSelectedOption().shouldNotHave(value("1"));
$("#dropdown").getSelectedOption().shouldNotHave(matchText("ption 1"),value("1"));
System.out.println("test");
}
@AfterMethod
public void closeTab() {
closeWebDriver();
}
} |
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:3000'); // Connect to the NestJS server
function Chat() {
const [userId, setUserId] = useState('4'); // Default or empty string if you prefer
const [senderId, setsenderId] = useState(''); // Default or empty string if you prefer
const [adminId, setAdminId] = useState('5'); // Default or empty string if you prefer
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
useEffect(() => {
// Re-join the room on userId or adminId change
const roomId = `chat_${userId}_${adminId}`;
socket.emit('join_room', { userId, adminId });
// Setup listener for incoming messages
const handleReceiveMessage = (data) => {
if (data.roomId === roomId) {
setMessages((msgs) => [...msgs, data]);
}
};
socket.on('receive_message', handleReceiveMessage);
return () => {
socket.off('receive_message', handleReceiveMessage);
};
}, [userId, adminId]);
const sendMessage = () => {
const roomId = `chat_${userId}_${adminId}`;
if (message !== '') {
socket.emit('send_message', { roomId, message, senderId: senderId,vendorId:senderId, userId:userId });
setMessage(''); // Clear the input after sending
}
};
console.log(messages,"messages")
return (
<div>
<input
type="text"
placeholder="Your User ID"
value={userId}
onChange={(e) => setUserId(e.target.value)}
/>
<input
type="text"
placeholder="Admin ID"
value={senderId}
onChange={(e) => setsenderId(e.target.value)}
/>
<input
type="text"
placeholder="Type a message..."
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={sendMessage}>Send Message</button>
<div>
<h3>Messages</h3>
{messages.map((msg, index) => (
<p key={index}>
<strong>{msg.senderId === userId ? userId : `User ${msg.senderId}`}: </strong>
{msg.message}
</p>
))}
</div>
</div>
);
}
export default Chat; |
import { Box, Button, FormControl, FormHelperText, FormLabel, Input, Typography } from '@mui/joy'
import { useFieldArray, useForm } from 'react-hook-form'
type FormValues = {
student: {
name: string,
age: number
}[]
}
export function DynamicForm() {
const { register, control, handleSubmit, formState: { errors } } = useForm<FormValues>({
// defaultValues: {
// student: [{ name: 'test 1', age: 10 }, { name: 'test 2', age: 21 }]
// },
mode: 'all'
})
const { fields, append, prepend, remove } = useFieldArray({
name: 'student',
control
})
// console.log(fields)
//console.log('errors', errors)
return (
<Box>
<Typography variant={'soft'}>Dynamic field</Typography>
<form onSubmit={handleSubmit((data) => console.log('submit', data))}>
{fields.map((field, index) => {
return (
<Box key={field.id} component={'section'} sx={{ mb: 1 }}>
<Typography>{`student-${index + 1}`}</Typography>
<FormControl error={!!errors.student?.[index]?.name}>
<FormLabel>Name</FormLabel>
<Input
{...register(`student.${index}.name`, { required: { value: true, message: 'Name is required' } })}
placeholder="Enter your name" />
{errors.student?.[index]?.name &&
<FormHelperText>{errors.student?.[index]?.name?.message ?? ''}</FormHelperText>}
</FormControl>
<FormControl error={!!errors.student?.[index]?.age}>
<FormLabel>Age</FormLabel>
<Input
{...register(`student.${index}.age`, {
min: { value: 18, message: 'Age should be at least 18' },
valueAsNumber: true
})}
placeholder="Enter your age" />
{errors.student?.[index]?.age &&
<FormHelperText>{errors.student?.[index]?.age?.message ?? ''}</FormHelperText>}
</FormControl>
<Button onClick={() => {
remove(index)
}}>Remove Student</Button>
</Box>
)
})}
<Button onClick={() => {
prepend({
name: '',
age: 0
})
}}>Add Student above</Button>
<Button onClick={() => {
append({
name: '',
age: 0
})
}}>Add Student below</Button>
<Button type={'submit'}>Submit</Button>
</form>
</Box>
)
} |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:bumn_eid/irwan_dev/padi/resources/const.dart';
import 'package:bumn_eid/irwan_dev/padi/views/ui/detail_profil_bumn.dart';
class ItemListOne extends StatelessWidget {
final String number;
final String name;
final int valueOne;
final int valueTwo;
final Widget route;
final bool status;
Function onTap;
ItemListOne({
Key key,
this.number,
this.name,
this.valueOne,
this.valueTwo,
this.route,
this.status,
this.onTap,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Container(
margin: const EdgeInsets.only(top: 10.0),
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 2,
offset: Offset(0, 3), // changes position of shadow
),
],
),
child: Material(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
child: InkWell(
borderRadius: BorderRadius.circular(10),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
new Expanded(
child: new Row(
children: [
new Text(
number,
style: new TextStyle(
fontWeight: FontWeight.w500,
fontSize: 13.0,
fontFamily: 'Poppins'),
),
SizedBox(
width: 5.0,
),
new Expanded(
child: new Text(
name,
style: new TextStyle(
fontWeight: FontWeight.w500,
fontSize: 13.0,
fontFamily: 'Poppins'),
),
)
],
),
),
new Row(
children: [
new Column(
children: [
new Text(
"Nominal",
style: new TextStyle(
fontWeight: FontWeight.w500,
color: secondaryColor,
),
),
new Text(
valueOne.toString(),
style: new TextStyle(
fontWeight: FontWeight.w500,
color: threeColor,
),
)
],
),
new SizedBox(
width: 10.0,
),
new Column(
children: [
new Text(
"UMKM",
style: new TextStyle(
fontWeight: FontWeight.w500,
color: secondaryColor,
),
),
new Text(
valueTwo.toString(),
style: new TextStyle(
fontWeight: FontWeight.w500,
color: threeColor,
),
)
],
),
new SizedBox(
width: 10.0,
),
new Icon(
Icons.arrow_forward,
color: primaryColor,
),
// if (status == true)
// new GestureDetector(
// onTap: () {
// Navigator.push(
// context,
// new MaterialPageRoute(
// builder: (context) {
// return new DetailProfilBumn();
// },
// ),
// );
// },
// child: new Icon(
// Icons.arrow_forward,
// color: primaryColor,
// ),
// )
// else
// new Container(),
],
)
],
),
),
),
),
);
}
} |
/* Atividade 1 - 1ºB - Recursividade
Crie um novo projeto para desenvolver um programa com um menu, cada opção do menu deve ser um exercício do 2 ao 6. Cada opção deve após receber entrada de dados, chamar uma função recursiva e exibir o resultado. O programa deve ser implementado em C# console.*/
string op = "0";
while (op != "6")
{
Console.Clear(); //limpar tela
Console.WriteLine("-------------- MENU --------------");
Console.WriteLine();
Console.WriteLine("1 - Ex.02 Potência");
Console.WriteLine("2 - Ex.03 Cubos");
Console.WriteLine("3 - Ex.04 Máximo Divisor Comum");
Console.WriteLine("4 - Ex.05 Sequencia Fibonacci");
Console.WriteLine("5 - Ex.06 Converter em binário");
Console.WriteLine();
Console.Write("Digite a opção desejada: ");
op = Console.ReadLine();
if (op == "1")
{
int b, e, resu = 0;
Console.Write("Digite o número da base: ");
b = int.Parse(Console.ReadLine());
Console.Write("Digite o expoente: ");
e = int.Parse(Console.ReadLine());
resu = potencia(b, e);
Console.Write("A potencia de ");
Console.Write("["+b+"]");
Console.Write(" elevado a ");
Console.Write("["+ e+"]");
Console.Write(" é: ");
Console.WriteLine("["+resu+"]");
}
else if (op == "2")
{
int num = 0;
Console.Write("Digite um número inteiro: ");
num = int.Parse(Console.ReadLine());
cubos(num);
}
else if (op == "3")
{
int x = 0,y = 0;
Console.Write("Digite um número inteiro: ");
x = int.Parse(Console.ReadLine());
Console.Write("Digite outro número inteiro: ");
y = int.Parse(Console.ReadLine());
Console.WriteLine(mdc(x,y));
}
else if (op == "4")
{
int num;
Console.Write("Digite um múmero inteiro para encontrar a série Fibonacci dele: ");
num = int.Parse(Console.ReadLine());
Console.WriteLine(fib_recursiva(num));
Console.WriteLine($"Calculando Fibonacci iterativamente {num} vezes: ");
fibonacciIterativa(num);
}
else if (op == "5")
{
int x, bin;
Console.Write("informe o numero inteiro para conversão: ");
x = int.Parse(Console.ReadLine());
bin = int.Parse(conversorbin(x));
Console.WriteLine($"O número: {x} em binário é: {bin}");
}
else if (op == "6")
{
break;
}
Console.ReadKey();
}
int potencia(int bas, int expoente)
{
if (expoente == 0)
{
return 1;
}
else
{
return bas * potencia(bas, expoente - 1);
}
}
void cubos(int n, int i = 1)
{
if (n >= i)
{
Console.WriteLine(n * n * n);
cubos(n - 1);
}
}
int mdc(int x, int y)
{
if (x == y)
{
return x;
}
else if (x > y)
{
return mdc(x - y, y);
}
else
{
return mdc(x, y - x);
}
}
int fib_recursiva(int numero)
{
if (numero == 0 || numero == 1)
{
return numero;
}
else if (numero == 2)
{
return 1;
}
else
{
return fib_recursiva(numero - 1) + fib_recursiva(numero - 2);
}
}
void fibonacciIterativa(int x)
{
int n1 = 0, n2 = 1, temporaria;
for (int i = 0; i < x; i++)
{
temporaria = n1;
n1 = n2;
n2 = n1 + temporaria;
Console.WriteLine(n2);
}
}
string conversorbin(int n)
{
if (n >= 1)
{
if (n % 2 == 1)
{
return "" + conversorbin((n - 1) / 2) + "1";
}
else
{
n = n / 2;
return "" + conversorbin(n) + "0";
}
}
return "0";
} |
import 'package:argem_first_design/widgets/shipment_card.dart';
import 'package:flutter/material.dart';
class PackagesScreen extends StatefulWidget {
const PackagesScreen({super.key});
@override
State<PackagesScreen> createState() => _PackagesScreenState();
}
class _PackagesScreenState extends State<PackagesScreen> {
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(15),
child: Column(
children: [
Row(
children: [
//shipment
Column(
crossAxisAlignment: CrossAxisAlignment.start,
// ignore: prefer_const_literals_to_create_immutables
children: [
const Text(
"Sales Order",
style: TextStyle(
fontSize: 35,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 20),
//elevatedbutton.icon
DecoratedBox(
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [
Colors.orangeAccent,
Colors.deepOrange,
],
),
borderRadius: BorderRadius.circular(20),
),
child: ElevatedButton.icon(
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Colors.transparent,
),
shadowColor: MaterialStateProperty.all(
Colors.transparent,
),
shape:
MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
icon: const Icon(
Icons.circle,
color: Colors.white,
size: 8,
),
label: const Text(
'PARTIALLY SHIPPED',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(height: 20),
//shipment infos
Row(
children: [
const CircleAvatar(
backgroundColor: Colors.white,
child: Icon(
Icons.file_copy,
color: Colors.grey,
),
),
const SizedBox(width: 20),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
// ignore: prefer_const_literals_to_create_immutables
children: [
const Text(
"ORDER DATE",
style: TextStyle(
color: Color.fromARGB(255, 159, 159, 159),
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
const Text(
"15 August 2015",
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(width: 50),
const CircleAvatar(
backgroundColor: Colors.white,
child: Icon(
Icons.local_shipping,
color: Colors.grey,
),
),
const SizedBox(width: 15),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
// ignore: prefer_const_literals_to_create_immutables
children: [
const Text(
"EXPECTED SHIPMENT DATE",
style: TextStyle(
color: Color.fromARGB(255, 159, 159, 159),
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
const Text(
"24 August 2015",
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
],
),
const SizedBox(width: 420),
//client card
Column(
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
// ignore: prefer_const_literals_to_create_immutables
children: [
const Text(
"BILLING TO",
style: TextStyle(
color: Color.fromARGB(255, 159, 159, 159),
fontWeight: FontWeight.bold,
fontSize: 10,
),
),
const SizedBox(height: 10),
const CircleAvatar(
backgroundColor: Colors.grey,
),
const SizedBox(height: 10),
const Text(
"Muhammed Yılmaz",
style: TextStyle(
color: Color.fromARGB(255, 1, 33, 193),
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
const Text(
"2762 Mapleview Drive\nSouth Fulton\nTenessee --38257",
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
),
maxLines: 5,
),
],
),
),
),
],
),
],
),
const SizedBox(height: 20),
//orders status
Expanded(
child: Container(
padding: const EdgeInsets.all(15),
height: 300,
width: 950,
decoration: BoxDecoration(
color: const Color.fromARGB(255, 234, 234, 234),
borderRadius: BorderRadius.circular(10),
),
child:
//liste ve index adı gelecek
SingleChildScrollView(
child: Column(
children: [
Row(
// ignore: prefer_const_literals_to_create_immutables
children: [
const SizedBox(
width: 250,
child: Text(
"ITEMS & DESCRIPTION",
style: TextStyle(
color: Color.fromARGB(255, 153, 153, 153),
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
const Spacer(),
const SizedBox(
width: 100,
child: Text(
"INVOICED",
style: TextStyle(
color: Color.fromARGB(255, 153, 153, 153),
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
const Spacer(),
const SizedBox(
width: 105,
child: Text(
"PACKED",
style: TextStyle(
color: Color.fromARGB(255, 153, 153, 153),
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
const Spacer(),
const SizedBox(
width: 105,
child: Text(
"SHIPPED",
style: TextStyle(
color: Color.fromARGB(255, 153, 153, 153),
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
const Spacer(),
const SizedBox(
width: 95,
child: Text(
"RATE",
style: TextStyle(
color: Color.fromARGB(255, 153, 153, 153),
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
const Spacer(),
const SizedBox(
width: 110,
child: Text(
"AMOUNT",
style: TextStyle(
color: Color.fromARGB(255, 153, 153, 153),
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 10),
//product card
const ShipmentCard(
productName: "OLLIE ARNES Women's Essential",
productCode: "SKU: 00001",
invoicedInfo:
Icon(Icons.check_circle, color: Colors.green),
packedInfo: Icon(Icons.check_circle, color: Colors.green),
shippedInfo:
Icon(Icons.check_circle, color: Colors.green),
ratePrice: "30.00 \$",
amountPrice: "270.00 \$",
),
const ShipmentCard(
productName: "T-shirt in soft cotton jersey with a",
productCode: "SKU: 00002",
invoicedInfo:
Icon(Icons.check_circle, color: Colors.green),
packedInfo:
Icon(Icons.watch_later, color: Colors.orangeAccent),
shippedInfo:
Icon(Icons.watch_later, color: Colors.orangeAccent),
ratePrice: "24.00 \$",
amountPrice: "72.00 \$",
),
const ShipmentCard(
productName: "New Balance 997H Canvas",
productCode: "SKU: 00003",
invoicedInfo:
Icon(Icons.check_circle, color: Colors.green),
packedInfo: Icon(Icons.check_circle, color: Colors.green),
shippedInfo:
Icon(Icons.watch_later, color: Colors.orangeAccent),
ratePrice: "112.00 \$",
amountPrice: "2 688.00 \$",
),
const ShipmentCard(
productName: "Jacket in washed denim jersey",
productCode: "SKU: 00004",
invoicedInfo:
Icon(Icons.check_circle, color: Colors.green),
packedInfo: Icon(Icons.check_circle, color: Colors.green),
shippedInfo:
Icon(Icons.check_circle, color: Colors.green),
ratePrice: "44.56 \$",
amountPrice: "401.04 \$",
),
const ShipmentCard(
productName: "Soft sweatshirt jacked with a jersey",
productCode: "SKU: 00005",
invoicedInfo:
Icon(Icons.check_circle, color: Colors.green),
packedInfo:
Icon(Icons.watch_later, color: Colors.orangeAccent),
shippedInfo:
Icon(Icons.watch_later, color: Colors.orangeAccent),
ratePrice: "30.00 \$",
amountPrice: "238.00 \$",
),
],
),
),
),
),
],
),
);
}
} |
################################################################################
Week 4
Git version control
o Centralized vs. distributed VCS
o Objects in git architecture (blob, tree, commit, tag)
o 2 ways to create a version controlled project (git init, git clone)
o Git commands: commit, checkout, branch
o Why do you have to add then commit?
o What’s a branch? A pointer to a commit object.
o Default branch? Master. Keeps moving each time a commit is added
o How to create a new branch. Why is it useful?
################################################################################
Centralized
One place for whole repo
Changes are updated and put on the repo.
Pros:
Everyone can see changes at the same time
Simple to design
Cons:
No backups of repo
Distributed
Each developer gets the full history of a project on their own hard drive
Developers can communicate changes between each other without going through a
central server
Pros:
Don't have to share all code at once,
Commands run fast because they are local.
Cons:
Have to download WHOLE repo.
Objects in git architecture (blob, tree, commit, tag)
head
Reference to a commit object
HEAD
reference to the currently checked out commit object
Master
Default head name that git creates when the repository is initialized.
# show differences between the working copy and the staged files in index.
# if everything is staged, then this will show no differences.
git diff
# This will show the differences between working directory and last commit
git diff HEAD
# revert a commit back
git revert
Git checkout
If you just checkout a file, you undo the changes made to the file if they've
been added to the index(stage)
# list all branches
git branch
# switch branches
get checkout <branchName>
# make a new branch
git branch <branchName> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.