text
stringlengths 184
4.48M
|
---|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Models\Book;
use App\Models\Favorite;
use Illuminate\Support\Facades\Storage;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Validation\Rule;
class BookController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
// $book = app(Controller::class)->getBook();
$books = Book::paginate(15);
return view('admin.books.index', ['books' => $books]);
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('admin.books.create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
// note
// 1. Book code must generated automatically based on something. Something still unknown
// 2. Add a synopsis, but is not required
$validate = $request->validate([
'book_code' => 'required',
'title' => 'required',
'category' => 'required',
'author' => 'required',
'publication_year' => 'required',
'type' => 'required',
'book_status' => 'required'
], [
'required' => ':attribute dibutuhkan',
]);
$book = new Book();
if ($request->hasFile('cover')) {
$extension = $request->cover->extension();
$filename = str_replace(' ', '_', $request->title) . '_' . uniqid() .'.' . $extension;
$path = $request->cover->storeAs('book_covers', $filename);
$book->cover = $filename;
}else{
return redirect('/admin/books/create')->with('error', ['message' => 'Gambar tidak boleh kosong!']);
}
$book->book_code = $request->book_code;
$book->title = $request->title;
$book->category = $request->category;
$book->author = $request->author;
$book->publication_year = $request->publication_year;
$book->type = $request->type;
$book->book_status = $request->book_status;
$book->editor = $request->editor;
$book->translator = $request->translator;
$book->language = $request->language;
$book->publisher = $request->publisher;
$book->page = $request->page;
$book->volume = $request->volume;
$book->synopsis = $request->synopsis;
$book->save();
return redirect('/admin/books')->with('success', ['message' => 'Data buku berhasil ditambahkan!']);
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
public function search(){
$user_data = Auth::user();
$books = Book::latest();
if(request('search')){
$books->where('title', 'like', '%' . request('search') . '%')
->orWhere('author', 'like', '%' . request('search') . '%');
}
return view('users/index', ['user_data' => $user_data,
'searchfilter' => 'true',
'search' => request('search'),
'available' => null,
'category' => null,
'books' => $books->paginate(16)]);
}
public function filter(){
$user_data = Auth::user();
$books = Book::latest();
$category = request('category');
$available = request('available');
if($category && $available){
$books->where('category', $category)
->Where('book_status', '0');
}
else if(!$category && $available){
$books->Where('book_status', '0');
}
else if($category && !$available){
$books->where('category', $category);
}
return view('users/index', ['user_data' => $user_data,
'searchfilter' => 'true',
'search' => null,
'available' => $available,
'category' => $category,
'books' => $books->paginate(16)]);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
$url = url()->previous();
// Menggunakan parse_url untuk mendapatkan query string
$query = parse_url($url, PHP_URL_QUERY);
// Menggunakan parse_str untuk mengurai query string menjadi array
parse_str($query, $params);
// Mengambil angka "page" dari array $params
$url_page = isset($params['page']) ? $params['page'] : "1";
$book = Book::find($id);
return view('admin.books.edit', ['book' => $book, 'url_page' => $url_page]);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
$book = Book::find($id);
$validate = $request->validate([
// 'book_code' => ['required', Rule::unique('book')->ignore($request->book_code)],
'book_code' => 'required',
'title' => 'required',
'category' => 'required',
'author' => 'required',
'publication_year' => 'required',
'type' => 'required',
'book_status' => 'required'
], [
'required' => ':attribute dibutuhkan',
]);
$book->book_code = $request->book_code;
$book->title = $request->title;
$book->category = $request->category;
$book->author = $request->author;
$book->publication_year = $request->publication_year;
$book->type = $request->type;
$book->book_status = $request->book_status;
$book->editor = $request->editor;
$book->translator = $request->translator;
$book->language = $request->language;
$book->publisher = $request->publisher;
$book->page = $request->page;
$book->volume = $request->volume;
$book->synopsis = $request->synopsis;
if ($request->hasFile('cover')) {
$extension = $request->cover->extension();
$filename = $request->book_code .'.' . $extension;
// delete old cover
if($book->cover !== 'cover_default.jpg') {
Storage::delete('book_covers/'.$book->cover);
}
$path = Storage::putFileAs(
'book_covers/', $request->file('cover'), $filename
);
$book->cover = $filename;
}
$book->update();
return redirect('/admin/books?page='.$request->url_page)->with('success', ['message' => 'Data buku berhasil diedit!']);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
Book::find($id)->delete();
return redirect('/admin/books')->with('success', ['message' => 'Data buku berhasil dihapus!']);
$book = Book::find($id);
if($book->cover !== 'cover_default.jpg') {
Storage::delete('book_covers/'.$book->cover);
}
$book->delete();
return redirect('/admin/books')->with('success', ['message' => 'Data buku berhasil dihapus!']);
}
public function addBook(Request $request){
}
public function bookSave(Request $request){
$user_id = $request->user_id;
$book_id = $request->book_id;
try{
if(Favorite::where('user_id', $user_id)->where('book_id', $book_id)->exists()){
return response()->json(
[
'error'=>false,
'message'=>'Buku ini telah anda tambahkan ke favorit :)'
]
);
}else{
$query = Favorite::create([
'user_id' => $user_id,
'book_id' => $book_id,
]);
return response()->json(
[
'error'=>false,
'message'=>'Buku telah ditambahkan ke favorit :D'
]
);
}
}catch(\Exception $e){
return response()->json(
[
'error'=>true,
'message'=>'Gagal',
'err_message'=>$e->getMessage(),
]
);
}
}
}
|
import threading
import time
import random
# 创建一个锁对象
lock = threading.Lock()
def producer(id):
while True:
lock.acquire() # 请求锁
try:
print(f"----------------------\nProducer {id} is working!")
time.sleep(0.5) # 模拟工作
print(f"Producer {id} is finished!\n----------------------")
finally:
lock.release() # 释放锁
time.sleep(random.uniform(0.2, 0.4))
def customer(id):
while True:
lock.acquire() # 请求锁
try:
print(f"----------------------\nCustomer {id} is working!")
time.sleep(0.5) # 模拟工作
print(f"Customer {id} is finished!\n----------------------")
finally:
lock.release() # 释放锁
time.sleep(random.uniform(0.2, 0.4))
# 创建并启动线程
threads = []
for i in range(2):
threads.append(threading.Thread(target=producer, args=(i+1,)))
threads.append(threading.Thread(target=customer, args=(i+1,)))
for thread in threads:
thread.start()
# 等待所有线程结束
for thread in threads:
thread.join()
|
<!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" />
<meta
name="description"
content="Jaime is a front-end engineer based in Fort Worth, TX."
/>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"
></script>
<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=Montserrat:wght@100;200;300;400&family=Playfair+Display:wght@700&family=Poppins:wght@500;700&family=Questrial&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="styles/portfolio.css" />
<script
src="https://kit.fontawesome.com/e25bab247d.js"
crossorigin="anonymous"
></script>
<title>Front-end developer - Jaime Parker</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-white">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img
src="images/logo.png"
alt="Jaime Parker Logo"
class="logo img-fluid"
/>
</a>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a
class="nav-link active"
aria-current="page"
href="/"
title="Homepage"
>Home</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="/about.html" title="About Jaime"
>About</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="/work.html" title="Jaime's Work"
>Work</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="/contact.html" title="Contact Jaime"
>Contact</a
>
</li>
</ul>
</div>
</div>
</nav>
<div class="hero">
<p>Hello, I am</p>
<h1>Jaime Parker</h1>
<h2 class="mb-5 text-muted">
Front-end developer based in Fort Worth, TX
</h2>
<div>
<a href="/contact.html" class="btn btn-branding" title="Contact Me"
>Contact me</a
>
</div>
</div>
<h4 class="text-center mb-5">Featured portfolio projects</h4>
<div class="container">
<div class="row mb-5">
<div class="col d-none d-lg-block">
<img
src="images/plant.png"
alt="whole food plant based diet project preview"
class="img-fluid"
/>
</div>
<!--col close-->
<div class="col">
<div class="project-description">
<h2 class="mb-5">Plant Based Diet Project</h2>
<p class="mb-5 text-muted">
My whole food plant based diet project was created with HTML and
CSS. I had a lot of fun creating this site. This project includes
resources to help others discover the benefits of eating a plant
based diet.
</p>
<a href="/work.html" class="btn btn-branding-outline mb-5"
>Learn more</a
>
</div>
<!--project description close-->
</div>
<!--col close-->
</div>
<!--row close-->
<!--start 2nd row-->
<div class="row mb-5">
<div class="col">
<div class="project-description">
<h2 class="mb-5">Weather App</h2>
<p class="mb-5 text-muted">
This weather app allows you to search for the current weather and
forecast of any city. It was built with HTML, CSS, and JavaScript.
While working on this project, I learned how to incorporate APIs
and about the power of JavaScript.
</p>
<a href="/work.html" class="btn btn-branding-outline mb-5"
>Learn more</a
>
</div>
<!--project description close-->
</div>
<!--col close-->
<div class="col d-none d-lg-block">
<img
src="images/weatherapp.png"
alt="weather app preview"
class="img-fluid"
/>
</div>
<!--close col d-none-->
</div>
<!--row close-->
<!--start 3rd row-->
<div class="row">
<div class="col d-none d-lg-block">
<img
src="images/dictionary.png"
alt="dictionary app preview"
class="img-fluid"
/>
</div>
<div class="col">
<div class="project-description">
<h2 class="mb-5">Dictionary App</h2>
<p class="mb-5 text-muted">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam
aperiam provident tempora? Cumque adipisci, non dolorem quia, odit
qui alias veniam excepturi rem dolor fugit dignissimos, sed
voluptatum blanditiis harum.
</p>
<a href="/work.html" class="btn btn-branding-outline mb-5"
>Learn more</a
>
</div>
<!--close project description-->
</div>
<!--col close-->
</div>
<!--row close-->
<footer>
<div
class="contact-box d-flex justify-content-between mb-5 d-none d-md-flex"
>
<div>
<h3>Work Inquiry</h3>
<p class="text-muted">Let's work together.</p>
</div>
<div>
<a
href="/contact.html"
class="btn btn-branding mt-3"
title="Contact Jaime"
>Contact me</a
>
</div>
</div>
<div class="d-flex justify-content-center mb-5">
<a
href="mailto:[email protected]"
class="email-link"
title="Email me"
>
[email protected]
</a>
</div>
<!--close class dflex-->
<div class="social-links d-flex justify-content-center">
<a
href="https://www.github.com/Karmahen"
target="_blank"
title="Github Profile"
>
<i class="fab fa-github"></i>
</a>
<a
href="https://www.linkedin.com/in/jaime-parker-529836a4/"
target="_blank"
title="LinkedIn Profile"
>
<i class="fab fa-linkedin"></i>
</a>
<a
href="https://www.twitter.com/jparker6"
target="_blank"
title="Twitter Profile"
>
<i class="fab fa-twitter"></i>
</a>
</div>
<!--close social links-->
<p class="text-center mt-5">
This
<a
href="https://github.com/Karmahen/Portfolio-Project-2022"
target="_blank"
>open-sourced
</a>
project was coded by Jaime Parker.
</p>
</footer>
</div>
<!--container close-->
</body>
</html>
|
import { Request, Response } from 'express'
import { logger } from '../../../log'
import { Address, ChainId } from '../../../types'
import { providerByChainId } from '../../../utils/providers'
import {
MULTICALL_INTERFACE,
ZKLINK_ABI,
ZKLINK_INTERFACE,
} from '../../../utils'
import { extendAddress } from '../../../utils/withdrawal'
import {
getSupportChains,
getSupportTokens,
recoveryDecimals,
} from '../../../utils/zklink'
import {
callMulticall,
getMulticallContractByChainId,
} from '../../../utils/multicall'
export interface RequestsBody {
chainId: ChainId
account: Address
}
async function batchGetPendingBalance(chainId: ChainId, account: Address) {
const supportChains = await getSupportChains()
const supportTokens = await getSupportTokens()
const multicall = getMulticallContractByChainId(chainId)
const provider = providerByChainId(chainId)
const chain = supportChains.find(
(v) => Number(v.layerOneChainId) === Number(chainId)
)
const layer2ChainId = chain?.chainId!
const tokens = Object.values(supportTokens)
.map((v) => v.id)
.filter((v) => Number(v) > 17)
.filter((v) => supportTokens[v].chains[layer2ChainId] !== undefined)
const callAddresses = tokens.map((v) => chain?.mainContract!)
const calls: string[] = tokens.map((id) => {
return ZKLINK_INTERFACE.encodeFunctionData('getPendingBalance', [
extendAddress(account),
id,
])
})
const rs = await callMulticall(
provider,
multicall,
ZKLINK_ABI,
'getPendingBalance',
callAddresses,
calls
)
if (!rs.length) {
return null
}
const result = tokens.map((tokenId, i) => {
const decimals = supportTokens[tokenId].chains[layer2ChainId].decimals
return {
tokenId,
decimals,
symbol: supportTokens[tokenId].symbol,
balance: rs[i],
recoveryBalance: recoveryDecimals(rs[i], BigInt(decimals)),
}
})
return result
.filter((v) => v.balance > 0n)
.map((v) => ({
...v,
balance: v.balance.toString(),
recoveryBalance: v.recoveryBalance.toString(),
}))
}
export async function getPendingBalance(req: Request, res: Response) {
try {
const account = req.params.account
const chainId = req.params.chainId ? Number(req.params.chainId) : undefined
const data: Record<
ChainId,
{
tokenId: number
decimals: number
symbol: string
balance: string
recoveryBalance: string
}[]
> = {}
if (chainId) {
const r = await batchGetPendingBalance(Number(chainId), account)
if (r !== null) {
data[chainId] = r
}
} else {
const supportChains = await getSupportChains()
const qs = supportChains.map((v) => {
return batchGetPendingBalance(Number(v.layerOneChainId), account)
})
const rs = await Promise.all(qs)
supportChains.forEach((v, i) => {
if (rs[i] !== null) {
data[v.layerOneChainId] = rs[i]!
}
})
}
res.json({
code: 0,
data,
})
} catch (e: any) {
logger.error(e)
res.json({
code: e?.code ?? 500,
message: e?.message,
})
}
}
|
<template>
<div class="shop-info">
<div class="shop-top">
<img :src="shop.logo" alt="">
<span class="shop-name">{{shop.name}}</span>
</div>
<div class="shop-middle">
<div class="shop-middle-left">
<div class="sells-info">
<div class="sells-count">{{shop.sells | sellCountFilter}} </div>
<div class="sells-text">总销量</div>
</div>
<div class="goods-info">
<div class="goods-count">{{shop.shopGoods}}</div>
<div class="goods-text">全部宝贝</div>
</div>
</div>
<div class="shop-middle-right" >
<table>
<tr v-for="(item,index) in shop.scores" :key="index">
<td>{{item.name}} </td>
<td class="score" :class="{'score-better': item.isBetter === true}">{{item.score}} </td>
<td class="better" :class="{'better-more': item.isBetter === true}">{{item.isBetter ? "高" : "低"}} </td>
</tr>
</table>
</div>
</div>
<div class="shop-bottom">
<a :href="shop.shopUrl">
<div class="enter-shop">进店逛逛</div>
</a>
</div>
</div>
</template>
<script>
export default {
name: 'DetailShop',
props: {
shop: {
type: Object,
default() {
return {}
}
}
},
filters: {
sellCountFilter: function (value) {
if (value < 10000) return value;
return (value/10000).toFixed(1) + '万'
}
},
}
</script>
<style lang='scss' scoped>
.shop-top {
padding: 30px 20px;
display: flex;
align-items: center;
img {
width: 50px;
height: 50px;
border-radius: 50%;
border: 1px solid rgba(0,0,0,.1);
}
.shop-name {
padding: 0 20px;
}
}
.shop-middle {
display: flex;
padding: 10px 0;
font-size: 14px;
.shop-middle-left {
flex: 1;
display: flex;
align-items: center;
justify-content: space-evenly;
text-align: center;
color: #333;
border-right: 1px solid rgba(0,0,0,.1);
.sells-info {
// flex: 1;
.sells-count {
font-size: 18px;
}
.sells-text {
margin-top: 10px;
font-size: 12px;
}
}
.goods-info {
// flex: 1;
.goods-count {
font-size: 18px;
}
.goods-text {
margin-top: 10px;
font-size: 12px;
}
}
}
.shop-middle-right {
display: flex;
justify-content: center;
flex: 1;
text-align: center;
font-size: 13px;
color: #333;
tr {
display: block;
margin : 5px 0;
}
.score {
width: 35px;
padding: 0 3px;
color: #5ea732;
}
.score-better {
color: #f13e3a;
}
.better {
color: #fff;
background-color: #5ea732;
}
.better-more {
color: #fff;
background-color: #f13e3a;
}
}
}
.shop-bottom {
text-align: center;
margin-top: 10px;
.enter-shop {
display: inline-block;
font-size: 14px;
background-color: #f2f5f8;
width: 150px;
height: 30px;
text-align: center;
line-height: 30px;
border-radius: 10px;
}
}
</style>
|
function solve(input) {
let school = {};
for (let line of input) {
if (line.includes(':')) addCourse(line);
if (line.includes('joins')) addStudent(line);
}
let sortedSchool = Object.fromEntries(Object.entries(school).sort((a, b) =>
Object.keys(b[1].students).length - Object.keys(a[1].students).length
))
Object.keys(sortedSchool).forEach(key => {
sortedSchool[key].students.sort((a, b) => b.credits - a.credits);
});
for(let key of Object.keys(sortedSchool)){
let places = sortedSchool[key].capacity;
console.log(`${key}: ${places} places left `);
for(let obj of Object.values(sortedSchool[key].students)){
console.log(`--- ${obj.credits}: ${obj.userName}, ${obj.email}`);
}
}
function addCourse(string) {
let [course, capacity] = string.split(': ');
capacity = Number(capacity);
if (!school.hasOwnProperty(course)) {
school[course] = {
capacity: capacity,
students: []
}
} else {
school[course].capacity += capacity;
}
}
function addStudent(string) {
let [user, credits, email, course] = string.split(/\[|\] with email | joins /g);
credits = Number(credits);
if (school.hasOwnProperty(course)) {
let placesLeft = school[course].capacity
if (placesLeft > 0) {
school[course].students.push({
userName: user,
credits : credits,
email: email
})
school[course].capacity --;
}
}
}
function checkStudent(user, course) {
for (let key of school[course]) {
if (key.hasOwnProperty(user)) {
return true
}
}
return false
}
}
solve([
'JavaBasics: 2',
'user1[25] with email [email protected] joins C#Basics',
'C#Advanced: 3',
'JSCore: 4',
'user2[30] with email [email protected] joins C#Basics',
'user13[50] with email [email protected] joins JSCore',
'user1[25] with email [email protected] joins JSCore',
'user8[18] with email [email protected] joins C#Advanced',
'user6[85] with email [email protected] joins JSCore',
'JSCore: 2',
'user11[3] with email [email protected] joins JavaBasics',
'user45[105] with email [email protected] joins JSCore',
'user007[20] with email [email protected] joins JSCore',
'user700[29] with email [email protected] joins JSCore',
'user900[88] with email [email protected] joins JSCore'
])
|
<template>
<div class="InputBox">
<p class="name"> {{ attributes.name }} </p>
<input v-show="attributes.type !== 'avatar'" class="input"
:type="attributes.type"
:placeholder="attributes.hint"
v-model="value" />
<input class="input-file"
type="file"
style="display: none"
id="input-file"
v-on:change="upload_file"/>
<i v-show="attributes.type === 'avatar' && is_empty(value)"
class="material-icons"
style="font-size: 3vw; align-items: center; justify-content: center; display: flex; border-radius: 50%; cursor: pointer; position: relative; left: 5%"
@click="select_file">account_circle</i>
<img v-if="attributes.type === 'avatar' && !is_empty(value)"
style="width: 3vw; height: 3vw; border-radius: 50%; position: relative; left: 4%; object-fit: cover"
@click="select_file"
:src="is_empty(value) ? '' : 'http://localhost:8000/Images/' + value">
</div>
</template>
<script>
import api from "@/components/Http/http";
export default {
name: "InputBox",
computed: {
value: {
get() {
return this.modelValue
},
set(value) {
this.$emit('update:modelValue', value)
}
}
},
methods: {
is_empty(str) {
return str.trim().length === 0
},
select_file() {
document.getElementById("input-file").click()
},
upload_file(e) {
let formData = new FormData()
formData.append('file', e.target.files[0])
api.post("/file/avatar", formData, {
headers: {'Content-Type': 'multipart/form-data'}
}).then(response => {
this.value = response.message
}).catch(error => {
console.log(error)
})
}
},
emits: ['update:modelValue'],
props: {
attributes: {
type: Object,
required: true
},
modelValue: {
type: String,
default: '',
}
},
data() {
return {
}
}
}
</script>
<style scoped>
.InputBox {
height: 100%;
position: relative;
display: flex;
flex-direction: row;
padding: 0 20px;
/*justify-content: center;*/
align-items: center;
animation: fade-in 0.3s ease-in-out;
}
@keyframes fade-in {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.name {
height: min-content;
margin: 0;
font-size: 1.1vw;
font-weight: bold;
}
.input {
width: 70%;
margin-left: 10px;
border: none;
font-size: 1vw;
}
.input:focus {
outline: none;
}
.input-file {
}
</style>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
input{
box-sizing: border-box;
width: 100%;
padding:10px 20px;
background-color: ivory;
margin: 5px 0;
}
input[type=text]{
border-radius: 15px;
color: deeppink;
}
/* 클릭시 */
input[type=text]:focus{
background-color: lavenderblush;
outline:none;
}
input[type=password]{
border:none;
border-bottom: 3px solid hotpink;
}
input[type=password]:focus{
border:none;
border-bottom: 3px dashed red;
}
select{
border: 2px solid yellowgreen;
width: 100px;
box-sizing: border-box;
padding:10px; /*패딩가능*/
margin:10px;
font-weight: bold; /*선택되면 굵은글씨로 */
}
/*입력창*/
textarea{
box-sizing: border-box;
width: 100px;
height: 200px;
font-size: 16px;
resize: none;
}
input[type=button], input[type=reset], input[type=submit]{
width: 100px;
background-color: powderblue;
color: black;
border: none; /*x면 검정테두리 생김*/
cursor:pointer;
}
</style>
</head>
<body>
<from action="">
<p>아이디: <input type="text" placeholder="아이디를 입력하세요" required/></p>
<p>비밀번호: <input type="password" placeholder="비밀번호를 입력하세요" required/></p>
<p>
직업
<select>
<option>교사</option>
<option>강사</option>
<option>의사</option>
<option>판사</option>
<option>학생</option>
<option>주부</option>
<option>사무직</option>
<option>기타</option>
</select>
</p>
<p>
<input type="submit" value="회원가입"/>
<input type="reset" value="다시작성"/>
<input type="button" value="돌아가기"/>
</p>
</from>
</body>
</html>
|
---
title: "E80: Experimental Engineering"
---
## Welcome!
E80, Experimental Engineering, is a sophomore-level, semester-long required course, in which students conduct multiple experiments covering a number of engineering disciplines.
These experiments are a training ground for a final project: a field deployment where student teams measure phenomena of their choice.
Experimental Engineering is an essential part of the engineering curriculum at Harvey Mudd College, and has been offered as a course for over twenty years.
Its predecessor E54 - which had more experiments and no field experience - was also offered for more than 20 years.
The primary purpose of the course is to teach basic instrumentation and measurement techniques, good lab report practice, technical report writing, analysis and presentation of data, the usage of experimental results for engineering design purposes, and the beginnings of professional practice.
In 2008 the course was revamped to change the field experience to flying fully-instrumented model rockets. In 2017 the course was revamped again with yet another new field experience: deploying fully autonomous underwater robots.
## Faculty and Office Hours
| Name | Day | Hours | Location |
|---------------------|------------------------|-------------------------------------|----------|
| Matthew Spencer | Monday | 9:30 am to 11:00 am and<br>1:00 pm to 4:00 pm | Parsons 2358 |
| Ethan Ritz | Monday/Wednesday | 4:00 pm to 5:00 pm | Middle tent in Strauss plaza |
| Qimin Yang | Tuesday | 9:00 am to 11:00 am | Parsons 2365 |
| Josh Brake | Tuesday | 1:00 pm to 3:00 pm | Tent outside Parsons |
| Dre Helmns | Wednesday | 1:00 pm to 3:00 pm | Parsons 1292C |
You may attend any office hours, not just your section professor's.
## Meeting Times
- <u>Lab Section 1</u>:\
Tuesday 1:15 p.m. to 5:15 p.m. in Parsons B171 & B181 (Prof. Helmns)
- <u>Lab Section 2</u>:\
Wednesday 1:15 p.m. to 5:15 p.m. in Parsons B171 & B181 (Prof. Yang)
- <u>Lab Section 3</u>:\
Thursday 1:15 p.m. to 5:15 p.m. in Parsons B171 & B181 (Prof. Ritz)
- Writing and Reflection for all sections - Friday 1:15 p.m. - 3:15 p.m
- Section 1 - Shan 2440
- Section 2 - Shan 2450
- Section 3 - Shan 2454
After spring break: There will be open lab hours in Parsons B171 & B181 during the normally scheduled lab times.
Students may only work in the E80 labs when a professor, staff or a proctor opens the lab. Any team may use the equipment in the labs during a lab section, but teams that are scheduled for the section have top priority for the equipment.
## Mask Policy
Masks will be required for all E80 activities until further notice.
## Digital Communication
- [https://github.com/HMC-E80/E80](https://github.com/HMC-E80/E80) This is our Github repository, which lets you use Git to acces E80 software. Git is a distributed version control system where you can copy source code and track changes to the code. [Lab 0](/labs/lab0) will walk you through the steps to configure Git on your computer.
- [https://discord.gg/Eu7gFZKgcj](https://discord.gg/Eu7gFZKgcj) This is an invite to our Discord server. All digital communication and asynchronous help requests will go through Discord, so default to messaging there instead of emailing us.
- [https://harveymuddcollege.instructure.com/courses/1097](https://harveymuddcollege.instructure.com/courses/1097) This is our Canvas site. We will use Canvas to collect your assignments, receive your quiz responses and record your grades.
- All other information for the course is distributed on this website.
## Course kit fee
- There is a $65 kit fee per student. This fee can be waived in cases of financial hardship. Course instructors will not know about waiver requests.
- Kit payment can be made [here](https://docs.google.com/forms/d/e/1FAIpQLSfLGyW_zk6jB89jHjIme0mkHV_LVAtXeJSDNIf7njMEDN1t1w/viewform).
- Kit waiver request can be made [here](https://docs.google.com/forms/d/e/1FAIpQLScM-5lYfwQAE_5v6WAz357C1cftwr4sNQRPj4dC_GaPD-ihvw/viewform).
## Team and Group Assignments
Almost all work in E80 is completed in teams. Some details about teams are below.
- Teams are assigned before your first laboratory meeting.
- These assignments will be made using whatever method your instructor desires, and the nominal team size is four members.
- Sometimes registration limits in a class will require teams of three or five members to be formed.
- These teams are designated using a 2 digit number where the first is your section number and the second is your team's number (e.g. section 1's team 1 is 11).
- You must report your team number on all assignments.
- For three of the labs (2, 3, and 4), you will need to split your team into 2 sub-teams.
- A different sub-team must be used for each of these Labs.
- Team assignments will be for the duration of the course.
- If you're having problems on your team, talk to a professor or staff member *early* so we can try to help.
Team assignments can be found on the [People tab on Cavnas](https://harveymuddcollege.instructure.com/courses/1097/users).
## Graded Submissions
### Graded Submissions Breakdown
::: {.center-table}
| Item | Weight |
|--------------------------------|:------:|
| [Lecture Quizzes](#lecture-quizzes) | 7% |
| [Surveys and Team Check-Ins](#surveys-and-team-check-ins) | 6% |
| [Laboratory Submission Sheets](#laboratory-submission-sheets) | 32% |
| [Laboratory Writing Assignments](#laboratory-writing-assignments) | 15% |
| [Technical Memorandum](#technical-memorandum) | 10% |
| [Final Presentation](#final-presentation) | 10% |
| [Final Report](#final-report) | 15% |
| [Participation](#participation) | 5% |
:::
### Turn-In on Canvas
All assignments that you need to complete, including links to quizzes, can be found in the [Modules tab on Cavnas](https://harveymuddcollege.instructure.com/courses/1097/modules). You will always turn in assignments on Canvas or complete quizzes/surveys linked from Canvas.
### Specifications Grading
The grading in E80 for submission sheets and writing assignments is based on whether or not your deliverables meet two different levels of specifications: **effort** and **completion**.
The overall grade on an assignment is determined by how many of the sections meet either effort or completion.
Effort specs describe **good-faith effort** whereas completion specs describe **correctness**.
In most situations, completing all the effort specs is equivalent to a passing grade on the assignment.
The remaining sections of completion specs raise your grade from a passing grade to full credit.
If the initial version of a submitted assignment does not meet specs, it may be revised according to the stipulations of the course [resubmissions policy](#resubmission-policy).
### Graded Submissions Details
#### Lecture Quizzes
- There are seven video lecture sets that you are expected to watch. Each of these video sets has an associated online quiz. You must take each of these quizzes individually.
- You may not talk to other people in order to take the quiz, but they are open book, notes and internet. The one exception to the 'no people' rule is that you may speak with a professor to clarify ideas before you open the quiz associated with the lecture set.
#### Surveys and Team Check-Ins
- You will be called upon to complete surveys at the beginning, middle and end of the class, and each week, you will be asked to complete a team check-in (a quick peer evaluation) for the lab done that week. Completing each of the check-ins is worth 0.5% of your grade, and completing each of the longer surveys is worth 1% of your grade.
- There are a total of 6 weekly check-ins (from weeks 2 through 7) and they are due each Friday at 3:30 pm.
- These are individual assignments
#### Laboratory Submission Sheets
- There are a total of 8 labs in the class: Lab0 through Lab7. You must submit a submission sheet for each of the labs that contains data you collected during the lab. (Though note that in lab0 the Matlab on-ramp deliverable is the submission sheet.) This submission sheet will be evaluated for correctness: it's a way of assessing whether your experimental procedure was correct during the lab. Each submission sheet you provide will be worth 4% of your final grade.
- These are group assignments, so there will be only one submission per team. The Matlab onramp for lab 0 is an exception: it is an individual assignment.
#### Laboratory Writing Assignments
- You will be required to complete a writing assignment after labs 1-5. The purpose of the writing assignments is to train you in specific aspects of scientific writing: making figures, using tables, equations, etc. These assignments are completed entirely on Friday in the Writing and Reflection section. Each writing assignment will be worth 3% of your final grade, and you submit five assignments for a total of 15%.
- These are individual assignments. The team contract exercise in week 0 is an exception, there should be one team contract submission per team.
#### Technical Memorandum
- Each student will write an individual technical memorandum on material covered in Lab 6. See the [Lab 6](labs/lab6) page for more information.
- You must submit a tech memo to pass the class.
#### Final Presentation
- Each team will make a final presentation during Presentation Days, on Wednesday, May 1st, 2024. A detailed schedule will be posted ASAP. The presentation is 15-minutes long followed by a 10-minute Q&A session. The Final Presentation guidelines and rubric are found on the [Final Project Report and Presentation page](/labs/project/report).
#### Final Report
- A final technical report will be submitted by each team on the results of the final AUV deployments. The report will be graded for both technical content and proper use of [technical English](https://www.mit.edu/course/21/21.guide/). A rough draft of your final report is due at 11:59 PM on 4/26/24. The final draft is due at 11:59 PM on 5/1/2024. The Final Report guidelines are found on the Final Project page.
#### Participation
- The instructors will assign you a participation grade which is determined by their in-lab observations, your peer evaluations, and your regular progress through the project checkoffs.
## End-of-Semester Grades
Grades will be awarded on a standard grading scale (93.3% is an A, 90% A-, 86.6% is a B+, etc ...) based on your total individual score.
The professors reserve the right to award grades more leniently than this grading standard.
## Course Calendar
A Google Sheet with the key dates and assignments in E80 can be found [here](https://docs.google.com/spreadsheets/d/1qR7HhVNWtqK8va9gGP6NGhX_NoIblt1x9VRRuFam1ng/edit?usp=sharing).
You can also review the [Modules tab on Cavnas](https://harveymuddcollege.instructure.com/courses/1097/modules) for a week-by-week breakdown of what's due with links to refernece material and where to turn stuff in.
## Course Policies
### Attendance and Tardiness
Students sometimes have to miss E80 labs for an assortment of reasons. The instructors don't record attendance because we assume that groups will work to equitably account for absences or tardiness. For example, if your group has a member with a planned absence for a particular lab, then you and your teammates should discuss how to shift more prelab work to the person who will be absent. If you don't feel like everyone is pulling their fair share, talk to your group and talk to an instructor so we can help you navigate the situation.
### Late Work Policy
No late work is accepted. You will receive no points for work submitted after deadlines.
This is in keeping with good professional practice. Some assignments may allow for multiple attempts and resubmission, but the first attempt always needs to be submitted by the appropriate deadline.
### Incomplete Grade Policy
Incomplete grades will be granted only in rare circumstances and require the approval of the instructor.
### Pre- and Post-Lab Work Policy
The amount of time that you are free to work in lab is restricted. We enforce these restrictions for three main reasons:
(1) to simulate demands that can arise in real-world engineering,
(2) to help students internalize the learning goals of the class, and
(3) to help keep E80 to a smaller time footprint.
You are allowed to work in any way you would like on before a lab (pre-lab) as long as you do not touch any hardware.
You may NOT collect data (for your experiment), manipulate or test hardware, populate a protoboard, or use the laboratory equipment outside of your lab hours.
However, you may look at datasheets, write software, calculate expected results, prepare Excel sheets to do calculations in lab, ask how equipment works, run your preparations by professors, and pursue a variety of other activities.
You can spend as much or as little time desired on the pre-lab activities, but successful teams spend a lot of time and energy before the lab starts.
The post-lab period is for reflection, resubmission when it's allowed, and taking a break from E80.
You may NOT collect data, manipulate or test hardware, populate a protoboard, or use the laboratory equipment outside of lab.
However, you may freely reprocess any data that you have already collected during a lab section.
This includes, but is not limited to, writing MATLAB code for processing and visualizing your data.
When in doubt about whether an activity is acceptable outside of lab, ask.
### Resubmission Policy
Lab submission sheets and writing assignments in E80 are able to be resubmitted without penalty if they do not meet completion specs on the initial attempt.
To be clear, this means that resubmitted assignments are worth the same amount as initial submission and full credit can be earned even if the initial submission does not fully meet the specifications.
The resubmission policy is subject to the stipulations listed below:
1. You must submit **something** by the assignment deadline.
- Don't phone this in because there is limited time for resubmission.
2. After you receive feedback, you can revise your submissions until spring break.
- Most of specs can be done outside of lab with data.
- However, if you weren't able to get good data, there is one week before spring break where you can go back to collect more.
3. Resubmissions are checked off by an instructor during office hours.
4. For all submissions, you will need to self-assess **before** you submit. Every assignment you submit should be accompanied along with a checklist of specs that you believe the assignment meets or does not meet.
5. All resubmissions must be completed by spring break.
### Cooperation Between Teams
Cooperation between teams is limited.
The rules for each period of the week (pre-lab, during lab, post-lab and writing and reflection) are below.
In this section, the word group will refer to a full team of students during a normal week or a sub-team of students during weeks where teams are split into sub-teams.
1. Pre-lab: A group may discuss the lab with another group to make sure they are clear on concepts and understanding. Groups may not share code, writing, or documentation with other groups.
2. During Lab: Groups cannot work together, discuss concepts or understanding, share data, share code, or share writing. Groups may arrange to swap hardware to debug and test defective parts of an experiment or device, but they should strongly consider elevating their concerns to an instructor if part swaps are necessary or if parts are being destroyed.
3. Post-Lab: Groups may work with other groups in the same way as the prelab: they may discuss concepts and understanding (including talking about the scale of measured results from lab).
4. Writing and Reflection: Each student should be producing an individual work product and may not exchange code or writing with other students. Data may be shared among a group, but not between groups.
These work restrictions are relaxed during the final project (after spring break): Groups may work on their robot at any time and may discuss any aspect of their robots with one another (as if the prelab policy always applies).
### Sharing Rubrics
We will be returning/releasing graded lab report rubrics throughout the semester.
It is an HONOR CODE VIOLATION to share these rubrics with other teams or with students enrolled in future versions of E80.
### Access to Lab During the Final Project
- Students may work in the labs any time that it is open.
- Students may only work in the E80 lab when a professor, staff member or proctor opens the lab.
- Any team may use the equipment in the E80 and electronics labs during a lab section, but teams which are scheduled for a section have top priority for the equipment.
### Accessibility and Accommodations
Harvey Mudd College strives to make all learning experiences as accessible as possible. If you anticipate or experience academic barriers based on your disability (including mental health, chronic or temporary medical conditions). If you have any questions, please contact the Office of Accessible Education at [[email protected]](mailto:[email protected]). Students from the other Claremont Colleges should contact their home college's disability officer. You also need to register with the [Office of Disability Resources](https://www.hmc.edu/student-life/disability-resources/). to establish reasonable accommodations.
### Academic Honesty/Plagiarism
**Each student will be responsible for observing HMC's Honor code and abiding by the Standards of Conduct:**\
> “All members of ASHMC are responsible for maintaining their integrity and the integrity of the College community in all academic matters and in all affairs concerning the community.” --<cite>ASHMC Constitution</cite>
1. Thoughtful respect for the rights of others;
2. Honesty and integrity in both academic and personal matters;
3. Responsible behavior both on and off campus;
4. Appropriate use of campus buildings and equipment, and;
5. Compliance with College regulations and policies.
|
package ru.kata.spring.boot_security.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.kata.spring.boot_security.demo.model.User;
import ru.kata.spring.boot_security.demo.repository.UserRepository;
import ru.kata.spring.boot_security.demo.userdetails.UserDetailsImpl;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String bankAccount) throws UsernameNotFoundException {
User user = userRepository.findByBankAccount(bankAccount)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
return new UserDetailsImpl(user);
}
}
|
<!DOCTYPE html>
<html lang="pt-br">
<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" type="text/css" href="bootstrap/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Minha pagina</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light margin">
<a class="navbar-brand" href="#">
<img src="img/globallabs.png" alt="" width="220" height="80">
</a>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link white-text" href="#quemsomos">Quem somos</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#parceiros">Parceiros</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#servicos">Servicos</a>
</li>
</ul>
</div>
</nav>
<section id="quemsomos">
<div class="container-fluid quem-somos text-center margin" >
<h3>Quem Somos</h3>
<img src="img/time.jpg" class="rounded-circle" width="300" height="300">
<h4>Somos um time comprometido com os resultados</h4>
</div>
</section>
<section id="parceiros">
<div class=" container-fluid text-center margin parceiros">
<h3>Parceiros</h3>
<div class="container">
<div class="row">
<div class="col-lg-4">
<img src="img/dio.png" alt="" width="100%">
</div>
<div class="col-lg-4">
<img src="img/dio.png" alt="" width="100%">
</div>
<div class="col-lg-4">
<img src="img/dio.png" alt="" width="100%">
</div>
</div>
</div>
</div>
</section>
<section id="servicos">
<div class="container-fluid text-center margin servicos">
<h3>Serviços</h3>
<div class="container">
<div class="row">
<div class="col-lg-6">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<img src="img/app1.jpg" alt="" width="100%">
</div>
<div class="col-lg-6">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<img src="img/app2.jpg" alt="" width="100% ">
</div>
</div>
</div>
</div>
</section>
<footer class="container-fluid text-center bg-footer margin">
<p>Desenvolvido por Jhonatan assis</p>
</footer>
</body>
</html>
|
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const authRoute = require("./routes/auth");
const userRoute = require("./routes/users");
const postRoute = require("./routes/post");
app.use(express.json());
dotenv.config();
mongoose
.connect(process.env.MONGO_DB, {})
.then(console.log("Database Connected"))
.catch((err) => {
console.log(err);
});
app.get("", (req, res) => {
res.send(
"Api is working \n getRequest for post => https://blogrestapi152.herokuapp.com/api/post "
);
});
app.use("/api/auth", authRoute);
app.use("/api/user", userRoute);
app.use("/api/post", postRoute);
module.exports = app;
|
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CategoryRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* バリーデーションのためにデータを準備
*
* @return void
*/
protected function prepareForValidation()
{
// 全角スペースを半角スペースに変換します
$this->merge([
'categoryName' => mb_convert_kana($this->categoryName, 's')
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'categoryName' => 'required'
];
}
/**
* 定義済みバリデーションルールのエラーメッセージ取得
*
* @return array
*/
public function messages()
{
return [
'categoryName.required' => 'カテゴリー名は必須です。'
];
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact section project</title>
<link href="/fontawesome-free-5.15.4-web/css/all.css" rel="stylesheet"> <!--load all styles -->
<!-- bootstrap4 cdn -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<style>
#contact{
padding: 2% 10%;
background-color: cadetblue;
}
.form-group label{
margin-bottom: 0;
font-weight: bolder;
}
</style>
</head>
<body>
<section id="contact">
<div class="section-title">
<h3 class="text-center text-light">Contact Me</h3>
<hr class="hr-style">
</div>
<div class="row">
<div class="col-lg-12">
<form action="mailto:[email protected]" method="POST" enctype="text/plain" class="was-validated">
<div class="form-group mb-1">
<label for="fullname">Full Name:</label>
<input type="text" class="form-control" name="fullname" required>
<div class="valid-feedback" style="color: darkgreen;">valid</div>
<div class="invalid-feedback" style="color: red;">Enter fullname before submitting the form</div>
</div>
<div class="form-group mb-1">
<label for="email">E-mail:</label>
<input type="email" class="form-control" name="email" required>
</div>
<div class="form-group mb-1">
<label for="message">Message:</label>
<textarea style="resize: none;" class="form-control" name="" id="" cols="30" rows="4"></textarea>
</div>
<div class="form-group text-center mb-1">
<input type="submit" class="btn btn-primary" value="submit">
<input type="reset" class="btn btn-primary" value="reset">
</div>
</form>
</div>
</div>
</section>
<!-- bootstrap js, jquery, popper -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</body>
</html>
|
<!DOCTYPE html>
<html xmlns:th="http//www.thymeleaf.org">
<head th:replace="master/master :: head">
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<header th:replace="master/master :: header"></header>
<div class="container">
<div>
<form th:action="@{/suscripciones/guardar}" method="post"
th:object="${sus}">
<div class="col-sm-12">
<label class="form-label">Paciente:</label> <select
name="selectPaciente" class="form-control"
th:field="*{paciente.idPaciente}">
<option th:each="pa:${listaPacientes}" th:value="${pa.idPaciente}"
th:text="${pa.nombrePaciente}"
selected="(${pa.idPaciente}==*{paciente.idPaciente})"></option>
</select>
</div>
<div class="col-sm-12">
<label class="form-label">Plan:</label> <select name="selectPlan"
class="form-control" th:field="*{plan.idPlan}">
<option th:each="pl:${listaPlanes}" th:value="${pl.idPlan}"
th:text="${pl.titulo}" selected="(${pl.idPlan}==*{plan.idPlan})">
</option>
</select>
</div>
<div class="col-sm-12">
<label class="form-label">Fecha: </label> <input type="date"
class="form-control" th:field="*{fecha}"></input>
</div>
<div class="col-sm-12">
<label class="form-label">Meses: </label> <input
type="text" class="form-control" th:field="*{meses}"></input>
</div>
<div class="col-sm-12">
<input type="submit" class="btn btn-dark" value="Registrar"></input>
</div>
</form>
</div>
</div>
</body>
</html>
|
// Declare global variables
let numRows = 0;
let numCols = 0;
let colorSelected;
// Add a row
function addR() {
let table = document.getElementById("grid");
// Check if there are no columns
if(numRows == 0){
numCols = 0;
}
numRows++;
// Creating a new row using "tr" which is a table row
let new_row = table.insertRow();
// Create a new box for each column
for(let i = 0; i <= numCols; i++){
// Create a new box using "td" which is a table data
let newBox = new_row.insertCell();
// Set the color of the box to the selected color
newBox.onclick = function()
{
newBox.style.backgroundColor=colorSelected
};
// Append the new box to the new row
// new_row.appendChild(newBox);
}
// Append the new row to the table
//numRows++;
console.log("Rows: " + numRows + " Columns: " + numCols + "\n Added a row");
}
// Add a column
function addC() {
let table = document.getElementById("grid");
//numCols++;
// If there are no rows, add one row because the grid is empty
if(numRows == 0) {
addR(); // Use addR to add both a row and a column if the grid is empty
return;
}
numCols++;
// Iterate through each row and add a new box to the end of each row
for(let i = 0; i < numRows; i++){
let newBox = document.createElement("td");
newBox.onclick = function()
{
newBox.style.backgroundColor=colorSelected
};
// Append the new box to the end of each row
table.rows[i].appendChild(newBox);
}
//numCols = table.rows[0].cells.length;
console.log("Rows: " + numRows + " Columns: " + numCols + "\n Added a column");
}
// Remove a row
function removeR() {
// If there are no rows, do nothing
if(numRows == 0){
return;
}
let table = document.getElementById("grid");
table.deleteRow(-1);
numRows--;
// if the row we removed was the last remaining row, then we have no columns
if(numRows == 0){
numCols = 0;
}
console.log("Rows: " + numRows + " Columns: " + numCols + "\n Removed a row");
}
// Remove a column
function removeC() {
let table = document.getElementById("grid");
// If there are no columns, make sure to delete rows if there are any
if(numCols == 0){
numRows = 0;
while(table.rows.length > 0)
{
table.deleteRow(0);
}
return;
}
// Iterate through each row and delete the last box in each row
numCols--;
for(let i = 0; i < table.rows.length; i++)
{
table.rows[i].deleteCell(-1);
}
console.log("Rows: " + numRows + " Columns: " + numCols + "\n Removed a column");
}
// Set global variable for selected color
function selectColor(){
colorSelected = document.getElementById("selectedColorId").value;
console.log(colorSelected);
}
// Fill all uncolored cells
function fillU(){
let table = document.getElementById("grid");
// Iterate through each cell and set the background color to the selected color if it is not already colored
for(let i = 0; i < table.rows.length; i++){
for(let j = 0; j < table.rows[i].cells.length; j++)
{
if(table.rows[i].cells[j].style.backgroundColor === "")
{
table.rows[i].cells[j].style.backgroundColor = colorSelected;
}
}
}
}
// Fill all cells
function fillAll(){
let table = document.getElementById("grid");
// Iterate through each cell and set the background color to the selected color
for(let i = 0; i < table.rows.length; i++)
{
for(let j = 0; j < table.rows[i].cells.length; j++)
{
table.rows[i].cells[j].style.backgroundColor = colorSelected;
}
}
}
// Clear all cells
function clearAll(){
let table = document.getElementById("grid");
// Iterate through each row and delete
while(table.rows.length > 0)
{
table.deleteRow(0);
}
numRows = 0;
numCols = 0;
}
|
<?php
namespace App\Http\Controllers;
use App\Models\Hobi;
use App\Models\HobiModel;
use Illuminate\Http\Request;
class HobiModelController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$hobi = HobiModel::all();
return view('hobi.hobi')
->with('hb',$hobi);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('hobi.create_hobi')
->with('url_form', url('/hobi'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//validasi
$request->validate([
'nim' => 'required|string|max:10|unique:hobi,nim',
'nama' => 'required|string|max:50',
'hobi' => 'required|string|max:200',
]);
$data =HobiModel::create($request->except(['_token']));
return redirect('hobi')
->with('success', 'Hobi Berhasil Ditambahkan');
}
/**
* Display the specified resource.
*
* @param \App\Models\Hobi $hobi
* @return \Illuminate\Http\Response
*/
public function show(HobiModel $hobi)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Hobi $hobi
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$hobi = HobiModel::find($id);
return view('hobi.create_hobi')
->with('hb', $hobi)
->with('url_form', url('/hobi/'. $id));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Hobi $hobi
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'nim' => 'required|string|max:10|unique:hobi,nim,'.$id,
'nama' => 'required|string|max:50',
'hobi' => 'required|string|max:200',
]);
$data =HobiModel::where('id', '=', $id)->update($request->except(['_token', '_method']));
return redirect('hobi')
->with('success', 'Hobi Berhasil Diedit');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Hobi $hobi
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
HobiModel::where('id', '=', $id)->delete();
return redirect('hobi')
->with('success', 'Hobi berhasil Dihapus');
}
}
|
//
// AlertDisplayer.swift
// IMDB
//
// Created by Ramy Sabry on 29/04/2022.
//
import UIKit
import RxSwift
import RxCocoa
protocol AlertDisplayerProtocol {
func showAlert(with alertItem: AlertItem?)
}
extension AlertDisplayerProtocol where Self: BaseViewController {
func bindAlert(to alertItem: BehaviorRelay<AlertItem?>) {
alertItem.subscribe { [weak self] alertItem in
guard let self = self else { return }
guard let alertItem = alertItem.element else { return }
self.showAlert(with: alertItem)
}
.disposed(by: disposeBag)
}
func showAlert(with alertItem: AlertItem?) {
guard let alertItem = alertItem else { return }
let alertController = UIAlertController(
title: alertItem.title,
message: alertItem.message,
preferredStyle: alertItem.style
)
alertItem.actions.forEach { action in
alertController.addAction(
action.toUIAlertAction
)
}
self.startPresentationTimerIfNeeded(with: alertItem, for: alertController)
DispatchQueue.main.async {
self.present(alertController, animated: true, completion: nil)
}
}
private func startPresentationTimerIfNeeded(
with alertItem: AlertItem,
for alertController: UIAlertController
) {
guard alertItem.actions.isEmpty == false else { return }
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
alertController.dismiss(animated: true, completion: nil)
}
}
}
|
import React, { useState, useId } from 'react'
import { FaAngleRight, FaAngleDown } from 'react-icons/fa'
export function Disclosure({ children, label, defaultIsOpen = false }) {
const [isOpen, setIsOpen] = useState(defaultIsOpen)
function onSelect() {
setIsOpen(!isOpen)
}
// Notice how awful it is to build class name strings.
// We'll fix it with data-attributes
return (
<div className="disclosure">
<button onClick={onSelect} className={`disclosure-button ${isOpen ? 'open' : 'collapsed'}`}>
{isOpen ? <FaAngleDown /> : <FaAngleRight />}
<span>{label}</span>
</button>
<div className={`disclosure-panel ${isOpen ? 'open' : 'collapsed'}`} hidden={!isOpen}>
{children}
</div>
</div>
)
}
export const DisclosureButton = ({ children }) => {}
export const DisclosurePanel = ({ children }) => {}
|
package com.creatoo.hn.dao.model;
import java.util.Date;
import javax.persistence.*;
@Table(name = "whg_supply_tra")
public class WhgSupplyTra {
/**
* 培训ID
*/
@Id
private String id;
/**
* 创建时间
*/
private Date crtdate;
/**
* 创建人
*/
private String crtuser;
/**
* 状态(1-可编辑, 9-待审核, 2-待发布,6-已发布, 4-已下架, 5-已撤消)
*/
private Integer state;
/**
* 状态变更时间
*/
private Date statemdfdate;
/**
* 状态变更用户ID
*/
private String statemdfuser;
/**
* 删除状态(0-未删除;1-已删除)
*/
private Integer delstate;
/**
* 培训名称
*/
private String title;
/**
* 部门id
*/
private String deptid;
/**
* 培训图片
*/
private String image;
/**
* 艺术分类
*/
private String arttype;
/**
* 分类
*/
private String etype;
/**
* 关键字
*/
private String ekey;
/**
* 培训方式(0 普通培训 1直播)
*/
private String islive;
/**
* 培训时长
*/
private String duration;
/**
* 培训周期
*/
private String period;
/**
* 是否收费
*/
private Integer ismoney;
/**
* 省份
*/
private String province;
/**
* 市
*/
private String city;
/**
* 区域
*/
private String area;
/**
* 联系人
*/
private String contacts;
/**
* 培训联系电话
*/
private String phone;
/**
* 邮箱
*/
private String email;
/**
* 配送次数
*/
private String psnumber;
/**
* 配送省份
*/
private String psprovince;
/**
* 配送范围
*/
private String pscity;
/**
* 合适人群
*/
private String fitcrowd;
/**
* 说明
*/
private String notice;
/**
* 文化馆ID
*/
private String cultid;
/**
* 培训简介
*/
private String coursedesc;
/**
* 培训大纲
*/
private String outline;
/**
* 审核者
*/
private String checkor;
/**
* 发布者
*/
private String publisher;
/**
* 审核时间
*/
private Date checkdate;
/**
* 发布时间
*/
private Date publishdate;
/**
* 所属单位
*/
private String workplace;
/**
* 固定电话
*/
private String telephone;
/**
* 文艺专家
*/
private String artistid;
public String getArtistid() {
return artistid;
}
public void setArtistid(String artistid) {
this.artistid = artistid;
}
public String getWorkplace() {
return workplace;
}
public void setWorkplace(String workplace) {
this.workplace = workplace;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
/**
* 获取培训ID
*
* @return id - 培训ID
*/
public String getId() {
return id;
}
/**
* 设置培训ID
*
* @param id 培训ID
*/
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
/**
* 获取创建时间
*
* @return crtdate - 创建时间
*/
public Date getCrtdate() {
return crtdate;
}
/**
* 设置创建时间
*
* @param crtdate 创建时间
*/
public void setCrtdate(Date crtdate) {
this.crtdate = crtdate;
}
/**
* 获取创建人
*
* @return crtuser - 创建人
*/
public String getCrtuser() {
return crtuser;
}
/**
* 设置创建人
*
* @param crtuser 创建人
*/
public void setCrtuser(String crtuser) {
this.crtuser = crtuser == null ? null : crtuser.trim();
}
/**
* 获取状态(1-可编辑, 9-待审核, 2-待发布,6-已发布, 4-已下架, 5-已撤消)
*
* @return state - 状态(1-可编辑, 9-待审核, 2-待发布,6-已发布, 4-已下架, 5-已撤消)
*/
public Integer getState() {
return state;
}
/**
* 设置状态(1-可编辑, 9-待审核, 2-待发布,6-已发布, 4-已下架, 5-已撤消)
*
* @param state 状态(1-可编辑, 9-待审核, 2-待发布,6-已发布, 4-已下架, 5-已撤消)
*/
public void setState(Integer state) {
this.state = state;
}
/**
* 获取状态变更时间
*
* @return statemdfdate - 状态变更时间
*/
public Date getStatemdfdate() {
return statemdfdate;
}
/**
* 设置状态变更时间
*
* @param statemdfdate 状态变更时间
*/
public void setStatemdfdate(Date statemdfdate) {
this.statemdfdate = statemdfdate;
}
/**
* 获取状态变更用户ID
*
* @return statemdfuser - 状态变更用户ID
*/
public String getStatemdfuser() {
return statemdfuser;
}
/**
* 设置状态变更用户ID
*
* @param statemdfuser 状态变更用户ID
*/
public void setStatemdfuser(String statemdfuser) {
this.statemdfuser = statemdfuser == null ? null : statemdfuser.trim();
}
/**
* 获取删除状态(0-未删除;1-已删除)
*
* @return delstate - 删除状态(0-未删除;1-已删除)
*/
public Integer getDelstate() {
return delstate;
}
/**
* 设置删除状态(0-未删除;1-已删除)
*
* @param delstate 删除状态(0-未删除;1-已删除)
*/
public void setDelstate(Integer delstate) {
this.delstate = delstate;
}
/**
* 获取培训名称
*
* @return title - 培训名称
*/
public String getTitle() {
return title;
}
/**
* 设置培训名称
*
* @param title 培训名称
*/
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
/**
* 获取培训图片
*
* @return image - 培训图片
*/
public String getImage() {
return image;
}
/**
* 设置培训图片
*
* @param image 培训图片
*/
public void setImage(String image) {
this.image = image == null ? null : image.trim();
}
/**
* 获取艺术分类
*
* @return arttype - 艺术分类
*/
public String getArttype() {
return arttype;
}
/**
* 设置艺术分类
*
* @param arttype 艺术分类
*/
public void setArttype(String arttype) {
this.arttype = arttype == null ? null : arttype.trim();
}
/**
* 获取分类
*
* @return etype - 分类
*/
public String getEtype() {
return etype;
}
/**
* 设置分类
*
* @param etype 分类
*/
public void setEtype(String etype) {
this.etype = etype == null ? null : etype.trim();
}
/**
* 获取关键字
*
* @return ekey - 关键字
*/
public String getEkey() {
return ekey;
}
/**
* 设置关键字
*
* @param ekey 关键字
*/
public void setEkey(String ekey) {
this.ekey = ekey == null ? null : ekey.trim();
}
/**
* 获取培训方式(0 普通培训 1直播)
*
* @return islive - 培训方式(0 普通培训 1直播)
*/
public String getIslive() {
return islive;
}
/**
* 设置培训方式(0 普通培训 1直播)
*
* @param islive 培训方式(0 普通培训 1直播)
*/
public void setIslive(String islive) {
this.islive = islive;
}
/**
* 获取培训时长
*
* @return duration - 培训时长
*/
public String getDuration() {
return duration;
}
/**
* 设置培训时长
*
* @param duration 培训时长
*/
public void setDuration(String duration) {
this.duration = duration == null ? null : duration.trim();
}
/**
* 获取培训周期
*
* @return period - 培训周期
*/
public String getPeriod() {
return period;
}
/**
* 设置培训周期
*
* @param period 培训周期
*/
public void setPeriod(String period) {
this.period = period == null ? null : period.trim();
}
/**
* 获取是否收费
*
* @return ismoney - 是否收费
*/
public Integer getIsmoney() {
return ismoney;
}
/**
* 设置是否收费
*
* @param ismoney 是否收费
*/
public void setIsmoney(Integer ismoney) {
this.ismoney = ismoney;
}
/**
* 获取省份
*
* @return province - 省份
*/
public String getProvince() {
return province;
}
/**
* 设置省份
*
* @param province 省份
*/
public void setProvince(String province) {
this.province = province == null ? null : province.trim();
}
/**
* 获取市
*
* @return city - 市
*/
public String getCity() {
return city;
}
/**
* 设置市
*
* @param city 市
*/
public void setCity(String city) {
this.city = city == null ? null : city.trim();
}
/**
* 获取区域
*
* @return area - 区域
*/
public String getArea() {
return area;
}
/**
* 设置区域
*
* @param area 区域
*/
public void setArea(String area) {
this.area = area == null ? null : area.trim();
}
/**
* 获取联系人
*
* @return contacts - 联系人
*/
public String getContacts() {
return contacts;
}
/**
* 设置联系人
*
* @param contacts 联系人
*/
public void setContacts(String contacts) {
this.contacts = contacts == null ? null : contacts.trim();
}
/**
* 获取培训联系电话
*
* @return phone - 培训联系电话
*/
public String getPhone() {
return phone;
}
/**
* 设置培训联系电话
*
* @param phone 培训联系电话
*/
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
/**
* 获取邮箱
*
* @return email - 邮箱
*/
public String getEmail() {
return email;
}
/**
* 设置邮箱
*
* @param email 邮箱
*/
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
/**
* 获取配送次数
*
* @return psnumber - 配送次数
*/
public String getPsnumber() {
return psnumber;
}
/**
* 设置配送次数
*
* @param psnumber 配送次数
*/
public void setPsnumber(String psnumber) {
this.psnumber = psnumber == null ? null : psnumber.trim();
}
/**
* 获取配送省份
*
* @return psprovince - 配送省份
*/
public String getPsprovince() {
return psprovince;
}
/**
* 设置配送省份
*
* @param psprovince 配送省份
*/
public void setPsprovince(String psprovince) {
this.psprovince = psprovince == null ? null : psprovince.trim();
}
/**
* 获取配送范围
*
* @return pscity - 配送范围
*/
public String getPscity() {
return pscity;
}
/**
* 设置配送范围
*
* @param pscity 配送范围
*/
public void setPscity(String pscity) {
this.pscity = pscity == null ? null : pscity.trim();
}
/**
* 获取合适人群
*
* @return fitcrowd - 合适人群
*/
public String getFitcrowd() {
return fitcrowd;
}
/**
* 设置合适人群
*
* @param fitcrowd 合适人群
*/
public void setFitcrowd(String fitcrowd) {
this.fitcrowd = fitcrowd == null ? null : fitcrowd.trim();
}
/**
* 获取说明
*
* @return notice - 说明
*/
public String getNotice() {
return notice;
}
/**
* 设置说明
*
* @param notice 说明
*/
public void setNotice(String notice) {
this.notice = notice == null ? null : notice.trim();
}
/**
* 获取文化馆ID
*
* @return cultid - 文化馆ID
*/
public String getCultid() {
return cultid;
}
/**
* 设置文化馆ID
*
* @param cultid 文化馆ID
*/
public void setCultid(String cultid) {
this.cultid = cultid == null ? null : cultid.trim();
}
/**
* 获取培训简介
*
* @return coursedesc - 培训简介
*/
public String getCoursedesc() {
return coursedesc;
}
/**
* 设置培训简介
*
* @param coursedesc 培训简介
*/
public void setCoursedesc(String coursedesc) {
this.coursedesc = coursedesc == null ? null : coursedesc.trim();
}
/**
* 获取培训大纲
*
* @return outline - 培训大纲
*/
public String getOutline() {
return outline;
}
/**
* 设置培训大纲
*
* @param outline 培训大纲
*/
public void setOutline(String outline) {
this.outline = outline == null ? null : outline.trim();
}
public String getDeptid() {
return deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public String getCheckor() {
return checkor;
}
public void setCheckor(String checkor) {
this.checkor = checkor;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Date getCheckdate() {
return checkdate;
}
public void setCheckdate(Date checkdate) {
this.checkdate = checkdate;
}
public Date getPublishdate() {
return publishdate;
}
public void setPublishdate(Date publishdate) {
this.publishdate = publishdate;
}
}
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2015 by the Free Software Foundation, Inc.
#
# This file is part of HyperKitty.
#
# HyperKitty is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# HyperKitty is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# HyperKitty. If not, see <http://www.gnu.org/licenses/>.
#
# Author: Aurelien Bompard <[email protected]>
#
from __future__ import absolute_import, unicode_literals
import datetime
import json
from django.shortcuts import redirect, render, get_object_or_404
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils import formats
from django.utils.dateformat import format as date_format
from django.http import Http404, HttpResponse
from hyperkitty.models import Favorite, MailingList, ThreadCategory
from hyperkitty.lib.view_helpers import (FLASH_MESSAGES, get_category_widget,
get_months, get_display_dates, daterange, check_mlist_private)
from hyperkitty.lib.paginator import paginate
if settings.USE_MOCKUPS:
from hyperkitty.lib.mockup import generate_top_author
@check_mlist_private
def archives(request, mlist_fqdn, year=None, month=None, day=None):
if year is None and month is None:
today = datetime.date.today()
return redirect(reverse(
'hk_archives_with_month', kwargs={
"mlist_fqdn": mlist_fqdn,
'year': today.year,
'month': today.month}))
try:
begin_date, end_date = get_display_dates(year, month, day)
except ValueError:
# Wrong date format, for example 9999/0/0
raise Http404("Wrong date format")
mlist = get_object_or_404(MailingList, name=mlist_fqdn)
threads = mlist.get_threads_between(begin_date, end_date)
if day is None:
list_title = date_format(begin_date, "F Y")
no_results_text = "for this month"
else:
#list_title = date_format(begin_date, settings.DATE_FORMAT)
list_title = formats.date_format(begin_date) # works with i18n
no_results_text = "for this day"
extra_context = {
'month': begin_date,
'month_num': begin_date.month,
"list_title": list_title.capitalize(),
"no_results_text": no_results_text,
}
if day is None:
extra_context["participants_count"] = \
mlist.get_participants_count_for_month(int(year), int(month))
return _thread_list(request, mlist, threads, extra_context=extra_context)
def _thread_list(request, mlist, threads, template_name='hyperkitty/thread_list.html', extra_context=None):
categories = [ (c.name, c.name.upper())
for c in ThreadCategory.objects.all() ] \
+ [("", "no category")]
threads = paginate(threads, request.GET.get('page'))
for thread in threads:
# Favorites
thread.favorite = False
if request.user.is_authenticated():
try:
Favorite.objects.get(thread=thread, user=request.user)
except Favorite.DoesNotExist:
pass
else:
thread.favorite = True
# Category
thread.category_hk, thread.category_form = \
get_category_widget(request, thread.category, categories)
flash_messages = []
flash_msg = request.GET.get("msg")
if flash_msg:
flash_msg = { "type": FLASH_MESSAGES[flash_msg][0],
"msg": FLASH_MESSAGES[flash_msg][1] }
flash_messages.append(flash_msg)
context = {
'mlist' : mlist,
'threads': threads,
'months_list': get_months(mlist),
'flash_messages': flash_messages,
}
if extra_context is not None:
context.update(extra_context)
return render(request, template_name, context)
@check_mlist_private
def overview(request, mlist_fqdn=None):
if not mlist_fqdn:
return redirect('/')
mlist = get_object_or_404(MailingList, name=mlist_fqdn)
threads = []
for thread_obj in mlist.recent_threads:
thread_obj.category_widget = get_category_widget(
None, thread_obj.category)[0]
threads.append(thread_obj)
# top threads are the one with the most answers
top_threads = sorted(threads, key=lambda t: t.emails_count, reverse=True)
# active threads are the ones that have the most recent posting
active_threads = sorted(threads, key=lambda t: t.date_active, reverse=True)
# top authors are the ones that have the most kudos. How do we determine
# that? Most likes for their post?
if settings.USE_MOCKUPS:
authors = generate_top_author()
authors = sorted(authors, key=lambda author: author.kudos)
authors.reverse()
else:
authors = []
# Popular threads
pop_threads = []
for t in threads:
votes = t.get_votes()
if votes["likes"] - votes["dislikes"] > 0:
pop_threads.append(t)
def _get_thread_vote_result(t):
votes = t.get_votes()
return votes["likes"] - votes["dislikes"]
pop_threads.sort(key=_get_thread_vote_result, reverse=True)
# Threads by category
threads_by_category = {}
for thread in active_threads:
if not thread.category:
continue
# don't use defaultdict, use .setdefault():
# http://stackoverflow.com/questions/4764110/django-template-cant-loop-defaultdict
if len(threads_by_category.setdefault(thread.category, [])) >= 5:
continue
threads_by_category[thread.category].append(thread)
# Personalized discussion groups: flagged/favorited threads and threads by user
if request.user.is_authenticated():
favorites = [ f.thread for f in Favorite.objects.filter(
thread__mailinglist=mlist, user=request.user) ]
mm_user_id = request.user.hyperkitty_profile.get_mailman_user_id()
threads_posted_to = mlist.threads.filter(
emails__sender__mailman_id=mm_user_id).distinct()
else:
favorites = []
threads_posted_to = []
# Empty messages # TODO: translate this
empty_messages = {
"flagged": 'You have not flagged any discussions (yet).',
"posted": 'You have not posted to this list (yet).',
"active": 'No discussions this month (yet).',
"popular": 'No vote has been cast this month (yet).',
}
context = {
'view_name': 'overview',
'mlist' : mlist,
'top_threads': top_threads[:20],
'most_active_threads': active_threads[:20],
'top_author': authors,
'pop_threads': pop_threads[:20],
'threads_by_category': threads_by_category,
'months_list': get_months(mlist),
'flagged_threads': favorites,
'threads_posted_to': threads_posted_to,
'empty_messages': empty_messages,
}
return render(request, "hyperkitty/overview.html", context)
@check_mlist_private
def recent_activity(request, mlist_fqdn):
"""Return the number of emails posted in the last 30 days"""
# pylint: disable=unused-argument
mlist = get_object_or_404(MailingList, name=mlist_fqdn)
begin_date, end_date = mlist.get_recent_dates()
days = daterange(begin_date, end_date)
# Use get_messages and not get_threads to count the emails, because
# recently active threads include messages from before the start date
emails_in_month = mlist.emails.filter(
date__gte=begin_date,
date__lt=end_date)
# graph
emails_per_date = {}
# populate with all days before adding data.
for day in days:
emails_per_date[day.strftime("%Y-%m-%d")] = 0
# now count the emails
for email in emails_in_month:
date_str = email.date.strftime("%Y-%m-%d")
if date_str not in emails_per_date:
continue # outside the range
emails_per_date[date_str] += 1
# return the proper format for the javascript chart function
evolution = [ {"date": d, "count": emails_per_date[d]}
for d in sorted(emails_per_date) ]
return HttpResponse(json.dumps({"evolution": evolution}),
content_type='application/javascript')
|
from typing import Dict, List, Tuple
import numpy as np
import random
import copy
import torch
import torchvision.transforms as T
from data import transforms
from tasks.refinement import T5LayoutSequence
from utils import utils
class T5CompletionLayoutSequence(T5LayoutSequence):
def parse_seq(self, _, output_str) -> Tuple[List[int], List[Tuple]]:
return super().parse_seq(output_str)
class T5CompletionDataset:
def __init__(self, cargs, tokenizer, seq_processor, sort_by_pos: bool = True,
shuffle_before_sort_by_label: bool = False,
sort_by_pos_before_sort_by_label: bool = False, *args, **kwargs) -> None:
self.tokenizer = tokenizer
self.seq_processor = seq_processor
self.index2label = seq_processor.index2label
self.sort_by_pos = sort_by_pos
transform_functions = [
transforms.LexicographicSort(),
transforms.DiscretizeBoundingBox(
num_x_grid=cargs.discrete_x_grid,
num_y_grid=cargs.discrete_y_grid)
]
self.transform = T.Compose(transform_functions)
self.shuffle_before_sort_by_label = shuffle_before_sort_by_label
self.sort_by_pos_before_sort_by_label = sort_by_pos_before_sort_by_label
print("Completion: ", transform_functions, "Sort by Pos: ", sort_by_pos,
", Shuffle: ", shuffle_before_sort_by_label,
", Sort by Pos before: ", sort_by_pos_before_sort_by_label)
super().__init__(*args, **kwargs)
def _sort_by_labels(self, labels, bboxes):
_labels = labels.tolist()
idx2label = [[idx, self.index2label[_labels[idx]]]
for idx in range(len(labels))]
idx2label_sorted = sorted(idx2label, key=lambda x: x[1])
idx_sorted = [d[0] for d in idx2label_sorted]
return labels[idx_sorted], bboxes[idx_sorted]
def _shuffle(self, labels, bboxes):
ele_num = len(labels)
shuffle_idx = np.arange(ele_num)
random.shuffle(shuffle_idx)
return labels[shuffle_idx], bboxes[shuffle_idx]
def process(self, data) -> Dict:
nd = self.transform(copy.deepcopy(data))
# build layout sequence
labels = nd['labels']
bboxes = nd['discrete_gold_bboxes']
gold_bboxes = nd['discrete_gold_bboxes']
in_labels = labels[:1]
in_bboxes = bboxes[:1, :]
in_str = self.seq_processor.build_seq(in_labels, in_bboxes).lower().strip()
if self.sort_by_pos:
sorted_labels, sorted_bbox = labels, gold_bboxes
else:
if self.shuffle_before_sort_by_label:
sorted_labels, sorted_bbox = self._shuffle(labels, gold_bboxes)
sorted_labels, sorted_bbox = self._sort_by_labels(sorted_labels, sorted_bbox)
else:
sorted_labels, sorted_bbox = self._sort_by_labels(labels, gold_bboxes)
out_str = self.seq_processor.build_seq(sorted_labels, sorted_bbox).lower().strip()
return {
'in_str': in_str,
'out_str': out_str,
'input_labels': in_labels,
'input_bboxes': in_bboxes,
'out_labels': sorted_labels,
'out_bboxes': sorted_bbox,
'gold_labels': sorted_labels,
'gold_bboxes': sorted_bbox,
'name': data['name']
}
def completion_inference(model, data, seq_processor, tokenizer, device, top_k=10, temperature=0.7) -> Tuple[Dict, Dict]:
gold_labels, mask = utils.to_dense_batch(data['gold_labels'])
gold_bbox, _ = utils.to_dense_batch(data['gold_bboxes'])
_input_labels, _input_mask = utils.to_dense_batch(data['input_labels'])
_input_bbox, _ = utils.to_dense_batch(data['input_bboxes'])
mask = mask.to(device).detach()
_input_mask = _input_mask.to(device).detach()
in_tokenization = tokenizer(data['in_str'], add_eos=True, add_bos=False)
in_ids = in_tokenization['input_ids'].to(device)
in_mask = in_tokenization['mask'].to(device)
in_padding_mask = ~in_mask
task_ids = None
if 'task_id' in data:
task_ids = torch.tensor(data['task_id']).long().to(device)
decode_max_length = 120
output_sequences = model(in_ids, in_padding_mask, max_length=decode_max_length, do_sample=True, top_k=top_k,
temperature=temperature, task_ids=task_ids)['output']
out_str = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
in_str = data['in_str']
pred_bbox, pred_labels = list(), list()
input_labels, input_bbox, input_mask = list(), list(), list()
for idx, ostr in enumerate(out_str):
out_str[idx] = ostr.strip()
# combine input elements and output elements
_pred_labels, _pred_bbox = seq_processor.parse_seq(in_str[idx], out_str[idx])
if _pred_labels is None:
# something wrong in the model's predictions
continue
_pred_labels = torch.tensor(_pred_labels).long()
_pred_bbox = torch.tensor(_pred_bbox).long()
pred_labels.append(_pred_labels)
pred_bbox.append(_pred_bbox)
input_labels.append(_input_labels[idx])
input_bbox.append(_input_bbox[idx])
input_mask.append(_input_mask[idx])
input_labels = torch.stack(input_labels, dim=0).to(device).detach()
input_bbox = torch.stack(input_bbox, dim=0).to(device).detach()
input_mask = torch.stack(input_mask, dim=0).to(device).detach()
# Compute Metrics
# label
pred_labels, pred_mask = utils.to_dense_batch(pred_labels)
pred_labels = pred_labels.to(device)
# bbox
pred_bbox, _ = utils.to_dense_batch(pred_bbox)
metric = {
'num_bbox_correct': 0, # num_bbox_correct,
'num_bbox': mask.unsqueeze(dim=-1).repeat(1, 1, 4).sum(), # num_bbox,
'num_label_correct': 0, # num_label_correct,
'num_examples': mask.size(0),
}
out = {
'pred_labels': pred_labels,
'pred_bboxes': pred_bbox,
'gold_labels': gold_labels,
'gold_bboxes': gold_bbox,
'input_labels': input_labels.to(device).detach(),
'input_bboxes': input_bbox.to(device).detach(),
'gold_mask': mask,
'pred_mask': pred_mask,
'input_mask': input_mask,
'pred_str': out_str,
'input_str': data['in_str'],
'gold_str': data['out_str']
}
return metric, out
|
/*
* 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 controller;
import dao.UserDAO;
import dto.UserDTO;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author HAO
*/
public class LoginController extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
private static final String EVENT_DEP_PAGE = "SearchEventController";
private static final String ADMIN_PAGE = "AdminController";
private static final String ERROR = "login.jsp";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String url = ERROR;
try {
String userID = request.getParameter("txtEmail");
String password = request.getParameter("txtPassword");
UserDAO dao = new UserDAO();
UserDTO us = dao.checkLogin(userID, password);
HttpSession ses = request.getSession();
if (us != null) {
if (us.getRoleID() == 2) { // if role is event_dep
url = EVENT_DEP_PAGE;
} else if (us.getRoleID() == 3) {
url = ADMIN_PAGE;
}
ses.setAttribute("USER", us);
} else {
ses.setAttribute("mess", "Email or Password incorrect !!");
}
} catch (NoSuchAlgorithmException | SQLException | NamingException e) {
Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, e);
} finally {
response.sendRedirect(url);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
import Koa, { Context, Middleware } from 'koa'
import Router from '@koa/router'
import koaLogger from 'koa-pino-logger'
import pino, { LevelWithSilent, Level } from 'pino'
import cors from '@koa/cors'
import etag from 'koa-etag'
import responseTime from 'koa-response-time'
import session from 'koa-generic-session'
import jwt from 'koa-jwt'
import jwksRsa from 'jwks-rsa'
import bodyParser from 'koa-bodyparser'
import { addGracefulShutdownHook, getHealthContextHandler, shutdown } from '@neurocode.io/k8s-graceful-shutdown'
import logger from './logger/index.ts'
import { IncomingMessage, Server, ServerResponse } from 'http'
const loggerInstance = logger.child({ context: null })
const app = new Koa()
app.keys = process.env.APP_KEYS ? process.env.APP_KEYS.split(',') : ['asfsdfs87f6sd8f6sd8f67sdf876', 'sadf86sd8f6s8df6s8d76s87d6fg']
app.use(responseTime())
.use(etag())
.use(session({
key: 'o:sess',
}))
.use(cors())
export const router: Router = new Router()
export const get = router.get.bind(router)
export const put = router.put.bind(router)
export const post = router.post.bind(router)
export const patch = router.patch.bind(router)
export const del = router.delete.bind(router)
const exposedRouter: Router = new Router()
export const exposed = {
get: exposedRouter.get.bind(exposedRouter),
put: exposedRouter.put.bind(exposedRouter),
post: exposedRouter.post.bind(exposedRouter),
patch: exposedRouter.patch.bind(exposedRouter),
del: exposedRouter.delete.bind(exposedRouter),
}
const healthy = (ctx: Context) => {
ctx.status = 200
ctx.body = 'ok'
}
const notHealthy = (ctx: Context) => {
ctx.body = 'nope'
ctx.status = 503
}
const healthCheck = getHealthContextHandler({ healthy, notHealthy })
exposed.get('/health', healthCheck)
const healthcheckLogLevel: Level = process.env.HEALTHCHECK_LOG_LEVEL as Level || 'debug'
const getDefaultLogLevel: () => Level = () => process.env.PINO_LEVEL as Level || process.env.LOG_LEVEL || 'info'
let defaultLogLevel = getDefaultLogLevel()
const setDebug = () => { defaultLogLevel = 'debug' }
const setDefault = () => { defaultLogLevel = getDefaultLogLevel() }
process.on('SIGUSR1', setDebug)
process.on('SIGUSR2', setDefault)
const chindingsSymbol = pino.symbols.chindingsSym
const customLogLevel = (res: ServerResponse<IncomingMessage>) => {
// @ts-ignore
if (res.log[chindingsSymbol].split(',"url":"')[1].replace(/\".+/, '') === '/health') {
return healthcheckLogLevel
}
return defaultLogLevel as LevelWithSilent
}
const usedLogger = koaLogger({ logger, customLogLevel })
app.use(usedLogger)
const jwksHost = process.env.AUTH_JWKS_HOST || `https://ids.${process.env.DOMAIN}`
const audience = process.env.AUTH_AUDIENCE || `https://api.${process.env.DOMAIN}`
const issuer = process.env.AUTH_ISSUER_HOST || process.env.AUTH_JWKS_HOST || `https://ids.${process.env.DOMAIN}/`
loggerInstance.debug(`Using jwksHost: ${jwksHost}`)
loggerInstance.debug(`Using audience: ${audience}`)
loggerInstance.debug(`Using issuer: ${issuer}`)
const jwtMiddleware = jwt({
secret: jwksRsa.koaJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `${jwksHost}/.well-known/jwks.json`
}),
audience,
issuer,
algorithms: ['RS256']
})
let server: Server
const closeServers = () => {
return new Promise(resolve => {
server.close(resolve)
})
}
const gracePeriodSec = 2 * 1000
let close: Function
export const stop = async () => {
process.off('SIGUSR1', setDebug)
process.off('SIGUSR2', setDefault)
logger.info(`Stopping HTTP server`)
await close()
}
interface StartOptions {
afterAuthMiddlewares?: Array<Middleware>
}
export const start = async (port = process.env.PORT || 3000, { afterAuthMiddlewares = [] }: StartOptions) => {
app
.use(exposedRouter.routes())
.use(exposedRouter.allowedMethods())
if (process.env.BYPASS_AUTH !== 'true') {
app.use(jwtMiddleware)
afterAuthMiddlewares.forEach(middleware => app.use(middleware))
}
app
.use(router.routes())
.use(router.allowedMethods())
server = app.listen(port)
server.addListener('close', () => logger.debug('HTTP server has shut down'))
logger.info(`Started HTTP server on port ${port}`)
close = shutdown(server)
addGracefulShutdownHook(gracePeriodSec, closeServers)
return stop
}
const body = () => bodyParser()
export { loggerInstance as logger, body }
export default app
|
Chapter 2: The Soul of Italy - Naples
Introduction to Campania
Campania, with its vibrant streets and bustling markets, is the soul of Italy's pasta tradition. The region is home to Naples, the birthplace of many iconic Italian dishes, including pizza and spaghetti alla puttanesca. Campania's culinary scene is characterized by its use of fresh seafood, ripe tomatoes, and aromatic herbs, all of which play a central role in its pasta dishes.
History of Pasta in Campania
Pasta has been a staple in Campania for centuries, with records dating back to the 12th century when the region was a hub for pasta production and trade. The introduction of tomatoes from the New World in the 16th century transformed the culinary landscape of Naples, leading to the creation of now-iconic dishes such as spaghetti al pomodoro.
Regional Pasta Specialties
1. Spaghetti alla Puttanesca: A bold, flavorful dish made with tomatoes, olives, capers, and anchovies.
2. Linguine al Frutti di Mare: Pasta served with a mix of seafood, embodying the region's coastal flavors.
3. Gnocchi alla Sorrentina: Potato gnocchi baked with tomato sauce and mozzarella, a comforting dish that showcases Campania's dairy products.
Recipes
Spaghetti alla Puttanesca Recipe
Ingredients:
- 400g spaghetti
- 2 tablespoons olive oil
- 2 garlic cloves, minced
- 1 teaspoon red pepper flakes
- 1 can (400g) diced tomatoes
- 1/4 cup olives, pitted and chopped
- 2 tablespoons capers, rinsed
- 6 anchovy fillets, chopped
- Salt to taste
- Fresh parsley, chopped, for garnish
Instructions:
1. Heat the olive oil in a large pan over medium heat. Add the garlic and red pepper flakes, and sauté for 1 minute.
2. Add the tomatoes, olives, capers, and anchovies. Season with salt. Bring to a simmer and cook for 10 minutes.
3. Cook the spaghetti according to the package instructions. Drain and add to the sauce.
4. Serve hot, garnished with fresh parsley.
Linguine al Frutti di Mare Recipe
Ingredients:
- 400g linguine
- 2 tablespoons olive oil
- 2 garlic cloves, minced
- 1/2 cup white wine
- 1 cup tomato sauce
- 1/2 cup mixed seafood (clams, mussels, shrimp)
- Salt and pepper to taste
- Fresh parsley, chopped, for garnish
Instructions:
1. Heat the olive oil in a large pan over medium heat. Add the garlic and sauté until fragrant.
2. Add the white wine and tomato sauce. Bring to a simmer.
3. Add the seafood and cook until the shellfish open and the shrimp is pink. Season with salt and pepper.
4. Cook the linguine according to the package instructions. Drain and add to the sauce.
5. Serve hot, garnished with fresh parsley.
This chapter delves into the vibrant and bustling streets of Naples, focusing on dried pasta and the unique pasta making traditions of the region. It includes recipes and insights into the Neapolitan way of life, providing a rich narrative that blends culinary history with practical cooking advice.
|
package com.demo.service;
import com.demo.model.Bill;
import com.demo.model.Book;
import com.demo.repository.IBillRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@Service
public class BillService implements IBillService{
@Autowired
private IBillRepository billRepository;
@Override
public List<Bill> showAllBill() {
return billRepository.findAll();
}
@Override
@Transactional
public String createBill(Book book) {
System.out.println(1 / book.getQuality());
String hireCode = getHireCode();
Bill bill = new Bill(hireCode, book);
billRepository.save(bill);
return hireCode;
}
@Override
public void deleteBillByCode(String code) {
billRepository.deleteById(code);
}
@Override
public Bill findByCode(String code) {
return billRepository.findById(code).get();
}
@Override
public List<String> getAllHireCode() {
List<Bill> list = showAllBill();
List<String> hireCodeList = new ArrayList<>();
for (Bill bill : list){
hireCodeList.add(bill.getHireCode());
}
return hireCodeList;
}
@Override
public String getHireCode() {
String i;
while (true) {
i = new Random().nextInt(100000) + "";
for (int k = 0; k < 4 - i.length(); k++){
i = "0" + i;
}
if (!getAllHireCode().contains(i)){
break;
}
}
return i;
}
}
|
import dotenv from "dotenv";
import express, { Express, Request, Response } from "express";
import cors from "cors";
import connectToMongoDB from "./models";
import User from "./models/User";
import Post from "./models/Post";
import Resume from "./models/Resume"
import Portfolio from "./models/Portfolio"
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { UserProfileType, UserTokenDataType, UserType } from "./Types/UserType";
import cookieParser from "cookie-parser";
import imageDownloader from "image-downloader";
import multer from 'multer'
import fs from 'fs'
import pathLB from "path"
import { Error } from "mongoose";
import { ResumeType } from "./Types/ResumeType";
import { PortfolioType } from "./Types/PortfolioType";
import axios, { AxiosResponse } from "axios"
dotenv.config();
const app: Express = express();
const port = 4000 || process.env.PORT;
const bcryptSalt = bcrypt.genSaltSync(10);
const jwtSecret = 'fasefraw4r5r3wq45wdfgw34twdfg';
app.use(express.json());
app.use(cookieParser());
app.use('/uploads/',express.static(__dirname+'/uploads'))
app.use(cors({credentials:true,origin:['https://build-your-portfolio.netlify.app','http://localhost:5173']}));
// 몽고DB 연결
connectToMongoDB();
app.get('/',async (req:Request,res:Response) => {
res.json('백엔드 서버 테스트')
})
// 회원가입
app.post('/register', async (req:Request,res:Response) => {
const {nickName,name,email,password} = req.body;
// validation
const dbEmail=await User.findOne({email:email})
const dbNickName = await User.findOne({ nickName: nickName });
if (dbNickName?.nickName === nickName) {
return res.status(409).json('이미 존재하는 닉네임입니다.');
}
if(dbEmail?.email===email){
return res.status(409).json('이미 존재하는 이메일 입니다.');
}
try{
const userDoc = await User.create({
nickName,
name,
email,
password:bcrypt.hashSync(password, bcryptSalt),
});
res.status(200).json({userDoc});
}catch(e){
res.status(422)
}
}
);
// 로그인
app.post('/login', async (req:Request,res:Response) => {
const {email,password} = req.body;
const userDoc = await User.findOne({email}) as UserType;
if (userDoc) {
try{
const passOk = bcrypt.compareSync(password, userDoc.password);
if (passOk) {
jwt.sign({
email:userDoc.email,
id:userDoc._id
}, jwtSecret, {}, (err,token) => {
if (err) throw err;
res.cookie('token', token,{ sameSite: 'none', secure: true }).status(200).json(userDoc);
});
} else {
res.status(400).json('비밀번호가 일치하지 않습니다');
}
}catch(err){
res.status(500).json({errMsg:'password 정보가 없습니다.', errinfo:'혹시 구글이나 깃허브 회원가입하셨다면 구글,깃허브 로그인을 이용해주시면 감사하겠습니다'})
}
} else {
res.status(404).json('해당 이메일의 유저를 찾을 수 없습니다');
}
});
// 깃허브 로그인
app.get('/github/login',async (req:Request,res:Response)=> {
// 1. 깃허브에 accessToken얻기
const baseUrl = "https://github.com/login/oauth/access_token";
const body = {
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code: req.query.code,
};
try{
const { data: requestToken } = await axios.post(baseUrl, body, {
headers: { Accept: "application/json" },
});
console.log(requestToken)
// 2. 깃허브에 있는 user정보 가져오기
const { access_token } = requestToken; // ③ ~ ④에 해당
const apiUrl = "https://api.github.com";
const { data: userdata } = await axios.get(`${apiUrl}/user`, {
headers: { Authorization: `token ${access_token}` },
})
console.log(userdata)
const { data: emailDataArr } = await axios.get(`${apiUrl}/user/emails`, {
headers: { Authorization: `token ${access_token}` },
});
const { login: nickname,name } = userdata;
const { email } = emailDataArr.find(
(emailObj:EmailObjType) => emailObj.primary === true && emailObj.verified === true,
)
// 3. 이메일과 일치하는 유저를 DB 찾음
const dbEmailUser = await User.findOne({email:email})
// 4. 이메일과 일치하는 유저인지에 따라 회원가입 또는 로그인
try{
if(dbEmailUser && dbEmailUser?.email===email){
// 이미 존재하는 이메일이면 바로 로그인시키기
jwt.sign({
email:dbEmailUser.email,
id:dbEmailUser._id
}, jwtSecret, {}, (err,token) => {
if (err) throw err;
console.log('db로찾은 db유저',dbEmailUser)
return res.cookie('token', token,{ sameSite: 'none', secure: true }).status(200).json(dbEmailUser);
});
}else{
// 존재하지 않는 이메일이면 회원가입 후 로그인시키기
const userDoc = await User.create({
nickName:nickname,
name:name,
email:email,
})
console.log('회원가입할 때 userDoc',userDoc)
jwt.sign({
email:userDoc.email,
id:userDoc._id
}, jwtSecret, {}, (err,token) => {
if (err) throw err;
return res.cookie('token', token,{ sameSite: 'none', secure: true }).status(200).json(userDoc);
});
}
}catch(e){
res.status(422)
}
}catch(err){
console.error(err);
return res.redirect(
500,
"/?loginError=서버 에러로 인해 로그인에 실패하였습니다. 잠시 후에 다시 시도해 주세요",
);
}
}
)
// 구글 로그인
app.get("/google/login",async (req: Request, res: Response) => {
const { code } = req.query;
// 토큰을 요청하기 위한 구글 인증 서버 url
const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';
// access_token, refresh_token 등의 구글 토큰 정보 가져오기
const tokenData = await axios.post(GOOGLE_TOKEN_URL, {
// x-www-form-urlencoded(body)
code,
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
redirect_uri: process.env.GOOGLE_REDIRECT_URI,
grant_type: 'authorization_code',
});
// email, google id 등을 가져오기 위한 url
const GOOGLE_USERINFO_URL = 'https://www.googleapis.com/oauth2/v2/userinfo';
// email, google id 등의 사용자 구글 계정 정보 가져오기
const googleUserData= await axios.get(GOOGLE_USERINFO_URL, {
// Request Header에 Authorization 추가
headers: {
Authorization: `Bearer ${tokenData.data.access_token}`,
},
});
// userData로 email db확인
const dbEmailUser = await User.findOne({email:googleUserData.data.email})
try{
// 해당 email이 db에 있으면 토큰발급 후 로그인
if(dbEmailUser && dbEmailUser?.email===googleUserData.data.email){
jwt.sign({
email:dbEmailUser.email,
id:dbEmailUser._id
}, jwtSecret, {}, (err,token) => {
if (err) throw err;
return res.cookie('token', token,{ sameSite: 'none', secure: true }).status(200).json(dbEmailUser);
});
}else{
// 해당 email이 db에 없으면 회원가입시키고 토큰발급
const userDoc = await User.create({
name:googleUserData.data.name,
email:googleUserData.data.email,
})
jwt.sign({
email:userDoc.email,
id:userDoc._id
}, jwtSecret, {}, (err,token) => {
if (err) throw err;
return res.cookie('token', token,{ sameSite: 'none', secure: true }).status(200).json(userDoc);
});
}
}catch(err){
res.status(422).json(err)
}
});
// 로그아웃
app.post('/logout',(req:Request,res:Response)=>{
res.cookie('token','',{ sameSite: 'none', secure: true }).json(true);
})
// 로그인 유지 및 유저정보
app.get('/profile', (req:Request,res:Response) => {
const {token} = req.cookies;
if (token) {
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
const userData = userDataCallback as UserTokenDataType
if (err) throw err;
const userDoc = await User.findById(userData.id) as UserProfileType;
const userResumeDoc = await Resume.findOne({author:userData.id}) as ResumeType | null
const userPortfolioDoc = await Portfolio.find({author:userData.id}) as PortfolioType[] | null
try{
const resultUser:UserProfileType = {
selectedUserUI:userDoc.selectedUserUI,
nickName:userDoc.nickName,
email:userDoc.email,
name:userDoc.name,
_id:userDoc._id,
profileImg:userDoc.profileImg,
userResumeDoc:userResumeDoc,
userPortfolio:userPortfolioDoc,
}
res.status(200).json(resultUser);
}catch(e){
res.status(500).json("유저 정보 요청 실패")
}
});
} else {
res.json(null);
}
});
// id값으로 유저정보 찾기
app.get('/user/:id', async (req:Request,res:Response) => {
const {id:userId} = req.params;
try{
const userDoc = await User.findById(userId) as UserProfileType;
if(!userDoc){
return res.status(404).json('사용자를 찾을 수 없습니다')
}
const userResumeDoc = await Resume.findOne({author:userId}) as ResumeType | null
const userPortfolioDoc = await Portfolio.find({author:userId}) as PortfolioType[] | null
const resultUser:UserProfileType = {
selectedUserUI:userDoc.selectedUserUI,
nickName:userDoc.nickName,
email:userDoc.email,
name:userDoc.name,
_id:userDoc._id,
profileImg:userDoc.profileImg,
userResumeDoc:userResumeDoc,
userPortfolio:userPortfolioDoc,
}
res.json({resultUser});
}catch(err){
res.status(500).json('서버 오류 발생')
}
})
// 프로필 이미지 수정
app.put('/profile-image', async (req: Request, res: Response) => {
const { token } = req.cookies;
const { profileImg } = req.body;
if (token) {
try {
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
const userData = userDataCallback as UserTokenDataType
if (err) throw err;
const userDoc = await User.findById(userData.id)
if (userDoc) {
userDoc.profileImg = profileImg
await userDoc.save();
res.status(200).json({ message: '프로필이 성공적으로 업데이트되었습니다.' });
} else {
res.json({ message: '사용자를 찾을 수 없습니다.' });
}
})
} catch (err) {
res.status(500).json({ message: '서버 오류입니다.' });
}
} else {
res.status(401).json({ message: '인증되지 않은 요청입니다.' });
}
});
// user-UI 선택 api
app.put('/user-ui', async (req: Request, res: Response) => {
const { token } = req.cookies;
const { selectedUserUI } = req.body;
console.log(selectedUserUI)
if (token) {
try {
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
const userData = userDataCallback as UserTokenDataType
if (err) throw err;
const userDoc = await User.findById(userData.id)
if (userDoc) {
userDoc.selectedUserUI = selectedUserUI
await userDoc.save();
res.status(200).json(userDoc);
} else {
res.json({ message: '사용자를 찾을 수 없습니다.' });
}
})
} catch (err) {
res.status(500).json({ message: '서버 오류입니다.' });
}
} else {
res.status(401).json({ message: '인증되지 않은 요청입니다.' });
}
})
// input string(이미지주소)으로 이미지업로드
app.post('/upload-by-link', async (req: Request, res: Response) => {
const { link }: { link: string } = req.body;
const newName = 'photo' + Date.now() + '.jpg';
const uploadPath = pathLB.join(__dirname, 'uploads', newName); // 경로 수정
try{
await imageDownloader.image({
url: link,
dest: uploadPath,
});
res.json(newName);
}catch(err){
res.json('url을 입력해주세요')
}
});
// input file로 파일업로드
const photosMiddleware = multer({ dest: pathLB.join(__dirname, 'uploads') }); // 경로 수정
app.post('/upload', photosMiddleware.array('photos', 100), (req: Request, res: Response) => {
const uploadFiles: string[] = [];
if (Array.isArray(req.files)) {
for (let i = 0; i < req.files.length; i++) {
const { path, originalname } = req.files[i];
const parts = originalname.split('.');
const ext = parts[parts.length - 1];
const newName = 'photo' + Date.now() + '.' + ext;
const uploadPath = pathLB.join(__dirname, 'uploads', newName); // 경로 수정
fs.renameSync(path, uploadPath);
uploadFiles.push(newName);
}
}
res.json(uploadFiles);
});
// 이력서 등록
app.post('/resume/create',(req:Request,res:Response)=>{
const {token} = req.cookies;
const {birth,finalEducation,phone,myselfSentence,reasonForCoding,coverLetter,certification,channel,technology,career,activity,
} = req.body;
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
const userData = userDataCallback as UserTokenDataType
if (err) throw err;
const resumeDoc = await Resume.create({
author:userData.id,
birth,finalEducation,phone,myselfSentence,reasonForCoding,coverLetter,certification,channel,technology,career,activity,
})
res.json({resumeDoc})
});
})
// 이력서 수정
app.put('/resume/update',async (req,res)=>{
const {token} = req.cookies;
const {resumeId,nickName,name,birth,finalEducation,phone,myselfSentence,reasonForCoding,coverLetter,certification,channel,technology,career,activity,
} = req.body;
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
const userData = userDataCallback as UserTokenDataType
if(err) throw err;
const resumeDoc = await Resume.findById(resumeId)
const userDoc = await User.findById(userData.id)
if(resumeDoc && userDoc){
if(resumeDoc.author){
if(userData.id === resumeDoc.author.toString()){
resumeDoc.set({
birth,finalEducation,phone,myselfSentence,reasonForCoding,coverLetter,certification,channel,technology,career,activity,
})
userDoc.name = name;
userDoc.nickName = nickName;
await userDoc.save();
await resumeDoc.save();
res.json({resumeDoc,userDoc})
}
}
}
});
})
// 이력서 id값으로 가져오기
app.get('/resume/:id',async (req,res)=>{
const {id} = req.params;
res.json(await Resume.findById(id))
})
// 포트폴리오 등록
app.post('/portfolio/create',(req:Request,res:Response)=>{
const {token} = req.cookies;
const {title,purpose,introduce, process,learned,photos, usedTechnology,developPeriod,demoLink,category,selectedUI,important_functions
} = req.body;
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
const userData = userDataCallback as UserTokenDataType
if (err) throw err;
const portfolioDoc = await Portfolio.create({
author:userData.id,
title,purpose,introduce, process,learned,photos, usedTechnology,developPeriod,demoLink,category,selectedUI,important_functions
})
res.status(200).json({portfolioDoc})
});
})
// 포트폴리오 수정
app.put('/portfolio/update',async (req,res)=>{
const {token} = req.cookies;
const {portfolioId,title,purpose,introduce, process,learned,photos, usedTechnology,developPeriod,demoLink,category,selectedUI,important_functions
} = req.body;
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
const userData = userDataCallback as UserTokenDataType
if(err) throw err;
const portfolioDoc = await Portfolio.findById(portfolioId)
if(portfolioDoc){
if(portfolioDoc.author){
if(userData.id === portfolioDoc.author.toString()){
portfolioDoc.set({
title,purpose,introduce, process,learned,photos, usedTechnology,developPeriod,demoLink,category,selectedUI,important_functions
})
await portfolioDoc.save();
console.log(portfolioDoc)
res.json({portfolioDoc})
}
}
}
});
})
// 포트폴리오 삭제
app.delete('/portfolio/delete/:id',async (req:Request,res:Response)=>{
const {id:portfolioId} = req.params;
const {token} = req.cookies;
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
const userData = userDataCallback as UserTokenDataType
if(err) throw err;
const portfolioDoc = await Portfolio.findById(portfolioId)
if(portfolioDoc){
if(portfolioDoc.author){
if(userData.id === portfolioDoc.author.toString()){
const resultPortfolio = await Portfolio.findOneAndDelete({_id:portfolioId})
res.status(200).json('포트폴리오 삭제')
}else{
return res.status(404).json("포트폴리오의 author가 일치하지 않습니다")
}
}
}
});
})
// id값으로 포트폴리오 찾기
app.get('/portfolio/:id', async (req:Request,res:Response) => {
const {id:portfolioId} = req.params;
try{
const PortfolioDoc = await Portfolio.findById(portfolioId) as PortfolioType | null
if(PortfolioDoc){
const userDoc = await User.findById(PortfolioDoc?.author) as UserType;
if(userDoc){
const portfolio_detail = {
PortfolioDoc,
author_name: userDoc.name,
}
res.json({portfolio_detail});
}
}
}catch(err){
res.status(404).json('포트폴리오를 찾을 수 없습니다')
}
})
// 로그인 유저가 등록한 post 찾기
app.get('/user-posts', (req,res) => {
const {token} = req.cookies;
jwt.verify(token, jwtSecret, {}, async (err, userDataCallback) => {
if(err) throw err;
const userData = userDataCallback as UserTokenDataType
const {id} = userData;
const userPostList = await Post.find({author:id})
res.json(userPostList);
});
});
// id값으로 post 찾기
app.get('/post/:id',async (req,res)=>{
const {id} = req.params;
res.json(await Post.findById(id))
})
// 메인페이지 post 전체 찾기
app.get('/posts',async (req,res)=>{
res.json(await Post.find())
})
// 검색기능 - name과 nickName으로 user찾기
app.get("/search", async (req: Request, res: Response) => {
const { search } = req.query;
try {
const users = await User.find({
$or: [
{ name: search as string },
{ nickName: search as string }
]
});
res.json(users);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.listen(port)
|
#if UNITY_2021_2_OR_NEWER
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using LiteNetLib.Utils;
using UnityEditor;
using UnityEngine;
namespace LiteEntitySystem.Extensions
{
[Serializable]
public struct ResourceInfo : INetSerializable
{
public string FieldName;
public string Path;
public void Serialize(NetDataWriter writer)
{
writer.Put(FieldName);
writer.Put(Path);
}
public void Deserialize(NetDataReader reader)
{
FieldName = reader.GetString();
Path = reader.GetString();
}
}
public class SharedScriptableObject : ScriptableObject, INetSerializable
#if UNITY_EDITOR
, ISerializationCallbackReceiver
#endif
{
[SerializeField, HideInInspector] private ResourceInfo[] _resourcePaths;
[SerializeField, HideInInspector] private int _resourcesHash;
[SerializeField, HideInInspector] private string _serializedName;
public string ResourceName => _serializedName;
private Type _type;
#if UNITY_EDITOR
private FieldInfo[] _fields;
private static readonly Type ResourceType = typeof(UnityEngine.Object);
private static readonly ThreadLocal<List<ResourceInfo>> ResourceInfoCache = new(() => new List<ResourceInfo>());
private const string ResourcesPath = "Assets/Resources/";
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
int newHash = 0;
var resourceInfoCache = ResourceInfoCache.Value;
resourceInfoCache.Clear();
_type ??= GetType();
_fields ??= _type.GetFields(BindingFlags.Instance | BindingFlags.Public);
foreach(var field in _fields)
{
if(!field.FieldType.IsSubclassOf(ResourceType))
continue;
var fieldValue = field.GetValue(this);
if(fieldValue == null)
continue;
string assetPath = AssetDatabase.GetAssetPath((UnityEngine.Object)fieldValue);
if(string.IsNullOrEmpty(assetPath))
continue;
if (!assetPath.StartsWith(ResourcesPath))
{
Debug.LogWarning($"Resource in {_type.Name} ({field.Name}) is not in Resources path: \"{assetPath}\"");
continue;
}
int lastPointPosition = assetPath.LastIndexOf(".", StringComparison.InvariantCulture);
assetPath = lastPointPosition != -1
? assetPath.Substring(ResourcesPath.Length, lastPointPosition - ResourcesPath.Length)
: assetPath.Substring(ResourcesPath.Length);
resourceInfoCache.Add(new ResourceInfo { FieldName = field.Name, Path = assetPath });
newHash ^= assetPath.GetHashCode();
}
newHash ^= name.GetHashCode();
if (newHash != _resourcesHash)
{
_serializedName = name;
_resourcesHash = newHash;
_resourcePaths = resourceInfoCache.ToArray();
EditorUtility.SetDirty(this);
}
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
}
#endif
internal void LoadResources()
{
if (_resourcePaths == null || _resourcePaths.Length == 0)
return;
_type ??= GetType();
foreach (var resourceInfo in _resourcePaths)
{
var field = _type.GetField(resourceInfo.FieldName);
field.SetValue(this, Resources.Load(resourceInfo.Path, field.FieldType));
}
}
//INetSerializable
public virtual void Serialize(NetDataWriter writer)
{
if (_resourcePaths == null || _resourcePaths.Length == 0)
return;
writer.Put((ushort)_resourcePaths.Length);
for (int i = 0; i < _resourcePaths.Length; i++)
_resourcePaths[i].Serialize(writer);
writer.Put(_serializedName);
}
public virtual void Deserialize(NetDataReader reader)
{
ushort resourcesCount = reader.GetUShort();
_resourcePaths = new ResourceInfo[resourcesCount];
for (int i = 0; i < resourcesCount; i++)
_resourcePaths[i].Deserialize(reader);
_serializedName = reader.GetString();
LoadResources();
}
}
}
#endif
|
package app.logorrr.docs
import app.logorrr.{LogoRRRAppLauncher, OsxBridge}
import app.logorrr.conf._
import app.logorrr.docs.Area._
import app.logorrr.io.Fs
import app.logorrr.meta.AppMeta
import app.logorrr.util.CanLog
import app.logorrr.views.main.LogoRRRStage
import javafx.embed.swing.SwingFXUtils
import javafx.scene.Node
import javafx.stage.Stage
import pureconfig.ConfigSource
import java.nio.file.{Path, Paths}
import javax.imageio.ImageIO
import scala.util.{Failure, Success, Try}
/**
* Simple application to take screenshots from a JavaFX app for documentation purposes
*/
object ScreenShotterApp {
def persistNodeState(node: Node, target: Path): Boolean = {
val renderedNode = node.snapshot(null, null)
ImageIO.write(SwingFXUtils.fromFXImage(renderedNode, null), "png", target.toFile)
}
def main(args: Array[String]): Unit = {
LogoRRRAppLauncher.loadNativeLibraries()
javafx.application.Application.launch(classOf[ScreenShotterApp], args: _*)
}
}
class ScreenShotterApp extends javafx.application.Application with CanLog {
def fromFile(settingsFilePath: Path): Settings = {
Try(ConfigSource.file(settingsFilePath).loadOrThrow[Settings].filterWithValidPaths()) match {
case Failure(_) =>
logWarn(s"Could not load $settingsFilePath, using default settings ...")
Settings.Default
case Success(value) =>
logInfo(s"Loaded settings from $settingsFilePath.")
value
}
}
def start(stage: Stage): Unit = {
val s0 = Seq[Area](R1280x800)
val s1 = Seq[Area](R1440x900)
val s2 = Seq[Area](R2560x1600)
val s3 = Seq[Area](R2880x1800)
for (Area(w, h, width, height) <- s3) {
val path = Paths.get(s"docs/src/main/resources/screenshotter-$w-$h.conf")
val settings: Settings =
fromFile(path)
val updatedSettings = settings.copy(stageSettings = settings.stageSettings.copy(width = width, height = height))
OsxBridge.registerPath(updatedSettings.logFileSettings.values.head.pathAsString)
LogoRRRGlobals.set(updatedSettings, getHostServices)
LogoRRRStage(stage).show()
/*
val bPath = Paths.get(s"docs/releases/${AppMeta.appVersion}/")
Fs.createDirectories(bPath)
val f = bPath.resolve(s"${width}x$height.png")
Future {
Thread.sleep(5000)
JfxUtils.execOnUiThread({
ScreenShotterApp.persistNodeState(stage.getScene.getRoot, f)
logInfo(s"created ${f.toAbsolutePath.toString}")
})
}
*/
}
}
}
|
import { readInput } from "../util";
type Set = {
red: number;
green: number;
blue: number;
};
export type Game = {
gameId: number;
sets: Set[];
};
export const parseFile = (filepath: string): Game[] => {
const gameIdRegex = /Game (?<gameId>\d+): (?<sets>.*)/;
return readInput(filepath)
.split("\n")
.map((l): Game => {
const matches = l.match(gameIdRegex);
const gameId = Number(matches.groups["gameId"]);
const sets = matches.groups["sets"]
.split(";")
.map((s) => s.trim())
.map((setString) => ({
red: Number(setString.match(/(\d+) red/)?.[1] ?? 0),
green: Number(setString.match(/(\d+) green/)?.[1] ?? 0),
blue: Number(setString.match(/(\d+) blue/)?.[1] ?? 0),
}));
return {
gameId,
sets,
};
});
};
export const getPossibleGames = (
red: number,
green: number,
blue: number,
games: Game[],
): number[] => {
return games
.filter((game) => {
return game.sets.every((s) => isSetPossible(red, green, blue, s));
})
.map((game) => game.gameId);
};
const isSetPossible = (
red: number,
green: number,
blue: number,
set: Set,
): boolean => set.red <= red && set.green <= green && set.blue <= blue;
export const solve = () => {
return getPossibleGames(
12,
13,
14,
parseFile("src/day2/day2.input.txt"),
).reduce((a, b) => a + b);
};
// parseFile("src/day2/day2.input.txt");
// console.log(JSON.stringify(parseFile("src/day2/day2.input.txt"), null, 2));
|
import {getServerSession} from "next-auth/next"
import {z} from "zod"
import {authOptions} from "@/lib/auth"
import {db} from "@/lib/db"
import {userNameSchema} from "@/lib/validations/user"
const routeContextSchema = z.object({
params: z.object({
userId: z.string(),
}),
})
export async function GET(req: Request,
context: z.infer<typeof routeContextSchema>) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return new Response("Unauthorized", { status: 403 })
}
const posts = await db.user.findFirst({
where: {
id: context.params.userId,
},
select: {
name: true,
email: true,
image: true
},
});
return new Response(JSON.stringify(posts))
} catch (error) {
return new Response(null, { status: 500 })
}
}
export async function PATCH(
req: Request,
context: z.infer<typeof routeContextSchema>
) {
try {
// Validate the route context.
const { params } = routeContextSchema.parse(context)
// Ensure user is authentication and has access to this user.
const session = await getServerSession(authOptions)
if (!session?.user || params.userId !== session?.user.id) {
return new Response(null, { status: 403 })
}
// Get the request body and validate it.
const body = await req.json()
const payload = userNameSchema.parse(body)
// Update the user.
await db.user.update({
where: {
id: session.user.id,
},
data: {
name: payload.name,
},
})
return new Response(null, { status: 200 })
} catch (error) {
if (error instanceof z.ZodError) {
return new Response(JSON.stringify(error.issues), { status: 422 })
}
return new Response(null, { status: 500 })
}
}
|
Tree is Data Structure
Non Linear Data Structute
Node
Root
Parent
Child
Ancestor
Descendant
Sibling
leaf
Code:
class Node
{
int data;
node* left;
node* rightl
};
for nary
class node
{
int data;
vector<node*> child;
}
1
/ \
2 3
/ \
4 5
Types Of questions
1. Online Test
MCQ -> easy or formula based - 2n+1 type
Coding Question -> 95% classical question or similar level question
both in interview or coding test
5% ques can be tough -> Tree, heap, map -> where multiple concept are being asked
1. **Introduction to Trees**:
- A tree is a hierarchical data structure consisting of nodes connected by edges.
- It is a special type of graph with no cycles, which means there is only one path between any two nodes.
2. **Tree Terminology**:
- **Node**: A fundamental unit of a tree, which stores data and has zero or more child nodes.
- **Root**: The topmost node in a tree, from which all other nodes are descended.
- **Leaf**: A node with no children, i.e., a node at the end of a branch.
- **Parent**: A node that has one or more child nodes.
- **Child**: A node that is a direct descendant of another node.
- **Siblings**: Nodes that share the same parent.
- **Depth**: The level of a node in the tree, with the root node at depth 0.
- **Height**: The length of the longest path from a node to a leaf.
3. **Binary Trees**:
- A binary tree is a tree in which each node can have at most two children, often referred to as the left child and the right child.
- Special types of binary trees include binary search trees (BSTs) where the left child is smaller than the parent, and the right child is larger.
1
/ | \
2 3 4
/ \ \
5 6 7
In this N-ary tree:
- Node 1 is the root.
- Node 2, 3, and 4 are children of Node 1.
- Node 2 has two children, Node 5 and Node 6.
- Node 4 has one child, Node 7.
This is just a basic representation of an N-ary tree, where each node can have a variable number of children. In practice, N-ary trees can have more complex structures with different numbers of children for each node.
4. **Tree Traversal**:
- Tree traversal is the process of visiting and processing all nodes in a tree.
- Common traversal algorithms:
- **In-order**: Visit left subtree, visit the current node, visit right subtree (used for BSTs to get sorted output).
- **Pre-order**: Visit the current node, visit left subtree, visit right subtree (used for creating a copy of the tree).
- **Post-order**: Visit left subtree, visit right subtree, visit the current node (used for deleting a tree).
5. **Binary Heap**:
- A binary heap is a binary tree with special properties, often used to implement priority queues.
- Min-heap: The value of each node is smaller than or equal to the values of its children.
- Max-heap: The value of each node is greater than or equal to the values of its children.
6. **Balanced Binary Trees**:
- Balanced trees, like AVL trees and Red-Black trees, ensure that the tree remains relatively balanced, resulting in efficient operations.
- AVL trees: Ensure the balance factor (height difference between left and right subtrees) of each node is at most 1.
- Red-Black trees: Ensure the tree remains approximately balanced and have specific rules for coloring nodes to maintain balance.
7. **Tree Applications**:
- Trees are used in various applications, such as:
- Hierarchical data representation (file systems, organization charts).
- Searching and sorting (binary search trees).
- Expression parsing and evaluation.
- Game trees (e.g., in chess AI).
- Network routing algorithms (e.g., OSPF).
8. **Tree Operations**:
- Insertion: Adding a new node to the tree while maintaining its properties.
- Deletion: Removing a node from the tree while maintaining its properties.
- Searching: Finding a specific node or element in the tree.
- Updating: Modifying the value of a node.
These are some fundamental concepts and notes on trees in data structures and algorithms. Trees play a crucial role in various applications, and understanding them is essential for solving many algorithmic problems.
|
import { useCallback, useEffect, useState } from 'react';
import { apiSendSms } from 'src/services/api.services';
import useAppNavigation from './useAppNavigation';
import BackgroundTimer from 'react-native-background-timer-android';
let timeout: number;
const setTimeoutFn = BackgroundTimer.setTimeout;
const clearTimeoutFn = BackgroundTimer.clearTimeout;
const useSmsSend = (phone: string) => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [wait, setWait] = useState(0);
const { navigate } = useAppNavigation();
useEffect(() => {
timeout = setTimeoutFn(() => {
if (wait === 0) {
clearTimeoutFn(timeout);
return;
}
setWait((prev) => prev - 1);
}, 1000);
}, [wait]);
const sendSms = useCallback(async () => {
setLoading(true);
setError('');
try {
const response = await apiSendSms(phone);
const isCreated: boolean = response.data.is_created;
navigate('confirmPhoneNumber', { phone, isCreated });
} catch (e) {
if (typeof e === 'number') {
setWait(Math.ceil(e));
} else {
setError(e as string);
}
} finally {
setLoading(false);
}
}, [phone]);
return { sendSms, wait, loading, error };
};
export default useSmsSend;
|
#' @title Functional cover summary plot
#'
#' @description For veg data, summarizes and plots mean cover of functional groups.
#' @description Data are summarized for all years specified.
#' @description Background data are supplied from the lpi data select. Data for a selected ranch are not used in the calculation of regional averages.
#'
#'
#' @param lpi A dataframe object of lpi data from a veg survey
#' @param transect Ranch for which to make plot
#' @param type "absolute" or "relative" cover
#' @param surveyyear The year for which to calculate cover
#' @param background = TRUE whether to display "background" data on plot not from selected ranch
#' @param xlab,ylab Axis labels
#' @param legendnames specifies how points are named on the legend
#' @param legendtitle Character string of legend title
#' @param boxcolors vector of colors to display data on the boxplot
#'
#' @return A ggplot of functional cover with error bars
#'
#' @examples data = functional.cover.plot(lpi, type = "absolute")
#'
#' @export functional.cover.plot
#'
#'
#'
#'
functional.cover.plot = function(lpi,
type = "absolute",
transect,
background = TRUE,
invasives = FALSE,
surveyyear = max(levels(as.factor(lpi$year))),
xlab = "Functional Group",
ylab = "Percent Cover",
legendtitle = "Ranch",
legendnames = c(paste(transect, collapse = " "), "Others"),
boxcolors = c("black","gray")){
library(ggplot2)
cov = functional.cover.table(lpi, type = type, transect = levels(lpi$Transect.Name),
surveyyear = surveyyear, invasives = invasives,
includemeta = TRUE)
if(!background){cov = subset(cov, subset = Transect %in% transect)}
cov$NumIndices = NULL
cov = melt(cov, id = c("Transect" ,"pointyear", "Point.Id", "year"))
names(cov)<-c("Transect", "pointyear", "Point.Id", "year", "Type", "Cover")
masked = cov
masked$Transect = as.character(replace(as.character(masked$Transect),
masked$Transect != transect, values = "zzzz"))
masked$Transect = as.character(replace(as.character(masked$Transect),
masked$Transect == transect, values = "aaaa"))
masked$year = as.factor(masked$year)
masked$Type = as.factor(masked$Type)
cover_plot = ggplot(masked, aes(x = Type, y = Cover, color = Transect)) +
geom_boxplot() +
scale_color_manual(name = legendtitle, values = boxcolors, labels = legendnames) +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
xlab(xlab) +
ylab(ylab)
return(cover_plot)
}
|
/*
* musicplayer.h
*
* Copyright 2017-2019 Dariusz Sikora <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*
*/
#ifndef MUSICPLAYER_H
#define MUSICPLAYER_H
#include <QListView>
#include <QFileSystemModel>
#include <QStandardPaths>
#include <QMediaPlaylist>
#include <QMediaPlayer>
#include <iostream>
/**
* @brief The MusicPlayer class Class for music player
*/
class MusicPlayer : public QMediaPlayer
{
Q_OBJECT
public:
MusicPlayer();
~MusicPlayer();
bool openIn(QString dir);
bool add(QMediaContent media);
bool addAll(QList<QMediaContent> media);
void play(QMediaContent media);
void play(int index);
void play(QString mediaPath);
void play();
void next();
void prev();
std::string getTrackPath();
QDir getDir();
QStringList getFormats();
private:
QDir *currentDir;
QMediaPlaylist *playList;
QList<QMediaContent> getDirContent();
int getFromPlaylist(QMediaContent mediaToCheck);
};
#endif // MUSICPLAYER_H
|
const fs = require('fs')
const momentService = require('../service/moment.service')
const commentService = require('../service/comment.service')
const { PICTURE_PATH } = require('../constants/file.path')
class MomentController {
async create(ctx, next) {
// 1.获取图像信息
const files = ctx.req.files
const {title, content, userId} = ctx.req.body
let result = []
// 2.将所有的文件信息保存到数据库中
for (let file of files) {
const { filename, mimetype, size } = file
result = await momentService.create(title, content, userId, filename, mimetype, size)
}
// 2. 把数据插入到数据库中
ctx.body = '成功上传新动态'
}
async detail(ctx, next) {
// 1. 获取数据
const momentId = ctx.params.momentId
// 2. 查询数据
const result = await momentService.getMomentById(momentId)
ctx.body = result
}
async list(ctx, next) {
const result = await momentService.getMomentList()
ctx.body = result
}
async getListById(ctx, next) {
const {userId} = ctx.params
const result = await momentService.getListById(userId)
ctx.body = result
}
async getKeywordMoment(ctx, next) {
const {keyword} = ctx.params;
const keywordMoment = await momentService.searchKeywordMoment(keyword)
ctx.body = keywordMoment
}
async update(ctx, next) {
// 1. 获取参数
const { momentId } = ctx.params
const { content } = ctx.request.body
const result = await momentService.update(content, momentId)
ctx.body = result
}
async remove(ctx, next) {
// 1.获取momentId
const { momentId } = ctx.params
await commentService.removeCommentsByMomentId(momentId)
// 2.删除内容
const result = await momentService.remove(momentId)
ctx.body = result
}
async getFileInfo(ctx, next) {
let { filename } = ctx.params
const fileInfo = await momentService.getFileByFilename(filename)
const { type } = ctx.query
const types = ['small', 'middle', 'large']
if (types.some(item => item === type)) {
filename = filename + '-' + type
}
ctx.response.set('content-type', fileInfo.mimetype)
ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`)
}
}
module.exports = new MomentController()
|
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
interface IntroState {
isIntroDone: boolean;
setIntroDone: (isDone: boolean) => void;
}
const useIntroStore = create<IntroState>()(
persist(
(set) => ({
isIntroDone: false,
setIntroDone: (isDone) => set({ isIntroDone: isDone }),
}),
{
name: "introanimation-storage",
storage: createJSONStorage(() => sessionStorage),
},
),
);
export const getIntroDone = () => useIntroStore.getState().isIntroDone;
export const setIntroDone = (isDone: boolean) =>
useIntroStore.getState().setIntroDone(isDone);
|
<script lang="ts">
export let showModal: boolean;
export let isLoading: boolean;
export let saveText: string = "Save Changes";
export let onAccept: () => void;
let dialog; // HTMLDialogElement
$: console.log(dialog);
$: if (dialog && showModal) dialog.showModal();
$: if (dialog && !showModal) dialog.close();
</script>
<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-noninteractive-element-interactions -->
<dialog
bind:this={dialog}
on:close={() => (showModal = false)}
on:click|self={() => dialog.close()}
>
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click|stopPropagation>
<slot name="header" />
<hr />
<slot />
<!-- svelte-ignore a11y-autofocus -->
<!-- <button autofocus on:click={() => dialog.close()}>close modal</button> -->
<div
class="flex items-center justify-end p-6 border-t border-blueGray-200 rounded-b border-none"
>
<button
class="text-red-500 background-transparent font-bold uppercase px-6 py-2 text-sm outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
type="button"
on:click={() => dialog.close()}
>
Tutup
</button>
{#if onAccept === undefined}
<button
class="bg-red-500 text-white active:bg-red-600 font-bold uppercase text-sm px-6 py-3 rounded shadow hover:shadow-lg outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
type="submit"
>
{isLoading ? "Loading..." : saveText}
</button>
{:else}
<button
class="bg-red-500 text-white active:bg-red-600 font-bold uppercase text-sm px-6 py-3 rounded shadow hover:shadow-lg outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
type="button"
on:click={onAccept}
>
{isLoading ? "Loading..." : saveText}
</button>
{/if}
</div>
</div>
</dialog>
<style>
dialog {
max-width: 32em;
border-radius: 0.2em;
border: none;
padding: 0;
}
dialog::backdrop {
background: rgba(0, 0, 0, 0.3);
}
dialog > div {
padding: 1em;
}
dialog[open] {
animation: zoom 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}
@keyframes zoom {
from {
transform: scale(0.95);
}
to {
transform: scale(1);
}
}
dialog[open]::backdrop {
animation: fade 0.2s ease-out;
}
@keyframes fade {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
button {
display: block;
}
</style>
|
from app.system_db.models import TitleService
from app.system_db import db_session,Base
from sqlalchemy import text
from pydantic import validate_call
from app.system_db.basic import BasicCRUD
class TitleServiceCRUD(BasicCRUD):
@staticmethod
def add(**params):
with db_session() as session:
session.add(TitleService(
title_service = params.get("title_service"),
type_service_id = params.get("type_service_id")
))
db_session.commit()
@staticmethod
def update(id,**params):
with db_session() as session:
session.query(TitleService).filter_by(id=id).update({"title_service":params.get("title_service"),"type_service_id":params.get("type_service_id")})
db_session.commit()
@staticmethod
def get_fk_id(id):
with db_session() as session:
fk_id = session.query(TitleService.type_service_id).filter(TitleService.id==id).scalar()
return fk_id
@staticmethod
def get(id):
with db_session() as session:
title_service = session.query(TitleService).filter_by(id=id).scalar()
return title_service
@staticmethod
def get_fk_data():
with db_session() as session:
fk_data = session.query(TitleService).all()
return fk_data
@staticmethod
@validate_call
def get_preview_data(offset:int,columns:list = TitleService.list_display.copy(),tablename:str="title_service"):
"""
Понимаю все риски насчёт sql инъекций,но другого решения не придумал,
НО всё под контролем т.к. типы данных валидируются через пайдентик
"""
if not 'id' in columns:
columns.insert(0,'id')
params = ','.join([column for column in columns])
query = """SELECT %s FROM %s OFFSET %s LIMIT 100;"""%(params,tablename,offset)
query = text(query)
with db_session() as session:
data = session.execute(query)
return data
@staticmethod
def get_types(tablename:str = 'title_service'):
table_types = {}
for k,v in Base.metadata.tables.items():
if v.name == tablename:
for column in v.columns.items()[1:]:
table_types[column[1].name] = (column[1].type,column[1])
return table_types
@staticmethod
def delete(id):
with db_session() as session:
session.query(TitleService).filter_by(id=id).delete()
session.commit()
@staticmethod
def get_data_by_fk(fk_id):
with db_session() as session:
title_services = session.query(TitleService).filter_by(type_service_id=fk_id).all()
return title_services
@staticmethod
def get_first_id():
with db_session() as session:
title_service = session.query(TitleService.id).first()
return title_service
|
// src/components/Login/LoginScreen.tsx
import React from 'react';
import { Text, Button, ActivityIndicator } from 'react-native';
import { BaseScreen, TextInput } from '../../../../globalComponents';
import Styles from "../../styles";
import LocalizedString from '../../../../utils/localization';
const LoginScreen: React.FC<LoginScreenProps> = ({
username, password, loading, onLogin, onChangeUsername, onChangePassword
}) => {
return (
<BaseScreen customStyle={Styles.bodyContainer}>
<Text>Login Screen</Text>
<TextInput
value={username}
editable={!loading}
placeholder={LocalizedString.loginScreen.labelUsername}
onChangeText={(e) => onChangeUsername(e)}
/>
<TextInput
value={password}
secureTextEntry={true}
editable={!loading}
placeholder={LocalizedString.loginScreen.labelPassword}
onChangeText={(e) => onChangePassword(e)}
/>
{loading ?
<ActivityIndicator animating={true} color={'blue'} />
: <Button title="Login" onPress={onLogin} />
}
</BaseScreen>
);
};
export default LoginScreen;
|
//
// ResponseHandler.swift
// FindingFalcone
//
// Created by Pallab Maiti on 04/03/24.
//
import Foundation
protocol ResponseHandlerProtocol {
func parseData<T: Codable>(_ data: Data?) throws -> T?
}
let sharedDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
final class ResponseHandler: ResponseHandlerProtocol {
let decoder: JSONDecoder
init(decoder: JSONDecoder = sharedDecoder) {
self.decoder = decoder
}
func parseData<T: Codable>(_ data: Data?) throws -> T? {
guard let data = data else {
return nil
}
return try decoder.decode(T.self, from: data)
}
}
|
#pragma once
#include "Repository.h"
#include "RepositoryCSV.h"
#include "RepositoryHTML.h"
#include "RepositorySQL.h"
#include "Comparator.h"
class Service
{
private:
Repository* dogsRepo;
Repository* userAdoptionList;
public:
// Service constructor
Service(Repository* _dogsRepo, Repository* _userAdoptionList);
/*
Add a dog to the dogsRepo.
*/
void addDog(int id, const std::string& breed, const std::string& name, int age, const std::string& photograph);
/*
Remove a dog from the dogsRepo.
*/
void removeDog(int id);
/*
Update dog's information.
*/
void updateBreed(int id, std::string& _breed);
/*
Update dog's information.
*/
void updateName(int id, std::string& _name);
/*
Update dog's information.
*/
void updateAge(int id, int _age);
/*
Update dog's information.
*/
void updatePhotograph(int id, std::string& _photograph);
/*
Update dog's information.
*/
void adoptDog(int id);
/*
Get the length of the dogsRepo.
*/
int getDogsRepoSize() const;
/*
Get the length of the userAdoptionList.
*/
int getUserAdoptionListSize() const;
/*
Return a copy of the dogsRepo.
*/
std::vector<Dog> getDogsRepoElements() const;
/*
Return a copy of the userAdoptionList.
*/
std::vector<Dog> getUserAdpotionElements() const;
void saveElementsToFile();
void initialiseApplicationFromFile();
void saveAdoptionList();
};
template <typename T>
void customSort(std::vector<T>& v, Comparator<T>* c)
{
for (int i = 0; i < v.size() - 1; i++)
for (int j = i + 1; j < v.size(); j++)
if (!c->compare(v[i], v[j]))
{
Dog aux = v[i];
v[i] = v[j];
v[j] = aux;
}
}
|
function showError(inputElement, errorElement, errorMessage, props) {
inputElement.classList.add(props.inputErrorClass);
errorElement.textContent = errorMessage;
errorElement.classList.add(props.errorClass);
}
function hideError(inputElement, errorElement, props) {
inputElement.classList.remove(props.inputErrorClass);
errorElement.textContent = "";
errorElement.classList.remove(props.errorClass);
}
function checkInputValidity(inputElement, errorElement, props) {
if (!inputElement.validity.valid) {
showError(inputElement, errorElement, inputElement.validationMessage, props);
} else {
hideError(inputElement, errorElement, props);
}
}
function toggleButtonState(formElement, submitButtonElement, inputElements, props) {
const isValid = inputElements.every(
(inputElement) => inputElement.validity.valid
);
submitButtonElement.disabled = !isValid;
submitButtonElement.classList.toggle(props.inactiveButtonClass, !isValid);
}
function resetForm(formElement, submitButtonElement, inputElements, props) {
formElement.reset();
toggleButtonState(formElement, submitButtonElement, inputElements, props);
}
function setEventListeners(formElement, props) {
const inputElements = Array.from(
formElement.querySelectorAll(props.inputSelector)
);
const submitButtonElement = formElement.querySelector(
props.submitButtonSelector
);
function handleFormSubmit(evt) {
evt.preventDefault();
}
function handleInputChange(evt) {
const inputElement = evt.target;
const errorElement = inputElement.nextElementSibling;
checkInputValidity(inputElement, errorElement, props);
toggleButtonState(formElement, submitButtonElement, inputElements, props);
}
inputElements.forEach((inputElement) => {
inputElement.addEventListener("input", handleInputChange);
});
formElement.addEventListener("submit", handleFormSubmit);
resetForm(formElement, submitButtonElement, inputElements, props);
}
function enableValidation(props) {
const formElements = document.querySelectorAll(props.formSelector);
formElements.forEach((formElement) => {
setEventListeners(formElement, props);
});
}
enableValidation({
formSelector: ".popup__form",
inputSelector: ".popup__input",
submitButtonSelector: ".popup__submit-btn",
inactiveButtonClass: "popup__button_disabled",
inputErrorClass: "popup__input_type_error",
errorClass: "popup__error_visible",
});
|
import './App.scss';
import React, { useEffect, useState } from 'react';
import { getCompaniesStatic } from './api/getCompanies';
import { Company } from './components/Company';
import { TimeslotState, useTimeslotsStore } from './stores/timeslotsStore';
import { getCompanyWithGroupedDates, ICompanyWithGroupedTimeslots } from './util/getCompanyWithGroupedDates';
const getInitTimeslotsStore = (state: TimeslotState) => state.initTimeslotsStore;
function App() {
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string>('');
const [companies, setCompanies] = useState<Array<ICompanyWithGroupedTimeslots>>([]);
const initTimeslotsStore = useTimeslotsStore(getInitTimeslotsStore);
useEffect(() => {
async function loadCompanies() {
setLoading(true);
const { companies, error } = await getCompaniesStatic();
if (error) {
setCompanies([]);
setError(error);
} else if (companies) {
setCompanies(companies.map(getCompanyWithGroupedDates));
initTimeslotsStore(companies);
setError('');
}
setLoading(false);
}
loadCompanies();
}, []);
if (error) {
return <div>Error</div>;
}
return (
<div className='App font-mono'>
<div className='w-screen text-2xl text-center bg-amber-500 p-20 shadow-md'>Timeslot Selection</div>
<div className='content-wrapper sm:px-10 md:px-20 lg:px-40'>
{loading && 'Loading'}
<div className='flex flex-row'>
{companies.map((company) => (
<Company key={company.id} company={company} />
))}
</div>
</div>
</div>
);
}
export default App;
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using TrashCollector.Data;
using TrashCollector.Models;
namespace TrashCollector.Controllers
{
//[Authorize(Roles = "Customer")]
public class CustomersController : Controller
{
private readonly ApplicationDbContext _context;
public CustomersController(ApplicationDbContext context)
{
_context = context;
}
// GET: Customers
public IActionResult Index()
{
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
var myCustomerProfile = _context.Customers.Where(c => c.IdentityUserId == userId).SingleOrDefault();
if (myCustomerProfile == null)
{
return RedirectToAction("Create");
}
return View(myCustomerProfile);
}
public ActionResult Index2()
{
var customers = _context.Customers;
return View(customers);
}
// GET: Customers/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var customer = await _context.Customers
.Include(c => c.IdentityUser)
.FirstOrDefaultAsync(m => m.CustomerId == id);
if (customer == null)
{
return NotFound();
}
return View(customer);
}
// GET: Customers/Create
public IActionResult Create()
{
Customer customer = new Customer();
ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id");
List<string> daysOfWeek = new List<string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
customer.DaysOfWeek = new SelectList(daysOfWeek);
return View(customer);
}
// POST: Customers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name,DayOfWeekChoice,AccountBalance,Adress,ExtraDayDateChoice,StartDate,StopDate")] Customer customer)
{
if (ModelState.IsValid)
{
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
customer.IdentityUserId = userId;
_context.Add(customer);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", customer.IdentityUserId);
return View(customer);
}
// GET: Customers/Edit/5
//[Authorize(Roles = "Customer")]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
{
return NotFound();
}
List<string> daysOfWeek = new List<string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
customer.DaysOfWeek = new SelectList(daysOfWeek);
ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", customer.IdentityUserId);
return View(customer);
}
// POST: Customers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, Customer customer)
{
try
{
_context.Update(customer);
_context.SaveChanges();
//return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", customer.IdentityUserId);
return RedirectToAction("Index");
}
// GET: Customers/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var customer = await _context.Customers
.Include(c => c.IdentityUser)
.FirstOrDefaultAsync(m => m.CustomerId == id);
if (customer == null)
{
return NotFound();
}
return View(customer);
}
// POST: Customers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var customer = await _context.Customers.FindAsync(id);
_context.Customers.Remove(customer);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool CustomerExists(int id)
{
return _context.Customers.Any(e => e.CustomerId == id);
}
}
}
|
import "./App.scss";
import Navigation from "./components/Navigation";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import ROUTES from "./utils/routes";
import Home from "./components/Home";
import Auction from "./components/Auction";
import Project from "./components/Project";
import Logo from "./components/Logo";
import { Container } from "react-bootstrap";
import AccountInfo from "./components/AccountInfo";
import AuthProvider from "./components/Auth";
import React from "react";
import Footer from "./components/Footer";
import BetPlacementProvider from "./components/BetPlacement";
import Admin from "./components/admin/Admin";
import ImageModalProvider from "./components/ImageModal";
function App() {
return (
<React.Suspense fallback={null}>
<ImageModalProvider>
<AuthProvider>
<BetPlacementProvider>
<BrowserRouter>
<div>
<header>
<Container
fluid
className="d-flex justify-content-between pt-3 pb-3 ps-4 pe-4"
>
<Navigation />
<AccountInfo />
</Container>
</header>
<Logo />
</div>
<Switch>
<Route path={ROUTES.ROUTE_AUCTION + "/:id?"}>
<Auction />
</Route>
<Route path={ROUTES.ROUTE_PROJECT + "/:id?"}>
<Project />
</Route>
<Route path={ROUTES.ROUTE_ADMIN}>
<Admin />
</Route>
<Route path={ROUTES.ROUTE_HOME}>
<Home />
</Route>
</Switch>
<Footer />
</BrowserRouter>
</BetPlacementProvider>
</AuthProvider>
</ImageModalProvider>
</React.Suspense>
);
}
export default App;
|
#ifndef SBPLATFORMER_H
#define SBPLATFORMER_H
#include <memory>
#include <vector>
#include <string>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include "SbMessage.h"
#include "SbWindow.h"
#include "SbObject.h"
#include "SbFont.h"
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
const int LEVEL_WIDTH = 2000;
const int LEVEL_HEIGHT = 1500;
const int CONTROLLER_DEADZONE = 7000;
const std::string name = "Platformer";
const double GRAVITY = 2.5e-6;
const double JUMP = 1.0/700.0;
const double FRICTION = 4e-7;
const double PLAYER_VELOCITY = 1.0/2000.0;
const double STEP_SIZE = LEVEL_WIDTH / 20;
class Exit;
class Platform;
class Level;
class Platformer;
/* MovementLimits and MovementRange are used to define moving platforms
*/
struct MovementLimits
{
MovementLimits(uint32_t l, uint32_t r, uint32_t t, uint32_t b)
: left(l), right(r), top(t), bottom(b)
{}
MovementLimits() = default;
uint32_t left = 0;
uint32_t right = 0;
uint32_t top = 0;
uint32_t bottom = 0;
};
struct MovementRange
{
MovementRange(double l, double r, double t, double b)
: left(l), right(r), top(t), bottom(b)
{}
MovementRange() = default;
MovementLimits to_limits(uint32_t width, uint32_t height) {
MovementLimits result;
result.left = left * width;
result.right = right * width;
result.top = top * height;
result.bottom = bottom * height;
return result;
}
double left = 0;
double right = 0;
double top = 0;
double bottom = 0;
};
struct Velocity
{
Velocity(double xdir, double ydir)
: x(xdir), y(ydir)
{}
Velocity() = default;
double x = 0;
double y = 0;
};
class Player : public SbObject
{
public:
Player(const SbDimension* ref);
bool check_exit(const Exit& goal);
void handle_event(const SDL_Event& event);
int move(const std::vector<std::unique_ptr<SbObject>>& level);
void follow_platform();
// void render();
/*! Reset after goal.
*/
void reset();
private:
bool check_air_deltav( double sensitivity );
const std::unique_ptr<SbObject>* standing_on_ = nullptr;
bool exit_ = false;
double velocity_max_ = PLAYER_VELOCITY;
double velocity_jump_ = JUMP;
bool on_surface_ = true;
/*! allowed_air_deltav_ is the number of direction changes allowed in mid-air. in_air_deltav_ keeps track of direction changes in mid-air
*/
uint32_t in_air_deltav_ = 0;
uint32_t allowed_air_deltav_ = 2;
double controller_sensitivity_ = 0.1;
double friction_ = FRICTION;
double step_size = STEP_SIZE;
double movement_start_position;
SbControlDir direction_ = SbControlDir::none;
};
class Platform : public SbObject
{
friend class Level;
public:
Platform(int x, int y, int width, int height, const SbDimension* ref);
Platform( SbRectangle bounding_box, const SbDimension* ref );
int move();
private:
Velocity velocity_;
MovementLimits limits_;
void set_velocities(double x, double y);
void set_velocities(Velocity v);
void set_limits(MovementLimits limit);
};
class Exit : public SbObject
{
public:
Exit(int x, int y, int width, int height);
Exit(SbRectangle box, const SbDimension* ref);
};
class Level
{
public:
Level(uint32_t num, const SbDimension* window_ref);
void create_level(uint32_t num);
Exit const& exit() const {return *exit_;}
std::vector<std::unique_ptr<SbObject>> const& platforms() const {return platforms_; }
uint32_t width() { return dimension_.w; }
uint32_t height() {return dimension_.h; }
void render(const SDL_Rect &camera);
uint32_t level_number() { return level_num_; }
// void handle_event(const SDL_Event& event);
void move();
void update_size();
const SbDimension* get_dimension() const {return &dimension_;}
private:
SbDimension dimension_ = {100,100};
const SbDimension* window_ref_;
uint32_t level_num_ = 0;
std::unique_ptr<Exit> exit_ = nullptr;
std::vector<std::unique_ptr<SbObject>> platforms_;
};
class Platformer
{
public:
Platformer();
~Platformer();
Platformer(const Platformer&) = delete ;
Platformer& operator=(const Platformer& toCopy) = delete;
void initialize();
void reset();
static Uint32 reset_game(Uint32 interval, void *param );
void run();
SbWindow* window() {return &window_; }
private:
std::unique_ptr<Player> player_;
std::unique_ptr<Level> level_ = nullptr;
SDL_GameController* game_controller_ = nullptr;
bool in_exit_ = false;
uint32_t current_level_ = 0;
SbWindow window_{name, SCREEN_WIDTH, SCREEN_HEIGHT};
SDL_Rect camera_;
std::unique_ptr<SbFpsDisplay> fps_display_ = nullptr;
SbTimer reset_timer_;
};
struct LevelCoordinates
{
LevelCoordinates(SbDimension d, std::vector<SbRectangle> t, SbRectangle g, std::vector<MovementRange> r, std::vector<Velocity> v)
: dimension(d), tiles(t),goal(g), ranges(r), velocities(v)
{}
SbDimension dimension;
std::vector<SbRectangle> tiles;
SbRectangle goal;
std::vector<MovementRange> ranges;
std::vector<Velocity> velocities;
};
////// levels //////
std::vector<LevelCoordinates> levels;
SbDimension dim0 = {LEVEL_WIDTH, LEVEL_HEIGHT};
std::vector<SbRectangle> lev0 = {{0,0,1.0,0.03}, {0.97,0.0,0.03,1.0}, {0.0,0.0,0.03,1.0}, {0.0, 0.97, 1.0, 0.03} /* outer boxes */
, {0.85, 0.75, 0.12, 0.03 }
,{0.03,0.77,0.12,0.03}, {0.18, 0.57, 0.12, 0.03}, {0.03, 0.37, 0.12, 0.03}
};
SbRectangle goal0 = {0.03, 0.25, 0.03, 0.12};
std::vector<MovementRange> range0 = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} /* outer frame */
, {0, 0, 0.15, 0}
, {0, 0.08, 0.0, 0.0}, {0.02, 0.1, 0.07, 0.05}, {0, 0, 0, 0}
};
std::vector<Velocity> velocity0 = { {0, 0}, {0, 0}, {0, 0}, {0, 0}
,{0, 0.00005}
,{ 0.00005, 0}, {0.00003, 0.00003}, {0,0}
};
//// levels end ////
#endif // SBPLATFORMER_H
|
"""
Использование тайм-аутов в wait
с. 127
"""
import asyncio
from aiohttp import ClientSession
from util import async_timed
from chapter_04 import fetch_status
@async_timed()
async def main():
async with ClientSession() as session:
url = 'https://example.com'
fetchers = [
asyncio.create_task(fetch_status(session, url)),
asyncio.create_task(fetch_status(session, url)),
asyncio.create_task(fetch_status(session, url, delay=3)),
]
done, pending = await asyncio.wait(fetchers, timeout=1)
print(f'Число завершившихся задач {len(done)}')
print(f'Число ожидающих задач {len(pending)}')
for done_task in done:
print(await done_task)
asyncio.run(main())
|
import { headers } from "next/headers";
import ProductCard from "@/Components/ProductCard";
import React from "react";
import Pagination from "@/Components/SharedUI/Pagination";
import { getServerSession } from "next-auth";
import { authOptions } from "../api/auth/[...nextauth]/route";
import { redirect } from "next/navigation";
import { GetAllProducts, GetBasketItems } from "@/libs/BackendApi";
import ErrorTostClient from "@/libs/ErrorTostClient";
class AtomicState {
constructor() {
this.messages = [];
this.Type = "";
}
addMessage(message, Type) {
this.messages.push(message);
this.Type = Type;
}
getMessages() {
const messages = this.messages;
const Type = this.Type;
return { Type, messages };
}
clearAllMessages() {
this.messages = []; // messages dizisini boşalt
this.Type = ""; // Type özelliğini boşalt
}
}
const state = new AtomicState();
async function CreateProductWithImage({ searchParams }) {
const session = await getServerSession(authOptions);
if (!session) {
redirect("/Login?callbackUrl=/CreateProduct");
}
const headersList = headers();
const header_url = headersList.get("x-invoke-path") || "";
const CurrentPage = searchParams.Page || "0";
let Products = await GetAllProducts(CurrentPage, 12, true, "Products");
let result = state.getMessages();
let Basket = await GetBasketItems(session.accessToken);
console.log(Basket);
return (
<>
<div className="grid mt-12 grid-cols-2 gap-x-6 gap-y-10 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 xl:gap-x-8 max-w-[1200px] mx-auto">
{Products &&
Products.products.map((item, key) => {
return <ProductCard item={item} key={key} keyValue={key} />;
})}
</div>
<div className="w-full flex flex-row justify-center items-center mt-4">
<Pagination
hasNext={Products ? Products.hasNext : false}
hasPrev={Products ? Products.hasPrev : 0}
totalCount={Products ? Products.totalCount : 0}
totalPageSize={Products ? Products.totalPageSize : 0}
currentPage={Products ? Products.currentPage : 0}
pagesize={Products ? Products.pagesize : 0}
pathName={header_url}
/>
</div>
<ErrorTostClient result={result} />
{/* <div className="flex flex-col max-w-xl mx-auto">
{JSON.stringify(Basket)}
{Basket.map((item, key) => {
return <>
<div key={key} className="justify-between mb-6 rounded-lg bg-white p-6 shadow-md sm:flex sm:justify-start">
<img src="https://images.unsplash.com/photo-1515955656352-a1fa3ffcd111?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" alt="product-image" className="w-full rounded-lg sm:w-40" />
<div className="sm:ml-4 sm:flex sm:w-full sm:justify-between">
<div className="mt-5 sm:mt-0">
<h2 className="text-lg font-bold text-gray-900">Name</h2>
<p className="mt-1 text-xs text-gray-700">{item.price}</p>
</div>
<div className="mt-4 flex justify-between sm:space-y-6 sm:mt-0 sm:block sm:space-x-6">
<div className="flex items-center border-gray-100">
<span className="cursor-pointer rounded-l bg-gray-100 py-1 px-3.5 duration-100 hover:bg-blue-500 hover:text-blue-50"> - </span>
<input className="h-8 w-8 border bg-white text-center text-xs outline-none" type="number" value="2" min="1" />
<span className="cursor-pointer rounded-r bg-gray-100 py-1 px-3 duration-100 hover:bg-blue-500 hover:text-blue-50"> + </span>
</div>
<div className="flex items-center space-x-4">
<p className="text-sm">Price <b>TL</b></p>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="h-5 w-5 cursor-pointer duration-150 hover:text-red-500">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
</div>
</div>
</div></>;
})}
</div>*/}
</>
);
}
export default CreateProductWithImage;
|
import React, { useState } from "react";
import { Fade, Flip, Slide } from "react-awesome-reveal";
import CreditCardForm from "./CreditCardForm";
import UPIForm from "./UPIFrom";
const PaymentOptions = ({ setcheckOutstep }) => {
const [selectedOption, setSelectedOption] = useState("");
const handleOptionChange = (e) => {
setSelectedOption(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
// Assuming form validation is successful, move to the next step
onComplete(selectedOption);
};
return (
<>
<Fade >
<div className="p-4 border-2 border-black rounded-lg shadow-md bg-white ">
<h2 className="text-lg font-semibold mb-4">Payment Options</h2>
<form onSubmit={handleSubmit}>
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700">
Select Payment Option
</label>
<div className="mt-1">
<label className="inline-flex items-center">
<input
type="radio"
value="creditCard"
checked={selectedOption === "creditCard"}
onChange={handleOptionChange}
className="form-radio"
/>
<span className="ml-2">Credit Card</span>
</label>
<label className="inline-flex items-center ml-4">
<input
type="radio"
value="UPI"
checked={selectedOption === "UPI"}
onChange={handleOptionChange}
className="form-radio"
/>
<span className="ml-2">UPI</span>
</label>
<label className="inline-flex items-center ml-4">
<input
type="radio"
value="COD"
checked={selectedOption === "COD"}
onChange={handleOptionChange}
className="form-radio"
/>
<span className="ml-2">Cash On Delivery</span>
</label>
</div>
</div>
<div className="flex mt-6">
<button
type="button"
onClick={() => {
setcheckOutstep(1)
}}
className="px-4 py-2 mr-2 bg-gray-200 text-gray-700 rounded-lg font-semibold hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-300"
>
Back
</button>
</div>
</form>
</div>
</Fade>
<span className={`${selectedOption === "creditCard"?'block':'hidden'}`}>
<Fade>
<CreditCardForm />
</Fade>
</span>
<span className={`${selectedOption === "UPI"?'block':'hidden'}`}>
<Fade>
<UPIForm />
</Fade>
</span>
</>
);
};
export default PaymentOptions;
|
//*****************************************************************************
//
// uart_echo.c - Example for reading data from and writing data to the UART in
// an interrupt driven fashion.
//
// Copyright (c) 2013-2020 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.2.0.295 of the EK-TM4C1294XL Firmware Package.
//
//*****************************************************************************
#include <stdint.h>
#include <stdbool.h>
#include "inc/hw_ints.h"
#include "inc/hw_types.h" ////****
#include "inc/hw_memmap.h"
#include "driverlib/debug.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/uart.h"
#include "driverlib/pwm.h"
#include "driverlib/timer.h"
char data[20]="COUNT:001_A";
uint32_t g_ui32SysClock;
uint32_t g_ui32Flags; ////****
uint8_t global_counter=0;
//*****************************************************************************
//
// The error routine that is called if the driver library encounters an error.
//
//*****************************************************************************
#ifdef DEBUG
void
__error__(char *pcFilename, uint32_t ui32Line)
{
}
#endif
//*****************************************************************************
//
// The UART interrupt handler.
//
//*****************************************************************************
bool flag=false;
int32_t counter=0;
bool flag2=true;
uint32_t num=0; //000-999
uint32_t dig_centenas=0; //000-999
uint32_t dig_unidades=0; //000-999
uint32_t dig_decenas=0; //000-999
uint32_t num2=-1; //000-999
void GPIOIntHandler(void)
{
global_counter++;
uint32_t ui32Status;
ui32Status=GPIOIntStatus(GPIO_PORTJ_BASE, true);
GPIOIntClear(GPIO_PORTJ_BASE,ui32Status);
//UARTSend((uint8_t *)"\033[2JPressed: ", 12);
if(data[9]=='_'){
num=(int)(data[6]-48)*100+(int)(data[7]-48)*10+(int)(data[8]-48);//preguntar al inge
if(num!=num2)
{
flag2=true;
}
if(flag2==true){
counter=num;
flag2=false;
}
dig_centenas=(int)counter/100;
dig_decenas=(int)(counter-dig_centenas*100)/10;
dig_unidades=(int)(counter-dig_centenas*100-dig_decenas*10);
UARTCharPut(UART0_BASE, 'p');
UARTCharPut(UART0_BASE, ':');
UARTCharPut(UART0_BASE, (uint8_t)48+dig_centenas);
UARTCharPut(UART0_BASE, (uint8_t)48+dig_decenas);
UARTCharPut(UART0_BASE, (uint8_t)48+dig_unidades);
UARTCharPut(UART0_BASE, '\n');
if(data[0]=='C'&&data[1]=='O'&&data[2]=='U'&&data[3]=='N'&&data[4]=='T'&&data[5]==':'&&data[9]=='_'&&data[10]=='A'){
counter++;
if(counter>=1000)
{
counter=999;
}
}
if(data[0]=='C'&&data[1]=='O'&&data[2]=='U'&&data[3]=='N'&&data[4]=='T'&&data[5]==':'&&data[9]=='_'&&data[10]=='D'){
counter--;
if(counter<1)
{
counter=0;
}
}
num2=num;//preguntar al inge
}
if(global_counter==5)
{
MAP_TimerLoadSet(TIMER0_BASE, TIMER_A, 120000000);
MAP_TimerEnable(TIMER0_BASE, TIMER_A);
}
}
void
Timer0IntHandler(void)
{
char cOne, cTwo;
//
// Clear the timer interrupt.
//
MAP_TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
//
// Toggle the flag for the first timer.
//
HWREGBITW(&g_ui32Flags, 0) ^= 1;
//
// Use the flags to Toggle the LED for this timer
//
//GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_0, g_ui32Flags);
//
// Update the interrupt status.
//
MAP_IntMasterDisable();
cOne = HWREGBITW(&g_ui32Flags, 0) ? '1' : '0';
cTwo = HWREGBITW(&g_ui32Flags, 1) ? '1' : '0';
if(flag){ ///****
GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_1, 0xff);///****
}///****
else{///****
GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_1, 0x00);///****
}///****
flag = !flag;///****
MAP_IntMasterEnable();///****
}
void
UARTIntHandler(void)
{
uint32_t ui32Status,pwm_value;
uint8_t dig1,dig2,dig3,dig4;
//
// Get the interrrupt status.
//
ui32Status = MAP_UARTIntStatus(UART0_BASE, true);
//
// Clear the asserted interrupts.
//
MAP_UARTIntClear(UART0_BASE, ui32Status);
//
// Loop while there are characters in the receive FIFO.
//
uint8_t ind=0;
while(MAP_UARTCharsAvail(UART0_BASE))
{
//
// Read the next character from the UART and write it back to the UART.
//
//MAP_UARTCharPutNonBlocking(UART0_BASE,
// MAP_UARTCharGetNonBlocking(UART0_BASE));
data[ind]=MAP_UARTCharGetNonBlocking(UART0_BASE);
//
// Blink the LED to show a character transfer is occuring.
//
MAP_GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_0, GPIO_PIN_0);
//
// Delay for 1 millisecond. Each SysCtlDelay is about 3 clocks.
//
SysCtlDelay(g_ui32SysClock / (1000 * 3));
//
// Turn off the LED
//
MAP_GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_0, 0);
ind++;
}
if (data[0] == 'L' && data[1] == 'D' && data[2] == '_' && data[3] == 'O' && data[4] == 'N')
{
MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_4, 0xFF);
}
if (data[0] == 'L' && data[1] == 'D' && data[2] == '_' && data[3] == 'O' && data[4] == 'F' && data[5] == 'F')
{
MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_4, 0x00);
}
// if(data[0]=='P' && data[1]=='W' && data[2]=='M'&& data[3]=='_'){
// dig1=data[4]-48;
// dig2=data[5]-48;
// dig3=data[6]-48;
// dig4=data[7]-48;
// pwm_value=dig1*1000+dig2*100+dig3*10+dig4;
// MAP_PWMPulseWidthSet(PWM0_BASE, PWM_OUT_0, pwm_value); ///***
// }
// if(data[0]=='m' && data[1]=='1' && data[2]=='_')
// {
// uint8_t timer_value;
// dig1=data[3]-48;
// dig2=data[4]-48;
// dig3=data[5]-48;
// timer_value= dig1*100 + dig2*10 + dig3;
// MAP_TimerLoadSet(TIMER0_BASE, TIMER_A, 120000000/timer_value);
// MAP_TimerEnable(TIMER0_BASE, TIMER_A); //!
// UARTCharPut(UART0_BASE, 'p');
// UARTCharPut(UART0_BASE, ':');
// UARTCharPut(UART0_BASE, (uint8_t)48+dig1);
// UARTCharPut(UART0_BASE, (uint8_t)48+dig2);
// UARTCharPut(UART0_BASE, (uint8_t)48+dig3);
// }
}
//*****************************************************************************
//
// Send a string to the UART.
//
//*****************************************************************************
void
UARTSend(const uint8_t *pui8Buffer, uint32_t ui32Count)
{
//
// Loop while there are more characters to send.
//
while(ui32Count--)
{
//
// Write the next character to the UART.
//
MAP_UARTCharPutNonBlocking(UART0_BASE, *pui8Buffer++);
}
}
//*****************************************************************************
//
// This example demonstrates how to send a string of data to the UART.
//
//*****************************************************************************
int
main(void)
{
uint32_t ui32PWMClockRate;
//
// Run from the PLL at 120 MHz.
// Note: SYSCTL_CFG_VCO_240 is a new setting provided in TivaWare 2.2.x and
// later to better reflect the actual VCO speed due to SYSCTL#22.
//
g_ui32SysClock = MAP_SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ |
SYSCTL_OSC_MAIN |
SYSCTL_USE_PLL |
SYSCTL_CFG_VCO_240), 120000000);
//
// Enable the GPIO port that is used for the on-board LED.
//
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPION);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM0);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0); ///****
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOJ);//****///
//
// Enable the GPIO pins for the LED (PN0).
//
MAP_GPIOPinTypeGPIOOutput(GPIO_PORTN_BASE, GPIO_PIN_0|GPIO_PIN_1);
MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_4);
MAP_GPIOPinTypeGPIOInput(GPIO_PORTJ_BASE,GPIO_PIN_0); //****///
GPIOPadConfigSet(GPIO_PORTJ_BASE,GPIO_PIN_0,GPIO_STRENGTH_4MA,GPIO_PIN_TYPE_STD_WPU); //****///
//
// Enable the peripherals used by this example.
//
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
//
// Enable processor interrupts.
//
MAP_IntMasterEnable();
GPIOIntTypeSet(GPIO_PORTJ_BASE, GPIO_INT_PIN_0,GPIO_FALLING_EDGE);
GPIOIntRegister(GPIO_PORTJ_BASE,GPIOIntHandler);
GPIOIntEnable(GPIO_PORTJ_BASE, GPIO_INT_PIN_0);
//GPIOIntRegister(uint32_t ui32Port, void (*pfnIntHandler)(void))
//GPIOIntRegisterPin(uint32_t ui32Port, uint32_t ui32Pin,
// void (*pfnIntHandler)(void))
MAP_TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC); ///****
MAP_TimerLoadSet(TIMER0_BASE, TIMER_A, g_ui32SysClock/10);///****periodo del timer
MAP_IntEnable(INT_TIMER0A);///****
MAP_TimerIntEnable(TIMER0_BASE, TIMER_TIMA_TIMEOUT);///****
MAP_TimerEnable(TIMER0_BASE, TIMER_A);///****
//
// Set GPIO A0 and A1 as UART pins.
//
MAP_GPIOPinConfigure(GPIO_PA0_U0RX);
MAP_GPIOPinConfigure(GPIO_PA1_U0TX);
MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
//
// Configure the UART for 115,200, 8-N-1 operation.
//
MAP_UARTConfigSetExpClk(UART0_BASE, g_ui32SysClock, 115200,
(UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
UART_CONFIG_PAR_NONE));
//
// Enable the UART interrupt.
//
MAP_IntEnable(INT_UART0);
MAP_UARTIntEnable(UART0_BASE, UART_INT_RX | UART_INT_RT);
//
// Prompt for text to be entered.
//
UARTSend((uint8_t *)"\033[2JEnter text: ", 16);
//
// Loop forever echoing data through the UART.
//
MAP_GPIOPinConfigure(GPIO_PF0_M0PWM0);
MAP_GPIOPinTypePWM(GPIO_PORTF_BASE, GPIO_PIN_0);
MAP_PWMClockSet(PWM0_BASE, PWM_SYSCLK_DIV_64);
ui32PWMClockRate = g_ui32SysClock / 64;
MAP_PWMGenConfigure(PWM0_BASE, PWM_GEN_0,
PWM_GEN_MODE_DOWN | PWM_GEN_MODE_NO_SYNC);
MAP_PWMGenPeriodSet(PWM0_BASE, PWM_GEN_0, (ui32PWMClockRate / 1000));
MAP_PWMPulseWidthSet(PWM0_BASE, PWM_OUT_0, 1200);
MAP_PWMOutputState(PWM0_BASE, PWM_OUT_0_BIT, true);
MAP_PWMGenEnable(PWM0_BASE, PWM_GEN_0);
while(1)
{
//MAP_PWMPulseWidthSet(PWM0_BASE, PWM_OUT_0, 1800);
}
}
|
package com.nhatthanh.shopping.localData.dao
import androidx.room.*
import com.nhatthanh.shopping.product.model.Cart
import kotlinx.coroutines.flow.Flow
@Dao
interface CartDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertCart(cart: Cart)
@Query("DELETE FROM cart WHERE id =:id")
suspend fun delete(id: Int)
@Query("UPDATE cart SET quantityItem = :quantity WHERE id =:id")
suspend fun updateQuantity(id: Int, quantity: Int)
@Query("SELECT * FROM cart ORDER BY id DESC")
fun getAllCart(): Flow<List<Cart>>
}
|
package com.example.playlistmaker
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.playlistmaker.databinding.ActivitySettingsBinding
import com.google.android.material.switchmaterial.SwitchMaterial
class SettingsActivity : AppCompatActivity() {
private lateinit var binding: ActivitySettingsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySettingsBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.toolbar.setNavigationOnClickListener { finish() }
binding.shareAppIcon.setOnClickListener {
var intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_TEXT, "https://practicum.yandex.ru/android-developer/")
startActivity(intent)
}
binding.supportIcon.setOnClickListener {
val subject = this.getString(R.string.write_support_subject)
val message = this.getString(R.string.write_support_message)
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:")
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]"))
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, message)
startActivity(intent)
}
binding.agreementIcon.setOnClickListener {
val url = Uri.parse("https://yandex.ru/legal/practicum_offer/")
val intent = Intent(Intent.ACTION_VIEW, url)
startActivity(intent)
}
val sharedPreferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE)
binding.themeSwitcher.isChecked = sharedPreferences.getBoolean(DARK_THEME_KEY, false)
binding.themeSwitcher.setOnCheckedChangeListener { switcher, checked ->
(applicationContext as App).switchTheme(checked)
sharedPreferences.edit()
.putBoolean(DARK_THEME_KEY, checked)
.apply()
binding.themeSwitcher.setChecked(checked)
}
}
}
|
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Learn Codeql With L4yn3 | ch1e的自留地</title>
<link rel="shortcut icon" href="https://ch1e.cn/favicon.ico?v=1693578748982">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/fonts/remixicon.css" rel="stylesheet">
<link rel="stylesheet" href="https://ch1e.cn/styles/main.css">
<link rel="alternate" type="application/atom+xml" title="Learn Codeql With L4yn3 | ch1e的自留地 - Atom Feed" href="https://ch1e.cn/atom.xml">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700">
<meta name="description" content="小弟bingbingzi求着我学习Codeql,那就浅学一下,给小弟点面子。
Codeql安装
引擎安装
去https://github.com/github/codeql-cli-binaries/releases 下载对应系统版本的c..." />
<meta name="keywords" content="" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/katex.min.css">
<script src="//cdn.jsdelivr.net/gh/highlightjs/[email protected]/build/highlight.min.js"></script>
</head>
<body>
<div class="main">
<div class="main-content">
<div class="site-header">
<a href="https://ch1e.cn">
<img class="avatar" src="https://ch1e.cn/images/avatar.png?v=1693578748982" alt="">
</a>
<h1 class="site-title">
ch1e的自留地
</h1>
<p class="site-description">
Manners maketh man
</p>
<div class="menu-container">
<a href="/" class="menu">
首页
</a>
<a href="/archives" class="menu">
归档
</a>
<a href="/post/about" class="menu">
关于
</a>
<a href="https://ch1e.cn/post/friends" class="menu">
友链
</a>
</div>
<div class="social-container">
</div>
</div>
<div class="post-detail">
<article class="post">
<h2 class="post-title">
Learn Codeql With L4yn3
</h2>
<div class="post-info">
<span>
2022-10-16
</span>
<span>
13 min read
</span>
</div>
<img class="post-feature-image" src="https://ch1e-img.oss-cn-beijing.aliyuncs.com/img/image-20221016222149948.png" alt="">
<div class="post-content-wrapper">
<div class="post-content" v-pre>
<p>小弟bingbingzi求着我学习Codeql,那就浅学一下,给小弟点面子。</p>
<h1 id="codeql安装">Codeql安装</h1>
<h2 id="引擎安装">引擎安装</h2>
<p>去https://github.com/github/codeql-cli-binaries/releases 下载对应系统版本的codeql引擎,并且添加到环境变量当中,在cmd中输入codeql可以查看是否设置成功</p>
<h2 id="sdk安装">SDK安装</h2>
<pre><code class="language-git">git clone https://github.com/Semmle/ql
</code></pre>
<h2 id="vscode插件">VSCode插件</h2>
<figure data-type="image" tabindex="1"><img src="https://ch1e-img.oss-cn-beijing.aliyuncs.com/img/image-20221016204658168.png" alt="image-20221016204658168" loading="lazy"></figure>
<p>并且在设置当中设置好codeql可执行文件的路径即可</p>
<h1 id="codeql使用">Codeql使用</h1>
<p>使用<a href="https://www.freebuf.com/author/l4yn3l">l4yn3 </a>师傅的靶场 https://github.com/l4yn3/micro_service_seclab/</p>
<p>为了测试刚刚的环境是否可用,用这个靶场来进行测试,命令如下</p>
<pre><code>codeql database create ~/CodeQL/databases/micro-service-seclab-database --language="java" --command="mvn clean install --file pom.xml" --source-root=~/CodeQL/micro-service-seclab/
</code></pre>
<p>这里使用maven编译的时候会导致不成功,可以在pom.xml文件中加入如下代码</p>
<pre><code class="language-xml"> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</code></pre>
<p>先来看看上面的命令的意思,codeql database create就是创建一个数据库,--language就是语言为java,--command就是用这个命令去编译(python和php脚本不需要),--source-root就是项目路径</p>
<p>输入命令以后成功即可在vscode中导入数据库,也就是create后面的那个目录</p>
<figure data-type="image" tabindex="2"><img src="https://ch1e-img.oss-cn-beijing.aliyuncs.com/img/image-20221016205121599.png" alt="image-20221016205121599" loading="lazy"></figure>
<p>然后使用vscode打开我们下载的sdk目录,在java/ql目录下可以新建个test.ql,输入<code>select "hello world"</code>即可测试,部分因为版本原因会报错,这时候需要先在 ql 文件同级目录下创建一个名为 <strong>qlpack.yml</strong>,内容如下:</p>
<pre><code>name: mssql
version: 0.0.1
libraryPathDependencies: codeql/java-all
</code></pre>
<p>然后右键Codeql:run Query即可运行ql文件</p>
<figure data-type="image" tabindex="3"><img src="https://ch1e-img.oss-cn-beijing.aliyuncs.com/img/image-20221016205409506.png" alt="image-20221016205409506" loading="lazy"></figure>
<h1 id="codeql语法">Codeql语法</h1>
<p>QL查询的语法结构为</p>
<pre><code>from [datatype] var
where condition(var = something)
select var
</code></pre>
<p>经常会用到的ql类库如下:</p>
<table>
<thead>
<tr>
<th style="text-align:center">名称</th>
<th style="text-align:center">解释</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">Method</td>
<td style="text-align:center">方法类,Method method表示获取当前项目中所有的方法</td>
</tr>
<tr>
<td style="text-align:center">MethodAccess</td>
<td style="text-align:center">方法调用类,MethodAccess call表示获取当前项目当中的所有方法调用</td>
</tr>
<tr>
<td style="text-align:center">Parameter</td>
<td style="text-align:center">参数类,Parameter表示获取当前项目当中所有的参数</td>
</tr>
</tbody>
</table>
<h2 id="method">Method</h2>
<p>获取项目中定义的所有方法:</p>
<pre><code>import java
from Method method
select method
</code></pre>
<figure data-type="image" tabindex="4"><img src="https://ch1e-img.oss-cn-beijing.aliyuncs.com/img/image-20221016210536254.png" alt="image-20221016210536254" loading="lazy"></figure>
<p>获取名为getStudent的方法名称</p>
<pre><code>import java
from Method method
where method.hasName("getStudent")
select method.getName(),method.getDeclaringType()
</code></pre>
<figure data-type="image" tabindex="5"><img src="https://ch1e-img.oss-cn-beijing.aliyuncs.com/img/image-20221016211112926.png" alt="image-20221016211112926" loading="lazy"></figure>
<pre><code>method.getName() 获取的是当前方法的名称
method.getDeclaringType() 获取的是当前方法所属class的名称。
</code></pre>
<h2 id="谓词">谓词</h2>
<p>类似于函数,其实就和函数差不多。对于上面的案例,可以修改一下</p>
<pre><code>import java
predicate isStudent(Method method){
exists(|method.hasName("getStudent"))
}
from Method method
where isStudent(method)
select method.getName(),method.getDeclaringType()
</code></pre>
<p>predicate表示当前方法没有返回值,exists子查询,根据内部子查询返回true或者false,来筛选出数据</p>
<h2 id="source和sink">Source和Sink</h2>
<blockquote>
<p>什么是source和sink</p>
<p>在代码自动化安全审计的理论当中,有一个最核心的三元组概念,就是(source,sink和sanitizer)。</p>
<p>source是指漏洞污染链条的输入点。比如获取http请求的参数部分,就是非常明显的Source。</p>
<p>sink是指漏洞污染链条的执行点,比如SQL注入漏洞,最终执行SQL语句的函数就是sink(这个函数可能叫query或者exeSql,或者其它)。</p>
<p>sanitizer又叫净化函数,是指在整个的漏洞链条当中,如果存在一个方法阻断了整个传递链,那么这个方法就叫sanitizer。</p>
<p><strong>只有当source和sink同时存在,并且从source到sink的链路是通的,才表示当前漏洞是存在的。</strong></p>
</blockquote>
<p>source通俗的说就是我们可控的变量,Sinkd通俗的说就是危险函数,这也就是代码审计的最基本的可控变量+危险函数。</p>
<h3 id="设置source">设置Source</h3>
<p>codeql中通过下面的代码来设置source</p>
<pre><code>override predicate isSource(DataFlow::Node src) {}
</code></pre>
<p>可以看看我们靶场系统中的source是什么,比如</p>
<pre><code class="language-java">@RequestMapping(value = "/one")
public List<Student> one(@RequestParam(value = "username") String username) {
return indexLogic.getStudent(username);
}
</code></pre>
<p>采用了springboot框架,懂的师傅都知道,我们需要对/one路由传入username参数,在这,username就是source</p>
<pre><code class="language-java">@PostMapping(value = "/object")
public List<Student> objectParam(@RequestBody Student user) {
return indexLogic.getStudent(user.getUsername());
}
</code></pre>
<p>在这source就是user,和类型无关,本例中我们设置Source的代码为:</p>
<pre><code>override predicate isSource(DataFlow::Node src) { src instanceof RemoteFlowSource }
</code></pre>
<p>这是<code>SDK</code>自带的规则,里面包含了大多常用的Source入口。我们使用的SpringBoot也包含在其中, 我们可以直接使用。</p>
<h3 id="设置sink">设置Sink</h3>
<p>在本案例中,我们的sink应该为<code>query</code>方法(Method)的调用(MethodAccess),所以我们设置Sink为:</p>
<pre><code>override predicate isSink(DataFlow::Node sink) {
exists(Method method, MethodAccess call |
method.hasName("query")
and
call.getMethod() = method and
sink.asExpr() = call.getArgument(0)
)
}
</code></pre>
<p>上面查询的意思为:查找一个query()方法的调用点,并把它的第一个参数设置为sink。<br>
在靶场系统(<code>micro-service-seclab</code>)中,sink就是:</p>
<pre><code>jdbcTemplate.query(sql, ROW_MAPPER);
</code></pre>
<h2 id="flow数据流">Flow数据流</h2>
<blockquote>
<p>设置好 Source 和 Sink,就相当于搞定了首尾,但是首尾是否能够连通才能决定是否存在漏洞!</p>
<p>一个受污染的变量,能够毫无阻拦的流转到危险函数,就表示存在漏洞!</p>
</blockquote>
<p>我们通过使用<code>config.hasFlowPath(source, sink)</code>方法来判断是否连通。</p>
<pre><code>from VulConfig config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select source.getNode(), source, sink, "source"
</code></pre>
<h1 id="初步成果">初步成果</h1>
<p>我们使用官方提供的TaintTracking::Configuration方法定义source和sink,至于中间是否是通的,这个后面使用CodeQL提供的<code>config.hasFlowPath(source, sink)</code>来帮我们处理。</p>
<p>我们最终第一版写的demo.ql如下:</p>
<pre><code>/**
* @id java/examples/vuldemo
* @name Sql-Injection
* @description Sql-Injection
* @kind path-problem
* @problem.severity warning
*/
import java
import semmle.code.java.dataflow.FlowSources
import semmle.code.java.security.QueryInjection
import DataFlow::PathGraph
class VulConfig extends TaintTracking::Configuration {
VulConfig() { this = "SqlInjectionConfig" }
override predicate isSource(DataFlow::Node src) { src instanceof RemoteFlowSource }
override predicate isSink(DataFlow::Node sink) {
exists(Method method, MethodAccess call |
method.hasName("query")
and
call.getMethod() = method and
sink.asExpr() = call.getArgument(0)
)
}
}
from VulConfig config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select source.getNode(), source, sink, "source"
</code></pre>
<p>CodeQL语法和Java类似,extends代表集成父类TaintTracking::Configuration。</p>
<p>这个类是官方提供用来做数据流分析的通用类,提供很多数据流分析相关的方法,比如isSource(定义source),isSink(定义sink)</p>
<p>src instanceof RemoteFlowSource 表示src 必须是 RemoteFlowSource类型。在RemoteFlowSource里,官方提供很非常全的source定义,我们本次用到的Springboot的Source就已经涵盖了。</p>
<h1 id="误报解决">误报解决</h1>
<p>在上面的初版代码中,会存在误报,这里的List泛型是Long,不可能注入的</p>
<figure data-type="image" tabindex="6"><img src="https://ch1e-img.oss-cn-beijing.aliyuncs.com/img/image-20221016222149948.png" alt="image-20221016222149948" loading="lazy"></figure>
<p>这说明我们的规则里,对于List<Long>,甚至List<Integer>类型都会产生误报,source误把这种类型的参数涵盖了。可以使用isSanitizer</p>
<blockquote>
<p>isSanitizer是CodeQL的类<code>TaintTracking::Configuration</code>提供的净化方法。它的函数原型是:</p>
<p>override predicate isSanitizer(DataFlow::Node node) {}</p>
<p>在CodeQL自带的默认规则里,对当前节点是否为基础类型做了判断。</p>
<p>override predicate isSanitizer(DataFlow::Node node) {<br>
node.getType() instanceof PrimitiveType or<br>
node.getType() instanceof BoxedType or<br>
node.getType() instanceof NumberType<br>
}</p>
<p>表示如果当前节点是上面提到的基础类型,那么此污染链将被净化阻断,漏洞将不存在。</p>
</blockquote>
<p>所以我们只要在基本的内容上加点特殊的处理即可。</p>
<pre><code>override predicate isSanitizer(DataFlow::Node node) {
node.getType() instanceof PrimitiveType or
node.getType() instanceof BoxedType or
node.getType() instanceof NumberType or
exists(ParameterizedType pt| node.getType() = pt and pt.getTypeArgument(0) instanceof NumberType )
}
</code></pre>
<p>如果当前node节点的类型为基础类型,数字类型和泛型数字类型(比如List)时,就切断数据流,认为数据流断掉了,不会继续往下检测。</p>
<h1 id="漏报解决">漏报解决</h1>
<p>有如下代码</p>
<pre><code class="language-java">public List<Student> getStudentWithOptional(Optional<String> username) {
String sqlWithOptional = "select * from students where username like '%" + username.get() + "%'";
//String sql = "select * from students where username like ?";
return jdbcTemplate.query(sqlWithOptional, ROW_MAPPER);
}
</code></pre>
<p>其中是通过username.get()获取的,应该是这里让他source-sink的链接断了,我们强制接上即可</p>
<figure data-type="image" tabindex="7"><img src="https://ch1e-img.oss-cn-beijing.aliyuncs.com/img/image-20221016222713604.png" alt="image-20221016222713604" loading="lazy"></figure>
<blockquote>
<p>isAdditionalTaintStep方法是CodeQL的类<code>TaintTracking::Configuration</code>提供的的方法,它的原型是:</p>
<p>override predicate isAdditionalTaintStep(DataFlow::Node node1, DataFlow::Node node2) {}</p>
<p>它的作用是将一个可控节点<br>
A强制传递给另外一个节点B,那么节点B也就成了可控节点。</p>
</blockquote>
<pre><code>/**
* @id java/examples/vuldemo
* @name Sql-Injection
* @description Sql-Injection
* @kind path-problem
* @problem.severity warning
*/
import java
import semmle.code.java.dataflow.FlowSources
import semmle.code.java.security.QueryInjection
import DataFlow::PathGraph
predicate isTaintedString(Expr expSrc, Expr expDest) {
exists(Method method, MethodAccess call, MethodAccess call1 | expSrc = call1.getArgument(0) and expDest=call and call.getMethod() = method and method.hasName("get") and method.getDeclaringType().toString() = "Optional<String>" and call1.getArgument(0).getType().toString() = "Optional<String>" )
}
class VulConfig extends TaintTracking::Configuration {
VulConfig() { this = "SqlInjectionConfig" }
override predicate isSource(DataFlow::Node src) { src instanceof RemoteFlowSource }
override predicate isSanitizer(DataFlow::Node node) {
node.getType() instanceof PrimitiveType or
node.getType() instanceof BoxedType or
node.getType() instanceof NumberType or
exists(ParameterizedType pt| node.getType() = pt and pt.getTypeArgument(0) instanceof NumberType )
}
override predicate isSink(DataFlow::Node sink) {
exists(Method method, MethodAccess call |
method.hasName("query")
and
call.getMethod() = method and
sink.asExpr() = call.getArgument(0)
)
}
override predicate isAdditionalTaintStep(DataFlow::Node node1, DataFlow::Node node2) {
isTaintedString(node1.asExpr(), node2.asExpr())
}
}
from VulConfig config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select source.getNode(), source, sink, "source"
</code></pre>
<h1 id="instanceof">instanceof</h1>
<blockquote>
<p>instanceof是用来优化代码结构非常好的语法糖。</p>
<p>我们都知道,我们可以使用exists(|)这种子查询的方式定义source和sink,但是如果source/sink特别复杂(比如我们为了规则通用,可能要适配springboot, Thrift RPC,Servlet等source),如果我们把这些都在一个子查询内完成,比如 condition 1 or conditon 2 or condition 3, 这样一直下去,我们可能后面都看不懂了,更别说可维护性了。<br>
况且有些情况如果一个子查询无法完成,那么就更没法写了。</p>
</blockquote>
<p>instanceof给我们提供了一种机制,我们只需要定义一个abstract class,比如这个案例当中的:</p>
<pre><code>/** A data flow source of remote user input. */
abstract class RemoteFlowSource extends DataFlow::Node {
/** Gets a string that describes the type of this remote flow source. */
abstract string getSourceType();
}
</code></pre>
<p>然后在isSource方法里进行instanceof,判断src是 RemoteFlowSource类型就可以了。</p>
<pre><code>override predicate isSource(DataFlow::Node src) {
src instanceof RemoteFlowSource
}
</code></pre>
<h1 id="lombok问题">Lombok问题</h1>
<p>Lombok会自动生成get和set方法,正常代码就是</p>
<pre><code class="language-java">package com.l4yn3.microserviceseclab.data;
import lombok.Data;
@Data
public class Student {
private int id;
private String username;
private int sex;
private int age;
}
</code></pre>
<p>但是由于lombok的实现机制,导致CodeQL无法获取到lombok自动生成的代码,所以就导致使用了lombok的代码即使存在漏洞,也无法被识别的问题。</p>
<p>还好CodeQL官方的issue里面,有人给出了这个问题的解决办法([查看](https://github.com/github/codeql/issues/4984#:~:text=Unfortunately Lombok does not work with the CodeQL,the source files before running CodeQL as follows%3A))。</p>
<pre><code># get a copy of lombok.jar
wget https://projectlombok.org/downloads/lombok.jar -O "lombok.jar"
# run "delombok" on the source files and write the generated files to a folder named "delombok"
java -jar "lombok.jar" delombok -n --onlyChanged . -d "delombok"
# remove "generated by" comments
find "delombok" -name '*.java' -exec sed '/Generated by delombok/d' -i '{}' ';'
# remove any left-over import statements
find "delombok" -name '*.java' -exec sed '/import lombok/d' -i '{}' ';'
# copy delombok'd files over the original ones
cp -r "delombok/." "./"
# remove the "delombok" folder
rm -rf "delombok"
</code></pre>
<p>上面的代码,实现的功能是:去掉代码里的lombok注解,并还原setter和getter方法的java代码,从而使CodeQL的Flow流能够顺利走下去,从而检索到安全漏洞。</p>
<h1 id="参考">参考</h1>
<p>https://www.freebuf.com/articles/web/283795.html</p>
</div>
<div class="toc-container">
<ul class="markdownIt-TOC">
<li><a href="#codeql%E5%AE%89%E8%A3%85">Codeql安装</a>
<ul>
<li><a href="#%E5%BC%95%E6%93%8E%E5%AE%89%E8%A3%85">引擎安装</a></li>
<li><a href="#sdk%E5%AE%89%E8%A3%85">SDK安装</a></li>
<li><a href="#vscode%E6%8F%92%E4%BB%B6">VSCode插件</a></li>
</ul>
</li>
<li><a href="#codeql%E4%BD%BF%E7%94%A8">Codeql使用</a></li>
<li><a href="#codeql%E8%AF%AD%E6%B3%95">Codeql语法</a>
<ul>
<li><a href="#method">Method</a></li>
<li><a href="#%E8%B0%93%E8%AF%8D">谓词</a></li>
<li><a href="#source%E5%92%8Csink">Source和Sink</a>
<ul>
<li><a href="#%E8%AE%BE%E7%BD%AEsource">设置Source</a></li>
<li><a href="#%E8%AE%BE%E7%BD%AEsink">设置Sink</a></li>
</ul>
</li>
<li><a href="#flow%E6%95%B0%E6%8D%AE%E6%B5%81">Flow数据流</a></li>
</ul>
</li>
<li><a href="#%E5%88%9D%E6%AD%A5%E6%88%90%E6%9E%9C">初步成果</a></li>
<li><a href="#%E8%AF%AF%E6%8A%A5%E8%A7%A3%E5%86%B3">误报解决</a></li>
<li><a href="#%E6%BC%8F%E6%8A%A5%E8%A7%A3%E5%86%B3">漏报解决</a></li>
<li><a href="#instanceof">instanceof</a></li>
<li><a href="#lombok%E9%97%AE%E9%A2%98">Lombok问题</a></li>
<li><a href="#%E5%8F%82%E8%80%83">参考</a></li>
</ul>
</div>
</div>
</article>
</div>
<div class="next-post">
<div class="next">下一篇</div>
<a href="https://ch1e.cn/post/weblogic-cve-2020-2555/">
<h3 class="post-title">
Weblogic CVE-2020-2555
</h3>
</a>
</div>
<div class="site-footer">
Powered by <a href="https://github.com/getgridea/gridea" target="_blank">Gridea</a>
<a class="rss" href="https://ch1e.cn/atom.xml" target="_blank">
<i class="ri-rss-line"></i> RSS
</a>
</div>
</div>
</div>
<script>
hljs.initHighlightingOnLoad()
let mainNavLinks = document.querySelectorAll(".markdownIt-TOC a");
// This should probably be throttled.
// Especially because it triggers during smooth scrolling.
// https://lodash.com/docs/4.17.10#throttle
// You could do like...
// window.addEventListener("scroll", () => {
// _.throttle(doThatStuff, 100);
// });
// Only not doing it here to keep this Pen dependency-free.
window.addEventListener("scroll", event => {
let fromTop = window.scrollY;
mainNavLinks.forEach((link, index) => {
let section = document.getElementById(decodeURI(link.hash).substring(1));
let nextSection = null
if (mainNavLinks[index + 1]) {
nextSection = document.getElementById(decodeURI(mainNavLinks[index + 1].hash).substring(1));
}
if (section.offsetTop <= fromTop) {
if (nextSection) {
if (nextSection.offsetTop > fromTop) {
link.classList.add("current");
} else {
link.classList.remove("current");
}
} else {
link.classList.add("current");
}
} else {
link.classList.remove("current");
}
});
});
</script>
</body>
</html>
|
#include <iostream>
#include <cmath>
#include <random>
#include <chrono>
using namespace std;
static default_random_engine generator;
#define M_PI 3.14159265358979323846
double W(int N, double T, double r, double q, double sigma, double S0) {
normal_distribution<double> dist(0, 1);
double dt = T / N;
vector<double> S;
S.push_back(S0);
double drift = exp(dt * ((r - q) - 0.5 * pow(sigma, 2)));
double vol = sqrt(pow(sigma, 2) * dt);
for (int i = 1; i < N; i++) {
double Z = dist(generator);
S.push_back(S[i - 1] * drift * exp(vol * Z));
}
return S.back();
}
/*
* @brief Monte Carlo Simulation for Call Option Pricing with Standard Error Measure
* @param underlying_price: price of stock/underlying asset
* @param strike_price: strike price of contract
* @param risk_free_interest_rate: risk-free interest rate
* @param time_to_maturity: time until expiration date of contract (assumed contract can only be exercised then)
* @param volatility: volatility of underlying asset
* @param dividend_yield: dividend yield for instruments that pay in dividends
* @param n: number of time steps
* @param m: number of simulations/random variables
* @param stderrorp: optional pointer to store standard error into
* @returns call option price based on Monte Carlo Simulation
*/
double callOptionValue(double underlying_price, double strike_price, double risk_free_interest_rate, double time_to_maturity, double volatility, double dividend_yield, int N, int M, double* stderrorp)
{
// standard error placeholders
double sum_CT = 0.0;
vector<double> simulations;
// run simulations
for (int i = 0; i < M; i++) {
double ST = W(N, time_to_maturity, risk_free_interest_rate, dividend_yield, volatility, underlying_price);
simulations.push_back(ST);
double CT = max(0.0, ST - strike_price);
sum_CT += CT;
}
double C0 = exp(-risk_free_interest_rate * time_to_maturity) * sum_CT / M;
if (stderrorp) {
double sum_CT2 = 0.0;
// calculating sample variance
for (double x : simulations) {
sum_CT2 = pow(x - C0, 2);
}
double SE = sum_CT2 / (M-1);
*stderrorp = SE;
}
return C0;
}
/*
* @brief Monte Carlo Simulation for Put Option Pricing with Standard Error Measure
* @param underlying_price: price of stock/underlying asset
* @param strike_price: strike price of contract
* @param risk_free_interest_rate: risk-free interest rate
* @param time_to_maturity: time until expiration date of contract (assumed contract can only be exercised then)
* @param volatility: volatility of underlying asset
* @param dividend_yield: dividend yield for instruments that pay in dividends
* @param n: number of time steps
* @param m: number of simulations/random variables
* @param stderrorp: optional pointer to store standard error into
* @returns call option price based on Monte Carlo Simulation
*/
double putOptionValue(double underlying_price, double strike_price, double risk_free_interest_rate, double time_to_maturity, double volatility, double dividend_yield, int N, int M, double* stderrorp)
{
// standard error placeholders
double sum_CT = 0.0;
vector<double> simulations;
// run simulations
for (int i = 0; i < M; i++) {
double ST = W(N, time_to_maturity, risk_free_interest_rate, dividend_yield, volatility, underlying_price);
simulations.push_back(ST);
double CT = max(0.0, strike_price - ST);
sum_CT += CT;
}
double C0 = exp(-risk_free_interest_rate * time_to_maturity) * sum_CT / M;
if (stderrorp) {
double sum_CT2 = 0.0;
// calculating sample variance
for (double x : simulations) {
sum_CT2 = pow(x - C0, 2);
}
double SE = sum_CT2 / (M - 1);
*stderrorp = SE;
}
return C0;
}
// Use sieve of Eratosthenes to compute first n primes
vector<int> sieve(int n) {
vector<bool>prime(n*n, true);
vector<int> res;
int p = 2;
for (int i = 0; i <= n; i++) {
while (!prime[p]) p++;
res.push_back(p);
for (int j = p; j < n * n; j += p) {
prime[j] = false;
}
}
return res;
}
double scrambledRadicalInverse(vector<int> perm, int a, int b) {
double reversedDigits = 0;
double invBase = 1.0 / (double) b, invBaseN = 1.0;
while (a > 0) {
// Integer divide to determine how many times base 'b' goes into 'a'
int next = a / b;
// Get integer remainder, determines next digit in sequence
int digit = a - next * b;
// Extend sequence to new digit
reversedDigits = (double) reversedDigits * b + perm[digit];
// Update the power
invBaseN = invBase;
a = next;
}
return reversedDigits * invBaseN;
}
double generate(vector<int>&primes, vector<vector<int>> &perms, int currentDimension, int maxDimension, int globalSample) {
if (currentDimension >= maxDimension) {
default_random_engine generator;
uniform_real_distribution<double> distribution(0.0, 1.0);
return distribution(generator);
}
int base = primes[currentDimension + 1];
return scrambledRadicalInverse(perms[currentDimension], globalSample, base);
}
double boxMuller(double U1, double U2, double mean, double sigma) {
double u = U1 * 2 * M_PI;
return sigma * sqrt(U2) * cos(u) + mean;
}
double haltonPath(int N, double T, double r, double q, double sigma, double S0, vector<int> primes, vector<vector<int>> &perms) {
// dimensions of sampling
int currDim = 0, globalSample = 0;
double dt = T / N;
vector<double> S;
S.push_back(S0);
double drift = exp(dt * ((r - q) - 0.5 * pow(sigma, 2)));
double vol = sqrt(pow(sigma, 2) * dt);
for (int i = 1; i < N; i++) {
double Z1 = generate(primes, perms, currDim, N, globalSample);
globalSample++;
double Z2 = generate(primes, perms, currDim, N, globalSample);
currDim++;
globalSample++;
double Z = boxMuller(Z1, Z2, 0, 1);
S.push_back(S[i - 1] * drift * exp(vol * Z));
}
return S.back();
}
/*
* @brief Monte Carlo Simulation Using Halton Sampling for Call Option Pricing with Standard Error Measure
* @param underlying_price: price of stock/underlying asset
* @param strike_price: strike price of contract
* @param risk_free_interest_rate: risk-free interest rate
* @param time_to_maturity: time until expiration date of contract (assumed contract can only be exercised then)
* @param volatility: volatility of underlying asset
* @param dividend_yield: dividend yield for instruments that pay in dividends
* @param N: number of time steps
* @param M: number of simulations/random variables
* @param stderrorp: optional pointer to store standard error into
* @returns call option price based on Monte Carlo Simulation
*/
double callOptionValueHalton(double underlying_price, double strike_price, double risk_free_interest_rate, double time_to_maturity, double volatility, double dividend_yield, int N, int M, double* stderrorp)
{
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
// standard error placeholders
double sum_CT = 0.0;
vector<double> simulations;
vector<int> primes = sieve(N + 1);
// Pre-compute a permutation for every prime base b
vector<vector<int>> perms;
for (int i = 0; i < N; i++) {
vector<int> row;
for (int j = 0; j < primes[i + 1]; j++) {
row.push_back(j);
}
shuffle(row.begin() + 1, row.end(), default_random_engine(seed));
perms.push_back(row);
}
// run simulations
for (int i = 0; i < M; i++) {
double ST = haltonPath(N, time_to_maturity, risk_free_interest_rate, dividend_yield, volatility, underlying_price, primes, perms);
simulations.push_back(ST);
double CT = max(0.0, ST- strike_price);
sum_CT += CT;
}
double C0 = exp(-risk_free_interest_rate * time_to_maturity) * sum_CT / M;
if (stderrorp) {
double sum_CT2 = 0.0;
// calculating sample variance
for (double x : simulations) {
sum_CT2 = pow(x - C0, 2);
}
double SE = sum_CT2 / (M - 1);
*stderrorp = SE;
}
return C0;
}
/*
* @brief Monte Carlo Simulation Using Halton Sampling for Put Option Pricing with Standard Error Measure
* @param underlying_price: price of stock/underlying asset
* @param strike_price: strike price of contract
* @param risk_free_interest_rate: risk-free interest rate
* @param time_to_maturity: time until expiration date of contract (assumed contract can only be exercised then)
* @param volatility: volatility of underlying asset
* @param dividend_yield: dividend yield for instruments that pay in dividends
* @param N: number of time steps
* @param M: number of simulations/random variables
* @param stderrorp: optional pointer to store standard error into
* @returns put option price based on Monte Carlo Simulation
*/
double putOptionValueHalton(double underlying_price, double strike_price, double risk_free_interest_rate, double time_to_maturity, double volatility, double dividend_yield, int N, int M, double* stderrorp)
{
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
// standard error placeholders
double sum_CT = 0.0;
vector<double> simulations;
vector<int> primes = sieve(N + 1);
// Pre-compute a permutation for every prime base b
vector<vector<int>> perms;
for (int i = 0; i < N; i++) {
vector<int> row;
for (int j = 0; j < primes[i + 1]; j++) {
row.push_back(j);
}
shuffle(row.begin() + 1, row.end(), default_random_engine(seed));
perms.push_back(row);
}
// run simulations
for (int i = 0; i < M; i++) {
double ST = haltonPath(N, time_to_maturity, risk_free_interest_rate, dividend_yield, volatility, underlying_price, primes, perms);
simulations.push_back(ST);
double CT = max(0.0, strike_price - ST);
sum_CT += CT;
}
double C0 = exp(-risk_free_interest_rate * time_to_maturity) * sum_CT / M;
if (stderrorp) {
double sum_CT2 = 0.0;
// calculating sample variance
for (double x : simulations) {
sum_CT2 = pow(x - C0, 2);
}
double SE = sum_CT2 / (M - 1);
*stderrorp = SE;
}
return C0;
}
int main() {
double S = 50.00;
double K = 10.00;
double vol = 0.5;
double r = 0.05;
double T = 3.5;
int N = 100;
int M = 10000;
double q = 0.0;
double* errorfactorCall = (double*) malloc(sizeof(double));
double resultCall = callOptionValue(S, K, r, T, vol, q, N, M, errorfactorCall);
printf("Call option value: %f \n", resultCall);
printf("Standard error: %f \n", *errorfactorCall);
double* errorfactorPut = (double*)malloc(sizeof(double));
double resultPut = putOptionValue(S, K, r, T, vol, q, N, M, errorfactorPut);
printf("Put option value: %f \n", resultPut);
printf("Standard error: %f \n", *errorfactorPut);
resultCall = callOptionValueHalton(S, K, r, T, vol, q, N, M, errorfactorCall);
printf("Call option value: %f \n", resultCall);
printf("Standard error: %f \n", *errorfactorCall);
resultCall = putOptionValueHalton(S, K, r, T, vol, q, N, M, errorfactorPut);
printf("Put option value: %f \n", resultCall);
printf("Standard error: %f \n", *errorfactorPut);
free(errorfactorCall);
free(errorfactorPut);
}
|
/*
* ClassiCraft - ClassiCraftMC
* Copyright (C) 2018-2022.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package nameless.classicraft.event;
import nameless.classicraft.ClassiCraftMod;
import nameless.classicraft.init.ModBlocks;
import nameless.classicraft.init.ModItems;
import net.minecraft.tags.ItemTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.ItemLike;
import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@Mod.EventBusSubscriber(modid = ClassiCraftMod.MOD_ID)
public class FurnaceEvents {
@SubscribeEvent
public static void setFuelValue(FurnaceFuelBurnTimeEvent event) {
handleFuelValue(event, ModItems.TALLOW.get(), 20);
handleFuelValue(event, ItemTags.SAPLINGS, 100);
handleFuelValue(event, ItemTags.LEAVES, 200);
handleFuelValue(event, ModBlocks.THATCH.get(), 200);
handleFuelValue(event, ModBlocks.DRIED_THATCH.get(), 200);
handleFuelValue(event, ModBlocks.THATCH_STAIRS.get(), 200);
handleFuelValue(event, ModBlocks.DRIED_THATCH_STAIRS.get(), 200);
handleFuelValue(event, ModBlocks.THATCH_SLAB.get(), 50);
handleFuelValue(event, ModBlocks.DRIED_THATCH_SLAB.get(), 50);
handleFuelValue(event, ModBlocks.THATCH_CARPET.get(), 20);
handleFuelValue(event, ModBlocks.DRIED_THATCH_CARPET.get(), 20);
handleFuelValue(event, Items.WHEAT, 200);
handleFuelValue(event, ModBlocks.REED.get(), 200);
handleFuelValue(event, ModBlocks.CATTAIL.get(), 200);
handleFuelValue(event, Items.HAY_BLOCK, 1800);
handleFuelValue(event, ModBlocks.THATCH.get(), 1800);
handleFuelValue(event, ModBlocks.DRIED_THATCH.get(), 1800);
handleFuelValue(event, ModBlocks.THATCH_SLAB.get(), 900);
handleFuelValue(event, ModBlocks.DRIED_THATCH_SLAB.get(), 900);
handleFuelValue(event, ModBlocks.THATCH_STAIRS.get(), 1800);
handleFuelValue(event, ModBlocks.DRIED_THATCH_STAIRS.get(), 1800);
handleFuelValue(event, ModBlocks.THATCH_CARPET.get(), 450);
handleFuelValue(event, ModBlocks.DRIED_THATCH_CARPET.get(), 450);
}
private static void handleFuelValue(FurnaceFuelBurnTimeEvent event, ItemLike item, int burnTime) {
var itemStack = event.getItemStack();
if (itemStack.is(item.asItem())) {
event.setBurnTime(burnTime);
}
}
private static void handleFuelValue(FurnaceFuelBurnTimeEvent event, TagKey<Item> item, int burnTime) {
var itemStack = event.getItemStack();
if (itemStack.is(item)) {
event.setBurnTime(burnTime);
}
}
}
|
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { UserProvider } from '../context/UserContext';
import { useEffect } from 'react';
import axios from 'axios';
import Home from './Home';
import Search from './Search';
import PharmaLocator from './PharmLocator';
import BlogPostList from './BlogPostList';
import Login from './Login';
import Register from './Register';
import MyJournal from './MyJournal';
import Drug from './Drug';
import MyDrugList from './MyDrugList';
import BlogPost from './BlogPost';
import Navbar from "./Navbar";
import SaveBlog from "./SaveBlog";
import useApplicationData from "../hooks/useApplicationData";
import '../styles/App.css';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function App() {
// Gather all important helpers and states
// const websocket = new WebSocket('ws://localhost:8080');
const { user, setUser, userInfo, setUserInfo, allBlogs, setAllBlogs, drugs, setDrugs, setCookie, removeCookie, getCookie } = useApplicationData();
const addNotification = (title) => toast(`${title} has been added in blogs`);
// Update all blogs for realtime updates
// useEffect(() => {
// websocket.onopen = () => {
// websocket.onmessage = (event) => {
// const blogs = JSON.parse(event.data);
// if (blogs.type === 'BLOGS') {
// setAllBlogs(blogs.blogs);
// return (blogs.title) ? addNotification(blogs.title) : null;
// }
// };
// };
// }, [websocket.onmessage]);
// When app is refreshed
useEffect(() => {
getCookie()
.then((data) => {
setUser(data.data.id);
setUserInfo(data.data);
return axios.get("/blogs")
})
.then((data) => {
setAllBlogs(data.data);
})
}, []);
// To get all saved meds when user is logged in
useEffect(() => {
if (user) {
Promise.all([
axios.get(`/favourite/${user}`),
]).then((data) => {
setDrugs(data[0].data)
})
}
}, [user]);
// create context file to make api call to get cookie and get cookie from that (context provider)
return (
<div className="App">
<Router>
<Navbar user={user} setUser={setUser} setUserInfo={setUserInfo} userInfo={userInfo} removeCookie={removeCookie} />
<ToastContainer autoClose={3000} />
<UserProvider>
<Routes>
<Route path="*" element={<h1>404 Page Not Found</h1>} />
<Route path="/" element={<Home />} />
<Route path="/search" element={<Search />} />
<Route path="/register" element={<Register setUser={setUser} setUserInfo={setUserInfo} setCookie={setCookie} />} />
<Route path="/login" element={<Login setUser={setUser} setUserInfo={setUserInfo} setCookie={setCookie} />} />
<Route path="/blogs/:id" element={<BlogPost user={user} userInfo={userInfo} /*websocket={websocket}*/ allBlogs={allBlogs} />} />
<Route path="/drugs/*" element={<Drug user={user} drugs={drugs} setDrugs={setDrugs} />} />
<Route path="/pharma" element={<PharmaLocator user={user} />} />
<Route path="/blogs" element={<BlogPostList user={user} allBlogs={allBlogs} setAllBlogs={setAllBlogs} />} />
<Route path="/blogs/add" element={<SaveBlog user={user} allBlogs={allBlogs} setAllBlogs={setAllBlogs} />} />
<Route path="/blogs/edit/*" element={<SaveBlog user={user} allBlogs={allBlogs} setAllBlogs={setAllBlogs} />} />
<Route path="/myjournal" element={<MyJournal user={user} />} />
<Route path="/mydrugs" element={<MyDrugList user={user} drugs={drugs} setDrugs={setDrugs} />} />
</Routes>
</ UserProvider>
</Router>
</div>
);
}
export default App;
|
import React from "react";
import { HashRouter, Route } from "react-router-dom";
import Navigation from "./components/Navigation";
import Home from "./routes/Home";
import About from "./routes/About";
import Detail from "./routes/Detail";
function App() {
return (
<div>
<HashRouter>
<Navigation></Navigation>
<Route path="/" exact={true} component={Home} />
<Route path="/about" exact={true} component={About} />
<Route path="/movie/:id" exact={true} component={Detail} />
</HashRouter>
</div>
);
}
export default App;
|
/*
* $Id$
*
* Authors:
* Jeff Buchbinder <[email protected]>
*
* REMITT Electronic Medical Information Translation and Transmission
* Copyright (C) 1999-2014 FreeMED Software Foundation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.remitt.server;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* Servlet implementation class LoggerServlet
*/
public class LoggerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static final Logger logger = Logger.getLogger(LoggerServlet.class);
/**
* Default constructor.
*/
public LoggerServlet() {
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
System.out.println("LogggerServlet init() starting.");
// Attempt to divine base install, and if we're using jetty, shim it
if (System.getProperty("jetty.home") != null
&& System.getProperty("jetty.home") != "") {
System.setProperty("catalina.home", System
.getProperty("jetty.home"));
}
String log4jfile = getInitParameter("log4j-properties");
System.out.println("log4j-properties: " + log4jfile);
if (log4jfile != null) {
String propertiesFilename = getServletContext().getRealPath(
log4jfile);
System.out.println("Using file " + propertiesFilename);
PropertyConfigurator.configure(propertiesFilename);
logger.info("logger configured.");
} else {
String propertiesFilename = getServletContext().getRealPath(
"/WEB-INF/log4j.properties");
System.out.println("Using file " + propertiesFilename);
PropertyConfigurator.configure(propertiesFilename);
logger.info("logger configured.");
}
System.out.println("LoggerServlet init() done.");
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
|
{{Infobox Anatomy |
Name = Pelvic cavity |
Latin = Cavitas pelvis |
GraySubject = |
GrayPage = |
Image = Scheme body cavities-en.svg |
Caption = |
Image2 = |
Caption2 = |
Precursor = |
System = |
Artery = |
Vein = |
Nerve = |
Lymph = Primarily [[internal iliac lymph nodes]] |
MeshName = |
MeshNumber = |
DorlandsPre = c_16 |
DorlandsSuf = 12220544 |
}}
{{Infobox Bone |
Name = Pelvic cavity |
Latin = Pelvis major |
GraySubject = 58 |
GrayPage = 238-239 |
Image = Gray241.png |
Caption = Male [[pelvis]]. |
Image2 = Gray242.png |
Caption2 = Female [[pelvis]]. |
System = |
MeshName = |
MeshNumber = |
DorlandsPre = p_10 |
DorlandsSuf = 12623257 |
}}
The '''pelvic cavity''' is a [[body cavity]] that is bounded by the bones of the [[pelvis]]. Its oblique roof is the [[pelvic inlet]] (the superior opening of the pelvis). Its lower boundary is the [[pelvic floor]].
The pelvic cavity primarily contains [[reproductive organs]], the [[urinary bladder]], the [[pelvic colon]], and the [[rectum]]. The [[rectum]] is placed at the back of the pelvis, in the curve of the [[sacrum]] and [[coccyx]]; the bladder is in front, behind the [[pubic symphysis]].
In the female, the [[uterus]] and [[vagina]] occupy the interval between these viscera. The pelvic cavity also contains major arteries, veins, muscles, and nerves. These structures have to work together in a little crowded space. They can be affected by many different diseases and by many drugs in many different ways. One part may impact upon another, for example constipation may overload the rectum and compress the urinary bladder, or childbirth might damage the [[Pudendal nerve|pudendal nerves]] and later lead to anal weakness.
==Borders==
[[File:Pelvis.jpg|thumb|right|300px|Pelvis]]
The pevis has an anteroinferior, a posterior and two lateral pelvic walls; and an inferior pelvic wall, also called the [[Pelvic floor]].<ref>Moore, Keith L. et al. (2010) ''Clinically Oriented Anatomy'' 6th Ed, ch.3 ''Pelvis and perineum'', p.339</ref><ref>Richard S. Snell ''Clinical Anatomy By Regions'', ''Pevic cavity'' [http://books.google.com/books?id=vb4AcUL4CE0C&pg=PA242 p.242]</ref> The [[parietal peritoneum]] is attached here and to the [[abdominal wall]].<ref>Tank, P. (2013) ''Grants Dissector'' 15th ed., ch.4 ''The abdomen'', p.99</ref>
=== Lesser pelvis ===
The lesser pelvis (or "true pelvis") is the space enclosed by the [[pelvic girdle]] and below the [[pelvic brim]]: between the [[pelvic inlet]] and the [[pelvic floor]]. This cavity is a short, curved canal, deeper on its posterior than on its anterior wall. Some consider this region to be the entirety of the pelvic cavity. Others define the pelvic cavity as the larger space including the [[#Greater pelvis|greater pelvis]], just above the pelvic inlet.
The lesser pelvis is bounded in front and below by the [[pubic symphysis]] and the [[superior rami of the pubes]]; above and behind, by the sacrum and coccyx; and laterally, by a broad, smooth, quadrangular area of bone, corresponding to the inner surfaces of the body and superior ramus of the [[ischium]], and the part of the [[ilium]] below the [[arcuate line (ilium)|arcuate line]].
{| class="wikitable"
|-
|colspan=3| <center> roof: [[pelvic brim]]<ref name="titleAnatomy of the Female Pelvis - D. El-Mowafi">{{cite web |url=http://www.gfmer.ch/Obstetrics_simplified/anatomy_of_the_female_pelvis.htm |title=Anatomy of the Female Pelvis - D. El-Mowafi |accessdate=2007-12-03 |format= |work=}}</ref> </center>
|-
| posterior: [[sacrum]], [[coccyx]] || lateral: [[obturator internus]] || anterior: [[pubic symphysis]]
|-
|colspan=3| <center> floor: [[pelvic floor]] </center>
|}
The lesser pelvis contains the [[pelvic colon]], [[rectum]], [[Urinary bladder|bladder]], and some of the [[organs of generation]].
The [[rectum]] is at the back, in the curve of the [[sacrum]] and [[coccyx]]; the bladder is in front, behind the [[pubic symphysis]]. In the female, the [[uterus]] and [[vagina]] occupy the interval between these viscera.
The [[pelvic splanchnic nerves]] arising at S2-S4 are in the lesser pelvis.
=== Greater pelvis ===
The greater pelvis (or "false pelvis") is the space enclosed by the [[pelvic girdle]] above and in front of the [[pelvic brim]].
It is bounded on either side by the [[ilium (bone)|ilium]]; in front it is incomplete, presenting a wide interval between the anterior borders of the [[ilium (bone)|ilia]], which is filled by the [[parietes]] of the [[abdomen]]; behind is a deep notch on either side between the ilium and the [[base of the sacrum]].
It is generally considered part of the [[abdominal cavity]] (this is why it is sometimes called the false pelvis).<ref>Drake et al. (2009) Grays Anatomy for Students, 2nd Edition, ch.5 ''Pelvis and perineum - ''general description'', p.406</ref> Some{{who|date=April 2013}} consider this region part of the pelvic cavity,{{cn|date=April 2013}} while others reframe the classification question by calling the combination the [[abdominopelvic cavity]].
The greater pelvis supports the [[intestines]] (specifically, the [[ileum]] and [[sigmoid colon]]), and transmits part of their weight to the anterior wall of the [[abdomen]].
The [[femoral nerve]] from L2-L4 is in the greater pelvis, but not in the lesser pelvis.
==Ligaments==
{| class="wikitable"
| '''Ligament''' || '''From''' || '''To'''
|-
| [[broad ligament of the uterus]] || ||
|-
| * [[mesovarium]] || [[ovary]] ||
|-
| * [[mesosalpinx]] || [[Fallopian tube]] ||
|-
| * [[mesometrium]] || ||
|-
| [[cardinal ligament]] || ||
|-
| [[ovarian ligament]] || ovary || uterus
|-
| [[round ligament of the uterus]] || ||
|-
| [[suspensory ligament of the ovary]] || ||
|}
== Measurements ==
The pelvis can be classified into four main types by measuring the pelvic diameters and conjugates at the pelvic inlet and outlet and as oblique diameters.
[[File:FPC.JPG|thumb|right|300px|Female pelvic cavity]]
{| class="wikitable"
|+ Pelvic measurements<ref>{{cite book
| first = Werner | last = Platzer
| title = Color Atlas of Human Anatomy, Vol. 1: Locomotor System
| publisher = [[Thieme Medical Publishers|Thieme]] | isbn = 3-13-533305-1<!---US: 1-58890-159-9--->
| year = 2004 | edition = 5th |page=190
}}</ref>
! Measurement !! From !! To !! Length
|-
| Transverse diameter<br />(of inlet) || colspan="2" | Between extreme lateral points of pelvic inlet || 13.5-14 cm
|-
| Oblique diameter I || Right [[sacroiliac joint]] || Left iliopubic eminence || 12-12.5 cm
|-
| Oblique diameter II || Left sacroiliac joint || Right iliopubic eminence || 11.5-12 cm
|-
| Anatomical conjugate<br />(true conjugate) || Pubic symphysis || Promontory || ~12 cm
|-
| obsteric conjugate || Retropubic eminence<br />(posterior surface<br />of symphysis) || Promontory || >10 cm
|-
| Diagonal conjugate* || Inferior pubic ligament || Promontory || 11.5-12 cm
|-
| Straight conjugate || Lower border of symphysis || Tip of coccyx || 9.5-10 cm
|-
| Median conjugate || Lower border of symphysis || Lower border of sacrum || 11.5 cm
|-
| Transverse diameter<br />(of outlet) || colspan="2" | Between [[ischial tuberosities]] || 10-11 cm
|-
| Interspinous distance || colspan="2" | Between anterior superior iliac spines || 26 cm<br />(female)
|-
| Intercristal distance || colspan="2" | Between furthest lateral points of [[iliac crest]] || 29 cm<br />(female)
|-
| External conjugate || Spinous process of fifth lumbar vertebra || Upper edge of symphysis || ~20 cm
|-
| Intertrochanteric distance || colspan="2" | Between femurs || 31 cm
|-
| colspan="4" | *Because the true conjugate can not be measured directly it is derived from the diagonal conjugate which is measured through the vagina.
|}
==Arteries==
* [[internal iliac artery]]
* [[median sacral artery]]
* [[ovarian artery]]
==Nerves==
* [[sacral plexus]]
* [[splanchnic nerves]]
* [[femoral nerve]] ([[#Greater pelvis|greater pelvis]])
==Additional images==
<gallery>
Image:Bassin osseux.jpg
Image:Gray319.png|Articulations of pelvis. Anterior view.
Image:Gray539.png|The arteries of the pelvis.
Image:Gray829.png|Dissection of side wall of pelvis showing sacral and pudendal plexuses.
Image:Gray837.png|Sacral plexus of the right side.
Image:Male pelvic cavity.jpg|Male pelvic cavity
Image:Female pelvic cavity.jpg|Female pelvic cavity
Image:Scheme body cavities-en.svg|Body cavities
</gallery>
== References ==
{{reflist}}
{{Gray's}}
==External links==
* [http://www.smbs.buffalo.edu/ana/newpage45.htm Overview at buffalo.edu]
* [http://faculty.southwest.tn.edu/rburkett/human_20.jpg Diagram at southwest.tn.edu]
* [http://www.changbioscience.com/store/images/anatomical/smd070/smd0703.htm Photo of model (female)]
* {{SUNYAnatomyLabs|44|os|05|02}} - "The Male Pelvis: Articulated bones of male pelvis"
* {{SUNYAnatomyLabs|44|os|05|03}}
{{Pelvis}}
{{Torso general}}
[[ru:малый таз]]
[[sv:Stora bäckenet]]
[[sv:Lilla bäckenet]]
|
import torch
import numpy as np
import matplotlib.pyplot as plt
import pytorch3d
from pytorch3d.renderer import look_at_view_transform
from pytorch3d.renderer import OpenGLPerspectiveCameras
from pytorch3d.renderer import (
AlphaCompositor,
RasterizationSettings,
MeshRenderer,
MeshRasterizer,
PointsRasterizationSettings,
PointsRenderer,
PointsRasterizer,
HardPhongShader,
)
import mcubes
def get_device():
"""
Checks if GPU is available and returns device accordingly.
"""
if torch.cuda.is_available():
device = torch.device("cuda:0")
else:
device = torch.device("cpu")
return device
def get_points_renderer(
image_size=512, device=None, radius=0.01, background_color=(1, 1, 1)
):
"""
Returns a Pytorch3D renderer for point clouds.
Args:
image_size (int): The rendered image size.
device (torch.device): The torch device to use (CPU or GPU). If not specified,
will automatically use GPU if available, otherwise CPU.
radius (float): The radius of the rendered point in NDC.
background_color (tuple): The background color of the rendered image.
Returns:
PointsRenderer.
"""
if device is None:
if torch.cuda.is_available():
device = torch.device("cuda:0")
else:
device = torch.device("cpu")
raster_settings = PointsRasterizationSettings(
image_size=image_size,
radius=radius,
)
renderer = PointsRenderer(
rasterizer=PointsRasterizer(raster_settings=raster_settings),
compositor=AlphaCompositor(background_color=background_color),
)
return renderer
def render_points(filename, points, image_size=256, color=[0.7, 0.7, 1], device=None):
# The device tells us whether we are rendering with GPU or CPU. The rendering will
# be *much* faster if you have a CUDA-enabled NVIDIA GPU. However, your code will
# still run fine on a CPU.
# The default is to run on CPU, so if you do not have a GPU, you do not need to
# worry about specifying the device in all of these functions.
if device is None:
device = get_device()
# Get the renderer.
points_renderer = get_points_renderer(image_size=256, radius=0.01)
# Get the vertices, faces, and textures.
# vertices, faces = load_cow_mesh(cow_path)
# vertices = vertices.unsqueeze(0) # (N_v, 3) -> (1, N_v, 3)
# faces = faces.unsqueeze(0) # (N_f, 3) -> (1, N_f, 3)
textures = torch.ones(points.size()).to(device) * 0.5 # (1, N_v, 3)
rgb = textures * torch.tensor(color).to(device) # (1, N_v, 3)
point_cloud = pytorch3d.structures.pointclouds.Pointclouds(
points=points, features=rgb
)
R, T = look_at_view_transform(10.0, 10.0, 96)
# Prepare the camera:
cameras = OpenGLPerspectiveCameras(R=R, T=T, device=device)
rend = points_renderer(point_cloud.extend(2), cameras=cameras)
# Place a point light in front of the cow.
# lights = pytorch3d.renderer.PointLights(location=[[0.0, 1.0, -2.0]], device=device)
# rend = renderer(mesh, cameras=cameras, lights=lights)
rend = rend.detach().cpu().numpy()[0, ..., :3] # (B, H, W, 4) -> (H, W, 3)
plt.imsave(filename, rend)
# The .cpu moves the tensor to GPU (if needed).
return rend
def render_points_with_save(
points, cameras, image_size, save=False, file_prefix="", color=[0.7, 0.7, 1]
):
device = points.device
if device is None:
device = get_device()
# Get the renderer.
points_renderer = get_points_renderer(image_size=image_size[0], radius=0.01)
textures = torch.ones(points.size()).to(device) # (1, N_v, 3)
rgb = textures * torch.tensor(color).to(device) # (1, N_v, 3)
point_cloud = pytorch3d.structures.pointclouds.Pointclouds(
points=points, features=rgb
)
all_images = []
with torch.no_grad():
torch.cuda.empty_cache()
for cam_idx in range(len(cameras)):
image = points_renderer(point_cloud, cameras=cameras[cam_idx].to(device))
image = image[0, :, :, :3].detach().cpu().numpy()
all_images.append(image)
# Save
if save:
plt.imsave(f"{file_prefix}_{cam_idx}.png", image)
return all_images
def get_mesh_renderer(image_size=512, lights=None, device=None):
"""
Returns a Pytorch3D Mesh Renderer.
Args:
image_size (int): The rendered image size.
lights: A default Pytorch3D lights object.
device (torch.device): The torch device to use (CPU or GPU). If not specified,
will automatically use GPU if available, otherwise CPU.
"""
if device is None:
if torch.cuda.is_available():
device = torch.device("cuda:0")
else:
device = torch.device("cpu")
raster_settings = RasterizationSettings(
image_size=image_size,
blur_radius=0.0,
faces_per_pixel=1,
)
renderer = MeshRenderer(
rasterizer=MeshRasterizer(raster_settings=raster_settings),
shader=HardPhongShader(device=device, lights=lights),
)
return renderer
def implicit_to_mesh(
implicit_fn,
scale=0.5,
grid_size=128,
device="cpu",
color=[0.7, 0.7, 1],
chunk_size=262144,
thresh=0,
):
Xs = torch.linspace(-1 * scale, scale, grid_size + 1).to(device)
Ys = torch.linspace(-1 * scale, scale, grid_size + 1).to(device)
Zs = torch.linspace(-1 * scale, scale, grid_size + 1).to(device)
grid = torch.stack(torch.meshgrid(Xs, Ys, Zs), dim=-1)
grid = grid.view(-1, 3)
num_points = grid.shape[0]
sdfs = torch.zeros(num_points)
with torch.no_grad():
for chunk_start in range(0, num_points, chunk_size):
torch.cuda.empty_cache()
chunk_end = min(num_points, chunk_start + chunk_size)
sdfs[chunk_start:chunk_end] = implicit_fn.get_distance(
grid[chunk_start:chunk_end, :]
).view(-1)
sdfs = sdfs.view(grid_size + 1, grid_size + 1, grid_size + 1)
vertices, triangles = mcubes.marching_cubes(sdfs.cpu().numpy(), thresh)
# normalize to [-scale, scale]
vertices = (vertices / grid_size - 0.5) * 2 * scale
vertices = torch.from_numpy(vertices).unsqueeze(0).float()
faces = torch.from_numpy(triangles.astype(np.int64)).unsqueeze(0)
textures = torch.ones_like(vertices) # (1, N_v, 3)
textures = textures * torch.tensor(color) # (1, N_v, 3)
mesh = pytorch3d.structures.Meshes(
verts=vertices,
faces=faces,
textures=pytorch3d.renderer.TexturesVertex(textures),
)
mesh = mesh.to(device)
return mesh
def render_geometry(model, cameras, image_size, save=False, thresh=0.0, file_prefix=""):
device = list(model.parameters())[0].device
lights = pytorch3d.renderer.PointLights(location=[[0, 0, -3]], device=device)
mesh_renderer = get_mesh_renderer(
image_size=image_size[0], lights=lights, device=device
)
mesh = implicit_to_mesh(model.implicit_fn, scale=3, device=device, thresh=thresh)
all_images = []
with torch.no_grad():
torch.cuda.empty_cache()
for cam_idx in range(len(cameras)):
image = mesh_renderer(mesh, cameras=cameras[cam_idx].to(device))
image = image[0, :, :, :3].detach().cpu().numpy()
all_images.append(image)
# Save
if save:
plt.imsave(f"{file_prefix}_{cam_idx}.png", image)
return all_images
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title</title>
</head>
<body>
<div id="app" class="main">
<aa></aa>
<bb></bb>
<p>hello vue</p>
</div>
<script src="./vue.js"></script>
<script>
var aa = {
template: "<h2>{{name}}</h2>",
data: function () {
return {
name: "我是组件aa"
}
}
}
var bb = {
template: "<p>{{name}}</p>",
data: function () {
return {
name: "我是组件bb"
}
}
}
let vm = new Vue({
el: "#app",
data: function () {
return {
name: '根组件'
}
},
components: {
aa, bb
}
})
</script>
</body>
</html>
|
---
layout: post
title: "자바스크립트 변수의 값 검사 방법"
description: " "
date: 2023-09-09
tags: [javascript]
comments: true
share: true
---
자바스크립트에서 변수의 값 검사는 매우 중요합니다. 정확한 값 검사를 통해 프로그램의 안정성과 신뢰성을 확보할 수 있습니다. 이 글에서는 다양한 자바스크립트 변수의 값 검사 방법을 알아보겠습니다.
## 1. typeof 연산자를 사용한 값 검사
자바스크립트에서는 `typeof` 연산자를 사용하여 변수의 타입을 확인할 수 있습니다. 다음은 `typeof` 연산자를 사용하여 변수 `x`의 타입을 검사하는 예시입니다:
```javascript
var x = 10;
console.log(typeof x); // 출력: "number"
x = "Hello";
console.log(typeof x); // 출력: "string"
x = true;
console.log(typeof x); // 출력: "boolean"
```
`typeof` 연산자는 변수의 타입을 문자열로 반환합니다. 이를 통해 변수의 타입에 따라 다른 동작을 수행할 수 있습니다.
## 2. 값이 유효한지 확인하기
자바스크립트에서 값이 유효한지 확인하는 방법은 여러 가지가 있습니다. 가장 간단한 방법은 변수의 값이 `null` 또는 `undefined`인지 확인하는 것입니다. 다음은 변수 `x`의 값이 `null` 또는 `undefined`인지 확인하는 예시입니다:
```javascript
var x = null;
if (x === null || x === undefined) {
console.log("x is null or undefined");
} else {
console.log("x is not null or undefined");
}
```
또한 값을 확인하기 위해 논리 연산자를 사용할 수도 있습니다. 예를 들어, `x`가 `null` 또는 `undefined`이면 `y`에 기본 값을 할당하는 예시를 살펴보겠습니다:
```javascript
var x = null;
var y = x || "default value";
console.log(y); // 출력: "default value"
```
위 코드에서 `x`가 `null` 또는 `undefined`이므로 `y`에는 `"default value"`라는 기본 값이 할당됩니다.
## 3. 배열이 비어있는지 확인하기
배열이 비어있는지 확인하는 방법은 다양합니다. 가장 간단한 방법은 배열의 `length` 속성을 사용하여 길이를 확인하는 것입니다. 다음은 배열이 비어있는지 확인하는 예시입니다:
```javascript
var arr = [];
if (arr.length === 0) {
console.log("Array is empty");
} else {
console.log("Array is not empty");
}
```
또는 배열의 `isArray()` 메소드를 사용하여 배열인지 확인하고, 배열이 비어있는지 검사할 수도 있습니다:
```javascript
var arr = [];
if (Array.isArray(arr) && arr.length === 0) {
console.log("Array is empty");
} else {
console.log("Array is not empty");
}
```
위 코드에서 `Array.isArray(arr)`는 `arr`이 배열인지 확인하고, `arr.length === 0`은 배열이 비어있는지 확인합니다.
## 4. 객체가 비어있는지 확인하기
객체가 비어있는지 확인하는 방법도 여러 가지가 있습니다. 가장 간단한 방법은 객체의 속성 개수를 확인하는 것입니다. 다음은 객체가 비어있는지 확인하는 예시입니다:
```javascript
var obj = {};
if (Object.keys(obj).length === 0) {
console.log("Object is empty");
} else {
console.log("Object is not empty");
}
```
위 코드에서 `Object.keys(obj).length === 0`은 객체에 속성이 없는지 확인합니다.
## 5. 변수가 정의되었는지 확인하기
변수가 정의되었는지 확인하는 방법은 `typeof` 연산자를 사용하여 `undefined`인지 확인하는 것입니다. 다음은 변수가 정의되었는지 확인하는 예시입니다:
```javascript
var x;
if (typeof x === "undefined") {
console.log("x is not defined");
} else {
console.log("x is defined");
}
```
위 코드에서 `typeof x === "undefined"`은 변수 `x`가 정의되지 않았는지 확인합니다.
## 결론
자바스크립트에서 변수의 값 검사는 프로그램의 안정성과 신뢰성을 확보하기 위해 필수적입니다. `typeof` 연산자를 사용하여 변수의 타입을 확인하고, 값이 유효한지, 배열이 비어있는지, 객체가 비어있는지, 변수가 정의되었는지 확인하는 등 다양한 방법을 통해 변수의 값 검사를 수행할 수 있습니다. 올바른 값 검사를 통해 안정적인 자바스크립트 코드를 작성할 수 있습니다.
|
package question1_31;
class Main {
public static void main(String[] args) {
Person person1 = new Person("鈴木", "太郎", 20, 1.7, 60);
Person person2 = new Person("山田", "花子", 22, 1.5, 40);
// car,bicycleをインスタンス化
Car car = new Car();
Bicycle bicycle = new Bicycle();
/* 問題4:MainクラスからsetOwnerを用いて、Carクラスのインスタンス「car」の所有者を「person1」に、
Bicycleクラスのインスタンス「bicycle」の所有者を「person2」に設定します。
Personクラスのインスタンスからフルネームを取得し、ownerにセットしてください。*/
car.setOwner(person1.fullName());
bicycle.setOwner(person2.fullName());
// 問題5:セットできたら、ownerをコンソールに出力してください。
System.out.println(car.getOwner());
System.out.println(bicycle.getOwner());
/* 問題10:Mainクラスからbuyメソッドを用いて、「person1」がcarを購入、
「person2」がbicycleを購入するプログラムを作成しましょう。*/
person1.buy(car);
person2.buy(bicycle);
}
}
|
import React, { Component } from 'react'
import '../../css/Products.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHeart, faPlusSquare } from '@fortawesome/free-solid-svg-icons'
import solo1 from '../../assets/solo1.jpg'
import solo2 from '../../assets/solo2.jpg'
import { Modal } from 'react-bootstrap'
import {
Row,
Col,
Container,
CardDeck,
Card,
Accordion,
Button,
Alert,
} from 'react-bootstrap'
import { Link } from 'react-router-dom'
class Products extends Component {
state = {
sizes: [],
products: [],
wishListAlert: false,
show: false,
imageUrl: '',
}
displayTShirtsOnly = (event) => {
this.setState({
tShirt: true,
})
alert(this.state.tShirt)
}
handleShow = async (title, color) => {
const response = await fetch(
'https://mr-oyebode-backend-yqavh.ondigitalocean.app/product/color-code-image',
{
method: 'POST',
body: JSON.stringify({
title: title,
color: color,
}),
headers: {
'Content-Type': 'application/json',
},
},
)
const details = await response.text()
this.setState({ show: true, imageUrl: details })
}
handleClose = () => {
this.setState({ show: false, imageUrl: '' })
}
// addToWishList = async (id, productImage, productName, productPrice) => {
// const productDetails = {
// productId: id,
// image: productImage,
// name: productName,
// price: parseInt(productPrice),
// }
// if (localStorage['userId']) {
// let response = await fetch(
// `https://mr-oyebode-backend-yqavh.ondigitalocean.app/wishlist/${localStorage['userId']}`,
// {
// method: 'POST',
// body: JSON.stringify(productDetails),
// headers: {
// 'Content-Type': 'Application/json',
// },
// },
// )
// if (response.ok) {
// this.setState({ wishListAlert: true })
// setTimeout(() => {
// this.setState({
// wishListAlert: false,
// })
// }, 1200)
// } else {
// this.setState({ wishListErrorAlert: true })
// setTimeout(() => {
// this.setState({
// wishListErrorAlert: false,
// })
// }, 1200)
// }
// } else if (localStorage['guestToken']) {
// this.setState({ wishListErrorAlert: true })
// setTimeout(() => {
// this.setState({
// wishListErrorAlert: false,
// })
// }, 1200)
// }
// }
render() {
return (
<>
<Container>
<div id="featured-text" className="mt-5">
<h2>Our products</h2>
</div>
<CardDeck>
{this.props.productsAsProps.map((prod) => {
return (
<div className="product-image-wrapper col-sm-4 col-md-6 col-lg-4">
<div className="single-products">
<div className="productinfo text-center">
<img src={prod.imageUrl[0].url} alt="" />
<h2>£ {prod.price}</h2>
<p>{prod.name}</p>
<div className="d-flex justify-content-center">
<Row id="color-code-wrapper">
{prod.stock.map((colorCode) => {
return (
<Col
style={{ backgroundColor: colorCode.colorCode }}
id="color-code"
className="mx-2"
onClick={() =>
this.handleShow(
prod.name,
colorCode.colorCode,
)
}
>
</Col>
)
})}
</Row>
</div>
<button
onClick={() =>
this.props.addToCartAsProps(
prod._id,
prod.imageUrl[0].url,
prod.name,
prod.color,
prod.price,
prod.sizes,
prod.total,
prod.stock,
)
}
className="add-to-cart"
>
<i className="fa fa-shopping-cart"></i>Add to cart
</button>
</div>
{/* <div className="product-overlay">
<div className="overlay-content">
<h2>£ {prod.price}</h2>
<p>{prod.name}</p>
<button
onClick={() =>
this.props.addToCartAsProps(
prod._id,
prod.imageUrl[0].url,
prod.name,
prod.color,
prod.price,
prod.sizes,
prod.total,
prod.stock,
)
}
className="btn btn-default add-to-cart"
>
<i className="fa fa-shopping-cart"></i>Add to cart
</button>
</div>
</div> */}
</div>
<div className="choose">
<div className="d-flex justify-content-between">
<Link to={`/details/${prod._id}`} id="more-details">
<FontAwesomeIcon
icon={faPlusSquare}
className="fa-1x "
/>
More details
</Link>
<Link to to="/allProducts" id="more-details">
<FontAwesomeIcon
icon={faPlusSquare}
className="fa-1x "
/>
View all products
</Link>
</div>
</div>
</div>
)
})}
</CardDeck>
<Modal show={this.state.show} onHide={() => this.handleClose()}>
<Modal.Body>
<div>
<p id="modal-cancel-div" onClick={() => this.handleClose()}>
X
</p>
</div>
<img src={this.state.imageUrl} id="modal-image" />
</Modal.Body>
</Modal>
</Container>
</>
)
}
}
export default Products
|
//
// HomeViewModel.swift
// NetworkApp
//
// Created by Lucas Neves dos santos pompeu on 02/01/24.
//
import Foundation
protocol HomeViewModelProtocol: AnyObject {
func success()
func error(message: String)
}
class HomeViewModel {
private var service: HomeService = HomeService()
private var personList: [Person] = []
private weak var delegate: HomeViewModelProtocol?
public func delegate(delegate: HomeViewModelProtocol?) {
self.delegate = delegate
}
public func fetchRequest() {
service.getPersonList { [weak self] result in
guard let self else { return }
switch result {
case .success(let success):
personList = success
delegate?.success()
case .failure(let failure):
delegate?.error(message: failure.errorDescription ?? "")
}
}
}
public var numberOfRowsInSection: Int {
return personList.count
}
func loadCurrentPerson(indexPath: IndexPath) -> Person {
return personList[indexPath.row]
}
}
|
import { setInformationModal } from "@/store/reducers/globalSlice";
import { QuestionMarkCircleIcon } from "@heroicons/react/20/solid";
import { useDispatch } from "react-redux";
const QuestionButton = ({ body, title }: { body: string; title: string }) => {
const dispatch = useDispatch();
return (
<>
<button
className="hover:text-indigo-500"
onClick={() => {
dispatch(
setInformationModal({
title,
body,
show: true,
})
);
}}
>
<QuestionMarkCircleIcon className="h-5 w-5" />
</button>
</>
);
};
export default QuestionButton;
|
import React from "react";
import { useSelector } from "react-redux";
import { Route, Redirect } from "react-router-dom";
export default function PrivateRoute({ component: Component, ...rest }) {
const { isAuthenticated } = useSelector((state) => state.auth);
return (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/", state: { from: props.location } }} />
)
}
/>
);
}
|
let reloadBooksButton = document.getElementById('reloadBooks');
reloadBooksButton.addEventListener("click", reloadBooks)
let booksContainer = document.getElementById("books-container");
function reloadBooks() {
booksContainer.innerHTML = '';
fetch('http://localhost:8080/api/books')
.then(rsp => rsp.json())
.then(json => json.forEach(book => {
let bookRow = document.createElement('tr');
let titleCol = document.createElement('td');
let authorCol = document.createElement('td');
let isbnCol = document.createElement('td');
let actionBtn = document.createElement('td');
let deleteBtn = document.createElement('button');
titleCol.textContent = book.title;
authorCol.textContent = book.author.name;
isbnCol.textContent = book.isbn;
deleteBtn.textContent = 'Delete';
deleteBtn.dataset.id = book.id;
actionBtn.appendChild(deleteBtn);
bookRow.appendChild(titleCol);
bookRow.appendChild(authorCol);
bookRow.appendChild(isbnCol);
bookRow.appendChild(actionBtn);
booksContainer.appendChild(bookRow)
deleteBtn.addEventListener('click', deleteBtnClicked);
}))
}
function deleteBtnClicked(e) {
let bookId = e.target.dataset.id;
let requestOptions = {
method: 'DELETE'
}
fetch(`http://localhost:8080/api/books/${bookId}`, requestOptions)
.then(_ => reloadBooks())
.catch(error => console.log('error', error));
}
|
from dataclasses import dataclass
from string import Template
from src.general import Material, Boundary
@dataclass(kw_only=True)
class HeatFlowMaterial(Material):
kx: float
ky: float
qv: float
kt: float
def __str__(self):
cmd = Template("hi_addmaterial($materialname, $kx, $ky, $qv, $kt)")
cmd = cmd.substitute(
materialname=f'"{self.material_name}"',
kx=self.kx,
ky=self.ky,
qv=self.qv,
kt=self.kt,
)
return cmd
@dataclass(kw_only=True)
class HeatFlowBaseClass(Boundary):
type: int
Tset: float = 0
qs: float = 0
Tinf: float = 0
h: float = 0
beta: float = 0
def __str__(self):
cmd = Template("hi_addboundprop($propname, $BdryFormat, $Tset, $qs, $Tinf, $h, $beta)")
cmd = cmd.substitute(
propname=f'"{self.name}"',
BdryFormat=self.type,
Tset=self.Tset,
qs=self.qs,
Tinf=self.Tinf,
h=self.h,
beta=self.beta,
)
return cmd
# HeatFlow Boundary Conditions
class HeatFlowFixedTemperature(HeatFlowBaseClass):
def __init__(self, name: str, Tset: float):
self.name = name
self.Tset = Tset
self.type = 0
class HeatFlowHeatFlux(HeatFlowBaseClass):
def __init__(self, name: str, qs: float):
self.name = name
self.qs = qs
self.type = 1
class HeatFlowConvection(HeatFlowBaseClass):
def __init__(self, name: str, Tinf: float, h: float):
self.name = name
self.h = h
self.Tinf = Tinf
self.type = 2
class HeatFlowRadiation(HeatFlowBaseClass):
def __init__(self, name: str, Tinf: float, beta: float):
self.name = name
self.beta = beta
self.Tinf = Tinf
self.type = 3
class HeatFlowPeriodic(HeatFlowBaseClass):
def __init__(self, name: str):
self.name = name
self.type = 4
class HeatFlowAntiPeriodic(HeatFlowBaseClass):
def __init__(self, name: str):
self.name = name
self.type = 5
|
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { OktaAuth } from '@okta/okta-auth-js';
import { Router } from '@angular/router';
import { environment } from '@env/environment';
@Injectable()
export class OktaAuthInterceptor implements HttpInterceptor {
constructor(private oktaAuth: OktaAuth, private router: Router) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (environment.mock && request.method === 'GET') {
request = request.clone({ headers: request.headers.set('Prefer', 'code=200, dynamic=true') });
}
request = request.clone({ headers: request.headers.set('Accept', 'application/json') });
request = request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.oktaAuth.getAccessToken()}` || ''),
});
if (!request.headers.has('Content-Type')) {
request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
}
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401 || error.status === 403) {
this.oktaAuth.closeSession();
this.router.navigate(['/auth/login'], { queryParams: { returnUrl: this.router.url } });
}
return throwError(error);
}),
);
}
}
|
import { ComplexType, add, div, mul, sub } from "./index.ts";
describe("function add", () => {
test("only real number", () => {
const complexNumber1: ComplexType = { real: 1, imag: 0 };
const complexNumber2: ComplexType = { real: 10, imag: 0 };
expect(add(complexNumber1, complexNumber2)).toBe("11");
});
test("only real imag", () => {
const complexNumber1: ComplexType = { real: 0, imag: 1 };
const complexNumber2: ComplexType = { real: 0, imag: 10 };
expect(add(complexNumber1, complexNumber2)).toBe("11i");
});
test("plus number", () => {
const complexNumber1: ComplexType = { real: 1, imag: 4 };
const complexNumber2: ComplexType = { real: 10, imag: 5 };
expect(add(complexNumber1, complexNumber2)).toBe("11+9i");
});
test("minus number", () => {
const complexNumber1: ComplexType = { real: -1, imag: -4 };
const complexNumber2: ComplexType = { real: -10, imag: -5 };
expect(add(complexNumber1, complexNumber2)).toBe("-11-9i");
});
});
describe("function sub", () => {
test("only real number", () => {
const complexNumber1: ComplexType = { real: 10, imag: 0 };
const complexNumber2: ComplexType = { real: 1, imag: 0 };
expect(sub(complexNumber1, complexNumber2)).toBe("9");
});
test("only real imag", () => {
const complexNumber1: ComplexType = { real: 0, imag: 10 };
const complexNumber2: ComplexType = { real: 0, imag: 1 };
expect(sub(complexNumber1, complexNumber2)).toBe("9i");
});
test("plus number and show -i", () => {
const complexNumber1: ComplexType = { real: 1, imag: 4 };
const complexNumber2: ComplexType = { real: 10, imag: 5 };
expect(sub(complexNumber1, complexNumber2)).toBe("-9-i");
});
test("minus number and show +i ", () => {
const complexNumber1: ComplexType = { real: -1, imag: -4 };
const complexNumber2: ComplexType = { real: -10, imag: -5 };
expect(sub(complexNumber1, complexNumber2)).toBe("9+i");
});
});
describe("function mul", () => {
test("test mul", () => {
const complexNumber1: ComplexType = { real: 1, imag: -4 };
const complexNumber2: ComplexType = { real: -10, imag: 5 };
expect(mul(complexNumber1, complexNumber2)).toBe("10+45i");
});
});
describe("function div", () => {
test("test div", () => {
const complexNumber1: ComplexType = { real: 1, imag: -4 };
const complexNumber2: ComplexType = { real: -10, imag: 5 };
expect(div(complexNumber1, complexNumber2)).toBe("-0.24+0.28i");
});
});
|
<%--
Document : student
Created on : 29 Oct 2023, 12:06:16
Author : user
--%>
<%@include file="header.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div class="jumborton bg-white text-center">
<h1>ADD STUDENT</h1>
</div>
<div class="mx-4 mb-5">
<form class="row g-3" action="StudentProcess.jsp" method="post">
<div class="col-12">
<label for="sName" class="form-label" >First Name</label>
<input type="text" class="form-control" id="sName" name="sName">
</div>
<div class="col-md-6">
<label for="email" class="form-label" >Email</label>
<input type="email" class="form-control" id="email" name="email">
</div>
<div class="col-md-6">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="col-md-6">
<label for="gender" class="form-label">Gender</label>
<div class="form-check">
<input class="form-check-input" type="radio" value="Male" name="gender" id="gender">
<label class="form-check-label" for="Male">
Male
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" value="Female" id="gender" >
<label class="form-check-label" for="Female">
Female
</label>
</div>
</div>
<div class="col-12">
<label for="address" class="form-label">Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="1234 Main St">
</div>
<div class="col-md-6">
<label for="city" class="form-label">City</label>
<input type="text" class="form-control" id="city" name="city">
</div>
<div class="col-md-4">
<label for="state" class="form-label">State</label>
<select id="state" class="form-select" name="state">
<option selected>Open this select menu</option>
<option value="Dhaka">Dhaka</option>
<option value="Rajshahi">Rajshahi</option>
<option value="Khulna">Khulna</option>
</select>
</div>
<div class="col-md-2">
<label for="inputZip" class="form-label">Zip</label>
<input type="text" class="form-control" id="inputZip" name="zip">
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Check me out
</label>
</div>
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
<div class="col-md-6">
<button type="reset" class="btn btn-danger">Reset</button>
</div>
</form>
</div>
</body>
</html>
<%@include file="footer.jsp" %>
|
import React from 'react';
import { CodeEditor, Language } from '@patternfly/react-code-editor';
import { Text, Form, Title, Alert } from '@patternfly/react-core';
import { useAppDispatch, useAppSelector } from '../../../../store/hooks';
import {
selectFirstBootScript,
setFirstBootScript,
} from '../../../../store/wizardSlice';
const detectScriptType = (scriptString: string): Language => {
const lines = scriptString.split('\n');
if (lines[0].startsWith('#!')) {
// Extract the path from the shebang
const path = lines[0].slice(2);
if (path.includes('bin/bash') || path.includes('bin/sh')) {
return Language.shell;
} else if (path.includes('bin/python') || path.includes('bin/python3')) {
return Language.python;
} else if (path.includes('ansible-playbook')) {
return Language.yaml;
}
}
// default
return Language.shell;
};
const FirstBootStep = () => {
const dispatch = useAppDispatch();
const selectedScript = useAppSelector(selectFirstBootScript);
const language = detectScriptType(selectedScript);
return (
<Form>
<Title headingLevel="h1" size="xl">
First boot configuration
</Title>
<Text>
Configure the image with a custom script that will execute on its first
boot.
</Text>
<Alert
variant="warning"
isExpandable
isInline
title="Important: please do not include sensitive information"
>
<Text>
Please ensure that your script does not contain any secrets,
passwords, or other sensitive data. All scripts should be crafted
without including confidential information to maintain security and
privacy.
</Text>
</Alert>
<CodeEditor
isUploadEnabled
isDownloadEnabled
isCopyEnabled
isLanguageLabelVisible
language={language}
onCodeChange={(code) => dispatch(setFirstBootScript(code))}
code={selectedScript}
height="35vh"
/>
</Form>
);
};
export default FirstBootStep;
|
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import mysql from 'mysql2';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
app.use(express.static(join(__dirname, '../build')));
app.get('/', (req, res) => {
res.sendFile(join(__dirname, '../build', 'index.html'));
});
const PORT = process.env.PORT || 31491
const connection = mysql.createConnection({
host: '9z6n6e.stackhero-network.com',
user: 'root',
port: 3306,
password: '6z6P1Dadytt24aFQkxjvgljQW4G4Ydgm',
database: 'root',
entities: [],
synchronize: true,
ssl: {}
});
connection.connect((err) => {
if (err) {
console.error('Errore durante la connessione al database:', err);
} else {
setInterval(() => connection.ping(), 120 * 1000);
console.log('Connessione al database MySQL riuscita!');
}
});
app.use(cors());
app.use(bodyParser.json());
app.get('/api/match', (req, res) => {
const sql = `SELECT partita.ID, partita.partita, partita.data, COUNT(ticket.partitaID) AS bigliettiDisponibili, MIN(ticket.prezzo) AS prezzoMin FROM partita LEFT JOIN ticket ON partita.ID = ticket.partitaID GROUP BY partita.ID;`;
connection.query(sql, (error, results, fields) => {
if (error) {
console.error('Errore nella query:', error);
res.status(500).send('Errore nel server.');
} else {
res.json(results);
}
});
});
app.get('/api/tickets', (req, res) => {
const partitaID = req.query.matchID;
const sql = 'SELECT * FROM ticket WHERE partitaID = ?';
connection.query(sql, [partitaID], (error, results, fields) => {
if (error) {
console.error('Errore nella query:', error);
res.status(500).send('Errore nel server.');
} else {
res.json(results);
}
});
});
app.get('/api/infoUser', (req, res) => {
const userName = req.query.userName;
const sql = 'SELECT * FROM user WHERE username = ?';
connection.query(sql, [userName], (error, results, fields) => {
if (error) {
console.error('Errore nella query:', error);
res.status(500).send('Errore nel server.');
} else {
res.json(results);
}
});
});
app.get('/api/login', (req, res) => {
const userName = req.query.userName;
const pwd = req.query.password;
const sql = 'SELECT * FROM user WHERE username = ? and password = ?';
connection.query(sql, [userName, pwd], (error, results, fields) => {
if (error) {
console.error('Errore nella query:', error);
res.status(500).send('Errore nel server.');
} else {
if (results.length > 0) res.json(results);
else res.status(401).send('Username o password sbagliati.');
}
});
});
app.post('/api/register', (req, res) => {
const userName = req.body.userName;
const sql = 'SELECT * FROM user WHERE username = ?';
connection.query(sql, [userName], (error, results, fields) => {
if (error) {
res.status(500).send('Errore nel server.');
} else {
if (results.length > 0) {
res.status(400).send('Username già esistente.');
return
}
else {
const pwd = req.body.password;
const nome = req.body.nome || ''
const cognome = req.body.cognome || ''
const instagram = req.body.instagram || ''
const cellulare = req.body.cellulare || ''
const email = req.body.email || ''
const created = req.body.created;
const sql = 'INSERT INTO user (username, nome, cognome, mail, instagram, cellulare, password, created_date) VALUES (?,?,?,?,?,?,?,?)';
connection.query(sql, [userName, nome, cognome, email, instagram, cellulare, pwd, created], (error, results) => {
if (error) {
console.log(error)
res.status(500).send('Errore nel server.');
} else {
const sql = 'SELECT * FROM user WHERE username = ?';
connection.query(sql, [userName], (error, results, fields) => {
if (error) {
console.error('Errore nella query:', error);
res.status(500).send('Errore nel server.');
} else {
if (results.length > 0) res.json(results);
else res.status(401).send('Username o password sbagliati.');
}
});
}
});
}
}
});
});
app.post('/api/editUser', (req, res) => {
const userName = req.body.userName;
const pwd = req.body.password;
const new_pwd = req.body.nuova_password || pwd
const nome = req.body.nome || ''
const cognome = req.body.cognome || ''
const instagram = req.body.instagram || ''
const cellulare = req.body.cellulare || ''
const email = req.body.email || ''
const sqlCheck = 'SELECT * FROM user WHERE username = ? and password = ?';
connection.query(sqlCheck, [userName, pwd], (error, results, fields) => {
if (error) {
console.error('Errore nella query:', error);
res.status(500).send('Errore nel server.');
} else {
if (results.length > 0) {
const sql = 'UPDATE user set password = ?, nome = ?, cognome = ?, mail = ?, instagram = ?, cellulare = ? WHERE username = ?';
connection.query(sql, [new_pwd, nome, cognome, email, instagram, cellulare, userName], (error, results) => {
if (error) {
console.log(error)
res.status(500).send('Errore nel server.');
} else {
const sql = 'SELECT * FROM user WHERE username = ?';
connection.query(sql, [userName], (error, results, fields) => {
if (error) {
console.error('Errore nella query:', error);
res.status(500).send('Errore nel server.');
} else {
res.json(results);
}
});
}
});
}
else res.status(401).send('Username o password sbagliati.')
}
});
});
app.post('/api/tickets', (req, res) => {
const userName = req.body.userName;
const partitaID = req.body.partitaID;
const anello = req.body.anello;
const colore = req.body.colore;
const settore = req.body.settore;
const fila = req.body.fila;
const posti = req.body.posti
const necessariaTdt = req.body.necessariaTdt
const prezzo = req.body.prezzo || null
const sql = 'INSERT INTO ticket (partitaID, user, anello, colore, settore, fila, posti, necessariaTdt, prezzo) VALUES (?,?,?,?,?,?,?,?,?)';
connection.query(sql, [partitaID, userName, anello, colore, settore, fila, posti, necessariaTdt, prezzo], (error, results) => {
if (error) {
console.log(error)
res.status(500).send('Errore nel server.');
} else {
const sql = 'SELECT * FROM ticket WHERE id = LAST_INSERT_ID()';
connection.query(sql, [], (error, results, fields) => {
if (error) {
res.status(500).send('Errore nel server.');
} else {
res.json(results);
}
});
}
});
});
app.post('/api/deleteTickets', (req, res) => {
const ticketID = req.body.ticketID;
const sql = 'DELETE FROM ticket WHERE id = ?';
connection.query(sql, [ticketID], (error, results) => {
if (error) {
console.log(error)
res.status(500).send('Errore nel server.');
} else {
res.json(results);
}
});
});
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
|
---
import Layout from "../../layouts/Layout.astro";
import { getProjectPageData, getNextProject } from "../../sanity/api";
import PortableText from "../../components/utils/portableText.astro";
import { Image } from "astro:assets";
import EpisodePlayer from "../../components/projects/episodePlayer.astro";
import ProjectMedia from "../../components/projects/projectMedia.astro";
import CornerTopLeft from "../../components/cornerPieces/cornerTopLeft.astro";
import CornerBottomRight from "../../components/cornerPieces/cornerBottomRight.astro";
import CornerBottomLeft from "../../components/cornerPieces/cornerBottomLeft.astro";
import CornerTopRight from "../../components/cornerPieces/cornerTopRight.astro";
import Footer from "../../components/footer.astro";
import NextProject from "../../components/projects/nextProject.astro";
const pages = await getProjectPageData();
const { slug } = Astro.params;
const page = pages.find((page) => page.slug === slug);
if (!page) return Astro.redirect("/404");
const {
title,
awardArray,
awardImageArray,
clientArray,
creditsArray,
servicesArray,
description,
secondaryDescription,
thumbnail,
video,
episodeArray,
mediaArray,
} = page;
const currentProjectTitle = title;
const nextProjectData = await getNextProject(currentProjectTitle);
// if (nextProjectData) {
// console.log("Next project data:", nextProjectData);
// } else {
// console.log("No next project found.");
// }
---
<Layout>
<section class="main-video__wrapper">
<video
class="main-video"
preload="metadata"
loop="true"
controls
muted="true"
poster={thumbnail}
>
<source src={video} type="video/mp4" />
Your browser does not support the video tag.
</video>
</section>
<section class="project-details__wrapper">
<div class="project-details__flex">
<div class="project-details-left">
<div>
<h1>{title}</h1>
{
clientArray != null && (
<div class="project-details-item clients-item">
<p class="item-title">Clients</p>
{clientArray.map((client) => {
return <p>{client}</p>;
})}
</div>
)
}
</div>
<div class="project-details-left-bottom">
{
awardArray != null && (
<>
<p class="item-title">Clients</p>
<div class="project-details-item item-two-col">
{awardArray.map((award) => {
return <p>{award}</p>;
})}
</div>
</>
)
}
{
awardImageArray != null && (
<div class="project-details-awards-images">
{awardImageArray.map((award) => {
return (
<Image
quality={25}
inferSize
src={award.imageSrc}
alt="Image of an award badge"
class="award-image"
/>
);
})}
</div>
)
}
</div>
</div>
<div class="project-details-right">
{
description != null && (
<div class="project-details-overview">
<h5>Project Overview</h5>
<p>
<PortableText data={description} />
</p>
</div>
)
}
<div class="project-details-credits">
{
servicesArray != null && (
<div class="project-details-item">
<p class="item-title">Services</p>
{servicesArray.map((service) => {
return <p>{service}</p>;
})}
</div>
)
}
{
creditsArray != null && (
<div class="project-details-item">
<p class="item-title">Credits</p>
{creditsArray.map((credit) => {
return <p>{credit}</p>;
})}
</div>
)
}
</div>
</div>
</div>
</section>
{
episodeArray != null && (
<section class="episode__wrapper">
<EpisodePlayer episodeData={episodeArray} />
</section>
)
}
{
secondaryDescription != null && (
<section class="project-overview__wrapper">
<div class="project-overview-text">
<PortableText data={secondaryDescription} />
</div>
</section>
)
}
{
mediaArray !== null && (
<section class="project-media__wrapper">
<CornerTopLeft />
<CornerTopRight />
<CornerBottomLeft />
<CornerBottomRight />
<ProjectMedia mediaArray={mediaArray} />
</section>
)
}
{
nextProjectData !== null && (
<section>
<div class="sticky-gradient" />
<NextProject nextProjectData={nextProjectData} />
</section>
)
}
<Footer />
</Layout>
<style>
.main-video__wrapper {
position: relative;
width: 100%;
height: 90vh;
}
.main-video {
aspect-ratio: 16/9;
height: 100%;
width: 100%;
}
.project-details__wrapper {
color: var(--white);
margin: 4rem;
}
.project-details__flex {
display: flex;
justify-content: space-between;
}
.project-details-left {
flex: 2;
display: flex;
justify-content: space-between;
flex-direction: column;
}
.project-details-left-bottom {
margin-top: 4rem;
}
.item-two-col {
column-count: 2;
column-gap: 1.5rem;
width: 500px;
}
.project-details-awards-images {
margin-top: 2rem;
display: flex;
flex-wrap: wrap;
gap: 2rem;
opacity: 0.5;
max-width: 40vw;
}
.award-image {
height: 100px;
width: auto;
}
.project-details-right {
color: var(--white);
flex: 1;
display: flex;
justify-content: space-between;
flex-direction: column;
}
.project-details-overview {
& h5 {
margin-bottom: 2rem;
}
}
.project-details-credits {
margin-top: 2rem;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 2rem;
}
.project-details-item {
color: rgba(var(--rgb-white), 0.5);
}
.clients-item {
margin-top: 2rem;
}
.item-title {
color: var(--white);
margin-bottom: 1rem;
}
.episode__wrapper {
position: relative;
width: 100%;
}
.project-overview__wrapper {
color: var(--white);
width: var(--inner-width);
margin: 4rem auto;
}
.project-overview-text {
margin-top: 2rem;
column-count: 3;
column-gap: 1.5rem;
width: 100%;
}
.project-media__wrapper {
position: relative;
width: calc(100% - 1rem * 2);
margin: 1rem;
}
.sticky-gradient {
z-index: 11;
position: sticky;
top: 0;
left: 0;
width: 100%;
height: 200px;
background: linear-gradient(
0deg,
rgba(0, 0, 0, 0) 21.56%,
rgba(0, 0, 0, 0.25) 48.54%,
#000 100%
);
}
@media (max-width: 992px) {
.project-details-left {
display: none;
}
.project-details__wrapper,
.project-overview__wrapper {
margin: 1rem;
}
.project-overview-text {
column-count: 1;
}
.sticky-gradient {
display: none;
}
}
</style>
|
from abc import ABC, abstractmethod
class AbstractStorage(ABC):
@abstractmethod
def add(self, name: str, amount: int) -> None:
...
@abstractmethod
def remove(self, name: str, amount: int) -> None:
...
@abstractmethod
def get_free_space(self) -> int:
...
@abstractmethod
def get_items(self) -> dict[str, int]:
...
@abstractmethod
def get_unique_items_count(self) -> int:
...
|
using System.ComponentModel;
namespace MudBlazor
{
/// <summary>
/// The flex-wrap CSS property sets whether flex items are forced onto one line or
/// can wrap onto multiple lines. If wrapping is allowed, it sets the direction that lines are stacked.
/// </summary>
public enum Wrap
{
/// <summary>
/// This is the default value.
/// The flex items are laid out in a single line which may cause the flex container to overflow.
/// The cross-start is either equivalent to start or before depending on the flex-direction value.
/// </summary>
[Description("nowrap")]
NoWrap,
/// <summary>
/// The flex items break into multiple lines. The cross-start is either equivalent to start or before
/// depending flex-direction value and the cross-end is the opposite of the specified cross-start.
/// </summary>
[Description("wrap")]
Wrap,
/// <summary>
/// Behaves the same as wrap but cross-start and cross-end are permuted.
/// </summary>
[Description("wrap-reverse")]
WrapReverse
}
}
|
import java.util.ArrayList;
import java.util.List;
public class VirtualThreadsDemo {
private static final int NUMBER_OF_VIRTUAL_THREADS = 20;
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () -> System.out.println("내부 스레드 : " + Thread.currentThread());
// 기존 스레드 = 플랫폼 스레드
// Thread platformThead = new Thread(runnable);
// Thread platformThread = Thread.ofPlatform().unstarted(runnable);
//
// platformThread.start(); // 내부 스레드 : Thread[#21,Thread-0,5,main]
// platformThread.join();
// 가상 스레드
// Thread virtualThread = Thread.ofVirtual().unstarted(runnable);
// virtualThread.start(); // 내부 스레드 : VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1
// virtualThread.join();
// 가상의 스레드 여러개 실행
List<Thread> virtualThreads = new ArrayList<>();
for (int i = 0; i < NUMBER_OF_VIRTUAL_THREADS; i++) {
Thread virtualThead = Thread.ofVirtual().unstarted(runnable);
virtualThreads.add(virtualThead);
}
for (Thread virtualThread : virtualThreads) {
virtualThread.start();
// 내부 스레드 : VirtualThread[#22]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1
}
for (Thread virtualThread : virtualThreads) {
virtualThread.join();
}
// 20개로 늘렸을 때 가상 스레드는 각각의 ID를 가지지만
// 플랫폼 스레드는 5개만 생성하고 연결되는 걸 볼 수 있다.
// 내부 스레드 : VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1
// 내부 스레드 : VirtualThread[#29]/runnable@ForkJoinPool-1-worker-3
// 내부 스레드 : VirtualThread[#23]/runnable@ForkJoinPool-1-worker-3
// 내부 스레드 : VirtualThread[#24]/runnable@ForkJoinPool-1-worker-3
// 내부 스레드 : VirtualThread[#34]/runnable@ForkJoinPool-1-worker-5
// 내부 스레드 : VirtualThread[#26]/runnable@ForkJoinPool-1-worker-3
// 내부 스레드 : VirtualThread[#27]/runnable@ForkJoinPool-1-worker-3
// 내부 스레드 : VirtualThread[#28]/runnable@ForkJoinPool-1-worker-3
// 내부 스레드 : VirtualThread[#22]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#30]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#31]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#32]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#33]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#35]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#36]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#37]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#38]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#39]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#40]/runnable@ForkJoinPool-1-worker-2
// 내부 스레드 : VirtualThread[#25]/runnable@ForkJoinPool-1-worker-4
}
}
|
/***
* @Author: insbread
* @Date: 2022-07-20 17:16:14
* @LastEditTime: 2022-07-20 17:16:15
* @LastEditors: insbread
* @Description: 静态vector数组,数组大小固定
* @FilePath: /elsa-server/SDK/include/container/elsac_array_list.h
* @版权声明
*/
#pragma once
#include <cstring>
#include <assert.h>
#include "container/elsac_vector.h"
namespace ElsaNContainer
{
template <typename T, int MAX_NUM>
class ElsaCStaticArrayList
{
protected:
T m_pDataPtr[MAX_NUM];
int m_iCount;
public:
ElsaCStaticArrayList()
{
m_iCount = 0;
};
virtual ~ElsaCStaticArrayList()
{
m_iCount = 0;
};
inline operator T *() { return m_pDataPtr; }
inline operator T *() const { return m_pDataPtr; }
int Size() const { return m_iCount; }
int Count() const { return m_iCount; }
int MaxSize() const { return MAX_NUM; }
// 在数组末尾追加一个数字,并返回所在的索引
int Add(const T &data)
{
assert(m_iCount + 1 <= MAX_NUM); // 保证还有空位置
memcpy(m_pDataPtr + m_iCount, &data, sizeof(T));
m_iCount++;
return m_iCount - 1;
}
// 在数组末尾追加一个数字,并返回所在的索引
int PushBack(const T &data)
{
return Add(data);
}
// 在idx处插入数据data
void Insert(const int idx, const T &data)
{
assert(idx >= 0 && idx <= m_iCount); // 确保索引合法
assert(m_iCount + 1 <= MAX_NUM); // 确保有空闲位置
if (idx < m_iCount)
{
memmove(m_pDataPtr + idx + 1, m_pDataPtr + idx, sizeof(T) * (m_iCount - idx));
}
m_pDataPtr[idx] = data;
m_iCount++;
}
inline const T &Get(const int index) const
{
assert(index >= 0 && index < m_iCount);
return m_pDataPtr[index];
}
inline void Set(const int index, const T &data)
{
assert(index >= 0 && index < m_iCount);
m_pDataPtr[index] = data;
}
void Remove(const int index, const int num)
{
assert(index >= 0 && index + num - 1 <= m_iCount);
if (num > 0)
{
memmove(m_pDataPtr + index, m_pDataPtr + index + num, sizeof(T) * (m_iCount - index - num));
m_iCount -= num;
}
}
void Remove(const int index)
{
assert(index >= 0 && index < m_iCount); // 这里会顺便检测是否为空,因为为空的话assert永远为false
Remove(index, 1);
}
inline void Clear()
{
m_iCount = 0;
}
inline void Trunc(const int num)
{
assert(num >= 0 && num <= MAX_NUM);
m_iCount = num;
}
inline void AddArray(const T *data, int length)
{
assert(m_iCount + length <= MAX_NUM);
if (length > 0)
{
memcpy(m_pDataPtr + m_iCount, data, sizeof(T) * length);
m_iCount += length;
}
}
inline void AddList(const ElsaCVector<T> &list)
{
AddArray((T *)list, list.Count());
}
// 从后往前搜索数组,返回逆序第一个找到data的下标
int Index(const T &data) const
{
for (int i = m_iCount - 1; i >= 0; i--)
{
if (m_pDataPtr[i] == data)
{
return i;
}
}
return -1;
}
};
};
// #define TEST_DEBUG
#ifdef TEST_DEBUG
using namespace ElsaNContainer;
inline void ElsaCStaticArrayListTestFuc()
{
ElsaCVector<int> vec;
ElsaCStaticArrayList<int, 200> tm;
for (int i = 0; i < 10; i++)
{
tm.PushBack(i * 2);
vec.Push(i + 21);
}
for (int i = 0; i < tm.Count(); i++)
printf("%d ", tm[i]);
puts("\n");
tm.Insert(1, 1);
tm.Insert(3, 3);
for (int i = 0; i < tm.Count(); i++)
printf("%d ", tm[i]);
puts("\n");
tm.Set(0, 100);
tm.Set(1, 200);
for (int i = 0; i < tm.Count(); i++)
printf("%d ", tm[i]);
puts("\n");
tm.Remove(0, 2);
tm.Remove(tm.Count() - 1, 1);
for (int i = 0; i < tm.Count(); i++)
printf("%d ", tm[i]);
puts("\n");
tm.AddList(vec);
for (int i = 0; i < tm.Count(); i++)
printf("%d ", tm[i]);
puts("\n");
printf("idx of 10 : %d\n", tm.Index(10));
return;
}
#endif
|
package pokeregions.monsters.act1.allyPokemon;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.actions.defect.AnimateOrbAction;
import com.megacrit.cardcrawl.actions.defect.ChannelAction;
import com.megacrit.cardcrawl.actions.defect.EvokeOrbAction;
import com.megacrit.cardcrawl.actions.defect.EvokeWithoutRemovingOrbAction;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.localization.CardStrings;
import pokeregions.BetterSpriterAnimation;
import pokeregions.PokemonRegions;
import pokeregions.cards.AbstractAllyPokemonCard;
import pokeregions.monsters.AbstractPokemonAlly;
import pokeregions.orbs.MewtwoDark;
import static pokeregions.PokemonRegions.makeMonsterPath;
import static pokeregions.util.Wiz.atb;
public class Mewtwo extends AbstractPokemonAlly
{
public static final String ID = PokemonRegions.makeID(Mewtwo.class.getSimpleName());
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
public static final String NAME = cardStrings.NAME;
public Mewtwo(final float x, final float y, AbstractAllyPokemonCard allyCard) {
super(NAME, ID, 100, -5.0F, 0, 150.0f, 130.0f, null, x, y);
this.animation = new BetterSpriterAnimation(makeMonsterPath("Mewtwo/Mewtwo.scml"));
this.animation.setFlip(true, false);
this.allyCard = allyCard;
setStaminaInfo(allyCard);
move1Intent = Intent.MAGIC;
move2Intent = Intent.BUFF;
addMove(MOVE_1, move1Intent);
addMove(MOVE_2, move2Intent);
defaultMove = MOVE_1;
}
@Override
public void takeTurn() {
super.takeTurn();
switch (this.nextMove) {
case MOVE_1: {
atb(new ChannelAction(new MewtwoDark(pokeregions.cards.pokemonAllyCards.act1.Mewtwo.MOVE_1_INCREASE)));
break;
}
case MOVE_2: {
atb(new AbstractGameAction() {
@Override
public void update() {
halfDead = true;
this.isDone = true;
}
});
for (int i = 0; i < pokeregions.cards.pokemonAllyCards.act1.Mewtwo.MOVE_2_EFFECT - 1; i++) {
atb(new AnimateOrbAction(1));
atb(new EvokeWithoutRemovingOrbAction(1));
}
atb(new AnimateOrbAction(1));
atb(new EvokeOrbAction(1));
break;
}
}
postTurn();
}
}
|
import { faAngleDown, faAngleRight } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Link from "next/link";
export type sidebarProps = {
state: [boolean, React.Dispatch<React.SetStateAction<boolean>>];
projects: Array<{ name: string; slug: string }>;
title: string;
};
export default function SidebarLink({ projects, title, state }: sidebarProps) {
const [selected, setSelected] = state;
return (
<div>
<button
className="text-lg font-semibold"
onClick={() => setSelected(!selected)}
>
<FontAwesomeIcon
icon={selected ? faAngleDown : faAngleRight}
className="mr-2 h-4 w-4"
/>
<span>{title}</span>
</button>
{selected && (
<ul className="ml-6">
{projects.map(({ name, slug }, i) => (
<li key={i}>
<Link href={`/portfolio/${slug}`}>{name}</Link>
</li>
))}
</ul>
)}
</div>
);
}
|
package com.clay.springcloud.controller;
import com.clay.springcloud.entities.CommonResult;
import com.clay.springcloud.entities.Payment;
import com.clay.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
@RestController
@Slf4j
public class PaymentController {
@Autowired
public PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping(value = "/payment/discovery")
public Object discovery(){
List<String> services = discoveryClient.getServices();
for (String element : services) {
log.info("***** element:"+element);
}
List<ServiceInstance> instances = discoveryClient.getInstances("cloud-provider-payment");
for (ServiceInstance instance : instances) {
log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
}
return this.discoveryClient;
}
@PostMapping("/payment/create")
public CommonResult create(@RequestBody Payment payment){
boolean save = paymentService.save(payment);
if (save){
return CommonResult.succes("端口:"+serverPort);
}
return CommonResult.fail();
}
@GetMapping("/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Integer id){
Payment payment = paymentService.getById(id);
return CommonResult.succes("端口:"+serverPort,payment);
}
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
return serverPort;
}
@GetMapping(value = "/payment/feign/timeOut")
public String timeOut(){
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return serverPort;
}
@GetMapping("/payment/zipkin")
public String paymentZipkin()
{
return "hi ,i'am paymentzipkin server fall back,welcome to atguigu,O(∩_∩)O哈哈~";
}
}
|
//
// 二叉树中和为某一个值的路径.swift
// HT_LeetCode
//
// Created by 陈竹青 on 2020/11/25.
//
import Foundation
/**
题目: 二叉树中和为某一个值的路径
题目分析:
要获取二叉树中路径之后为某值,我们就需要遍历所有路径,然后判断是否为指定某个值,如果是我们就保存到数组中。
利用二叉树的前序遍历的方法就可以
**/
func testSumEqualTo() -> Void {
//构建一个二叉树用于测试
/*
1
/ \
2 3
/ \ / \
4 5 6 7
/
8
*/
let node1 = TreeNode(1)
let node2 = TreeNode(2)
let node3 = TreeNode(3)
let node4 = TreeNode(4)
let node5 = TreeNode(5)
let node6 = TreeNode(6)
let node7 = TreeNode(7)
let node8 = TreeNode(8)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
node6.right = node8
var list : [TreeNode] = []
inorderTreeToSum(node: node1, target: 10, current: 0, paths: &list)
}
func inorderTreeToSum(node: TreeNode?,target: Int ,current: Int, paths: inout [TreeNode]) -> Void {
guard let n = node else {
return
}
//保存当前节点
paths.append(n)
//计算当前节点的和
let sum = current + n.val
//判断是否满足条件,如果满足条件打印出路劲
if sum == target {
print("************")
for p in paths {
print("\(p.val)->")
}
}
//遍历左子树
inorderTreeToSum(node: n.left, target: target, current: sum, paths: &paths)
//遍历右子树
inorderTreeToSum(node: n.right, target: target, current: sum, paths: &paths)
//回溯到上一个节点,需要把最后一个节点删除。
if paths.count > 0 {
paths.removeLast()
}
}
|
import {CreateUserDTO} from "../../dtos/CreateUserDTO";
import {prisma} from "../../../../prisma/client";
import { User } from "@prisma/client";
import {AppError} from "../../../../errors/AppError";
const bcrypt = require("bcryptjs");
export class CreateUserUseCase {
async execute( { nome, email, password }:CreateUserDTO ): Promise<User>
{
const userExists = await prisma.user.findUnique(
{
where: {
email
}
}
);
if (userExists) {
throw new AppError("Este email já foi usado para cadastro!");
}
password = await bcrypt.hash(password, 8);
const user = await prisma.user.create(
{
data: {
nome,
email,
password
}
}
);
return user;
}
}
|
---
title: Schema management in Kafka
date: 2020-05-27
---
Kafka stores records as binary data. When stored on the broker, it is simply a stream of bytes. There needs to be a contract between publishers and subscribers to know how to encode/decode a message in a topic. The encoding/decoding is also known as serialization/deserialization.
For Kafka, a widely adopted serialization format is Avro. All messages stored within a topic should be encoded with same or similar schemas to avoid compatibility issues.
## Serialization/Deserialization
How to encode and publish a message (Publisher side)
1. Get the avro schema
2. Create an encoder for that schema
3. Encode the message using schema
4. Push the encoded bytes to the broker
How to consume the message (Consumer side)
1. Get the avro schema
2. Create a decoder for the schema
3. Read the bytes from the broker
4. Use the decoder to recover back the message
There are Avro libraries/SDK available in all major languages. Avro schema is a standard format represented as a JSON. You can read more about Avro [here](https://avro.apache.org/).
If you follow the steps above, there are 2 major aspects of reading and writing from Kafka. One is creating the encoder/decoder which is made easier thanks to Avro libraries available to us. The other aspect is the contract between publishers and consumers of a topic to make sure they both have a consistent schema to refer to when reading/writing those messages. If A publishes messages using schema 1 and B tries to decode it using schema 2, it can be interpreted in a very different way which defeats the purpose of sharing the information.
Once the 2 parties (or multiple) decide on the schema or format, they can store that schema locally in their application and read/write from Kafka asynchronously. However, when the publisher wishes to alter the schema by adding/deleting a field or type conversions, they have to relay that information to everyone who is associated with that topic. This is where schema management becomes important. A common store to share and store schemas would make life much easier.
## Schema Registry
Confluent introduced a schema store they called Schema Registry. It is a distributed metadata store that provides a RESTful interface to store and retrieve schemas. It supports Avro, JSON, Protobuf schemas that can be shared among all consumers and publishers. It is provided as a separate service and can be deployed with or without Kafka platform.
### Registering a schema
A JSON based schema can be registered as a HTTP POST request. Every schema is assigned a unique **schema ID** that can serve as an identifier for a schema. If you try to register the same schema again, it will simply return the same schema ID of the original one. The schema IDs are monotonically increasing as you add more schemas.
In a Kafka topic, the key and the value can both have different schemas. Schema registry supports topic schemas based on the topic name and whether it is a key or a value. The combination of topic and key/value identifier is what is called _subject_. Schemas can evolve in a compatible way to support multiple formats for a topic.
### Fetching a schema
A schema is identified either by the subject or schemaID. A simple GET request with a subject or a schema ID parameter will return a JSON based format that can be saved and used by the decoder.
### Embedding schema ID in Kafka messages
A common pratice followed across the industry is embedding schemaID to every Kafka message. The first byte is a 0x0 character followed by 4 bytes representing the schemaID and the rest of the message is the encoded bytes.
Kafka message with schema ID 35 would look like below:
`00 00 00 00 23 21 22 .....`
The first byte is the null byte, the next 4 bytes are 0x23 (35) followed by encoded bytes.
This approach doesnt add more than 4 bytes of overhead to your message and can get the schema using the schema ID for every message independently. The schema fetched can be cached to avoid fetching schema on every message and only fetched when it has evolved in the middle.
|
# Diabetic Management Mobile App

Welcome to the Diabetic Management Mobile App project! This mobile app is designed to help individuals with diabetes manage their condition more effectively. The app provides users with tools and features to monitor their blood sugar levels, track medication intake, record food consumption, and receive valuable insights to better manage their health.
## Features
The Diabetic Management Mobile App comes with the following features:
1. **Blood Sugar Tracking**: Users can record their blood sugar levels at different times of the day and track the trends over time.
2. **Medication Reminders**: The app allows users to set reminders for taking their medications, ensuring they never miss a dose.
3. **Food Journal**: Users can keep a record of their meals and snacks, including carbohydrate counts and mealtime notes.
4. **Activity Monitoring (Optional)**: In future iterations, we plan to add activity tracking to help users monitor their physical activity levels.
5. **Insights and Analytics (Future Development)**: The app aims to provide users with valuable insights and analytics based on their data to identify patterns and make informed decisions.
## Frontend
The frontend of the mobile app has been developed using Flutter, a powerful and flexible framework for building native mobile applications for Android and iOS platforms. The user interface (UI) and user experience (UX) have been designed to be intuitive and user-friendly, with a focus on delivering a smooth and responsive experience.
## Backend (Work in Progress)
The next phase of development involves building the backend for the app. We plan to use Node.js with Express to create a robust and scalable backend that will handle user authentication, data storage, and provide APIs for the frontend to interact with the server.
## Project Setup
To set up the app on your local machine, follow these steps:
1. Clone the repository from GitHub: [project-repository-url](https://github.com/octorose/D-one2.git).
2. Install the required dependencies by following the instructions provided in the `README` file of the project.
3. Run the app on your preferred mobile device simulator or physical device.
## Contribution Guidelines
We welcome contributions to this open-source project. If you want to contribute, follow these guidelines:
1. Fork the project repository to your GitHub account.
2. Create a new branch from the `main` branch for each feature or bug fix.
3. Make your changes and additions, ensuring that the code is well-documented and follows best practices.
4. Test your changes locally to avoid any potential issues.
5. Once you are confident with your changes, create a pull request to merge your branch into the `main` branch.
6. Discuss your changes with the maintainers and incorporate feedback to improve the project.
7. Be respectful and collaborative in the development process.
## Future Roadmap
As this project progresses, we have some exciting features planned for future development:
- Integration with Continuous Glucose Monitoring (CGM) devices to enable real-time data tracking.
- Enhanced data visualization to help users better understand their health trends.
- Integration with health professionals to provide personalized recommendations and support.
- Multi-language support to make the app accessible to a wider user base.
Thank you for your interest in the Diabetic Management Mobile App project. Together, we can make a positive impact on the lives of individuals managing diabetes. Happy coding!
|
# Standard-Setup-Win10
Powershell script wich configures some general settings on a windows 10 system
### Version:
5.0 - First Mature Release
### Usage:
This script runs multiple functions that configure a computer as described in the Standard-Configuration of Root Service AG.
You can get more Details with the "Get-Help" command.
### Disclaimer:
Most of the sections are copied from the internet and changed so that they fit to our Standard configuration.
### What's new:
Cleaner Code
Better Logging
RemoveApps via CSV
## Comming next version
Rewrite everything to english
### Comment-Legend:
* "#[]" - organizational
* "#XX" - Features (With numbers)
* "#T" - Todo
### Link:
https://github.com/TheOtherOne0101/Standard-Setup-Win10
## Sources
In the following list you find links to the Sources of parts of the Code (Microsoft Docs are not included):
* [How to use Parameters I](https://www.red-gate.com/simple-talk/sysadmin/powershell/how-to-use-parameters-in-powershell/)
* [How to use Parameters II](https://www.red-gate.com/simple-talk/sysadmin/powershell/how-to-use-parameters-in-powershell-part-ii/)
* [How to add Help to Scripts](https://www.red-gate.com/simple-talk/sysadmin/powershell/how-to-add-help-to-powershell-scripts/)
* [InternetVerbindungtesten](https://learn-powershell.net/2011/02/07/quick-hits-test-internet-access/)
* [AlleDesktopsymboleanzeigen](https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Show-Desktop-4c0f9630)
* [StandardProgrammeinstallieren](https://forum.pulseway.com/topic/1930-install-adobe-reader-dc-with-powershell/)
* [Windowsaktivieren](https://blogs.technet.microsoft.com/rgullick/2013/06/13/activating-windows-with-powershell/)
* [DeleteWindows.old](https://gallery.technet.microsoft.com/scriptcenter/How-to-Delete-the-912d772b)
* [Benutzer mit Profil löschen](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/remove-localuser?view=powershell-5.1)
* [Laufwerke umbenennen](https://winaero.com/blog/change-drive-label-rename-drive-windows-10/)
* [Computer Umbenennen](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/rename-computer?view=powershell-6)
* [Energieoptionen ändern](https://stackoverflow.com/questions/44921510/change-power-plan-to-high-performance)
* [Remote Dekstop aktivieren](https://www.interfacett.com/blogs/methods-to-enable-and-disable-remote-desktop-locally/)
* [OneDrive aus Autostart entfernen](https://stackoverflow.com/questions/18946024/powershell-removing-a-specific-registry-key)
* [Systemeigenschaften anpassen](https://social.technet.microsoft.com/Forums/ie/en-US/bf986cda-e3f0-4744-9a1a-b20ba71764a1/how-do-i-create-a-directory-in-powershell)
* [Systemeigenschaften anpassen](https://devblogs.microsoft.com/scripting/use-powershell-to-copy-files-and-folders-to-a-new-location/)
* [NumLock automatisch setzen](https://stackoverflow.com/questions/9794893/powershell-toggle-num-lock-on-and-off)
* [Sprachleiste ausblenden, nur DE-CH](https://stackoverflow.com/questions/47539292/remove-language-from-windows-10-using-powershell)
* [Sprachleiste ausblenden, nur DE-CH](https://stackoverflow.com/questions/56080275/why-do-we-need-brackets-in-this-example)
* [Fernwartung auf Desktops und in C:/root/ reinkopieren](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-6)
* [Vorinstallierten Windows Müll entfernen](https://community.spiceworks.com/scripts/show/4711-remove-junk-apps-from-windows-10)
* [Unötige Programme deinstallieren ](http://lifeofageekadmin.com/how-to-uninstall-programs-using-powershell/)
* [Alle Kacheln entfernen](https://superuser.com/questions/1068382/how-to-remove-all-the-tiles-in-the-windows-10-start-menu)
|
/**
* ByteBuffer
* ------------------------------------------------------------------
* Copyright (c) Chi-Tai Dang
*
* @author Chi-Tai Dang
* @version 1.0
* @remarks
*
* This file is part of the Environs framework developed at the
* Lab for Human Centered Multimedia of the University of Augsburg.
* http://hcm-lab.de/environs
*
* Environ is free software; you can redistribute it and/or modify
* it under the terms of the Eclipse Public License v1.0.
* A copy of the license may be obtained at:
* http://www.eclipse.org/org/documents/epl-v10.html
* --------------------------------------------------------------------
*/
#include "stdafx.h"
#define ENVIRONS_NATIVE_MODULE
/// Compiler flag that enables verbose debug output
#ifndef NDEBUG
//# define DEBUGVERB
//# define DEBUGVERBVerb
#endif
#include "Byte.Buffer.h"
#include "Environs.Obj.h"
#ifndef WINDOWS_PHONE
# include <string.h>
#endif
#include "Environs.Lib.h"
#include "Environs.Native.h"
#include "Environs.Mobile.h"
#define CLASS_NAME "Byte.Buffer. . . . . . ."
/* Namespace: environs -> */
namespace environs
{
bool disposeJBuffer ( void * buffer );
namespace API
{
/*
* Class: hcm_environs_Environs
* Method: GetBufferHeaderSize
* Signature: ()I
*/
ENVIRONSAPI jint EnvironsProc ( GetBufferHeaderSizeN )
{
return ( SIZE_OF_BYTEBUFFER + BUFFER_PREFIX_SIZE );
}
/*
* Class: hcm_environs_Environs
* Method: GetBufferHeaderBytesToSize
* Signature: ()I
*/
ENVIRONSAPI jint EnvironsProc ( GetBufferHeaderBytesToSizeN )
{
return SIZE_OF_BYTEBUFFER_TO_SIZE;
}
/*
* Class: hcm_environs_Environs
* Method: GetBufferHeaderBytesToType
* Signature: ()I
*/
ENVIRONSAPI jint EnvironsProc ( GetBufferHeaderBytesToTypeN )
{
return SIZE_OF_BYTEBUFFER_TO_TYPE;
}
/*
* Class: hcm_environs_Environs
* Method: GetBufferHeaderBytesToStartValue
* Signature: ()I
*/
ENVIRONSAPI jint EnvironsProc ( GetBufferHeaderBytesToStartValueN )
{
return SIZE_OF_BYTEBUFFER_TO_STARTVALUE;
}
}
ByteBuffer * allocBuffer ( unsigned int capacity )
{
CVerbVerbArg ( "allocBuffer: allocate capacity of %i", capacity );
ByteBuffer * buffer = 0;
unsigned int size = capacity + SIZE_OF_BYTEBUFFER + 8;
#ifdef ANDROID
int status;
JNIEnv *env;
bool isAttached = false;
if ( !g_JavaVM || !g_java_mallocID || !g_EnvironsClass ) {
CErr ( "allocBuffer: Failed to call from jni to java - invalid jni resources!" );
return 0;
}
status = g_JavaVM->GetEnv ( ( void ** ) &env, JNI_VERSION_1_6 );
if ( status < 0 ) {
//CInfo ( "allocBuffer: No JNI environment available, assuming native thread." );
status = g_JavaVM->AttachCurrentThread ( &env, 0 );
if ( status < 0 ) {
CErr ( "allocBuffer: failed to attach current thread" );
return 0;
}
isAttached = true;
}
if ( !env ) {
CErr ( "allocBuffer: failed to get JNI environment" );
return 0;
}
jobject jByteBuffer = ( jobject ) env->CallStaticObjectMethod ( g_EnvironsClass, g_java_mallocID, size, true );
if ( jByteBuffer ) {
buffer = ( ByteBuffer * ) env->GetDirectBufferAddress ( jByteBuffer );
if ( !buffer ) {
CErr ( "allocBuffer: Failed to get reference to memory of the shared buffer!" );
disposeJBuffer ( jByteBuffer );
}
else {
// Initialize header of ByteBuffer
// ByteBuffer * header = (ByteBuffer *) buffer;
memset ( buffer, 0, SIZE_OF_BYTEBUFFER );
// Save capacity of buffer
buffer->capacity = capacity;
jobject jByteBufferGlobal = env->NewGlobalRef ( jByteBuffer );
if ( !jByteBufferGlobal ) {
CErr ( "allocBuffer: Failed to get GLOBAL reference to memory of the shared buffer!" );
disposeJBuffer ( jByteBuffer );
}
else {
buffer->managed.reference = jByteBufferGlobal;
}
}
}
if ( isAttached )
g_JavaVM->DetachCurrentThread ();
#else
buffer = ( ByteBuffer * ) calloc ( 1, size );
if ( buffer ) {
// Save capacity of buffer
( ( ByteBuffer * ) buffer )->capacity = capacity;
}
#endif
CVerbVerbArg ( "allocBuffer: done (%s)", buffer == 0 ? "failed" : "success" );
return buffer;
}
bool disposeBuffer ( ByteBuffer * buffer )
{
if ( !buffer ) {
CErr ( "disposeBuffer: invalid memory buffer parameter! (NULL)" );
return false;
}
CVerbVerb ( "disposeBuffer: disposing buffer" );
#ifdef ANDROID
return disposeJBuffer ( ( void * ) buffer->managed.reference );
#else
free ( buffer );
return true;
#endif
}
#ifdef ANDROID
bool disposeJBuffer ( void * buffer )
{
CVerbVerb ( "disposeBuffer" );
int status;
JNIEnv *env;
bool isAttached = false;
if ( !buffer ) {
CErr ( "disposeBuffer: invalid memory buffer parameter! (NULL)" );
return false;
}
if ( !g_JavaVM || !g_java_freeID || !g_EnvironsClass ) {
CErr ( "disposeBuffer: Failed to call from jni to java - invalid jni resources!" );
return false;
}
status = g_JavaVM->GetEnv ( ( void ** ) &env, JNI_VERSION_1_6 );
if ( status < 0 ) {
//CInfo ( "disposeBuffer: No JNI environment available, assuming native thread" );
status = g_JavaVM->AttachCurrentThread ( &env, 0 );
if ( status < 0 ) {
CErr ( "disposeBuffer: failed to attach current thread" );
return false;
}
isAttached = true;
}
if ( !env ) {
CErr ( "disposeBuffer: failed to get JNI environment" );
return false;
}
status = env->CallStaticBooleanMethod ( g_EnvironsClass, g_java_freeID, buffer );
env->DeleteGlobalRef ( ( jobject ) buffer );
if ( isAttached )
g_JavaVM->DetachCurrentThread ();
CVerbVerbArg ( "disposeBuffer: done with status %i", status );
return status;
}
#endif
ByteBuffer * relocateBuffer ( ByteBuffer * buffer, bool dispose, unsigned int capacity )
{
CVerbVerb ( "relocateBuffer" );
if ( buffer && buffer->capacity >= capacity )
return buffer;
ByteBuffer * newBuffer = allocBuffer ( capacity );
if ( !newBuffer )
return 0;
if ( buffer && dispose )
disposeBuffer ( buffer );
return newBuffer;
}
jobject allocJByteBuffer ( JNIEnv * jenv, unsigned int capacity, char * &buffer )
{
CVerbVerbArg ( "allocJByteBuffer: allocate capacity of %i", capacity );
jobject jByteBuffer;
#ifdef ANDROID
jByteBuffer = ( jobject ) jenv->CallStaticObjectMethod ( g_EnvironsClass, g_java_mallocID, capacity, false );
if ( jByteBuffer ) {
buffer = ( char * ) jenv->GetDirectBufferAddress ( jByteBuffer );
if ( !buffer ) {
CErr ( "allocJByteBuffer: Failed to get reference to memory of the shared buffer!" );
}
}
#else
buffer = ( char * ) malloc ( capacity );
jByteBuffer = buffer;
#endif
CVerbVerbArg ( "allocJByteBuffer: done (%s)", buffer == 0 ? "failed" : "success" );
return jByteBuffer;
}
void releaseJByteBuffer ( jobject &buffer )
{
#ifndef ANDROID
if ( buffer ) {
free ( buffer );
buffer = 0;
}
#endif
}
} // <- namespace environs
|
require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const seedDB = require('./seed');
const cors = require('cors');
const quotesRoutes = require('./api/quoteRoutes');
const authRoutes = require('./api/authRoutes');
const MONGODBURL = process.env.MONGODBURL;
mongoose.connect(MONGODBURL)
.then( ()=> {
console.log('DB connected successfully')
})
.catch( (err)=> {
console.log(err);
})
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(cookieParser());
app.use(cors( {origin: ["https://quote-vista-front.vercel.app", "http://localhost:3000"] , credentials: true}))
app.use(quotesRoutes);
app.use(authRoutes);
app.get('/hello' , (req , res)=> {
res.status(200).json({msg: 'hello from quotes app'});
})
// seedDB();
app.listen(8080 , ()=> {
console.log('server connected at port 8080')
})
|
#include "Form.hpp"
#include "Bureaucrat.hpp"
#include <iostream>
Form::~Form() {}
Form::Form()
: _name("<No-Name>"), _isSigned(false), _gradeRequiredToSign(1),
_gradeRequiredToExecute(1) {}
Form::Form(std::string name, int gradeRequiredToSign,
int gradeRequiredToExecute)
: _name(name), _isSigned(false), _gradeRequiredToSign(gradeRequiredToSign),
_gradeRequiredToExecute(gradeRequiredToExecute) {
this->gradeChecker(gradeRequiredToSign);
this->gradeChecker(gradeRequiredToExecute);
}
Form::Form(const Form ©)
: _name(copy._name), _isSigned(copy.isSigned()),
_gradeRequiredToSign(copy._gradeRequiredToSign),
_gradeRequiredToExecute(copy._gradeRequiredToExecute) {}
Form &Form::operator=(const Form &rhs) {
if (&rhs != this) {
this->_isSigned = rhs.isSigned();
}
return *this;
}
const char *Form::GradeTooHighException::what() const throw() {
return "Grade is too high !";
}
const char *Form::GradeTooLowException::what() const throw() {
return "Grade is too low !";
}
void Form::gradeChecker(int grade) const {
if (grade < 1) {
throw GradeTooLowException();
} else if (grade > 150) {
throw GradeTooHighException();
}
}
std::string Form::getName() const { return this->_name; }
bool Form::isSigned() const { return this->_isSigned; }
int Form::getGradeRequiredToSign() const { return this->_gradeRequiredToSign; }
int Form::getGradeRequiredToExecute() const {
return this->_gradeRequiredToExecute;
}
void Form::beSigned(Bureaucrat &person) {
if (person.getGrade() > this->getGradeRequiredToSign())
throw GradeTooLowException();
this->_isSigned = true;
}
std::ostream &operator<<(std::ostream &out, const Form &rhs) {
out << rhs.getName();
return out;
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vCard to Qrcode Vue.js</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="vue-qrcode.min.js"></script>
<script src="vcard-creator.js"></script>
<script src="live.js"></script>
</head>
<body>
<div id="app">
<ol>
<li>
<label for="Name">Name</label>
<input v-model="Name">
</li>
<li><label for="Company">公司</label>
<input v-model="Company">
</li>
<li> <label for="Jobtitle">职位</label>
<input v-model="Jobtitle">
</li>
<li> <label for="PhoneNumber1">电话1</label>
<input v-model="PhoneNumber1">
</li>
<li> <label for="PhoneNumber1">电话2</label>
<input v-model="PhoneNumber2">
</li>
</ol>
<qrcode v-bind:value="qrcodeValue"></qrcode>
</div>
<script>
Vue.config.productionTip = true;
var vCard = window.vcardcreator.default;
Vue.component(VueQrcode.name, VueQrcode);
var app8 = new Vue({
el: '#app',
data: {
Name: "",
//lastName: "",//名
//firstName: "", //姓
//additional: "",
//prefix: "",
//suffix: "",
Company: "",
Jobtitle: "",
//Role: "",
//Email: "",
PhoneNumber1: "",
PhoneNumber2: "",
//Address: "",
//URL: ""
},
computed: {
qrcodeValue: function () {
var vcard = new vCard();
lastName = "";
firstName = "";
//根据姓名长度,识别姓氏和名字(大雾方式)
if (this.Name.length < 4) {
lastName = this.Name.slice(1);
firstName = this.Name.slice(0, 1);
} else if (this.Name.length == 4) {
lastName = this.Name.slice(2, 4);
firstName = this.Name.slice(0, 2);
} else {
lastName = this.Name;
}
//vcard.addName(lastName, firstName, this.additional, this.prefix, this.suffix)
vcard.addName(lastName, firstName, '', '', '')
vcard.addCompany(this.Company)
vcard.addJobtitle(this.Jobtitle)
//vcard.addRole(this.Role)
//vcard.addEmail(this.Email)
vcard.addPhoneNumber(this.PhoneNumber1, 'PREF;WORK')
vcard.addPhoneNumber(this.PhoneNumber2, 'WORK')
//vcard.addAddress('', '', '', '', '', '', '')
//vcard.addURL(this.URL)
return vcard.toString()
}
}
})
</script>
</body>
</html>
|
use super::errors::StorageError;
use crate::{
rest_server::errors::InvalidParam,
types::database::{DatabaseReadError, DatabaseReader},
utils::Unexpected,
};
use anyhow::Error;
use serde::Serialize;
use warp::{http::StatusCode, Rejection, Reply};
pub(super) async fn get_latest_block<Db: DatabaseReader + Clone + Send>(
db: Db,
) -> Result<impl Reply, Rejection> {
let db_result = db.get_latest_block().await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_block_by_hash<Db: DatabaseReader + Clone + Send>(
hash: String,
db: Db,
) -> Result<impl Reply, Rejection> {
check_hash_is_correct_format(&hash)?;
let db_result = db.get_block_by_hash(&hash).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_block_by_height<Db: DatabaseReader + Clone + Send>(
height: u64,
db: Db,
) -> Result<impl Reply, Rejection> {
let db_result = db.get_block_by_height(height).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_deploy_by_hash<Db: DatabaseReader + Clone + Send>(
hash: String,
db: Db,
) -> Result<impl Reply, Rejection> {
check_hash_is_correct_format(&hash)?;
let db_result = db.get_deploy_aggregate_by_hash(&hash).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_deploy_accepted_by_hash<Db: DatabaseReader + Clone + Send>(
hash: String,
db: Db,
) -> Result<impl Reply, Rejection> {
check_hash_is_correct_format(&hash)?;
let db_result = db.get_deploy_accepted_by_hash(&hash).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_deploy_processed_by_hash<Db: DatabaseReader + Clone + Send>(
hash: String,
db: Db,
) -> Result<impl Reply, Rejection> {
check_hash_is_correct_format(&hash)?;
let db_result = db.get_deploy_processed_by_hash(&hash).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_deploy_expired_by_hash<Db: DatabaseReader + Clone + Send>(
hash: String,
db: Db,
) -> Result<impl Reply, Rejection> {
check_hash_is_correct_format(&hash)?;
let db_result = db.get_deploy_expired_by_hash(&hash).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_step_by_era<Db: DatabaseReader + Clone + Send>(
era_id: u64,
db: Db,
) -> Result<impl Reply, Rejection> {
let db_result = db.get_step_by_era(era_id).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_faults_by_public_key<Db: DatabaseReader + Clone + Send>(
public_key: String,
db: Db,
) -> Result<impl Reply, Rejection> {
check_public_key_is_correct_format(&public_key)?;
let db_result = db.get_faults_by_public_key(&public_key).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_faults_by_era<Db: DatabaseReader + Clone + Send>(
era: u64,
db: Db,
) -> Result<impl Reply, Rejection> {
let db_result = db.get_faults_by_era(era).await;
format_or_reject_storage_result(db_result)
}
pub(super) async fn get_finality_signatures_by_block<Db: DatabaseReader + Clone + Send>(
block_hash: String,
db: Db,
) -> Result<impl Reply, Rejection> {
check_hash_is_correct_format(&block_hash)?;
let db_result = db.get_finality_signatures_by_block(&block_hash).await;
format_or_reject_storage_result(db_result)
}
fn format_or_reject_storage_result<T>(
storage_result: Result<T, DatabaseReadError>,
) -> Result<impl Reply, Rejection>
where
T: Serialize,
{
match storage_result {
Ok(data) => {
let json = warp::reply::json(&data);
Ok(warp::reply::with_status(json, StatusCode::OK).into_response())
}
Err(req_err) => Err(warp::reject::custom(StorageError(req_err))),
}
}
fn check_hash_is_correct_format(hash: &str) -> Result<(), Rejection> {
let hash_regex = regex::Regex::new("^([0-9A-Fa-f]){64}$")
.map_err(|err| warp::reject::custom(Unexpected(err.into())))?;
if !hash_regex.is_match(hash) {
return Err(warp::reject::custom(InvalidParam(Error::msg(format!(
"Expected hex-encoded hash (64 chars), received: {} (length: {})",
hash,
hash.len()
)))));
}
Ok(())
}
fn check_public_key_is_correct_format(public_key_hex: &str) -> Result<(), Rejection> {
let public_key_regex = regex::Regex::new("^([0-9A-Fa-f]{2}){33,34}$")
.map_err(|err| warp::reject::custom(Unexpected(err.into())))?;
if !public_key_regex.is_match(public_key_hex) {
return Err(warp::reject::custom(InvalidParam(Error::msg(format!(
"Expected hex-encoded public key (66/68 chars), received: {} (length: {})",
public_key_hex,
public_key_hex.len()
)))));
}
Ok(())
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webcam BMI Prediction</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/4.3.0/tf.min.js" integrity="sha512-X00OiLKFsrh2ogo5R/0KNAxplnmE4DS1uYuVlMIsIr1nHztxqg4ovnQwWgqQuO+bqQH1EOkoEVxGMzN/p4ZXDg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/control_utils/control_utils.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/face_mesh.js" crossorigin="anonymous"></script>
</head>
<body>
<video id="video" width="640" height="480" autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width="640" height="480"></canvas>
<div id="results">
<p id="bmi-label" style="font-size: 50px;"></p>
</div>
<script>
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const captureBtn = document.getElementById('capture');
const bmiLabel = document.getElementById('bmi-label');
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(stream => {
video.srcObject = stream;
video.play();
})
.catch(err => {
console.error('An error occurred: ', err);
});
const faceMesh = new FaceMesh({locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/${file}`;
}});
faceMesh.setOptions({
maxNumFaces: 1,
minDetectionConfidence: 0.5,
minTrackingConfidence: 0.5,
refineLandmarks: true,
});
faceMesh.onResults(onResults);
async function onResults(results) {
if (results.multiFaceLandmarks) {
const face = results.multiFaceLandmarks[0];
const flattenedPoints = flattenPoints(face);
// Draw points on the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(video, 0, 0, 640, 480);
face.forEach(point => {
ctx.beginPath();
ctx.arc(point.x * 640, point.y * 480, 2, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
});
const model = await tf.loadLayersModel('tfjs_model/model.json');
console.log(model.summary());
const inputTensor = tf.tensor2d([flattenedPoints]);
const prediction = model.predict(inputTensor);
const bmi = prediction.dataSync()[0];
bmiLabel.innerHTML = `Predicted BMI: ${bmi.toFixed(2)}`;
}
}
captureBtn.addEventListener('click', async () => {
bmiLabel.innerHTML = `Loading face model. Please wait ...`;
await faceMesh.send({image: video});
});
function flattenPoints(points) {
console.log(points);
let flattenedPoints = [];
points.forEach(point => {
flattenedPoints.push(point.x);
flattenedPoints.push(point.y);
flattenedPoints.push(point.z);
});
return flattenedPoints;
}
</script>
</body>
</html>
|
#ifndef __bingo_ptr__
#define __bingo_ptr__
#include "base_cpp/obj_array.h"
#include "base_cpp/exception.h"
#include "base_cpp/tlscont.h"
#include "bingo_mmf.h"
#include "base_cpp/profiling.h"
#include "base_cpp/os_sync_wrapper.h"
#include <new>
#include <string>
#include <thread>
using namespace indigo;
namespace bingo
{
class BingoAllocator;
struct BingoAddr
{
BingoAddr ()
{
offset = (size_t)-1;
file_id = (size_t)-1;
}
BingoAddr (size_t f_id, size_t off) : offset(off), file_id(f_id)
{
}
size_t file_id;
size_t offset;
bool operator== (const BingoAddr &other)
{
return (file_id == other.file_id) && (offset == other.offset);
}
static const BingoAddr bingo_null;
};
template<typename T> class BingoPtr
{
public:
BingoPtr ()
{
}
explicit BingoPtr (BingoAddr addr) : _addr(addr)
{
}
explicit BingoPtr (size_t file_id, size_t offset) : _addr(file_id, offset)
{
}
T * ptr();
const T * ptr() const;
T & ref()
{
return *ptr();
}
const T & ref() const
{
return *ptr();
}
T * operator->()
{
return ptr();
}
const T * operator->() const
{
return ptr();
}
BingoPtr<T> operator+ (int off)
{
return BingoPtr<T>(_addr.file_id, _addr.offset + off * sizeof(T));
}
T & operator[] (int idx)
{
return *(ptr() + idx);
}
/*
qword serialize () const
{
return _offset;
}
void unserialize (qword data)
{
_offset = data;
}
*/
bool isNull ()
{
return (_addr.offset == -1) && (_addr.file_id == -1);
}
void allocate ( int count = 1 );
operator BingoAddr() const { return _addr; }
private:
BingoAddr _addr;
};
template<typename T> class BingoArray
{
public:
BingoArray( int block_size = 10000 ) : _block_size(block_size)
{
_size = 0;
_block_count = 0;
}
void resize (int new_size)
{
if (new_size > reserved())
{
int blocks_count = (_size + _block_size - 1) / _block_size;
int new_blocks_count = (new_size + _block_size - 1) / _block_size;
if (new_blocks_count > _max_block_count)
throw Exception("BingoArray: block count limit is exceeded");
for (int i = blocks_count; i < new_blocks_count; i++)
{
_blocks[i].allocate(_block_size);
for (int j = 0; j < _block_size; j++)
new((_blocks[i] + j).ptr()) T();
}
_block_count = new_blocks_count;
}
_size = new_size;
}
T & at (int index)
{
if (index < 0 || index >= _size)
throw Exception("BingoArray: incorrect idx %d (size=%d)", index, _size);
return *(_blocks[index / _block_size].ptr() + index % _block_size);
}
const T & at (int index) const
{
if (index < 0 || index >= _size)
throw Exception("BingoArray: incorrect idx %d (size=%d)", index, _size);
return *(_blocks[index / _block_size].ptr() + index % _block_size);
}
T & operator [] (int index)
{
return at(index);
}
const T & operator [] (int index) const
{
return at(index);
}
T & top ()
{
int index = _size - 1;
return *(_blocks[index / _block_size].ptr() + index % _block_size);
}
size_t find (const T & elem)
{
for (size_t i = 0; i < size(); i++)
{
if (at(i) == elem)
return i;
}
return (size_t)-1;
}
T & push ()
{
if (_size % _block_size == 0)
{
int blocks_count = (_size + _block_size - 1) / _block_size;
_blocks[blocks_count].allocate(_block_size);
}
T * arr = _blocks[_size / _block_size].ptr();
int idx_in_block = _size % _block_size;
_size++;
new(arr + idx_in_block) T();
return arr[idx_in_block];
}
template <typename A> T & push (A &a)
{
if (_size % _block_size == 0)
{
int blocks_count = (_size + _block_size - 1) / _block_size;
_blocks[blocks_count].allocate(_block_size);
}
T * arr = _blocks[_size / _block_size].ptr();
int idx_in_block = _size % _block_size;
_size++;
new(arr + idx_in_block) T(a);
return arr[idx_in_block];
}
void push (T elem)
{
T & new_elem = push();
new_elem = elem;
}
int size () const
{
return _size;
}
int reserved () const
{
return _block_count * _block_size;
}
private:
static const int _max_block_count = 40000;
int _block_size;
int _block_count;
int _size;
BingoPtr<T> _blocks[_max_block_count];
};
template<typename T> class BingoList
{
private:
struct _Link
{
BingoPtr<T> data_ptr;
BingoPtr<_Link> next_link;
BingoPtr<_Link> prev_link;
_Link()
{
data_ptr = BingoPtr<T>(BingoAddr::bingo_null);
next_link = BingoPtr<_Link>(BingoAddr::bingo_null);
prev_link = BingoPtr<_Link>(BingoAddr::bingo_null);
}
};
public:
struct Iterator
{
BingoPtr<_Link> cur_link;
Iterator () : cur_link(BingoPtr<T>(-1, -1)) { }
Iterator (BingoPtr<_Link> link) : cur_link(link) { }
Iterator (const Iterator &it) : cur_link(it.cur_link) { }
T & operator*()
{
return cur_link->data_ptr.ref();
}
T * operator->()
{
return cur_link->data_ptr.ptr();
}
Iterator & operator= (const Iterator & it)
{
cur_link = it.cur_link;
return *this;
}
bool operator== (const Iterator & it) const
{
if ((BingoAddr)cur_link == (BingoAddr)it.cur_link)
return true;
return false;
}
bool operator!= (const Iterator & it) const
{
return !(*this == it);
}
Iterator & operator++ (int)
{
if ((BingoAddr)(cur_link->next_link) == BingoAddr::bingo_null)
throw Exception("BingoList::Iterator:operator++ There's no next link");
cur_link = cur_link->next_link;
return *this;
}
Iterator & operator-- (int)
{
if ((BingoAddr)(cur_link->prev_link) == BingoAddr::bingo_null)
throw Exception("BingoList::Iterator:operator-- There's no previous link");
cur_link = cur_link->prev_link;
return *this;
}
};
BingoList()
{
_size = 0;
_begin_link.allocate();
new(_begin_link.ptr()) _Link();
_end_link = _begin_link;
}
bool empty () const
{
if (_end_link == _begin_link)
return true;
return false;
}
unsigned int size () const
{
return _size;
}
void insertBefore(Iterator pos, const BingoPtr<T> x)
{
BingoPtr<_Link> new_link;
new_link.allocate();
new(new_link.ptr()) _Link();
new_link->data_ptr = x;
new_link->next_link = pos.cur_link;
new_link->prev_link = pos.cur_link->prev_link;
if (!((BingoAddr)(pos.cur_link->prev_link) == BingoAddr::bingo_null))
pos.cur_link->prev_link->next_link = new_link;
pos.cur_link->prev_link = new_link;
if ((BingoAddr)(pos.cur_link) == (BingoAddr)(_begin_link))
_begin_link = new_link;
_size++;
}
void insertBefore(Iterator pos, const T &x)
{
BingoPtr<T> data;
data.allocate();
data.ref() = x;
insertBefore(pos, data);
}
void erase (Iterator & pos)
{
if (pos.cur_link->prev_link != -1)
pos.cur_link->prev_link->next_link = pos.cur_link->next_link;
if (pos.cur_link->next_link != -1)
pos.cur_link->next_link->prev_link = pos.cur_link->prev_link;
if (pos.cur_link == _begin_link)
_begin_link = pos.cur_link->next_link;
if (pos.cur_link == _end_link)
throw Exception("BingoList:erase End link can't be removed");
_size--;
}
void pushBack (const T &x)
{
insertBefore(end(), x);
}
void pushBack (const BingoPtr<T> x)
{
insertBefore(end(), x);
}
Iterator begin () const
{
return Iterator(_begin_link);
}
Iterator top () const
{
Iterator end_it(_end_link);
end_it--;
return end_it;
}
Iterator end () const
{
return Iterator(_end_link);
}
private:
BingoPtr<_Link> _begin_link;
BingoPtr<_Link> _end_link;
int _size;
};
class MMFStorage;
class BingoAllocator
{
public:
template<typename T> friend class BingoPtr;
friend class MMFStorage;
static int getAllocatorDataSize ();
private:
struct _BingoAllocatorData
{
_BingoAllocatorData() : _min_file_size(0), _max_file_size(0), _free_off(0), _cur_file_id(0), _existing_files(0)
{
}
size_t _min_file_size;
size_t _max_file_size;
size_t _cur_file_id;
dword _existing_files;
size_t _free_off;
};
ObjArray<MMFile> *_mm_files;
size_t _data_offset;
static PtrArray<BingoAllocator> _instances;
std::string _filename;
int _index_id;
static OsLock _instances_lock;
static void _create (const char *filename, size_t min_size, size_t max_size, size_t alloc_off, ObjArray<MMFile> *mm_files, int index_id);
static void _load (const char *filename, size_t alloc_off, ObjArray<MMFile> *mm_files, int index_id, bool read_only);
template<typename T> BingoAddr allocate ( int count = 1 )
{
byte * mmf_ptr = (byte *)_mm_files->at(0).ptr();
_BingoAllocatorData *allocator_data = (_BingoAllocatorData *)(mmf_ptr + _data_offset);
int szf_t = sizeof(T);
int alloc_size = sizeof(T) * count;
size_t file_idx = allocator_data->_cur_file_id;
size_t file_off = allocator_data->_free_off;
size_t file_size = _mm_files->at((int)file_idx).size();
if (alloc_size > file_size - file_off)
_addFile(alloc_size);
file_idx = allocator_data->_cur_file_id;
file_size = _mm_files->at((int)file_idx).size();
size_t res_off = allocator_data->_free_off;
size_t res_id = allocator_data->_cur_file_id;
allocator_data->_free_off += alloc_size;
if (allocator_data->_free_off == file_size)
_addFile(0);
return BingoAddr(res_id, res_off);
}
static BingoAllocator *_getInstance ();
byte * _get (size_t file_id, size_t offset);
BingoAllocator ();
void _addFile (int alloc_size);
static size_t _getFileSize(size_t idx, size_t min_size, size_t max_size, dword sizes);
static void _genFilename (int idx, const char *filename, std::string &out_name);
};
// Implementations for BingoPtr and BingoAllocator are dependent and thus implementation is here
template <typename T>
T * BingoPtr<T>::ptr()
{
BingoAllocator *_allocator = BingoAllocator::_getInstance();
return (T *)(_allocator->_get(_addr.file_id, _addr.offset));
}
template <typename T>
const T * BingoPtr<T>::ptr() const
{
BingoAllocator *_allocator = BingoAllocator::_getInstance();
return (T *)(_allocator->_get(_addr.file_id, _addr.offset));
}
template <typename T>
void BingoPtr<T>::allocate ( int count )
{
BingoAllocator *_allocator = BingoAllocator::_getInstance();
_addr = _allocator->allocate<T>(count);
}
};
#endif //__bingo_ptr__
|
import React from "react";
import { useForm } from "react-hook-form";
export default function App({ addTodo, removeDuplicate }) {
const { register, handleSubmit, watch, formState } = useForm({
mode: "onChange"
});
const onSubmit = ({ newTodo }) => {
addTodo(newTodo);
};
const removeDuplicates = () => {
removeDuplicate();
};
console.log(watch("newTodo")); // watch input value by passing the name of it
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<input {...register("newTodo", { required: true })} />
<span> </span>
<button disabled={!formState.isValid} onClick={handleSubmit(onSubmit)}>
Add
</button>
<button onClick={handleSubmit(removeDuplicates)}>
Remove Duplicates
</button>
</div>
</form>
);
}
|
import { StatusBar } from 'expo-status-bar';
import { KeyboardAvoidingView, ScrollView, Text, TextInput, View } from 'react-native';
import { estilo } from './style';
import { Icon } from 'react-native-elements';
import Cidades from '../../Cidades.json'
import { useState } from 'react';
export default function Home() {
const[searchWord, setSearchWord] = useState('')
return(
<View
style={estilo.all}>
<View style={estilo.inform}>
<View style={estilo.informLeft}>
<View style={estilo.location}>
<Icon
name='place'
color='#7ED957'
size={35}
/>
<Text
style={estilo.cidade}>
BEBEDOURO
</Text>
</View>
</View>
<View style={estilo.informRight}>
<Icon
name='person'
color='#7ED957'
size={35}
style={estilo.account}
/>
</View>
</View>
<View style={estilo.body}>
<View style={estilo.regiao}>
<View style={estilo.searchIcon}>
<TextInput
placeholder='Pesquisar...'
onChangeText={setSearchWord}
style={estilo.search}>
</TextInput>
</View>
<View style={estilo.searchiconTop}>
<Text style={estilo.region}>Cinemas na Região</Text>
<ScrollView
style={estilo.cinemas}>
{Cidades.filter((val)=>{
if(searchWord == ""){
return val
}else if(val.Cidades.toLowerCase().includes(searchWord.toLowerCase())){
return val
}
}).map((item, index)=>(
<Text key={index}>{item.Cidades}</Text>
))}
</ScrollView>
</View>
</View>
</View>
<View style={estilo.nav}>
</View>
</View>
);
}''
|
//
// ViewController.swift
// LoginScreenUI
//
// Created by 奈木野諭吉 on 2023/08/18.
//
import UIKit
import SwiftUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
struct ContentView: View {
@State private var username = ""
@State private var password = ""
@State private var wrongUsername = 0
@State private var wrongPassword = 0
@State private var showingLoginScreen = false
var body: some View {
NavigationView {
ZStack {
Color.blue
.ignoresSafeArea()
Circle()
.scale(1.7)
.foregroundColor(.white.opacity(0.15))
Circle()
.scale(1.35)
.foregroundColor(.white)
VStack{
Text("Login")
.font(.largeTitle)
.bold()
.padding()
TextField("Username", text: $username)
.padding()
.frame(width: 300, height: 50)
.background(Color.black.opacity(0.05))
// 枠を丸くする
.cornerRadius(10)
.border(.red, width: CGFloat(wrongUsername))
SecureField("Password", text: $password)
.padding()
.frame(width: 300, height: 50)
.background(Color.black.opacity(0.05))
.cornerRadius(10)
.border(.red, width: CGFloat(wrongPassword))
Button("Login"){
//Authenticate user
authenticateUser(username: username, password: password)
}
.foregroundColor(.white)
.frame(width: 300, height: 50)
.background(Color.blue)
.cornerRadius(10)
NavigationLink(destination: Text("You are logged in @\(username)"), isActive: $showingLoginScreen){
EmptyView()
}
}
}
.navigationBarHidden(true)
}
}
func authenticateUser(username: String, password: String){
if username.lowercased() == "Mario2021"{
wrongUsername = 0
if password.lowercased() == "abc123"{
wrongPassword = 0
showingLoginScreen = true
} else {
wrongPassword = 2
}
} else {
wrongUsername = 2
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
var db = require('@utility/database');
/**
* Checks if user of a given email and password exists and returns their data.
* @param {string} email - The user's email.
* @param {string} pass - The user's password.
* @returns {Promise<Object>} - A promise that resolves to the user object if login is successful.
* @throws {Error('invalid email or password')} - If email and password don't match.
*/
exports.login = async function (email, pass) {
return await db.Request()
.input('email', email)
.input('pass', pass)
.query('SELECT * FROM [dbo].[user] WHERE email = @email AND pass = @pass')
.then(result => {
if (result.recordset.length == 0) {
throw new Error('invalid email or password');
} else {
let user = {
user_id: result.recordset[0].user_id,
email: result.recordset[0].email,
name: result.recordset[0].name,
join_date: new Date(result.recordset[0].join_date).toISOString().substring(0,10),
is_guest: false,
is_admin: result.recordset[0].is_admin
};
return user;
}
});
}
/**
* Registers a user with the given email, name and password.
* @param {string} email - The user's email.
* @param {string} name - The user's name.
* @param {string} pass - The user's password.
* @param {Date} birth_date - The user's birth date.
* @param {string} gender - The user's gender.
* @returns {null} - Nothing.
* @throws {Error('email already exists')} - If email already exists.
* @throws {Error('name already exists')} - If name already exists.
* @throws {Error('email too short')} - If email is too short. (must be at least 8 characters long)
* @throws {Error('name too short')} - If name is too short.
* @throws {Error('pass too short')} - If password is too short.
* @throws {Error('value too long')} - If any value is too long.
* @throws {Error('user age')} - If user age is less than 16 years.
*/
exports.register = async function (email, name, pass, birth_date, gender) {
await db.Request()
.input('email', email)
.input('name', name)
.input('pass', pass)
.input('birth_date', birth_date)
.input('gender', gender)
.query('INSERT INTO [dbo].[user] (email, name, pass, birth_date, gender) VALUES (@email, @name, @pass, @birth_date, @gender)')
.catch(err => {
if (err.code === 'EREQUEST' && err.originalError) {
var info = err.originalError.info;
if (info.message.includes('unique_email'))
throw new Error('email already exists');
if (info.message.includes('unique_name'))
throw new Error('name already exists');
if (info.message.includes('email_len'))
throw new Error('email too short');
if (info.message.includes('name_len'))
throw new Error('name too short');
if (info.message.includes('pass_len'))
throw new Error('pass too short');
if (info.number === 2628)
throw new Error('value too long');
if (info.message.includes('user_age'))
throw new Error('user age');
}
throw err;
});
}
|
package conjuntos;
import java.util.HashSet;
import java.util.Set;
/* CONJUNTOS
Os conjuntos são implementados com a interface Set e uma das classes
que implementamesta interface e a HahSet.
A maioria das coleções possuem os mesmos métodos já conhecidos e
utilizados com as listas, mas o comportamento desses objetos é um
pouco diferente a PERFORMACE é melhor em conjuntos do que nas Listas.
Características dos conjuntos:
- Não aceitam valores repetidos (aceitam mas não incluem).
- A ordem de inserção não é respeitada e faz uma semi-ordenação.
- Não aceita ordenação pelo => collections.sort.
- Não possui índice (nome.get(algumaCoisa)).
*/
public class Programa {
public static void main(String[] args) {
// Modelo de CONJUNTO
Set<String> nomes = new HashSet<String>();
// Adicionando objetos
nomes.add("Paulo");
nomes.add("Reginaldo");
nomes.add("Cardoso");
nomes.add("Corinthians");
nomes.add("Timão");
nomes.add("Indaiatuba");
nomes.add("Paulo"); // não será inserido por conta da repetição
// Imprimir o conjunto um baixo do outro
for (String nome : nomes) {
System.out.println(nome);
}
System.out.println();
// Ver o tamanho do conjunto
System.out.println("Tamanho da lista: " + nomes.size());
System.out.println();
// Imprimir o conjunto um a frente do outro
System.out.println(nomes);
System.out.println();
// Verificar se contém um nome
System.out.println("Se true está na lista, e se false não está na lista (Paulo) -> " + nomes.contains("Paulo"));
System.out.println();
System.out.println("Tentar adicionar um nome que já existe (Paulo) -> " + nomes.add("Paulo"));
System.out.println("Tentar adicionar um nome que não existe no conjunto -> " + nomes.add("Indaiatuba"));
System.out.println();
// Lista atualizada
System.out.println("Lista atualizada: \n" + nomes);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.