text
stringlengths 184
4.48M
|
---|
import 'dotenv/config'
import { z } from 'zod'
const envSchema = z.object({
NODE_ENV: z.enum(['dev', 'test', 'production']).default('dev'),
SERVER_PORT: z.coerce.number().default(3333),
JWT_SECRET: z.string(),
AWS_REGION: z.string(),
AWS_ACCESS_KEY_ID: z.string(),
AWS_SECRET_ACCESS_KEY: z.string(),
AWS_BUCKET: z.string(),
AWS_URL_IMAGE: z.string().url(),
URL_SERVER: z.string(),
})
const _env = envSchema.safeParse(process.env)
if (_env.success === false) {
console.log('Invalid environment variables.', _env.error.format())
throw new Error('Invalid environment variables.')
}
export const env = _env.data
|
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import Modal from 'react-bootstrap/Modal';
import Tooltip from 'react-bootstrap/Tooltip';
import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
import { toast } from 'react-toastify';
import { TeamCard } from 'components/teamformation';
import {
CloseButton,
CloseButtonContainer,
CloseIconImg,
DecisionButton,
DecisionButtonContainer,
DisplayText,
TeamFormationMessage,
PageButton,
PageButtonIcon,
PageButtonsContainer,
PageIndicator
} from 'common/styles/teamformation/teamFormationInboxModalStyles';
import {
ModalBody,
ModalHeading
} from 'common/styles/teamformation/teamFormationModalStyles';
import { refreshAccessToken } from 'util/auth';
import { handleError } from 'util/plazaUtils';
import { refreshHeadingSectionData } from 'actions/teamFormation';
import { API_ROOT } from 'index';
import {
CommonModalProps,
ConnectionError,
IdsResponse,
NoPermissionError,
RootState,
TeamFormationParticipantInvitation,
TeamFormationTeamFullError,
UnknownError
} from 'types';
import closeIcon from 'assets/icons/close.svg';
import arrowLeftIcon from 'assets/icons/arrow-left.svg';
import arrowRightIcon from 'assets/icons/arrow-right.svg';
const ParticipantInboxModal = (props: CommonModalProps): JSX.Element => {
const { show, setShow } = props;
const dispatch = useDispatch();
const history = useHistory();
const accessToken = useSelector(
(state: RootState) => state.auth.jwtAccessToken
);
const [invitationIds, setInvitationIds] = useState<number[]>([]);
const [currentIndex, setCurrentIndex] = useState<number | null>(null);
const [
currentInvitationData,
setCurrentInvitationData
] = useState<TeamFormationParticipantInvitation | null>(null);
const [dataLoaded, setDataLoaded] = useState(false);
useEffect(() => {
if (show) {
setDataLoaded(false);
getParticipantInbox().catch((err) => handleError(err));
} else {
// Reset state
setInvitationIds([]);
setCurrentIndex(null);
setCurrentInvitationData(null);
}
}, [show]);
useEffect(() => {
if (currentIndex !== null && invitationIds[currentIndex] !== undefined) {
getInvitationData(currentIndex).catch((err) => handleError(err));
}
}, [currentIndex, invitationIds]);
const getParticipantInbox = async (overriddenAccessToken?: string) => {
const token = overriddenAccessToken ? overriddenAccessToken : accessToken;
let res;
try {
res = await fetch(`${API_ROOT}/teamFormation/participants/inbox`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
});
} catch (err) {
throw new ConnectionError();
}
if (res.status === 200) {
const resBody: IdsResponse = await res.json();
if (resBody.ids.length > 0) {
// Reset to beginning of invitations
setInvitationIds(resBody.ids);
setCurrentIndex(0);
} else {
resetInboxState();
setDataLoaded(true);
}
} else if (res.status === 401) {
const refreshedToken = await refreshAccessToken(history);
await getParticipantInbox(refreshedToken);
} else if (res.status === 403) {
history.push('/');
throw new NoPermissionError();
} else {
throw new UnknownError();
}
};
const getInvitationData = async (
id: number,
overriddenAccessToken?: string
) => {
const token = overriddenAccessToken ? overriddenAccessToken : accessToken;
if (currentIndex === null) return;
let res;
try {
res = await fetch(
`${API_ROOT}/teamFormation/participants/invitations/${invitationIds[currentIndex]}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
}
);
} catch (err) {
throw new ConnectionError();
}
if (res.status === 200) {
const resBody: TeamFormationParticipantInvitation = await res.json();
setCurrentInvitationData(resBody);
setDataLoaded(true);
} else if (res.status === 401) {
const refreshedToken = await refreshAccessToken(history);
await getParticipantInbox(refreshedToken);
} else if (res.status === 403) {
history.push('/');
throw new NoPermissionError();
} else {
throw new UnknownError();
}
};
const setCurrentInvitationAccepted = async (
invitationAccepted: boolean | null,
overriddenAccessToken?: string
) => {
const token = overriddenAccessToken ? overriddenAccessToken : accessToken;
if (currentIndex === null) return;
const reqBody = {
accepted: invitationAccepted
};
let res;
try {
res = await fetch(
`${API_ROOT}/teamFormation/participants/invitations/${invitationIds[currentIndex]}/setInvitationAccepted`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(reqBody)
}
);
} catch (err) {
throw new ConnectionError();
}
if (res.status === 200) {
switch (invitationAccepted) {
case true:
toast.success(
'Successfully accepted the invitation! Welcome to the team!'
);
dispatch(refreshHeadingSectionData());
history.push('/teamformation');
break;
case false:
toast.success('The invitation has been dismissed.');
break;
case null:
toast.success('The invitation decision has been reset.');
}
if (invitationIds[currentIndex + 1] !== undefined) {
// Advance to the next invitation
setInvitationIds(
invitationIds.filter((id) => id !== invitationIds[currentIndex])
);
} else if (invitationIds[currentIndex - 1] !== undefined) {
// Advance to the previous invitation
setInvitationIds(
invitationIds.filter((id) => id !== invitationIds[currentIndex])
);
setCurrentIndex(currentIndex - 1);
} else {
resetInboxState();
}
} else if (res.status === 400) {
throw new TeamFormationTeamFullError();
} else if (res.status === 401) {
const refreshedToken = await refreshAccessToken(history);
await setCurrentInvitationAccepted(invitationAccepted, refreshedToken);
} else if (res.status === 403) {
history.push('/');
throw new NoPermissionError();
} else {
throw new UnknownError();
}
};
const resetInboxState = () => {
setInvitationIds([]);
setCurrentIndex(null);
setCurrentInvitationData(null);
};
const handleSetCurrentInvitationAccepted = async (
requestAccepted: boolean | null
) => {
try {
await setCurrentInvitationAccepted(requestAccepted);
} catch (err) {
handleError(err);
}
};
return (
<Modal
show={show}
size="lg"
onHide={() => setShow(false)}
dialogClassName="modal-fullscreen-lg-down"
handleClose={() => setShow(false)}
>
<ModalBody>
<CloseButtonContainer>
<CloseButton onClick={() => setShow(false)}>
<CloseIconImg src={closeIcon} alt="Close Your Inbox" />
</CloseButton>
</CloseButtonContainer>
<ModalHeading>Your Inbox</ModalHeading>
{show &&
(dataLoaded ? (
<>
{currentInvitationData !== null ? (
<>
<TeamCard
teamData={currentInvitationData.invitingTeam}
showActionButton={false}
/>
<TeamFormationMessage>
{currentInvitationData.message}
</TeamFormationMessage>
<DecisionButtonContainer>
<OverlayTrigger
overlay={
currentInvitationData.invitingTeam.members.length >=
currentInvitationData.invitingTeam.size ? (
<Tooltip
id={`team-${currentInvitationData.invitingTeam.id}-full-tooltip`}
>
This team is full.
</Tooltip>
) : (
<span />
)
}
>
<span>
<DecisionButton
variant="success"
onClick={async () => {
if (
confirm(
'By accepting this invitation, you will be hidden from the participant browser. If you have received any other invitations, they will remain in your inbox. Continue?'
)
) {
await handleSetCurrentInvitationAccepted(true);
}
}}
disabled={
currentInvitationData.invitingTeam.members.length >=
currentInvitationData.invitingTeam.size
}
>
Accept and Join Team
</DecisionButton>
</span>
</OverlayTrigger>
<DecisionButton
variant="danger"
onClick={() => handleSetCurrentInvitationAccepted(false)}
>
Decline Invitation
</DecisionButton>
</DecisionButtonContainer>
</>
) : (
<DisplayText>
There are no new invitations in your inbox at this time.
</DisplayText>
)}
{currentIndex !== null && (
<PageButtonsContainer>
<PageButton
variant="secondary"
onClick={() => setCurrentIndex(currentIndex - 1)}
disabled={currentIndex === 0}
>
<PageButtonIcon
src={arrowLeftIcon}
alt="Go To Previous Invitation"
/>
</PageButton>
<PageIndicator>
{currentIndex + 1} / {invitationIds.length}
</PageIndicator>
<PageButton
variant="secondary"
onClick={() => setCurrentIndex(currentIndex + 1)}
disabled={invitationIds.length - 1 === currentIndex}
>
<PageButtonIcon
src={arrowRightIcon}
alt="Go To Next Invitation"
/>
</PageButton>
</PageButtonsContainer>
)}
</>
) : (
<DisplayText>Loading...</DisplayText>
))}
</ModalBody>
</Modal>
);
};
export default ParticipantInboxModal;
|
// import { useEffect, useState } from "react";
import { useNavigate } from 'react-router-dom';
// components
import Header from '../components/Layout/Header';
import CategoryBox from '../components/RecommendMenu/CategoryBox';
import SelectButton from '../components/Common/SelectButton';
// styles
import classes from './CategoryPage.module.css';
// images
import CategoryDescription from '../assets/descriptions/category_description.png';
import Coffee from '../assets/category/coffee.png';
import Tea from '../assets/category/tea.png';
import Juice from '../assets/category/juice.png';
import Icecream from '../assets/category/icecream.png';
import Cake from '../assets/category/cake.png';
import Bingsu from '../assets/category/bingsu.png';
import SeletedCoffee from '../assets/category/selected_coffee.png';
import SelectedTea from '../assets/category/selected_tea.png';
import SelectedJuice from '../assets/category/selected_juice.png';
import SelectedIcecream from '../assets/category/selected_icecream.png';
import SelectedCake from '../assets/category/selected_cake.png';
import SelectedBingsu from '../assets/category/selected_bingsu.png';
//import
import { useContext } from 'react';
import { SelectedList } from '../context/SelectedList';
const CategoryPage = () => {
const selectedList = useContext(SelectedList);
const selectedCategory = selectedList.category;
const navigate = useNavigate();
const handleMenuClick = (menu) => {
if (selectedCategory === menu) {
selectedList.setCategory('');
} else {
selectedList.setCategory(menu);
}
};
console.log(selectedCategory);
const onClickButtonHandler = (e) => {
// select button clicked
if (selectedCategory === "") {
e.preventDefault();
alert("종류를 선택해주세요!");
} else if (
selectedCategory === "coffee" ||
selectedCategory === "tea" ||
selectedCategory === "juice"
) {
navigate("/temperature");
} else {
// navigate("/option");
alert("Coming Soon!!!!!!!!!!!!!!!!!!!!!!!")
}
};
return (
<div className={classes['page-container']}>
<Header />
<img src={CategoryDescription} alt='category-description' />
<div className={classes['menus-container']}>
<CategoryBox
className={classes['menu-container']}
onClick={() => handleMenuClick('coffee')}
imageSrc={selectedCategory === 'coffee' ? SeletedCoffee : Coffee}
/>
<CategoryBox
className={classes['menu-container']}
onClick={() => handleMenuClick('tea')}
imageSrc={selectedCategory === 'tea' ? SelectedTea : Tea}
/>
<CategoryBox
className={classes['menu-container']}
onClick={() => handleMenuClick('juice')}
imageSrc={selectedCategory === 'juice' ? SelectedJuice : Juice}
/>
<CategoryBox
className={classes['menu-container']}
onClick={() => handleMenuClick('icecream')}
imageSrc={
selectedCategory === 'icecream' ? SelectedIcecream : Icecream
}
/>
<CategoryBox
className={classes['menu-container']}
onClick={() => handleMenuClick('cake')}
imageSrc={selectedCategory === 'cake' ? SelectedCake : Cake}
/>
<CategoryBox
className={classes['menu-container']}
onClick={() => handleMenuClick('bingsu')}
imageSrc={selectedCategory === 'bingsu' ? SelectedBingsu : Bingsu}
/>
</div>
<SelectButton text={'선택완료'} onClick={onClickButtonHandler} />
</div>
);
};
export default CategoryPage;
|
import { useAppDispatch, useAppSelector } from 'app/hook';
import UserInfoWrap from 'components/Mypage/UserInfoWrap';
import UserTheme from 'components/Mypage/UserTheme';
import {
useGetUserImageQuery,
useGetUserInfoQuery,
useGetUserThemeQuery,
} from 'features/users/userApi';
import { logout, selectIsLogin } from 'features/users/userSlice';
import useMedia from 'hooks/useMedia';
import { useRouter } from 'next/router';
import React, { useEffect } from 'react';
import styled from 'styled-components';
import { applyMediaQuery } from 'styles/mediaQuery';
function Mypage() {
const { isMobile, isTablet } = useMedia();
const isLogin = useAppSelector(selectIsLogin);
const dispatch = useAppDispatch();
const router = useRouter();
const { data: userInfo } = useGetUserInfoQuery(undefined, {
refetchOnMountOrArgChange: true,
});
const { data: userImage } = useGetUserImageQuery(undefined, {
refetchOnMountOrArgChange: true,
});
const { data: userThemeWrap } = useGetUserThemeQuery(undefined, {
refetchOnMountOrArgChange: true,
});
const handleClickLogout = () => {
dispatch(logout());
router.push('/');
};
useEffect(() => {
if (!isLogin) {
router.push('/');
}
}, [isLogin]);
if (!userInfo || !userImage || !userThemeWrap)
return (
<StyledRoot>
{(isMobile || isTablet) && (
<LogoutButton onClick={handleClickLogout}>로그아웃</LogoutButton>
)}
</StyledRoot>
);
return (
<StyledRoot>
<UserInfoWrap userInfo={userInfo} userImage={userImage} />
<UserTheme userTheme={userThemeWrap.theme} />
{(isMobile || isTablet) && <LogoutButton onClick={handleClickLogout}>로그아웃</LogoutButton>}
</StyledRoot>
);
}
const StyledRoot = styled.div`
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 11rem auto;
${applyMediaQuery('mobile', 'tablet')} {
margin: 0;
margin-top: 3rem;
justify-content: flex-start;
}
${applyMediaQuery('mobile')} {
margin-top: 1.4rem;
}
`;
const LogoutButton = styled.button`
all: unset;
align-self: flex-end;
margin-top: 10.5rem;
margin-bottom: 5rem;
padding: 0 1.2rem;
color: ${({ theme }) => theme.colors.purpleMain};
font-size: 1.1rem;
line-height: 1.6rem;
font-weight: 500;
${applyMediaQuery('tablet')} {
font-size: 1.3rem;
}
`;
export default Mypage;
|
import sqlite3
import subscriptionManager
subscription_info = "subscription_info.txt"
# Function to rent a game
def rent_game(database, customer_id, ID):
try:
conn = sqlite3.connect(database)
cursor = conn.cursor()
# Check if the customer exists in the database
cursor.execute("SELECT * FROM Rentals WHERE customer_id = ?", (customer_id,))
customer = cursor.fetchone()
if not customer:
conn.close()
return "Invalid customer ID. Please provide a valid customer ID."
# Check if the customer has rented any games
cursor.execute("SELECT * FROM Rentals WHERE customer_id = ? AND game_id = ?", (customer_id, ID))
rented_game = cursor.fetchone()
if rented_game:
conn.close()
return "You have already rented this game."
# Check the customer's subscription status using the subscriptionManager
subscriptions = subscriptionManager.load_subscriptions(subscription_info)
if not subscriptionManager.check_subscription(customer_id, subscriptions):
conn.close()
return "Customer does not have an active subscription. Rental not allowed."
# Check if the customer has an active subscription type
cursor.execute("SELECT SubscriptionType FROM subscriptions WHERE CustomerID = ?", (customer_id,))
subscription_type = cursor.fetchone()
if not subscription_type:
conn.close()
return "Customer does not have a valid subscription type."
# Get the rental limit based on the customer's subscription type
rental_limit = subscriptionManager.get_rental_limit(subscription_type[0])
# Check how many games the customer has rented
cursor.execute("SELECT COUNT(*) FROM Rentals WHERE customer_id = ?", (customer_id,))
num_rented_games = cursor.fetchone()[0]
if num_rented_games >= rental_limit:
conn.close()
return f"Sorry, you have reached your rental limit based on your subscription (SubscriptionType: {subscription_type[0]})."
# Update the game table availability coulumn to "unavailable" to corresponding ID
cursor.execute("UPDATE games SET availability = ? WHERE ID = ?", ("unavailable", ID))
conn.commit()
conn.close()
return f"Game rented successfully. You can still rent {rental_limit - num_rented_games} more games."
except sqlite3.Error as e:
print("SQLite error:", e)
return "An error occurred during the rental process."
# test case
if __name__ == '__main__':
database_name = 'MyGameRentals2.db'
customer_id = "8749"
ID = 2
result = rent_game(database_name, customer_id, ID)
print(result)
|
import React, { useEffect, useState } from "react";
import Cart from "../Cart/Cart";
import Youtuber from "../Youtuber/Youtuber";
const Developers = () => {
const [youtubers, setYoutubers] = useState([]);
const [cart, setCart] = useState([]);
useEffect(() => {
fetch("./youtubers.JSON")
.then((res) => res.json())
.then((data) => setYoutubers(data));
}, []);
const handleAddToCart = (youtuber) => {
const newCart = [...cart, youtuber];
setCart(newCart);
};
return (
<>
<div className="container">
<div className="row">
<div className="col-sm-9">
<div className="row g-5">
{youtubers.map((youtuber) => (
<Youtuber
key={youtuber.key}
youtuber={youtuber}
handleAddToCart={handleAddToCart}
></Youtuber>
))}
</div>
</div>
<div className="col-sm-3">
<Cart cart={cart}></Cart>
</div>
</div>
</div>
</>
);
};
export default Developers;
|
from flask import Flask, render_template,request, redirect,session
import pymysql
import os
from werkzeug.utils import secure_filename
from sms import send_sms
app = Flask(__name__)
app.secret_key = "Strovold19."
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDERS = os.path.join(APP_ROOT, "static\images")
app.config['UPLOAD_FOLDERS'] = UPLOAD_FOLDERS
@app.route("/")
def index():
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cursor = con.cursor()
dramaCursor = con.cursor()
actionsCursor = con.cursor()
horrorsCursor = con.cursor()
romancesCursor = con.cursor()
sql = "SELECT * FROM products"
dramaSql = "SELECT * FROM products WHERE product_cat = 'dramas' LIMIT 4"
actionSql = "SELECT * FROM products WHERE product_cat = 'actions' LIMIT 4"
horrorSql = "SELECT * FROM products WHERE product_cat = 'horrors' LIMIT 4"
romanceSql = "SELECT * FROM products WHERE product_cat = 'romances' LIMIT 4"
cursor.execute(sql)
dramaCursor.execute(dramaSql)
actionsCursor.execute(actionSql)
horrorsCursor.execute(horrorSql)
romancesCursor.execute(romanceSql)
allproducts = cursor.fetchall()
alldramas = dramaCursor.fetchall()
allactions = actionsCursor.fetchall()
allhorrors = horrorsCursor.fetchall()
allromances = romancesCursor.fetchall()
return render_template("home.html", products=allproducts, dramas=alldramas, actions=allactions, horrors=allhorrors, romances=allromances)
@app.route("/categories/<category>")
def categories(category):
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cursor = con.cursor()
sql = "SELECT * FROM products WHERE product_cat = %s"
cursor.execute(sql, (category,))
allproducts = cursor.fetchall()
return render_template("products.html", products=allproducts, cat_name=category)
@app.route("/product/<product_id>")
def product(product_id):
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cursor = con.cursor()
sql = """
SELECT p.*, AVG(r.rating) AS average_rating
FROM products p
LEFT JOIN ratings r ON p.product_id = r.product_id
WHERE p.product_id = %s
GROUP BY p.product_id
"""
cursor.execute(sql, (product_id,))
allProducts = cursor.fetchone()
return render_template("singleproduct.html", product=allProducts)
@app.route("/upload")
def upload():
if request.args.get("msg") != "":
msg = request.args.get("msg")
return render_template("upload.html", msg=msg)
else:
return render_template("upload.html", msg="")
@app.route("/save-products", methods=['GET', 'POST'])
def saveProducts():
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cur = con.cursor()
if request.method == 'POST':
product_name = request.form['product_name']
product_desc = request.form['product_desc']
product_cost = request.form['product_cost']
product_category = request.form['product_cat']
product_image = request.files['product_image']
myFileName = secure_filename(product_image.filename)
if product_name == "" or product_desc == "" or product_cost == "" or product_category == "" or product_image== "":
msg = "Please Fill In All Fields"
return redirect(f"/upload?msg={msg}")
else:
sql= "INSERT INTO products(product_name,product_desc,product_cost,product_cat,product_img_path)VALUES (%s,%s,%s,%s,%s)"
cur.execute(sql,(product_name,product_desc,product_cost,product_category,myFileName))
con.commit()
product_image.save(os.path.join(app.config['UPLOAD_FOLDERS'],myFileName))
msg="Products Added Successfuly"
return redirect(f"/upload?msg={msg}")
else:
msg="the method was not post"
return redirect(f"/upload?msg={msg}")
@app.route("/register")
def register():
if request.args.get("msg") != "":
msg = request.args.get("msg")
color = request.args.get("color")
return render_template("register.html", msg=msg,color=color)
else:
return render_template("register.html", msg="",color="")
@app.route("/save-user", methods=['GET', 'POST'])
def saveUsers():
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cur = con.cursor()
if request.method == 'POST':
f_name = request.form['f_name']
l_name = request.form['l_name']
email = request.form['email']
phone = request.form['phone']
dob = request.form['dob']
password = request.form['password']
c_password = request.form['c_password']
if f_name == "" or l_name == "" or email == "" or phone == "" or dob == "" or password == "":
msg = "Please Fill In All Fields"
color = "danger"
return redirect(f"/register?msg={msg}&color={color}")
elif len(password) <=8:
msg = "password must have at least eight characters"
color = "danger"
return redirect(f"/register?msg={msg}&color={color}")
elif password != c_password:
msg = "passwords don't match"
color = "danger"
return redirect(f"/register?msg={msg}&color={color}")
else:
sql= "INSERT INTO users(f_name,l_name,email,phone,dob,password)VALUES (%s,%s,%s,%s,%s,%s)"
cur.execute(sql,(f_name,l_name,email,phone,dob,password))
con.commit()
message = "You have successfuly registerd on sokogarden"
send_sms(phone,message)
msg = "Info Added Successfuly"
color = "danger"
return redirect(f"/upload?msg={msg}&color={color}")
else:
msg = "the method was not post"
color="danger"
return redirect(f"/upload?msg={msg}")
@app.route("/login")
def login():
if request.args.get("msg") != "":
msg = request.args.get("msg")
color = request.args.get("color")
return render_template("login.html", msg=msg,color=color)
else:
return render_template("login.html", msg="",color="")
@app.route("/do-login", methods=['GET', 'POST'])
def dologin():
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cur = con.cursor()
if request.method == 'POST':
email = request.form["email"]
password = request.form["password"]
if email == "" or password == "":
msg = "Please Fill In All Fields"
color = "danger"
return redirect(f"/login?msg={msg}&color={color}")
elif len(password) <=8:
msg = "password must have at least eight characters"
color = "danger"
return redirect(f"/register?msg={msg}&color={color}")
else:
sql = "SELECT user_id FROM users WHERE email = %s AND password = %s LIMIT 1"
cur.execute(sql,(email,password))
user = cur.fetchone()
if cur.rowcount == 1:
session['key'] = str (user[0])
return redirect("/profile")
else:
msg = "Email and Password are incorrect"
color = "danger"
return redirect(f"/login?msg={msg}&color={color}")
else:
msg = "the method was not post"
color = "danger"
return redirect(f"/login?msg={msg}&color={color}")
@app.route("/logout")
def logout():
session.pop('key',None)
return redirect("/login")
@app.route("/profile")
def profile():
if "key" in session:
user_id = session['key']
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cur = con.cursor()
sql = "SELECT f_name,l_name FROM users WHERE user_id = %s"
cur.execute(sql,(user_id))
data = cur.fetchone()
return render_template("profile.html",data=data)
else:
msg = "you must be logged in to access"
color = "danger"
return redirect(f"/login?msg={msg}&color={color}")
@app.route("/ratings/")
def ratings():
if "key" in session:
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cur = con.cursor()
sql = "SELECT product_id, product_name, product_cost FROM products WHERE product_id = %s"
product_id = 1 # Replace with the actual product ID you want to retrieve
cur.execute(sql, (product_id,))
data = cur.fetchone()
return render_template("ratings.html", data=data)
else:
msg = "You must be logged in to access this page"
color = "danger"
return redirect(f"/login?msg={msg}&color={color}")
@app.route("/save-ratings", methods=['GET', 'POST'])
def saveRatings():
con = pymysql.connect(host="localhost", user="root", password="", database="mov")
cur = con.cursor()
if request.method == 'POST':
product_id = request.form['product_id']
rating = request.form['rating']
if product_id == "" or rating == "":
msg = "Please Fill In All Fields"
color = "danger"
return redirect(f"/ratings?msg={msg}")
else:
try:
rating = float(rating)
if rating < 1 or rating > 10:
msg = "Rating must be between 1 and 10"
color = "danger"
return redirect(f"/ratings?msg={msg}")
sql = "INSERT INTO ratings(product_id, rating) VALUES (%s, %s)"
cur.execute(sql, (product_id, rating))
con.commit()
msg = "Rating submitted successfully"
color = "warning"
return redirect(f"/ratings?msg={msg}")
except ValueError:
msg = "Invalid rating value"
return redirect(f"/ratings?msg={msg}")
else:
msg = "Invalid request method"
return redirect(f"/ratings?msg={msg}")
if __name__ == "__main__":
app.run(debug=True)
import pdb; pdb.set_trace()
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSepetUrunTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sepet_urun', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('sepet_id');
$table->unsignedInteger('urun_id');
$table->integer('adet');
$table->decimal('fiyati', 5, 2);
$table->string('durum', 30);
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
$table->softDeletes();
$table->foreign('sepet_id')->references('id')->on('sepet')->onDelete('cascade');
$table->foreign('urun_id')->references('id')->on('urun')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sepet_urun');
}
}
|
<template>
<v-app>
<div v-if="getCurrentUser.userId !== undefined" >
<v-navigation-drawer
v-model="drawer"
app
>
<v-list-item>
<v-list-item-avatar>
<v-img
src="@/assets/logo.svg"
/>
</v-list-item-avatar>
<v-list-item-content>
<v-list-item-title>Inventory </v-list-item-title>
</v-list-item-content>
</v-list-item>
<v-divider></v-divider>
<v-list dense>
<v-list-item
v-for="item in navItems"
:key="item.title"
:to="item.path"
link
>
<v-list-item-icon>
<v-icon>{{ item.icon }}</v-icon>
</v-list-item-icon>
<v-list-item-content>
<v-list-item-title>{{ item.title }}</v-list-item-title>
</v-list-item-content>
</v-list-item>
</v-list>
</v-navigation-drawer>
<v-app-bar
app
color="primary"
dark
>
<v-app-bar-nav-icon @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
<v-spacer></v-spacer>
<v-btn
icon
v-if="getCurrentUser.userId !== undefined"
@click="logout"
>
<v-icon>mdi-logout</v-icon>
</v-btn>
</v-app-bar>
<v-main >
<router-view/>
</v-main>
<v-footer app >
<v-btn text target="_blank" href="https://github.com/Ragupathi-D/books" >Raguathi-D </v-btn>
</v-footer>
</div>
<div v-else >
<router-view/>
</div>
</v-app>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
name : 'app',
methods : {
...mapActions('USER',{
'logoutProcess' : 'logout'
}),
async logout(){
await this.logoutProcess()
this.$router.push('/login')
}
},
computed: {
...mapGetters('USER', {
getCurrentUser : 'getCurrentUser',
navItems : 'getNavItems'
})
},
data () {
return {
drawer: null,
}
},
}
</script>
|
# Release Process
This document explains how to create releases in this project in each release scenario.
Currently there are 2 release procedures for this project:
- [Latest Release](#latest-release)
- [Non-Latest Release](#non-latest-release)
## Latest Release
This procedure is used when we want to create new release from the latest development edge (latest commit in the `master` branch).
The steps for this procedure are the following:
1. Create a new branch from the `master` branch with the following name format: `pre_release/v{MAJOR}.{MINOR}.{BUILD}`. For example, if we want to release for version `0.6.0`, we will first create a new branch from the `master` called `pre_release/v0.6.0`.
2. Update method `Version()` in `version.go` to return the target version.
3. Update the `CHANGELOG.md` to include all the notable changes.
4. Create a new PR from this branch to `master` with the title: `Release v{MAJOR}.{MINOR}.{BUILD}` (e.g `Release v0.6.0`).
5. At least one maintainer should approve the PR. However if the PR is created by the repo owner, it doesn't need to get approval from other maintainers.
6. Upon approval, the PR will be merged to `master` and the branch will be deleted.
7. Create new release from the `master` branch.
8. Set the title to `Release v{MAJOR}.{MINOR}.{BUILD}` (e.g `Release v0.6.0`).
9. Set the newly release tag using this format: `v{MAJOR}.{MINOR}.{BUILD}` (e.g `v0.6.0`).
10. Set the description of the release to match with the content inside `CHANGELOG.md`.
11. Set the release as the latest release.
12. Publish the release.
13. Done.
## Non-Latest Release
This procedure is used when we need to create fix or patch for the older releases. Consider the following scenario:
1. For example our latest release is version `0.7.1` which has the minimum go version `1.18`.
2. Let say our user got a critical bug in version `0.6.0` which has the minimum go version `1.15`.
3. Due to some constraints, this user cannot upgrade his/her minimum go version.
4. We decided to create fix for this version by releasing `0.6.1`.
In this scenario, the procedure is the following:
1. Create a new branch from the version that we want to patch.
2. We name the new branch with the increment in the build value. So for example if we want to create patch for `0.6.0`, then we should create new branch with name: `patch_release/v0.6.1`.
3. We create again new branch that will use `patch_release/v0.6.1` as base. Let say `fix/handle-cve-233`.
4. We will push any necessary changes to `fix/handle-cve-233`.
5. Create a new PR that target `patch_release/v0.6.1`.
6. Follow step `2-10` as described in the [Latest Release](#latest-release).
7. Publish the release without setting the release as the latest release.
8. Done.
|
#! /usr/bin/env python
import csv
import datetime
import json
import subprocess
import sys
import time
from config import MACHINES, WAIT_TIME, BENCHMARKS
def run_benchmarks() -> str:
print("Running benchmarks")
results = {}
for node, values in MACHINES.items():
results[node] = {}
for name, command in BENCHMARKS:
print(f"Running {name} on {node}")
print(f"Command: {command}")
proc = subprocess.run("ssh {user}@{host} \"cd {directory} && {command}\"".format(**values, command=command),
capture_output=True, shell=True)
results[node][name] = json.loads(proc.stdout)
print(f"Finished {name} on {node}, sleeping for {WAIT_TIME}...")
time.sleep(WAIT_TIME) # TODO: Fix redundant wait period
print("Writing results file")
result_filename = f"results/{datetime.datetime.now()}.json"
with open(result_filename, "w") as result_file:
result_file.write(json.dumps(results, indent=2))
print("Benchmark run complete")
return result_filename
def compile_results(result_filename: str):
print(f"Compiling results from {result_filename}")
results = {}
with open(result_filename, "r") as f:
raw_results = json.loads(f.read())
for node, benchmarks in raw_results.items():
for benchmark, data in benchmarks.items():
if benchmark not in results.keys():
results[benchmark] = {}
jobs = data["jobs"]
results[benchmark][node] = {
"iops": get_avg_value(jobs, "write", "iops"),
"bandwidth": get_avg_value(jobs, "write", "bw_bytes") / 1024 / 1024,
"io_written": get_avg_value(jobs, "write", "io_bytes") / 1024 / 1024
}
headers = ["node", "iops", "bandwidth", "io_written"]
for benchmark, nodes in results.items():
with open(f"{benchmark}.csv", "w") as f:
datawriter = csv.writer(f, delimiter=",")
datawriter.writerow(headers)
for node, datapoints in nodes.items():
datawriter.writerow([node, datapoints["iops"], datapoints["bandwidth"], datapoints["io_written"]])
print("Done")
def get_avg_value(jobs: list[dict], operation: str, key: str) -> float:
values = list(map(lambda x: x[operation][key], jobs))
return sum(values) / len(values)
if __name__ == "__main__":
if len(sys.argv) < 2:
result_filename = run_benchmarks()
else:
result_filename = sys.argv[1]
print(f"Skipping benchmark, reading results from {result_filename}")
compile_results(result_filename)
|
import { initialStateType, userInfoType } from "@/types/types";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import cookie from "js-cookie";
const initialState: initialStateType = {
isAuthenticated: false,
error: null,
isLoading: false,
userCreated: null,
};
export const SignUpAction = createAsyncThunk(
"auth/signup",
async (data: userInfoType, { rejectWithValue }) => {
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/auth/signup`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
return rejectWithValue(await response.json());
}
const responseData = await response.json();
return responseData;
} catch (error) {
return rejectWithValue(error);
}
}
);
export const SignInAction = createAsyncThunk(
"auth/signin",
async (data: userInfoType, { rejectWithValue }) => {
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/auth/signin`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
return rejectWithValue(await response.json());
}
const responseData = await response.json();
return responseData;
} catch (error) {
return rejectWithValue(error);
}
}
);
export const AuthSlice = createSlice({
name: "auth",
initialState,
reducers: {
logOut: (state) => {
state.isAuthenticated = false;
state.userCreated = null;
cookie.remove("token");
window.location.href = "/";
},
resetAuthState: (state) => {
state.isAuthenticated = false;
state.userCreated = null;
state.error = null;
}
},
extraReducers(builder) {
builder.addCase(SignUpAction.pending, (state) => {
state.isLoading = true;
});
builder.addCase(SignUpAction.fulfilled, (state, action: any) => {
state.isLoading = false;
state.isAuthenticated = true;
state.userCreated = action.payload;
});
builder.addCase(SignUpAction.rejected, (state, action: any) => {
state.isLoading = false;
state.error = action.payload || null;
state.userCreated = null;
});
// Signin
builder.addCase(SignInAction.pending, (state) => {
state.isLoading = true;
});
builder.addCase(SignInAction.fulfilled, (state, action: any) => {
state.isLoading = false;
state.isAuthenticated = true;
state.userCreated = action.payload;
cookie.set("token", action.payload.token, {
expires: 7 * 24 * 60 * 60 * 1000,
});
cookie.set("userInfo", JSON.stringify(action.payload.userInfo), {
expires: 7 * 24 * 60 * 60 * 1000,
});
});
builder.addCase(SignInAction.rejected, (state, action: any) => {
state.isLoading = false;
state.error = action.payload || null;
state.userCreated = null;
});
},
});
export const { logOut,resetAuthState } = AuthSlice.actions;
|
package murraco.service;
import javax.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import murraco.model.AppUserRole;
import murraco.model.AuthResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import murraco.exception.CustomException;
import murraco.model.AppUser;
import murraco.repository.UserRepository;
import murraco.security.JwtTokenProvider;
import java.util.ArrayList;
import java.util.List;
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtTokenProvider jwtTokenProvider;
private final AuthenticationManager authenticationManager;
public AuthResponse signin(String username, String password) {
AuthResponse response = new AuthResponse();
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
String token = jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getAppUserRoles());
response.setAccessToken(token);
response.setUserName(username);
List<AppUserRole> d =userRepository.findByUsername(username).getAppUserRoles();
if(d!=null){
List<String> roles = new ArrayList<String>();
for(AppUserRole role: d){
roles.add(role.name());
}
response.setRoles(roles);
}
} catch (AuthenticationException e) {
throw new CustomException("Invalid username/password supplied", HttpStatus.UNPROCESSABLE_ENTITY);
}
return response;
}
public String signup(AppUser appUser) {
if (!userRepository.existsByUsername(appUser.getUsername())) {
appUser.setPassword(passwordEncoder.encode(appUser.getPassword()));
userRepository.save(appUser);
jwtTokenProvider.createToken(appUser.getUsername(), appUser.getAppUserRoles());
return "SUCCESS";
} else {
throw new CustomException("Username is already in use", HttpStatus.UNPROCESSABLE_ENTITY);
}
}
public void delete(String username) {
userRepository.deleteByUsername(username);
}
public AppUser search(String username) {
AppUser appUser = userRepository.findByUsername(username);
if (appUser == null) {
throw new CustomException("The user doesn't exist", HttpStatus.NOT_FOUND);
}
return appUser;
}
public AppUser whoami(HttpServletRequest req) {
return userRepository.findByUsername(jwtTokenProvider.getUsername(jwtTokenProvider.resolveToken(req)));
}
public String refresh(String username) {
return jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getAppUserRoles());
}
}
|
<div *ngIf="identity" class="navigation col-lg-1 col-xs-2">
<h1 class="head-title">
<a [routerLink]="['/']"><span class="glyphicon glyphicon-music" aria-hidden="true"></span>{{title}}</a>
</h1>
<nav id="navigation">
<a [routerLink]="['/artistas', 1]">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
Artistas
</a>
</nav>
<nav id="user_logged">
<div class="user-image">
<img id="image-logged" src="{{url + 'get-image-user/' + identity.image}}">
</div>
<span id="identity_name">{{identity.name}}</span>
<a [routerLink]="['/mis-datos']" [routerLinkActive]="['actived']">
<span class="glyphicon glyphicon-cog" aria-hidden="true"></span>
Mis datos
</a>
<a (click)="logout()" class="btn-logout">
<span class="glyphicon glyphicon-log-out" aria-hidden="true"></span>
Salir
</a>
</nav>
</div>
<div *ngIf="identity" class="central col-lg-11 col-xs-10">
<router-outlet></router-outlet>
<div class="clearfix"></div>
<player *ngIf="identity" class="player"></player>
</div>
<div class="col-lg-11 col-xs-10" *ngIf="!identity">
<div class="col-lg-6 col-xs-12">
<h1 style="color: white;">Identifícate</h1>
<div *ngIf="errorMessage">
<div class="alert alert-info">
<strong>Error</strong> {{errorMessage}}
</div>
</div>
<form #loginForm="ngForm" (ngSubmit)="onSubmit()" class="col-md-7">
<div class="input-field col s12 m6">
<label for="email">Correo electrónico:</label>
<input type="email" #email="ngModel" name="email" [(ngModel)]="user.email" placeholder="" required/>
<span *ngIf="!email.valid && email.touched">
El email es obligatorio
</span>
</div>
<div class="input-field col s12 m6">
<label for="password">Contraseña:</label>
<input type="password" #password="ngModel" name="password" [(ngModel)]="user.password" placeholder="" required/>
</div>
<input type="submit" value="Entrar" class="btn btn-primary">
</form>
</div>
<div class="col-lg-6 col-xs-12">
<h1 style="color: white;">Regístrate</h1>
<div *ngIf="alertRegister">
<div class="alert alert-info">{{alertRegister}}
</div>
</div>
<form #registerForm="ngForm" (ngSubmit)="onSubmitRegister()" class="col-md-10">
<div class="input-field col s12 m6">
<label for="name">Nombre:</label>
<input type="text" #name="ngModel" name="name" [(ngModel)]="user_register.name" placeholder="" required/>
<span *ngIf="!name.valid && name.touched">
El nombre es obligatorio
</span>
</div>
<div class="input-field col s12 m6">
<label for="surname">Apellidos:</label>
<input #surname="ngModel" name="surname" [(ngModel)]="user_register.surname" type="text" placeholder="" required/>
<span *ngIf="!surname.valid && surname.touched">
Los apellidos son obligatorios
</span>
</div>
<div class="input-field col s12 m6">
<label for="email">Correo electrónico:</label>
<input type="email" #email="ngModel" name="email" [(ngModel)]="user_register.email" placeholder="" required/>
<span *ngIf="!email.valid && email.touched">
El email es obligatorio
</span>
</div>
<div class="input-field col s12 m6">
<label for="password">Contraseña:</label>
<input type="password" #password="ngModel" name="password" [(ngModel)]="user_register.password" placeholder="" required/>
<span *ngIf="!password.valid && passwordtouched">
La contraseña es obligatoria
</span>
</div>
<input type="submit" value="Registrarse" class="btn btn-primary">
</form>
</div>
</div>
|
//
// Vector3.swift
//
//
// Created by David Green on 10/5/20.
//
import Foundation
/// Describes a 3D vector
public struct Vector3: Equatable, Codable, CustomDebugStringConvertible, Hashable {
// MARK: - Static properties
/// Returns a `Vector3` with components `0, 0, 0`.
public static let zero: Vector3 = Vector3(0, 0, 0)
/// Returns a `Vector3` with components `1, 1, 1`.
public static let one: Vector3 = Vector3(1, 1, 1)
/// Returns a `Vector3` with components `1, 0, 0`.
public static let unitX: Vector3 = Vector3(1, 0, 0)
/// Returns a `Vector3` with components `0, 1, 0`.
public static let unitY: Vector3 = Vector3(0, 1, 0)
/// Returns a `Vector3` with components `0, 0, 1`.
public static let unitZ: Vector3 = Vector3(0, 0, 1)
/// Returns a `Vector3` with components `0, 1, 0`.
public static let up: Vector3 = Vector3(0, 1, 0)
/// Returns a `Vector3` with components `0, -1, 0`.
public static let down: Vector3 = Vector3(0, -1, 0)
/// Returns a `Vector3` with components `0, -1, 0`.
public static let right: Vector3 = Vector3(1, 0, 0)
/// Returns a `Vector3` with components `-1, 0, 0`.
public static let left: Vector3 = Vector3(-1, 0, 0)
/// Returns a `Vector3` with components `0, 0, -1`.
public static let forward: Vector3 = Vector3(0, 0, -1)
/// Returns a `Vector3` with components `0, 0, 1`.
public static let backward: Vector3 = Vector3(0, 0, 1)
// MARK: - Public ivars
/// The *x* coordinate of this `Vector3`.
public var x: Float
/// The *y* coordinate of this `Vector3`.
public var y: Float
/// The *z* coordinate of this `Vector3`.
public var z: Float
// MARK: - CustomDebugStringConvertible
public var debugDescription: String {
return "\(x) \(y) \(z)"
}
// MARK: - Constructors
/// Constructs a 3d vector with X, Y, and Z from three values.
///
/// - Parameters:
/// - x: The x coordinate in 3d space.
/// - y: The y coordinate in 3d space.
/// - z: The z coordinate in 3d space.
public init(_ x: Float, _ y: Float, _ z: Float) {
self.x = x
self.y = y
self.z = z
}
/// Constructs a 3D vector with X, Y, and Z set to the same value
///
/// - Parameters:
/// - value: The x, y, and z coordinates in 3d space.
public init(_ value: Float) {
x = value
y = value
z = value
}
/// Constructs a 3D vector with X, Y from a `Vector2` and Z from a scalar.
///
/// - Parameters:
/// - value: The x and y coordinates in 3d space.
/// - z: The z coordinate in 3d space.
public init(_ value: Vector2, _ z: Float) {
x = value.x
y = value.y
self.z = z
}
}
// MARK: - Public methods
public extension Vector3 {
/// Creates a new `Vector3` that contains the cartesian coordinates of a vector specified in barycentric coordinates and relative to a 3d triangle.
/// - Parameters:
/// - value1: The first vector of a 3d triangle.
/// - value2: The second vector of a 3d triangle.
/// - value3: The third vector of a 3d triangle.
/// - amount1: Barycentric scalar **b2** which represents a weighting factor towards the second vector of the 3d triangle.
/// - amount2: Barycentric scalar **b3** which represents a weighting factor towards the third vector of the 3d triangle.
/// - Returns: The cartesian translation of barycentric coordinates.
static func barycentric(_ value1: Vector3, _ value2: Vector3, _ value3: Vector3, amount1: Float, amount2: Float) -> Vector3 {
return Vector3(
MathHelper.barycentric(value1.x, value2.x, value3.x, amount1: amount1, amount2: amount2),
MathHelper.barycentric(value1.y, value2.y, value3.y, amount1: amount1, amount2: amount2),
MathHelper.barycentric(value1.z, value2.z, value3.z, amount1: amount1, amount2: amount2))
}
/// Creates a new `Vector3` that contains the cartesian coordinates of a vector specified in barycentric coordinates and relative to a 3d triangle.
/// - Parameters:
/// - value1: The first vector of a 3d triangle.
/// - value2: The second vector of a 3d triangle.
/// - value3: The third vector of a 3d triangle.
/// - amount1: Barycentric scalar **b2** which represents a weighting factor towards the second vector of the 3d triangle.
/// - amount2: Barycentric scalar **b3** which represents a weighting factor towards the third vector of the 3d triangle.
/// - result: The cartesian translation of barycentric coordinates as an `inout` parameter.
static func barycentric(_ value1: Vector3, _ value2: Vector3, _ value3: Vector3, amount1: Float, amount2: Float, result: inout Vector3) {
result.x = MathHelper.barycentric(value1.x, value2.x, value3.x, amount1: amount1, amount2: amount2)
result.y = MathHelper.barycentric(value1.y, value2.y, value3.y, amount1: amount1, amount2: amount2)
result.z = MathHelper.barycentric(value1.z, value2.z, value3.z, amount1: amount1, amount2: amount2)
}
/// Creates a new `Vector3` that contains the Catmull Rom interpolation of the specified vectors.
/// - Parameters:
/// - value1: The first vector in the interpolation.
/// - value2: The second vector in the interpolation.
/// - value3: The third vector in the interpolation.
/// - value4: The fourth vector in the interpolation.
/// - amount: Weighting factor.
/// - Returns: The result of the interpolation.
static func catmullRom(_ value1: Vector3, _ value2: Vector3, _ value3: Vector3, _ value4: Vector3, amount: Float) -> Vector3 {
return Vector3(
MathHelper.catmullRom(value1.x, value2.x, value3.x, value4.x, amount: amount),
MathHelper.catmullRom(value1.y, value2.y, value3.y, value4.y, amount: amount),
MathHelper.catmullRom(value1.z, value2.z, value3.z, value4.z, amount: amount))
}
/// Creates a new `Vector3` that contains the Catmull Rom interpolation of the specified vectors.
/// - Parameters:
/// - value1: The first vector in the interpolation.
/// - value2: The second vector in the interpolation.
/// - value3: The third vector in the interpolation.
/// - value4: The fourth vector in the interpolation.
/// - amount: Weighting factor.
/// - result: The result of the interpolation as an `inout` parameter.
static func catmullRom(_ value1: Vector3, _ value2: Vector3, _ value3: Vector3, _ value4: Vector3, amount: Float, result: inout Vector3) {
result.x = MathHelper.catmullRom(value1.x, value2.x, value3.x, value4.x, amount: amount)
result.y = MathHelper.catmullRom(value1.y, value2.y, value3.y, value4.y, amount: amount)
result.z = MathHelper.catmullRom(value1.z, value2.z, value3.z, value4.z, amount: amount)
}
/// Round the members of this `Vector3` towards positive infinity.
/// - Returns: The rounded vector
var ceiling: Vector3 {
return Vector3(x.rounded(.up), y.rounded(.up), z.rounded(.up))
}
/// Clamp the components of the vector within a specified range.
/// - Parameters:
/// - min: The minimum component values.
/// - max: The maximum component values.
/// - Returns: The clamped vector.
func clamped(between min: Vector3, and max: Vector3) -> Vector3 {
return Vector3(MathHelper.clamp(x, min: min.x, max: max.x),
MathHelper.clamp(y, min: min.y, max: max.y),
MathHelper.clamp(z, min: min.z, max: max.z))
}
/// Clamp the components of the vector within a specified range.
/// - Parameters:
/// - min: The minimum component values.
/// - max: The maximum component values.
mutating func clamp(between min: Vector3, and max: Vector3) {
x = MathHelper.clamp(x, min: min.x, max: max.x)
y = MathHelper.clamp(y, min: min.y, max: max.y)
z = MathHelper.clamp(z, min: min.z, max: max.z)
}
/// Computes the cross product of two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - Returns: The cross product of the two vectors.
static func cross(_ value1: Vector3, _ value2: Vector3) -> Vector3 {
return Vector3(value1.y * value2.z - value2.y * value1.z,
-(value1.x * value2.z - value2.x * value1.z),
value1.x * value2.y - value2.x * value1.y)
}
/// Computes the cross product of two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - result: The cross product of the two vectors as an `inout` parameter.
static func cross(_ value1: Vector3, _ value2: Vector3, result: inout Vector3) {
result = cross(value1, value2)
}
/// Computes the cross product of this and an other vector.
/// - Parameter other: The second vector.
/// - Returns: The cross product of the two vectors.
func cross(_ other: Vector3) -> Vector3 {
return Vector3.cross(self, other)
}
/// Returns the distance between two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - Returns: The distance between two vectors
static func distance(_ value1: Vector3, _ value2: Vector3) -> Float {
return distanceSquared(value1, value2).squareRoot()
}
/// Returns the distance between two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - result: The distance between two vectors as an `inout` parameter.
static func distance(_ value1: Vector3, _ value2: Vector3, result: inout Float) {
result = distance(value1, value2)
}
/// Returns the squared distance between two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - Returns: The squared distance between two vectors.
static func distanceSquared(_ value1: Vector3, _ value2: Vector3) -> Float {
let v1 = value1.x - value2.x, v2 = value1.y - value2.y, v3 = value1.z - value2.z
return (v1 * v1) + (v2 * v2) + (v3 * v3)
}
/// Returns the squared distance between two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - result: The squared distance between two vectors as an `inout` parameter.
static func distanceSquared(_ value1: Vector3, _ value2: Vector3, result: inout Float) {
result = distanceSquared(value1, value2)
}
/// Returns the dot product of two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - Returns: The dot product of the two vectors.
static func dot(_ value1: Vector3, _ value2: Vector3) -> Float {
return value1.x * value2.x + value1.y * value2.y + value1.z * value2.z
}
/// Returns the dot product of two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - result: The dot product of the two vectors as an `inout` parameter.
static func dot(_ value1: Vector3, _ value2: Vector3, result: inout Float) {
result = dot(value1, value2)
}
/// Returns a new vector that contains the members of the original vector rounded towards negative infinity.
var floor: Vector3 {
return Vector3(x.rounded(.down), y.rounded(.down), z.rounded(.down))
}
/// Creates a new `Vector3` that contains a hermite spline interpolation.
/// - Parameters:
/// - value1: The first position vector.
/// - tangent1: The first tangent vector.
/// - value2: The second position vector.
/// - tangent2: The second tangent vector.
/// - amount: Weighting factor.
/// - Returns: The hermite spline interpolated vector.
static func hermite(_ value1: Vector3, tangent1: Vector3, _ value2: Vector3, tangent2: Vector3, amount: Float) -> Vector3 {
return Vector3(
MathHelper.hermite(value1.x, tangent1: tangent1.x, value2.x, tangent2: tangent2.x, amount: amount),
MathHelper.hermite(value1.y, tangent1: tangent1.y, value2.y, tangent2: tangent2.y, amount: amount),
MathHelper.hermite(value1.z, tangent1: tangent1.z, value2.z, tangent2: tangent2.z, amount: amount)
)
}
/// Creates a new `Vector3` that contains a hermite spline interpolation.
/// - Parameters:
/// - value1: The first position vector.
/// - tangent1: The first tangent vector.
/// - value2: The second position vector.
/// - tangent2: The second tangent vector.
/// - amount: Weighting factor.
/// - result: The hermite spline interpolated vector as an `inout` value.
static func hermite(_ value1: Vector3, tangent1: Vector3, _ value2: Vector3, tangent2: Vector3, amount: Float, result: inout Vector3) {
result = hermite(value1, tangent1: tangent1, value2, tangent2: tangent2, amount: amount)
}
/// The length of this vector.
var length: Float {
return Float(((x * x) + (y * y) + (z * z)).squareRoot())
}
/// The squared length of this vector.
var lengthSquared: Float {
return Float(((x * x) + (y * y) + (z * z)))
}
/// Creates a vector that contains the linear interpolation of the specified vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - amount: Weighting value (between 0.0 and 1.0).
/// - Returns: The result of the linear interpolation of the specified vectors.
static func lerp(_ value1: Vector3, _ value2: Vector3, amount: Float) -> Vector3 {
return Vector3(MathHelper.lerp(value1.x, value2.x, amount: amount),
MathHelper.lerp(value1.y, value2.y, amount: amount),
MathHelper.lerp(value1.z, value2.z, amount: amount))
}
/// Creates a vector that contains the linear interpolation of the specified vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - amount: Weighting value (between 0.0 and 1.0).
/// - result: The result of the linear interpolation of the specified vectors as an `inout` parameter.
static func lerp(_ value1: Vector3, _ value2: Vector3, amount: Float, result: inout Vector3) {
result.x = MathHelper.lerp(value1.x, value2.x, amount: amount)
result.y = MathHelper.lerp(value1.y, value2.y, amount: amount)
result.z = MathHelper.lerp(value1.z, value2.z, amount: amount)
}
/// Creates a vector that contains the linear interpolation of the specified vectors.
/// Uses `MathHelper.lerpPrecise` for the interpolation for less efficient but more accurate results.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - amount: Weighting value (between 0.0 and 1.0).
/// - Returns: The result of the linear interpolation of the specified vectors.
static func lerpPrecise(_ value1: Vector3, _ value2: Vector3, amount: Float) -> Vector3 {
return Vector3(MathHelper.lerpPrecise(value1.x, value2.x, amount: amount),
MathHelper.lerpPrecise(value1.y, value2.y, amount: amount),
MathHelper.lerpPrecise(value1.z, value2.z, amount: amount))
}
/// Creates a vector that contains the linear interpolation of the specified vectors.
/// Uses `MathHelper.lerpPrecise` for the interpolation for less efficient but more accurate results.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - amount: Weighting value (between 0.0 and 1.0).
/// - result: The result of the linear interpolation of the specified vectors as an `inout` parameter.
static func lerpPrecise(_ value1: Vector3, _ value2: Vector3, amount: Float, result: inout Vector3) {
result.x = MathHelper.lerpPrecise(value1.x, value2.x, amount: amount)
result.y = MathHelper.lerpPrecise(value1.y, value2.y, amount: amount)
result.z = MathHelper.lerpPrecise(value1.z, value2.z, amount: amount)
}
/// Returns a vector that contains the maximal component values from two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - Returns: A Vector containing the maximal components from each source vector.
static func max(_ value1: Vector3, _ value2: Vector3) -> Vector3 {
return Vector3(
Swift.max(value1.x, value2.x),
Swift.max(value1.y, value2.y),
Swift.max(value1.z, value2.z)
)
}
/// Returns a vector that contains the maximal component values from two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - result: A Vector containing the maximal components from each source vector as an `inout` parameter.
static func max(_ value1: Vector3, _ value2: Vector3, result: inout Vector3) {
result.x = Swift.max(value1.x, value2.x)
result.y = Swift.max(value1.y, value2.y)
result.z = Swift.max(value1.z, value2.z)
}
/// Returns a vector that contains the minimal component values from two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - Returns: A Vector containing the minimal components from each source vector.
static func min(_ value1: Vector3, _ value2: Vector3) -> Vector3 {
return Vector3(
Swift.min(value1.x, value2.x),
Swift.min(value1.y, value2.y),
Swift.min(value1.z, value2.z)
)
}
/// Returns a vector that contains the minimal component values from two vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - result: A Vector containing the minimal components from each source vector as an `inout` parameter.
static func min(_ value1: Vector3, _ value2: Vector3, result: inout Vector3) {
result.x = Swift.min(value1.x, value2.x)
result.y = Swift.min(value1.y, value2.y)
result.z = Swift.min(value1.z, value2.z)
}
/// Returns a vector containing the normalized vector for a vector.
var normalized: Vector3 {
let factor = 1.0 / self.length
return Vector3(x * factor, y * factor, z * factor)
}
/// Creates a new vector that contains the reflected vector of this vector and the provided normal.
/// - Parameter normal: Reflection normal.
/// - Returns: Reflected vector.
func reflect(by normal: Vector3) -> Vector3 {
let dotProduct = (x * normal.x) + (y * normal.y) + (z * normal.z)
let reflectedX = x - (2.0 * normal.x) * dotProduct
let reflectedY = y - (2.0 * normal.y) * dotProduct
let reflectedZ = z - (2.0 * normal.z) * dotProduct
return Vector3(reflectedX, reflectedY, reflectedZ)
}
/// Returns a vector containing the members of this vector rounded to the nearest integer.
var rounded: Vector3 {
return Vector3(x.rounded(), y.rounded(), z.rounded())
}
/// Creates a vector that contains the cubic interpolation of the specified vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - amount: Weighting value (between 0.0 and 1.0).
/// - Returns: The result of the cubic interpolation of the specified vectors.
static func smoothStep(_ value1: Vector3, _ value2: Vector3, amount: Float) -> Vector3 {
return Vector3(MathHelper.smoothStep(value1.x, value2.x, amount: amount),
MathHelper.smoothStep(value1.y, value2.y, amount: amount),
MathHelper.smoothStep(value1.z, value2.z, amount: amount))
}
/// Creates a vector that contains the cubic interpolation of the specified vectors.
/// - Parameters:
/// - value1: The first vector.
/// - value2: The second vector.
/// - amount: Weighting value (between 0.0 and 1.0).
/// - result: The result of the cubic interpolation of the specified vectors as an `inout` parameter.
static func smoothStep(_ value1: Vector3, _ value2: Vector3, amount: Float, result: inout Vector3) {
result.x = MathHelper.smoothStep(value1.x, value2.x, amount: amount)
result.y = MathHelper.smoothStep(value1.y, value2.y, amount: amount)
result.z = MathHelper.smoothStep(value1.z, value2.z, amount: amount)
}
}
// MARK: - Operators
public extension Vector3 {
/// Inverts the values in the `Vector3`.
///
/// - Parameters:
/// - vector: Source `Vector3` on the right of the negative sign.
///
/// - Returns:Result of the inversion.
@inlinable
static prefix func - (vector: Vector3) -> Vector3 {
return Vector3(-vector.x, -vector.y, -vector.z)
}
/// Adds two vectors.
///
/// - Parameters:
/// - left: Source `Vector3` on the left of the plus sign.
/// - right: Source `Vector3` on the right of the plus] sign.
///
/// - Returns:Sum of the vectors.
@inlinable
static func + (left: Vector3, right: Vector3) -> Vector3 {
return Vector3(left.x + right.x, left.y + right.y, left.z + right.z)
}
/// Subtracts a `Vector3` from a `Vector3`.
///
/// - Parameters:
/// - left: Source `Vector3` on the left of the minus sign.
/// - right: Source `Vector3` on the right of the minus sign.
///
/// - Returns:Result of the vector subtraction.
@inlinable
static func - (left: Vector3, right: Vector3) -> Vector3 {
return Vector3(left.x - right.x, left.y - right.y, left.z - right.z)
}
/// Multiplies the components of two `Vector3`s by each other.
///
/// - Parameters:
/// - left: Source `Vector3` on the left of the multiplication sign.
/// - right: Source `Vector3` on the right of the multiplication sign.
///
/// - Returns:Result of the vector multiplication.
@inlinable
static func * (left: Vector3, right: Vector3) -> Vector3 {
return Vector3(left.x * right.x, left.y * right.y, left.z * right.z)
}
/// Multiplies the components of a`Vector3` by a scalar.
///
/// - Parameters:
/// - left: Source `Vector3` on the left of the multiplication sign.
/// - right: Scalar value on the right of the multiplication sign.
///
/// - Returns:Result of the vector multiplication by a scalar.
@inlinable
static func * (left: Vector3, right: Float) -> Vector3 {
return Vector3(left.x * right, left.y * right, left.z * right)
}
/// Multiplies the components of a`Vector3` by a scalar.
///
/// - Parameters:
/// - left: Scalar value on the left of the multiplication sign.
/// - right: Source `Vector3` on the right of the multiplication sign.
///
/// - Returns:Result of the vector multiplication by a scalar.
@inlinable
static func * (left: Float, right: Vector3) -> Vector3 {
return Vector3(left * right.x, left * right.y, left * right.z)
}
/// Divides the components of two `Vector3`s by each other.
///
/// - Parameters:
/// - left: Source `Vector3` on the left of the division sign.
/// - right: Source `Vector3` on the right of the division sign.
///
/// - Returns:Result of the vector division.
@inlinable
@inline(__always)
static func / (left: Vector3, right: Vector3) -> Vector3 {
return Vector3(left.x / right.x, left.y / right.y, left.z / right.z)
}
/// Divides the components of a`Vector3` by a scalar.
///
/// - Parameters:
/// - left: Source `Vector3` on the left of the division sign.
/// - right: Scalar value on the right of the division sign.
///
/// - Returns:Result of the vector division by a scalar.
@inlinable
@inline(__always)
static func / (left: Vector3, right: Float) -> Vector3 {
let factor = 1.0 / right
return Vector3(left.x * factor, left.y * factor, left.z * factor)
}
}
|
import Image from 'next/future/image'
import { Container } from '@/components/Container'
import backgroundImage from '@/images/background-faqs.jpg'
const faqs = [
[
{
question: 'What exactly is Userowl?',
answer:
'It’s a widget that you can place on your website or web application. Your users or internal UAT team can use this widget to give feedback on your product.',
},
{
question: 'How long does it take to add the widget script to my application?',
answer:
'It usually takes only 5-10 minutes to set up and you are ready to go. We have guides on common frameworks and CMS systems.',
},
{
question: 'Can I customize how the widget looks on our site so that it fits our brand guidelines?',
answer:
'Yes, you can customize the fields and style of the widget easily in a WYSIWYG editor.',
},
],
[
{
question: 'How do I see the collected feedback and bugs?',
answer:
'You see bugs, feature requests, or general feeedback on Userowl application. You can organize the way you manage feedback with many of the available views like inbox view, kanban view, list view, etc.',
},
{
question:
'Do I receive notifications when users report a new bug or feature?',
answer:
'Yes, you can configure to set who receives email notifications on your team.',
},
{
question:
'Can I have multiple users that are in my organization?',
answer:
'Yes, you can invite your team members and assign roles to them. With the help of the product, QA, and development teams on board you can assign issues and track reported feedback.',
},
],
[
{
question: 'How do I access Userowl application?',
answer:
'Userowl is a SaaS solution, so you and your team can access it on your browser of choice. It is responsive so you can do urgent tasks with your smartphone on the go.',
},
{
question: 'What is the pricing model on Userowl?',
answer: 'Userowl is a subscription-based service. You can select the appropriate tier for your use and subscribe to a monthly or yearly plan. We also offer free trials.',
},
{
question: 'How is my data managed?',
answer:
'At Userowl we prioritize data safety and ownership from the start. We comply with GDPR, CCPA, and KVKK. You can customize which personal information to take and you can export your data anytime because you own your data. You can also comply with your users’ requests to manage their data.',
},
],
]
export function Faqs() {
return (
<section
id="faq"
aria-labelledby="faq-title"
className="relative overflow-hidden bg-slate-50 py-20 sm:py-32"
>
<Image
className="absolute top-0 left-1/2 max-w-none translate-x-[-30%] -translate-y-1/4"
src={backgroundImage}
alt=""
width={1558}
height={946}
unoptimized
/>
<Container className="relative" itemScope itemType="https://schema.org/FAQPage">
<div className="mx-auto max-w-2xl lg:mx-0">
<h2
id="faq-title"
className="font-display text-3xl tracking-tight text-slate-900 sm:text-4xl"
>
Frequently asked questions
</h2>
<p className="mt-4 text-lg tracking-tight text-slate-700">
If you can’t find what you’re looking for, email our support team
and we will get back to you.
</p>
</div>
<ul
role="list"
className="mx-auto mt-16 grid max-w-2xl grid-cols-1 gap-8 lg:max-w-none lg:grid-cols-3"
>
{faqs.map((column, columnIndex) => (
<li key={columnIndex}>
<ul role="list" className="flex flex-col gap-y-8">
{column.map((faq, faqIndex) => (
<li key={faqIndex} itemScope itemProp="mainEntity" itemType="https://schema.org/Question">
<h3 className="font-display text-lg leading-7 text-slate-900" itemProp="name">
{faq.question}
</h3>
<div itemScope itemProp="acceptedAnswer" itemType="https://schema.org/Answer">
<p className="mt-4 text-sm text-slate-700" itemProp="text">{faq.answer}</p>
</div>
</li>
))}
</ul>
</li>
))}
</ul>
</Container>
</section>
)
}
|
package com.callor.apps.service;
import java.util.Random;
// EvenServiceV1 코드를 복사해온것처럼 사용하겠다. 필요한 일부만 내 방식대로 변환해서 사용하고 싶다.
/*
* 자바프로그래밍에서 상속
* V2 클래스에서는 V1클래슬 상속했다.
* v1에 작성한(선언한) 변수, method 코드를 그대로 이어받아서 사용하겠다.
*
* V1에 작성된 method들의 코드를 그대로 사용하면서 일부 method의 코드를 변경, 확장, 기능개선을 하여
* 내 프로젝트에 적용하겠다. => 상속의 가장 큰 이유
*/
public class EvenServiceV2 extends EvenServiceV1 {
public EvenServiceV2() {
intNum = new int[100];
intSum = 0;
}
// 객체지향 상속의 특징을 잘 표현한 부분
public void printEven() {
int nCount = 0;
for (int i = 0; i < intNum.length; i++) {
if (intNum[i] % 2 == 0) {
System.out.printf("%4d",intNum[i] + "는 짝수");
nCount++;
if(nCount % 5 == 0) {
System.out.println();
}
}
}
}
}
|
#!/usr/bin/node
// Define a recursive function to compute factorial
function factorial (n) {
// Base case: factorial of 0 is 1
if (isNaN(n) || n < 0) {
return 1;
} else if (n === 0) {
return 1;
} else {
// Recursive case: n * factorial(n-1)
return n * factorial(n - 1);
}
}
// Get the first argument passed to the script
const arg = process.argv[2];
const numInt = parseInt(arg);
// Calculate the factorial using the factorial function
const result = factorial(numInt);
console.log(result);
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Basket, AsteroidsList } from '@/components'
import { OptionDistance } from '@/components/OptionDistance/OptionDistance'
import { useGlobalContext } from '@/features/Context/store'
import { fetchAsteroidList } from '@/shared/api/routes/asteroids'
import { formatAsteroidData } from '@/shared/utils/formatAsteroidData'
import { AsteroidData, ResponseData } from '@/shared/interfaces/interfaces'
import s from './homePage.module.scss'
export const HomePage = () => {
const start_date = useMemo(() => {
const date = new Date()
return date.toISOString().slice(0, 10)
}, [])
const { setAsteroidData, asteroidData, cartItemsId } = useGlobalContext()
const [dataFromServer, setDataFromServer] = useState<ResponseData>()
const [counter, setCounter] = useState(0)
const [dateParam, setDateParam] = useState<string>(start_date)
const scrollHandler = useCallback((e: Event) => {
if (
(e.target as Document).documentElement.scrollHeight -
((e.target as Document).documentElement.scrollTop +
window.innerHeight) <
1
) {
setCounter(prev => (prev += 1))
}
}, [])
useEffect(() => {
window.addEventListener('scroll', scrollHandler)
return () => {
window.removeEventListener('scroll', scrollHandler)
}
}, [scrollHandler])
useEffect(() => {
const date = new Date()
date.setDate(date.getDate() + counter)
const formattedDate = date.toISOString().slice(0, 10)
setDateParam(formattedDate)
}, [counter])
useEffect(() => {
fetchAsteroidList(dateParam)
.then(res => {
setDataFromServer(res.data)
})
.catch(error => {
if (error.response) {
console.log(error.response.data)
} else if (error.request) {
console.log(error.request)
}
})
.finally()
}, [dateParam, setDataFromServer])
useEffect(() => {
if (dataFromServer) {
const concactArray = Object.values(
dataFromServer?.near_earth_objects || {}
).flat()
const sortedArray = concactArray.sort((a, b) =>
a.close_approach_data[0].close_approach_date >
b.close_approach_data[0].close_approach_date
? 1
: -1
)
setAsteroidData(prevArr => [
...prevArr,
...sortedArray.filter(
newObj => !prevArr.some(obj => obj.id === newObj.id)
),
])
}
}, [dataFromServer, setAsteroidData])
const newFormattedAsteroidsData = asteroidData?.map(formatAsteroidData)
return (
<>
<div className={s.container}>
<h1 className={s.title}>Ближайшие подлёты астероидов</h1>
<OptionDistance />
<AsteroidsList asteroids={newFormattedAsteroidsData} />
</div>
<Basket itemCount={cartItemsId.length} />
</>
)
}
|
import chess
import pandas as pd
import numpy as np
import gc
import re
import random
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
import time
NUM_POSITIONS = 50000 # Change this to specify the number of chess positions for training
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
letter_2_num = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7}
num_2_letter = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h'}
chess_data = pd.read_csv("data/filtered_chess_games.csv")
def board_2_rep(board):
pieces = ['p', 'r', 'n', 'b', 'q', 'k']
layers = []
for piece in pieces:
layers.append(create_rep_layer(board, piece))
board_rep = np.stack(layers)
return board_rep
def create_rep_layer(board, piece_type):
s = str(board)
s = re.sub(f"[^{piece_type}{piece_type.upper()} \n]", '.', s)
s = re.sub(f"{piece_type}", "-1", s)
s = re.sub(f"{piece_type.upper()}", "1", s)
s = re.sub("\.", "0", s)
board_mat = []
for row in s.split("\n"):
row = row.split(" ")
row = [int(x) for x in row]
board_mat.append(row)
return np.array(board_mat)
def create_move_list(s):
s = str(s)
s = re.sub(r"[\[\]']", '', s)
moves = re.sub('\d*\. ','',s).split(' ')[:-1]
if moves[-1] == '':
moves.pop()
return moves
def move_2_rep(move, board):
try:
board.push_san(move).uci()
except:
return None
move = str(board.pop())
from_output_layer = np.zeros((8,8))
from_row = 8 - int (move[1])
from_column = letter_2_num [move[0]]
from_output_layer [from_row,from_column] = 1
to_output_layer = np.zeros((8,8))
to_row = 8 - int(move[3])
to_column = letter_2_num[move[2]]
to_output_layer [to_row, to_column] = 1
return np.stack([from_output_layer, to_output_layer])
class ChessDataset(Dataset):
def __init__(self, games):
super(ChessDataset, self).__init__()
self.games = games
def __len__(self):
return NUM_POSITIONS
def __getitem__(self, index):
while True:
game_i = np.random.randint(self.games.shape[0])
random_game = chess_data['AN'].values[game_i]
moves = create_move_list(random_game)
if len(moves) < 2:
continue
game_state_i = np.random.randint(len(moves)-1)
next_move = moves[game_state_i]
moves = moves[:game_state_i]
board = chess.Board()
for move in moves:
try:
board.push_san(move)
except:
continue
x = board_2_rep(board)
y = move_2_rep(next_move, board)
if y is None:
continue
if game_state_i % 2 == 1:
x *= -1
return x, y
data_train = ChessDataset(chess_data)
data_train_loader = DataLoader(data_train, batch_size=250, shuffle=True, drop_last=True)
class module(nn.Module):
def __init__(self, hidden_size):
super(module, self).__init__()
self.conv1 = nn.Conv2d(hidden_size, hidden_size, 3, stride=1, padding=1)
self.conv2 = nn.Conv2d(hidden_size, hidden_size, 3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(hidden_size)
self.bn2 = nn.BatchNorm2d(hidden_size)
self.activation1 = nn.ReLU()
self.activation2 = nn.ReLU()
def forward(self, x):
x_input = torch.clone(x)
x = self.conv1(x)
x = self.bn1(x)
x = self.activation1(x)
x = self.conv2(x)
x = self.bn2(x)
x = x + x_input
x = self.activation2(x)
return x
class ChessNet(nn.Module):
def __init__(self, hidden_layers=4, hidden_size=200):
super(ChessNet, self).__init__()
self.hidden_layers = hidden_layers
self.input_layer = nn.Conv2d(6, hidden_size, 3, stride=1, padding=1)
self.module_list = nn.ModuleList([module(hidden_size) for i in range(hidden_layers)])
self.output_layer = nn.Conv2d(hidden_size, 2, 3, stride=1, padding=1)
def forward(self, x):
x = self.input_layer(x)
x = F.relu(x)
for i in range(self.hidden_layers):
x = self.module_list[i](x)
x = self.output_layer(x)
return x
metric_from = nn.CrossEntropyLoss()
metric_to = nn.CrossEntropyLoss()
model = ChessNet()
model.to(device)
if __name__ == "__main__":
# Training loop
num_epochs = 10
optimizer = torch.optim.Adam(model.parameters(), lr=0.0015, weight_decay=0.0001)
for epoch in range(num_epochs):
total_loss = 0.0
# Use tqdm to visualize progress
with tqdm(data_train_loader, unit="batch") as t:
for batch_idx, (x, y) in enumerate(t):
x = x.float().to(device)
y = y.float().to(device)
# Forward pass
output = model(x)
# Calculate loss
loss_from = metric_from(output[:, 0, :], y[:, 0, :])
loss_to = metric_to(output[:, 1, :], y[:, 1, :])
loss = loss_from + loss_to
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item()
# Update tqdm progress bar
t.set_postfix(loss=total_loss / (batch_idx + 1)) # Update loss in progress bar
# Print epoch loss
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {total_loss / len(data_train_loader):.4f}")
torch.save(model.state_dict(), "model.pth")
print("Model saved!")
|
This is an attempt to create more structure for LAMMPS-Tools.
The focus will be much more around the C++ lib and much less around Python.
All data types will be pure C++ and C++ only. Manipulation of them from
Python will only be by passing a pointer to said data structures around to
a C-like interface. This way, the library can also be extended to other
scripting languages and it allows me to program more in C++, in which I am
much more comfortable. It also enforces better thinking about which parts to
expose and which parts not to, which should lead to better encapsulation.
So, the basic design of the code will be like this:
(exposed by) (called from)
C++ backend --------------> C interface --------------> Scripting languages
Here are some examples of functionality in the three domains:
C++ backend | C interface | Scripting languages
--------------------+-----------------------+-------------------------
neighborize | lt_neighborize(...) | Created by pybind11,
| | cffi, whatever.
NOTE: If you simply want to _update_ a working lammps-tools to
a new version, this procedure is not necessary. Instead, follow
the steps described in Updating lammps-tools.
There are two ways right now of building lammps-tools:
CMake or plain old make. These instructions only really
work on Linux or Mac OS X, and probably BSD, not Windows.
There are some prerequisites:
- Python 3 (>=3.4 seems to work)
- CMake 2.8 or later (if you want to build using CMake)
- A C++11-capable compiler (gcc >= 4.8 works)
In the guide shell commands are prefixed with a "$" and
should be run as is (without the "$" that is).
0) This section requires that you have CMake installed.
1) Follow these instructions to build the C++ library:
1a) $ cd lammps-tools-v2
1b) $ mkdir build
1c) $ cmake ../
Optional: Configure your build. If not necessary,
continue with 2).
1d) $ ccmake ../
This opens a graphical interface in your terminal. In it,
you can set some options. For older compilers, you'll want
to disable USE_EXCEPTIONS and enable LEGACY_COMPILER.
If the found compiler version is lower than 4.8, you need
to change it to point to a higher version. Follow these steps:
1d1) In ccmake, press t to enable "advanced options"
1d2) Select CMAKE_CXX_COMPILER
1d3) Press enter to edit. Change it to point to a modern C++
compiler that fully supports C++11.
Press Enter after you're done editting.
1d4) Press c twice, and then g.
1d5) Press q to leave ccmake.
2) $ make
This will build the library. You can speed it up by
adding "-j<a number>" to build in parallel:
$ make -j4
3) After building, copy the library to the lammps-tools-v2 dir.
On Linux:
$ cp liblammpstools.so ../
On Mac OS X:
$ cp liblammpstools.dylib ../
Now we need to build the Python bindings.
4) $ cd ../
5) $ cd foreign_interfaces/python3/
6) $ mkdir build
7) $ cd build
8) $ cmake ../
CMake might fail to find a compiler that's recent enough.
If so, follow these steps. Else, continue at 8e).
8a) $ ccmake ../
8b) Press t
8c) Change "CMAKE_CXX_COMPILER" to a C++11-capable one.
In particular, you need to pick one that supports pybind11
(see https://github.com/pybind/pybind11, "Supported compilers").
8d) Press c twice.
8e) CMake might also fail to find Python, especially on clusters.
If so, it will print a warning:
"SEND_WARNING Could not automatically find Python! Set it "
"yourself in advanced options!".
If it finds Python3, continue at step 9). Else, follow these steps:
8f) $ ccmake ../
8g) Press t
8f) Change PYTHON_INCLUDE_DIR to a Python 3 include directory
(one that contains Python.h)
8g) Change PYTHON_LIBRARY to a Python 3 library (libpython3.so (Linux)
or libpython3.dylib (Mac OS X))
8h) Press c twice. As of writing, CMAKE just repeats the aforementioned
warning; ignore it. I need to fix that later. :$
8i) Press g.
9) $ make
10) $ cp *_.so ../lammpstools
11) Now you're all set. lammps-tools-v2/foreign_interfaces/python3 now
contains a functional Python package called "lammpstools". You can
test using it bu running Python3 and importing the module. Make sure
that you use the same interpreter version as what you compiled against.
That is, if in step 8 you compiled against libpython3.5m.so, your
Python interpreter version needs to be 3.5 too.
12) $ cd ../
13) $ python3 -c "import lammpstools"
If this command executes without errors, you can definitely use
lammpstools with your interpreter. To be able to import it from
anywhere, just make sure the module is in your PYTHONPATH. On Linux,
if you use bash, this does the trick:
$ echo 'export PYTHONPATH=$PYTHONPATH":'$( pwd )'"' >> ~/.bashrc
On Mac OS X, this works:
$ echo 'export PYTHONPATH=$PYTHONPATH":'$( pwd )'"' >> ~/.bash_profile
Alternatively, you can copy lammpstools to a location that is already
in the python path. This is more nice for administrators. Replace
"<some dir that is in PYTHONPATH>" with a dir that is in PYTHONPATH:
$ cp -r lammpstools <some dir that is in PYTHONPATH>
14) Now you're all set. You can just use "import lammpstools"
in any python3 script and it should work.
1) If you want to use GNU make, you probably already know what
you're doing and you don't need instructions. :)
If you already have a working instance of lammps-tools and simply
want to update (to get the latest features), follow these steps:
1) Go to the lammps-tools-v2 dir.
2) $ git pull
3) $ cd build
4) $ make
5) On Linux: $ cp liblammpstools.so ../
On Mac OS X: $ cp liblammpstools.dylib ../
6) cd ../
7) cd foreign_interfaces/python3/build
8) make
9) cp *_.so ../lammpstools
Done.
|
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
import { HttpHeaders, HttpParams } from '@angular/common/http';
import { GoogleAuthService } from 'ng-gapi';
import GoogleUser = gapi.auth2.GoogleUser
import { MyCookieService } from '../cookie.service'
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-log-in',
templateUrl: './log-in.component.html',
styleUrls: ['./log-in.component.css']
})
export class LogInComponent implements OnInit {
constructor(private apiService: ApiService, private googleAuth: GoogleAuthService, private cookieServ: MyCookieService) { }
ngOnInit() { }
getCookie() {
return this.cookieServ.getCookie()
}
getAuthToken() {
return sessionStorage.getItem('token')
}
getInfoSession() {
return JSON.parse(sessionStorage.getItem('info'))
}
getMessagesSession() {
return JSON.parse(sessionStorage.getItem('messages'))
}
getInfo(): void {
let body = new HttpParams().set('token', this.getAuthToken()).set('cookie', this.getCookie());
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.apiService.getInfoService(body, headers).subscribe((data) => {
sessionStorage.setItem('info', JSON.stringify(data));
})
}
signIn() {
this.googleAuth.getAuth()
.subscribe((auth) => {
auth.signIn().then(res => this.signInSuccessHandler(res)
)
});
}
onSubmit(form: NgForm) {
this.getMessages(form)
}
getMessages(form) {
let body = new HttpParams().set('token', this.getAuthToken()).set('cookie', this.getCookie()).set('keep', form.value.keep);
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers = headers.append('Access-Control-Allow-Origin', '*');
headers = headers.append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
this.apiService.getMessagesService(body, headers).subscribe((data) => {
sessionStorage.setItem('messages', JSON.stringify(data));
})
}
private signInSuccessHandler(res: GoogleUser) {
sessionStorage.setItem('token', res.getAuthResponse().access_token);
window.location.reload();
}
}
|
import type { ITag } from '@/components/molecules/TagsInput'
import type { StateCreator } from 'zustand'
import { create } from 'zustand'
export type UserTeamType = {
id: number
team: {
id: number
name: string
}
}
interface UserSlice {
user_id: number
first_name: string
last_name: string
email: string
avatar: string
slug: string
google_id: string
teams: UserTeamType[]
watchedTags: ITag[]
updated_at: string
role?: string
permissions?: Array<{
name: string
category: string
}>
setUserID: (
user_id: number,
first_name: string,
last_name: string,
email: string,
avatar: string,
slug: string,
google_id: string,
teams: UserTeamType[],
watchedTags: ITag[],
updated_at: string,
role: string,
permissions: Array<{
name: string
category: string
}>
) => void
updateProfile: (first_name: string, last_name: string, avatar: string) => void
setWatchedTags: (input: ITag[]) => void
}
const createUserSlice: StateCreator<UserSlice> = (set) => ({
user_id: 0,
first_name: '',
last_name: '',
email: '',
avatar: '',
slug: '',
google_id: '',
teams: [],
watchedTags: [],
updated_at: '',
role: '',
permissions: [],
setUserID: (
user_id,
first_name,
last_name,
email,
avatar,
slug,
google_id,
teams,
watchedTags,
updated_at,
role,
permissions
) => {
set(() => ({
user_id,
first_name,
last_name,
email,
avatar,
slug,
google_id,
teams,
watchedTags,
updated_at,
role,
permissions,
}))
},
updateProfile: (first_name, last_name, avatar) => {
set((state) => ({
...state,
first_name,
last_name,
avatar,
}))
},
setWatchedTags: (input: ITag[]) => {
set((state) => ({
...state,
watchedTags: input,
}))
},
})
export const useBoundStore = create<UserSlice>()((...a) => ({
...createUserSlice(...a),
}))
|
import * as React from 'react';
import {Text, StyleSheet, SafeAreaView, ScrollView, View} from 'react-native';
import CartItem from '../components/CartItem';
import {useCart} from '../shared/contexts/CartContext';
import {Dimensions} from 'react-native';
function Cart(): JSX.Element {
const cartProducts = useCart();
const windowHeight = Dimensions.get('window').height;
function selectedCarsString(cartLength: number) {
if (cartLength === 1) {
return `${cartLength} Carro selecionado:`;
} else if (cartLength === 0) {
return 'Nenhum carro selecionado';
} else if (cartLength > 1) {
return `${cartLength} Carros selecionados:`;
}
return '';
}
return (
<SafeAreaView>
<ScrollView>
<View style={[styles.cartWrapper, {minHeight: windowHeight}]}>
<Text testID="selectedCarsLabel" style={styles.selectedCars}>
{selectedCarsString(cartProducts.length)}
</Text>
{cartProducts.map(product => {
return <CartItem key={product._id} product={product} />;
})}
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
cartWrapper: {flex: 1, backgroundColor: 'white', padding: 20},
selectedCars: {fontSize: 22, fontWeight: '800', color: 'black'},
});
export default Cart;
|
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/models/allProducts/all_products.dart';
import '../../data/services/homeServeice/home_serveices.dart';
part 'get_all_prouducts_state.dart';
class GetAllProuductsCubit extends Cubit<GetAllProuductsState> {
GetAllProuductsCubit(this.homeServeices) : super(GetAllProuductsInitial());
final HomeServeices homeServeices;
Future<void> getAllproducts() async {
emit(GetAllProuductsLoading());
var result = await homeServeices.getAllproducts();
result.fold(
(failure) {
emit(GetAllProuductsFailure(failure.errMessage));
},
(product) {
emit(GetAllProuductsSuccess(product));
},
);
}
}
|
import React, { useState, useEffect } from 'react'
import axios from 'axios';
import { Box, IconButton, Paper } from '@mui/material'
import ArrowBackIcon from '@mui/icons-material/ArrowBack'
import { Match, Ticket, MAIN_COLOR, User, DEBUG_SERVER } from '../utils/interfaces'
import TopBar from './TopBar'
import InfoMessages from './InfoMessages'
import MatchesTable from './MatchesTable'
import TicketsTable from './TicketsTable'
import SportsSoccerIcon from '@mui/icons-material/SportsSoccer'
import { UserContext } from '../utils/userContext';
const MainPage: React.FC = () => {
const userContext = new UserContext();
const [mainView, setMainView] = useState<'MATCHES'|'TICKETS'>('MATCHES');
const [matches, setMatches] = useState<Match[]>([]);
const [currentMatchTickets, setCurrentMatchTickets] = useState<Ticket[]>([]);
const [currentMatch, setCurrentMatch] = useState<Match>();
const [loggedUser, setLoggedUser] = useState<User | null>(userContext.getCurrentUser());
useEffect(() => {
setLoggedUser(loggedUser)
userContext.setCurrentUser(loggedUser)
}, [loggedUser]);
useEffect(() => {
const fetchMatches = async () => {
try {
let response = null
if (!DEBUG_SERVER) response = await axios.get('https://www.iunticket.it/api/match');
else response = await axios.get('http://localhost:31491/api/match');
setMatches(response.data);
} catch (error) {
console.error('Errore nel recupero delle partite:', error);
}
};
fetchMatches();
}, []);
const handleLoadTickets = async (matchID: number) => {
try {
let response = null
if (!DEBUG_SERVER) response = await axios.get('https://www.iunticket.it/api/tickets?matchID='+matchID);
else response = await axios.get('http://localhost:31491/api/tickets?matchID='+matchID);
setCurrentMatchTickets(response.data);
const currMatch = matches.filter(el=>el.ID === matchID)
if (currMatch.length > 0) setCurrentMatch(currMatch[0])
setMainView('TICKETS')
} catch (error) {
console.error('Errore nel recupero dei biglietti:', error);
}
}
return (
<Box>
<TopBar loggedUser={loggedUser} setLoggedUser={setLoggedUser}/>
<Paper style={{padding:"15px"}}>
{mainView === 'TICKETS' &&
<Box fontWeight="bold" style={{color:MAIN_COLOR}} display="flex" alignItems="center" marginBottom="20px">
<IconButton onClick={() => {setMainView('MATCHES'); setCurrentMatch(undefined)}} style={{marginTop:"10px", color:MAIN_COLOR}} aria-label="Back">
<ArrowBackIcon />
<Box fontWeight="bold" fontSize="18px" style={{color: "black"}}>
{'Torna alla lista partite'}
</Box>
</IconButton>
</Box>
}
{currentMatch &&
<Box fontWeight="bold" fontSize="25px" style={{color: "black", marginBottom:"20px"}} display="flex" alignItems="center" >
<SportsSoccerIcon fontSize="inherit" color="primary" style={{marginRight:"10px"}} />
{currentMatch.partita + ' - ' + currentMatch.data}
</Box>
}
{mainView === 'MATCHES' ?
<MatchesTable matches={matches} handleLoadTickets={handleLoadTickets}></MatchesTable>
:
<TicketsTable tickets={currentMatchTickets} setTickets={setCurrentMatchTickets} matches={matches} setMatches={setMatches} currentMatch={currentMatch} loggedUser={loggedUser}></TicketsTable>
}
{mainView === 'MATCHES' &&
<Box style={{marginTop:'15px'}}>
<InfoMessages/>
</Box>}
</Paper>
</Box>
);
};
export default MainPage;
|
package com.starter.starter.service;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.starter.starter.model.*;
import com.starter.starter.repository.*;
@Configuration
public class DataInitialization {
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
private PasswordEncoder bcryptEncoder;
@EventListener(ApplicationReadyEvent.class)
public void initializeData() {
/* Create admin */
if (!userRepository.existsByUsername("admin")) {
User admin = new User("admin", "[email protected]", bcryptEncoder.encode("adminpassword"));
userRepository.save(admin);
}
/* Create roles */
if (!roleRepository.existsByName("User") && !roleRepository.existsByName("Admin") && !roleRepository.existsByName("Moderator")) {
User admin = userRepository.findByUsername("admin").get();
Role role1 = new Role("User");
Role role2 = new Role("Admin");
Role role3 = new Role("Moderator");
roleRepository.save(role1);
roleRepository.save(role2);
roleRepository.save(role3);
Set<Role> roles = new HashSet<>();
roles.add(role1);
roles.add(role2);
roles.add(role3);
admin.setRoles(roles);
userRepository.save(admin);
}
}
}
|
#include <iostream>
#include <vector>
#include <list>
// hashtable function
class Ds_hashset{
private:
int table_size = 100;
float occ = 50;
int kmer;
int keys;
std::vector<std::pair<int, char>> table;
public:
// constructor
Ds_hashset(int t_size, float occup, int k);
// accesors
int getTsize() const{
return table_size;
}
float getOcc() const{
return occ;
}
int getKmer() const{
return kmer;
}
std::pair<int, char> getKey(int index){
return table[index];
}
// other functions
int hashFunction(int key);
void insert(int key, char);
void resize_table(int newSize);
};
// implementing functions
// constructor
Ds_hashset::Ds_hashset(int t_size, float occup, int k){
table_size = t_size;
occ = occup;
kmer = k;
keys = 0;
// intially set the table size
table[table_size];
}
// resizes the table by creating a new table and readding the elements back
void Ds_hashset::resize_table(int newSize){
std::vector<std::pair<int, char>> newTable = table;
newTable.clear();
newTable.resize(newSize);
// loop through new table and bring back all the previous elements
for (unsigned i = 0; i < newTable.size()-1; i++){
int index = hashFunction(newTable[i].first) % newSize;
newTable[index] = newTable[i];
}
table_size = newSize;
table = newTable;
}
// return the postion in the hashtable
int Ds_hashset::hashFunction(int key){
// first check to see if size over occupancy
// uses resize function if table needs to be resized
if (keys >= table.size() * occ){
resize_table(table.size() * 2 + 1);
}
return key % table_size;
}
// inserts a key into table
void Ds_hashset::insert(int key, char val){
int hashval = hashFunction(key);
std::pair<int, char> cell = table[hashval];
bool keyExist = false;
// loop through table to see first if the exists
for (unsigned int i = 0; i < table.size(); i++){
if (table[i].second == val){
keyExist = true;
table[i].second = val;
break;
}
}
// else simply place into table
if (!keyExist){
std::pair<int, char> pair;
pair.first = key; pair.second = val;
cell = pair;
keys+=1;
}
}
|
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">Staff Employment History Details</div>
<div class="card-body">
<div class="form-row mt-sm-2">
<div class="col-sm-3">
<button type="button" wire:click.prevent="" class="btn btn-success mt-3" data-toggle="modal" data-target="#createModal">Add Staff Employment History details</button>
</div>
<div class="col-sm-3">
<button type="button" wire:click="" class="btn btn-success mt-3" data-toggle="modal" data-target="#uploadExcelModal">Upload Employment History Details from Excel</button>
</div>
</div>
@if (session()->has('message'))
<div class="alert alert-success" style="margin:4px;">
{{ session('message') }}
</div>
@endif
@if (session()->has('errormessage'))
<div class="alert alert-danger" style="margin:4px;">
{{ session('errormessage') }}
</div>
@endif
@if (session()->has('errorsImport'))
<div class="alert alert-danger" role="alert" id="scrollableAlertDiv">
<strong>Errors:</strong>
Rows that could not be inserted
<ul>
@foreach($errorsImport as $errorsImport)
<li>{{ $errorsImport[0]}}</li>
@endforeach
</ul>
</div>
@endif
<!--add details model start-->
<div wire:ignore.self id="createModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="createModalLabel">Employment History Details Form</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true close-btn">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="exampleFormControlInput3">Select Staff<span class="mustFill">*</span></label>
<select class="form-control" id="exampleFormControlInput3" wire:model="cid">
<option value="">Select</option>
@foreach($Staff_in_list as $staff)
<option value='{{ $staff->cid}}'>{{ $staff->Name}}</option>
@endforeach
</select>
@error('cid')<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="exampleFormControlInput3">School Served<span class="mustFill">*</span></label>
<input type="text" wire:model="school" class="form-control" id="exampleFormControlInput3">
@error('school')<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="exampleFormControlInput3">Dzongkhag<span class="mustFill">*</span></label>
<select class="form-control" id="exampleFormControlInput3" wire:model="dzongkhag_served">
<option value="">Select</option>
<option value="Bumthang">Bumthang</option>
<option value="Chhukha">Chhukha</option>
<option value="Dagana">Dagana</option>
<option value="Gasa">Gasa</option>
<option value="Haa">Haa</option>
<option value="Lhuentse">Lhuentse</option>
<option value="Mongar">Mongar</option>
<option value="Paro">Paro</option>
<option value="Pema Gatshel">Pema Gatshel</option>
<option value="Punakha">Punakha</option>
<option value="Samdrup Jongkhar">Samdrup Jongkhar</option>
<option value="Samtse">Samtse</option>
<option value="Sarpang">Sarpang</option>
<option value="Tashi Yangtse">Tashi Yangtse</option>
<option value="Trashigang">Trashigang</option>
<option value="Trongsa">Trongsa</option>
<option value="Tsirang">Tsirang</option>
<option value="Wangdue Phodrang">Wangdue Phodrang</option>
<option value="Zhemgang">Zhemgang</option>
</select>
@error('dzongkhag_served')<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="exampleFormControlInput3">From<span class="mustFill">*</span></label>
<input type="date" wire:model="start_date" class="form-control" id="exampleFormControlInput3">
@error('start_date')<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="exampleFormControlInput3">To<span class="mustFill">*</span></label>
<input type="date" wire:model="end_date" class="form-control" id="exampleFormControlInput3">
@error('end_date')<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div wire:loading.table wire:target="store">
Saving you data.....
<div class="la-line-scale la-dark la-x">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<button wire:click.prevent="store()" class="btn btn-success" wire:loading.attr="disabled">Save</button>
<button type="button" class="btn btn-secondary close-btn" data-dismiss="modal" wire:loading.attr="disabled">Close</button>
</form>
</div>
</div>
</div>
</div>
<!--end of model to add staff details-->
<!--model for excel file upload-->
<div wire:ignore.self id="uploadExcelModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content" id="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="createModalLabel">Upload an excel file</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true close-btn">×</span>
</button>
</div>
<div class="modal-body">
<form wire:submit.prevent="save">
@csrf
<table>
<tr><td>
<div class="form-group">
<input type="file" id="fileControl" wire:model="excelfile" />
@error('excelfile')<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div wire:loading.table wire:target="excelfile">
uploading file....
<div style="color: #fdaed4" class="la-line-scale">
<div wire:loading.table wire:target="importExcel">
Importing from excel file.......
<div style="color: #fdaed4" class="la-line-scale">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
</td>
<td>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<button wire:click.prevent="importExcel()" class="btn btn-success" wire:loading.attr="disabled">Import details</button>
<button type="button" class="btn btn-secondary close-btn" data-dismiss="modal" wire:loading.attr="disabled">Close</button>
</div>
</td>
</tr>
</table>
<br/>
</form>
</div>
</div>
</div>
</div><!--end of model for excel file upload-->
<!--delete confirmation model start-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header" style="background-color:#d27979;">
<h5 class="modal-title" id="exampleModalLabel">Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button>
</div>
<div class="modal-body"> Are you sure you want to delete this record? </div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" wire:loading.attr="disabled">NO</button>
<button type="button" class="btn btn-danger" wire:click="delete()" wire:loading.attr="disabled">yes</button>
<div wire:loading.table wire:target="delete">
Deleting........
<div class="la-line-scale la-dark la-x">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--end of delete modal-->
<div>
<div class="form-row mt-sm-3">
<div class="col-sm-2 mb-2 text-center">
Per page: 
<select class="form-control" id="exampleFormControlInput3" wire:model="showperpage">
<option>5</option>
<option>10</option>
<option>20</option>
<option>50</option>
<option>100</option>
</select>
</div>
<div class="col-sm-4 mb-2 text-center">
</div>
<div class="col-sm-4 mb-2 text-center">
Search: 
<input wire:model="search" class="form-control" type="text" placeholder="type here to search..">
</div>
<div class="col-sm-2 mb-4 text-center">
Download table:<br/>
<button type="button" wire:click.prevent="exportExcel()" class="btn btn-success">Download</button>
</div>
</div>
<div wire:loading.flex wire:target="exportExcel">
Preparing you download........
<div class="la-line-scale la-dark la-3x">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<div class="table-responsive rounded" id="style-2">
<table class="table table-bordered">
<thead class="thead-light" style="position:sticky;top:0;">
<th class="nonToogleDisplay header">
#
</th>
<th class="header">
<a wire:click.prevent="sortBy('Name')" role="button" href="#" class="nonToogleDisplay">Name
@include('includes._sort-icon',['field'=>'Name'])
</a>
</th>
<th class="header">
<a wire:click.prevent="sortBy('staff_employment_details.cid')" role="button" href="#" class="nonToogleDisplay">CID
@include('includes._sort-icon',['field'=>'cid'])
</a>
</th>
<th class="header">
<a wire:click.prevent="sortBy('school')" role="button" href="#" class="nonToogleDisplay">School served
@include('includes._sort-icon',['field'=>'school'])
</a>
</th>
<th class="header">
<a wire:click.prevent="sortBy('dzongkhag_served')" role="button" href="#" class="nonToogleDisplay">Dzongkhag
@include('includes._sort-icon',['field'=>'dzongkhag_served'])
</a>
</th>
<th class="header">
<a wire:click.prevent="sortBy('start_date')" role="button" href="#" class="nonToogleDisplay">From
@include('includes._sort-icon',['field'=>'start_date'])
</a>
</th>
<th class="header">
<a wire:click.prevent="sortBy('end_date')" role="button" href="#" class="nonToogleDisplay">To
@include('includes._sort-icon',['field'=>'end_date'])
</a>
</th>
<th class="header">
Actions
</th>
</thead>
<tbody>
@foreach($employmentDetailsList as $item)
<tr>
<td class="nonToogleDisplay"> <img src="{{url('storage/images/staff/'.$item->img_location) }}" class="datatablepic"></td>
<td>{{$item->Name}}</td>
<td>{{$item->cid}}</td>
<td>{{$item->school}}</td>
<td>{{$item->dzongkhag_served}}</td>
<td>{{\Carbon\Carbon::parse($item->start_date)->format('M d Y')}}</td>
@if(is_null($item->end_date))
<td>
-----
</td>
@elseif(($item->end_date)->format('M d Y')=='Jan 01 1900')
<td>
-----
</td>
@elseif(($item->end_date)->format('M d Y')=='Nov 30 -0001')
<td>
-------
</td>
@else
<td>
{{\Carbon\Carbon::parse($item->end_date)->format('M d Y')}}
</td>
@endif
<td>
<button wire:click="selectItem({{ $item->id }},'delete')" class="btn btn-danger btn-sm mt-sm-1">Delete</button>
<button wire:click="selectItem({{$item->id}},'update')" class="btn btn-success btn-sm mt-sm-1">Update</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
{{$employmentDetailsList->links()}}
<div class="col text-right text-muted">
showing {{$employmentDetailsList->firstItem()}} to {{$employmentDetailsList->LastItem()}} out of {{$employmentDetailsList->total()}}
</div>
</div>
</div> <!--end of card body-->
</div><!--class="card"-->
</div><!--end of class="col-md-12"-->
</div><!--class="row justify-content-center"-->
</div><!--end of class="container-fluid"-->
|
<div class="panel panel-primary">
<div class="panel-heading m-3">
<h2>Complaints List</h2>
</div>
<button class="btn btn-primary m-3" [routerLink]="[isProd ? '/manager/complaint-add' : '/complaint-add']"><strong>Add complaint</strong></button>
<div class="form-control form-control-lg">
<input [(ngModel)]="SearchString" (keyup)="FilterFn()" placeholder="Filter" >
</div>
<div>
<div class="form-check form-check-inline">
<input type="radio" id="complaintAnswerAll" [(ngModel)]="isAnswered" (change)="FilterFn()" value="All" checked="true" />
<label class="form-check-label" for="complaintAnswerAll">
All
</label>
</div>
<div class="form-check form-check-inline">
<input type="radio" id="complaintAnswerYes" [(ngModel)]="isAnswered" (change)="FilterFn()" value="Answered" />
<label class="form-check-label" for="complaintAnswerYes">
Answered
</label>
</div>
<div class="form-check form-check-inline">
<input type="radio" name="complaintAnswerNo" [(ngModel)]="isAnswered" (change)="FilterFn()" value="Not answered" />
<label class="form-check-label" for="exampleRadios1">
Not answered
</label>
</div>
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Date</th>
<th>Pharmacy</th>
<th>Manager</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let complaint of complaints' [routerLink]="[isProd ? '/manager/complaints' : '/complaints', complaint.id]">
<td>{{complaint.id}}</td>
<td>{{complaint.title}}</td>
<td>{{complaint.createdDate | date: 'dd-MM-yyyy, hh:mm'}}</td>
<td>{{complaint.pharmacy.name}}</td>
<td>{{complaint.manager.name}} {{complaint.manager.surname}}</td>
</tr>
</tbody>
</table>
</div>
</div>
|
document.getElementById('find-me').addEventListener('click', function() {
const status = document.getElementById('status');
const bakeryLat = 40.50583747622529;
const bakeryLng = -78.38690023678137;
function success(position) {
const userLat = position.coords.latitude;
const userLng = position.coords.longitude;
const map = L.map('index-map').fitWorld();
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
const userMarker = L.marker([userLat, userLng]).addTo(map)
.bindPopup('Your location').openPopup();
const bakeryMarker = L.marker([bakeryLat, bakeryLng]).addTo(map)
.bindPopup('Bakery location').openPopup();
const group = new L.featureGroup([userMarker, bakeryMarker]);
map.fitBounds(group.getBounds().pad(0.5));
const distance = calculateDistance(userLat, userLng, bakeryLat, bakeryLng);
status.textContent = `Distance to the bakery: ${distance.toFixed(2)} kilometers.`;
}
function error() {
status.textContent = 'Unable to retrieve your location';
}
if (!navigator.geolocation) {
status.textContent = 'Geolocation is not supported by your browser';
} else {
status.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(success, error);
}
});
function calculateDistance(lat1, lon1, lat2, lon2) {
function degreesToRadians(degrees) {
return degrees * Math.PI / 180;
}
const earthRadiusKm = 6371;
const dLat = degreesToRadians(lat2-lat1);
const dLon = degreesToRadians(lon2-lon1);
lat1 = degreesToRadians(lat1);
lat2 = degreesToRadians(lat2);
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return earthRadiusKm * c;
}
|
/*
* Copyright (C) 2024 RollW
*
* 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 tech.rollw.player.data.setting
import java.util.Locale
/**
* @author RollW
*/
@JvmInline
value class LocaleKey private constructor(val code: String) {
override fun toString(): String {
return code
}
fun asLocale(): Locale {
return when (this) {
System -> Locale.getDefault()
English -> Locale.ENGLISH
Chinese -> Locale.CHINESE
Japanese -> Locale.JAPANESE
Korean -> Locale.KOREAN
French -> Locale.FRENCH
German -> Locale.GERMAN
Italian -> Locale.ITALIAN
Spanish -> Locale.forLanguageTag("es")
Portuguese -> Locale.forLanguageTag("pt")
Russian -> Locale.forLanguageTag("ru")
Arabic -> Locale.forLanguageTag("ar")
else -> Locale.getDefault()
}
}
companion object {
val System = LocaleKey("system")
val English = LocaleKey("en")
val Chinese = LocaleKey("zh")
val Japanese = LocaleKey("ja")
val Korean = LocaleKey("ko")
val French = LocaleKey("fr")
val German = LocaleKey("de")
val Italian = LocaleKey("it")
val Spanish = LocaleKey("es")
val Portuguese = LocaleKey("pt")
val Russian = LocaleKey("ru")
val Arabic = LocaleKey("ar")
fun fromLocale(locale: String): LocaleKey {
return when (locale) {
"en" -> English
"zh" -> Chinese
"ja" -> Japanese
"ko" -> Korean
"fr" -> French
"de" -> German
"it" -> Italian
"es" -> Spanish
"pt" -> Portuguese
"ru" -> Russian
"ar" -> Arabic
else -> System
}
}
}
}
|
import Link from "next/link";
import { MdDelete, MdEditSquare } from "react-icons/md";
type Board = {
boardUuid: string;
price: string;
deposit: string;
title: string;
space: string;
};
type Props = {
board: Board;
id: string;
};
const Item = ({ id, board }: Props) => {
return (
<div className="items-start flex-col bg-gray-50 rounded-lg shadow sm:flex dark:bg-gray-700 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800">
<Link href={`/landlord/${id}`}>
<img className="w-full rounded-lg" src="/images/logo.png" alt="Bonnie Avatar" />
<div className="p-5 pt-0 w-full">
<div className="flex justify-between">
<h3 className="flex items-center text-xl font-bold tracking-tight text-gray-900 dark:text-white">
{`월세 ${board?.price}/${board?.deposit}`}
</h3>
<span className="flex justify-center items-center w-12 h-12 leading-12 rounded-full bg-white text-amber-600">
0
</span>
</div>
<span className="text-gray-500 dark:text-gray-400">{`${board.space} 평`}</span>
<p className="mt-3 mb-4 font-light text-gray-500 dark:text-gray-400">
{board.title}
</p>
<ul className="flex space-x-5 justify-center sm:mt-0">
<li>
<button
type="button"
className="text-white inline-flex items-center bg-primary-500 hover:bg-primary-600 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-xs px-2.5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800"
>
<MdEditSquare fontSize={16} className="mr-1" />
수정
</button>
</li>
<li>
<button
type="button"
className="inline-flex items-center text-white bg-red-500 hover:bg-red-600 focus:ring-4 focus:outline-none focus:ring-red-300 font-medium rounded-lg text-xs px-2.5 py-2.5 text-center dark:bg-red-500 dark:hover:bg-red-600 dark:focus:ring-red-900"
>
<MdDelete fontSize={16} className="mr-1" />
삭제
</button>
</li>
</ul>
</div>
</Link>
</div>
);
};
export default Item;
|
package cz.judas.jan.advent.year2023
import com.google.common.collect.Range
import cz.judas.jan.advent.Answer
import cz.judas.jan.advent.Constant
import cz.judas.jan.advent.Fraction
import cz.judas.jan.advent.InputData
import cz.judas.jan.advent.Pattern
import cz.judas.jan.advent.SymbolicEquation
import cz.judas.jan.advent.Variable
import cz.judas.jan.advent.Vector
import cz.judas.jan.advent.parserFor
import cz.judas.jan.advent.solveLinearSystem
import cz.judas.jan.advent.toFraction
import cz.judas.jan.advent.unorderedPairs
object Day24 {
private val parser = parserFor<Hailstone>()
@Answer("12783")
fun part1(input: InputData): Int {
val hailstones = input.lines()
.map(parser::parse)
val range = Range.closed(200000000000000.0, 400000000000000.0)
return hailstones.unorderedPairs()
.count { (first, second) ->
first.futureIntersectionWith(second)?.let { range.contains(it[0].toDouble()) && range.contains(it[1].toDouble()) } ?: false
}
}
@Answer("948485822969419")
fun part2(input: InputData): Long {
val hailstones = input.lines()
.map(parser::parse)
.take(3)
val px = Variable("px")
val py = Variable("py")
val pz = Variable("pz")
val vx = Variable("vx")
val vy = Variable("vy")
val vz = Variable("vz")
val equations = hailstones
.map { hailstone ->
listOf(
SymbolicEquation((py - hailstone.position.y) * (vx - hailstone.velocity.x), (px - hailstone.position.x) * (vy - hailstone.velocity.y)),
SymbolicEquation((pz - hailstone.position.z) * (vx - hailstone.velocity.x), (px - hailstone.position.x) * (vz - hailstone.velocity.z)),
SymbolicEquation((py - hailstone.position.y) * (vz - hailstone.velocity.z), (pz - hailstone.position.z) * (vy - hailstone.velocity.y)),
)
}
.zipWithNext()
.flatMap { (equations1, equations2) -> equations1.zip(equations2).map { it.second - it.first } }
val solution = solveLinearSystem(equations)!!
return (solution.getValue(px) + solution.getValue(py) + solution.getValue(pz)).toLong()
}
@Pattern("(.+) @ (.+)")
data class Hailstone(
val position: Vector3d,
val velocity: Vector3d
) {
fun futureIntersectionWith(other: Hailstone): Vector? {
val t1 = Variable("t1")
val t2 = Variable("t2")
val solution = solveLinearSystem(
listOf(
SymbolicEquation(Constant(position.x) + t1 * velocity.x, Constant(other.position.x) + t2 * other.velocity.x),
SymbolicEquation(Constant(position.y) + t1 * velocity.y, Constant(other.position.y) + t2 * other.velocity.y)
)
)
if (solution !== null) {
val actualT1 = solution.getValue(t1)
if (actualT1 > Fraction.ZERO && solution.getValue(t2) > Fraction.ZERO) {
return Vector(
position.x.toFraction() + actualT1 * velocity.x,
position.y.toFraction() + actualT1 * velocity.y
)
}
}
return null
}
}
@Pattern("(-?\\d+), (-?\\d+), (-?\\d+)")
data class Vector3d(val x: Long, val y: Long, val z: Long) {
operator fun times(multiplier: Long): Vector3d {
return Vector3d(x * multiplier, y * multiplier, z * multiplier)
}
operator fun plus(other: Vector3d): Vector3d {
return Vector3d(x + other.x, y + other.y, z + other.z)
}
}
}
|
# coding=utf-8
# coding=utf-8
# Copyright 2019 The RecSim Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
r"""An example of main function for training in RecSim.
Use the interest evolution environment and a slateQ agent for illustration.
To run locally:
python main.py --base_dir=/tmp/interest_evolution \
--gin_bindings=simulator.runner_lib.Runner.max_steps_per_episode=50
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from absl import flags
import numpy as np
from recsim.agents import random_agent
from recsim.agents import tabular_q_agent
from recsim.agents import full_slate_q_agent
from recsim.agents import slate_decomp_q_agent
from recsim.agents.slate_decomp_q_agent import select_slate_greedy, compute_target_greedy_q
from recsim.environments import preference_dynamics
from recsim.simulator import runner_lib
FLAGS = flags.FLAGS
flags.DEFINE_string('algorithm', 'full_slate', 'The algorithm to run the experiments with.')
def create_agent(sess, environment, eval_mode, summary_writer=None):
"""Creates an instance of FullSlateQAgent.
Args:
sess: A `tf.Session` object for running associated ops.
environment: A recsim Gym environment.
eval_mode: A bool for whether the agent is in training or evaluation mode.
summary_writer: A Tensorflow summary writer to pass to the agent for
in-agent training statistics in Tensorboard.
Returns:
An instance of FullSlateQAgent.
"""
kwargs = {
'observation_space': environment.observation_space,
'action_space': environment.action_space,
'summary_writer': summary_writer,
'eval_mode': eval_mode,
}
return full_slate_q_agent.FullSlateQAgent(sess, **kwargs)
def create_random_agent(sess, environment, eval_mode, summary_writer=None):
"""Returns an instance of RandomAgent"""
del sess
del eval_mode
del summary_writer
kwargs = {
'action_space': environment.action_space,
}
return random_agent.RandomAgent(**kwargs)
def create_tabular_q_agent(sess, environment, eval_mode, summary_writer=None):
"""Returns an instance of RandomAgent"""
del sess
kwargs = {
'observation_space': environment.observation_space,
'action_space': environment.action_space,
'summary_writer': summary_writer,
'eval_mode': eval_mode
}
return tabular_q_agent.TabularQAgent(**kwargs)
def create_full_slateQ_agent(sess, environment, eval_mode, summary_writer=None):
"""Returns an instance of FullSlateQAgent"""
kwargs = {
'observation_space': environment.observation_space,
'action_space': environment.action_space,
'summary_writer': summary_writer,
'eval_mode': eval_mode
}
return full_slate_q_agent.FullSlateQAgent(sess, **kwargs)
def create_slate_decomp_agent(sess, environment, eval_mode, summary_writer=None):
"""Returns an instance of SlateDecompQAgent"""
kwargs = {
'observation_space': environment.observation_space,
'action_space': environment.action_space,
'summary_writer': summary_writer,
'eval_mode': eval_mode,
'select_slate_fn': select_slate_greedy,
'compute_target_fn': compute_target_greedy_q
}
return slate_decomp_q_agent.SlateDecompQAgent(sess, **kwargs)
def main(argv):
if len(argv) > 1:
raise app.UsageError('Too many command-line arguments.')
runner_lib.load_gin_configs(FLAGS.gin_files, FLAGS.gin_bindings)
base_dir = FLAGS.base_dir + '/inevolution'
algorithm = FLAGS.algorithm
seed = 0
slate_size = 2
num_candidates = 10
np.random.seed(seed)
env_config = {
'num_candidates': num_candidates,
'slate_size': slate_size,
'resample_documents': True,
'seed': seed,
}
for algorithm in ['full_slate_q', 'slate_decomp_q', 'tabular_q_agent', 'random']:
if algorithm == 'full_slate_q':
experiment_dir = base_dir + '/full_slate_q'
train, evaluate = experiment_config(experiment_dir, create_full_slateQ_agent, env_config)
train.run_experiment()
evaluate.run_experiment()
elif algorithm == 'slate_decomp_q':
experiment_dir = base_dir + '/slate_decomp_q'
train, evaluate = experiment_config(experiment_dir, create_slate_decomp_agent, env_config)
train.run_experiment()
evaluate.run_experiment()
elif algorithm == 'tabular_q_agent':
experiment_dir = base_dir + '/tabular_q_agent'
train, evaluate = experiment_config(experiment_dir, create_tabular_q_agent, env_config)
train.run_experiment()
evaluate.run_experiment()
elif algorithm == 'random':
experiment_dir = base_dir + '/random'
train, evaluate = experiment_config(experiment_dir, create_random_agent, env_config)
train.run_experiment()
evaluate.run_experiment()
else:
print(f'No algorithm found: {algorithm}.')
def experiment_config(base_dir, create_agent_fn, env_config):
t_runner = runner_lib.TrainRunner(
base_dir=base_dir,
create_agent_fn=create_agent_fn,
env=preference_dynamics.create_environment(env_config),
episode_log_file=FLAGS.episode_log_file,
max_training_steps=50,
num_iterations=20)
e_runner = runner_lib.EvalRunner(
base_dir=base_dir,
create_agent_fn=create_agent_fn,
env=preference_dynamics.create_environment(env_config),
max_eval_episodes=200,
test_mode=True)
return t_runner, e_runner
if __name__ == '__main__':
flags.mark_flag_as_required('base_dir')
app.run(main)
|
"""
Test the launcher runs the correct commands given the correct input
"""
from pathlib import Path
from unittest.mock import patch, MagicMock
from click.testing import CliRunner
from duckstore.config import db_name
from duckstore.scripts.launcher import launch
launcher_mod = "duckstore.scripts.launcher"
def test_launch_loads_db(db_folder):
runner = CliRunner()
db_folder_path = Path(db_folder)
db_path = db_folder_path / db_name
assert db_path.is_file()
with (patch(f"{launcher_mod}.create_app") as mock,
patch.object(Path, "cwd") as cwd_mock):
cwd_mock.return_value = db_folder_path
run_mock = mock.return_value
result = runner.invoke(launch) # noqa
mock.assert_called_once_with(db_folder_path, create=False)
run_mock.run.assert_called()
assert result.exit_code == 0
assert result.output == (
f"Database found at {db_path}. Loading from folder.\n"
)
def test_launch_nofolder_selected():
"""
Test the launcher exits as intended if not given a folder
:return:
"""
runner = CliRunner()
with patch(f"{launcher_mod}.get_folder_dialog") as mock:
mock.return_value = False
result = runner.invoke(launch, args=[]) # noqa
assert result.exit_code == 1
assert result.output == "Folder not selected - Exiting.\n"
|
import { useState, ChangeEvent, useEffect } from "react";
import {
StyledContainerModal,
StyledModal,
StyledMessage,
StyledContainerRepos,
StyledContainerSearch,
} from "./style";
import { Input } from "../Input";
import { CardRepository } from "../CardRepository";
import { getStorage, removeStorage } from "../../utils/storage";
import { AiOutlineCloseCircle } from "react-icons/ai";
import { ICardRepository } from "../../interfaces";
import { Toaster } from "react-hot-toast";
export interface IPropsModal {
show: boolean;
close: () => void;
}
export function Modal({ show, close }: IPropsModal) {
const [search, setSearch] = useState<string>("");
const [repositories, setRepositories] = useState<ICardRepository[]>([]);
useEffect(() => {
setRepositories(getStorage());
}, [show]);
const removeCard = (id: string): void => {
removeStorage(id);
setRepositories(getStorage());
};
const handleChangeSearch = (
e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => setSearch(e.target.value);
const filterRepositories = repositories.filter((repo) =>
repo.title.toLowerCase().includes(search.toLocaleLowerCase())
);
return (
<>
<Toaster position="top-right" reverseOrder={false} />
<StyledContainerModal show={show}>
<StyledModal>
<StyledContainerSearch>
<Input
placeholder="Pesquisar repositórios"
type="text"
value={search}
change={handleChangeSearch}
/>
<AiOutlineCloseCircle onClick={close} role="closeButton" />
</StyledContainerSearch>
<hr />
<StyledContainerRepos>
{filterRepositories.length === 0 ? (
<StyledMessage>Nenhum repositório salvo.</StyledMessage>
) : (
filterRepositories.map(
({ title, description, url, id }: ICardRepository) => {
return (
<CardRepository
key={id}
title={title}
buttonTitle={false}
description={description}
url={url}
func={() => removeCard(id!)}
/>
);
}
)
)}
</StyledContainerRepos>
</StyledModal>
</StyledContainerModal>
</>
);
}
|
import csv
import matplotlib.pyplot as plt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# This function checks if point q1 lies online segment p1,r
# based on the 3 collinear points
def on_segment(p1, q1, r):
if max(p1.x, r.x) >= q1.x >= min(p1.x, r.x) and max(p1.y, r.y) >= q1.y >= min(p1.y, r.y):
return True
return False
# finding the orientation of the 3 points
def orientation(a, b, r):
val = (b.y - a.y) * (r.x - b.x) - (b.x - a.x) * (r.y - b.y)
if val == 0:
# collinear
return 0
elif val > 0:
# clockwise
return 1
else:
# counterclockwise
return 2
def do_intersect(p1, q1, p2, q2):
# We find the orientation using the p and q of each point
o1 = orientation(p1, q1, p2)
o2 = orientation(p1, q1, q2)
o3 = orientation(p2, q2, p1)
o4 = orientation(p2, q2, q1)
# General case
if o1 != o2 and o3 != o4:
return True
# p1,q1,p2 are collinear
# p2 lies on segment p1,q1
if o1 == 0 and on_segment(p1, p2, q1):
return True
# p1,q1,q2 are collinear
# q2 lies on segment p1,q1
if o2 == 0 and on_segment(p1, q2, q1):
return True
# p2,q2,p1 are collinear
# p1 lies on segment p2,q2
if o3 == 0 and on_segment(p2, q1, q2):
return True
# p2,q2,q1 are collinear
# p1 lies on segment p2,q2
if o4 == 0 and on_segment(p2, q1, q2):
return True
return False
# Open the CSV file and add the points in the arrays
points = []
with open('coordinates.csv', mode='r', encoding='utf-8-sig') as file:
reader = csv.reader(file)
# p and q are the two points of a line
# Insert the coordinates of each line
for row in reader:
# Adds the columns to x and y of the Point class
# ,and then it passes them to the p and q variables
# So now we have p.x,p.y and q.x,q.y
p = Point(float(row[0]), float(row[1]))
q = Point(float(row[2]), float(row[3]))
# Then we add those two points in an array to store them
# p is stored in even cells and q in odd cells
points.append(p)
points.append(q)
def run_lineSegInter():
for i in range(0, len(points) - 1, 2):
# we start from i + 2 in the second for loop because we don't want to check two times for every point
# because the array is 1D
for j in range(i + 2, len(points) - 1, 2):
# we have i, i+1, j and j+1 in a nested for loop because we want to check all the points with each other.
# Because we have a 1D array and for each line we have two cells we need to add 1 to take the whole line
# In the first loop the cursor i will have the vales 0 and 0+1 that will be the first line
# and cursor j will have the values 2 and 2+1, because in the second for loop we start from i+2
if do_intersect(points[i], points[i + 1], points[j], points[j + 1]):
print("Lines {},{}-{},{} and {},{}-{},{} intersect".format(int(points[i].x), int(points[i].y),
int(points[i + 1].x), int(points[i + 1].y),
int(points[j].x), int(points[j].y),
int(points[j + 1].x), int(points[j + 1].y)))
# we make and show the plot for the lines that intersect
plt.figure(figsize=(5, 5))
plt.plot((int(points[i].x), int(points[i + 1].x)), (int(points[i].y), int(points[i + 1].y)), '.r--')
plt.plot((int(points[j].x), int(points[j + 1].x)), (int(points[j].y), int(points[j + 1].y)), '.b--')
plt.show()
|
import 'package:flutter/material.dart';
import 'package:explore/app_colors.dart';
import 'package:explore/screens/choose_avatar_screen.dart';
class ChooseRocketScreen extends StatefulWidget {
const ChooseRocketScreen({Key? key}) : super(key: key);
@override
_ChooseRocketScreenState createState() => _ChooseRocketScreenState();
}
class _ChooseRocketScreenState extends State<ChooseRocketScreen> {
String stringRocket = "";
int selectedRocket = 0;
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
double rocketSize = screenWidth * 0.3; // 30% of the screen width
double spacing = screenWidth * 0.03; // 3% of the screen width
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
leading: Container(
decoration: BoxDecoration(
color: AppColors.darkPurple,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: IconButton(
icon: const Icon(
Icons.arrow_back,
color: AppColors.white,
),
onPressed: () => Navigator.pop(context),
),
),
backgroundColor: Colors.transparent,
elevation: 0,
),
body: DecoratedBox(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/StarsBackground.png"),
fit: BoxFit.cover,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildRocketAvatar(Icons.rocket_launch_outlined, rocketSize, 1),
SizedBox(width: spacing),
buildRocketAvatar(Icons.rocket_outlined, rocketSize, 2),
],
),
SizedBox(height: spacing),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildRocketAvatar(Icons.rocket_launch, rocketSize, 3),
SizedBox(width: spacing),
buildRocketAvatar(Icons.rocket, rocketSize, 4),
],
),
],
),
),
),
);
}
Widget buildRocketAvatar(IconData icon, double size, int id) {
return Container(
height: size,
width: size,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: stringRocket == icon.toString() ? AppColors.lightGrey : AppColors.darkBlue,
),
margin: const EdgeInsets.all(10.0),
child: IconButton(
icon: Icon(icon),
onPressed: () {
selectRocket(icon.toString());
navigateToChooseAvatarScreen(id);
},
),
);
}
void selectRocket(String rocket) {
setState(() {
stringRocket = rocket;
});
}
void navigateToChooseAvatarScreen(int selectedRocket) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChooseAvatarScreen(selectedRocket: selectedRocket),
),
);
}
}
|
import { useState } from "react";
import { useHabbits } from "../context/HabbitsContext";
import EmojiPicker from "emoji-picker-react";
export default function Popup() {
const { openModal, setOpenModal, onAddHabbit } = useHabbits();
const [title, setTitle] = useState("");
const [step, setStep] = useState("");
const [icon, setIcon] = useState("");
const [emoji, setEmoji] = useState(false);
function handlerSubmitForm(e) {
e.preventDefault();
onAddHabbit(title, step, icon);
setTitle("");
setStep("");
setOpenModal(false);
setIcon("");
}
return (
<>
{openModal && (
<div className="cover cover_hidden">
<div className="popup">
<h2>Новая привычка</h2>
<div className="icon-label">
<div className="emoji">
<span>{icon}</span>{" "}
</div>
<button onClick={() => setEmoji(!emoji)} className="btn btn_lg">
{!emoji ? `Выбрать эмоджи` : "Скрыть эмоджи"}
</button>
</div>
{emoji && (
<EmojiPicker
previewConfig={{
showPreview: false,
}}
height={280}
onEmojiClick={(emojiData) => {
setIcon(emojiData.emoji);
setEmoji(!emoji);
}}
/>
)}
<button
className="popup__close"
onClick={() => setOpenModal(false)}
>
<img src="/src/assets/images/close.svg" alt="Закрыть" />
</button>
<form className="popup__form" onSubmit={handlerSubmitForm}>
<input
type="text"
name="name"
placeholder="Название"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
<input
value={step}
onChange={(e) => setStep(e.target.value)}
type="number"
name="target"
placeholder="Цель"
required
/>
<button
className="btn btn_lg"
type="submit"
onClick={handlerSubmitForm}
>
Добавить
</button>
</form>
</div>
</div>
)}
</>
);
}
|
//
// ViewController.swift
// Word Garden
//
// Created by Zachary Moelchert on 2/14/21.
//
// App through Week 3 assignment
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var wordsGuessedLabel: UILabel!
@IBOutlet weak var wordsMissedLabel: UILabel!
@IBOutlet weak var wordsRemainingLabel: UILabel!
@IBOutlet weak var wordsInGameLabel: UILabel!
@IBOutlet weak var wordBeingRevealedLabel: UILabel!
@IBOutlet weak var guessedLetterTextField: UITextField!
@IBOutlet weak var guessLetterButton: UIButton!
@IBOutlet weak var playAgainButton: UIButton!
@IBOutlet weak var gameStatusMessageLabel: UILabel!
@IBOutlet weak var flowerImageView: UIImageView!
var wordsToGuess = ["SWIFT", "DOG", "CAT"]
var currentWordIndex = 0
var wordToGuess = ""
var lettersGuessed = ""
let maxNumberOfWrongGuessed = 8
var wrongGuessesRemaining = 8
var wordsGuessedCount = 0
var wordsMissedCount = 0
var guessCount = 0
var audioPlayer: AVAudioPlayer!
func enabledButton() {
let text = guessedLetterTextField.text!
guessLetterButton.isEnabled = !(text.isEmpty)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
enabledButton()
wordToGuess = wordsToGuess[currentWordIndex]
wordBeingRevealedLabel.text = "_" + String(repeating: " _", count: wordToGuess.count - 1)
updateGameStatusLabels()
}
func updateGameStatusLabels() {
wordsGuessedLabel.text = "Words Guessed: \(wordsGuessedCount)"
wordsMissedLabel.text = "Words Missed: \(wordsMissedCount)"
wordsRemainingLabel.text = "Words to Guess: \(wordsToGuess.count - (wordsGuessedCount + wordsMissedCount))"
wordsInGameLabel.text = "Words in Game: \(wordsToGuess.count)"
}
func updateAfterWinOrLoss() {
currentWordIndex += 1
guessedLetterTextField.isEnabled = false
guessLetterButton.isEnabled = false
playAgainButton.isHidden = false
updateGameStatusLabels()
}
func updateUIAfterGuess() {
guessedLetterTextField.resignFirstResponder()
guessedLetterTextField.text! = ""
guessLetterButton.isEnabled = false
}
func formatRevealedWord() {
// format and show revealedWord in wordBeingRevealedLabel
var revealedWord = ""
for letter in wordToGuess {
if lettersGuessed.contains(letter) {
revealedWord = revealedWord + "\(letter) "
} else {
revealedWord = revealedWord + "_ "
}
}
revealedWord.removeLast()
wordBeingRevealedLabel.text = revealedWord
}
func drawFlowerAndPlaySound (currentLetterGuessed: String) {
if wordToGuess.contains(currentLetterGuessed) == false {
wrongGuessesRemaining = wrongGuessesRemaining - 1
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
UIView.transition(with: self.flowerImageView,
duration: 0.5,
options: .transitionCrossDissolve,
animations: {self.flowerImageView.image = UIImage(named: "wilt\(self.wrongGuessesRemaining)")}) { (_) in
if self.wrongGuessesRemaining != 0 {
self.flowerImageView.image = UIImage(named: "flower\(self.wrongGuessesRemaining)")
} else {
self.playSound(name: "word-not-guessed")
UIView.transition(with: self.flowerImageView, duration: 0.5, options: .transitionCrossDissolve, animations: {self.flowerImageView.image = UIImage(named: "flower\(self.wrongGuessesRemaining)")}, completion: nil)
}
}
self.playSound(name: "incorrect")
}
} else {
playSound(name: "correct")
}
}
func guessALetter() {
// get current letter guessed and add it to all lettersGuessed
let currentLetterGuessed = guessedLetterTextField.text!
lettersGuessed = lettersGuessed + currentLetterGuessed
formatRevealedWord()
// update image after guess, if needed, and keep track of wrong guesses
drawFlowerAndPlaySound(currentLetterGuessed: currentLetterGuessed)
// update gameStatusMessageLabel
guessCount += 1
let guess = (guessCount == 1 ? "Guess" : "Guesses")
gameStatusMessageLabel.text = "You've Made \(guessCount) \(guess)"
if wordBeingRevealedLabel.text!.contains("_") == false {
gameStatusMessageLabel.text = "You've guessed it! It took you \(guessCount) \(guess) to guess the word."
wordsGuessedCount += 1
playSound(name: "word-guessed")
updateAfterWinOrLoss()
} else if wrongGuessesRemaining == 0 {
gameStatusMessageLabel.text = "So sorry. You're all out of guesses"
wordsMissedCount += 1
updateAfterWinOrLoss()
}
if currentWordIndex == wordsToGuess.count {
gameStatusMessageLabel.text! += "\n\nYou've tried all of the words! Restart from the beginning?"
}
}
func playSound(name: String) {
if let sound = NSDataAsset(name: name) {
do {
try audioPlayer = AVAudioPlayer(data: sound.data)
audioPlayer.play()
} catch {
print("ERROR: \(error.localizedDescription)could not initialize AVAudioPlayer object")
}
} else {
print("ERROR: could not read data from file sound0")
}
}
@IBAction func guessedLetterFieldChanged(_ sender: UITextField) {
enabledButton()
sender.text = String(sender.text?.last ?? " ").trimmingCharacters(in: .whitespaces).uppercased()
}
@IBAction func doneKeyPressed(_ sender: UITextField) {
guessALetter()
updateUIAfterGuess()
}
@IBAction func guessALetterButtonPressed(_ sender: UIButton) {
guessALetter()
updateUIAfterGuess()
}
@IBAction func playAgainButtonPressed(_ sender: UIButton) {
if currentWordIndex == wordsToGuess.count {
currentWordIndex = 0
wordsGuessedCount = 0
wordsMissedCount = 0
}
playAgainButton.isHidden = true
guessedLetterTextField.isEnabled = true
guessLetterButton.isEnabled = true
wordToGuess = wordsToGuess[currentWordIndex]
wrongGuessesRemaining = maxNumberOfWrongGuessed
wordBeingRevealedLabel.text = "_" + String(repeating: " _", count: wordToGuess.count - 1)
guessCount = 0
flowerImageView.image = UIImage(named: "flower\(maxNumberOfWrongGuessed)")
lettersGuessed = ""
gameStatusMessageLabel.text = "You've Made Zero Guesses"
updateGameStatusLabels()
}
}
|
import 'package:flutter/material.dart';
import 'package:rosella/models/user.dart';
import 'package:rosella/screens/Orientation/landscape.dart';
import 'package:rosella/screens/Orientation/portrait.dart';
import 'package:rosella/screens/login.dart';
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0xFFF485AD),
elevation: 0,
),
body: OrientationBuilder(
builder: ((context, orientation) {
if (orientation == Orientation.portrait) {
return portraitMode(context);
} else {
return landscapeMode(context);
}
}),
),
drawer: Drawer(
child: SingleChildScrollView(
child: Column(
children: [
Container(
width: double.infinity,
height: 220,
// margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
decoration: const BoxDecoration(
color: Color(0xFFF485AD),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40))),
child: SafeArea(
bottom: false,
right: false,
left: false,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const CircleAvatar(
backgroundImage: AssetImage('assets/logo4.png'),
radius: 45),
const SizedBox(
height: 10,
),
Text(username,
style:
const TextStyle(fontSize: 22, color: Colors.white)),
],
),
),
),
Container(
padding: const EdgeInsets.fromLTRB(8, 0, 0, 60),
child: Column(
children: [
const ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20),
leading: Icon(Icons.content_paste_rounded),
title: Text('My Orders'),
),
const ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20),
leading: Icon(Icons.favorite_outline_outlined),
title: Text('Wishlist'),
),
const ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20),
leading: Icon(Icons.location_on_outlined),
title: Text('Addresses'),
),
const ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20),
leading: Icon(Icons.star_outline_sharp),
title: Text('Vouchers'),
),
const ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20),
leading: Icon(Icons.help_outline_outlined),
title: Text('Help Center'),
),
const ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20),
leading: Icon(Icons.settings),
title: Text('Settings'),
),
ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Login()),
);
},
contentPadding: const EdgeInsets.symmetric(horizontal: 20),
leading: const Icon(Icons.logout),
title: const Text('Logout'),
),
],
),
),
],
),
)),
);
}
}
|
package org.caicoders.domain.internet;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class InternetSpeed implements IInternetSpeed {
private String internetSpeedStr; // Variable for storing Internet speed information
private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public InternetSpeed() {
scheduler.scheduleAtFixedRate(
this::collectAndSendInternetSpeed,
0,
1,
TimeUnit.SECONDS
);
}
@Override
public void collectAndSendInternetSpeed() {
try {
// Try to connect to Google to measure the speed
URL url = new URL("https://www.google.com");
URLConnection connection = url.openConnection();
long startTime = System.currentTimeMillis();
// Read the response to measure the speed
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
long totalBytesRead = 0;
try (InputStream inputStream = connection.getInputStream()) {
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
totalBytesRead += bytesRead;
}
}
long endTime = System.currentTimeMillis();
// Calculate the speed in Mbps
long totalTime = endTime - startTime;
double speedMbps = (totalBytesRead * 8.0 / 1024.0 / 1024.0) / (totalTime / 1000.0);
// Build the string with the Internet speed information
internetSpeedStr = String.format("%.3f", speedMbps).replace(',', '.') + " Mbps";
System.out.flush(); // Flush the output to avoid buffering
} catch (IOException e) {
// Manage the exception if there's an error
internetSpeedStr = "N.D";
System.out.println(internetSpeedStr);
}
}
@Override
public String getInternetSpeedStr() {
return internetSpeedStr;
}
}
|
package com.palcas.poker.persistance;
import com.fasterxml.jackson.core.JsonParseException;
import com.palcas.poker.persistance.account.Account;
import com.palcas.poker.persistance.account.AccountRepository;
import com.palcas.poker.persistance.account.JacksonAccountRepository;
import com.palcas.poker.persistance.constants.JacksonPersistenceSettings;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class JacksonAccountRepositoryTest {
private static AccountRepository accountRepository;
@BeforeAll
public static void setUp() {
accountRepository = new JacksonAccountRepository(JacksonPersistenceSettings.TEST_ACCOUNT_FILE_PATH);
}
@BeforeEach
public void writeTestDataInFile(){
String testData = "["
+ "{\"name\": \"Alice\", \"passwordHash\": \"e55a9d387402d3e84953f3b584a62eb5c8d9f796f1e1313cb6c6dc395f260d37\", \"passwordSalt\": \"1337\", \"chips\": 1000}, "
+ "{\"name\": \"Bob\", \"passwordHash\": \"013bd4cdf01910a5a02bb51ad7b50de82553a1d31827ed5c1f6760bca326dcc2\", \"passwordSalt\": \"69\", \"chips\": 2000}"
+ "]";
try (FileWriter writer = new FileWriter(JacksonPersistenceSettings.TEST_ACCOUNT_FILE_PATH)) {
writer.write(testData);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test void testLoadAccount() {
try {
Account bob = accountRepository.loadAccount("Bob");
assertEquals("Bob", bob.getName());
assertEquals("69", bob.getPasswordSalt());
assertEquals("013bd4cdf01910a5a02bb51ad7b50de82553a1d31827ed5c1f6760bca326dcc2", bob.getPasswordHash());
assertEquals(2000, bob.getChips());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void testAddAccount() {
Account accountToAdd = new Account("Georg", "634aa687c3365f3d3ac110f61542a4fcf839b5efba21b6893d201a63aa8ecda6", "9572");
Account loadedAccount;
try {
accountRepository.saveAccount(accountToAdd);
loadedAccount = accountRepository.loadAccount("Georg");
} catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals(accountToAdd.getName(), loadedAccount.getName());
assertEquals(accountToAdd.getPasswordHash(), loadedAccount.getPasswordHash());
assertEquals(accountToAdd.getPasswordSalt(), loadedAccount.getPasswordSalt());
}
@Test
public void testUpdatingTheHashOfAnExistingAccount() {
Account alice;
try {
alice = accountRepository.loadAccount("Alice");
} catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals("Alice", alice.getName());
assertEquals("e55a9d387402d3e84953f3b584a62eb5c8d9f796f1e1313cb6c6dc395f260d37", alice.getPasswordHash());
Account updatedAlice;
try {
alice.setPasswordHash("96a6602ef951499be98990c3acf28d434056eeb865c1186b2e3c5456babc62ba");
accountRepository.saveAccount(alice);
updatedAlice = accountRepository.loadAccount("Alice");
} catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals("Alice", updatedAlice.getName());
assertEquals("96a6602ef951499be98990c3acf28d434056eeb865c1186b2e3c5456babc62ba", alice.getPasswordHash());
}
@Test
public void throwsExceptionBecauseJSONFileIsBroken() {
try (FileWriter writer = new FileWriter(JacksonPersistenceSettings.TEST_ACCOUNT_FILE_PATH)) {
writer.write("hellothere{this\"isa}}broken[]assf1le[[[[[[");
} catch (IOException e) {
throw new RuntimeException(e);
}
assertThrows(JsonParseException.class, () -> accountRepository.loadAccount("Alice"));
}
@Test void returnsNullBecauseAccountIsNotFond() {
try {
Account nonexistentAccount = accountRepository.loadAccount("Ghost");
assertEquals(null, nonexistentAccount);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// #Requirement
@Test void returnsNullIfNameIsNull() {
Account account;
try {
account = accountRepository.loadAccount(null);
} catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals(null, account);
}
// #LifeSaver #BugFix
@Test void returnsNullAndCreatesEmptyFileIfFileDoesntExistYet() {
//the non-existing-account-filepath must point to a non-existing account
AccountRepository corruptAccountRepository = new JacksonAccountRepository(JacksonPersistenceSettings.NON_EXISTING_ACCOUNT_FILE_PATH);
Account account;
File file = new File(JacksonPersistenceSettings.NON_EXISTING_ACCOUNT_FILE_PATH);
try {
account = corruptAccountRepository.loadAccount("Alice");
} catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals(null, account);
assert(file.exists());
// Clean up: Delete the file after assertions
deleteCreatedFile(file);
}
// #LifeSaver #BugFix
@Test void createsFileWithAccountIfFileDoesntExistYet() {
//the non-existing-account-filepath must point to a non-existing account
AccountRepository corruptAccountRepository = new JacksonAccountRepository(JacksonPersistenceSettings.NON_EXISTING_ACCOUNT_FILE_PATH);
File file = new File(JacksonPersistenceSettings.NON_EXISTING_ACCOUNT_FILE_PATH);
Account accountToAdd = new Account("Georg", "634aa687c3365f3d3ac110f61542a4fcf839b5efba21b6893d201a63aa8ecda6", "9572");
Account receivedAccount;
try {
corruptAccountRepository.saveAccount(accountToAdd);
receivedAccount = corruptAccountRepository.loadAccount("Georg");
} catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals(accountToAdd, receivedAccount);
assert(file.exists());
// Clean up: Delete the file after assertions
deleteCreatedFile(file);
}
public static void deleteCreatedFile(File file) {
File direcotry = new File(extractLowestDirectoryPath(file));
if (file.exists()) {
file.delete();
}
if (direcotry.exists()) {
direcotry.delete();
}
}
public static String extractLowestDirectoryPath(File file) {
file = file.getParentFile();
if (file == null) {
return null;
}
return file.getPath();
}
}
|
// Dart imports:
// Package imports:
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flowerstore/data/api_error.dart';
import 'package:flowerstore/data/datasource/invoice/invoice_datasource.dart';
import 'package:meta/meta.dart';
// Project imports:
import 'package:flowerstore/data/datasource/product/product_datasource.dart';
import '../../../data/datasource/invoice/model/request/get_invoice_request.dart';
import '../../../domain/entity/invoice.dart';
// Part files:
part 'analytic_event.dart';
part 'analytic_state.dart';
class AnalyticBloc extends Bloc<AnalyticEvent, AnalyticState> {
final InvoiceDataSource _dataSource;
AnalyticBloc(this._dataSource)
: super(AnalyticInitial()) {
on<GetAnalyticsEvent>(
(event, emit) async => _onGetAnalyticsEvent(event, emit));
}
_onGetAnalyticsEvent(
GetAnalyticsEvent event, Emitter<AnalyticState> emit) async {
final cacheState = state;
emit(AnalyticLoading());
try {
final response = await _dataSource.getInvoice(event.request);
emit(AnalyticLoaded(response));
} on APIError catch (error) {
emit(AnalyticError(message: error.message));
if (cacheState is AnalyticLoaded) {
emit(cacheState);
} else {
emit(AnalyticLoaded(const []));
}
}
}
}
|
//重建二叉树
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* 关于slice,slice返回的是新的数组,end不包括在内
*
*
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function (preorder, inorder) {
if(!preorder.length && !inorder.length){
return null;
}
const rootVal = preorder[0];
const node = new TreeNode(rootVal);
let i = 0;
for(;i<inorder.length;i++){
if(inorder[i]===rootVal){
break;
}
}
node.left = buildTree(preorder.slice(1,i+1),inorder.slice(0, i))
node.right = buildTree(preorder.slice(i+1),inorder.slice(i+1))
return node
}
|
import React, { useState } from 'react';
import '../stylesheets/login.css';
import {useNavigate} from 'react-router-dom';
async function loginUser(credentials) {
return fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(res => {
if (res.status === 200) {
return res;
}
else if (res.status === 300) {
return false;
}
});
}
// This entire portion is used for react-router setup
export const Login = () => {
const navigate = useNavigate();
const [email, setEmail] = useState();
const [password, setPassword] = useState();
const handleSubmit = async e => {
e.preventDefault();
const signin = await loginUser({
email,
password
});
if (!signin) {
return resetForm();
}
return navigate('/home');
};
const resetForm = () => {
setEmail('');
setPassword('');
alert('Wrong user info!');
};
return (
<div className="login">
<h1>Please Log In</h1>
<form onSubmit={handleSubmit}>
<label>
<p>Email</p>
<input type="text" onChange={e => setEmail(e.target.value)} value = {email} />
</label>
<label>
<p>Password</p>
<input type="password" onChange={e => setPassword(e.target.value)} value = {password} />
</label>
<div>
<label>
<button className="signupButton" type="button" onClick={e => navigate('/signup')}>No account yet?</button>
</label>
</div>
<div>
<button className="submit" type="submit">Submit</button>
</div>
</form>
</div>
);
};
|
#' Covariate-Adjusted-Sparse-Matrix-completion
#' Fit function
#'
#' @param y A sparse matrix of class Incomplete.
#' @param X covariate matrix
#' @param svdH (optional) A list consisting of the SVD of the hat matrix. see reduced_hat_decomp function.
#' @param Xterms (optional) A list of terms computed using GetXterms function.
#' @param J (hyperparameter). The maximum rank of the low-rank matrix M = AB. Default is 2
#' @param lambda (hyperparameter) The L2 regularization parameter for A and B
#' @param r (hyperparameter, optional) The rank of covariate effects (beta). The rank will be the same
#' as the covariate matrix if r not provided
#' @return A list of u,d,v of M, Beta, and a vector of the observed Xbeta
#' @examples
#' CASMC_fit(y,X,J=5)
#' @export
#'
CASMC3_fit <-
function(y,
X,
J = 2,
lambda.M = 0,
lambda.beta = 0,
# similarity matrix for A
S.a = NULL,
lambda.a = 0,
# similarity matrix for B
S.b = NULL,
lambda.b = 0,
normalized_laplacian = TRUE,
# convergence parameters
maxit = 300,
thresh = 1e-05,
trace.it = FALSE,
warm.start = NULL,
# the following should not be modified
final.svd = TRUE,
beta.iter.max = 10,
learning.rate = 0.001,
init = "naive",
min_eigv = 0) {
stopifnot(inherits(y, "dgCMatrix"))
irow = y@i
pcol = y@p
n <- dim(y)
m <- n[2]
n <- n[1]
k <- ncol(X)
if (trace.it)
nz = nnzero(y, na.counted = TRUE)
#-------------------------------
laplace.a = laplace.b = F
if (!is.null(S.a) && lambda.a > 0) {
laplace.a = T
L.a = computeLaplacian(S.a, normalized = normalized_laplacian) * lambda.a
}
if (!is.null(S.b) && lambda.b > 0) {
laplace.b = T
L.b = computeLaplacian(S.b, normalized = normalized_laplacian) * lambda.b
}
#---------------------------------------------------
# warm start or initialize (naive or random)
warm = FALSE
clean.warm.start(warm.start)
if (!is.null(warm.start)) {
#must have u,d and v components
if (!all(match(c("u", "d", "v", "beta"), names(warm.start), 0) >
0))
stop("warm.start is missing some or all of the components.")
warm = TRUE
# prepare U, Dsq, V
D = warm.start$d
JD = sum(D > min_eigv)
if (JD >= J) {
U = warm.start$u[, seq(J), drop = FALSE]
V = warm.start$v[, seq(J), drop = FALSE]
Dsq = D[seq(J)]
} else{
# upscale
Ja = J - JD
Dsq = c(D, rep(D[JD], Ja))
U = warm.start$u
Ua = matrix(rnorm(n * Ja), n, Ja)
Ua = Ua - U %*% (t(U) %*% Ua)
Ua = tryCatch(
fast.svd(Ua, trim = FALSE)$u,
error = function(e)
svd(Ua)$u
)
U = cbind(U, Ua)
V = cbind(warm.start$v, matrix(0, m, Ja))
}
#----------------
# prepare beta
beta = warm.start$beta
stopifnot(all(dim(beta) == c(k, m)))
} else{
# initialize. Warm start is not provided
stopifnot(init %in% c("random", "naive"))
if (init == "random") {
stop("Not implemented yet.")
} else if (init == "naive") {
Y_naive = as.matrix(y)
Y_naive = naive_MC(Y_naive)
svdH = reduced_hat_decomp.H(X)
Xbeta <- svdH$u %*% (svdH$v %*% Y_naive)
M <- as.matrix(Y_naive - Xbeta)
M <- tryCatch(
propack.svd(M, J),
error = function(e) {
message(paste("Naive Init:", e))
svd_trunc_simple(M, J)
}
)
U = M$u
V = M$v
Dsq = pmax(M$d, min_eigv)
#----------------------
# initialization for beta = X^-1 Y
# comment for later: shouldn't be X^-1 H Y??
beta = as.matrix(ginv(X) %*% Xbeta)
Y_naive <- Xbeta <- M <- NULL
#---------------------------------------------------------------
}
}
XtX = t(X) %*% X
#----------------------------------------
yobs <- y@x # y will hold the model residuals
ratio <- 1
iter <- 0
#----------------------------------------
while ((ratio > thresh) & (iter < maxit)) {
iter <- iter + 1
U.old = U
V.old = V
Dsq.old = Dsq
#----------------------------------------------
# part 0: Update y (training residulas)
# prereq: U, Dsq, V, Q, R, yobs
# updates: y; VDsq; XQ
VDsq = t(Dsq * t(V))
M_obs = suvC(U, VDsq, irow, pcol)
if (iter == 1) {
xbeta.obs <- suvC(X, (t(beta)), irow, pcol)
y@x = yobs - M_obs - xbeta.obs
}
#----------------------------------------------
# part 1: update beta
beta.old <- matrix(0, k, m)
beta.thresh = lambda.beta * learning.rate
beta.iter = 0
partial.update = learning.rate * as.matrix(t(X) %*% y + XtX %*% beta)
while (sqrt(sum((beta - beta.old) ^ 2)) > 1e-3 &
beta.iter < beta.iter.max) {
beta.old <- beta
update = beta + partial.update - learning.rate * XtX %*% beta
beta <- matrix(0, k, m)
beta[update > beta.thresh] = update[update > beta.thresh] - beta.thresh
beta[update < -beta.thresh] = update[update < -beta.thresh] + beta.thresh
beta.iter <- beta.iter + 1
#print(sqrt(sum((beta - beta.old) ^ 2)))
}
#-------------------------------------------------------------------
# part extra: re-update y
xbeta.obs <-
suvC(X, (t(beta)), irow, pcol)
y@x = yobs - M_obs - xbeta.obs
#--------------------------------------------------------------------
# print("hi2")
##--------------------------------------------
# part 3: Update B
# prereq: U, VDsq, y, Dsq, lambda.M, L.b
# updates U, Dsq, V
B = t(U) %*% y + t(VDsq)
if (laplace.b)
B = B - t(V) %*% L.b
B = as.matrix(t((B) * (Dsq / (Dsq + lambda.M))))
Bsvd = tryCatch({
fast.svd(B, trim = FALSE)
}, error = function(e) {
message(paste("Loop/B:", e))
svd(B)
})
V = Bsvd$u
Dsq = pmax(Bsvd$d, min_eigv)
U = U %*% (Bsvd$v)
#-------------------------------------------------------------
# part 4: Update A
# prereq: U, D, VDsq, y, lambda.M, L.a
# updates U, Dsq, V
A = (y %*% V) + t(Dsq * t(U))
if (laplace.a)
A = A - L.a %*% U
A = as.matrix(t(t(A) * (Dsq / (Dsq + lambda.M))))
Asvd = tryCatch({
#svd(A)
fast.svd(A, trim = FALSE)
}, error = function(e) {
message(paste("Loop/A:", e))
svd(A)
})
U = Asvd$u
Dsq = pmax(Asvd$d, min_eigv)
V = V %*% (Asvd$v)
#------------------------------------------------------------------------------
ratio = Frob(U.old, Dsq.old, V.old, U, Dsq, V)
#------------------------------------------------------------------------------
if (trace.it) {
obj = (.5 * sum(y@x ^ 2) +
lambda.M * sum(Dsq)) / nz
cat(iter,
":",
"obj",
format(round(obj, 5)),
"ratio",
ratio,
"qiter",
beta.iter,
"\n")
}
#-----------------------------------------------------------------------------------
}
if (iter == maxit &
trace.it)
warning(
paste(
"Convergence not achieved by",
maxit,
"iterations. Consider increasing the number of iterations."
)
)
# one final fit for one of the parameters (A) has proved to improve the performance significantly.
if (final.svd) {
#---- update A
A = (y %*% V) + t(Dsq * t(U))
if (laplace.a)
A = A - L.a %*% U
A = as.matrix(t(t(A) * (Dsq / (Dsq + lambda.M))))
Asvd = tryCatch({
fast.svd(A, trim = FALSE)
}, error = function(e) {
message(paste("Final/A:", e))
svd(A)
})
U = Asvd$u
V = V %*% Asvd$v
# is this good?
Dsq = pmax(Asvd$d - lambda.M, min_eigv)
#---------------------------------------------
if (trace.it) {
M_obs = suvC(t(Dsq * t(U)), V, irow, pcol)
y@x = yobs - M_obs - xbeta.obs
obj = (.5 * sum(y@x ^ 2) + lambda.M * sum(Dsq)) / nz
cat("final SVD:", "obj", format(round(obj, 5)), "\n")
cat("Number of Iterations for covergence is ", iter, "\n")
}
}
#-------------------------------------------------------
# trim in case we reduce the rank of M to be smaller than J.
J = min(sum(Dsq > min_eigv) + 1, J)
J = min(J, length(Dsq))
out = list(
u = U[, seq(J), drop = FALSE],
d = Dsq[seq(J)],
v = V[, seq(J), drop = FALSE],
beta = beta,
#---------------------
# hyperparameters
lambda.M = lambda.M,
lambda.beta = lambda.beta,
J = J,
lambda.a = lambda.a,
lambda.b = lambda.b,
#--------------------------
# convergence
n_iter = iter
)
out
}
|
import * as pulumi from "@pulumi/pulumi";
import * as gcp from "@pulumi/gcp";
import { Providers } from "@mussia33/node/shared";
export interface NetworkResourceProps {
region: string;
project: string;
provider?: Providers;
}
export class NetworkResource extends pulumi.ComponentResource {
constructor(
name: string,
networkResourceProps: NetworkResourceProps,
opts?: pulumi.ResourceOptions
) {
super("mussia33:core:network:", name, {}, opts);
const { project, region } = networkResourceProps;
const vpcAccess = new gcp.projects.Service(
"vpcaccess.googleapis.com",
{
disableDependentServices: true,
service: "vpcaccess.googleapis.com",
},
{ parent: this, ...opts }
);
const vpcNetwork = new gcp.compute.Network(
"vpcNetwork",
{
name: "my-first-vpc",
project,
description: "My first VPC",
mtu: 1460,
autoCreateSubnetworks: false,
},
{ parent: this, ...opts }
);
const ilSubnet = new gcp.compute.Subnetwork(
"ilSubnet",
{
ipCidrRange: "10.212.0.0/24",
region: "me-west1",
network: vpcNetwork.id,
name: "me-west1-subnet",
description: "Israel subnet",
},
{ parent: this, ...opts }
);
const euSubnet = new gcp.compute.Subnetwork(
"euSubnet",
{
ipCidrRange: "10.186.0.0/24",
region: region,
network: vpcNetwork.id,
name: `${region}-subnet`,
description: "Europe subnet",
},
{ parent: this, ...opts }
);
const defaultFirewall = new gcp.compute.Firewall(
"default-firewall",
{
network: vpcNetwork.name,
name: "default-firewall",
priority: 65534,
allows: [
{
protocol: "icmp",
},
{
protocol: "tcp",
ports: ["80", "8080", "1000-2000"],
},
],
sourceTags: ["web"],
},
{ parent: this, ...opts }
);
}
}
|
import React, { ChangeEvent } from 'react';
import Select from '@components/UI/Select/Select.tsx';
import SearchField from '@components/UI/SearchField/SearchField.tsx';
import { useAppDispatch, useAppSelector } from '@/hooks/store.ts';
import {
setActiveCategory,
setActiveSorter,
setSearchQuery,
setStartSearch,
} from '@/store/slices/filtersSlice.ts';
import styles from './FiltersSection.module.css';
interface FilterSectionProps {}
const FiltersSection: React.FC<FilterSectionProps> = () => {
const { categories, sorters, activeCategory, activeSorter } =
useAppSelector(state => state.filters);
const dispatch = useAppDispatch();
const onClick = () => {
dispatch(setStartSearch(true));
setTimeout(() => {
dispatch(setStartSearch(false));
}, 0);
};
const onCategoryChange = (e: ChangeEvent<HTMLSelectElement>) => {
const value = e.target.value;
dispatch(setActiveCategory(value));
};
const onSorterChange = (e: ChangeEvent<HTMLSelectElement>) => {
const value = e.target.value;
dispatch(setActiveSorter(value));
};
const onSearchQueryChange = (value: string) => {
dispatch(setSearchQuery(value));
};
return (
<div className={styles.FiltersSection}>
<h1 className={styles.title}>Find your favourite book</h1>
<SearchField onChange={onSearchQueryChange} onClick={onClick} />
<div className={styles.filters}>
<Select
name="category"
description="Choose category"
options={categories}
defaultValue={activeCategory}
onChange={onCategoryChange}
/>
<Select
name="sort"
description="Sort by"
options={sorters}
defaultValue={activeSorter}
onChange={onSorterChange}
/>
</div>
</div>
);
};
export default FiltersSection;
|
//
// MusicListViewCell.swift
// MusicPlayer
//
// Created by Nanda Wisnu Tampan on 20/09/21.
//
import Api
import UIKit
import Kingfisher
class MusicListViewCell: UITableViewCell {
// MARK: - Properties
var isPlaying = false
lazy var songNameLabel: UILabel = {
let view = UILabel()
view.font = UIFont.boldSystemFont(ofSize: 14)
view.textColor = .black
view.numberOfLines = 0
view.textAlignment = .center
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var artistNameLabel: UILabel = {
let view = UILabel()
view.font = UIFont(name: "HelveticaNeue", size: 14)
view.textColor = .black
view.numberOfLines = 0
view.textAlignment = .center
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var albumNameLabel: UILabel = {
let view = UILabel()
view.font = UIFont(name: "HelveticaNeue", size: 12)
view.textColor = .black
view.numberOfLines = 0
view.textAlignment = .center
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var albumImage: UIImageView = {
let view = UIImageView()
view.layer.masksToBounds = true
view.layer.cornerRadius = 2
view.contentMode = .scaleAspectFill
view.kf.indicatorType = .activity
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var soundWaveIcon: UIImageView = {
let view = UIImageView()
view.layer.masksToBounds = true
view.contentMode = .scaleAspectFill
view.translatesAutoresizingMaskIntoConstraints = false
view.image = UIImage(named: "ic_soundwave")
return view
}()
var imageURL: String? {
didSet {
guard let url = imageURL else { return }
albumImage.loadAlbumArtwork(resource: url)
}
}
var item: Music? {
didSet {
guard let item = item else { return }
setItem(item)
}
}
override func layoutSubviews() {
super.layoutSubviews()
setupUI()
}
override func prepareForReuse() {
super.prepareForReuse()
soundWaveIcon.isHidden = true
isHidden = false
isSelected = false
isHighlighted = false
}
}
extension MusicListViewCell {
// MARK: - UI Setup
/// Set UI layout and constraints
private func setupUI() {
backgroundColor = .white
let bgView = UIView()
bgView.translatesAutoresizingMaskIntoConstraints = false
bgView.addSubview(albumImage)
bgView.addSubview(songNameLabel)
bgView.addSubview(artistNameLabel)
bgView.addSubview(albumNameLabel)
bgView.addSubview(soundWaveIcon)
bgView.backgroundColor = UIColor.lightGray
contentView.addSubview(bgView)
let padding: CGFloat = 10
NSLayoutConstraint.activate([
// album image artwork constraints
albumImage.topAnchor.constraint(equalTo: contentView.topAnchor, constant: padding),
albumImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: padding),
albumImage.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -padding),
albumImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
albumImage.widthAnchor.constraint(equalToConstant: 80),
albumImage.heightAnchor.constraint(equalToConstant: 80),
// song name label constraints
songNameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: padding),
songNameLabel.leadingAnchor.constraint(equalTo: albumImage.trailingAnchor, constant: padding),
// artist name label constraints
artistNameLabel.topAnchor.constraint(equalTo: songNameLabel.bottomAnchor, constant: padding),
artistNameLabel.leadingAnchor.constraint(equalTo: albumImage.trailingAnchor, constant: padding),
// album name label constraints
albumNameLabel.topAnchor.constraint(equalTo: artistNameLabel.bottomAnchor, constant: padding),
albumNameLabel.leadingAnchor.constraint(equalTo: albumImage.trailingAnchor, constant: padding),
albumNameLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -padding),
// soundwave icon
soundWaveIcon.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
soundWaveIcon.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -padding),
soundWaveIcon.widthAnchor.constraint(equalToConstant: 50),
soundWaveIcon.heightAnchor.constraint(equalToConstant: 30),
contentView.bottomAnchor.constraint(greaterThanOrEqualTo: albumImage.bottomAnchor, constant: padding)
])
}
private func setItem(_ music: Music) {
songNameLabel.text = music.trackName
artistNameLabel.text = music.artistName
albumNameLabel.text = music.collectionName
soundWaveIcon.isHidden = !isPlaying
if let url = music.artworkUrl60 {
albumImage.loadAlbumArtwork(resource: url)
albumImage.center = center
}
}
}
|
//
// CalendarDayCell.swift
// SobokSobok
//
// Created by taehy.k on 2022/01/15.
//
import UIKit
import FSCalendar
import SwiftUI
enum FilledType: Int {
case none
case all
case some
case today
}
enum SelectedType: Int {
case not
case single
}
final class CalendarDayCell: FSCalendarCell {
weak var circleImageView: UIImageView!
weak var selectionLayer: CAShapeLayer!
var width: CGFloat = 32.0 {
didSet {
setNeedsLayout()
}
}
var yPosition: CGFloat = 2.0 {
didSet {
setNeedsLayout()
}
}
var filledType: FilledType = .none {
didSet {
setNeedsLayout()
}
}
var selectedType: SelectedType = .not {
didSet {
setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
let circleImageView = UIImageView(image: Image.calenderBackgroundSome)
self.contentView.insertSubview(circleImageView, at: 0)
self.circleImageView = circleImageView
self.shapeLayer.isHidden = true
}
required init!(coder aDecoder: NSCoder!) {
fatalError()
}
override func layoutSubviews() {
super.layoutSubviews()
let width = width
let yPosition = yPosition
let distance = (self.contentView.bounds.width - width) / 2
let frame = CGRect(x: self.contentView.bounds.minX + distance,
y: self.contentView.bounds.minY + yPosition,
width: width,
height: width)
self.circleImageView.frame = frame
switch selectedType {
case .not:
self.titleLabel.font = UIFont.font(.pretendardRegular, ofSize: 16)
case .single:
self.titleLabel.font = UIFont.font(.pretendardBold, ofSize: 22)
}
switch filledType {
case .all:
self.titleLabel.textColor = Color.white
self.circleImageView.image = Image.calenderBackgroundAll
case .some:
self.titleLabel.textColor = Color.black
self.circleImageView.image = Image.calenderBackgroundSome
case .today:
self.titleLabel.textColor = Color.black
self.circleImageView.image = selectedType == .not ?
Image.calendarBackgroundTodayDefault : Image.calendarBackgroundToday
case .none:
self.titleLabel.textColor = Color.black
self.circleImageView.image = nil
}
}
func configureUI(isSelected: Bool, with type: FilledType) {
width = isSelected ? 48 : 32
yPosition = isSelected ? -6 : 2
selectedType = isSelected ? .single : .not
filledType = type
}
}
enum SelectionType : Int {
case none
case single
case leftBorder
case middle
case rightBorder
}
class DIYCalendarCell: FSCalendarCell {
weak var selectionLayer: CAShapeLayer?
weak var connectionLayer: CAShapeLayer?
var selectionType: SelectionType = .none {
didSet {
if selectionType == .none {
self.selectionLayer?.opacity = 0
self.connectionLayer?.opacity = 0
self.selectionLayer?.isHidden = true
self.connectionLayer?.isHidden = true
return
}
setNeedsLayout()
}
}
required init!(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
let selectionLayer = CAShapeLayer()
selectionLayer.fillColor = UIColor(red: 228 / 255, green: 246 / 255, blue: 246 / 255, alpha: 1.0).cgColor
selectionLayer.opacity = 0
self.contentView.layer.insertSublayer(selectionLayer, below: self.titleLabel.layer)
self.selectionLayer = selectionLayer
self.selectionLayer?.isHidden = true
let connectionLayer = CAShapeLayer()
connectionLayer.fillColor = UIColor(red: 228 / 255, green: 246 / 255, blue: 246 / 255, alpha: 1.0).cgColor
connectionLayer.opacity = 0
self.contentView.layer.insertSublayer(connectionLayer, below: self.titleLabel.layer)
self.connectionLayer = connectionLayer
self.connectionLayer?.isHidden = true
self.shapeLayer.isHidden = true
}
override func prepareForReuse() {
super.prepareForReuse()
self.selectionLayer?.opacity = 0
self.connectionLayer?.opacity = 0
self.contentView.layer.removeAnimation(forKey: "opacity")
}
override func layoutSubviews() {
super.layoutSubviews()
self.selectionLayer?.frame = self.contentView.bounds.insetBy(dx: 0, dy: -3)
self.connectionLayer?.frame = self.contentView.bounds.insetBy(dx: 0, dy: -3)
guard var connectionRect = connectionLayer?.bounds else {
return
}
connectionRect.size.height = connectionRect.height * 5 / 6
if selectionType == .middle {
self.connectionLayer?.isHidden = false
self.connectionLayer?.opacity = 1
self.connectionLayer?.path = UIBezierPath(rect: connectionRect).cgPath
self.titleLabel.textColor = UIColor.black
}
else if selectionType == .leftBorder {
self.connectionLayer?.isHidden = false
self.connectionLayer?.opacity = 1
var rect = connectionRect
rect.origin.x = connectionRect.width / 2
rect.size.width = connectionRect.width / 2
self.connectionLayer?.path = UIBezierPath(rect: rect).cgPath
}
else if selectionType == .rightBorder {
self.connectionLayer?.isHidden = false
self.connectionLayer?.opacity = 1
var rect = connectionRect
rect.size.width = connectionRect.width / 2
self.connectionLayer?.path = UIBezierPath(rect: rect).cgPath
}
if selectionType == .single || selectionType == .leftBorder || selectionType == .rightBorder {
self.selectionLayer?.isHidden = false
self.selectionLayer?.opacity = 1
let diameter: CGFloat = min(connectionRect.height, connectionRect.width)
let rect = CGRect(
x: self.contentView.frame.width / 2 - diameter / 2,
y: 0,
width: diameter,
height: diameter)
self.selectionLayer?.path = UIBezierPath(ovalIn: rect).cgPath
}
if selectionType == .single {
self.titleLabel.textColor = UIColor(red: 0 / 255, green: 171 / 255, blue: 182 / 255, alpha: 1.0)
}
}
override func configureAppearance() {
super.configureAppearance()
if self.isPlaceholder {
self.eventIndicator.isHidden = true
self.titleLabel.textColor = UIColor.lightGray
}
}
}
|
syntax = "proto3";
package proto;
option go_package = "github.com/ramyadmz/goauth/services/auth/pkg/pb";
message RegisterUserRequest{
string username = 1;
string password = 2;
string email = 3;
}
message RegisterUserResponse{
}
message UserLoginRequest{
string username = 1;
string password = 2;
}
message UserLoginResponse{
string session_id = 1;
}
message UserLogoutRequest{
string session_id = 2;
}
message UserLogoutResponse{
}
message UserConsentRequest {
int64 client_id = 1;
string session_id = 4;
}
message UserConsentResponse {
}
message RegisterClientRequest {
string name = 1;
string website = 2;
string scope = 3;
}
message RegisterClientResponse {
int64 client_id = 1;
string client_secret = 2;
}
message GetAuthorizationCodeRequest {
int64 client_id = 1;
string client_secret = 2;
string username = 3;
}
message GetAuthorizationCodeResponse {
string authorization_code = 1;
}
message ExchangeTokenRequest {
int64 client_id = 1;
string client_secret = 2;
string authorization_code = 3;
}
message ExchangeTokenResponse {
string access_token = 1;
string refresh_token = 2;
}
message RefreshTokenRequest {
string refresh_token = 1;
}
message RefreshTokenResponse {
string access_token = 1;
}
service OAuthService {
rpc RegisterUser (RegisterUserRequest) returns (RegisterUserResponse);
rpc UserLogin (UserLoginRequest) returns (UserLoginResponse);
rpc UserLogout (UserLogoutRequest) returns (UserLogoutResponse);
rpc UserConsent (UserConsentRequest) returns (UserConsentResponse);
rpc RegisterClient (RegisterClientRequest) returns (RegisterClientResponse);
rpc GetAuthorizationCode (GetAuthorizationCodeRequest) returns (GetAuthorizationCodeResponse);
rpc ExchangeToken (ExchangeTokenRequest) returns (ExchangeTokenResponse);
rpc RefreshToken (RefreshTokenRequest) returns (RefreshTokenResponse);
}
|
/*
* 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 javasorttest;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author 18323
*/
public class JavaSortTest {
/**
* @param args the command line arguments
*/
public static void main(String args[]){
boolean needAnswer = false;
JavaSort javasort = new JavaSort();
Scanner scanner=new Scanner(System.in);
//Initialize the originalArray outside of the scope of the "do while" loop.
int[] originalArray = JavaSort.randomArrayGen();
do{
//intitiate a user input switch case for sorting algo selection via method call
System.out.print("Select what sorting method should be used (enter the number) \n1. Bubble Sort\n2. Insertion Sort\n3. Shell Sort\n4. Merge Sort\n5. Quick Sort.\n6. Heap Sort\n7. End Program\n8. New Array\nEnter value here: ");
//initiate a do-while loop for multiple uses without restart
while (!scanner.hasNextInt()){
System.out.println("Enter a valid number!");
scanner.next();
}
int UserInput=scanner.nextInt();
//Important** make a copy of the original unsorted array for use in each individual case to scope.
int[] arrayToSort = Arrays.copyOf(originalArray, originalArray.length);
switch(UserInput){
case 1:
System.out.println("");
System.out.println("Start Bubble Algorithm");
long startTime = System.nanoTime();
javasort.bubbleSort(arrayToSort);//call bubble algo
long endTime = System.nanoTime();
System.out.println("End Bubble Algorithm time taken: "+(endTime-startTime)+" nano-seconds");
System.out.println(" ");
break;
case 2:
System.out.println(" ");
System.out.println("Start Insertion Algorithm");
long startTime1 = System.nanoTime();
javasort.InsertSort(arrayToSort);//call insertion algo
long endTime1 = System.nanoTime();
System.out.println("End Insertion Algorithm "+(endTime1-startTime1)+" nano-seconds");
System.out.println(" ");
break;
case 3:
System.out.println(" ");
System.out.println("Start Shell Algorithm");
long startTime2 = System.nanoTime();
javasort.ShellSort(arrayToSort);//call insertion algo
long endTime2 = System.nanoTime();
System.out.println("End Shell Algorithm "+(endTime2-startTime2)+" nano-seconds");
System.out.println(" ");
break;
case 4:
System.out.println(" ");
System.out.println("Start Merge Algorithm");
long startTime3 = System.nanoTime();
javasort.mergeSort(arrayToSort, 0, arrayToSort.length-1);//call insertion algo
long endTime3 = System.nanoTime();
System.out.println("End Merge Algorithm "+(endTime3-startTime3)+" nano-seconds");
System.out.println(" ");
break;
case 5:
System.out.println(" ");
System.out.println("Start Quicksort Algorithm");
long startTime4 = System.nanoTime();
javasort.quickSort(arrayToSort, 0, arrayToSort.length-1);//call insertion algo
long endTime4 = System.nanoTime();
System.out.println("End Quicksort Algorithm "+(endTime4-startTime4)+" nano-seconds");
System.out.println(" ");
break;
case 6:
System.out.println(" ");
System.out.println("Start Heapsort Algorithm");
long startTime5 = System.nanoTime();
javasort.sort(arrayToSort);//call insertion algo
long endTime5 = System.nanoTime();
System.out.println("End Heapsort Algorithm "+(endTime5-startTime5)+" nano-seconds");
System.out.println(" ");
break;
case 7:
System.out.println(" ");
System.out.println("-Closing Program-");//break and close loop per user input request
needAnswer = true;
break;
case 8:
System.out.println(" ");
System.out.println("-Generating A New Array-");//break and close loop per user input request
originalArray = JavaSort.randomArrayGen();
break;
default :
System.out.println("-Enter a valid input-");//default catch bad input values, request valid input
}}
while(!needAnswer);//close do while loop.
scanner.close();//close scanner
}
}
|
<nav class="navbar navbar-expand-lg navbar-light bg-light font-weight-light">
<div class="container-fluid">
<%= link_to root_path, class: 'navbar-brand' do %>
<%= image_tag("logo/logo.png") %> TutorNow
<% end %>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navmenu">
<span class="navbar-toggler-icon"></span>
</button>
<% if user_signed_in? %>
<div class="collapse navbar-collapse" id="navmenu">
<ul class="navbar-nav ms-auto">
<li class="nav-item active">
<div class="px-2 me-2"><strong><%= current_user.first_name %></strong></div>
</li>
<li class="nav-item">
<%= link_to "Appointments", my_appointments_path, class:"px-2 me-2" %>
</li>
<li class="nav-item">
<%= link_to "Create offer", new_offer_path, class:"px-2 me-2" %>
</li>
<li class="nav-item">
<%= link_to "Sign Out", destroy_user_session_path, method: :delete, class:"px-2 me-2" %>
</li>
</ul>
</div>
<% else %>
<div class="collapse navbar-collapse" id="navmenu">
<ul class="navbar-nav ms-auto">
<li>
<%= link_to "Sign Up", new_user_registration_path, class:"px-2 me-2" %>
</li>
<li class="nav-item">
<%= link_to "Sign In", new_user_session_path, class:"px-2 me-2" %>
</li>
</ul>
</div>
<% end %>
</div>
</nav>
|
package com.grl.propietaryapptfg.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import com.grl.propietaryapptfg.ui.theme.mostaza
import com.grl.propietaryapptfg.utils.Util
@Composable
fun CategoryItem(name: String, onClick: () -> Unit, isSelected: Boolean, modifier: Modifier) {
ConstraintLayout(modifier = modifier
.fillMaxHeight()
.clickable { onClick() }) {
val (title, bar) = createRefs()
Text(
modifier = Modifier
.constrainAs(title) {
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
top.linkTo(parent.top)
},
text = name,
textAlign = TextAlign.Center,
color = mostaza,
fontFamily = Util.loadFontFamilyFromAssets(),
fontSize = 35.sp,
fontWeight = FontWeight.Bold
)
if (isSelected) {
HorizontalDivider(
color = mostaza,
thickness = 5.dp,
modifier = Modifier.constrainAs(bar) { bottom.linkTo(parent.bottom) })
}
}
}
|
import { component$, useStylesScoped$ } from "@builder.io/qwik";
import constructChallengeModifierFullText from "~/util/constructChallengeModifierFullText";
import DayButtons from "./dayButtons";
import styles from "./dayViewer.css?inline";
import DayNavigationButtons from "./dayNavigationButtons";
export interface DayDataProps {
dayInfoData: {
dayNumber: number;
gameId: string;
gameName: string;
year: number;
repositoryLink: string;
rerollTokensEarned: number;
rerollTokensSpentDuringPart1: number;
rerollTokensSpentDuringPart2: number;
currentRerollTokens: number;
score: number;
modifierWhenPart1Completed: string;
modifierWhenPart1CompletedExplanatoryUrl: string;
optionWhenPart1Completed: string;
optionWhenPart1CompletedExplanatoryUrl: string;
challengeModifier: string;
challengeModifierExplanatoryUrl: string;
modifierOption: string;
modifierOptionExplanatoryUrl: string;
dateFirstRolled: string | null;
currentDay: number;
currentDayCompleted: boolean;
part1Completed: string | null;
part2Completed: string | null;
};
privateViewerData?: {
gameIsPublic: boolean;
gameNumber: string;
dayNumber: string;
incrementButtonPresses: Function | any;
loading: boolean;
setLoadingStatus: Function | any;
userId: string;
};
publicViewerData?: {
oauthAvatarUrl: string;
username: string;
};
}
export default component$((props: DayDataProps) => {
useStylesScoped$(styles);
return (
<>
<br />
<div class="dashedBorder textCenter fontLarger">
{" "}
<h1 class="margin0">{props.dayInfoData.gameName}</h1>
{props.publicViewerData && (
<p class="marginBottom1">
<img
src={props.publicViewerData!.oauthAvatarUrl}
alt="user avatar"
style={{ height: "1.5rem", width: "1.5rem" }}
width="24"
height="24"
/>{" "}
<span style={`vertical-align: text-top`}>
{props.publicViewerData!.username}
</span>
</p>
)}
<h2>Day {props.dayInfoData.dayNumber}</h2>
</div>
<br />
<br />
<p>
<a
href={`https://adventofcode.com/${props.dayInfoData.year}/day/${props.dayInfoData.currentDay}`}
target="_blank"
rel="noopener noreferrer"
class="textGreen"
>
°Puzzle Link°
</a>
</p>
{props.dayInfoData.repositoryLink !== "None" && (
<p>
<a
href={props.dayInfoData.repositoryLink}
target="_blank"
rel="noopener noreferrer"
>
°Repo Link°
</a>
</p>
)}
{props.privateViewerData?.gameIsPublic &&
props.dayInfoData.repositoryLink !== "None" && (
<p>
<a
href={`/game/public/${props.dayInfoData.gameId}/day/${props.privateViewerData.dayNumber}`}
class="textGreen"
>
°Public Link°
</a>
</p>
)}
<br />
<br />
<div class="flex column alignStart gap1" style={`max-width: 36rem`}>
<ul class="flex column alignStart gap1">
<li>
<strong>Reroll Tokens Earned</strong>:{" "}
<strong class="token">
{props.dayInfoData.rerollTokensEarned === 0
? "0"
: "".repeat(props.dayInfoData.rerollTokensEarned)}
</strong>
</li>
<li>
<strong>Reroll Tokens Spent During Part 1</strong>:{" "}
<strong class="tokenSpent">
{props.dayInfoData.rerollTokensSpentDuringPart1 === 0
? "0"
: props.dayInfoData.rerollTokensSpentDuringPart1 > 9
? props.dayInfoData.rerollTokensSpentDuringPart1 + ""
: "".repeat(props.dayInfoData.rerollTokensSpentDuringPart1)}
</strong>
</li>
<li>
<strong>Reroll Tokens Spent During Part 2</strong>:{" "}
<strong class="tokenSpent">
{props.dayInfoData.rerollTokensSpentDuringPart2 === 0
? "0"
: props.dayInfoData.rerollTokensSpentDuringPart2 > 9
? props.dayInfoData.rerollTokensSpentDuringPart2 + ""
: "".repeat(props.dayInfoData.rerollTokensSpentDuringPart2)}
</strong>
</li>
<li>
<strong>Current Reroll Tokens</strong>:{" "}
<strong class="token">
{props.dayInfoData.currentRerollTokens > 9
? props.dayInfoData.currentRerollTokens + ""
: "".repeat(props.dayInfoData.currentRerollTokens)}
</strong>
</li>
<li class={`marginBottom2`}>
<strong>Day Score</strong>:{" "}
{props.dayInfoData.score > 0 ? (
<strong class="token">+{props.dayInfoData.score}</strong>
) : (
<strong class="tokenSpent">{props.dayInfoData.score}</strong>
)}
</li>
<li>
<strong>Challenge Modifier</strong>:<br />
{props.dayInfoData.challengeModifier === "None"
? "None"
: constructChallengeModifierFullText(
props.dayInfoData.challengeModifier +
(props.dayInfoData.modifierOption !== "None"
? props.dayInfoData.modifierOption
: "")
)}
</li>
{props.dayInfoData.challengeModifierExplanatoryUrl !== "None" && (
<li>
Click this{" "}
<a
href={props.dayInfoData.challengeModifierExplanatoryUrl}
target="_blank"
rel="noopener noreferrer"
>
°external link°
</a>{" "}
to learn more about this Challenge Modifier
</li>
)}
{props.dayInfoData.modifierOptionExplanatoryUrl !== "None" && (
<li>
Click this{" "}
<a
href={props.dayInfoData.modifierOptionExplanatoryUrl}
target="_blank"
rel="noopener noreferrer"
>
°external link°
</a>{" "}
to learn more about this Modifier Option
</li>
)}
{props.dayInfoData.modifierWhenPart1Completed !== "None" &&
(props.dayInfoData.modifierWhenPart1Completed !==
props.dayInfoData.challengeModifier ||
props.dayInfoData.optionWhenPart1Completed !==
props.dayInfoData.modifierOption) && (
<>
<li class={`marginTop2`}>
<strong>Challenge Modifier During Part 1</strong>:{" "}
{props.dayInfoData.modifierWhenPart1Completed === "None"
? "None"
: constructChallengeModifierFullText(
props.dayInfoData.modifierWhenPart1Completed +
(props.dayInfoData.optionWhenPart1Completed !== "None"
? props.dayInfoData.optionWhenPart1Completed
: "")
)}
{props.dayInfoData.optionWhenPart1Completed !== "None" &&
props.dayInfoData.optionWhenPart1Completed}
</li>
</>
)}
{props.dayInfoData.modifierWhenPart1CompletedExplanatoryUrl !==
"None" &&
props.dayInfoData.modifierWhenPart1Completed !==
props.dayInfoData.challengeModifier && (
<li>
Click this{" "}
<a
href={
props.dayInfoData.modifierWhenPart1CompletedExplanatoryUrl
}
target="_blank"
rel="noopener noreferrer"
>
°external link°
</a>{" "}
to learn more about this Challenge Modifier that was completed
during Part 1
</li>
)}
{props.dayInfoData.optionWhenPart1CompletedExplanatoryUrl !==
"None" &&
props.dayInfoData.optionWhenPart1Completed !==
props.dayInfoData.modifierOption && (
<li>
Click this{" "}
<a
href={
props.dayInfoData.optionWhenPart1CompletedExplanatoryUrl
}
target="_blank"
rel="noopener noreferrer"
>
°external link°
</a>{" "}
to learn more about this Modifier Option that was completed
during Part 1
</li>
)}
{props.dayInfoData.dateFirstRolled && (
<>
<li class={`marginTop2`}>
<strong>First Rolled On</strong>: <br />
{new Date(props.dayInfoData.dateFirstRolled).toString()}{" "}
</li>
</>
)}
{props.dayInfoData.part1Completed && (
<li>
<strong>Part 1 Completed On</strong>:<br />
{new Date(props.dayInfoData.part1Completed).toString()}
</li>
)}
{props.dayInfoData.part2Completed && (
<li>
<strong>Part 2 Completed On</strong>:<br />
{new Date(props.dayInfoData.part2Completed).toString()}
</li>
)}{" "}
</ul>
<div class={`flex column gap1 marginTop2`}>
{props.privateViewerData ? (
<DayButtons
privateViewerData={props.privateViewerData}
dayInfoData={props.dayInfoData}
/>
) : (
<DayNavigationButtons
dayNumber={props.dayInfoData.dayNumber}
currentDay={props.dayInfoData.currentDay}
gameId={+props.dayInfoData.gameId}
/>
)}
</div>
</div>
<br />
</>
);
});
|
import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import Footer from '../components/molecules/footer/footer'
import Header from '../components/molecules/header/header'
import { withPrefix } from 'gatsby'
import { isIOS, isAndroid } from 'react-device-detect'
import BreadCrumb from '../components/atoms/bread-crumb/bread-crumb'
import { contentScript } from '../utils/contentScript'
import { connect } from 'react-redux'
import { ThemeProvider } from 'styled-components'
import { useCurrentWidth } from 'react-socks'
import { selectTheme } from '../utils/select-theme'
import './layout.scss'
let LayoutMain = ({
children,
showType,
isOpenMenu,
showQuickAccess = true,
defaultTypeUser = '',
defaultCategoryUser = '',
defaultSubcategoryUser = '',
indexDBUserName,
indexDBUser,
home,
modal,
isNotUser,
classBread,
showBread,
location,
category,
isBrowser,
isStepMenuTourGuideActive,
isTourOpen,
isTourGuideActive,
validateStreetCard,
OpenEventTour,
mockup,
accessibility,
colorFooter
}) => {
const [userData, setUserData] = useState(indexDBUser)
const [marginAdditional, setMarginAdditional] = useState(false)
const width = useCurrentWidth()
useEffect(() => {
setUserData(indexDBUser)
}, [indexDBUser])
if (typeof window !== 'undefined') {
contentScript(withPrefix('/tittle-content.js'))
}
const getAdditionalMarginTop = () => {
if (marginAdditional && showQuickAccess) return '114px'
if (marginAdditional && !showQuickAccess) return '52px'
return 0
}
return (
<ThemeProvider
theme={selectTheme(
indexDBUser?.category,
accessibility,
indexDBUser?.type
)}
>
<>
<Header
showTypePerson={showType}
defaultTypeUser={defaultTypeUser}
defaultCategoryUser={defaultCategoryUser}
defaultSubcategoryUser={defaultSubcategoryUser}
showQuickAccess={showQuickAccess}
isOpenMenu={isOpenMenu}
indexDBUser={userData}
indexDBUserName={indexDBUserName}
isNotUser={isNotUser}
isStepTourGuideActive={isStepMenuTourGuideActive}
isTourOpen={isTourOpen}
isTourGuideActive={isTourGuideActive}
validateStreetCard={validateStreetCard}
OpenEventTour={OpenEventTour}
indexDBUser={indexDBUser}
enabledAccessibility={e => {
setMarginAdditional(e)
}}
/>
{showBread && (
<div
className={classBread}
style={{ marginTop: getAdditionalMarginTop() }}
>
<BreadCrumb
location={location}
defaultTypeUser={defaultTypeUser}
defaultCategoryUser={defaultCategoryUser}
defaultSubcategoryUser={defaultSubcategoryUser}
/>
</div>
)}
<div
style={{
marginTop: width > 1024 && marginAdditional && !showBread ? 65 : 0,
background: accessibility
? accessibility.darkMode
? '#1E1C23'
: colorFooter
? colorFooter
: '#FFFFFF'
: '#FFFFFF'
}}
className={home ? 'home-mobile' : ''}
id="layout-main"
>
<main>{children}</main>
</div>
<Footer
indexDBUser={userData}
isIOS={isIOS}
isAndroid={isAndroid}
home={home}
modal={modal}
colorFooter={colorFooter}
/>
</>
</ThemeProvider>
)
}
LayoutMain.propTypes = {
children: PropTypes.node.isRequired,
indexDBUserName: PropTypes.string
}
function mapStateToProps(state) {
return {
accessibility: state.accesibility
}
}
LayoutMain = connect(mapStateToProps)(LayoutMain)
export default LayoutMain
|
import { React, useState, useEffect } from "react";
import Button from "@mui/material/Button";
import { Box } from "@mui/system";
import { DataGrid, gridClasses } from "@mui/x-data-grid";
import styles from "./style.module.css";
import { YMaps, Map, Placemark } from "react-yandex-maps";
import { api } from "../../../axiosConfig";
import { hydronodes } from "./data";
import clsx from "clsx";
const mapState = { center: [54.133392, 27.577899], zoom: 7, controls: [] };
export default function LevelsGp(props) {
const [map, setMap] = useState(mapState);
const [data, setData] = useState([]);
useEffect(() => {
const getData = async () => {
try {
const res = await api.get("/levelsGu/getAll");
res.data.forEach((item) => {
item.date = new Date(item.date);
});
setData(res.data);
} catch (err) {
console.log(err);
}
};
getData();
}, []);
let rows = hydronodes.map((row) => {
let rowData = data.filter((dat) => dat.hydronode === row.hydronode);
if (rowData.length === 0) return row;
let lastRecord = rowData[0];
rowData.forEach((dat) => {
if (dat.date.getTime() > lastRecord.date.getTime()) lastRecord = dat;
});
return {
...row,
level1: lastRecord.level1,
level2: lastRecord.level2,
level1Change: lastRecord.level1Change === "-" ? '—' : lastRecord.level1Change,
level2Change: lastRecord.level2Change === "-" ? '—' : lastRecord.level2Change,
date: lastRecord.date.toLocaleString().slice(0, 10),
};
});
const columns = [
{ field: "hydronode", headerName: "Гидроузел", width: "150" },
{ field: "river", headerName: "Река", width: "150" },
{
field: "date",
headerName: "Дата измерения",
width: "130",
},
{
field: "level1",
headerName: "Уровень воды над ПГ, ВБ",
type: "string",
width: "190",
},
{
field: "level2",
headerName: "Уровень воды над ПГ, НБ",
type: "string",
width: "190",
},
{
field: "level1Change",
headerName: "Изменение ВБ за сутки",
type: "string",
width: "175",
cellClassName: (params) => {
if (params.row.level1 === "—") {
return "";
}
return clsx("super-app", {
negative: params.row.level1Change < 0,
positive: params.row.level1Change > 0,
default:
params.row.level1Change === "0" || params.row.level1Change === "—",
});
},
},
{
field: "level2Change",
headerName: "Изменение НБ за сутки",
type: "string",
width: "175",
cellClassName: (params) => {
if (params.row.level1 === "—") {
return "";
}
return clsx("super-app", {
negative: params.row.level2Change < 0,
positive: params.row.level2Change > 0,
default:
params.row.level1Change === "0" || params.row.level2Change === "—",
});
},
},
{
field: "action1",
type: "actions",
headerName: "На карте",
getActions: ({ id }) => {
return [
<Button
options={rows.find((row) => row.id === id).options}
onClick={() =>
setMap({
center: rows.find((row) => row.id === id).coords,
zoom: 15,
})
}
key={id}
>
Показать
</Button>,
];
},
},
];
const marks = rows.map((row) => {
let contentBody =
"Гидроузел: " +
row.hydronode +
"<br> Река: " +
row.river +
"<br> Дата измерения: " +
row.date +
"<br> Уровень воды над ПГ, ВБ: " +
row.level1 +
"<br> Уровень воды над ПГ, НБ: " +
row.level2 +
"<br> Изменение уровня за сутки, ВБ: " +
row.level1Change +
"<br> Изменение уровня за сутки, НБ: " +
row.level2Change;
return (
<Placemark
geometry={row.coords}
key={row.id}
properties={{ balloonContentBody: contentBody }}
modules={["geoObject.addon.balloon"]}
options={{
iconLayout: "default#image",
iconImageHref: "/images/levelGu.png",
iconImageSize: [30, 30],
iconImageOffset: [-15, -15],
}}
/>
);
});
return (
<div className={styles.container}>
<Box
sx={{
"& .super-app.negative": {
backgroundColor: "#d47483",
color: "#1a3e72",
fontWeight: "600",
},
"& .super-app.positive": {
backgroundColor: "rgba(157, 255, 118, 0.49)",
color: "#1a3e72",
fontWeight: "600",
},
"& .super-app.default": {
backgroundColor: "rgba(114, 163, 255, 0.49)",
color: "#1a3e72",
fontWeight: "600",
},
}}
className={styles.element}
>
<DataGrid
rows={rows}
columns={columns}
experimentalFeatures={{ newEditingApi: true }}
getRowHeight={() => "auto"}
sx={{
[`& .${gridClasses.cell}`]: {
py: 1,
},
}}
/>
</Box>
<YMaps>
<Map state={map} className={styles.element}>
{marks}
</Map>
</YMaps>
</div>
);
}
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SociedadAnonima extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'sociedades_anonimas';
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'bonita_case_id',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'nombre',
'fecha_creacion',
'domicilio_legal',
'domicilio_real',
'email_apoderado',
'numero_expediente',
'numero_hash',
'url_codigo_QR',
'estado_evaluacion',
'bonita_case_id',
'apoderado_id',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'fecha_creacion' => 'datetime',
];
/**
* Obtener los estados a los que exporta.
*/
public function estados()
{
return $this->belongsToMany(Estado::class, 'sociedades_anonimas_estados')->withTimestamps();
}
}
|
#include <stdio.h>
#include <math.h>
#include <time.h>
#include "shared_array.h"
#include "initialize_array.c"
long long int mov=0;
long long int comp=0;
void bublesort(int A[], int n){ //algoritmo simple y estable, porque compara siempre 2 posiciones
int i, j, aux, troca;
for (i=0; i < n-1; i++){ //lazo externo O(n)
troca=0; //para mejorar el algoritmo
for(j = 1; j<n-i;j++){ //lazo interno O(n) -> Costo total: O(n2)
comp=comp+1;
// printf("A[j],A[j-1] %d %d\n", A[j], A[j-1]);
// printf("\n");
if (A[j] < A[j-1]){ //O(n2) # de comparaciones
aux = A[j];
A[j] = A[j-1];
A[j-1] = aux; //3 moviment para cada caso verdadero M(n)<=3C(n) entao M(n)=O(n2)
troca=1;
mov=mov+3;
}
}
if (troca==0) //para mejorar el algortimo
break;
}
} //
void printArray(int A[], int n){
int i;
for (i=0;i<n;i++)
printf("%d ", A[i]);
printf("\n");
// printf("n es: %i\n", n);
}
int main(){
clock_t start_t, end_t;
double total_t;
int i;
start_t = clock();
//int A[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
//int A[]={13, 65, 55, 40, 50, 35, 38, 20, 10, 44, 25};
//int A[]={1, 3, 6, 9, 13, 100, 2};
int n =sizeof(shared_array)/sizeof(shared_array[0]);
//ALEATORY
// initialize_array(shared_array, ARRAY_SIZE);
// srand((unsigned)time(NULL));
// shuffle(shared_array, ARRAY_SIZE);
//Nearly Sorted - 0.30% aleatory
initialize_array(shared_array, ARRAY_SIZE);
srand((unsigned)time(NULL));
shuffle_last_portion(shared_array, ARRAY_SIZE, UNSORTED_PERCENT);
//Sorted
// initialize_array(shared_array, ARRAY_SIZE);
//Reverse Sorted
// initialize_reverse_array(shared_array, ARRAY_SIZE);
printf("Vector inicial: \n");
printim(shared_array, ARRAY_SIZE);
bublesort(shared_array, ARRAY_SIZE);
printf("Resultado del ordenamiento: \n");
printim(shared_array, ARRAY_SIZE);
printf("Movimentaciones: %lld", mov);
printf("\n");
printf("Comparaciones: %lld", comp);
printf("\n");
end_t = clock();
total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
// printf("%f\n", total_t );
printf("Total time taken by CPU: %f\n", total_t );
// printf("Exiting of the program...\n");
return 0;
}
|
package com.example.metricscalculator;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class SubstitutionActivity extends AppCompatActivity {
private FloatingActionButton addResultButton;
private FloatingActionButton homeButton;
private TableLayout resultTable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_substitution);
resultTable = findViewById(R.id.resultTable); // Adjust the ID based on your XML layout
addResultButton = findViewById(R.id.addResultButton); // Adjust the ID based on your XML layout
homeButton = findViewById(R.id.homeButton); // Adjust the ID based on your XML layout
DatabaseHelper dbHelper = new DatabaseHelper(this);
UserDataManager userDataManager = UserDataManager.getInstance();
int userId = dbHelper.getUserIdByUsername(userDataManager.getUsername());
List<SubstitutionResultData> resultList = dbHelper.getSubstitutionResultsForUser(userId);
if (!resultList.isEmpty()) {
for (SubstitutionResultData result : resultList) {
addTableRow(resultTable, result);
}
} else {
addEmptyTableRow(resultTable, "Πατήστε το κουμπί παρακάτω για να προσθέσετε αποτελέσματα Αντικατάστασης");
}
addResultButton.setOnClickListener(v -> {
Intent intent = new Intent(SubstitutionActivity.this, SubstitutionActivityResults.class); // Adjust the class based on your actual implementation
startActivity(intent);
});
homeButton.setOnClickListener(v -> {
Intent intent = new Intent(SubstitutionActivity.this, ProfileActivity.class);
intent.putExtra("username", UserDataManager.getUsername());
intent.putExtra("firstName", UserDataManager.getFirstName());
intent.putExtra("lastName", UserDataManager.getLastName());
intent.putExtra("dateOfBirth", UserDataManager.getDateOfBirth());
intent.putExtra("education", UserDataManager.getEducation());
startActivity(intent);
});
}
private void addEmptyTableRow(TableLayout tableLayout, String message) {
TableRow row = new TableRow(this);
TextView messageTextView = new TextView(this);
messageTextView.setText(message);
setTableRowAttributes(messageTextView);
row.addView(messageTextView);
tableLayout.addView(row);
}
private void addTableRow(TableLayout tableLayout, SubstitutionResultData result) {
TableRow row = new TableRow(this);
// Add TextView for Correct
TextView correctTextView = new TextView(this);
correctTextView.setText(String.valueOf(result.getCorrect()));
setTableRowAttributes(correctTextView);
row.addView(correctTextView);
// Add TextView for Response Time
TextView responseTimeTextView = new TextView(this);
responseTimeTextView.setText(String.valueOf(result.getResponseTime()));
setTableRowAttributes(responseTimeTextView);
row.addView(responseTimeTextView);
TableLayout.LayoutParams params = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT
);
row.setLayoutParams(params);
tableLayout.addView(row);
}
private void setTableRowAttributes(TextView textView) {
textView.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT
));
textView.setPadding(16, 16, 16, 16);
textView.setGravity(Gravity.CENTER);
}
}
|
<template>
<div>
<div class="mx-md-3 pb-2">
<div class="card px-3 pt-3 pb-4 mx-md-4">
<div class="px-3">
<div class="heading pb-2">
<img src="~/assets/icons/placeholder-icon.svg" alt class="mr-2" />
<h6 class="subheading d-inline-block">PERSONAL INFORMATION</h6>
</div>
<p style="color: #091F0E; font-size: 15px">
Use this page to update your contact information and change
password.
</p>
<div class="change-photo d-md-flex">
<label for="profile-pic" style="cursor: pointer">
<img
:src="userDetail.image || avatar"
alt
class="rounded-circle"
height="100px"
ref="avatar"
style="object-fit: cover;width: 100px;"
/>
</label>
<div class="ml-md-3 d-md-flex flex-column justify-content-center">
<div class="d-flex flex-column justify-content-center">
<label for="profile-pic" style="cursor: pointer">
<a
href="#"
class="py-2"
style="letter-spacing: 0; pointer-events: none;"
>Upload a new profile image</a
>
</label>
<input
type="file"
name="profile-pic"
id="profile-pic"
hidden
accept="image/*"
@change="previewImage()"
:disabled="loading.profile"
/>
<p class="py-1 m-0">
Maximum size allowed is 600kb of PNG, JPEG ,JPG.
</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-10">
<form class="mt-3 px-3 mr-md-4" @submit.prevent="updateUserProfile">
<div class="row">
<div class="col-lg-4 col-md-6 px-2">
<div class="form-input my-2">
<label for="email2">EMAIL ADDRESS</label>
<input
type="email"
name="email2"
id="email2"
class="form-control mt-0"
disabled
:value="userDetail.email"
/>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-6 px-2">
<div class="form-input my-2">
<label for="name2">FULL NAME</label>
<input
type="text"
name="name2"
id="name2"
class="form-control mt-0"
:class="{ invalid: $v.userDetail.fullName.$error }"
v-model="userDetail.fullName"
:disabled="loading.profile"
/>
<template v-if="$v.userDetail.fullName.$dirty">
<p
v-if="!$v.userDetail.fullName.required"
class="invalid"
>
This field is required
</p>
<p
v-else-if="!$v.userDetail.fullName.minLength"
class="invalid"
>
Name should not be less than 2 characters
</p>
</template>
</div>
</div>
<div class="col-lg-4 col-md-6 px-2">
<div class="form-input my-2">
<label for="username2">USER NAME</label>
<input
type="text"
name="username2"
id="username2"
class="form-control mt-0"
:class="{ invalid: $v.userDetail.username.$error }"
v-model="userDetail.username"
:disabled="loading.profile"
/>
<template v-if="$v.userDetail.username.$dirty">
<p
v-if="!$v.userDetail.username.required"
class="invalid"
>
This field is required
</p>
<p
v-else-if="!$v.userDetail.username.minLength"
class="invalid"
>
Username should not be less than 6 characters
</p>
</template>
</div>
</div>
<div class="col-lg-4 col-md-6 px-2">
<div class="form-input my-2">
<label for="dob2">BIRTH DATE</label>
<input
type="text"
name="dob2"
id="dob2"
class="form-control mt-0"
disabled
:value="userDetail.dob | formatDate($moment)"
@input="value => (userDetail.dob = value)"
/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 px-2">
<button
class="green-btn mt-2 d-flex justify-content-center align-items-center"
type="submit"
:disabled="loading.profile"
>
<div
class="spinner-grow text-success"
role="status"
v-if="loading.profile"
>
<span class="sr-only">Loading...</span>
</div>
<span>Save Changes</span>
</button>
</div>
</div>
</form>
</div>
</div>
<hr class="mx-2 mt-4" />
<div class="row">
<div class="col-md-10">
<p
v-if="errorMessage"
class="invalid px-2"
style="font-size: 14px !important; font-weight: 400; "
>
{{ errorMessage }}
</p>
<form class="px-3 mr-md-4" @submit.prevent="updateUserPassword">
<div class="row">
<div class="col-lg-4 col-md-6 my-2 px-2">
<div class="form-input">
<label for="password2">CURRENT PASSWORD</label>
<input
type="password"
name="password2"
id="password2"
class="form-control mt-0"
@focus="errorMessage = ''"
:class="{
invalid:
$v.payload.currentPassword.$error || errorMessage
}"
v-model="payload.currentPassword"
:disabled="loading.password"
/>
<template
v-if="
$v.payload.currentPassword.$dirty &&
$v.payload.currentPassword.$model
"
>
<p
v-if="!$v.payload.currentPassword.required"
class="invalid"
>
This field is required
</p>
<p
v-else-if="!$v.payload.currentPassword.minLength"
class="invalid"
>
Password should not be less than 6 characters
</p>
</template>
</div>
</div>
<div class="col-lg-4 col-md-6 my-2 px-2">
<div class="form-input">
<label for="new-password2">NEW PASSWORD</label>
<input
type="password"
name="new-password2"
id="new-password2"
class="form-control mt-0"
@focus="errorMessage = ''"
:class="{
invalid: $v.payload.newPassword.$error || errorMessage
}"
v-model="payload.newPassword"
:disabled="loading.password"
/>
<template v-if="$v.payload.newPassword.$dirty">
<p
v-if="!$v.payload.newPassword.required"
class="invalid"
>
This field is required
</p>
<p
v-else-if="!$v.payload.newPassword.minLength"
class="invalid"
>
Password should not be less than 6 characters
</p>
</template>
</div>
</div>
<div class="col-lg-4 col-md-6 my-2 px-2">
<div class="form-input">
<label for="confirm-password2">CONFIRM NEW PASSWORD</label>
<input
type="password"
name="confirm-password2"
id="confirm-password2"
class="form-control mt-0"
@focus="errorMessage = ''"
:class="{
invalid: $v.confirmPassword.$error || errorMessage
}"
v-model="confirmPassword"
:disabled="loading.password"
/>
<template v-if="$v.confirmPassword.$dirty">
<p v-if="!$v.confirmPassword.required" class="invalid">
This field is required
</p>
<p
v-else-if="!$v.confirmPassword.minLength"
class="invalid"
>
Password should not be less than 6 characters
</p>
<p v-else-if="$v.confirmPassword.$error" class="invalid">
Passwords do not match
</p>
</template>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 px-2">
<button
class="green-btn mt-2 d-flex justify-content-center align-items-center"
:disabled="loading.password"
>
<div
class="spinner-grow text-success"
role="status"
v-if="loading.password"
>
<span class="sr-only">Loading...</span>
</div>
<span>Save Changes</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import avatar from "~/assets/images/avatar.svg";
import {
required,
minLength,
maxLength,
email,
sameAs
} from "vuelidate/lib/validators";
import { mapActions, mapGetters } from "vuex";
export default {
data() {
return {
avatar,
file: "",
errorMessage: "",
loading: {
password: false,
profile: false
},
confirmPassword: "",
payload: {
newPassword: "",
currentPassword: ""
},
userDetail: {}
};
},
validations: {
payload: {
newPassword: {
required,
minLength: minLength(6)
},
currentPassword: {
required,
minLength: minLength(6)
}
},
confirmPassword: {
required,
minLength: minLength(6),
sameAs: sameAs(vm => {
return vm.payload.newPassword;
})
},
userDetail: {
fullName: {
required,
minLength: minLength(2)
},
username: {
required,
minLength: minLength(6)
}
}
},
computed: {
...mapGetters("user", ["getUser"])
},
filters: {
formatDate(val, moment) {
return moment(val).format("MMMM, YYYY");
}
},
methods: {
...mapActions("user", ["changePassword", "updateProfile"]),
...mapActions("auth", ["signIn", "logout"]),
previewImage() {
this.file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(this.file);
reader.onload = e => {
this.$refs.avatar.src = e.target.result;
};
},
updateUserPassword() {
this.$v.payload.$touch();
this.$v.confirmPassword.$touch();
if (this.$v.payload.$error === true || this.$v.confirmPassword.$error) {
return;
}
const self = this;
this.loading.password = true;
this.changePassword(this.payload)
.then(data => {
if (data.graphQLErrors) {
self.errorMessage = data.graphQLErrors[0].message;
self.$toast.error(data.graphQLErrors[0].message);
this.loading.password = false;
return;
}
this.loading.password = false;
self.$toast.success(data.successMessage);
this.resetPasswordForm();
// this.logout();
// this.signIn({
// username: this.getUser.username,
// password: this.payload.newPassword
// });
return;
})
.catch(err => {
this.loading.password = false;
});
},
updateUserProfile() {
this.$v.userDetail.$touch();
if (this.$v.userDetail.$error === true) {
return;
}
this.loading.profile = true;
const payload = {
fullName: this.userDetail.fullName,
username: this.userDetail.username
};
if (this.file) payload.file = this.file;
const self = this;
this.updateProfile(payload)
.then(data => {
this.loading.profile = false;
if (data.graphQLErrors) {
self.errorMessage = data.graphQLErrors[0].message;
self.$toast.error(data.graphQLErrors[0].message);
return;
}
self.$toast.success("Your profile has been updated!");
return;
})
.catch(err => {
this.loading.profile = false;
});
},
resetPasswordForm() {
this.confirmPassword = "";
this.payload = {
newPassword: "",
currentPassword: ""
};
this.$v.confirmPassword.$reset();
this.$v.payload.$reset();
}
},
beforeMount() {
this.userDetail = JSON.parse(JSON.stringify(this.getUser));
}
};
</script>
<style scoped>
.container-fluid {
background-image: url("~assets/images/account-settings-BG.svg");
background-repeat: no-repeat;
background-size: cover;
background-color: #f9fdfa;
}
h4 {
color: #091f0e;
font-size: 22px;
letter-spacing: 1.15px;
}
.card {
background: #ffffff;
border: 1px solid rgba(7, 131, 78, 0.2);
box-sizing: border-box;
border-radius: 1px;
box-shadow: 12px 10px 20px rgba(46, 91, 255, 0.07);
}
label {
color: #2c7742;
font-size: 12px;
letter-spacing: 1.25px;
/* font-weight: 600; */
}
input {
background: rgba(198, 226, 215, 0.2);
border: 1px solid #c6e2d7;
box-sizing: border-box;
border-radius: 4px;
height: 35px;
}
h6 {
color: #2c7742;
font-size: 13px;
letter-spacing: 1.25px;
}
.change-photo a {
text-decoration-line: underline;
color: #009966;
font-size: 13px;
}
.change-photo p {
color: #666666;
font-size: 12px;
}
.green-btn {
width: 200px;
height: 52px;
padding: 0 5px;
border: none;
/* border: 1px solid #FFFFFF; */
border-radius: 2px;
background: #07834e;
color: white;
}
input.form-control:disabled {
background: #e7e7e7;
border: 1px solid #d3d3d3;
box-sizing: border-box;
border-radius: 4px;
}
hr {
background: rgba(7, 131, 78, 0.2);
}
</style>
|
<!DOCTYPE html>
<html>
<head>
<style>
.large {
/*This class named "large" is defined with the specified styling*/
font-size: 200%;
text-align: right;
}
.center {
/*This center class is defined with the specified styling*/
text-align: center;
color: red;
}
#id {
/*This id is defined with the specified styling.ID selector can be used to select only one specific element*/
background-color: aqua;
color: tomato;
text-align: center;
}
h3,h5 {
/*Grouping selectors h4 and h5 together to save space*/
color: darkgoldenrod;
text-align: "left";
}
h4 {
color: aquamarine;
}
</style>
</head>
<body>
<h1 class="center">This heading uses class center</h1><!--h1 is defined under class center-->
<h2 class="large">dkfjdfnfn</h2> <!-- h2 is defined under class large -->
<p class="center large">This paragraph will be red and in a large font-size.</p>
<!-- h2 is defined under class large and center. It can be referred to more than one class -->
<p id="id">The id selector uses the id attribute of an HTML element to select a specific element.</p>
<!-- id is defined under token id.Id is unique and is used to select one unique element -->
<h3>The grouping selector selects all the HTML elements with the same style definitions.</h3>
<h3>The grouping selector selects all the HTML elements with the same style definitions.</h3>
<h4>The grouping selector selects all the HTML elements with the same style definitions.</h4>
</body>
</html>
|
package com.burakozkan138.cinemabookingsystem.controller;
import java.util.List;
import org.apache.coyote.BadRequestException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.burakozkan138.cinemabookingsystem.dto.Request.ReservationCreateRequestDto;
import com.burakozkan138.cinemabookingsystem.dto.Request.ReservationUpdateRequestDto;
import com.burakozkan138.cinemabookingsystem.dto.Response.BaseResponse;
import com.burakozkan138.cinemabookingsystem.dto.Response.ReservationResponseDto;
import com.burakozkan138.cinemabookingsystem.service.ReservationService;
import jakarta.annotation.security.RolesAllowed;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
@RequiredArgsConstructor
@RequestMapping("/reservations")
@PreAuthorize("isAuthenticated()")
public class ReservationController {
private final ReservationService reservationService;
@GetMapping
public BaseResponse<List<ReservationResponseDto>> getMyReservations()
throws BadRequestException {
List<ReservationResponseDto> reservations = reservationService.getMyReservations();
return new BaseResponse<>(reservations, "Reservations fetched successfully", true, HttpStatus.OK);
}
@GetMapping("/all")
@RolesAllowed("ADMIN")
public BaseResponse<List<ReservationResponseDto>> getAllReservations() {
List<ReservationResponseDto> reservations = reservationService.getAllReservations();
return new BaseResponse<>(reservations, "Reservations fetched successfully", true, HttpStatus.OK);
}
@GetMapping("/{id}")
public BaseResponse<ReservationResponseDto> getReservationById(@PathVariable String id)
throws BadRequestException {
ReservationResponseDto reservation = reservationService.getReservationById(id);
return new BaseResponse<>(reservation, "Reservation fetched successfully", true, HttpStatus.OK);
}
@PostMapping
public BaseResponse<ReservationResponseDto> createReservation(
@Valid @RequestBody ReservationCreateRequestDto reservationCreateRequestDto)
throws BadRequestException {
ReservationResponseDto reservation = reservationService.createReservation(reservationCreateRequestDto);
return new BaseResponse<>(reservation, "Reservation created successfully", true, HttpStatus.CREATED);
}
@PutMapping("/{id}")
public BaseResponse<ReservationResponseDto> updateReservation(@PathVariable String id,
@Valid @RequestBody ReservationUpdateRequestDto reservationCreateRequestDto)
throws BadRequestException {
ReservationResponseDto reservation = reservationService.updateReservationById(id,
reservationCreateRequestDto);
return new BaseResponse<>(reservation, "Reservation updated successfully", true, HttpStatus.OK);
}
@DeleteMapping("/{id}/cancel")
public BaseResponse<Boolean> cancelReservationById(@PathVariable String id)
throws BadRequestException {
Boolean data = reservationService.cancelReservationById(id);
return new BaseResponse<>(data, "Reservation cancelled successfully", true, HttpStatus.OK);
}
}
|
package com.scottlogic.filters;
import com.scottlogic.UserPost;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class OrFilterTest {
UserPost userPost1 = new UserPost("Joe Bloggs",
OffsetDateTime.of(2020, 1, 3, 7, 12, 3, 0, ZoneOffset.UTC),
"Hello World!", 2);
UserPost userPost2 = new UserPost("Joe Bloggs",
OffsetDateTime.of(2020, 1, 3, 7, 13, 3, 0, ZoneOffset.UTC),
"Hello World!", 2);
UserPost userPost3 = new UserPost("Albert Einstein",
OffsetDateTime.of(2020, 1, 3, 8, 53, 34, 0, ZoneOffset.UTC),
"Another example post.", 0);
UserPost userPost4 = new UserPost("Cucumber",
OffsetDateTime.of(2021, 3, 12, 13, 22, 12, 0, ZoneOffset.UTC),
"An example of a post \nwith lines breaks.", 3);
UserPost userPost5 = new UserPost("",
OffsetDateTime.of(2020, 1, 3, 7, 12, 3, 0, ZoneOffset.UTC),
"Welcome to the jungle of misery extraterrestrial", 0);
UserPost userPost6 = new UserPost("Luke Vincent",
OffsetDateTime.of(2021, 12, 8, 7, 12, 3, 0, ZoneOffset.UTC),
"I will not approve your PR", -1);
OffsetDateTime date1 = OffsetDateTime.of(2020, 1, 2, 7, 12, 3, 0, ZoneOffset.UTC);
OffsetDateTime date2 = OffsetDateTime.of(2020, 1, 3, 9, 12, 3, 0, ZoneOffset.UTC);
AuthorPostFilter authorPostFilter = new AuthorPostFilter("Joe Bloggs"); //includes userPosts 1-2
DatePostFilter datePostFilter = new DatePostFilter(date1, date2); //includes userPosts 1-2-3-5
KeywordPostFilter keywordPostFilter = new KeywordPostFilter("example"); //includes userPosts 3-4
LikePostFilter likePostFilter = new LikePostFilter(true); //includes userPosts 1-2-4
@Test
void orPostFilter_withNull_returnsEmptyList() {
List<UserPost> expected = Arrays.asList();
List<UserPost> initialList = null;
List<UserPost> filteredList = new OrFilter(authorPostFilter, keywordPostFilter).filter(initialList);
Assertions.assertEquals(expected, filteredList);
}
@Test
void orPostFilter_withEmptyList_returnsEmptyList() {
List<UserPost> initialList = Arrays.asList();
List<UserPost> expected = Arrays.asList();
List<UserPost> filteredList = new OrFilter(authorPostFilter, keywordPostFilter).filter(initialList);
Assertions.assertEquals(expected, filteredList);
}
@Test
void orPostFilter_withOneElement_returnsOneElement() {
List<UserPost> initialList = Arrays.asList(userPost1);
List<UserPost> expected = Arrays.asList(userPost1);
List<UserPost> filteredList = new OrFilter(authorPostFilter, likePostFilter).filter(initialList);
Assertions.assertEquals(expected, filteredList);
}
@Test
void orPostFilter_withMultipleElements_returnsOneElement() {
List<UserPost> initialList = Arrays.asList(userPost1, userPost2, userPost3, userPost4, userPost5, userPost6);
List<UserPost> expected = Arrays.asList(userPost1, userPost2, userPost3, userPost4);
List<UserPost> filteredList = new OrFilter(authorPostFilter, keywordPostFilter).filter(initialList);
Assertions.assertEquals(expected, filteredList);
}
@Test
void orPostFilter_withMultipleElements_returnsMultipleElements() {
List<UserPost> initialList = Arrays.asList(userPost1, userPost2, userPost3, userPost4, userPost5, userPost6);
List<UserPost> expected = Arrays.asList(userPost1, userPost2, userPost3, userPost5, userPost4);
List<UserPost> filteredList = new OrFilter(datePostFilter, likePostFilter).filter(initialList);
Assertions.assertEquals(expected, filteredList);
}
}
|
import { Link, useNavigate } from "react-router-dom";
import bg from "../assets/others/authentication.png";
import im from "../assets/others/authentication2.png";
import { useForm } from "react-hook-form";
import { useAuth } from "./../Hooks/useAuth";
import { GoogleLogin } from "../Component/GoogleLogin";
import Swal from "sweetalert2";
import { useAxiosPublic } from "../Hooks/useAxiosPublic";
export const Registration = () => {
const { createUser, updateUser, logOut } = useAuth();
const navigate = useNavigate();
const axiosPublic = useAxiosPublic();
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm();
const onSubmit = (data) => {
createUser(data.email, data.password)
.then(() => {
updateUser(data?.name)
.then(() => {
// userinfo set on database
axiosPublic
.post("/user", { name: data.name, email: data.email })
.then((res) => {
if (res.data.insertedId) {
console.log("user added to the database");
Swal.fire({
text: "Registration Successfully and now you can login",
icon: "success",
});
reset();
logOut().then(() => navigate("/login"));
}
});
})
.catch((er) => alert(er));
})
.catch((er) => console.log(er));
};
return (
<div>
<div style={{ backgroundImage: `url(${bg})` }}>
<div className="hero min-h-screen ">
<div className="hero-content shadow-2xl mt-10 rounded-lg grid grid-cols-1 md:grid-cols-2">
<div className="text-center order-2 lg:text-left">
<img src={im} alt="" />
</div>
<div className="card shrink-0 w-full max-w-sm ">
<form onSubmit={handleSubmit(onSubmit)} className="card-body">
<h1 className="text-3xl font-bold text-center">Sign Up</h1>
<div className="form-control">
<label className="label">
<span className="label-text">Name</span>
</label>
<input
{...register("name")}
aria-invalid={errors.name ? "true" : "false"}
type="text"
placeholder="Name"
className="input input-bordered"
/>
</div>
<div className="form-control">
<label className="label">
<span className="label-text">Email</span>
</label>
<input
{...register("email", { required: true })}
type="email"
placeholder="email"
className="input input-bordered"
/>
{errors.email && (
<span className="text-red-500">This field is required</span>
)}
</div>
<div className="form-control">
<label className="label">
<span className="label-text">Password</span>
</label>
<input
{...register("password", {
required: true,
minLength: 6,
pattern: /^(?:(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*)$/,
})}
type="password"
placeholder="password"
className="input input-bordered"
required
/>
{errors.password?.type === "required" && (
<span className="text-red-500">This field is required</span>
)}
{errors.password?.type === "minLength" && (
<span className="text-red-500">
Minimum length has to be 6
</span>
)}
{errors.password?.type === "pattern" && (
<span className="text-red-500">
Minimum one uppercase one lowercase and special char
</span>
)}
</div>
<div className="form-control mt-6">
<button className="btn bg-[#D1A054] text-white">Login</button>
</div>
<GoogleLogin />
</form>
<h1 className="text-center text-[#D1A054]">
Already Have An Account?{" "}
<Link to="/login" className="cursor-pointer font-bold">
Login Now
</Link>
</h1>
</div>
</div>
</div>
</div>
</div>
);
};
|
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:log/core/constants/app_contants.dart';
import 'package:log/presentation/providers/auth_provider.dart';
import 'package:provider/provider.dart';
class UserDetailsPage extends StatefulWidget {
final User user;
UserDetailsPage({required this.user});
@override
_UserDetailsPageState createState() => _UserDetailsPageState();
}
class _UserDetailsPageState extends State<UserDetailsPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.user.name),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
radius: 100,
backgroundImage: NetworkImage(widget.user.image),
),
SizedBox(height: 20),
Text(
widget.user.name,
style: TextStyle(fontSize: 24),
),
],
),
),
);
}
}
class UserListPage extends StatefulWidget {
const UserListPage({Key? key}) : super(key: key);
@override
State<UserListPage> createState() => _UserListPageState();
}
class _UserListPageState extends State<UserListPage> {
late List<User> userList;
bool isDataLoaded = false;
String errorMessage = '';
List<User> filteredUserList = [];
@override
void initState() {
super.initState();
getUsers();
}
Future<void> getUsers() async {
String userEmail = context.read<AuthProvider>().user.email;
try {
Uri uri = Uri.parse('$baseUrl/ListOfusers/$userEmail');
var response = await http.get(uri);
if (response.statusCode == 200) {
List<User> users = (json.decode(response.body) as List)
.map((data) => User.fromJson(data))
.toList();
setState(() {
userList = users;
filteredUserList = userList;
isDataLoaded = true;
});
} else {
print('Error: ${response.statusCode}');
setState(() {
isDataLoaded = true;
errorMessage = 'Error loading users';
});
}
} catch (error) {
print('Error: $error');
setState(() {
isDataLoaded = true;
errorMessage = 'Error loading users';
});
}
}
void onSearch(String search) {
setState(() {
filteredUserList = userList
.where(
(user) => user.name.toLowerCase().contains(search.toLowerCase()))
.toList();
});
if (filteredUserList.isEmpty) {
// Show an Awesome Dialog when no results are found
AwesomeDialog(
context: context,
dialogType: DialogType.ERROR,
animType: AnimType.SCALE,
title: 'No Results Found',
desc: 'No users match your search criteria.',
btnCancelOnPress: () {},
btnOkOnPress: () {
// Clear the search text field when the dialog is dismissed
clearSearch();
},
)..show();
}
}
void clearSearch() {
setState(() {
// Clear the search text
filteredUserList = userList;
});
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
// Background Image
Image.asset(
'images/cover2.jpg',
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
// Your existing content
Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
elevation: 0,
backgroundColor: Color.fromARGB(255, 245, 220, 233),
title: Container(
height: 38,
child: TextField(
onChanged: (value) => onSearch(value),
decoration: InputDecoration(
filled: true,
fillColor: Color.fromRGBO(205, 245, 250, 0.898),
contentPadding: EdgeInsets.all(0),
prefixIcon: Icon(
Icons.search,
color: Color.fromARGB(255, 252, 50, 154),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: BorderSide.none,
),
hintStyle: TextStyle(
fontSize: 14,
color: Color.fromARGB(255, 252, 50, 154),
),
hintText: "Search users",
),
),
),
),
body: isDataLoaded
? errorMessage.isNotEmpty
? Text(errorMessage)
: userList.isEmpty
? const Text('No Data')
: ListView.builder(
itemCount: filteredUserList.length,
itemBuilder: (context, index) =>
getUserRow(index, filteredUserList[index]),
)
: const Center(
child: CircularProgressIndicator(),
),
),
],
);
}
Widget getUserRow(int index, User user) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UserDetailsPage(user: user),
),
);
},
child: ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(user.image),
),
title: Text(user.name),
subtitle: Text(
'${user.email}, ${user.phone ?? ""}',
),
trailing: ElevatedButton(
onPressed: () {
if (user.isFollowing) {
unfollowUser(user);
} else {
followUser(user);
}
},
style: ElevatedButton.styleFrom(
primary: user.isFollowing
? Color.fromARGB(255, 252, 50, 154)
: Color.fromARGB(255, 55, 164, 241),
),
child: Text(user.isFollowing ? 'Unfollow' : 'Follow'),
),
),
);
}
Future<void> followUser(User user) async {
try {
String userEmail = context.read<AuthProvider>().user.email;
Uri uri = Uri.parse('$baseUrl/usersfollow/${userEmail ?? ''}');
final response = await http.post(
uri,
body: {
'followUserEmail': user.email,
'follow': (!user.isFollowing).toString(),
},
);
if (response.statusCode == 200) {
setState(() {
user.isFollowing = !user.isFollowing;
});
} else {
// Handle the error here
}
} catch (error) {
print("Follow User Error: $error");
}
}
Future<void> unfollowUser(User user) async {
try {
String userEmail = context.read<AuthProvider>().user.email;
Uri uri = Uri.parse('$baseUrl/usersunfollow/${userEmail ?? ''}');
final response = await http.delete(
uri,
body: {
'followUserEmail': user.email,
'follow': user.isFollowing ? 'true' : 'false',
},
);
if (response.statusCode == 200) {
setState(() {
user.isFollowing = !user.isFollowing;
});
} else {
// Handle the error here
}
} catch (error) {
print("Unfollow User Error: $error");
}
}
}
class User {
final String name;
final String email;
final String image;
bool isFollowing;
final String? phone;
User({
required this.name,
required this.email,
required this.image,
this.isFollowing = false,
this.phone,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json['name'] ?? '',
email: json['email'] ?? '',
phone: json['phone'] ?? '',
image: json['image'] ?? '',
isFollowing: json['isFollowing'] ?? false,
);
}
}
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class CachedImage extends StatelessWidget {
CachedImage(
{super.key,
required this.imageUrl,
this.borderRadius,
this.boxFit,
this.width,
this.height});
final String imageUrl;
final double? borderRadius;
final BoxFit? boxFit;
final double? width;
final double? height;
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(borderRadius ?? 0),
child: CachedNetworkImage(
imageUrl: imageUrl,
fit: boxFit,
width: width,
height: height,
alignment: Alignment.center,
errorWidget: (context, url, error) => Container(
color: Colors.red,
child: Text(error),
),
placeholder: (context, url) => Container(color: Colors.white),
),
);
}
}
|
#include "Router.hpp"
#include <map>
#include <string>
#include <Poco/URI.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include "RouteId.hpp"
struct Router::Impl
{
std::map<RouteId, handler_type> routes;
};
void Router::add(const std::string& path, handler_type handler)
{
impl->routes[RouteId(path)] = std::move(handler);
}
Router::Router()
: impl(new Impl)
{
}
Router::~Router()
{
delete impl;
impl = nullptr;
}
void Router::handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
using Poco::URI;
const auto path = URI(request.getURI()).getPath();
auto it = impl->routes.find(RouteId(path));
if (it == impl->routes.end())
{
response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
response.send();
return;
}
it->second(request, response);
}
|
import { Edit, Delete } from '@mui/icons-material'
import { ReactNode } from 'react'
import { MenuItems } from '../../components/DataTable/components/MenuItems'
import { ColumnProps } from '../../components/DataTable/types'
export type DataTableMenuItems = {
title: string
icon: ReactNode
onClick?: (evt?: any) => void
}
const userMenuItems: (
row: any
) => DataTableMenuItems[] = (row) => [
{
title: "Editar",
icon: <Edit />,
onClick: () => {
console.log("Editar")
},
},
{
title: "Excluir",
icon: <Delete />,
onClick: () => {
console.log("Excluir")
},
},
]
export const userColumns: () => ColumnProps[] = () => [
{
name: 'Name',
selector: 'name',
id: 'name',
},
{
name: 'Email',
selector: 'email',
id: 'email',
},
{
name: 'Ações',
selector: 'actions',
id: 'actions',
customCell: (row) => (
<MenuItems
menuItems={userMenuItems(row)}
>
</MenuItems>
),
},
]
|
// Package main runs the MJS in Kubernetes controller
// Copyright 2024 The MathWorks, Inc.
package main
import (
"controller/internal/config"
"controller/internal/controller"
"controller/internal/logging"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"go.uber.org/zap"
)
func main() {
config, err := loadConfig()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Create logger
logger, loggerErr := logging.NewLogger(config.ControllerLogfile, config.LogLevel)
if loggerErr != nil {
fmt.Printf("Error creating logger: %v\n", loggerErr)
os.Exit(1)
}
defer logger.Close()
// Catch SIGTERMs in a channel
cancelChan := make(chan os.Signal, 1)
signal.Notify(cancelChan, syscall.SIGTERM, syscall.SIGINT)
// Run controller
logger.Info("Starting MJS controller")
scaler, err := controller.NewController(config, logger)
if err != nil {
fmt.Println(err)
logger.Error("Error creating controller", zap.Any("error", err))
os.Exit(1)
}
go scaler.Run()
// Block until a cancellation is received
sig := <-cancelChan
logger.Info("Caught signal; shutting down", zap.Any("sig", sig))
scaler.Stop()
}
// loadConfig reads the path to a config file from the command line arguments and reads in the config file
func loadConfig() (*config.Config, error) {
var configFile string
flag.StringVar(&configFile, "config", "", "Path to config file")
flag.Parse()
if configFile == "" {
return nil, errors.New("must provide path to config file")
}
return config.LoadConfig(configFile)
}
|
'use strict'
/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')
class AlbumsSchema extends Schema {
up() {
this.create('albums', (table) => {
table.increments()
table
.integer('account_id')
.notNullable()
.unsigned()
.references('id')
.inTable('accounts')
.onDelete('CASCADE')
.onUpdate('CASCADE')
table.string('album_name', 300).notNullable()
table
.integer('is_private', 1)
.default(0)
.notNullable()
.comment('0 for Public, 1 for Private')
table.string('type', 30).nullable().comment('own/favourite')
table
.integer('status', 1)
.default(1)
.notNullable()
.comment('0 for Inactive, 1 for Active')
table.timestamps()
})
}
down() {
this.drop('albums')
}
}
module.exports = AlbumsSchema
|
import offer from "../assets/offer.png";
import { motion } from "framer-motion";
const SpecialOffer = () => {
return (
<section className="my-36">
<div className="flex flex-col-reverse lg:flex-row gap-14">
<motion.div
initial={{ translateX: -50 }}
animate={{ translateX: 100 }}
transition={{
repeat: Infinity,
repeatType: "reverse", // This makes the animation reverse after each repeat
duration: 2, // Adjust the duration as needed
ease: "linear", // Use linear easing for a constant speed
}}
>
<img src={offer} alt="offer" />
</motion.div>
<div className="flex flex-col ">
<h1 className="text-6xl font-bold font-palanquin">
<span className="text-pink-500">Special </span>
Offer
</h1>
<p className="mt-4 lg:max-w-lg text-gray-400">
🍎 Back to School Special Offer! 🎒 <br /> Gear up for a successful
academic year with our exclusive Back to School deals on Apple
products.
</p>
<p className="font-montserrat mt-6 lg:max-w-lg text-gray-400 ">
Elevate your learning experience with the latest Apple devices at
unbeatable prices. From powerful MacBooks for your studies to iPads
that spark creativity, we've got you covered. Don't miss out on this
limited-time offer – it's the perfect way to start your journey back
to school with style and innovation! 📚💻🍏
<span className="text-blue-400">
#BackToSchool #AppleSpecialOffer"
</span>
</p>
<div className="mt-10 flex gap-5">
<button className=" font-poppins justify-between bg-pink-400 text-white flex items-center gap-3 rounded-full px-6 py-3 text-xl hover:bg-pink-300 transition-all duration-300 ease-in-out">
<p>View details</p>
</button>
<button className="font-poppins justify-between text-gray-400 bg-white border-gray-400 border-2 flex items-center gap-3 rounded-full px-6 py-3 text-xl transition-all duration-300 ease-in-out">
<p>Learn more</p>
</button>
</div>
</div>
</div>
</section>
);
};
export default SpecialOffer;
|
//
// ContentView.swift
// Recipe List App
//
// Created by Christopher Ching on 2021-01-14.
//
import SwiftUI
struct RecipeListView: View {
// Reference the view model
@EnvironmentObject var model: RecipeModel
var body: some View {
NavigationView {
ScrollView{
LazyVStack(alignment: .leading){
ForEach(model.recipes) { r in
NavigationLink(
destination: RecipeDetailView(recipe:r),
label: {
// MARK: Row item
HStack(spacing: 20.0) {
Image(r.image)
.resizable()
.scaledToFill()
.frame(width: 50, height: 50, alignment: .center)
.clipped()
.clipShape(Circle())
//.cornerRadius(5)
VStack(alignment: .leading){
Text(r.name)
.font(Font.custom("Avenir Heavy", size: 16))
highlights(highlights: r.highlights)
.font(Font.custom("Avenir", size: 13))
.foregroundColor(.gray)
}
}
})
}
}.foregroundColor(.black)
.padding()
}.navigationBarTitle("All Recipes")
}
}
}
struct RecipeListView_Previews: PreviewProvider {
static var previews: some View {
RecipeListView()
}
}
|
import React, { useState } from "react";
import { FaUser, FaHeart, FaSearch } from "react-icons/fa";
import Modal from "react-modal";
import "react-datepicker/dist/react-datepicker.css";
import "./ProjectPage.css";
import Result from "../../Components/common/Result/Result";
Modal.setAppElement("#root");
const Semantor = () => {
const results = [
{ id: 1, title: "Card Title 1", summary: "Summary text for Card 1..." },
{ id: 2, title: "Card Title 2", summary: "Summary text for Card 2..." },
{ id: 3, title: "Card Title 3", summary: "Summary text for Card 3..." },
];
const [selectedProject, setSelectedProject] = useState(null);
const [sidebarProjects, setSidebarProjects] = useState([]);
const [searchType, setSearchType] = useState("semantic");
const nonSelectedProjects = results.filter(p => p.id !== selectedProject?.id);
const [hasSelectedProject, setHasSelectedProject] = useState(false);
const handleCardClick = (project) => {
setSelectedProject(project);
setHasSelectedProject(true);
// Add more logic if needed
};
const clearSelection = () => {
setSelectedProject(null);
setHasSelectedProject(false);
};
return (
<div className="semantor-container">
<header className="semantor-header">
<h1>SEMANTOR</h1>
<div className="semantor-user-icons">
<FaUser className="user-icon" />
<FaHeart className="heart-icon" />
</div>
</header>
<div className="semantor-body">
<aside className="semantor-sidebar">
<div className="sidebar-item">
<a href="/History">History</a>
</div>
<br></br>
<div className="sidebar-item">
<a href="/search">Back to Search....</a>
</div>
<br />
<div className="line"></div>
<br />
<button className="add-project-btn">
Add Project
</button>
{hasSelectedProject && (
<>
<button className="back-button" onClick={clearSelection}>
Back to all projects
</button>
<div className="sidebar-title">Projects</div>
{nonSelectedProjects.map(project => (
<div key={project.id} className="sidebar-project-item" onClick={() => handleCardClick(project)}>
{project.title}
</div>
))}
</>
)}
</aside>
<main className="semantor-main">
{selectedProject ? (
<>
<h1 className="project-title">{selectedProject.title}</h1>
<div className="search-section">
<div className="search-type-buttons">
<button
className={`search-type-button ${searchType === "semantic" ? "active" : ""
}`}
onClick={() => setSearchType("semantic")}
>
Semantic
</button>
<button
className={`search-type-button ${searchType === "keyword" ? "active" : ""
}`}
onClick={() => setSearchType("keyword")}
>
Keyword
</button>
</div>
<div className="search-input">
<input type="text" placeholder="Search...." onKeyPress={(e) => {
if (e.key === 'Enter') {
// handleSearch(e);
}
}} />
<FaSearch className="search-icon" />
</div>
{/* ...render the selected project's results here using result components... */}
</div>
</>
) : (
<>
<h1 className="project-title">Projects:</h1>
<div className="result-box">
{results.map((result) => (
<div
className="card"
key={result.id}
onClick={() => handleCardClick(result)}
>
<div className="card-header">{result.title}</div>
<div className="card-content">
<div className="card-text">{result.summary}</div>
</div>
</div>
))}
</div>
</>
)}
</main>
</div>
</div>
);
};
export default Semantor;
|
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300..800;1,300..800&display=swap');
@import url("utilities.css");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: var(--white-color);
color: var(--black-color);
font-family: "Open Sans", sans-serif;
font-optical-sizing: auto;
font-style: normal;
font-variation-settings: "wdth" 100;
font-weight: 400;
line-height: 1.6rem;
}
ul {
list-style: none;
}
a {
color: var(--black-color);
text-decoration: none;
}
h1, h2 {
line-height: 1.2rem;
}
p {
margin: 10px 0;
}
img {
width: 100%;
}
/* Navbar */
.navbar {
align-items: center;
background-color: var(--black-color);
color: var(--white-color);
display: flex;
height: 70px;
justify-content: space-between;
opacity: .8;
padding: 0 30px;
position: fixed;
top: 0;
width: 100%;
}
.navbar .logo {
align-items: center;
display: flex;
}
.navbar .logo .l-icon {
margin-right: 8px;
}
.navbar ul {
display: flex;
}
.navbar a {
color: var(--white-color);
padding: 10px 20px;
margin: 0 5px;
}
.navbar a:hover {
border-bottom: 2px solid var(--primary-color);
}
/* Hero */
.hero * {
z-index: 5;
}
.hero {
background: url(../img/home/showcase.jpg) no-repeat center center/cover;
height: 100vh;
position: relative;
color: var(--white-color);
}
.hero::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .5);
}
.hero .content {
display: flex;
flex-direction: column;
align-items: center;
height: 100%;
justify-content: center;
}
.hero .content h1 {
font-size: 3.4rem;
}
.hero .content p {
font-size: 1.4rem;
/* avoid width extension */
max-width: 600px;
/* top l/r bottom */
margin: 20px 0 30px;
}
/* About-services */
.about {
padding: 30px;
margin: 90px 0;
}
/* Cases */
.cases {
margin: 90px 0;
}
.cases img:hover {
opacity: .7;
}
@media (max-width: 768px) {
.cases {
margin: 60px 0;
}
}
/* Team */
.team {
margin: 90px 0;
}
.team img {
border-radius: 5px;
margin-bottom: 15px;
}
@media (max-width: 768px) {
.team {
margin: 60px 0;
}
}
/* Contact */
.callback-form {
padding: 20px 0;
width: 100%;
}
.callback-form label {
display: block;
margin-bottom: 5px;
}
.callback-form .form-control {
margin-bottom: 15px;
}
.callback-form input[type=text],
.callback-form input[type=email] {
border-radius: 5px;
border: 2px solid var(--white-color);
height: 40px;
outline: none;
padding: 4px;
width: 100%;
}
@media (max-width: 768px) {
.callback-form .form-control {
margin-bottom: 20px;
}
}
/* Footer */
.footer {
display: flex;
justify-content: center;
}
/* Mobile */
@media (max-width: 768px) {
/* Navbar */
.navbar {
flex-direction: column;
height: 120px;
padding: 20px;
}
.navbar a {
padding: 10px;
margin: 0 3px;
}
/* Hero */
.hero .content h1 {
font-size: 2rem;
padding: 15px 0;
}
.hero .content p {
text-align: center;
}
/* About */
.about {
margin: 60px 0;
}
}
|
import { Request, Response } from 'express';
import createHttpError from 'http-errors';
import Collection, { ICollection } from '../models/collection.model';
import { IVendor } from '../models/vendor.model';
export const createCollection = async (req: Request, res: Response) => {
try {
if (!(req.user as IVendor).isVerified) {
throw new createHttpError.BadRequest('You are not verified');
}
const collection = new Collection({
vendorId: req.user._id,
...req.body,
});
await collection.save();
res.status(201).json({
data: collection,
});
} catch (error: any) {
res.status(error.statusCode || 500).json({
errors: {
common: {
msg: error.message || 'Server error occured',
},
},
});
}
};
export const getSingleCollection = async (req: Request, res: Response) => {
try {
const { collectionId } = req.params as { collectionId: string };
const collection = await Collection.findById(collectionId);
res.status(200).json({
data: collection,
});
} catch (error: any) {
res.status(error.statusCode || 500).json({
errors: {
common: {
msg: error.message || 'Server error occured',
},
},
});
}
};
export const getCollections = async (req: Request, res: Response) => {
try {
if (!(req.user as IVendor).isVerified) {
throw new createHttpError.BadRequest('You are not verified');
}
let { page, size } = req.query as { page: string | number; size: string | number };
if (!page) page = 1;
if (!size) size = 10;
const limit = +size;
const skip = (+page - 1) * +size;
const collections = await Collection.find({ vendorId: req.user.id })
.limit(limit)
.skip(skip);
res.status(200).json({
page,
size,
data: collections,
});
} catch (error: any) {
res.status(error.statusCode || 500).json({
errors: {
common: {
msg: error.message || 'Server error occured',
},
},
});
}
};
export const updateCollection = async (req: Request, res: Response) => {
try {
if (!(req.user as IVendor).isVerified) {
throw new createHttpError.BadRequest('You are not verified');
}
const { collectionId } = req.params as { collectionId: string };
const { name, productIds } = req.body as ICollection;
const collection = await Collection.findById(collectionId);
if (!collection) {
throw new createHttpError.BadRequest('Invalid collection id');
}
if (collection.vendorId.toString() !== req.user.id) {
throw new createHttpError.BadRequest('You are not the vendor of this collection');
}
if (name) collection.name = name;
if (productIds) collection.productIds = productIds;
await collection.save();
res.status(200).json({
data: collection,
});
} catch (error: any) {
res.status(error.statusCode || 500).json({
errors: {
common: {
msg: error.message || 'Server error occured',
},
},
});
}
};
export const deleteCollection = async (req: Request, res: Response) => {
try {
if (!(req.user as IVendor).isVerified) {
throw new createHttpError.BadRequest('You are not verified');
}
const { collectionId } = req.params as { collectionId: string };
const collection = await Collection.findById(collectionId);
if (!collection) {
throw new createHttpError.BadRequest('Invalid collection id');
}
if (collection.vendorId.toString() !== req.user.id) {
throw new createHttpError.BadRequest('You are not the vendor of this collection');
}
const deletedCollection = await collection.delete();
if (!deletedCollection) {
throw new createHttpError.InternalServerError('delete failed');
}
res.status(204).json({
message: 'Collection deleted successfully',
});
} catch (error: any) {
res.status(error.statusCode || 500).json({
errors: {
common: {
msg: error.message || 'Server error occured',
},
},
});
}
};
|
<!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">
<link rel="stylesheet" href="CSS/styling.css">
<!-- add google font -->
<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@200;300;400;500&display=swap" rel="stylesheet">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/fontawesome.min.css">
<title>Eduford</title>
</head>
<body>
<section class="sub-header">
<nav>
<a href="index.html"><img src="images/logo.png"></a>
<div class="nav-links" id="navLinks">
<!-- add close icon on mobile view -->
<i class="fa fa-times" onclick="hideMenu()"></i>
<ul>
<li><a href="index.html">HOME</a></li>
<li><a href="about.html">ABOUT</a></li>
<li><a href="course.html">COURSE</a></li>
<li><a href="blog.html">INSIGHT</a></li>
<li><a href="contact-page.html">CONTACT</a></li>
</ul>
</div>
<i class="fa fa-bars" onclick="showMenu()"></i>
</nav>
<h1>Our Courses</h1>
</section>
<!-- ------------------Courses section ---------------- -->
<!---------- Add Courses --------->
<section class="course">
<h1>Courses We Offers</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit!</p>
<div class="row">
<div class="course-col">
<h3>Intermediate</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Inventore deserunt delectus exercitationem
rerum? Dolorem praesentium, et optio excepturi fuga eos consequatur molestiae sint asperiores,
corrupti necessitatibus neque! Explicabo, quam ipsa?</p>
</div>
<div class="course-col">
<h3>Degree</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Inventore deserunt delectus exercitationem
rerum? Dolorem praesentium, et optio excepturi fuga eos consequatur molestiae sint asperiores,
corrupti necessitatibus neque! Explicabo, quam ipsa?</p>
</div>
<div class="course-col">
<h3>Post Graduation</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Inventore deserunt delectus exercitationem
rerum? Dolorem praesentium, et optio excepturi fuga eos consequatur molestiae sint asperiores,
corrupti necessitatibus neque! Explicabo, quam ipsa?</p>
</div>
</div>
</section>
<!-- --------Facilities ----------- -->
<section class="facilitiess">
<h1>Our Facilities</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit!</p>
<div class="row">
<div class="facilities-col">
<img src="images/library.png" alt="">
<h4>World Class Library</h4>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatibus, ratione! Lorem, ipsum.
</p>
</div>
<div class="facilities-col">
<img src="images/basketball.png" alt="">
<h4>Largest Play Ground</h4>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatibus, ratione! Lorem, ipsum.
</p>
</div>
<div class="facilities-col">
<img src="images/cafeteria.png" alt="">
<h4>Testy and healthy Food</h4>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatibus, ratione! Lorem, ipsum.
</p>
</div>
</div>
</section>
<!-- --------Footer------- -->
<section class="footer">
<h4>About Us</h4>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Inventore deserunt delectus exercitationem
rerum? Dolorem praesentium,<br> et optio excepturi fuga eos consequatur molestiae sint asperiores,
corrupti necessitatibus neque! Explicabo, quam ipsa?</p>
<div class="icons">
<i class="fa fa-facebook"></i>
<i class="fa fa-twitter"></i>
<i class="fa fa-instagram"></i>
<i class="fa fa-linkedin"></i>
</div>
<p>Made with <i class="fa fa-heart-o"></i> by easy Tutorial</p>
</section>
<!---------JavaScript for Toggle menu ------->
<script>
var navLinks = document.getElementById("navLinks");
function showMenu() {
navLinks.style.right = "0";
}
function hideMenu() {
navLinks.style.right = "-220px";
}
</script>
</body>
</html>
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WebChoThueXe.Models;
using WebChoThueXe.Repository;
namespace WebChoThueXe.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Roles = "Admin")]
public class CategoryController : Controller
{
private readonly DataContext _dataContext;
public CategoryController(DataContext context)
{
_dataContext = context;
}
//Index
public async Task<IActionResult> Index()
{
return View(await _dataContext.Categories.OrderByDescending(p => p.Id).ToListAsync());
}
//create
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CategoryModel category)
{
if (ModelState.IsValid)//tinh trang model
{
category.Slug = category.Name.Replace(" ", "-");
var slug = await _dataContext.Categories.FirstOrDefaultAsync(p => p.Slug == category.Slug);
if (slug != null)
{
ModelState.AddModelError("", "Danh Mục đã có trong database");
return View(category);
}
_dataContext.Add(category);
await _dataContext.SaveChangesAsync();
TempData["success"] = "Thêm Danh Mục Thành Công";
return RedirectToAction("Index");
}
else//neu khong kiem tra model
{
TempData["error"] = "Model Có Một Vài Chỗ Đang Lỗi";
List<string> errors = new List<string>();
foreach (var value in ModelState.Values)
{
foreach (var error in value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
string errorMessage = string.Join("\n", errors);
return BadRequest(errorMessage);
}
return View(category);
}
//edit
public async Task<IActionResult> Edit(int Id)
{
CategoryModel category = await _dataContext.Categories.FirstAsync(p => p.Id == Id);
return View(category);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(CategoryModel category)
{
if (ModelState.IsValid)//tinh trang model
{
category.Slug = category.Name.Replace(" ", "-");
var slug = await _dataContext.Categories.FirstOrDefaultAsync(p => p.Slug == category.Slug);
if (slug != null)
{
ModelState.AddModelError("", "Danh Mục đã có trong database");
return View(category);
}
_dataContext.Update(category);
await _dataContext.SaveChangesAsync();
TempData["success"] = "Cập Nhật Danh Mục Thành Công";
return RedirectToAction("Index");
}
else//neu khong kiem tra model
{
TempData["error"] = "Model Có Một Vài Chỗ Đang Lỗi";
List<string> errors = new List<string>();
foreach (var value in ModelState.Values)
{
foreach (var error in value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
string errorMessage = string.Join("\n", errors);
return BadRequest(errorMessage);
}
return View(category);
}
//delete
public async Task<IActionResult> Delete(int Id)
{
CategoryModel category = await _dataContext.Categories.FirstAsync(p => p.Id == Id);
_dataContext.Categories.Remove(category);
await _dataContext.SaveChangesAsync();
TempData["error"] = "Sản Phẩm Đã Xoá";
return RedirectToAction("Index");
}
}
}
|
import * as S from './style';
import * as I from '../../assets/svg';
import { Link, useNavigate } from 'react-router-dom';
import Input from 'components/Common/Input';
import { useForm } from 'react-hook-form';
import { SigninInterface } from 'types/auth';
import { useState } from 'react';
import auth from 'api/auth';
import { toast } from 'react-toastify';
import tokenService from 'utils/tokenService';
export default function SigninPage() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<SigninInterface>();
const [isError, setIsError] = useState(false);
const navigate = useNavigate();
const onValid = async (data: SigninInterface) => {
try {
const res: any = await auth.signin(data.email, data.password);
setIsError(false);
toast.success('로그인에 성공했습니다!', { autoClose: 2000 });
navigate('/');
tokenService.setUser(res.data);
} catch (error: any) {
switch (error.response.status) {
case 400:
toast.error('가입된 계정이 아닙니다.', { autoClose: 2000 });
break;
case 401:
toast.error('비밀번호가 틀렸습니다.', { autoClose: 2000 });
break;
}
}
};
const inValid = (error: any) => {
console.log(error);
setIsError(true);
};
return (
<S.SigninLayout>
<S.SigninSection>
<Link to="/">
<I.Back />
</Link>
<S.WelcomeBack>
Welcome
<br />
Back!
</S.WelcomeBack>
<p>돌아오신걸 환영해요!</p>
</S.SigninSection>
<S.SigninBox onSubmit={handleSubmit(onValid, inValid)}>
<Input
register={register('email', {
required: '이메일을 입력해주세요.',
pattern: {
message: '잘못된 이메일 형식입니다.',
value: /^s[0-9]+$/,
},
minLength: {
value: 6,
message: '6자를 모두 입력해 주세요',
},
})}
type="text"
email={true}
isError={isError}
placeholder="@gsm.hs.kr"
/>
<S.ErrorMessageLayout>
<S.ErrorMessage>{errors.email?.message}</S.ErrorMessage>
</S.ErrorMessageLayout>
<Input
register={register('password', {
required: '비밀번호를 입력해주세요.',
pattern: {
message: '영문, 숫자, 기호 포함 8~20자',
value:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
},
maxLength: {
value: 20,
message: '영문, 숫자, 기호 포함 8~20자',
},
minLength: {
value: 8,
message: '영문, 숫자, 기호 포함 8~20자',
},
})}
type="password"
placeholder="비밀번호"
isError={isError}
/>
<S.ErrorMessageLayout>
<S.ErrorMessage>{errors.password?.message}</S.ErrorMessage>
</S.ErrorMessageLayout>
<span>
<S.SignWrap>
<S.Signin>로그인</S.Signin>
<Link to="/signup_email">
<S.Signup>회원가입</S.Signup>
</Link>
</S.SignWrap>
<button>
<I.LoginButton />
</button>
</span>
</S.SigninBox>
</S.SigninLayout>
);
}
|
package br.com.cadsma.gestormobileapi.entities;
import br.com.cadsma.gestormobileapi.entities.pks.SetorPk;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
@Entity(name = Setor.ENTITY_NAME)
@IdClass(SetorPk.class)
public class Setor {
public static final String ENTITY_NAME = "SETOR";
@Id
@Column(name = "EMPRESA_CODIGO", nullable = false)
@JsonProperty("EMPRESA_CODIGO")
@ApiModelProperty(example = "2", required = true)
private int codigoEmpresa;
@Id
@Column(name = "CODIGO", nullable = false)
@JsonProperty("CODIGO")
@ApiModelProperty(example = "1", required = true)
private int codigo;
@Column(name = "NOME", nullable = false)
@JsonProperty("NOME")
@ApiModelProperty(example = "Setor 1", required = true)
private String nome;
@Column(name = "AREA", nullable = false)
@JsonProperty("AREA")
@ApiModelProperty(example = "1", required = true)
private int codigoArea;
@Column(name = "SUPERVISOR", nullable = false)
@JsonProperty("SUPERVISOR")
@ApiModelProperty(example = "10", required = true)
private int codigoSupervisor;
public int getCodigoEmpresa() {
return codigoEmpresa;
}
public void setCodigoEmpresa(int codigoEmpresa) {
this.codigoEmpresa = codigoEmpresa;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getCodigoArea() {
return codigoArea;
}
public void setCodigoArea(int codigoArea) {
this.codigoArea = codigoArea;
}
public int getCodigoSupervisor() {
return codigoSupervisor;
}
public void setCodigoSupervisor(int codigoSupervisor) {
this.codigoSupervisor = codigoSupervisor;
}
}
|
/*
* Copyright 2021-2023 Nickid2018
*
* 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 io.github.nickid2018.smcl.util;
import io.github.nickid2018.smcl.SnapshotAPI;
import io.github.nickid2018.smcl.number.MatrixObject;
import io.github.nickid2018.smcl.number.NumberObject;
@SnapshotAPI
public class MatrixFunctions {
public static MatrixObject transpose(MatrixObject matrix) {
int len1 = matrix.getRows();
int len2 = matrix.getColumns();
NumberObject[][] result = new NumberObject[len2][len1];
for (int i = 0; i < len1; i++)
for (int j = 0; j < len2; j++)
result[j][i] = matrix.getMatrix()[i][j];
return new MatrixObject(result);
}
private static NumberObject determinant(NumberObject[][] matrix) {
if (matrix.length == 1)
return matrix[0][0];
if (matrix.length == 2)
return matrix[0][0].multiply(matrix[1][1]).subtract(matrix[0][1].multiply(matrix[1][0]));
NumberObject result = matrix[0][0].getProvider().getZero();
for (int i = 0; i < matrix.length; i++) {
NumberObject[][] m = new NumberObject[matrix.length - 1][matrix.length - 1];
for (int j = 1; j < matrix.length; j++)
for (int k = 0; k < matrix.length; k++)
if (k < i)
m[j - 1][k] = matrix[j][k];
else if (k > i)
m[j - 1][k - 1] = matrix[j][k];
result = result.add(matrix[0][i].multiply(determinant(m)));
if (i % 2 == 1)
result = result.negate();
}
return result;
}
public static NumberObject determinant(MatrixObject matrix) {
if (!matrix.isSquare())
throw new ArithmeticException("The matrix is not a square");
return determinant(matrix.getMatrix());
}
public static MatrixObject getMinor(MatrixObject matrix, int x, int y) {
if (!matrix.isSquare())
throw new ArithmeticException("The matrix is not a square");
NumberObject[][] result = new NumberObject[matrix.getRows() - 1][matrix.getColumns() - 1];
for (int i = 0; i < matrix.getRows(); i++)
for (int j = 0; j < matrix.getColumns(); j++)
if (i < x && j < y)
result[i][j] = matrix.getMatrix()[i][j];
else if (i > x && j < y)
result[i - 1][j] = matrix.getMatrix()[i][j];
else if (i < x && j > y)
result[i][j - 1] = matrix.getMatrix()[i][j];
else if (i > x && j > y)
result[i - 1][j - 1] = matrix.getMatrix()[i][j];
return new MatrixObject(result);
}
public static MatrixObject invert(MatrixObject matrix) {
if (!matrix.isSquare())
throw new ArithmeticException("The matrix is not a square");
NumberObject det = determinant(matrix);
if (det.isZero())
throw new ArithmeticException("The matrix is not invertible");
NumberObject[][] result = new NumberObject[matrix.getRows()][matrix.getColumns()];
for (int i = 0; i < matrix.getRows(); i++)
for (int j = 0; j < matrix.getColumns(); j++) {
result[i][j] = determinant(getMinor(matrix, i, j));
if ((i + j) % 2 == 1)
result[i][j] = result[i][j].negate();
}
return transpose(new MatrixObject(result)).multiply(det.reciprocal());
}
}
|
---
uid: mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-a-controller
title: 新增控制器 |Microsoft Docs
author: Rick-Anderson
description: 注意:本教學課程的更新版本可在這裡使用 ASP.NET MVC 5 和 Visual Studio 2013。 更安全、更容易遵循和示範 。
ms.author: riande
ms.date: 08/28/2012
ms.assetid: 0267d31c-892f-49a1-9e7a-3ae8cc12b2ca
msc.legacyurl: /mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-a-controller
msc.type: authoredcontent
ms.openlocfilehash: f528c56435976c7f31fce453c834ef9eaebe6244
ms.sourcegitcommit: e7e91932a6e91a63e2e46417626f39d6b244a3ab
ms.translationtype: MT
ms.contentlocale: zh-TW
ms.lasthandoff: 03/06/2020
ms.locfileid: "78599838"
---
# <a name="adding-a-controller"></a>新增控制器
依[Rick Anderson](https://twitter.com/RickAndMSFT)
> > [!NOTE]
> > 本教學課程的更新版本可在[這裡](../../getting-started/introduction/getting-started.md)取得,其中使用 ASP.NET MVC 5 和 Visual Studio 2013。 它更安全、更容易遵循,並示範更多功能。
MVC 代表*模型視圖控制器*。 MVC 是一種模式,可供開發良好架構、可測試且易於維護的應用程式。 以 MVC 為基礎的應用程式包含:
- **M**模型 ():代表應用程式資料的類別,並使用驗證邏輯來強制執行該資料的商務規則。
- **V**檢視 ():您的應用程式用來動態產生 HTML 回應的範本檔案。
- **C**控制器 ():處理傳入瀏覽器要求、抓取模型資料,然後指定會傳回瀏覽器回應的視圖範本的類別。
我們將在此教學課程系列中涵蓋所有這些概念,並示範如何使用它們來建立應用程式。
讓我們從建立控制器類別開始。 在**方案總管**中,以滑鼠右鍵按一下 [*控制器*] 資料夾,然後選取 [**新增控制器**]。

將新的控制器命名為 "HelloWorldController"。 將預設範本保留為**空白的 MVC 控制器**,然後按一下 [**新增**]。

請注意,在**方案總管**中,已建立名為*HelloWorldController.cs*的新檔案。 檔案已在 IDE 中開啟。

以下列程式碼取代檔案的內容。
[!code-csharp[Main](adding-a-controller/samples/sample1.cs)]
控制器方法會傳回 HTML 字串做為範例。 控制器的名稱為 `HelloWorldController`,而上述第一個方法的名稱為 `Index`。 讓我們從瀏覽器叫用它。 執行應用程式(按 F5 或 Ctrl + F5)。 在瀏覽器中,將 "HelloWorld" 附加至網址列中的路徑。 (例如,在下圖中,它是 `http://localhost:1234/HelloWorld.`)瀏覽器中的頁面看起來會如下列螢幕擷取畫面所示。 在上述方法中,程式碼會直接傳回字串。 您已告訴系統只傳回一些 HTML,而且的確有!

ASP.NET MVC 會根據傳入的 URL,叫用不同的控制器類別(以及其中的不同動作方法)。 ASP.NET MVC 使用的預設 URL 路由邏輯會使用類似如下的格式來判斷要叫用的程式碼:
`/[Controller]/[ActionName]/[Parameters]`
URL 的第一個部分會決定要執行的控制器類別。 因此, */HelloWorld*會對應至 `HelloWorldController` 類別。 URL 的第二個部分會決定要執行的類別上的動作方法。 因此, */HelloWorld/Index*會導致 `HelloWorldController` 類別的 `Index` 方法執行。 請注意,我們只需要流覽至 */HelloWorld* ,預設會使用 `Index` 方法。 這是因為名為 `Index` 的方法是在控制器上呼叫的預設方法(如果未明確指定的話)。
瀏覽至 `http://localhost:xxxx/HelloWorld/Welcome`。 `Welcome` 方法會執行並傳回字串 "這是歡迎動作方法 ..."。 預設 MVC 對應為 `/[Controller]/[ActionName]/[Parameters]`。 在此 URL 中,控制器是 `HelloWorld`,而 `Welcome` 是動作方法。 您尚未使用 URL 的 `[Parameters]` 部分。

讓我們稍微修改範例,讓您可以將 URL 中的某些參數資訊傳遞至控制器(例如, */HelloWorld/Welcome? name = Scott&numtimes is = 4*)。 變更您的 `Welcome` 方法,使其包含兩個參數,如下所示。 請注意,程式碼會C#使用選擇性參數功能,表示如果未針對該參數傳遞任何值,則 `numTimes` 參數應預設為1。
[!code-csharp[Main](adding-a-controller/samples/sample2.cs)]
執行您的應用程式,並流覽至範例 URL (`http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4)`。 您可以在 URL 中針對 `name` 和 `numtimes` 嘗試不同的值。 [ASP.NET MVC 模型](http://odetocode.com/Blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx)系結系統會自動將來自網址列中的查詢字串的已具名引數對應至方法中的參數。

在這兩個範例中,控制器已執行 MVC 的 "VC" 部分,也就是視圖和控制器工作。 控制器會直接傳回 HTML。 一般來說,您不希望控制器直接傳回 HTML,因為程式碼會變得很麻煩。 相反地,我們通常會使用個別的視圖範本檔案來協助產生 HTML 回應。 我們來看一下如何執行這個動作。
> [!div class="step-by-step"]
> [上一頁](intro-to-aspnet-mvc-4.md)
> [下一頁](adding-a-view.md)
|
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import './scss/app.scss';
import Downloading from './components/Downloading';
import Home from './pages/Home';
import Header from './components/Header';
const Cart = React.lazy(() => import(/*webpackChunkName: "Cart" */ './pages/Cart'));
const FullPizza = React.lazy(() => import(/*webpackChunkName: "FullPizza" */ './pages/FullPizza'));
const NotFoundPage = React.lazy(() => import(/*webpackChunkName: "NotFoundPage" */ './pages/NotFoundPage'));
function App() {
return (
<div className='wrapper'>
<Header />
<div className='content'>
<Routes>
<Route path='/react-pizza-v2' element={<Home />} />
<Route
path='/react-pizza-v2/cart'
element={
<React.Suspense fallback={<Downloading />}>
<Cart />
</React.Suspense>
}
/>
<Route
path='/react-pizza-v2/pizza/:id'
element={
<React.Suspense fallback={<Downloading />}>
<FullPizza />
</React.Suspense>
}
/>
<Route
path='/react-pizza-v2/*'
element={
<React.Suspense fallback={<Downloading />}>
<NotFoundPage />
</React.Suspense>
}
/>
</Routes>
</div>
</div>
);
}
export default App;
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->text('address')->nullable();
$table->unsignedBigInteger('state_id')->nullable();
$table->string('city')->nullable();
$table->string('zip_code')->nullable();
$table->string('phone_number')->nullable();
$table->string('picture')->nullable();
$table->boolean('is_admin')->default(false);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
|
import { Route, Routes } from "react-router-dom";
import Layout from "./components/Layout";
import Home from "./pages/Home";
import About from "./pages/About";
import Courses from "./pages/Courses";
import OurTeam from "./pages/OurTeam";
import Contact from "./pages/Contact";
import Register from "./pages/Register";
import Login from "./pages/Login";
import Error from "./pages/Error";
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="courses" element={<Courses />} />
<Route path="our-team" element={<OurTeam />} />
<Route path="contact" element={<Contact />} />
</Route>
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="*" element={<Error />} />
</Routes>
</div>
);
}
export default App;
|
import { Optional } from "./../types/optional";
import { Log } from "./log";
export abstract class FullscreenUtils {
public static async toggle(): Promise<void> {
try {
const element = document.getElementsByTagName("canvas")[0];
const fullscreenEnabled = window.getPrefixedProperty<boolean>(document, "fullscreenEnabled", true);
const requestFullscreen = window.getPrefixedProperty<VoidFunction>(element, "requestFullscreen", true);
// Really firefox? You really had to be different?
const exitFullscreen = window.getPrefixedProperty<VoidFunction>(document, ["exitFullscreen", "msExitFullscreen", "mozCancelFullScreen", "webkitExitFullscreen"], true);
if (!fullscreenEnabled) {
Log.error("FullscreenUtils", "Fullscreen is not enabled");
return;
}
if (this.isFullscreen()) {
await exitFullscreen.call(document);
} else {
await requestFullscreen.call(element);
}
// Just to add a flavor on Android devices, since safari ios doesn't support anything... no fullscreen, no vibration, no nothing
const vibrate = window.getPrefixedProperty<(amount: number) => void | undefined>(navigator, "vibrate", false);
if (vibrate) vibrate.call(navigator, 100);
} catch (error) {
Log.error("FullscreenUtils", `Error while requesting fullscreen: ${error}`);
}
}
public static isFullscreen(): boolean {
const fullscreenElement = window.getPrefixedProperty<Optional<HTMLElement>>(document, "fullscreenElement", true);
return fullscreenElement !== null;
}
}
|
import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { Dish } from "../../../interfaces/dish";
import { DishesInfoService } from "../../../services/dishes-info.service";
@Component({
selector: 'app-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css']
})
export class FiltersComponent implements OnInit, OnChanges {
@Input() dishes: Dish[] = [];
@Output() filteredDishesEvent = new EventEmitter<Dish[]>();
uniqueCuisines!: Set<string>;
uniqueCategories!: Set<string>;
filteredCuisines: Set<string> = new Set();
filteredCategories: Set<string> = new Set();
minimumRating: number = 0;
constructor(public dishesInfo: DishesInfoService) {
}
ngOnInit(): void {
this.getInfoForFilters();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes["dishes"]) this.getInfoForFilters();
}
getInfoForFilters(): void {
this.getUniqueCuisines();
this.getUniqueCategories();
}
getUniqueCuisines(): void {
this.uniqueCuisines = new Set(this.dishes.map(dish => dish.cuisine));
}
getUniqueCategories(): void {
this.uniqueCategories = new Set<string>();
for (let dish of this.dishes) {
for (let category of dish.categories) {
this.uniqueCategories.add(category);
}
}
}
getFilteredCuisines(cuisine: string): void {
if (this.filteredCuisines.has(cuisine)) this.filteredCuisines.delete(cuisine);
else this.filteredCuisines.add(cuisine);
this.filterDishes();
}
getFilteredCategories(category: string): void {
if (this.filteredCategories.has(category)) this.filteredCategories.delete(category);
else this.filteredCategories.add(category);
this.filterDishes();
}
filterDishes(): void {
let filteredDishes: Dish[] = JSON.parse(JSON.stringify(this.dishes));
filteredDishes = this.filterCuisines(filteredDishes);
filteredDishes = this.filterCategories(filteredDishes);
filteredDishes = this.filterPrice(filteredDishes);
filteredDishes = this.filterRatings(filteredDishes);
this.filteredDishesEvent.emit(filteredDishes);
}
filterCuisines(dishes: Dish[]): Dish[] {
if (!dishes || dishes.length === 0) {
return [];
}
if (!this.filteredCuisines || this.filteredCuisines.size === 0) {
return dishes;
}
return dishes.filter(dish => this.filteredCuisines.has(dish.cuisine));
}
filterCategories(dishes: Dish[]): Dish[] {
if (!dishes || dishes.length === 0) {
return [];
}
if (!this.filteredCategories || this.filteredCategories.size === 0) {
return dishes;
}
return dishes.filter(dish => {
let found: boolean = false;
for (let category of this.filteredCategories) {
if (dish.categories.includes(category)) {
found = true;
break;
}
}
return found;
});
}
filterPrice(dishes: Dish[]): Dish[] {
if (!dishes || dishes.length === 0) return [];
if (this.dishesInfo.filterMinPrice === -1 && this.dishesInfo.filterMaxPrice === Number.MAX_SAFE_INTEGER) {
return dishes;
}
return dishes.filter(dish => this.dishesInfo.filterMinPrice <=
Math.round(dish.price * this.dishesInfo.exchangeRate) &&
Math.round(dish.price * this.dishesInfo.exchangeRate) <= this.dishesInfo.filterMaxPrice);
}
filterRatings(dishes: Dish[]): Dish[] {
if (!dishes || dishes.length === 0) return [];
if (this.minimumRating === 0) return dishes;
return dishes.filter(dish => this.dishesInfo.dishesRating[dish.id as string] >= this.minimumRating);
}
}
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AxiosError, AxiosResponse } from 'axios';
import axios from 'utils/axios';
import { Thunk } from 'redux/store';
import { Search } from 'interfaces';
const initialState: Search = {
searchUser: []
};
const searchSlice = createSlice({
name: 'search',
initialState,
reducers: {
setSearchUser: (state, action: PayloadAction<[]>) => {
state.searchUser = action.payload;
}
}
});
export const { setSearchUser } = searchSlice.actions;
export default searchSlice.reducer;
export const search =
(data: Search): Thunk =>
async (dispatch): Promise<AxiosResponse | AxiosError> => {
try {
const response: AxiosResponse = await axios.post('/users', data);
dispatch(setSearchUser(response.data.data));
return response;
} catch (error) {
return error as AxiosError;
}
};
|
class Solution {
// Function to determine if a list of integers contains any duplicates
bool containsDuplicate(List<int> nums) {
// Create an empty set to efficiently track unique elements
Set<int> seenNumbers = {};
// Iterate through each number in the list
for (int n in nums) {
// If the number is already in the set, it's a duplicate
if (seenNumbers.contains(n)) {
return true; // Return immediately as a duplicate is found
}
// Otherwise, add the number to the set to mark it as seen
seenNumbers.add(n);
}
// If the loop completes without finding duplicates, return false
return false;
}
}
|
import isEmpty from "lodash/isEmpty";
import { ref } from "vue";
import { useRoute } from "vue-router";
import {
CATEGORIES,
FIRST_PAGE,
MOVIE_DISCOVER_URL,
TRENDING_MOVIE_URL,
TRENDING_TV_URL,
TV_DISCOVER_URL,
SEARCH_TV_BY_TITLE,
SEARCH_MOVIE_BY_TITLE,
} from "@/constants";
/**
* Custom composition function for managing URL parameters based on the current route.
*
* @returns {Object} - An object containing reactive references and functions for URL parameters.
*/
export const useUrlSearchParams = () => {
const route = useRoute();
const searchParams = ref({});
const url = ref(null);
/**
* Determines the appropriate API URL based on the category and search query.
*
* @param {string} category - The category of the movie ("movies" or "tv").
*/
const getUrl = (category) => {
switch (category) {
case CATEGORIES.movies:
url.value = isEmpty(route.query)
? TRENDING_MOVIE_URL
: route.query.search
? SEARCH_MOVIE_BY_TITLE
: MOVIE_DISCOVER_URL;
break;
case CATEGORIES.tv:
url.value = isEmpty(route.query)
? TRENDING_TV_URL
: route.query.search
? SEARCH_TV_BY_TITLE
: TV_DISCOVER_URL;
break;
default:
url.value = TRENDING_MOVIE_URL;
}
};
/**
* Constructs search parameters based on the current route's query parameters.
*
* @param {string} category - The category of the movie ("movies" or "tv").
*/
const getSearchParams = (category) => {
const { sort, genres, minYear, maxYear, page, search } = route.query;
searchParams.value = { page: page ? page : FIRST_PAGE };
if (sort) {
searchParams.value.sort_by = sort;
}
if (search) {
searchParams.value.query = search;
}
if (genres) {
searchParams.value.with_genres = Array.isArray(genres)
? genres.join("|")
: genres;
}
if (minYear) {
const key =
category === CATEGORIES.movies
? "primary_release_date.gte"
: "first_air_date.gte";
searchParams.value[key] = `${+minYear}-01-01`;
}
if (maxYear) {
const key =
category === CATEGORIES.movies
? "primary_release_date.lte"
: "first_air_date.lte";
searchParams.value[key] = `${+maxYear}-12-31`;
}
};
return { url, searchParams, getUrl, getSearchParams };
};
|
<?php
namespace Magpie\Routes;
use Exception;
use Magpie\General\Names\CommonHttpStatusCode;
use Magpie\General\Traits\StaticCreatable;
use Magpie\HttpServer\Concepts\WithHeaderSpecifiable;
use Magpie\HttpServer\Request;
use Magpie\HttpServer\Response;
use Magpie\Routes\Concepts\RouteHandleable;
use Magpie\Routes\Constants\RouteMiddlewarePriority;
use Stringable;
/**
* Route middleware
*/
abstract class RouteMiddleware
{
use StaticCreatable;
/**
* Handle the route at current level
* @param Request $request
* @param RouteHandleable $next
* @return mixed
* @throws Exception
*/
public abstract function handle(Request $request, RouteHandleable $next) : mixed;
/**
* The priority weight for sorting, the lower the number, the higher the priority
* @return int
*/
public static function getPriorityWeight() : int
{
return RouteMiddlewarePriority::DEFAULT;
}
/**
* Try to cast the response to make it header specifiable
* @param mixed $response
* @return WithHeaderSpecifiable|mixed
*/
protected static function tryCastResponseAsHeaderSpecifiable(mixed $response) : mixed
{
if ($response instanceof WithHeaderSpecifiable) return $response;
if ($response === null) return new Response('', CommonHttpStatusCode::NO_CONTENT);
// Support for string as HTML content
if (is_string($response)) return new Response($response);
if ($response instanceof Stringable) return new Response($response->__toString());
// Otherwise, 'as-is'
return $response;
}
}
|
// components/ListComponent.tsx
import React from 'react';
import styles from './ListComponent.module.css';
interface ListItem {
id: number;
value: string;
}
interface ListComponentProps {
items: ListItem[];
onRemoveItem: (itemId: number) => void; // Add this line
}
const ListComponent: React.FC<ListComponentProps> = ({ items, onRemoveItem }) => {
return (
<ul className={styles.listContainer}>
{items.map((item) => (
<li key={item.id} className={styles.listItem}>
{item.value}
<button id="text-btn" onClick={() => onRemoveItem(item.id)} style={{ marginLeft: '10px' }}>Remove</button>
</li>
))}
</ul>
);
};
export default ListComponent;
|
using System;
namespace Delegates_Observer
{
public delegate void MyDelegate(object o);
class Source
{
public event MyDelegate Run;
public void Start()
{
Console.WriteLine("RUN");
if (Run != null) Run(this);
}
}
class Observer1 // Наблюдатель 1
{
public void Do(object o)
{
Console.WriteLine("Первый. Принял, что объект {0} побежал", o);
}
}
class Observer2 // Наблюдатель 2
{
public void Do(object o)
{
Console.WriteLine("Второй. Принял, что объект {0} побежал", o);
}
}
class Program
{
static void Main(string[] args)
{
Source s = new Source();
Observer1 o1 = new Observer1();
Observer2 o2 = new Observer2();
MyDelegate d1 = new MyDelegate(o1.Do);
s.Run += d1;
s.Run += o2.Do;
s.Start();
s.Run -= d1;
s.Start();
}
}
}
|
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import toast from 'react-hot-toast';
import {
addFavouriteRecipe,
deleteFavouriteRecipe,
} from '../services/recipesApi';
const useFavouriteRecipes = () => {
const queryClient = useQueryClient();
const {
mutateAsync: deleteFavouriteRecipeMutate,
isPending: isPendingDelete,
} = useMutation({
mutationFn: deleteFavouriteRecipe,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['favourite-recipes'],
});
toast.success('Recipe removed from favourites!');
},
onError: (error: AxiosError<ResponseError>) =>
toast.error(error?.response?.data.message || error.message),
});
const { mutateAsync: addFavouriteRecipeMutate, isPending: isPendingAdd } =
useMutation({
mutationFn: addFavouriteRecipe,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['favourite-recipes'],
});
toast.success('Recipe added to favourites!');
},
onError: (error: AxiosError<ResponseError>) =>
toast.error(error?.response?.data.message || error.message),
});
const isPending = isPendingDelete || isPendingAdd;
return {
deleteFavouriteRecipeMutate,
addFavouriteRecipeMutate,
isPending,
};
};
export default useFavouriteRecipes;
|
#ifndef FCG_TRAB_FINAL_MODEL_H
#define FCG_TRAB_FINAL_MODEL_H
#include "glm/vec4.hpp"
#include "LoadedObj.h"
#include "SceneObject.h"
#include "Camera.h"
#include <string>
class Model {
private:
// Características do modelo
glm::vec3 scale;
std::string name;
LoadedObj obj;
int objectId;
glm::vec3 position;
glm::vec3 direction;
float rotation;
// Posição original do modelo - para cálculos de direção e movimentação
glm::vec3 originalPosition;
// Funções para adição na cena virutal
void ComputeNormals();
void BuildTrianglesAndAddToVirtualScene(std::map<std::string, SceneObject> &virtualScene);
public:
Model(int id, glm::vec3 position, glm::vec3 scale, glm::vec3 direction, float rotation, const char* name, const char* path, std::map<std::string, SceneObject> &virtualScene);
// Move o jogador
void updatePlayer(float delta_t, Camera &camera, const Model& box);
// Move o bumerange
bool updateBoomerang(bool &boomerangIsThrown,
bool &primaryAttackStarts,
bool &secondaryAttackStarts,
bool &M1,
bool &M2,
bool &isPaused,
float &rotationBoomerang,
float &t,
float &delta_t,
glm::vec3 &robotPosition,
float robotRotation,
glm::vec3 &sceneryBboxMin,
glm::vec3 &sceneryBboxMax,
glm::mat4 &model);
// "Raio" da bounding box
float x_difference;
float z_difference;
// Axis-Aligned Bounding Box do objeto
glm::vec3 bbox_min;
glm::vec3 bbox_max;
// Atualiza bounding box
void updateBbox();
// Getters para informações de modelo
glm::vec3 getPosition();
glm::vec3 getDirection();
glm::vec3 getScale();
[[nodiscard]] float getRotation() const;
std::string getName();
[[nodiscard]] int getId() const;
glm::vec3 getOriginalPosition();
// Setters para atualização de inforamções de modelo
void setDirection(glm::vec3 direction);
void setPosition(glm::vec3 position);
void updateOriginalPosition();
};
#endif //FCG_TRAB_FINAL_MODEL_H
|
//
// AppointmentItemModel.swift
// QuickMeet
//
// Created by Bozidar Labas on 06.02.2024..
//
import Foundation
struct AppointmentItemModel {
var id: UUID
let details: String
let date: Date
let time: Date
let location: String
var saveToCalendar: Bool = false
var addNotification: Bool = false
private var dateString: String = ""
private var timeString: String = ""
var formatedDateTime: String { String(format: "datetime_at".localized, dateString, timeString) }
var dateAndTime: Date? {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.year, .month, .day], from: date)
let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: time)
return calendar.date(bySettingHour: timeComponents.hour ?? 0, minute: timeComponents.minute ?? 0, second: timeComponents.second ?? 0, of: calendar.date(from: dateComponents) ?? Date())
}
init(id: UUID? = nil, details: String, date: Date, time: Date, location: String) {
if let id = id {
self.id = id
} else {
self.id = UUID()
}
self.details = details
self.date = date
self.time = time
self.location = location
self.dateString = getDateTimeString(format: "dd.MM.yyyy", date: date)
self.timeString = getDateTimeString(format: "HH:mm", date: time)
}
private func getDateTimeString(format: String, date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date)
}
}
|
(ns backend.user.read.user-read-test
(:require [ring.mock.request :as mock]
[datomic.api :as d]
[backend.support.db :refer :all]
[backend.router :refer :all]
[midje.sweet :refer :all]
[backend.test-support :refer :all]
))
(defn- create-request
[id]
(mock/request :get (str "/users/" id)))
(facts
"User read"
(let [db-uri (test-db-uri)
config (test-config db-uri)
handler (create-handler config)
_ (start-database! db-uri)
setup (read-edn "backend/user/read/setup")
db (:db-after @(d/transact (d/connect db-uri) setup))]
(facts
"Full"
(let [request (create-request "username-full")
response (handler request)
response-body (read-json "backend/user/read/full-response")
]
(is-response-ok-version response response-body 123)
))
(facts
"Minimal"
(let [request (create-request "username-minimal")
response (handler request)
response-body (read-json "backend/user/read/minimal-response")
]
(is-response-ok-version response response-body 123)
))
(facts
"Not found"
(not-found-test handler (create-request 10)))
(facts
"Invalid id"
(not-found-test handler (create-request "invalid")))
))
|
import { FALLBACK_SEO } from "./constants";
export const getMetaFromVideo = (
videoName = "",
subcategory = "",
subfolder = null
) => {
if (!subfolder) {
return {
title: `${videoName} | Cannabis Product and Strain Reviews, Tips and Recommendations | Moodi Day`,
description: null,
};
}
switch (subfolder) {
case "product-review":
return {
title: `${videoName} Budtender Product Review | Budtender Reviews of Products Near You | Moodi Day`,
description: `${videoName} budtender product review with a reported reviewer rating of ${subcategory}. Watch more budtender product reviews for ${videoName} on Moodi Day.`,
};
case "strain-review":
return {
title: `${videoName} Budtender Strain Review | Budtender Reviews of Strains Near You | Moodi Day`,
description: `${videoName} budtender strain review. ${videoName} strain type of ${subcategory}. Watch more budtender strain reviews for ${videoName} on Moodi Day.`,
};
case "device-review":
return {
title: `${videoName} Budtender Device Review | Budtender Reviews of Cannabis Devices and Tools | Moodi Day`,
description: `${videoName} budtender device review with a reported reviewer rating of ${subcategory}. Watch more budtender device reviews for ${videoName} on Moodi Day.`,
};
case "accessory-review":
return {
title: `${videoName} Budtender Accessory Review | Budtender Reviews of Cannabis Devices and Tools | Moodi Day`,
description: `${videoName} accessory device review with a reported reviewer rating of ${subcategory}. Watch more budtender device reviews for ${videoName} on Moodi Day.`,
};
case "tips-tricks":
return {
title: `${videoName} Budtender Tutorial | Budtender Cannabis Tips and Recommendations | Moodi Day`,
description: `${videoName} budtender tutorial to help you find the right high. Watch more budtender cannabis tips, tricks and recommendations on Moodi Day.`,
};
case "brand-collabs":
return {
title: `${videoName} Brand Collab with Moodi Day`,
description: `${videoName} brand x budtender collab. Watch more brand and budtender collaborations on Moodi Day.`,
};
default:
return {
title: `${videoName} | Cannabis Product and Strain Reviews, Tips and Recommendations | Moodi Day`,
description: null,
};
}
};
export const getMetaFromMasterTag = (masterTag = "") => {
switch (masterTag) {
case "products":
return {
title: `Product Reviews | Reviews of Cannabis Products Near You`,
description: `Watch reviews of the top cannabis products sold at dispensaries near you. Browse reviews for product categories including flower, pre-rolls, edibles, beverages, concentrates and more.`,
};
case "accesories-devices":
return {
title: `Device and Accessory Reviews | Reviews of Popular Smoking Devices and Tools`,
description: `Watch reviews of popular devices and tools. Browse our extensive catalog of reviews for dry herb vaporizers, concentrate vaporizers, glass pieces and other essential cannabis tools.`,
};
case "strains":
return {
title: `Strain Reviews | Reviews of Cannabis Strains Near You`,
description: `Watch reviews of popular cannabis strains sold at dispensaries near you. Browse by indica, sativa or hybrid, or by reported effects and use cases.`,
};
case "tips-tricks":
return {
title: `Cannabis Tips & Tricks | Tutorials and Explainers to Help you Find the Right High`,
description: `Watch tutorials and explainers to help you avoid disappointing highs. Whether you are a newbie or an experienced cannabis consumer, we have tips and tricks to help you find the right high.`,
};
default:
return {
title: FALLBACK_SEO.title,
description: FALLBACK_SEO.description,
};
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.