text
stringlengths 184
4.48M
|
|---|
import numpy as np
import pandas as pd
from plotnine import *
from plotnine.data import mpg, mtcars
%matplotlib inline
type(mpg)
pd.DataFrame.head(mpg)
pd.DataFrame.head(mtcars)
(ggplot(mpg) +
aes(x = 'class', fill = 'class') +
geom_bar(size=20))
(
ggplot(mpg) +
aes(x = 'class', y = 'hwy', fill = 'class') +
geom_boxplot() +
labs(x = 'Car Classes', y = 'Highway Milage')
)
(
ggplot(mpg) +
aes(x = 'cty', y = 'hwy', fill = 'class') +
geom_point(alpha = .7)
)
(
ggplot(mpg) +
aes(x = 'cyl', y = 'hwy', fill = 'class') +
geom_boxplot()
)
(
ggplot(mtcars, aes('wt','mpg', color='factor(gear)')) +
geom_point() +
facet_wrap('~cyl')+
theme_bw()+
labs(x='Weight', y='Miles/gallon')+
scale_color_discrete(name='Forward Gear Number (Factor)')
)
(
ggplot(mtcars, aes('wt','mpg',color='factor(gear)'))+
geom_point()+
geom_smooth(method="lm")+
theme_bw()
)
(
ggplot(mtcars, aes('wt','mpg',color='factor(gear)', size='cyl'))+
geom_point()+
facet_wrap('~am')+
theme_bw()
)
(
ggplot(mtcars, aes('wt', 'mpg', color='factor(gear)', size='cyl'))+
geom_point()+
facet_grid('am~carb')+
theme_bw()
)
|
1. Print (console.log()) value of the property "name" in the given object:
```code
let student = {
name:"Max",
age: 27
};
```
2. a. Find the value of the price property and if it is greater than 100, discount it by 10%. If that’s not the case, discount it by 7%.
b. Update the object with the new property - discount and the corresponding value (7% or 10%) and the new price.
3. Use given object and loop through its properties and if it has property “discount” print “Already discounted by…” and add the value (how much was the discount). In opposite case, do what you did in the previous exercise: check the price, depending on it (if it’s greater or lower than 100) add discount (10% or 7%) and add the property “discount” to the object.
```code
let prod = {
name: "headphones",
price: 83.7,
discount: "7%",
};
End result should be like this >>
// end result - case 1:
// { name: 'headphones', price: '77.84', discount: '7%' }
// end result - case 2:
// Already discounted by 7%.
```
4. Write a JavaScript program to calculate circle area and perimeter.
Note : Create two methods to calculate the area and perimeter. The radius of the circle will be supplied by the user.
5. Write a program which can return a boolean if value is present in the range with given start and end values in an object
```code
// Example
let range = {
start: 10,
end: 50,
};
5 in range; // false
25 in range; // true
```
|
import Image from 'next/image';
type Props = {
src?: string;
alt?: string;
width?: string | number;
height?: string | number;
};
const Img: React.FC<Props> = (props) => {
const width =
typeof props.width === 'string' ? Number(props.width) : props.width;
const height =
typeof props.height === 'string' ? Number(props.height) : props.height;
return (
<Image
src={props.src ?? 'dummy.png'}
alt={props.alt ?? ''}
width={width ?? undefined}
height={height ?? undefined}
/>
);
};
export default Img;
|
import React, { useState } from 'react';
import { GoX } from 'react-icons/go';
function QuestionModal ({id, productName,hidden, hide, submitHandler}) {
const [newQuestion, setNewQuestion] = useState('');
const [nickname, setNickname] = useState('');
const [email, setEmail] = useState('');
const submitForm = (event) => {
event.preventDefault();
// Use regex similar to:
// newQuestion === /a-zA-Z?!./
// nickname === /a-zA-Z0-9/
// email === /[a-zA-Z0-9.]@a-zA-Z0-9].[com, edu, gov]/
const fieldNames = ['Question Field', 'Nickname', 'Email'];
let blankWarnings = [false, false, false];
const state = [newQuestion, nickname, email];
let blankString = '';
for (let i in state) {
if (state[i].length === 0) {
blankWarnings[i] = true;
blankString += `${fieldNames[i]}, `
} else {
blankWarnings[i] = false;
}
}
if (blankString) {
alert(`Please fill in: ${blankString}`);
} else {
const data = {
body: newQuestion,
name: nickname,
email: email,
product_id: id
};
submitHandler(data);
hide(event);
}
};
const changeHandler = (event) => {
const target = event.target;
const name = target.name;
let inputString = '';
switch(name) {
case 'question-input':
inputString = target.value;
setNewQuestion(inputString);
break;
case 'nickname-input':
inputString = target.value;
setNickname(inputString);
break;
case 'email-input':
inputString = target.value;
setEmail(inputString);
break;
}
}
return (
<div hidden={hidden}>
<div className='questions-modal'>
{/* <i className="fa-solid fa-x onclick" onClick={hide}></i> */}
<GoX className={"onclick"} onClick={hide} size={40}/>
<div className="questions-modal-header">
<h4>Add Your Question!</h4>
<h5>About the {productName}</h5>
</div>
<form className="questions-modal-form" onSubmit={submitForm}>
<h5>Your Question</h5>
<textarea maxLength={1000} name="question-input" value={newQuestion} rows="4" cols="40" placeholder="" onChange={changeHandler}></textarea>
<h5>What is your nickname?</h5>
<input maxLength={60} name="nickname-input" value={nickname} type="text" placeholder="Example: jackson11!" onChange={changeHandler}/>
<p>For privacy reasons, do not use your full name or email</p>
<h5>Your Email</h5>
<input maxLength={60} name="email-input" value={email} type="text" placeholder="Example: jackson@email.com" onChange={changeHandler}/>
<p>For authentication reasons, you will not be emailed</p>
<button type="submit" className="onclick">SUBMIT QUESTION</button>
</form>
</div>
</div>
);
};
export default QuestionModal;
|
import 'package:flutter/material.dart';
import 'package:introduction_screen/introduction_screen.dart';
import 'package:pas_ecommerce/pages/auth_page.dart';
import 'package:pas_ecommerce/provider/auth.dart';
import 'package:provider/provider.dart';
class OnboardingScreen extends StatelessWidget {
final introKey = GlobalKey<IntroductionScreenState>();
static const nameRoute = '/onboarding';
@override
Widget build(BuildContext context) {
final auth = Provider.of<Autth>(context, listen: false);
final pageDecoration = PageDecoration(
titleTextStyle: TextStyle(
fontSize: 28,
fontWeight: FontWeight.w700,
),
bodyTextStyle: TextStyle(fontSize: 19),
bodyPadding: EdgeInsets.fromLTRB(16, 0, 16, 16),
pageColor: Colors.white,
imagePadding: EdgeInsets.zero,
);
return IntroductionScreen(
key: introKey,
globalBackgroundColor: Colors.white,
pages: [
PageViewModel(
title: "Belanja Sekarang",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget varius est. Sed sodales dapibus nunc, sit amet facilisis nisl suscipit in. Nunc tincidunt sodales massa, ut semper nunc porta at. Nullam laoreet quis velit sed facilisis. Proin placerat pulvinar metus et feugiat. Morbi a convallis mauris. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec laoreet condimentum augue, sit amet aliquet sem sagittis vitae. Quisque et iaculis nibh.",
image: Image.asset(
"assets/splash 1.png",
width: 200,
),
decoration: pageDecoration),
PageViewModel(
title: "Pembayaran Bervariasi",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget varius est. Sed sodales dapibus nunc, sit amet facilisis nisl suscipit in. Nunc tincidunt sodales massa, ut semper nunc porta at. Nullam laoreet quis velit sed facilisis. Proin placerat pulvinar metus et feugiat. Morbi a convallis mauris. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec laoreet condimentum augue, sit amet aliquet sem sagittis vitae. Quisque et iaculis nibh.",
image: Image.asset(
"assets/splash 2.png",
width: 200,
),
decoration: pageDecoration),
PageViewModel(
title: "Pengiriman Cepat",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget varius est. Sed sodales dapibus nunc, sit amet facilisis nisl suscipit in. Nunc tincidunt sodales massa, ut semper nunc porta at. Nullam laoreet quis velit sed facilisis. Proin placerat pulvinar metus et feugiat. Morbi a convallis mauris. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec laoreet condimentum augue, sit amet aliquet sem sagittis vitae. Quisque et iaculis nibh.",
image: Image.asset(
"assets/splash 3.png",
width: 200,
),
decoration: pageDecoration,
footer: Padding(
padding: EdgeInsets.only(left: 15, right: 15, top: 45),
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginScreen(),
));
auth.onboarding = 1;
},
child: Text(
"Let's Shop",
style: TextStyle(
fontSize: 18,
),
),
style: ElevatedButton.styleFrom(
minimumSize: Size.fromHeight(55),
backgroundColor: Colors.purple,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
)),
),
)),
],
showSkipButton: false,
showDoneButton: false,
showBackButton: true,
back: Text(
"Back",
style: TextStyle(fontWeight: FontWeight.w600, color: Colors.purple),
),
next: Text(
"Next",
style: TextStyle(fontWeight: FontWeight.w600, color: Colors.purple),
),
onDone: () {},
dotsDecorator: DotsDecorator(
size: Size.square(10),
activeSize: Size(20, 10),
activeColor: Colors.purple,
color: Colors.black26,
spacing: EdgeInsets.symmetric(horizontal: 3),
activeShape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
)),
);
}
}
|
package code.hashing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public class Anagrams {
class Solution {
public ArrayList<ArrayList<Integer>> anagrams (final List<String> A) {
HashMap<String, ArrayList<Integer>> m = new HashMap();
IntStream.range(0, A.size()).
forEach(i -> {
String s = A.get(i);
char[] a = s.toCharArray();
Arrays.sort(a);
s = String.valueOf(a);
if (m.containsKey(s)) m.get(s).add(i + 1);
else m.put(s, new ArrayList<>(Arrays.asList(i + 1)));
});
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
m.values().forEach(l -> result.add(l));
return result;
}
}
public static void main(String[] args) {
System.out.println(
new Anagrams().
new Solution().
anagrams(Arrays.stream(new String[] { "cat", "dog", "god", "tca" }).
collect(toList()))
);
}
}
|
import { React, useState, useEffect} from 'react';
import './CartItem.css'
import { BiMinus, BiPlus } from 'react-icons/bi'
import { FaTrash } from 'react-icons/fa'
import { useCart } from '../../context/Context';
export const CartItem = (props) => {
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
const { cartItemsMap, setCartItemsMap, setCartIdItemMap,cartIdItemMap } = useCart();
const itemCount = cartItemsMap[props.id] || 0; // Get the count for this item
useEffect(() => {
// Update windowWidth when the window is resized
const handleResize = () => {
setWindowWidth(window.innerWidth);
};
window.addEventListener('resize', handleResize);
// Clean up the event listener when the component unmounts
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
const handleIncrement = () => {
setCartItemsMap({
...cartItemsMap,
[props.id]: itemCount + 1,
});
};
const handleDecrement = () => {
if (itemCount > 0) {
setCartItemsMap({
...cartItemsMap,
[props.id]: itemCount - 1,
});
}
};
const handleRemove = () => {
const updatedCartItemsMap = { ...cartItemsMap };
const updatedCartIdItemMap = { ...cartIdItemMap };
if (updatedCartItemsMap[props.id] >= 0) {
const itemCountToRemove = updatedCartItemsMap[props.id];
// Remove the item from cartItemsMap
delete updatedCartItemsMap[props.id];
// Remove all items with the same product ID from cartIdItemMap
for (const itemId in updatedCartIdItemMap) {
if (updatedCartIdItemMap[itemId].id === props.id) {
delete updatedCartIdItemMap[itemId];
}
}
// Update cartItemCount in context
}
// Update cartItemsMap and cartIdItemMap in context
setCartItemsMap(updatedCartItemsMap);
setCartIdItemMap(updatedCartIdItemMap);
};
return ( <div className=" w-full flex flex-col items-center">
{windowWidth > 450 ?(
<div className="bg-white flex w-1/2 flex-col rounded-lg shadow-md">
<div className=" flex justify-between px-4 py-4">
<img src={props.image_url} alt={props.name}
className="h-48 object-cover" />
<div className="flex flex-col justify-around">
<div className='text-xl'>{props.name}</div>
<div className="flex items-center justify-end py-10">
<button className='text-xl' onClick={handleDecrement}><BiMinus /> </button>
<p className="mx-2 text-xl border-2 px-4">{itemCount}</p>
<button className='text-xl' onClick={handleIncrement}><BiPlus /></button>
</div>
<button className='flex items-center justify-end gap-4 text-xl' onClick={handleRemove}><FaTrash /> Remove</button>
</div>
</div>
</div>):(
<div className="flex flex-col bg-white rounded-lg shadow-md">
<div className="flex flex-col gap-4 px-4 py-4">
<img src={props.image_url} alt={props.name}
className="w-full h-64 object-cover" />
<div className="flex flex-col items-center">
<div className='text-xl'>{props.name}</div>
<div className="flex items-center px-4 py-4">
<button className='text-xl' onClick={handleDecrement}><BiMinus /> </button>
<p className="mx-2 text-xl border-2 px-4">{props.count}</p>
<button className='text-xl' onClick={handleIncrement}><BiPlus /></button>
</div>
<button className='flex flex-row items-center gap-4' onClick={handleRemove}><FaTrash /> Remove</button>
</div>
</div>
</div>
)
}</div>
)
}
|
<template>
<div class="relative z-[600] h-full overflow-hidden" v-if="isOpen" id="modal">
<transition
appear
enter-active-class="transition-opacity duration-100"
leave-active-class="transition-opacity duration-100"
enter-from-class="opacity-0"
leave-from-class="opacity-0"
>
<div class="fixed inset-0 bg-white bg-opacity-90"></div>
</transition>
<transition
appear
enter-active-class="transition-opacity transition-transform duration-300"
leave-active-class="transition-opacity transition-transform duration-300"
enter-from-class="opacity-0 scale-90"
leave-from-class="opacity-0 scale-90"
>
<div
class="fixed inset-0 w-screen overflow-hidden flex min-h-full justify-center items-center"
@click="closeModal"
>
<div class="my-auto">
<div class="bg-white rounded-sm shadow-lg relative w-[678px]">
<div
class="flex justify-between h-full min-h-[695px]"
@click.stop=""
>
<KeepAlive>
<component
:is="view"
v-model="model"
v-bind="{ ...payload }"
></component>
</KeepAlive>
</div>
<div class="absolute right-[12px] top-[12px]">
<button @click="closeModal">
<Icon name="material-symbols-light:close" size="24" />
</button>
</div>
<div class="modal-action flex gap-3">
<button
v-for="action in actions"
@click="action.callback(model)"
:class="{
'bg-green-600 text-white': action.type === 'primary',
'border border-black': action.type === 'outlined',
}"
class="rounded-full py-2 px-6 capitalize"
>
{{ action.label }}
</button>
</div>
</div>
</div>
</div>
</transition>
</div>
</template>
<script setup lang="ts">
import { useModal } from "../../stores/modal";
import { storeToRefs } from "pinia";
const modal = useModal();
const { isOpen, view, actions, payload } = storeToRefs(modal);
const model = reactive({});
const closeModal = () => {
modal.close();
};
</script>
<style scoped></style>
|
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import * as winston from 'winston';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(private logger: winston.Logger) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
const req = context.switchToHttp().getRequest();
return next.handle().pipe(
tap(() =>
this.logger.info({
message: `${req.method} ${req.url} ${Date.now() - now}ms`,
level: 'info',
}),
),
);
}
}
|
package com.example.xmailserver.controller;
import com.example.xmailserver.pojo.Result;
import com.example.xmailserver.pojo.User;
import com.example.xmailserver.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public Result register(@RequestBody User user) {
try {
userService.add(user);
String folder = "/var/www/html/mail/" + user.getUsername();
Runtime.getRuntime().exec("mkdir " + folder);
return Result.success();
} catch (Exception e) {
return Result.error("username已经存在");
}
}
@GetMapping("/login")
public Result login(String username, String password) {
log.info("登录:{}", username);
User user = userService.login(username, password);
if (user == null) {
return Result.error("用户名或密码错误");
}
return Result.success(user);
}
@GetMapping()
public Result list() {
log.info("查询所有用户数据");
List<User> userList = userService.list();
return Result.success(userList);
}
@PutMapping()
public Result update(@RequestBody User user) {
log.info("更新用户数据: {}", user);
userService.update(user);
return Result.success();
}
@GetMapping("/updatePassword")
public Result updatePassword(String username, String newpassword, String oldpassword) {
log.info("更新用户密码: {}", username);
User user = userService.login(username, oldpassword);
if (user == null) {
return Result.error("旧密码错误");
}
user.setPassword(newpassword);
userService.update(user);
return Result.success();
}
@GetMapping("/addfriend")
public Result addfriend(String username, String friendname) {
log.info("添加好友: {}", username);
userService.addfriend(username, friendname);
return Result.success();
}
@GetMapping("/deletefriend")
public Result deletefriend(String username, String friendname) {
log.info("删除好友: {}", username);
userService.deletefriend(username, friendname);
return Result.success();
}
@GetMapping("listfriend")
public Result listfriend(String username) {
log.info("查询好友: {}", username);
List<String> userList = userService.listfriend(username);
return Result.success(userList);
}
@GetMapping("disable")
public Result disable(String username) {
log.info("禁用用户: {}", username);
User user = userService.getByUsername(username);
user.setStatus(0);
userService.update(user);
return Result.success();
}
@GetMapping("enable")
public Result enable(String username) {
log.info("启用用户: {}", username);
User user = userService.getByUsername(username);
user.setStatus(1);
userService.update(user);
return Result.success();
}
}
|
import * as React from 'react';
import CssBaseline from '@mui/material/CssBaseline';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Container from '@mui/material/Container';
import Toolbar from '@mui/material/Toolbar';
import Paper from '@mui/material/Paper';
import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepLabel from '@mui/material/StepLabel';
import Button from '@mui/material/Button';
import Link from '@mui/material/Link';
import Typography from '@mui/material/Typography';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import Info from './Info';
import Facility from './Facility'
import Preference from './Preference';
function Copyright() {
return (
<Typography variant="body2" color="text.secondary" align="center">
{'Copyright © '}
<Link color="inherit" href="#">
GharDera
</Link>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
);
}
const steps = [ 'General info','Roommate Preferences', 'Facilities'];
function getStepContent(step) {
switch (step) {
case 0:
return <Info/>
case 1:
return < Preference/> ;
case 2:
return <Facility />;
default:
throw new Error('Unknown step');
}
}
const theme = createTheme();
export default function Postroommate() {
const [activeStep, setActiveStep] = React.useState(0);
const handleNext = () => {
setActiveStep(activeStep + 1);
};
const handleBack = () => {
setActiveStep(activeStep - 1);
};
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<AppBar
position="absolute"
color="default"
elevation={0}
sx={{
position: 'relative',
borderBottom: (t) => `1px solid ${t.palette.divider}`,
}}
>
<Toolbar>
<Typography variant="h6" color="inherit" noWrap>
GharDera
</Typography>
</Toolbar>
</AppBar>
<Container component="main" >
<Paper variant="outlined" sx={{ my: { xs: 3, md: 6 }, p: { xs: 2, md: 3 } }}>
<Typography component="h1" variant="h4" align="center">
Post For Roommates
</Typography>
<Stepper activeStep={activeStep} sx={{ pt: 3, pb: 5 }}>
{steps.map((label) => (
<Step key={label}>
<StepLabel>{label}</StepLabel>
</Step>
))}
</Stepper>
{activeStep === steps.length ? (
<React.Fragment>
<Typography variant="h5" gutterBottom>
Thank you for your submission
</Typography>
<Typography variant="subtitle1">
Your Property number is #2001539. We have emailed your
confirmation, and will send you an update when we found the tenant.
</Typography>
</React.Fragment>
) : (
<React.Fragment>
{getStepContent(activeStep)}
<Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
{activeStep !== 0 && (
<Button onClick={handleBack} sx={{ mt: 3, ml: 1 }}>
Back
</Button>
)}
<Button
type='submit'
variant="contained"
onClick={handleNext}
sx={{ mt: 3, ml: 1 }}
>
{activeStep === steps.length - 1 ? 'Submit' : 'Next'}
</Button>
</Box>
</React.Fragment>
)}
</Paper>
<Copyright />
</Container>
</ThemeProvider>
);
}
|
import 'package:flutter/material.dart';
import '../../../../../core/util/widgets/custom_card.dart';
import '../../../data/models/ingredient.dart';
import '../../../data/models/mesauring_icon_icons.dart';
class IngredientItem extends StatelessWidget {
const IngredientItem({
super.key,
required this.ingredient,
});
final Ingredient ingredient;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 200,
child: CustomCard(
borderRadius: BorderRadius.circular(30),
elevation: 3,
onTap: () {},
margin: const EdgeInsets.all(5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
padding: const EdgeInsets.only(top: 10),
alignment: Alignment.center,
child: Transform.flip(
flipX: Directionality.of(context) == TextDirection.rtl,
child: Image.network(
ingredient.ingredientImage,
height: 120,
width: 120,
fit: BoxFit.contain,
errorBuilder: (ctx, error, stk) {
return const SizedBox(
height: 120,
width: 120,
child: Icon(
Icons.restaurant_rounded,
size: 55,
textDirection: TextDirection.ltr,
),
);
},
),
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.all(3),
child: Text(
ingredient.ingredientName,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge,
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsetsDirectional.only(start: 8),
child: Icon(MesauringIcon.measuringSpoons),
),
const SizedBox(width: 8),
Expanded(
child: Text(
ingredient.ingredientAmount,
// textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleMedium,
),
),
],
),
)
],
),
),
);
}
}
|
/*
* Licensed to Muhammad Hamadto
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* See the NOTICE file distributed with this work for additional information regarding copyright ownership.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sandpipers.cdk.core.construct.apigateway;
import io.sandpipers.cdk.core.construct.BaseConstruct;
import io.sadpipers.cdk.type.SafeString;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import software.amazon.awscdk.services.apigateway.LambdaRestApiProps;
import software.constructs.Construct;
/**
* L3 Construct representing AWS::ApiGateway::RestApi (Lambda Rest Api)
* <p> Example usage can be found in <a
* href="https://github.com/muhamadto/sandpipers-cdk/blob/main/sandpipers-cdk-examples/sandpipers-cdk-example-lambda/src/main/java/com/sandpipers/cdk/example/lambda/LambdaStack.java">sandpipers-cdk-example-lambda</a></p>
*/
@Getter
public class LambdaRestApi extends Construct implements BaseConstruct {
private software.amazon.awscdk.services.apigateway.LambdaRestApi lambdaRestApi;
public LambdaRestApi(
@NotNull final Construct scope,
@NotNull final SafeString id,
@NotNull final LambdaRestApiProps props) {
super(scope, id.getValue());
this.lambdaRestApi = software.amazon.awscdk.services.apigateway.LambdaRestApi.Builder.create(this, id.getValue())
.handler(props.getHandler())
.integrationOptions(props.getIntegrationOptions())
.proxy(props.getProxy())
.deploy(props.getDeploy())
.domainName(props.getDomainName())
.policy(props.getPolicy())
.defaultCorsPreflightOptions(props.getDefaultCorsPreflightOptions())
.defaultIntegration(props.getDefaultIntegration())
.defaultMethodOptions(props.getDefaultMethodOptions())
.cloudWatchRole(props.getCloudWatchRole())
.cloudWatchRoleRemovalPolicy(props.getCloudWatchRoleRemovalPolicy())
.deployOptions(props.getDeployOptions())
.description(props.getDescription())
.disableExecuteApiEndpoint(props.getDisableExecuteApiEndpoint())
.endpointExportName(props.getEndpointExportName())
.endpointTypes(props.getEndpointTypes())
.failOnWarnings(props.getFailOnWarnings())
.parameters(props.getParameters())
.retainDeployments(props.getRetainDeployments())
.apiKeySourceType(props.getApiKeySourceType())
.binaryMediaTypes(props.getBinaryMediaTypes())
.cloneFrom(props.getCloneFrom())
.endpointConfiguration(props.getEndpointConfiguration())
.minCompressionSize(props.getMinCompressionSize())
.build();
}
}
|
"use client";
import { MapPinIcon, MapIcon, StarIcon } from "@heroicons/react/24/outline";
import clsx from "clsx";
import Link from "next/link";
import { usePathname } from "next/navigation";
const BottomTabs = () => {
const pathname = usePathname();
return (
<div
className={clsx(
"fixed w-full left-0",
"flex items-center justify-between h-16",
"text-sm bottom-0 z-10 bg-white divide-x shadow-2xl"
)}
>
<Link
href="/mypage"
className={clsx("bottom-tab", {
"bottom-tab-active": "/mypage" === pathname,
})}
>
<div>
<MapPinIcon className="bottom-tab-icon" />
<span>나의 지역</span>
</div>
</Link>
<Link
href="/"
className={clsx("bottom-tab", {
"bottom-tab-active": "/" === pathname,
})}
>
<div>
<MapIcon className="bottom-tab-icon" />
<span>전체 지역</span>
</div>
</Link>
<Link
href="/favorites"
className={clsx("bottom-tab", {
"bottom-tab-active": "/favorites" === pathname,
})}
>
<div>
<StarIcon className="bottom-tab-icon" />
<span>즐겨찾기</span>
</div>
</Link>
</div>
);
};
export default BottomTabs;
|
import streamlit as st
import random
import time
# Define the choices
choices = ['rock', 'paper', 'scissors']
# Initialize scores
if 'scores' not in st.session_state:
st.session_state['scores'] = {'user': 0, 'computer': 0}
# Game logic
def game_logic(user_choice, computer_choice):
"""
Determines the winner of a rock-paper-scissors game.
Args:
user_choice (str): The user's choice ('rock', 'paper', or 'scissors').
computer_choice (str): The computer's choice ('rock', 'paper', or 'scissors').
Returns:
str: The winner of the game ('user', 'computer', or 'tie').
"""
if user_choice == computer_choice:
return 'tie'
elif (user_choice == 'rock' and computer_choice == 'scissors') or \
(user_choice == 'scissors' and computer_choice == 'paper') or \
(user_choice == 'paper' and computer_choice == 'rock'):
return 'user'
else:
return 'computer'
# Streamlit app
st.title('Rock-Paper-Scissors Game')
user_choice = st.selectbox('Choose rock, paper, or scissors:', choices, key="user_choice_selectbox")
computer_choice = random.choice(choices)
result = game_logic(user_choice, computer_choice)
if st.button('Play', key="play_button"):
with st.spinner('Playing...'):
time.sleep(4)
# st.empty()
if result == 'user':
st.session_state['scores']['user'] += 1
st.success(f'You chose {user_choice}, computer chose {computer_choice}. You win!')
st.balloons()
elif result == 'computer':
st.session_state['scores']['computer'] += 1
st.error(f'You chose {user_choice}, computer chose {computer_choice}. You lose!')
else:
st.info(f'You chose {user_choice}, computer chose {computer_choice}. You tied!')
|
如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语
输入"(()())(())"
输出:"()()()"
输入字符串为 "(()())(())",原语分解得到 "(()())" + "(())",
删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。
栈
遍历字符串,遇到左括号就入栈,遇到右括号就出栈,每次栈空的时候,都说明找到了一个原语,记录下每个原语的起始位置和结束位置,
class Solution {
public String removeOuterParentheses(String S) {
StringBuilder ans = new StringBuilder();
Stack<Character> stack = new Stack<>();
int start = 0;// 初始化原语的起始位置
int end = 0;// 初始化原语的结束位置
boolean flag = false;// 标志每个原语
for (int i = 0;i < S.length();i++) {
char ch = S.charAt(i);
if (ch == '(') {// 遇到左括号,入栈
stack.push(ch);
if (!flag) {// 遇到的第一个左括号,是原语的开始位置,记录下原语开始位置
start = i;
flag = true;
}
}
if (ch == ')') {// 遇到右括号,出栈
stack.pop();
if (stack.isEmpty()) {// 当栈空的时候,找到了一个完整的原语
end = i;// 记录下结束位置
ans.append(S.substring(start + 1,end));// 去掉原语的最外层括号,并追加到答案中
flag = false;// 置标志为false,往后接着找下一个原语
start = end;// 往后找,再次初始化原语开始位置
}
}
}
return ans.toString();
}
}
直接处理字符串
class Solution {
public String removeOuterParentheses(String S) {
int L =1 ,R =0;
StringBuilder ans = new StringBuilder();
for(int i=1;i<S.length();i++){
if(S.charAt(i) =='(')
L++;
else
R++;
if(L !=R)
ans.append(S.charAt(i));
else{
i++;
L=1;
R=0;
}
}
return ans.toString();
}
}
|
package vip.fairy.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import vip.fairy.model.Person;
import java.util.Arrays;
import java.util.List;
@RestController
public class HelloController {
/**
* http://localhost:8080/mvc/app/hello
* <p>
* http://localhost:8080/mvc/app/
*
* @return
*/
//@RequestMapping(value = {"/", "/hello"})
@GetMapping(value = "/hello")
public String hello() {
return "hello,你好!!";
}
@GetMapping(value = "/person_json", produces = "application/json;charset=utf-8")
public List<Person> personsJson() {
return Arrays.asList(new Person(1L, "张三", 18, "广州"), new Person(2L, "李四", 20, "上海"), new Person(3L, "王五", 30, "河南"));
}
@GetMapping(value = "/person_xml", produces = "application/xml;charset=utf-8")
public List<Person> personsXml() {
return Arrays.asList(new Person(1L, "张三", 18, "广州"), new Person(2L, "李四", 20, "上海"), new Person(3L, "王五", 30, "河南"));
}
/**
* http://localhost:8080/mvc/app/person
* Person 必须包含无参构造函数,否则会无法解析数据(HttpMessageConversionException)
*/
@PostMapping(path = "/person", produces = "application/json;charset=utf-8", consumes = "application/json;charset=utf-8")
public Person add(@RequestBody Person person) {
System.out.println(person);
return person;
}
}
|
import React from 'react';
import { Squash as Hamburger } from 'hamburger-react';
import { Link } from 'react-router-dom';
import useWindowPosition from './winpos';
function NavBar (){
function mouseOver(event){
event.target.style.color = 'rgba(250, 250, 250, 0.6)';
}
function mouseOut(event){
event.target.style.color = '';
}
const textStyle = {
fontFamily:"Bodoni Moda",
color: "rgba(0,0,0,0.9)",
fontSize: '10vw',
fontWeight: 500,
transition: '0.2s',
};
const textStyleSmall = {
fontFamily:"Roboto Mono",
color: 'black',
transition: '0.2s',
};
const buttonStyle = {
border:'none',
};
const scrollPos = Math.max(0, 1 - (useWindowPosition() / 130));
const final = Math.min(0.9, scrollPos**4)
const opacityStyle = {
opacity: final,
}
return (
<nav className="navbar navbar-expand-md fixed-top my-auto" style={opacityStyle}>
<div className="container-fluid" >
<Link className="navbar-brand" style={textStyle} to="/home#" onMouseOver={mouseOver} onMouseOut={mouseOut}>WP</Link>
<button className="navbar-toggler" style={buttonStyle} type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<Hamburger className="navbar-toggler-icon" ></Hamburger>
</button>
<div className="collapse navbar-collapse" id="navbarCollapse">
<ul className="navbar-nav ml-auto flex-nowrap">
<li className="nav-item">
<Link className="nav-link" aria-current="page" style={textStyleSmall} to="/about" onMouseOver={mouseOver} onMouseOut={mouseOut}>About</Link>
</li>
<li className="nav-item">
<Link className="nav-link" style={textStyleSmall} to="/contact" onMouseOver={mouseOver} onMouseOut={mouseOut}>Contact</Link>
</li>
</ul>
</div>
</div>
</nav>
)
}
export default NavBar;
|
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Level } from '../models/Level';
import { API_URLS } from '../shared/config/API';
import { tap } from 'rxjs/operators';
import { Page } from '../models/Page';
@Injectable({
providedIn: 'root'
})
export class LevelService {
constructor(private http: HttpClient) { }
token = localStorage.getItem('token');
getLevels(): Observable<Level[]>{
return this.http.get<Level[]>(API_URLS.Levels_URL);
}
addLevel(level: Level): Observable<any> {
return this.http.post(API_URLS.Levels_URL, level);
}
deleteLevel(id: number): Observable<any> {
return this.http.delete(API_URLS.Levels_URL + `/${id}`);
}
updateLevel(level: Level): Observable<any> {
return this.http.put(API_URLS.Levels_URL + `/${level.id}`, level);
}
getLevelsPaginations(page: number, size: number): Observable<Page<Level>> {
const params = new HttpParams().set('page', page.toString()).set('size', size.toString());
return this.http.get<Page<Level>>(API_URLS.Levels_URL, { params });
}
}
|
package contest
import "github.com/lovung/ds/maths"
// Recursive solution
func canSplitArray(nums []int, m int) bool {
sum := maths.Sum(nums...)
return recursiveCanSplitArray(nums, m, sum)
}
func recursiveCanSplitArray(nums []int, m int, sum int) bool {
n := len(nums)
if n <= 2 {
return true
}
ret := false
if sum-nums[0] >= m {
ret = ret || recursiveCanSplitArray(nums[1:], m, sum-nums[0])
}
if sum-nums[n-1] >= m {
ret = ret || recursiveCanSplitArray(nums[:n-1], m, sum-nums[n-1])
}
return ret
}
// DP
func canSplitArray2(nums []int, m int) bool {
n := len(nums)
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// col is k+i
for k := 0; k < n; k++ {
for i := 0; i < n; i++ {
j := i + k
if j >= n {
break
}
switch k {
case 0:
dp[i][j] = nums[j]
case 1:
dp[i][j] = dp[i][j-1] + nums[j]
default:
if dp[i][j-1] < m && dp[i+1][j] < m {
dp[i][j] = 0
} else {
dp[i][j] = maths.Max(dp[i][j-1], dp[i+1][j]) + nums[j]
}
}
}
}
return dp[0][n-1] > 0
}
// Smartest solution
func canSplitArray3(nums []int, m int) bool {
if len(nums) <= 2 {
return true
}
for i := 1; i < len(nums); i++ {
if nums[i]+nums[i-1] >= m {
return true
}
}
return false
}
|
import asyncio
import os
from loguru import logger
import requests
import random
from web3 import AsyncWeb3, Web3
from aiohttp import ClientSession
from eth_abi import encode
import os
from dotenv import load_dotenv
from .aevo import AevoLibClient
from .aevo_trading_tool.aevo_deposit import aevo_deposit
class AevoClient:
def __init__(self) -> None:
dotenv_path = os.path.join(os.path.dirname(__file__), '..', '.env')
load_dotenv(dotenv_path=dotenv_path)
self.ADDRESS = os.environ.get('address')
self.PRIVATE_KEY = os.environ.get('private_key')
self.SIGNING_KEY = os.environ.get('signing_key')
self.API_KEY = os.environ.get('aevo_api')
self.API_SECRET = os.environ.get('aevo_secret')
self.BASE_URL = "https://api.aevo.xyz"
self.COLLATERAL_ADDRESS = "0x643aaB1618c600229785A5E06E4b2d13946F7a1A" # USDC address
self.WITHDRAW_ADDRESS = "0xE3EF8bEE5c378D4D3DB6FEC96518e49AE2D2b957" # Withdraw to address
self.CONNECTOR_ADDRESS = "0x73019b64e31e699fFd27d54E91D686313C14191C" # socket connector
self.CHAIN_ID = 42161 # Arbitrum Mainnet chain id
self.NODE_URL = os.environ.get('rpc_end_point')
self.TAKER_FEE = 0.0008
self.MAKER_FEE = 0.0005
self.aevo_client = AevoLibClient(
signing_key=self.SIGNING_KEY,
wallet_address=self.ADDRESS,
api_key=self.API_KEY,
api_secret=self.API_SECRET,
env="mainnet",
)
def place_order(self,instrument_id,is_buy,reduce_only,quantity,price):
logger.info("Creating order...")
# place market order
response = self.aevo_client.rest_create_market_order(
instrument_id=instrument_id,
is_buy=is_buy,
quantity=quantity,
reduce_only=reduce_only,
)
logger.info(response)
if not reduce_only:
# place tp
take_response = self.place_tp(instrument_id=instrument_id,is_buy=is_buy,quantity=quantity,price=price)
# place sl
stop_response = self.place_sl(instrument_id=instrument_id,is_buy=is_buy,quantity=quantity,price=price)
return response,take_response,stop_response
elif reduce_only:
# TODO cancel tpsl
return
def place_tp(self,instrument_id,is_buy,quantity,price):
logger.info("Creating tp order...")
limit_price = 0
if is_buy:
limit_price = 2**256 - 1
trigger_price = price*(.97) if not is_buy else price*(1.03)
take_response = self.aevo_client.rest_create_order(
instrument_id=instrument_id,
is_buy=not is_buy,
limit_price=limit_price,
quantity=quantity,
close_position=True,
stop='TAKE_PROFIT',
trigger=trigger_price
)
logger.info(take_response)
return take_response
def place_sl(self,instrument_id,is_buy,quantity,price):
logger.info("Creating sl order...")
limit_price = 0
if is_buy:
limit_price = 2**256 - 1
trigger_price = price*(.97) if is_buy else price*(1.03)
stop_response = self.aevo_client.rest_create_order(
instrument_id=instrument_id,
is_buy=not is_buy,
limit_price=limit_price,
quantity=quantity,
close_position=True,
stop='STOP_LOSS',
trigger=trigger_price
)
logger.info(stop_response)
return stop_response
async def get_account(self) -> None:
logger.info("Getting AEVO portfolio...")
response = self.aevo_client.rest_get_account()
return response
async def get_fundings(self) -> None:
response = self.aevo_client.rest_get_account_fundings()
return response
async def get_positions(self) -> None:
response = self.aevo_client.rest_get_positions()
return response
async def get_markets(self,asset,instrument) -> None:
response = self.aevo_client.get_markets(asset,instrument)
return response
def get_funding(self,coins:str)-> None:
result = {}
for coin in coins:
coin_name = coin
if coin[0] == 'k':
coin_name = coin.replace('k','1000')
url = f"{self.BASE_URL}/funding?instrument_name={coin_name}-PERP"
headers = {"accept": "application/json"}
response = requests.get(url, headers=headers)
rsp_json = response.json()
result[coin] = rsp_json['funding_rate']
return result
async def deposit(self,amount:float)-> None:
await aevo_deposit(amount=amount)
async def sign_withdraw(
self,
web3: AsyncWeb3,
collateral: str,
to: str,
amount: int,
salt: int,
private_key: str,
socket_fees: int,
socket_msg_gas_limit: int,
socket_connector: str
) -> str:
data = encode(
["uint256", "uint256", "address"],
[socket_fees, socket_msg_gas_limit, socket_connector]
)
key_signature = web3.eth.account.sign_typed_data(
domain_data={
"name": "Aevo Mainnet",
"version": "1",
"chainId": self.CHAIN_ID,
},
message_types={
"Withdraw": [
{"name": "collateral", "type": "address"},
{"name": "to", "type": "address"},
{"name": "amount", "type": "uint256"},
{"name": "salt", "type": "uint256"},
{"name": "data", "type": "bytes32"}
]
},
message_data={
"collateral": web3.to_checksum_address(collateral),
"to": web3.to_checksum_address(to),
"amount": amount,
"salt": salt,
"data": web3.keccak(data)
},
private_key=private_key
)
return key_signature.signature.hex()
async def withdraw(self, amount: float):
web3 = AsyncWeb3(Web3.HTTPProvider(self.NODE_URL))
salt = random.randint(0, 10 ** 10)
amount_in_micro = int(amount * 10 ** 6) # Convert amount to micro-units as expected by the contract
socket_fees = random.randint(4326304606198636, 4326309606198636)
socket_msg_gas_limit = 2000000
signature = await self.sign_withdraw(
web3, self.COLLATERAL_ADDRESS, self.WITHDRAW_ADDRESS, amount_in_micro, salt, self.PRIVATE_KEY,
socket_fees, socket_msg_gas_limit, self.CONNECTOR_ADDRESS
)
payload = {
"account": web3.to_checksum_address(self.ADDRESS),
"amount": str(amount_in_micro),
"collateral": web3.to_checksum_address(self.COLLATERAL_ADDRESS),
"salt": str(salt),
"signature": signature,
"socket_connector": self.CONNECTOR_ADDRESS,
"socket_fees": str(socket_fees),
"socket_msg_gas_limit": str(socket_msg_gas_limit),
"to": web3.to_checksum_address(self.WITHDRAW_ADDRESS),
}
async with ClientSession() as session:
response = await session.post(f'{self.BASE_URL}/withdraw', json=payload)
response_data = await response.json()
if response.status != 200:
logger.error(f"Something went wrong: {response_data}")
return
logger.info(f"Successfully withdrawn {amount} USDC")
if __name__ == "__main__":
# asyncio.run(aevo_create_order(instrument_id=1,is_buy=False,reduce_only=True,quantity=0.01))
# response = asyncio.run(aevo_markets(asset='ETH',instrument='PERPETUAL'))
aevo_client = AevoClient()
response = asyncio.run(aevo_client.deposit(amount=1))
print(response)
|
//import JWT Token
const jwt = require('jsonwebtoken');
const db = require('./db')
const register = (uname, fullName, pswd) => {
return db.User.findOne({ uname })
.then(user => {
if (user) {
return {
status: false,
statusCode: 400,
message: 'User already registered'
}
}
else {
const newUser = new db.User({
uname: uname,
fullName: fullName,
pswd: pswd,
watchlist: []
})
newUser.save(); //data saved in mongodb
// this.saveDetails();
return {
status: true,
statusCode: 200,
message: 'Registered Successfully'
}
}
})
}
const login = (uname, pswd) => {
return db.User.findOne({ uname, pswd })
.then(user => {
if (user) {
currentUser = user.uname
fullName = user.fullName
//To generate Token
const token = jwt.sign({ currentUser: uname }, 'superkey2022') //superkey is a secret key(private key)
return {
status: true,
statusCode: 200,
message: 'Login Successful',
currentUser: currentUser,
fullName: fullName,
token: token
}
}
else {
return {
status: false,
statusCode: 400,
message: 'Invalid userdetails'
}
}
})
}
//get all the movies from db
const getMovies = () => {
return db.Movie.find().then(
(result) => {
if (result) {
return {
status: true,
statusCode: 200,
movies: result
}
}
else {
return {
status: false,
statusCode: 404,
message: ' Movie not found'
}
}
}
)
}
const getTrending = () => {
return db.Trending.find().then(
(result) => {
if (result) {
return {
status: true,
statusCode: 200,
result
}
}
else {
return {
status: false,
statusCode: 404,
message: 'No Movie found'
}
}
}
)
}
// const addtoWatchlist=(id, original_title, overview, poster_path, media_type, vote_average, release_date)=>{
// //data added to mongodb -- create a model in db.js
// return db.Watchlist.findOne({id}).then(
// (result)=>{
// if(result){
// return{
// status:true,
// statusCode:200,
// message:'Movie already exist'
// }
// }
// else{
// const newMovie= new db.Watchlist({id, original_title, overview, poster_path, media_type, vote_average, release_date})
// newMovie.save() //to save data into mongodb
// return{
// status:true,
// statusCode:200,
// message:'Movie added to Watchlist'
// }
// }
// }
// )
// }
const addtoWatchlist = (uname, id, title, name, original_title, original_name, overview, poster_path, media_type, vote_average, release_date, first_air_date) => {
//data added to mongodb -- create a model in db.js
return db.Watchlist.findOne({ uname, id }).then(
(result) => {
if (result) {
return {
status: true,
statusCode: 200,
message: 'already exist in the Watchlist'
}
}
else {
const newMovie = new db.Watchlist({ uname, id, title, name, original_title, original_name, overview, poster_path, media_type, vote_average, release_date, first_air_date })
newMovie.save() //to save data into mongodb
return {
status: true,
statusCode: 200,
message: 'Saved to Watchlist'
}
}
}
)
}
//to get wishlist
const getWatchlist = (uname) => {
return db.Watchlist.find({ uname }).then(
(result) => {
if (result) {
return {
status: true,
statusCode: 200,
watchlists: result
}
}
else {
return {
status: false,
statusCode: 404,
message: 'Your Watchlist is empty!'
}
}
}
)
}
//to delete wishlist
const deleteWatch = (uname, id) => {
return db.Watchlist.deleteOne({ uname, id }).then(
(result) => {
if (result) {
console.log(result, 'after removing#');
return db.User.find().then(
(result) => {
if (result) {
return {
status: true,
statusCode: 200,
watchlists: result,
message: "Movie Successfully Removed From The Watchlist"
}
}
else {
return {
status: false,
statusCode: 404,
message: 'Movie not found'
}
}
}
)
}
else {
return {
status: false,
statusCode: 404,
message: 'Movie not found'
}
}
}
)
}
const emptyWatchlist = (uname) => {
return db.Watchlist.remove({ uname })
.then(result => {
if (result) {
return {
status: true,
statusCode: 200,
message: 'watchlist emptied!'
}
}
else {
return {
status: false,
statusCode: 400,
message: 'Wathchlist not found'
}
}
})
}
//to add review
const addReview = (uname, author, id, rating, comment, reviewTime) => {
//data added to mongodb -- create a model in db.js
return db.Review.findOne({ uname, id }).then(
(result) => {
if (result) {
return {
status: true,
statusCode: 200,
message: 'Already reviewed, Please try to edit!'
}
}
else {
const newReview = new db.Review({ uname, author, id, rating, comment, reviewTime })
newReview.save() //to save data into mongodb
return {
status: true,
statusCode: 200,
message: 'Review added successfully'
}
}
}
)
}
//to get reviews
const getReviews = (id) => {
return db.Review.find({ id }).then(
(result) => {
if (result) {
return {
status: true,
statusCode: 200,
reviews: result
}
}
else {
return {
status: false,
statusCode: 404,
message: 'No review found!'
}
}
}
)
}
//to edit review
const getEditedReview = (uname, id, rating, comment, reviewTime) => {
return db.Review.findOne({ uname, id }).then(
(result) => {
if (result) {
result.rating = rating;
result.comment = comment;
result.reviewTime = reviewTime;
result.save();
return {
status: true,
statusCode: 200,
message: 'Review edited successfully',
reviews: result
}
}
else {
return {
status: false,
statusCode: 400,
message: 'Review editing failed!'
}
}
}
)
}
const deleteReview = (uname, id) => {
return db.Review.deleteOne({ uname, id })
.then(result => {
if (result) {
return {
status: true,
statusCode: 200,
message: 'Review deleted successfully',
reviews: result
}
}
else {
return {
status: false,
statusCode: 400,
message: 'Review not found'
}
}
})
}
// To delete an account
const deleteAcc = (uname) => {
return db.User.deleteOne({ uname })
.then(user => {
if (user) {
emptyWatchlist(uname);
return {
status: true,
statusCode: 200,
message: 'Account deleted successfully'
}
}
else {
return {
status: false,
statusCode: 400,
message: 'user not found'
}
}
})
}
module.exports = {
register,
login,
getMovies,
getTrending,
addtoWatchlist,
getWatchlist,
deleteWatch,
emptyWatchlist,
addReview,
getReviews,
getEditedReview,
deleteReview,
deleteAcc,
}
|
import 'package:advert/add_product/add_product.dart';
import 'package:advert/models/information.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class HomeView extends StatelessWidget {
const HomeView({super.key});
Stream<QuerySnapshot> readTodo() {
final db = FirebaseFirestore.instance;
return db.collection('products').snapshots();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 207, 97, 227),
body: StreamBuilder(
stream: readTodo(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CupertinoActivityIndicator(
color: Colors.pink,
radius: 30,
),
);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else if (snapshot.hasData) {
final List<Information> product = snapshot.data!.docs
.map((e) =>
Information.fromMap(e.data() as Map<String, dynamic>))
.toList();
return ListView.builder(
itemCount: product.length,
itemBuilder: (context, index) {
final products = product[index];
return Card(
child: Column(
children: [
products.image != null
? SizedBox(
height: 200,
child: PageView.builder(
itemCount: products.image!.length,
itemBuilder: (context, index) {
final images = products.image![index];
return Image.network(images);
}),
)
: const SizedBox(),
const SizedBox(height: 30),
ListTile(
title: Text(products.title),
leading: Text(products.description),
subtitle: Text(products.dateTime),
trailing: Text(products.adress),
)
],
),
);
});
} else {
return const Text("Unknown error");
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const AddProduct()),
);
},
child: const Icon(Icons.publish),
),
);
}
}
|
---
keywords: Personal Finance,Taxes,Tax Deductions and Credits,Deductions and Credits
title: 普通损失
description: 普通损失是因正常业务经营、非资本交易或出售非资本资产而实现的损失。
---
# 普通损失
## 什么是普通损失?
普通损失是纳税人在正常业务运营中支出超过收入时实现的损失。普通损失是纳税人遭受的非资本损失的损失。普通损失可以完全扣除以抵消收入,从而减少纳税人所欠税款。
## 了解普通损失
普通损失可能源于多种原因,包括伤亡和盗窃。当普通损失超过纳税人在一个纳税年度的总收入时,它们就可以扣除了。资本和普通是适用于特定资产销售和交易的两种税率。税率与纳税人的[边际税率挂钩](/marginaltaxrate)。净长期资本利率明显低于普通利率。因此,传统观点认为纳税人更喜欢资本收益率和普通损失率。
2017 年,7 个税级的税率从普通税率的 10% 到 39.6%,从长期资本净利率的 0% 到 20%。此外,最高税级的纳税人必须缴纳 3.8% 的[净投资](/netinvestmentincome)[收益税 (NIIT)](/netinvestmentincome) 。大多数情况下,这些税率在 2018 年适用。例外的是,普通税率现在从 10% 到 37% 不等,长期资本利率的收入门槛也略有变化。例如,对于最高税级的纳税人,2017 年的普通税率为 43.4%,但 2018 年为 40.8%,2017 年和 2018 年资本税率为 23.8%。
## 普通损失与资本损失
普通损失是不属于[资本损失的任何损失的隐喻废纸篓](/capitalloss)。当您出售资本资产(例如股票市场投资或您拥有的供个人使用的财产)时,就会发生资本损失。普通损失的确认是在您出售财产(例如库存、供应品、经商应收账款)、用作出租财产的房地产以及知识产权(例如音乐、文学、软件编码或艺术作品)时。这是由经营企业的企业主实现的损失,由于费用超过收入而未能盈利。由于纳税人在进行贸易或业务过程中的个人努力而创造或可用的财产确认的损失是一般损失。
例如,你花了 110 美元写了一个乐谱,你卖 100 美元。你有 10 美元的普通损失。
普通损失也可能源于其他原因。伤亡、盗窃和[关联方销售](/related-partytransaction)实现普通损失。出售[第 1231 节财产](/section-1231)(例如用于贸易或业务超过一年的不动产或可折旧商品)的销售也是如此。
## 纳税人的普通损失
纳税人喜欢他们的可扣除损失是普通的。总体而言,普通损失比长期资本损失更能节省税收。普通损失大部分可以在损失当年完全扣除,而资本损失则不能。普通损失将一对一地抵消普通收入和资本收益。资本损失严格限于抵消资本收益和最多 3,000 美元的普通收入。剩余的资本损失必须结转到另一年。
假设在纳税年度您赚了 100,000 美元并有 80,000 美元的开支。您购买了股票和债券,六个月后以多出 2,000 美元的价格卖出了股票,并以比您支付的价格低 1,000 美元的价格卖出了债券。然后,当你卖出一年多前购买的股票和债券时,股市暴跌,以至于你卖出股票的价格比你支付的少 14,000 美元,而债券的价格比你支付的多 3,000 美元。让我们将您的收益和损失净额计算出您的整体收益或损失,以及它是普通的还是资本的。
- 净您的短期资本收益和损失。 2,000 美元 - 1,000 美元 = 1,000 美元净短期资本收益。
- 净您的长期资本收益和损失。 $3,000 - $14,000 = $11,000 净长期资本损失。
- 净您的净短期和长期资本收益和损失。 1,000 美元 - 11,000 美元 = 10,000 美元净长期资本损失。
- 净您的普通收入和损失。 100,000 美元 - 80,000 美元 = 20,000 美元普通收益。
- 净您的净普通和净资本收益和损失。 $20,000 - $3,000 = $17,000 普通收益。
-在未来三年[结转剩余的 7,000 美元净资本损失。](/losscarryforward)
## 强调
- 普通损失与资本损失分开。
- 当费用超过正常业务运营中的收入时,纳税人实现了普通损失。
- 普通损失可完全扣除以抵消收入,从而减少纳税人所欠税款。
|
import bpy
import os
bl_info = {
"name": "Import Octance Lights",
"blender": (3, 64, 0),
"category": "Object",
}
def get_script_run_count():
counter_file_path = os.path.join(os.path.expanduser('~'), 'Documents', 'counter.txt')
if os.path.exists(counter_file_path):
with open(counter_file_path, 'r') as file:
counter = int(file.read().strip())
else:
counter = 0
return counter - 1
def update_script_run_count():
counter_file_path = os.path.join(os.path.expanduser('~'), 'Documents', 'counter.txt')
current_count = get_script_run_count() + 1
with open(counter_file_path, 'w') as file:
file.write(str(current_count + 1))
def link_texture_to_light_from_folder(folder_path):
extensions = ['.png', '.jpg', '.jpeg', '.tiff', '.bmp']
for light in bpy.data.lights:
image_path = None
for ext in extensions:
potential_path = os.path.join(folder_path, light.name + ext)
if os.path.exists(potential_path):
image_path = potential_path
break
if image_path:
# Enable use of nodes for this light data block
light.use_nodes = True
nodes = light.node_tree.nodes
nodes.clear() # Clear existing nodes
# Create necessary nodes
geom_node = nodes.new(type='ShaderNodeNewGeometry')
mapping_node = nodes.new(type='ShaderNodeMapping')
texture_node = nodes.new(type='ShaderNodeTexImage')
emission_node = nodes.new(type='ShaderNodeEmission')
output_node = nodes.new(type='ShaderNodeOutputLight')
# Load and assign the image to the texture node
image = bpy.data.images.load(image_path)
texture_node.image = image
# Set up node locations (for a cleaner layout)
geom_node.location = (-600, 0)
mapping_node.location = (-400, 0)
texture_node.location = (-200, 0)
emission_node.location = (0, 0)
output_node.location = (200, 0)
# Link the nodes together
links = light.node_tree.links
links.new(geom_node.outputs['Parametric'], mapping_node.inputs['Vector'])
links.new(mapping_node.outputs['Vector'], texture_node.inputs['Vector'])
links.new(texture_node.outputs['Color'], emission_node.inputs['Color'])
links.new(emission_node.outputs['Emission'], output_node.inputs['Surface'])
#清除未使用的数据块
for block in bpy.data.meshes:
if block.users == 0:
bpy.data.meshes.remove(block)
for block in bpy.data.materials:
if block.users == 0:
bpy.data.materials.remove(block)
imported_objects = [obj for obj in bpy.context.selected_objects]
def import_and_delete_usd(filepath, scale_factor):
global script_run_count
try:
# 导入 USD 文件
bpy.ops.wm.usd_import(filepath=filepath, scale=scale_factor)
print("USD文件导入成功!")
# 删除与 USD 文件关联的所有对象
imported_objects = [obj for obj in bpy.context.selected_objects]
# 删除文件
os.remove(filepath)
update_script_run_count()
print(f"已成功删除 {filepath} 文件!")
except Exception as e:
print(f"导入或删除文件时出错: {e}")
# 在函数末尾递增 run_count
finally:
# 在函数末尾递增 run_count
script_run_count += 1
# 设置文件路径和其他参数
script_run_count = get_script_run_count()
usd_filepath = f"C:\\Users\\Administrator\\Documents\\lights{script_run_count}.usdc"
scale = 0.01
folder_path = "C:\\Users\\Administrator\\Documents\\"
class OBJECT_OT_CustomOperator(bpy.types.Operator):
bl_idname = "object.custom_operator"
bl_label = "Import Octance Lights"
def execute(self, context):
script_run_count = get_script_run_count()
usd_filepath = f"C:\\Users\\Administrator\\Documents\\lights{script_run_count}.usdc"
scale = 0.01
folder_path = "C:\\Users\\Administrator\\Documents\\"
import_and_delete_usd(usd_filepath, scale)
link_texture_to_light_from_folder(folder_path)
return {'FINISHED'}
class OBJECT_PT_CustomPanel(bpy.types.Panel):
bl_label = "Python Script"
bl_idname = "OBJECT_PT_custom"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Tools'
def draw(self, context):
layout = self.layout
layout.operator("object.custom_operator")
def register():
bpy.utils.register_class(OBJECT_OT_CustomOperator)
bpy.utils.register_class(OBJECT_PT_CustomPanel)
def unregister():
bpy.utils.unregister_class(OBJECT_OT_CustomOperator)
bpy.utils.unregister_class(OBJECT_PT_CustomPanel)
if __name__ == "__main__":
register()
|
/*
* RERO ILS UI
* Copyright (C) 2021 RERO
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { Injectable } from '@angular/core';
import { Record, RecordService } from '@rero/ng-core';
import { Error } from '@rero/ng-core/lib/error/error';
import { BaseApi } from '@rero/shared';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PatronTransactionApiService extends BaseApi {
/**
* Constructor
* @param _recordService - RecordService
*/
constructor(private _recordService: RecordService) {
super();
}
/**
* Get fees
* @param patronPid - string
* @param status - string
* @param page - number
* @param itemsPerPage - number
* @param headers - object
* @return Observable
*/
getFees(
patronPid: string, status: string, page: number,
itemsPerPage: number = 10, headers = BaseApi.reroJsonheaders
): Observable<Record | Error> {
const query = `patron.pid:${patronPid} AND status:${status}`;
return this._recordService.getRecords(
'patron_transactions', query, page, itemsPerPage,
undefined, undefined, headers, undefined, ['total']
);
}
}
|
{% load static %}
<!-- Question -->
<div class="question">
<div class="row">
<div class="col-2 border-end border-4">
<!-- Avatar -->
<a href="#">
{% with avatar_url=question.author.avatar.url avatar_type="question-avatar" %}
{% include "inc/avatar-item.html" %}
{% endwith %}
{% comment %} <div class="question-avatar">
<div>
<img src="{{ question.author.avatar.url }}" alt="Avatar" />
</div>
</div> {% endcomment %}
</a>
<!-- Username -->
<div class="username">
<a href="#">{{ question.author.user|truncatechars:13 }}</a>
</div>
</div>
<div class="col-10">
<!-- Title -->
<h2 class="question-title">
<a href="{% url "question" question.id %}">{{ question.title }}</a>
</h2>
<!-- Question text -->
<div class="question-text">{{ question.content|linebreaksbr|truncatechars:400 }}</div>
</div>
</div>
<div class="row">
<!-- Tags -->
<div class="col-8 tags">
{% for tag in question.tag.all %}
{% include "inc/tag-item.html" %}
{% endfor %}
</div>
<!-- Answers -->
<div class="col-2">
<div class="icon-container">
<span><a href="#">
<img src="{% static "img/svg/answer-icon.svg" %}" alt="answers"
class="img-icon img-icon-question" /></a><span
class="answers-count fw-bold text-dark font-monospace fs-5 align-middle">{{ question.answers_count }}</span></span>
</div>
</div>
<!-- Votes -->
<div class="col-2">
{% with vote_obj=question icon_type="question" %}
{% include "inc/votes-item.html" %}
{% endwith %}
</div>
</div>
</div>
|
<div class="row" >
<!-- <h1 *ngIf="filteredBooks.length == 0">No items found.</h1> -->
<div *ngIf="sortedViewEnabled">
<div *ngFor="let genre of genres" class="col-md-5" >
<label style="color: orange;">{{genre.name | uppercase}}</label>
<hr>
<div *ngFor="let book of genre.books">
<book-item [book]="book" (bookUpdateEvent)="updateData()"></book-item>
</div>
</div>
</div>
<div *ngIf="!sortedViewEnabled">
<div *ngFor="let book of filteredBooks"class="col-md-8">
<book-item [book]="book" (bookUpdateEvent)="updateData()"></book-item>
</div>
</div>
</div>
<div class="myToolBar">
<form id="searchForm" (ngSubmit)="searchBooks(searchTerm)" class="col-md-2 search" >
<div class="form-group">
<input [(ngModel)]="searchTerm" name="searchTerm" type="text" class="form-control" placeholder="Search books" >
</div>
<button class="btn btn-primary" style="width: 100px;">
Search
</button>
<button class="btn btn-info" aria-label="Close" style="margin-left: 3px;" (click)="clearFilter()">
<span aria-hidden="true" >×</span>
</button>
</form>
<button (click)="changeBooksView()" class="btn btn-primary sort" [innerText]="buttonTitle" style="width: 100px;"></button>
<div class="sort2" *ngIf="!sortedViewEnabled">
<input type="radio" value="byTitle" name="byTitle" [checked]="byTitleChecked" (click)="handleRadioButton('byTitle')"> Sort by title
<hr>
<input type="radio" value="byAuthor" name="byAuthor" [checked]="byAuthorChecked" (click)="handleRadioButton('byAuthor')"> Sort by author
<hr>
<input type="radio" value="byPrice" name="byPrice" [checked]="byPriceChecked" (click)="handleRadioButton('byPrice')"> Sort by price
<hr>
</div>
</div>
|
package com.example.DemoLoginLogout.service;
import com.example.DemoLoginLogout.model.AppUser;
import com.example.DemoLoginLogout.model.Role;
import com.example.DemoLoginLogout.repository.RoleRepository;
import com.example.DemoLoginLogout.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class UserServiceImplTest {
@Mock
UserRepository userRepository;
@InjectMocks
UserServiceImpl userService;
@Mock
PasswordEncoder passwordEncoder;
@Mock
RoleRepository roleRepository;
@Test
public void when_saveUser_should_return_user() {
ArrayList<Role> roles = new ArrayList();
roles.add(new Role(null, "ROLE_USER"));
AppUser user = new AppUser(null, "George", "Georgescu", "george90", "password", roles);
when(userRepository.save(any(AppUser.class))).thenReturn(user);
AppUser createdUser = userService.saveUser(user);
assertThat(createdUser.getFirstName()).isSameAs(user.getFirstName());
assertThat(createdUser.getLastName()).isSameAs(user.getLastName());
assertThat(createdUser.getUsername()).isSameAs(user.getUsername());
assertThat(createdUser.getRoles()).isSameAs(user.getRoles());
}
}
|
const mongoose = require('mongoose');
const { Schema } = require('mongoose');
const bcrypt = require('bcrypt');
const Department = require('./Department');
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
},
email: {
type: String,
required: true,
unique: true,
match: [/.+@.+\..+/, 'Must match an email address!'],
},
password: {
type: String,
required: true,
minlength: 5,
},
department: [Department.schema],
});
userSchema.pre('save', async function (next) {
if (this.isNew || this.isModified('password')) {
const saltRounds = 10;
this.password = await bcrypt.hash(this.password, saltRounds);
}
next();
});
userSchema.methods.isCorrectPassword = async function (password) {
return bcrypt.compare(password, this.password);
};
const User = mongoose.model('User', userSchema);
module.exports = User;
|
import { CustomForm } from "../customForm/CustomForm";
import { CustomInput } from "../customInput/CustomInput";
import { Button } from "../button/Button";
import { NavLink } from "react-router-dom";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { Controller } from "react-hook-form";
import { useDispatch } from "react-redux";
import { fetchSignup } from "../../features/authSlice";
import { useNavigate } from "react-router-dom";
const schema = yup
.object({
email: yup.string().email().required(),
password: yup.string().min(6).required(),
})
.required();
export const RegistrationForm = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const {
control,
handleSubmit,
reset,
formState: { errors },
} = useForm({
resolver: yupResolver(schema),
defaultValues: {
email: "",
password: "",
},
});
const onSubmit = (data) => {
dispatch(fetchSignup({ ...data }))
.unwrap()
.then(() => {
reset();
navigate("/login");
});
};
return (
<CustomForm onSubmit={handleSubmit(onSubmit)}>
<div className={"div flex-col w-full relative"}>
<Controller
name="email"
control={control}
render={({ field }) => <CustomInput {...field} type="email" placeholder="Email" />}
/>
<p className="text-xs text-red py-[0.2rem] absolute bottom-[-1.3rem]">
{errors.email?.message}
</p>
</div>
<div className={"div flex-col w-full relative"}>
<Controller
name="password"
control={control}
render={({ field }) => <CustomInput {...field} type="password" placeholder="Password" />}
/>
<p className="text-xs text-red py-[0.2rem] absolute bottom-[-1.3rem]">
{errors.password?.message}
</p>
</div>
<Button type="submit" cn={"w-full"}>
Sign Up
</Button>
<div className={"flex items-center justify-center"}>
<span className="text-sm text-slate">
Have an account?{" "}
<NavLink
className={"text-slate hover:text-mainGreen transition duration-200 px-2"}
to={"/login"}
>
Sign In
</NavLink>
</span>
</div>
</CustomForm>
);
};
|
/**
* This class runs the code and displays the GUI
* @author Ojas Hunjan, Jawalant Patel, Lance Cheong Youne
*/
// Imports needed
import java.util.*;
import java.util.Map.Entry;
// userDictionary(child class) inherits methods from checkSpelling(super class)
public class userDictionary extends checkSpelling{
//initialize private variable
private Hashtable<String, String> userDictionary;
/**
* class constructor method
* sets initial value for necessary variables
*/
public userDictionary(){
super();
this.userDictionary = new Hashtable<String, String>();
}
/**
* setDictionary getter method used to initialize the dictionary
* @param none
* @return Hashtable<String, String> contains the user dictionary
*/
public Hashtable<String, String> getUserDictionary(){
return this.userDictionary;
}
/**
* addWordUser method adds the word to the user dictionary
* @param String is the word to be added to user dictionary
* @return void
*/
public void addWordUser(String word) {
if(!this.userDictionary.containsKey(word)){
this.userDictionary.put(word, word);
}
}
/**
* removeWordUser method removes the word from the user dictionary
* @param String is the word to be removed foro
* @return void
*/
public void removeWordUser(String word) {
if(this.userDictionary.containsKey(word)){
this.userDictionary.remove(word, word);
}
}
/**
* userDictionarytoString toString method used to convert the user dictionary to a string
* @param none
* @return String contains the user dictionary
*/
public String userDictionarytoString(){
// Uses string builder to construct a string
StringBuilder sb = new StringBuilder();
//enchance for loop to iterate the set of user dictionary
for (Entry<String, String> entry: this.userDictionary.entrySet()) {
String key = entry.getKey();
sb.append(key).append("\n"); // adds word to end of sb
}
String result = sb.toString(); // StringBuilder toString method
return result;
}
}
|
import React, { useEffect } from "react";
import { useDispatch, useSelector } from 'react-redux'
import { fetchTitlesLines, filterTitlesLines } from '../../../redux/slices/titles'
import Gstyles from "../../GraphApp.module.css"
import styles from "./LineDiv.module.css"
import { arrTitles } from "../../../FacDepTitlesNames";
import { FacultiesColors } from "../../Colors";
import { GraphFilter } from "../../GraphFilter";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js'
import { Line } from 'react-chartjs-2'
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
)
export function TitlesLines(props) {
const dispatch = useDispatch()
const { titlesLines } = useSelector(state => state.titles)
useEffect(() => {
dispatch(fetchTitlesLines())
}, [dispatch])
// const labels = titlesLines.items.reduce((prev, curr) => {
let labels = (titlesLines.filtered ? titlesLines.changedItems : titlesLines.items).reduce((prev, curr) => {
curr.citationArray.forEach(item => {
if (!prev.includes(item.year)) {
prev.push(item.year)
}
})
return prev
}, []).sort()
let index = -1;
// const datasets = titlesLines.items.map(item => {
let datasets = (titlesLines.filtered ? titlesLines.changedItems : titlesLines.items).map(item => {
index++
let arrCited = Array(labels.length - item.citationArray.length)
arrCited = arrCited.concat(item.citationArray.map(obj => obj.cited))
return Object({
label: item.name,
data: arrCited,
backgroundColor: FacultiesColors[index % FacultiesColors.length],
borderColor: FacultiesColors[index % FacultiesColors.length],
})
}).sort()
console.log(datasets)
const data = {
labels: labels,
datasets: datasets,
}
const options = {
responsive: true,
maintainAspectRatio: false,
scales: {
y:{
title:{
display:true,
text:"h-индекс",
color: "rgb(33,47,92)",
}
},
x:{
title:{
display:true,
text:"Год",
color: "rgb(33,47,92)",
}
},
},
plugins: {
legend:{
display:false,
},
}
}
return(
<div className={styles.TitlesLines}>
<GraphFilter filter={filterTitlesLines} array={arrTitles} cid={Gstyles.trd}/>
<h3>ПО ДОЛЖНОСТЯМ</h3>
<div className={styles.TL}>
<div className={styles.TitlesData}>
<Line data = {data} options={options} width={600} height={100}></Line>
</div>
</div>
</div>
)
}
|
--[[
1.变量分类
1)全局变量
2)局部变量
3)表中的域
Lua 中的变量全是全局变量,哪怕是语句块或是函数里,除非用 local 显式声明为局部变量
局部变量的作用域为从声明位置开始到所在语句块结束<这十分特殊>
2.赋值语句
1)改变一个变量的值
a = "hello" .. "world"
2)对多个变量同时赋值
a, b = 10, 2*x
3)交换变量
x, y = y, x -- 遇到赋值语句Lua会先计算右边所有的值然后再执行赋值操作,所以我们可以这样进行交换变量的值
4)当变量个数和值的个数不一致时,Lua会一直以变量个数为基础采取以下策略
a. 变量个数 > 值的个数 按变量个数补足nil
b. 变量个数 < 值的个数 多余的值会被忽略
5)多值赋值经常用来交换变量,或将函数调用返回给变量
a, b = f() -- f()返回两个值,第一个赋给a,第二个赋给b,尽可能使用局部变量,可以避免命名冲突,同时访问速度更快
3.索引
1)使用方括号 t[i]
2)使用. t.i
3)函数调用:gettable_event(t,i) -- 采用索引访问本质上是一个类似这样的函数调用
]]
--测试变量
print("------------------------------------------------")
a = 5 -- 全局变量
local b = 5 -- 局部变量
function joke()
c = 5 -- 全局变量
local d = 6 -- 局部变量
end
joke()
print(c,d) --> 5 nil,局部变量d不能被函数在外部引用
do
local e = 6 -- 局部变量
local a = 6
b = 6 -- 对局部变量重新赋值,变为全局变量
print(e, b); --> 6 6
end
print(a, e, b) -- a 在外部仍然为1全局变量
--测试赋值
print("------------------------------------------------")
a, b, c = 0, 1
print(a,b,c) --> 0 1 nil
a, b = a+1, b+1, b+2 -- value of b+2 is ignored
print(a,b) --> 1 2
a, b, c = 0 -- 常见错误
print(a,b,c) --> 0 nil nil
--测试索引
print("------------------------------------------------")
site = {}
site["key"] = "www.runoob.com"
print(site["key"])
print(site.key)
|
""" rtl_433_publish.py
working code 20230718
Publishes to console and to MQTT with appropriate topics
Broker is defined in mqtt_secrets.py; tested with test.mosquitto.org
** 20230717 - adding better start banner
** 20230717 - testing with loop bash script
** 20230718 - testing wih Vultr MQTT broker and Vultr Ignition Broker
"""
import sys
import json
import socket
import time
import datetime
import logging
from logging.handlers import RotatingFileHandler
import paho.mqtt.client as mqtt
from pprint import pprint
from typing import TextIO, Dict
from temp_sensors import Sensor_Dev_1, SensorReadingStack
from mqtt_secrets import MQTT_BROKER, MQTT_BROKER_ADDRESS, MQTT_BROKER_PORT, MQTT_USERNAME, MQTT_PASSWORD
# ###################################################################### #
# constants and environment #
# ###################################################################### #
MAX_DATA_STORE_TIME: int = 1800 # Maximum data store time in seconds (30 minutes)
MAX_STACK_SIZE: int = 10 # Maximum size of history stacks
MAX_MQTT_CONNECT_RETRIES = 3
MQTT_RETRY_WAIT_SECONDS = 5
PUBLISH_WAIT_TIME_S: int = 60 # Time between publishing to MQTT broker
PUBLISH_TO_CONSOLE: bool = True
PUBLISH_TO_FILE_TEXT: bool = False
PUBLISH_TO_FILE_JSON: bool = False
PUBLISH_TO_MQTT: bool = True
DEFAULT_LOGGING_LEVEL = logging.DEBUG
DEFAULT_LOGFILE_PATH = "/home/karl/Logs"
DEFAULT_LOGFILE_FILENAME = "rtl_433_publish.log"
DEFAULT_LOGFILE_FILESPECT = f"{DEFAULT_LOGFILE_PATH}/{DEFAULT_LOGFILE_FILENAME}"
MAX_LOGFILE_SIZE = 10*1024*1024
# ######################### setup logger #########################
log_file = DEFAULT_LOGFILE_FILESPECT
# Create logger
logger = logging.getLogger(__name__)
logger.setLevel(DEFAULT_LOGGING_LEVEL)
# Create a rotating file handler which rotates log files
handler = RotatingFileHandler(log_file, maxBytes=MAX_LOGFILE_SIZE, backupCount=5)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Add the handler to logger
logger.addHandler(handler)
# ######################### Print Startup Info #########################
def print_startup_info() -> None:
BORDER_SIZE: int = 80
msg = (
"\n" + "*" * BORDER_SIZE + "\n" +
f"PUBLISHING TO CONSOLE: {PUBLISH_TO_CONSOLE}\n"
f"PUBLISHING TO FILE (TEXT): {PUBLISH_TO_FILE_TEXT}\n"
f"PUBLISHING TO FILE (JSON): {PUBLISH_TO_FILE_JSON}\n"
f"PUBLISHING TO MQTT: {PUBLISH_TO_MQTT}\n"
)
logger.info(msg)
if PUBLISH_TO_MQTT:
msg = (
f"---------------- Single MQTT Broker ----------------\n"
f"PUBLISH_WAIT_TIME_S: {PUBLISH_WAIT_TIME_S}\n"
f"PUBLISH_TO_CONSOLE: {PUBLISH_TO_CONSOLE}\n"
f"PUBLISH_TO_FILE_TEXT: {PUBLISH_TO_FILE_TEXT}\n"
f"PUBLISH_TO_FILE_JSON: {PUBLISH_TO_FILE_JSON}\n"
f"PUBLISH_TO_MQTT: {PUBLISH_TO_MQTT}"
)
logger.info(msg)
msg = ("\n" + "*" * BORDER_SIZE + "\n" )
logger.info(msg)
return
# ######################### trim a specific stack #########################
def trim_stack(sensor_stack: SensorReadingStack) -> None:
format_str = "%Y-%m-%d %H:%M:%S.%f"
current_time: float = time.time()
# Iterate over the stack and remove readings older than MAX_DATA_STORE_TIME
while not sensor_stack.is_empty():
oldest_reading_time_str: str = sensor_stack.peek().time_raw
try:
oldest_reading_time = datetime.datetime.strptime(oldest_reading_time_str, format_str).timestamp()
except ValueError:
# If parsing with milliseconds fails, try without milliseconds
format_str = "%Y-%m-%d %H:%M:%S"
oldest_reading_time = datetime.datetime.strptime(oldest_reading_time_str, format_str).timestamp()
if current_time - oldest_reading_time > MAX_DATA_STORE_TIME:
sensor_stack.pop()
else:
break
# ######################### trim all stacks #########################
def trim_all_stacks(sensor_stacks: Dict[str, SensorReadingStack]) -> None:
# Iterate over all the sensor stacks and call trim_stack for each stack
for stack in sensor_stacks.values():
trim_stack(stack)
# ######################### publish to file #########################
def publish_to_file(sensor_reading: Sensor_Dev_1) -> None:
logger.error("Not publishing to file yet")
return
# ######################### publish to file as json #########################
def publish_to_file_as_json(sensor_reading: Sensor_Dev_1) -> None:
logger.error("Not publishing to file as json yet")
return
# ###################################################################### #
# MQTT Routines #
# ###################################################################### #
# ######################### handle an MQTT Operation #########################
def handle_mqtt_operation(operation, error_message):
try:
operation()
except Exception as e:
logger.error(f"{error_message}: {e}")
raise
# ######################### connect to broker #########################
def connect_to_broker(client, br_ip, br_port):
retries = 0
while retries < MAX_MQTT_CONNECT_RETRIES:
try:
client.connect(br_ip, br_port)
return
except socket.gaierror as e:
retries += 1
logger.warning(f"Failed to connect to {br_ip}:{br_port} due to DNS error. Retry {retries}/{MAX_MQTT_CONNECT_RETRIES}.")
time.sleep(MQTT_RETRY_WAIT_SECONDS)
except Exception as e:
logger.error(f"Unexpected error connecting to {br_ip}:{br_port}: {e}")
raise
raise Exception(f"Failed to connect to {br_ip}:{br_port} after {MAX_MQTT_CONNECT_RETRIES} retries.")
# ######################### set MQTT Broker Credentials #########################
def set_credentials(client, br_user, br_pass):
handle_mqtt_operation(
lambda: client.username_pw_set(br_user, br_pass),
"Exception on mqtt client credential instantiation"
)
# ######################### publish an MQTT Message #########################
def publish_message(client, topic, payload):
logger.DEBUG(f"Publishing: {payload}")
handle_mqtt_operation(
lambda: client.publish(topic, payload),
"Error publishing mqtt message"
)
# ######################### Disconnect from MQTT Broker #########################
def disconnect_from_broker(client):
handle_mqtt_operation(
lambda: client.disconnect(),
"Error disconnecting from broker"
)
# ######################### publish to a single broker #########################
def publish_to_broker(br_ip, br_port, br_user, br_pass, topic, payload):
logger.info(f"Publishing to: {br_ip}, topic: {topic}, \n {payload}\n")
client = mqtt.Client()
set_credentials(client, br_user, br_pass)
connect_to_broker(client, br_ip, br_port)
client.loop_start()
publish_message(client, topic, payload)
disconnect_from_broker(client)
client.loop_stop()
# ######################### publish to all the brokers #########################
def publish_to_brokers(sensor_reading: Sensor_Dev_1) -> None:
"""Function to publish the sensor reading to all active MQTT brokers"""
# Get the topic leaf name
topic_leaf_name: str = sensor_reading.sensor_name
topic = f"KTBMES/sensor/readings/{topic_leaf_name}"
# Prepare the payload
payload = json.dumps(sensor_reading.to_dict())
publish_to_broker(
br_ip=MQTT_BROKER_ADDRESS,
br_port=MQTT_BROKER_PORT,
br_user=MQTT_USERNAME,
br_pass=MQTT_PASSWORD,
topic=topic,
payload=payload,
)
return
# ######################### publish to console #########################
def publish_to_console(sensor_reading: Sensor_Dev_1) -> None:
# Function to publish the sensor reading to the console
logger.info(sensor_reading)
# ######################### publish data #########################
def publish_data(sensor_stacks: Dict[str, SensorReadingStack]) -> None:
# Function to publish the data in the sensor stacks based on configuration constants
logger.debug("+++ Publishing Stacks")
for stack in sensor_stacks.values():
if not stack.is_empty():
recent_reading: Sensor_Dev_1 = stack.peek()
logger.debug(f"\tid: {recent_reading.id_raw} Name: {recent_reading.sensor_name}")
if PUBLISH_TO_CONSOLE:
publish_to_console(recent_reading)
if PUBLISH_TO_FILE_TEXT:
publish_to_file(recent_reading)
if PUBLISH_TO_FILE_JSON:
publish_to_file_as_json(recent_reading)
if PUBLISH_TO_MQTT:
publish_to_brokers(recent_reading)
# ######################### consume - store - publish #########################
#! Have the Sensor_Dev_1.from_json check for valid keys
def consume_store_publish(file: TextIO) -> None:
sensor_stacks: Dict[str, SensorReadingStack] = {}
last_publish_time: float = time.time()
print_startup_info()
for line in file:
line = line.strip()
if line:
sensor_reading: Sensor_Dev_1 = Sensor_Dev_1.from_json(line)
logger.debug(f"*** Reading sensor:\n{sensor_reading}")
sensor_id = sensor_reading.id_raw
#! a check for non temp sensors should be made here
if sensor_reading.id_raw == "":
logger.info("---- ignoring device")
continue # for now, we ignore the line
if sensor_id not in sensor_stacks:
sensor_stacks[sensor_id] = SensorReadingStack(MAX_STACK_SIZE)
sensor_stack: SensorReadingStack = sensor_stacks[sensor_id]
sensor_stack.push(sensor_reading)
current_time: float = time.time()
if current_time - last_publish_time >= PUBLISH_WAIT_TIME_S:
publish_data(sensor_stacks)
last_publish_time = current_time
logger.debug(" Trimming stacks")
trim_all_stacks(sensor_stacks)
# ######################### setup logging #########################
def setup_logging(log_level=DEFAULT_LOGGING_LEVEL):
logger = logging.getLogger()
logger.setLevel(log_level)
log_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(log_format)
logger.addHandler(stream_handler)
# You can add more handlers here if needed. For instance, to log to a file.
# file_handler = logging.handlers.RotatingFileHandler("app.log", maxBytes=1e6, backupCount=5)
# file_handler.setFormatter(log_format)
# logger.addHandler(file_handler)
# ######################### Main #########################
def main() -> None:
setup_logging(DEFAULT_LOGGING_LEVEL) # Set up logging first with your default logging level
consume_store_publish(sys.stdin)
if __name__ == "__main__":
main()
exit(0)
|
import React, { useState, useEffect } from "react";
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import { Link } from "react-router-dom";
import moment from 'moment';
import { clerkApi } from "../services/api"
function Task({ match }) {
useEffect(() => {
console.log(match)
fetchData(1);
}, [])
const fetchData = (taskActivitieId) => {
clerkApi.get("/TaskActivities/" + taskActivitieId).then(
res => {
console.log(res)
setTaskActivitie(res.data);
}
).catch(err => {
console.log(err)
})
}
const [taskActivitie, setTaskActivitie] = useState([]);
const timeleft = (time) => {
return moment(time).fromNow();
}
const unsubscribe = () => {
console.log("unsubscribe")
}
return (
<div>
<Box align="left">
<Typography gutterBottom variant="h4" color="secondary">
{taskActivitie.title}
</Typography>
<Typography color="secondary" variant="body1">
{taskActivitie.description}
</Typography>
</Box>
<div className="taskMenu">
<Box>
<Grid container direction="row" justify="space-between" alignItems="center">
<Grid item>
<Button component={Link} to={'/tasks'} variant="contained" color="primary" disableElevation>
Zurück
</Button>
</Grid>
<Grid item>
<Button component={Link} to={'/tasks'} onClick={() => unsubscribe()} variant="contained" color="primary" disableElevation>
Abmelden
</Button>
</Grid>
</Grid>
</Box>
</div>
</div >
);
}
export default Task;
|
package controller
import (
"BACKEND/internals/entity"
"BACKEND/internals/service"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
// GameController 게임 생성 및 조회
type GameController struct {
gameService *service.GameService
}
func NewGameController(gameService *service.GameService) *GameController {
return &GameController{
gameService: gameService,
}
}
func (c *GameController) Get(ctx *gin.Context) {
id, err := strconv.Atoi(ctx.Param("id"))
if err != nil {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
avatarID := ctx.GetInt("avatarID")
// 첫 화면에서 API 호출 시 id == 0
game, err := c.gameService.Get(id, avatarID, ctx.Param("class"))
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
ctx.JSON(http.StatusOK, game)
}
func (c *GameController) Create(ctx *gin.Context) {
req := entity.CreateGameRequest{}
err := ctx.ShouldBindJSON(&req)
if err != nil {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
avatarID := ctx.GetInt("avatarID")
game, err := c.gameService.Create(avatarID, req)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
ctx.JSON(http.StatusOK, game)
}
func (c *GameController) Update(ctx *gin.Context) {
req := entity.UpdateGameRequest{}
err := ctx.ShouldBindJSON(&req)
if err != nil {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
game, err := c.gameService.Update(req)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
game.AvatarID = ctx.GetInt("avatarID")
ctx.JSON(http.StatusOK, game)
}
func (c *GameController) Delete(ctx *gin.Context) {
id, err := strconv.Atoi(ctx.Param("id"))
if err != nil {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
err = c.gameService.Delete(id)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, err) // 에러 정의해서 반환 코드 분기 필요
return
}
ctx.Status(http.StatusOK)
}
|
#!meta
{"kernelInfo":{"defaultKernelName":null,"items":[{"name":"csharp","languageName":"C#","aliases":["c#","cs"]},{"name":"fsharp","languageName":"F#","aliases":["f#","fs"]},{"name":"pwsh","languageName":"PowerShell","aliases":["powershell"]},{"name":"javascript","languageName":"JavaScript","aliases":["js"]},{"name":"html","languageName":"HTML"},{"name":"sql","languageName":"SQL"},{"name":"kql","languageName":"KQL"},{"name":"mermaid","languageName":"Mermaid"},{"name":"httpRequest","languageName":"http"},{"name":"value"}]}}
#!csharp
#r "nuget: Google.OrTools, 9.5.2237"
using Google.OrTools.LinearSolver;
#!csharp
Solver solver = Solver.CreateSolver("CBC");
if (solver is null)
{
Console.WriteLine("Unable to init kernel");
return;
}
#!csharp
Variable x = solver.MakeNumVar(0.0, double.PositiveInfinity, "x");
Variable y = solver.MakeNumVar(0.0, double.PositiveInfinity, "y");
Console.WriteLine("Number of variables = " + solver.NumVariables());
#!csharp
solver.Add(x + 2 * y <= 14.0);
solver.Add(3 * x - y >= 0.0);
solver.Add(x - y <= 2.0);
Console.WriteLine("Number of constraints = " + solver.NumConstraints());
solver.Maximize(3 * x + 4 * y);
#!csharp
Solver.ResultStatus resultStatus = solver.Solve();
if (resultStatus != Solver.ResultStatus.OPTIMAL)
{
Console.WriteLine("The problem does not have an optimal solution!");
return;
}
Console.WriteLine("Solution:");
Console.WriteLine("Objective value = " + solver.Objective().Value());
Console.WriteLine("x = " + x.SolutionValue());
Console.WriteLine("y = " + y.SolutionValue());
|
/*
* Copyright 2022-2023 The BoardGameWork Authors
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tools.aqua.bgw.components.uicomponents.structureddataview.tableview
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import tools.aqua.bgw.components.uicomponents.SelectionMode
import tools.aqua.bgw.components.uicomponents.TableView
/** Test changing [SelectionMode] in [TableView]. */
class TableViewChangeSelectionModeTest : TableViewTestBase(SelectionMode.SINGLE) {
/** Test change to [SelectionMode.NONE]. */
@Test
@DisplayName("Test change to SelectionMode.NONE")
fun testChangeToNone() {
dataView.selectionMode = SelectionMode.NONE
checkNotNotified()
checkInvocation(0, 0, 0)
}
/** Test change to [SelectionMode.MULTIPLE]. */
@Test
@DisplayName("Test change to SelectionMode.MULTIPLE")
fun testChangeToMultiple() {
dataView.selectionMode = SelectionMode.MULTIPLE
checkNotNotified()
checkInvocation(0, 0, 0)
}
/** Test change to [SelectionMode.NONE] after selecting. */
@Test
@DisplayName("Test change to SelectionMode.NONE after selecting")
fun testChangeToNoneAfterSelecting() {
dataView.selectFirst()
checkNotified()
checkInvocation(1, 0, 0)
dataView.selectionMode = SelectionMode.NONE
checkNotified(2)
checkInvocation(1, 0, 0)
assertEquals(0, dataView.selectedIndices.size)
assertEquals(0, dataView.selectedItems.size)
}
/** Test change to [SelectionMode.MULTIPLE] after selecting. */
@Test
@DisplayName("Test change to SelectionMode.MULTIPLE after selecting")
fun testChangeToMultipleAfterSelecting() {
dataView.selectFirst()
checkNotified()
checkInvocation(1, 0, 0)
dataView.selectionMode = SelectionMode.MULTIPLE
checkNotified(1)
checkInvocation(1, 0, 0)
}
/** Test change [SelectionMode.MULTIPLE] to [SelectionMode.SINGLE]. */
@Test
@DisplayName("Test change SelectionMode.MULTIPLE to SelectionMode.SINGLE")
fun testChangeMultipleToSingle() {
dataView.selectionMode = SelectionMode.MULTIPLE
checkNotNotified()
checkInvocation(0, 0, 0)
dataView.selectAll()
checkNotified()
checkInvocation(0, 1, 0)
dataView.selectionMode = SelectionMode.SINGLE
checkNotified(2)
checkInvocation(0, 1, 0)
assertEquals(0, dataView.selectedIndices.size)
assertEquals(0, dataView.selectedItems.size)
}
}
|
import ControlOfficerLayout from '../../layout/ControlOfficerLayout';
import React, { useEffect, useState } from 'react';
import TextField from '../../components/TextField';
import Button from '../../components/Button';
import { Formik } from 'formik';
import * as Yup from 'yup';
import {
Alert,
Autocomplete,
Collapse,
FormControl,
FormControlLabel,
IconButton,
Radio,
RadioGroup,
Switch,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
TextField as MuiTextField,
} from '@mui/material';
import { Add, Close } from '@mui/icons-material';
import { TimePicker } from '@mui/x-date-pickers/TimePicker';
import request from 'utils/request';
export default function AddTurn() {
const [addError, setAddError] = useState('');
const [addSuccess, setAddSuccess] = useState(false);
const [stations, setStations] = useState([]);
//const [selectedStation, setSelectedStation] = useState(null);
useEffect(() => {
(async function () {
try {
const res = await request('get', '/public/stations');
const stationList = res.data;
setStations(stationList);
} catch (e) {
if (e?.response?.status === 500) {
console.error('Fetching Error: ', e);
} else {
console.log(e?.response?.data);
setStations(e?.response?.data?.errors[0]);
}
}
})();
}, []);
const turnValidationSchema = Yup.object().shape({
turnNumber: Yup.number()
.min(3, ({ min }) => `Turn number must be at least ${min} characters`)
.required('Turn number is required'),
turnName: Yup.string().min(
3,
({ min }) => `Turn name must be at least ${min} characters`
),
});
async function handleSubmit(values, { setSubmitting, resetForm }) {
console.log('running');
// @ts-ignore
const submitValues = {
...values,
turnNumber: parseInt(values.turnNumber),
firstClass: undefined,
secondClass: undefined,
thirdClass: undefined,
trainCompartments: [
...values.firstClassCompartments,
...values.secondClassCompartments,
...values.thirdClassCompartments,
],
firstClassCompartments: undefined,
secondClassCompartments: undefined,
thirdClassCompartments: undefined,
intermediateStations: values.intermediateStations.map(
(station, index) => {
return {
stationId: station.stationId.stationId,
arrivalTime: station?.arrivalTime
? station?.arrivalTime._d.getHours() +
':' +
station?.arrivalTime._d.getMinutes()
: null,
departureTime: station?.departureTime
? station?.departureTime._d.getHours() +
':' +
station?.departureTime._d.getMinutes()
: null,
isStart: index === 0,
isEnd: index === values.intermediateStations.length - 1,
};
}
),
};
console.log(submitValues);
setAddError('');
setAddSuccess(false);
try {
await request('post', `/control-officer/train-turn/add/`, submitValues);
setAddSuccess(true);
resetForm();
} catch (e) {
if (e?.response?.status === 500) {
setAddError('Error adding turn');
console.error('Adding Error: ', e);
} else {
console.log(e?.response?.data);
setAddError(e?.response?.data?.errors[0]);
}
} finally {
setSubmitting(false);
}
}
return (
<ControlOfficerLayout>
<h1 className="my-0">Add train turns</h1>
<div className="bg-slate-100 rounded-3xl p-8">
<div className="mb-4">
<Collapse in={Boolean(addError)}>
<Alert
severity="error"
action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => {
setAddError(null);
}}
>
<Close fontSize="inherit" />
</IconButton>
}
>
Error adding train turn
</Alert>
</Collapse>
<Collapse in={Boolean(addSuccess)}>
<Alert
severity="success"
action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => {
setAddSuccess(null);
}}
>
<Close fontSize="inherit" />
</IconButton>
}
>
Train turn added successfully.
</Alert>
</Collapse>
</div>
<div>
<Formik
validationSchema={turnValidationSchema}
initialValues={{
turnNumber: '',
turnName: '',
reservable: false,
availability: 'DAILY',
type: 'SLOW',
firstClassCompartments: [],
secondClassCompartments: [],
thirdClassCompartments: [],
firstClass: 0,
secondClass: 0,
thirdClass: 0,
intermediateStations: [
{ stationId: null, arrivalTime: null, departureTime: null },
],
}}
onSubmit={handleSubmit}
>
{(formik) => (
<>
<form
onSubmit={formik.handleSubmit}
className="w-full flex flex-col gap-4 items-center"
>
<div className="w-full grid gap-4 grid-cols-7">
<p className="col-start-1 col-end-2">Turn Number</p>
<TextField
className="col-start-3 col-end-5"
fullWidth
id="turnNumber"
name="turnNumber"
{...formik.getFieldProps('turnNumber')}
error={Boolean(
formik.touched.turnNumber && formik.errors.turnNumber
)}
helperText={formik.errors.turnNumber}
/>
<p className="col-start-1 col-end-2">Turn Name</p>
<TextField
className="col-start-3 col-end-5"
fullWidth
id="turnName"
name="turnName"
{...formik.getFieldProps('turnName')}
error={Boolean(
formik.touched.turnName && formik.errors.turnName
)}
helperText={formik.errors.turnName}
/>
<p className="col-start-1 col-end-2">Reservable?</p>
<Switch
className="col-start-3 col-end-5"
id="reservable"
name="reservable"
value={formik.values.reservable}
onChange={formik.handleChange}
/>
<div
className={
formik.values.reservable
? 'col-start-2 col-end-7'
: 'hidden'
}
>
<div className="col-start-3 col-end-6 bg-slate-200 p-7 rounded-2xl">
<h2 className="m-0 mb-5 font-light">
Reservable compartment configuration
</h2>
<div className="flex flex-wrap gap-3">
<p>No of first class compartments</p>
<TextField
type="number"
id="firstClass"
name="firstClass"
value={formik.values.firstClass}
onChange={(e) => {
console.log('field value change', e.target.value);
const number = Number(e.target.value);
const newCompartments = [];
for (let i = 0; i < number; i++) {
newCompartments.push({
class: 'FIRST_CLASS',
compartmentNumber: '',
seatCount: 0,
});
}
console.log(number);
formik.setFieldValue(
'firstClassCompartments',
newCompartments
);
formik.handleChange(e);
}}
/>
</div>
<div className="bg-slate-100 rounded-2xl mt-3">
<Table className="m-2">
<TableHead>
<TableRow>
<TableCell>Compartment Number</TableCell>
<TableCell>No of seats</TableCell>
</TableRow>
</TableHead>
<TableBody>
{formik.values.firstClassCompartments.map(
(compartment, index) => (
<TableRow
key={index}
sx={{
'&:last-child td, &:last-child th': {
border: 0,
},
}}
>
<TableCell>
<TextField
type="text"
id={`firstClassCompartments[${index}].compartmentNumber`}
name={`firstClassCompartments[${index}].compartmentNumber`}
{...formik.getFieldProps(
`firstClassCompartments[${index}].compartmentNumber`
)}
/>
</TableCell>
<TableCell>
<TextField
type="number"
id={`firstClassCompartments[${index}].seatCount`}
name={`firstClassCompartments[${index}].seatCount`}
{...formik.getFieldProps(
`firstClassCompartments[${index}].seatCount`
)}
/>
</TableCell>
</TableRow>
)
)}
</TableBody>
</Table>
</div>
<div className="flex flex-wrap gap-3 mt-3">
<p>No of second class compartments</p>
<TextField
type="number"
id="secondClass"
name="secondClass"
value={formik.values.secondClass}
onChange={(e) => {
console.log('field value change', e.target.value);
const number = Number(e.target.value);
const newCompartments = [];
for (let i = 0; i < number; i++) {
newCompartments.push({
class: 'SECOND_CLASS',
compartmentNumber: '',
seatCount: 0,
});
}
console.log(number);
formik.setFieldValue(
'secondClassCompartments',
newCompartments
);
formik.handleChange(e);
}}
/>
</div>
<div className="bg-slate-100 rounded-2xl mt-3">
<Table className="m-2">
<TableHead>
<TableRow>
<TableCell>Compartment Number</TableCell>
<TableCell>No of seats</TableCell>
</TableRow>
</TableHead>
<TableBody>
{formik.values.secondClassCompartments.map(
(compartment, index) => (
<TableRow
key={index}
sx={{
'&:last-child td, &:last-child th': {
border: 0,
},
}}
>
<TableCell>
<TextField
type="text"
id={`secondClassCompartments[${index}].compartmentNumber`}
name={`secondClassCompartments[${index}].compartmentNumber`}
{...formik.getFieldProps(
`secondClassCompartments[${index}].compartmentNumber`
)}
/>
</TableCell>
<TableCell>
<TextField
type="number"
id={`secondClassCompartments[${index}].seatCount`}
name={`secondClassCompartments[${index}].seatCount`}
{...formik.getFieldProps(
`secondClassCompartments[${index}].seatCount`
)}
/>
</TableCell>
</TableRow>
)
)}
</TableBody>
</Table>
</div>
<div className="flex flex-wrap gap-3 mt-3">
<p>No of third class compartments</p>
<TextField
type="number"
id="thirdClass"
name="thirdClass"
value={formik.values.thirdClass}
onChange={(e) => {
console.log('field value change', e.target.value);
const number = Number(e.target.value);
const newCompartments = [];
for (let i = 0; i < number; i++) {
newCompartments.push({
class: 'THIRD_CLASS',
compartmentNumber: '',
seatCount: 0,
});
}
console.log(number);
formik.setFieldValue(
'thirdClassCompartments',
newCompartments
);
formik.handleChange(e);
}}
/>
</div>
<div className="bg-slate-100 rounded-2xl mt-3">
<Table className="m-2">
<TableHead>
<TableRow>
<TableCell>Compartment Number</TableCell>
<TableCell>No of seats</TableCell>
</TableRow>
</TableHead>
<TableBody>
{formik.values.thirdClassCompartments.map(
(compartment, index) => (
<TableRow
key={index}
sx={{
'&:last-child td, &:last-child th': {
border: 0,
},
}}
>
<TableCell>
<TextField
type="text"
id={`thirdClassCompartments[${index}].compartmentNumber`}
name={`thirdClassCompartments[${index}].compartmentNumber`}
{...formik.getFieldProps(
`thirdClassCompartments[${index}].compartmentNumber`
)}
/>
</TableCell>
<TableCell>
<TextField
type="number"
id={`thirdClassCompartments[${index}].seatCount`}
name={`thirdClassCompartments[${index}].seatCount`}
{...formik.getFieldProps(
`thirdClassCompartments[${index}].seatCount`
)}
/>
</TableCell>
</TableRow>
)
)}
</TableBody>
</Table>
</div>
</div>
</div>
<p className="col-start-1 col-end-2">Availability</p>
<FormControl className="col-start-3 col-end-7">
<RadioGroup
row
name="availability"
value={formik.values.availability}
className="grid gap-4 grid-cols-4"
onChange={(event) => {
formik.setFieldValue(
'availability',
event.currentTarget.value
);
}}
>
<FormControlLabel
value="DAILY"
control={<Radio />}
label="DAILY"
className="col-start-1"
/>
<FormControlLabel
value="NS"
control={<Radio />}
label="NS"
className="col-start-2"
/>
<FormControlLabel
value="SO"
control={<Radio />}
label="SO"
className="col-start-3"
/>
<FormControlLabel
value="NSU"
control={<Radio />}
label="NSU"
className="col-start-4"
/>
</RadioGroup>
</FormControl>
<p className="col-start-1 col-end-3">Type</p>
<FormControl className="col-start-3 col-end-7">
<RadioGroup
row
name="type"
value={formik.values.type}
className="grid gap-4 grid-cols-4"
onChange={(event) => {
formik.setFieldValue(
'type',
event.currentTarget.value
);
}}
>
<FormControlLabel
value="SLOW"
control={<Radio />}
label="SLOW"
className="col-start-1"
/>
<FormControlLabel
value="EXPRESS"
control={<Radio />}
label="EXPRESS"
className="col-start-2"
/>
<FormControlLabel
value="INTERCITY"
control={<Radio />}
label="INTERCITY"
className="col-start-3"
/>
</RadioGroup>
</FormControl>
<p className="col-start-1 col-end-2">Add schedule</p>
<Table className="col-start-3 col-end-7">
<TableHead>
<TableRow>
<TableCell>Station</TableCell>
<TableCell>Arrival Time</TableCell>
<TableCell>Departure Time</TableCell>
</TableRow>
</TableHead>
<TableBody>
{formik.values.intermediateStations.map(
(station, index) => (
<TableRow
key={index}
sx={{
'&:last-child td, &:last-child th': {
border: 0,
},
}}
>
<TableCell>
<Autocomplete
disablePortal
id="station"
getOptionLabel={(stations) =>
`${stations.name}`
}
options={stations}
value={
formik.values.intermediateStations[index]
.stationId
}
onChange={(e, station) => {
console.log(station, e);
formik.setFieldValue(
`intermediateStations[${index}].stationId`,
station
);
}}
isOptionEqualToValue={(option, value) =>
option.name === value.name
}
noOptionsText={'No Available Stations'}
classes={{
inputRoot: 'w-44 rounded-2xl',
}}
renderInput={(params) => (
<TextField
{...params}
label="Select a station"
className="w-44"
/>
)}
/>
</TableCell>
<TableCell>
<TimePicker
disabled={index === 0}
label="Arrival time"
value={
formik.values.intermediateStations[index]
.arrivalTime
}
onChange={(e) => {
formik.setFieldValue(
`intermediateStations[${index}].arrivalTime`,
e
);
}}
renderInput={(params) => (
<MuiTextField
{...params}
InputProps={{
...params.InputProps,
className: 'rounded-2xl',
}}
/>
)}
/>
</TableCell>
<TableCell>
<TimePicker
disabled={
index ===
formik.values.intermediateStations.length -
1
}
label="Departure time"
value={
formik.values.intermediateStations[index]
.departureTime
}
onChange={(e) => {
formik.setFieldValue(
`intermediateStations[${index}].departureTime`,
e
);
}}
renderInput={(params) => (
<MuiTextField
{...params}
InputProps={{
...params.InputProps,
className: 'rounded-2xl',
}}
/>
)}
/>
</TableCell>
</TableRow>
)
)}
</TableBody>
</Table>
<IconButton
className="col-start-3 col-end-7 h-10 w-10 bg-slate-700 text-slate-50 hover:bg-slate-900
"
onClick={(e) => {
const newIntermediateStations = [
...formik.values.intermediateStations,
];
newIntermediateStations.push({
stationId: null,
arrivalTime: null,
departureTime: null,
});
formik.setFieldValue(
'intermediateStations',
newIntermediateStations
);
}}
edge="end"
>
<Add />
</IconButton>
</div>
<Button type="submit" isLoading={formik.isSubmitting}>
Add turn
</Button>
</form>
</>
)}
</Formik>
</div>
</div>
{/* </div> */}
</ControlOfficerLayout>
);
}
|
#pragma once
#include "RewardFunction.h"
// https://github.com/AechPro/rocket-league-gym-sim/blob/main/rlgym_sim/utils/reward_functions/combined_reward.py
namespace RLGSC {
class CombinedReward : public RewardFunction {
public:
std::vector<RewardFunction*> rewardFuncs;
std::vector<float> rewardWeights;
bool ownsFuncs;
CombinedReward(std::vector<RewardFunction*> rewardFuncs, std::vector<float> rewardWeights, bool ownsFuncs = false) :
rewardFuncs(rewardFuncs), rewardWeights(rewardWeights), ownsFuncs(ownsFuncs) {
assert(rewardFuncs.size() == rewardWeights.size());
}
CombinedReward(std::vector<std::pair<RewardFunction*, float>> funcsWithWeights, bool ownsFuncs = false) :
ownsFuncs(ownsFuncs) {
for (auto& pair : funcsWithWeights) {
rewardFuncs.push_back(pair.first);
rewardWeights.push_back(pair.second);
}
}
protected:
virtual void Reset(const GameState& initialState) {
for (auto func : rewardFuncs)
func->Reset(initialState);
}
virtual void PreStep(const GameState& state) {
for (auto func : rewardFuncs)
func->PreStep(state);
}
virtual std::vector<float> GetAllRewards(const GameState& state, const ActionSet& prevAction, bool final) {
std::vector<float> allRewards(state.players.size());
for (int i = 0; i < rewardFuncs.size(); i++) {
auto rewards = rewardFuncs[i]->GetAllRewards(state, prevAction, final);
for (int j = 0; j < rewards.size(); j++)
allRewards[j] += rewards[j] * rewardWeights[i];
}
return allRewards;
}
virtual ~CombinedReward() {
if (ownsFuncs)
for (auto func : rewardFuncs)
delete func;
}
};
}
|
import { useState } from 'react';
import { View, StyleSheet, Dimensions, TouchableOpacity } from 'react-native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons//MaterialCommunityIcons';
import { getToken } from '../../services/verifications';
import HomeScreen from '../../views/Home';
import ProfileScreen from '../../views/Profile'
import FavoritesScreen from '../../views/Favorites';
import MyRecipesScreen from '../../views/MyRecipes';
import RegisterRecipes from '../../views/RegisterRecipes';
const Tab = createBottomTabNavigator();
const TabBar = ({ currentRoute, setRoute }) => {
const navigation = useNavigation();
const isTabActive = (tabName) => {
return currentRoute === tabName;
};
return (
<View style={styles.navbar}>
<TouchableOpacity style={ isTabActive("MyHome") ? {borderRadius: 50, padding: 5, backgroundColor: "#fff2"} : {padding: 5}} onPress={() => {
navigation.navigate('MyHome');
setRoute('MyHome');
}}>
<Icon name="home" size={26} color={isTabActive("MyHome") ? "#fff" : "#999"} />
</TouchableOpacity>
<TouchableOpacity style={ isTabActive("Favorites") ? {borderRadius: 50, padding: 5, backgroundColor: "#fff2"} : {padding: 5}} onPress={() => {
navigation.navigate('Favorites');
setRoute('Favorites');
}}>
<Icon name={isTabActive("Favorites") ? "heart" : "heart-outline"} size={26} color={isTabActive("Favorites") ? "#fff" : "#999"} />
</TouchableOpacity>
<TouchableOpacity style={{borderRadius: 50, padding: 5, backgroundColor: isTabActive("AddRecipe") ? "#FE8A07" : "#fff2"}} onPress={() => {
navigation.navigate('AddRecipe');
setRoute('AddRecipe');
}}>
<Icon name="plus" size={32} color="#fff" />
</TouchableOpacity>
<TouchableOpacity style={ isTabActive("Profile") ? {borderRadius: 50, padding: 5, backgroundColor: "#fff2"} : {padding: 5}} onPress={async () => {
if ((await getToken()).status === true) {
navigation.navigate('Profile')
setRoute('Profile');
} else {
alert("Falha de autenticação, tente logar novamente!");
navigation.navigate('MyHome');
}
}}>
<Icon name="account-circle" size={26} color={isTabActive("Profile") ? "#fff" : "#999"} />
</TouchableOpacity>
<TouchableOpacity style={ isTabActive("Settings") ? {borderRadius: 50, padding: 5, backgroundColor: "#fff2"} : {padding: 5}} onPress={() => {
navigation.navigate('MyRecipes');
setRoute('MyRecipes');
}}>
<Icon name="book" size={26} color={isTabActive("MyRecipes") ? "#fff" : "#999"} />
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
navbar: {
backgroundColor: '#242A37',
paddingHorizontal: 32,
paddingVertical: 8,
borderRadius: 16,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
width: Dimensions.get('window').width - 40,
position: 'absolute',
bottom: 16,
alignSelf: 'center',
}
});
const TabNavigator = () => {
const [route, setRoute] = useState("MyHome");
return (
<Tab.Navigator initialRouteName={route} screenOptions={{ headerShown: false }} tabBar={(props) => <TabBar {...props} currentRoute={route} setRoute={setRoute} />}>
<Tab.Screen name="MyHome" component={HomeScreen} />
<Tab.Screen name="Favorites" component={FavoritesScreen} />
<Tab.Screen name="AddRecipe" component={RegisterRecipes} />
<Tab.Screen name="Profile" component={ProfileScreen} />
<Tab.Screen name="MyRecipes" component={MyRecipesScreen} />
</Tab.Navigator>
);
}
export default TabNavigator;
|
import { Col, Form, Input, Modal, Row } from 'antd';
type Props = {
title: string;
visible: boolean;
onCancel: () => void;
onOk: (text: string) => void;
initialValue?: string;
availableEmptyComment?: boolean;
};
export function CommentModal(props: Props) {
const [form] = Form.useForm();
const onOk = async () => {
try {
await form.validateFields();
const comment = form.getFieldValue('comment');
props.onOk(comment);
} catch {
return;
}
};
return (
<Modal title={props.title} open={props.visible} onOk={onOk} onCancel={props.onCancel}>
<Form form={form} layout="vertical" initialValues={{ comment: props.initialValue ?? '' }}>
<Row gutter={24}>
<Col span={24}>
<Form.Item
name="comment"
rules={[
{ required: props.availableEmptyComment === true ? false : true, message: 'Please enter comment' },
]}
label="Comment"
>
<Input.TextArea style={{ height: 200 }} />
</Form.Item>
</Col>
</Row>
</Form>
</Modal>
);
}
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('dotenv').config();
import { Injectable } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { InjectModel } from 'nestjs-typegoose';
import { Account } from './models/account.model';
import { CreateAccountDto } from './dto/create-account-dto';
import * as bcrypt from 'bcrypt';
import { SALT_ROUNDS } from 'src/core/constants';
import * as _ from 'lodash';
import { ROLE_USER } from 'src/core/rbac';
import { InjectSendGrid, SendGridService } from '@ntegral/nestjs-sendgrid';
import * as uuid from 'uuid';
@Injectable()
export class AccountsService {
constructor(
@InjectModel(Account)
private readonly accountModel: ReturnModelType<typeof Account>,
@InjectSendGrid() private readonly client: SendGridService,
) {}
async createPasswordHash(password: string) {
const hash = await bcrypt.hash(password, SALT_ROUNDS);
return hash;
}
async create(account: CreateAccountDto): Promise<Account> {
const hash = await this.createPasswordHash(account.password);
// automatically assign a user role to a created account
account.role = ROLE_USER;
account.password = hash;
const createdAccount = new this.accountModel(account);
return await createdAccount.save();
}
async findByEmail(email: string): Promise<Account> {
return await this.accountModel
.findOne({
email: email,
})
.lean();
}
async createPasswordResetRequest(email: string) {
const account = await this.findByEmail(email);
if (!account) {
throw new Error('Could not find account');
}
const token = uuid.v4();
await this.accountModel.updateOne(
{
_id: account._id,
},
{
passwordResetToken: token,
passwordResetTokenGenerationDate: new Date(),
},
);
await this.client.send({
from: process.env.EMAIL_FROM,
to: account.email,
subject: 'Password Reset Request',
text: `Password reset token: ${token}`,
});
}
async updatePassword(token: string, password: string) {
const account = await this.accountModel.findOne({
passwordResetToken: token,
});
if (account) {
const hash = await this.createPasswordHash(password);
return await this.accountModel.updateOne(
{
_id: account._id,
},
{
password: hash,
passwordResetToken: '',
passwordResetTokenGenerationDate: null,
},
);
}
throw new Error('Invalid token');
}
}
|
#!/usr/bin/env -S deno run --allow-all
// deno-lint-ignore-file prefer-const no-explicit-any
import { printImage } from "https://x.nest.land/terminal_images@3.0.0/mod.ts"
import { download } from "https://deno.land/x/download@v2.0.2/mod.ts";
import * as Colors from "https://deno.land/std@0.175.0/fmt/colors.ts"
import { trytm } from "./trytm.ts";
const log = console.log
const sample = (arr: any[]) => arr[Math.floor(Math.random() * arr.length)]
const delay = (ms: number) => new Promise((r) => setTimeout(r, ms))
Deno.addSignalListener("SIGINT", () => log("[SIGINT] Detected; Aborting program"))
const isNsfw = !!Deno.args.find((str) => str == "--nsfw")
const urls = (isNsfw
? [ //if true get nsfw
"https://api.waifu.pics/nsfw/waifu",
"https://api.waifu.pics/nsfw/neko",
"https://api.waifu.im/search/?included_tags=hentai&gif=false&is_nsfw=true",
]
: [ //if false use sfw
"https://api.waifu.pics/sfw/waifu",
"https://api.waifu.pics/sfw/neko",
"https://api.waifu.im/search/?included_tags=waifu&is_nsfw=false",
"https://api.waifu.im/search/?included_tags=oppai&is_nsfw=false",
])
// stolen from [https://stackoverflow.com/a/61868755]
const exists = async (filename: string): Promise<boolean> => {
try {
await Deno.stat(filename)
return true
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false
} else {throw error}
}
}
//fetch json, if err throw err
let rndURL = sample(urls)
const [JSONResponse, err] = await trytm(fetch(rndURL))
if (err) throw Error('Couldn\'t fetch image')
//extract json data and declare img link
const JSONData = await (JSONResponse).json()
const link = JSONData.url ?? JSONData.images[0].url
//filename
let ext = link.split(".").at(-1)
const fileName = `${crypto.randomUUID()}.${ext}`
//term columns
const {columns} = Deno.consoleSize()
;(async () => {
//if /saved/ dir does not exist create dir
if (!await exists("./saved/")) Deno.mkdir("saved")
await printImage({
path: link,
width: columns,
}).then(async () => {
await delay(1)
log(`\u{2500}`.repeat(columns)) //<hr>
log(`[!] Sauce/Image Link: ${Colors.blue(link)}`) //link
const save = confirm(Colors.yellow("[?] Save image?")) //prompt to save image
//if (save == true) download
if (save) {
const [_success, err] = await trytm(download(link, {
dir: "./saved/",
file: fileName
}))
if (!err) log(Colors.green(`[✓] File saved successfully in /saved/ as ${fileName}`))
else throw Error(`Couldn\'t download image [${link}].`)
}
})
})()
//deno run --allow-all mod.ts
//deno fmt
|
<!DOCTYPE html>
<html lang="pl"
xmlns:th="https://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout}">
<body>
<div class="my-container">
<main class="main-content" layout:fragment="content">
<p class="notification-bar" th:if="${notification}" th:text="${notification}">
Belka z powiadomieniami
</p>
<h2 class="list-heading" th:text="${heading}">Pozycje użytkownika według kategorii</h2>
<h6 class="list-description" th:text="${description}">Opis kategorii</h6>
<ul class="position-list" th:remove="all-but-first">
<li class="position-list-item" th:each="position: ${positions}">
<div class="position-list-item-card">
<div class="position-list-item-content">
<h3 class="position-list-item-title"
th:text="${position.isInactive()} ? ${position.name} + ' - NIEAKTYWNA' : ${position.name}">
Nazwa pozycji
</h3>
</div>
<div class="position-list-item-rating">
<h5 th:text="${position.description}"></h5>
<h5>
<span class="colored-text">Kwota: </span>
<span th:style="${!position.isIncome} ? 'color: #ff4d4d;' : ''"
th:text="${position.amount} + ' zł'"></span>
</h5>
<h5>
<i class="fas fa-star colored-text"></i>
<span class="colored-text">Priorytet: </span>
<span th:text="${position.priority} + '/10'"></span>
</h5>
<h5>
<span class="colored-text">Najbliższa data wykonania: </span>
<span th:text="${position.isInactive()} ? 'BRAK' : ${position.getFormattedRebillDateTime()}"></span>
</h5>
<h5>
<span class="colored-text">Częstotliwość: </span>
<span th:text="${position.getRecurrenceType().description}"></span>
</h5>
</div>
<div class="position-buttons">
<a th:href="@{|/position/edit/${position.getPositionId()}|}" class="btn btn-outline-primary position-button">
<i class="fas fa-edit"></i> Edytuj
</a>
<form data-confirm="Czy na pewno usunąć?" th:action="@{'/position/delete/' + ${position.getPositionId()}}" method="POST" class="position-button">
<input type="hidden" name="_method" value="DELETE" />
<button type="submit" class="btn btn-outline-danger">
<i class="fas fa-trash-alt"></i> Usuń
</button>
</form>
</div>
</div>
</li>
</ul>
</main>
</div>
</body>
</html>
|
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import React from "react";
import { Filters, Permit, permits, useStore } from "@/lib/store";
export function FilterModal({ children }: React.PropsWithChildren) {
const filters = useStore((state) => state.filters);
const updateStore = useStore((state) => state.updateFilters);
function updateFilters(newstate: Partial<Filters>) {
updateStore({
...filters,
...newstate,
});
}
return (
<Dialog>
<DialogTrigger asChild>{children}</DialogTrigger>
<DialogContent className="rounded-xl">
<DialogHeader className="text-left">
<DialogTitle className="text-xl">Filters</DialogTitle>
<DialogDescription className="">
Select which parking lots you would like to see on the map.
</DialogDescription>
<ul className="space-y-3 pt-2">
<li className="flex justify-between items-center font-medium">
<h3>Free</h3>
<Checkbox
className="w-5 h-5"
checked={filters.free}
onClick={() => updateFilters({ free: !filters.free })}
/>
</li>
<li className="flex justify-between items-center font-medium pt-2">
<h3>Paid</h3>
<Checkbox
className="w-5 h-5"
checked={filters.paid}
onClick={() => updateFilters({ paid: !filters.paid })}
/>
</li>
<li className="flex justify-between items-center font-medium">
<h3>Permit</h3>
<Select
defaultValue={filters.permit}
onValueChange={(val: Permit) => {
updateFilters({ permit: val });
}}
>
<SelectTrigger className="w-[80px] h-9">
<SelectValue placeholder="Choose" />
</SelectTrigger>
<SelectContent>
{permits.map((permit) => (
<SelectItem key={permit} value={permit}>
{permit}
</SelectItem>
))}
</SelectContent>
</Select>
</li>
<li className="flex justify-between items-center font-medium">
<h3>Open Now</h3>
<Checkbox
className="w-5 h-5"
checked={filters.open}
onClick={() => updateFilters({ open: !filters.open })}
/>
</li>
</ul>
</DialogHeader>
</DialogContent>
</Dialog>
);
}
|
# Blissful Book Bin
A helpful book cataloging application build with React, MUI & Sass.
The user can CRUD books, tags, and categories with notifications that the actions were successful or not.
## Main page with books table display

## Add & Edit books with a modal form

## Explore new books to add from the Faker API

##
## Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
|
import {
TextField,
Select,
MenuItem,
FormControl,
InputLabel,
Box,
} from "@mui/material";
import "react-day-picker/dist/style.css";
import { useMoveBack } from "../../hooks/useMoveBack";
import ButtonText from "../../ui/ButtonText";
import styled, { css } from "styled-components";
import { useState } from "react";
import { DemoContainer } from "@mui/x-date-pickers/internals/demo";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import Textarea from "@mui/joy/Textarea";
import Button from "@mui/material/Button";
import { useNavigate } from "react-router-dom/dist";
const DropdownMenu = ({ options, label, value, onChange }) => {
return (
<FormControl fullWidth sx={{ minWidth: 120 }}>
<InputLabel>{label}</InputLabel>
<Select value={value} onChange={onChange} label={label}>
{options.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</Select>
</FormControl>
);
};
function EditNewCarService() {
const Row = styled.div`
display: flex;
${(props) =>
props.type === "horizontal" &&
css`
justify-content: space-between;
align-items: center;
gap: 1.6rem;
`}
${(props) =>
props.type === "vertical" &&
css`
flex-direction: column;
gap: 1.6rem;
align-items: start;
`}
`;
const carOptions = [
{ value: "toyota", label: "Toyota Camry" },
{ value: "honda", label: "Honda Accord" },
{ value: "ford", label: "Ford Mustang" },
];
const moveBack = useMoveBack();
const [selectedCar, setSelectedCar] = useState("");
const navigate = useNavigate();
const handleCarChange = (event) => {
setSelectedCar(event.target.value);
};
return (
<Row type="vertical">
<ButtonText onClick={moveBack}>← Car Services</ButtonText>
<h1>Edit Service</h1>
<Row type="horizontal">
<TextField
type="text"
id="username"
label="User name"
// This makes this form better for password managers
autoComplete="username"
placeholder="User Name"
sx={{
width: 366,
height: 56,
padding: "2px 4px",
borderRadius: "16px",
}}
/>
<TextField
type="number"
id="phoneNumber"
label="Phone Number"
// This makes this form better for password managers
autoComplete="phone number"
placeholder="Phone Number"
sx={{
width: 366,
height: 56,
padding: "2px 4px",
borderRadius: "16px",
}}
/>
</Row>
<Row type="horizontal">
<Box
sx={{
width: 366,
borderRadius: "16px",
}}
>
<DropdownMenu
options={carOptions}
label="Select Driver"
value={selectedCar}
onChange={handleCarChange}
/>
</Box>
<Box>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer components={["DatePicker"]}>
<DatePicker
label="Request Date"
sx={{
width: 366,
height: 56,
borderRadius: "16px",
}}
/>
</DemoContainer>
</LocalizationProvider>
</Box>
</Row>
<Row type="horizontal">
<Box
sx={{
width: 366,
height: 56,
borderRadius: "16px",
}}
>
<DropdownMenu
options={carOptions}
label="Car Make"
value={selectedCar}
onChange={handleCarChange}
/>
</Box>
<Box
sx={{
width: 366,
height: 56,
borderRadius: "16px",
}}
>
<DropdownMenu
options={carOptions}
label="Car Model"
value={selectedCar}
onChange={handleCarChange}
/>
</Box>
</Row>
<Row type="horizontal">
<Box
sx={{
width: 366,
borderRadius: "16px",
}}
>
<DropdownMenu
options={carOptions}
label="Model Year"
value={selectedCar}
onChange={handleCarChange}
/>
</Box>
<Box>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer components={["DatePicker"]} sx={{ pt: 0 }}>
<DatePicker
label="License Expiry Date"
sx={{
width: 366,
height: -10,
}}
/>
</DemoContainer>
</LocalizationProvider>
</Box>
</Row>
<Row type="horizontal">
<Box>
<Textarea
placeholder="Issue Details"
minRows={7}
sx={{
width: 366,
}}
/>
</Box>
</Row>
<Row type="horizontal">
<Button
onClick={() => {
navigate("/car-services");
}}
variant="contained"
sx={{
width: 139,
height: 56,
borderRadius: 5,
fontSize: 16,
background: "#005379",
shadow: "0 4 60 0 #0038FF26",
}}
>
save
</Button>
</Row>
</Row>
);
}
export default EditNewCarService;
|
import React, { useState } from "react";
import "./Post.css";
import Comment from "../../img/comment.png";
import Share from "../../img/share.png";
import Heart from "../../img/like.png";
import { getTimelinePosts } from "../../redux/actions/PostsAction";
import NotLike from "../../img/notlike.png";
import { likePost, deletePost } from "../../redux/api/PostsRequests";
import { useSelector, useDispatch } from "react-redux";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
const Post = ({ data }) => {
const server = process.env.REACT_APP_PUBLIC_FOLDER;
const dispatch = useDispatch();
const { user } = useSelector((state) => state.authReducer.authData);
const [liked, setLiked] = useState(data.likes.includes(user._id));
const [likes, setLikes] = useState(data.likes.length);
const handleLike = () => {
likePost(data._id, user._id);
setLiked((prev) => !prev);
liked ? setLikes((prev) => prev - 1) : setLikes((prev) => prev + 1);
};
const handleDelete = () => {
deletePost(data._id, user._id);
setTimeout(() => {
dispatch(getTimelinePosts(user._id));
}, 50);
};
return (
<div className="post">
<div className="postWrapper">
<div className="postTop">
<div className="postTopLeft">
<img
className="postProfileImg"
src={
data.imageUser
? server + data.imageUser
: server + "defaultProfile.png"
}
alt=""
/>
<span className="postUsername">@{data.username}</span>
<a className="postDate">
{data.createdAt.slice(0, 10)}
</a>
<div></div>
<a className="postDate">{data.createdAt.slice(11, 16)}</a>
</div>
<div className="postTopRight">
{data.username === user.username ? (
<DeleteForeverIcon
fontSize="large"
style={{ color: "red", cursor: "pointer" }}
onClick={handleDelete}
/>
) : null}
</div>
</div>
<div className="postCenter">
<span className="postText">{data.desc}</span>
<img
className="postImg"
src={
data.image ? process.env.REACT_APP_PUBLIC_FOLDER + data.image : ""
}
alt=""
/>
</div>
<div className="postBottom">
<div className="postBottomLeft">
<img
src={liked ? Heart : NotLike}
alt=""
style={{ cursor: "pointer" }}
onClick={handleLike}
/>
<img src={Comment} alt="" />
<img src={Share} alt="" />
<span>{likes} likes</span>
</div>
</div>
</div>
</div>
);
};
export default Post;
|
import { JwtPayload } from 'jsonwebtoken';
import { IValidationOptions } from '..';
export function validateTokenClaims(
tokenPayload: JwtPayload,
{ applicationId, audience, scopes, tenantId }: IValidationOptions,
): void {
// tenantId
if (!tokenPayload.tid) {
throw new Error('The token\'s payload does not contain "tid" property');
}
const isValidTenantId = tokenPayload.tid === tenantId;
if (!isValidTenantId) {
throw new Error("The token's payload contains different tenantId");
}
// applicationId
if (!tokenPayload.appid) {
throw new Error('The token\'s payload does not contain "appid" property');
}
const isValidApplicationId = tokenPayload.appid === applicationId;
if (!isValidApplicationId) {
throw new Error("The token's payload contains different applicationId");
}
// audience
if (!tokenPayload.aud) {
throw new Error('The token\'s payload does not contain "aud" property');
}
const isValidAudience = tokenPayload.aud === audience;
if (!isValidAudience) {
throw new Error("The token's payload contains different audience");
}
// security token service
if (!tokenPayload.iss) {
throw new Error('The token\'s payload does not contain "iss" property');
}
const isValidSecurityTokenService = tokenPayload.iss.includes('sts') && tokenPayload.iss.includes(tenantId);
if (!isValidSecurityTokenService) {
throw new Error("The token's payload contains different security token service");
}
// scopes
if (!tokenPayload.scp) {
throw new Error('The token\'s payload does not contain "scp" property');
}
if (typeof tokenPayload.scp !== 'string') {
throw new Error("The token's payload scopes are not a string value");
}
// expiration
if (!tokenPayload.exp) {
throw new Error('The token\'s payload does not contain "exp" property');
}
if (typeof tokenPayload.exp !== 'number') {
throw new Error("The token's payload expiration is not a number value");
}
const isValidExpiration = tokenPayload.exp > Math.floor(Date.now() / 1000);
if (!isValidExpiration) {
throw new Error("The token's payload contains different expiration");
}
const scopesAsArray = tokenPayload.scp.split(' ');
const hasValidScopes = scopes.every((_scope) => scopesAsArray.includes(_scope));
if (!hasValidScopes) {
throw new Error("The token's payload contains different scopes");
}
}
|
#Creating Basemap map
#Basemap allows you to create maps in Python. The library builds projections for latitude and longitude coordinates and then passes the plotting work on to matplotlib. This means you can build extra features based on the power of matplotlib.
#In this exercise, we're going to set up a map of the continental United States on a Mercator projection. The corner coordinates of this map are provided for you below.
#Instructions 1/2
#50 XP
#Import Basemap from mpl_toolkits.basemap.
#Instantiate Basemap. Use each element of us_boundingbox in order as arguments.
# Import Basemap
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
# Set up the US bounding box
us_boundingbox = [-125, 22, -64, 50]
# Set up the Basemap object
m = Basemap(llcrnrlon = us_boundingbox[0],
llcrnrlat = us_boundingbox[1],
urcrnrlon = us_boundingbox[2],
urcrnrlat = us_boundingbox[3],
projection='merc')
#Instructions 2/2
#50 XP
#Instantiate Basemap. Use each element of us_boundingbox in order as arguments.
#Draw the continents , coastlines, and countries with Basemap methods .fillcontinents(), .drawcoastlines(), and .drawcountries(), respectively.
# Import Basemap
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
# Set up the US bounding box
us_boundingbox = [-125, 22, -64, 50]
# Set up the Basemap object
m = Basemap(llcrnrlon = us_boundingbox[0],
llcrnrlat = us_boundingbox[1],
urcrnrlon = us_boundingbox[2],
urcrnrlat = us_boundingbox[3],
projection='merc')
# Draw continents in white,
# coastlines and countries in gray
m.fillcontinents(color='white')
m.drawcoastlines(color='gray')
m.drawcountries(color='gray')
# Draw the states and show the plot
m.drawstates(color='gray')
plt.show()
|
import React, { Component } from "react";
import header from "../images/platziconf-logo.svg";
import Badge from "../components/Badge";
import BadgeForm from "../components/BadgeForm";
import PageLoading from "../components/PageLoading";
import api from "../api";
import "./styles/BadgeEdit.css";
class BadgeEdit extends Component {
state = {
loading: true,
error: null,
form: {
firstName: "",
lastName: "",
email: "",
jobTitle: "",
twitter: "",
}
};
componentDidMount(){
this.fetchData();
}
fetchData = async(e) =>{
this.setState({
loadind: true,
error: null
});
try {
const data = await api.badges.read(
this.props.match.params.badgeId
);
this.setState({
loadind: false,
form: data
});
} catch (error) {
this.setState({
loadind: false,
error: error
});
}
}
handleChange = e => {
this.setState({
form: {
...this.state.form,
[e.target.name]: e.target.value
}
});
};
handlesubmit = async e => {
e.preventDefault();
this.setState({
loadind: true,
error: null
});
try {
await api.badges.update(this.props.match.params.badgeId, this.state.form);
this.setState({
loadind: false
});
this.props.history.push('/badges')
} catch (error) {
this.setState({
loadind: false,
error: error
});
}
};
render() {
if(this.state.loadind){
return <PageLoading/>
}
return (
<React.Fragment>
<div className="BadgeEdit__hero">
<img className="BadgeEdit__hero-image img-fluid" src={header} alt="" />
</div>
<div className="container">
<div className="row">
<div className="col-6">
<Badge
firstName={this.state.form.firstName || "FIRST_NAME"}
LastName={this.state.form.lastName || "LAST_EMA"}
twitter={this.state.form.twitter || "TWITTER"}
jobTitle={this.state.form.jobTitle || "JOB_TITLE"}
email={this.state.form.email || "EMAIL"}
/>
</div>
<div className="col-6">
<h1>Edit Asistente</h1>
<BadgeForm
onChange={this.handleChange}
onSubmit={this.handlesubmit}
formValues={this.state.form}
error={this.state.error}
/>
</div>
</div>
</div>
</React.Fragment>
);
}
}
export default BadgeEdit;
|
import React, { useState } from "react";
import { Button, Flex, useToast, Spinner, chakra, Text } from "@chakra-ui/react";
import { hasMetamask } from "../../utils/hasMetamask";
import useEthersProvider from "../../hooks/useEthersProvider";
import { ethers } from "ethers";
const Header = () => {
const [isLoading, setIsLoading] = useState(false);
const { account, setAccount, provider } = useEthersProvider();
const toast = useToast();
const connectWallet = async () => {
if (!hasMetamask) {
toast({
description: "Please install Metamask and retry",
status: "error",
duration: 5000,
isClosable: true
})
} else {
setIsLoading(true);
if (provider) {
let network = await provider.getNetwork();
// main blockchain
if (network.chainId === 1) {
setAccount(null);
setIsLoading(false);
toast({
description: "Please switch to dev chain ethereum on Metamask",
status: "warning",
duration: 4000,
isClosable: true
})
} else {
const resultAccount = await provider.send("eth_requestAccounts", []);
setAccount(ethers.utils.getAddress(resultAccount[0]));
setIsLoading(false);
toast({
description: "Your are connected",
status: "success",
duration: 4000,
isClosable: true
})
}
}
}
}
return (
<Flex align="center" flexDir={["column", "column", "row", "row"]} my="md" px={["sm", "sm", "lg", "lg"]} p="2rem">
<Text fontSize="2rem" fontWeight={900} letterSpacing={7}>
SMILEY
</Text>
<Flex align='center' justify="flex-end" flex={1}>
{isLoading ? (
<Spinner />
) : account ? (
<Flex flexDir="column" align={["center", "center", "flex-end", "flex-end"]}>
<Text fontSize={15}>
Connected Wallet : <chakra.span fontWeight="bold" color="orange.400">{account.substring(0, 6)}...{account.substring(account.length - 5, account.length)}</chakra.span>
</Text>
</Flex>
) : (
<Button colorScheme="orange" onClick={() => connectWallet()} fontSize={15}>
Connect Wallet
</Button>
)}
</Flex>
</Flex >
)
}
export default Header;
|
[](../../README.md)
# [TrOCR: Transformer based model for state-of-the-art optical character recognition (OCR) on both printed and handwritten text](https://aihub.qualcomm.com/models/trocr)
End-to-end text recognition approach with pre-trained image transformer and text transformer models for both image understanding and wordpiece-level text generation.
This is based on the implementation of TrOCR found
[here](https://huggingface.co/microsoft/trocr-small-stage1). This repository contains scripts for optimized on-device
export suitable to run on Qualcomm® devices. More details on model performance
accross various devices, can be found [here](https://aihub.qualcomm.com/models/trocr).
[Sign up](https://myaccount.qualcomm.com/signup) for early access to run these models on
a hosted Qualcomm® device.
## Example & Usage
Install the package via pip:
```bash
pip install "qai_hub_models[trocr]"
```
Once installed, run the following simple CLI demo:
```bash
python -m qai_hub_models.models.trocr.demo
```
More details on the CLI tool can be found with the `--help` option. See
[demo.py](demo.py) for sample usage of the model including pre/post processing
scripts. Please refer to our [general instructions on using
models](../../../#getting-started) for more usage instructions.
## Export for on-device deployment
This repository contains export scripts that produce a model optimized for
on-device deployment. This can be run as follows:
```bash
python -m qai_hub_models.models.trocr.export
```
Additional options are documented with the `--help` option. Note that the above
script requires access to Deployment instructions for Qualcomm® AI Hub.
## License
- The license for the original implementation of TrOCR can be found
[here](https://github.com/microsoft/unilm/blob/master/LICENSE).
- The license for the compiled assets for on-device deployment can be found [here]({deploy_license_url})
## References
* [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282)
* [Source Model Implementation](https://huggingface.co/microsoft/trocr-small-stage1)
## Community
* Join [our AI Hub Slack community](https://join.slack.com/t/qualcomm-ai-hub/shared_invite/zt-2dgf95loi-CXHTDRR1rvPgQWPO~ZZZJg) to collaborate, post questions and learn more about on-device AI.
* For questions or feedback please [reach out to us](mailto:ai-hub-support@qti.qualcomm.com).
|
import React, {useState} from "react"
function Input ({todoList,setTodoList}) {
const [title, setTitle] = useState("")
const [desc, setDesc] = useState("")
const titleChangeHandler = (event) => {
setTitle(event.target.value)
}
const descChangeHandler = (event) => {
setDesc(event.target.value)
}
const formSubmitHandler = (event) => {
if(todoList.length ===0){
const newTodo={
id:1,
title,
desc,
isDone : false
}
setTodoList([...todoList,newTodo])
setTitle("")
setDesc("")
}else{
let max_id =todoList[todoList.length -1]
let num = max_id.id
let max_num = num + 1
const newTodo = {
id:max_num,
title,
desc,
isDone:false
}
setTodoList([...todoList,newTodo])
setTitle("")
setDesc("")
}
// const newTodo = {
// id : todoList.length + 1,
// title,
// desc,
// isDone : false
// }
// console.log(newTodo)
// event.preventDefault();
// setTodoList([...todoList, newTodo])
// alert("할 일 등록 완료!")
// setTitle("")
// setDesc("")
}
return (
<div className='input-form'>
<form onSubmit={formSubmitHandler}>
<div>
제목 : <input className="input-box" type="text" value={title} required onChange={titleChangeHandler}/>
</div>
<div>
내용 : <input className="input-box" type="text" value={desc} required onChange={descChangeHandler}/>
</div>
<input type="submit" value="추가하기" className='submit-btn'/>
</form>
</div>
)
}
export default Input
|
#######################################################################################################################
# Adapted from https://github.com/CompVis/taming-transformers/blob/master/taming/modules/losses/lpips.py #
#######################################################################################################################
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from collections import namedtuple
import os, hashlib
import requests
from tqdm import tqdm
from .discriminator import NLayerDiscriminator, weights_init
URL_MAP = {
"vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"
}
CKPT_MAP = {
"vgg_lpips": "vgg.pth"
}
MD5_MAP = {
"vgg_lpips": "d507d7349b931f0638a25a48a722f98a"
}
class LPIPS(nn.Module):
# Learned perceptual metric
def __init__(self, use_dropout=True):
super().__init__()
self.scaling_layer = ScalingLayer()
self.chns = [64, 128, 256, 512, 512] # vg16 features
self.net = vgg16(pretrained=True, requires_grad=False)
self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
self.load_from_pretrained()
for param in self.parameters():
param.requires_grad = False
def load_from_pretrained(self, name="vgg_lpips"):
ckpt = get_ckpt_path(name, "taming/modules/autoencoder/lpips")
self.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False)
print("loaded pretrained LPIPS loss from {}".format(ckpt))
@classmethod
def from_pretrained(cls, name="vgg_lpips"):
if name != "vgg_lpips":
raise NotImplementedError
model = cls()
ckpt = get_ckpt_path(name)
model.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False)
return model
def forward(self, input, target):
# if input.shape[1] < 3: # the standard vgg in channels is 3
# B, C, H, W = input.shape
# in0_input = torch.cat([input, torch.zeros(size=(B, 3 - C, H, W)).to(input.device)], dim=1)
# in1_input = torch.cat([target, torch.zeros(size=(B, 3 - C, H, W)).to(target.device)], dim=1)
in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target))
outs0, outs1 = self.net(in0_input), self.net(in1_input)
feats0, feats1, diffs = {}, {}, {}
lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]
for kk in range(len(self.chns)):
feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])
diffs[kk] = (feats0[kk] - feats1[kk]) ** 2
res = [spatial_average(lins[kk].model(diffs[kk]), keepdim=True) for kk in range(len(self.chns))]
val = res[0]
for l in range(1, len(self.chns)):
val += res[l]
return val
class ScalingLayer(nn.Module):
def __init__(self):
super(ScalingLayer, self).__init__()
# self.register_buffer('shift', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])
# self.register_buffer('scale', torch.Tensor([.458, .448, .450])[None, :, None, None])
self.register_buffer('shift', torch.Tensor([-.030, -.088])[None, :, None, None])
self.register_buffer('scale', torch.Tensor([.458, .448])[None, :, None, None])
def forward(self, inp):
return (inp - self.shift) / self.scale
class NetLinLayer(nn.Module):
""" A single linear layer which does a 1x1 conv """
def __init__(self, chn_in, chn_out=1, use_dropout=False):
super(NetLinLayer, self).__init__()
layers = [nn.Dropout(), ] if (use_dropout) else []
layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False), ]
self.model = nn.Sequential(*layers)
class vgg16(torch.nn.Module):
def __init__(self,
requires_grad=False,
weights=models.VGG16_Weights.DEFAULT, pretrained=True
):
super(vgg16, self).__init__()
if pretrained:
weights = models.VGG16_Weights.DEFAULT
else:
weights = None
vgg_pretrained_features = models.vgg16(weights=weights).features
# getting weights of input channel
selected_weights = vgg_pretrained_features[0].weight[:, :2, ...]
vgg_pretrained_features[0] = nn.Conv2d(2, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
vgg_pretrained_features[0].weight = nn.Parameter(selected_weights, requires_grad=False)
self.slice1 = torch.nn.Sequential()
self.slice2 = torch.nn.Sequential()
self.slice3 = torch.nn.Sequential()
self.slice4 = torch.nn.Sequential()
self.slice5 = torch.nn.Sequential()
self.N_slices = 5
for x in range(4):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(4, 9):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(9, 16):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(16, 23):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
for x in range(23, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
h = self.slice1(X)
h_relu1_2 = h
h = self.slice2(h)
h_relu2_2 = h
h = self.slice3(h)
h_relu3_3 = h
h = self.slice4(h)
h_relu4_3 = h
h = self.slice5(h)
h_relu5_3 = h
vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'])
out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)
return out
def normalize_tensor(x,eps=1e-10):
norm_factor = torch.sqrt(torch.sum(x**2,dim=1,keepdim=True))
return x/(norm_factor+eps)
def spatial_average(x, keepdim=True):
return x.mean([2, 3],keepdim=keepdim)
def get_ckpt_path(name, root, check=False):
assert name in URL_MAP
path = os.path.join(root, CKPT_MAP[name])
if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]):
print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path))
download(URL_MAP[name], path)
md5 = md5_hash(path)
assert md5 == MD5_MAP[name], md5
return path
def download(url, local_path, chunk_size=1024):
os.makedirs(os.path.split(local_path)[0], exist_ok=True)
with requests.get(url, stream=True) as r:
total_size = int(r.headers.get("content-length", 0))
with tqdm(total=total_size, unit="B", unit_scale=True) as pbar:
with open(local_path, "wb") as f:
for data in r.iter_content(chunk_size=chunk_size):
if data:
f.write(data)
pbar.update(chunk_size)
def md5_hash(path):
with open(path, "rb") as f:
content = f.read()
return hashlib.md5(content).hexdigest()
class LPIPSWithDiscriminator(nn.Module):
def __init__(self,
disc_start,
logvar_init=0.,
kl_weight=1.,
pixel_weight=1.,
perceptual_weight=1.,
disc_weight=1.,
cos_weight=1.,
disc_input_channels=3,
disc_channels=64,
disc_num_layers=3,
disc_factor=1.,
**kwargs
) -> None:
super().__init__()
self.pixel_weight = pixel_weight
self.perceptual_weight = perceptual_weight
self.disc_weight = disc_weight
self.cos_weight = cos_weight
self.disc_factor = disc_factor
self.kl_weight = kl_weight
self.disc_start = disc_start
self.logvar = nn.Parameter(torch.ones(1) * logvar_init, requires_grad=True)
# modules
self.lpips = LPIPS().eval()
self.discriminator = NLayerDiscriminator(
disc_input_channels, disc_channels, disc_num_layers, use_actnorm=False
).apply(weights_init)
def calculate_adaptive_weight(self, rec_loss, g_loss, last_layer=None):
if last_layer is not None:
nll_grads = torch.autograd.grad(rec_loss, last_layer, retain_graph=True)[0]
g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
else:
nll_grads = torch.autograd.grad(rec_loss, self.last_layer[0], retain_graph=True)[0]
g_grads = torch.autograd.grad(g_loss, self.last_layer[0], retain_graph=True)[0]
disc_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
disc_weight = torch.clamp(disc_weight, 0.0, 1e4).detach()
disc_weight = disc_weight * self.disc_weight
return disc_weight
def autoencoder_loss(self, x, recon_x, global_step, last_layer=None, split='train'):
l1_loss = F.l1_loss(recon_x, x, reduction='none') * self.pixel_weight
p_loss = self.lpips(x, recon_x) * self.perceptual_weight
rec_loss = l1_loss + p_loss
rec_loss = torch.sum(rec_loss) / rec_loss.shape[0]
# discriminator loss term
g_loss = torch.tensor(0.0, requires_grad=True)
if global_step > self.disc_start:
logits_recon = self.discriminator(recon_x.contiguous())
g_loss = -torch.mean(logits_recon)
# lsgan style
# valid = torch.ones_like(logits_recon) - torch.rand_like(logits_recon) * 0.05
# g_loss = F.mse_loss(logits_recon, valid)
disc_weight = torch.tensor(0.0)
if last_layer is not None and global_step > self.disc_start:
disc_weight = self.calculate_adaptive_weight(rec_loss, g_loss, last_layer)
g_loss = g_loss * disc_weight
# compute total loss
loss = rec_loss + g_loss * self.disc_factor
split = split + '/' if split != 'train' else ''
log = {
"{}auxilary_loss".format(split): loss.clone().detach().mean(),
"{}l1_loss".format(split): l1_loss.detach().mean(),
"{}p_loss".format(split): p_loss.detach().mean(),
"{}rec_loss".format(split): rec_loss.detach().mean(), # L1 + p_loss
"{}disc_weight".format(split): disc_weight.detach(),
"{}g_loss".format(split): g_loss.detach().mean(),
}
return loss, log
def discriminator_loss(self, x, recon_x, global_step):
default_return = torch.tensor(0.0, requires_grad=True), {
"d_loss": torch.tensor(0.0),
"logits_real": torch.tensor(0.0),
"logits_fake": torch.tensor(0.0)
}
if global_step > self.disc_start:
logits_real = self.discriminator(x.contiguous().detach())
logits_fake = self.discriminator(recon_x.contiguous().detach())
d_loss = self.disc_factor * hinge_loss(logits_real, logits_fake)
# ls-gan style
# valid = torch.ones_like(logits_real) - torch.rand_like(logits_real) * 0.05
# fake = torch.rand_like(logits_fake) * 0.05
# real_loss = F.mse_loss(logits_real, valid)
# fake_loss = F.mse_loss(logits_fake, fake)
# d_loss = 0.5 * (real_loss + fake_loss) * self.disc_factor
log = {
"d_loss": d_loss.clone().detach().mean(),
"logits_real": logits_real.detach().mean(),
"logits_fake": logits_fake.detach().mean()
}
return d_loss, log
return default_return
def forward(self, codebook_loss, x, recon_x, z_i, optimizer_idx, global_step, last_layer=None):
if optimizer_idx == 0:
loss, log = self.autoencoder_loss(codebook_loss, x, recon_x, z_i, global_step, last_layer)
elif optimizer_idx == 1:
loss, log = self.discriminator_loss(x, recon_x, global_step)
return loss, log
def hinge_loss(logits_real, logits_fake):
loss = 0.5 * (torch.mean(F.relu(1.0 - logits_real)) + torch.mean(F.relu(1.0 + logits_fake)))
return loss
|
import { IsEmail, IsString, MinLength } from "class-validator";
import { Ruta } from "src/rutas/entities/ruta.entity";
export class CreateClientDto {
@IsString()
@MinLength(1)
fullName: string;
@IsString()
@MinLength(5)
documento: string;
@IsString()
@MinLength(7)
telefono: string;
@IsString()
@IsEmail()
email: string;
@IsString()
@MinLength(1)
direccion: string;
@IsString()
@MinLength(7)
telefonoFamiliar: string;
@IsString()
ruta: Ruta;
}
|
import { dataview as dv } from "../utility/dataview";
import { wrapError as wrap } from "../utility/wrap-error";
import type { Unit } from "../type/unit";
type NumUnit = Unit<number, RangeError>;
const getFloat16 = (buffer: Uint8Array, offset: number, isLittleEndian?: boolean) => {
/*
* seee_eeff ffff_ffff
* e: 5, f: 10
* s * (2 ** e_eeee - 01111) * 1.ffffffffff
* s * (2 ** e_eeee - 01111) * 0.ffffffffff (e == 0_0000 = 0)
* s * Infinity (e == 1_1111 = 31, f == 0)
* NaN (e == 1_1111 = 31, f != 0)
*/
const u16 = dv(buffer).getUint16(offset, isLittleEndian);
const sign = u16 >> 15 ? -1 : 1;
const exponent = (u16 & 0b0111_1100_0000_0000) >> 10;
const significant = u16 & 0b0011_1111_1111;
if (exponent === 0) {
return sign * significant * Math.pow(2, -24);
}
if (exponent === 31) {
return significant ? Number.NaN : sign * Number.POSITIVE_INFINITY;
}
return sign * (significant + Math.pow(2, 10)) * Math.pow(2, exponent - 25);
};
export const f16be: NumUnit = [2, (buffer, offset) => wrap(() => getFloat16(buffer, offset))];
export const f16le: NumUnit = [2, (buffer, offset) => wrap(() => getFloat16(buffer, offset, true))];
export const f32be: NumUnit = [4, (buffer, offset) => wrap(() => dv(buffer).getFloat32(offset))];
export const f32le: NumUnit = [4, (buffer, offset) => wrap(() => dv(buffer).getFloat32(offset, true))];
export const f64be: NumUnit = [8, (buffer, offset) => wrap(() => dv(buffer).getFloat64(offset))];
export const f64le: NumUnit = [8, (buffer, offset) => wrap(() => dv(buffer).getFloat64(offset, true))];
|
/// <summary>
/// Codeunit Json Parser (ID 50111).
/// </summary>
codeunit 50111 "Json Builder"
{
var
DocumentToken: JsonToken;
trigger OnRun()
var
JsonBuilder: Codeunit "Json Builder";
begin
JsonBuilder.NewArray();
JsonBuilder.Add(BuildJson('a'));
JsonBuilder.Add(BuildJson('b'));
Message(JsonBuilder.AsString());
end;
local procedure BuildJson(Token: Text): JsonToken
var
JsonBuilder: Codeunit "Json Builder";
begin
JsonBuilder.Add('key1', Token + '1');
JsonBuilder.Add('key2', Token + '2');
exit(JsonBuilder.AsToken());
end;
/// <summary>
/// Creates new json object.
/// </summary>
procedure New()
var
JsonObject: JsonObject;
begin
DocumentToken := JsonObject.AsToken();
end;
/// <summary>
/// Creates new json object from token.
/// </summary>
/// <param name="JsonToken">JsonToken.</param>
procedure New(JsonToken: JsonToken)
begin
DocumentToken := JsonToken;
end;
/// <summary>
/// Creates new json object from object.
/// </summary>
/// <param name="JsonObject">JsonObject.</param>
procedure New(JsonObject: JsonObject)
begin
DocumentToken := JsonObject.AsToken();
end;
/// <summary>
/// Creates new json array.
/// </summary>
procedure NewArray()
var
JsonArray: JsonArray;
begin
DocumentToken := JsonArray.AsToken();
end;
/// <summary>
/// Creates new json array from Array token.
/// </summary>
/// <param name="JsonToken">JsonToken.</param>
procedure NewArray(JsonToken: JsonToken)
begin
DocumentToken := JsonToken;
end;
/// <summary>
/// Creates new json array from Array.
/// </summary>
/// <param name="JsonArray">JsonArray.</param>
procedure NewArray(JsonArray: JsonArray)
begin
DocumentToken := JsonArray.AsToken();
end;
/// <summary>
/// Adds new key/value pair to an json object.
/// </summary>
/// <param name="NodeKey">Text.</param>
/// <param name="NodeValue">Text.</param>
procedure Add(NodeKey: Text; NodeValue: Text)
begin
If IsNull() then
New();
If not DocumentToken.IsObject() then
Error('Pair %1/%2 can not be added to Json %3.', NodeKey, NodeValue, GetType());
DocumentToken.AsObject().Add(NodeKey, NodeValue);
end;
/// <summary>
/// Adds new object to an array.
/// </summary>
/// <param name="JsonToken">JsonToken.</param>
procedure Add(JsonToken: JsonToken)
var
JsonBuilder: Codeunit "Json Builder";
begin
JsonBuilder.New(JsonToken);
If IsNull() then
NewArray();
If not DocumentToken.IsArray() then
Error('Json %1 can not be added to Json %2.', JsonBuilder.AsString(), GetType());
DocumentToken.AsArray().Add(JsonToken);
end;
/// <summary>
/// Returns string from document.
/// </summary>
/// <returns>Return variable Result of type Text.</returns>
procedure AsString() Result: Text
begin
DocumentToken.WriteTo(Result);
end;
/// <summary>
/// Returns Json token from document.
/// </summary>
/// <returns>Return value of type JsonToken.</returns>
procedure AsToken(): JsonToken
begin
exit(DocumentToken);
end;
/// <summary>
/// Tests if document is empty or null.
/// </summary>
/// <returns>Return value of type Boolean.</returns>
procedure IsNull(): Boolean;
begin
exit(AsString() = 'null');
end;
/// <summary>
/// Returns type of document.
/// </summary>
/// <returns>Return value of type Text.</returns>
procedure GetType(): Text;
begin
case true of
DocumentToken.IsArray:
exit('Array');
DocumentToken.IsObject:
exit('Object');
DocumentToken.IsValue:
exit('Value');
else
exit('Unknown');
end;
end;
/// <summary>
/// Field returns value of field as JsonValue.
/// </summary>
/// <param name="FieldName">Name of the field to retrieve.</param>
/// <returns>Return value of type JsonFiles. Add AsText or such function to then end of this call.</returns>
procedure Field(FieldName: Text): JsonValue
var
JsonToken: JsonToken;
begin
DocumentToken.AsObject().Get(FieldName, JsonToken);
exit(JsonToken.AsValue());
end;
}
|
(() => {
class Apocalipsis {
public static instance: Apocalipsis;
private constructor(public name: string) {}
public static callApocalipsis(): Apocalipsis {
if(!Apocalipsis.instance) {
Apocalipsis.instance = new Apocalipsis("Apocalipsis");
}
return Apocalipsis.instance;
}
public changeName(newName: string): void {
this.name = newName;
}
}
//* Implementación del Patrón de Diseño Singleton
const apocalipsis1 = Apocalipsis.callApocalipsis();
const apocalipsis2 = Apocalipsis.callApocalipsis();
const apocalipsis3 = Apocalipsis.callApocalipsis();
//* apocalipsis1.changeName('Gustavo');
// const apocalipsis1 = new Apocalipsis('Soy Apocalipsis1... el único')
// const apocalipsis2 = new Apocalipsis('Soy Apocalipsis2... el único')
// const apocalipsis3 = new Apocalipsis('Soy Apocalipsis3... el único')
console.log(apocalipsis1, apocalipsis2, apocalipsis3);
})()
|
import Head from "next/head";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import useSWR from "swr";
import EventList from "@/components/EventList";
import EventSearch from "@/components/EventSearch";
import ResultsTitle from "@/components/ResultsTitle";
import Button from "@/components/ui/Button";
import ErrorAlert from "@/components/ui/ErrorAlert";
import { getFilteredEvents } from "@/dummy-data";
const fetcher = (...args) => fetch(...args).then((res) => res.json());
export default function FilteredEventPage() {
const [allEvents, setAllEvents] = useState([]);
const router = useRouter();
const { data, error } = useSWR(
"https://nextjs-course-7f144-default-rtdb.asia-southeast1.firebasedatabase.app/events.json",
fetcher
);
useEffect(() => {
if (data) {
const e = Object.entries(data).map(([key, value]) => ({
...value,
id: key,
}));
setAllEvents(e);
}
}, [data]);
if (!router.query.slug) {
<p className="center">Loading....</p>;
}
const [year, month] = router.query.slug;
const nYear = +year;
const nMonth = +month;
// if (props.error) {
if (isNaN(nYear) || isNaN(nMonth) || nMonth < 1 || nMonth > 12 || error) {
return (
<>
<ErrorAlert>
<p>Invalid filter. Please adjust your values!</p>
</ErrorAlert>
<div className="center">
<Button link="/events">Show All Events</Button>
</div>
</>
);
}
const events = allEvents.filter((event) => {
const eventDate = new Date(event.date);
return (
eventDate.getFullYear() === nYear && eventDate.getMonth() === nMonth - 1
);
});
// const {
// events,
// date: { year, month },
// } = props;
if (!events || events.length === 0) {
return (
<>
<ErrorAlert>
<p>No events found for the chosen filter!</p>
</ErrorAlert>
<div className="center">
<Button link="/events">Show All Events</Button>
</div>
</>
);
}
return (
<div>
<Head>
<title>Filter Events</title>
<meta
name="description"
content={`Find Events in ${nYear}/${nMonth}`}
/>
</Head>
<ResultsTitle date={new Date(nYear, nMonth - 1)} />
<EventList events={events} />
</div>
);
}
// export async function getServerSideProps(context) {
// const { params } = context;
// const [year, month] = params.slug;
// const nYear = +year;
// const nMonth = +month;
// if (isNaN(nYear) || isNaN(nMonth) || nMonth < 1 || nMonth > 12) {
// return {
// props: {
// error: true,
// },
// };
// }
// const events = await getFilteredEvents({ year: nYear, month: nMonth });
// return {
// props: {
// events,
// date: {
// year: nYear,
// month: nMonth,
// },
// },
// };
// }
|
import { withIronSessionApiRoute } from "iron-session/next";
const HALF_HR_IN_MS = 60 * 30 * 1000;
export const AUTHENTICATION_COOKIE_OPTIONS = {
sameSite: true,
httpOnly: true,
// secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
secure: process.env.NODE_ENV === "production",
maxAge: HALF_HR_IN_MS,
overwrite: true,
};
export default withIronSessionApiRoute(loginRoute, {
cookieName: process.env.authentication_cookie_name,
password: process.env.secret_cookie_password,
ttl: HALF_HR_IN_MS,
cookieOptions: AUTHENTICATION_COOKIE_OPTIONS,
});
async function loginRoute(req, res) {
// Makes sure it's a POST request.
if (req.method !== "POST") {
return res.status(404).json({ message: "not found" });
}
// Grab the credentials from the request body.
const credentials = req.body;
try {
// Calls the authentication provider to log in.
const loginResponse: Response = await fetch(
`${process.env.backend_url}/auth/admin-login`,
{
method: "POST",
body: JSON.stringify(credentials),
headers: {
"Content-Type": "application/json",
},
}
);
// If the answer is not 2xx, we assume the credentials are invalid.
if (!loginResponse.ok) {
return res.status(401).json({ message: "Invalid credentials" });
}
// Reads the access token
const loginResData = await loginResponse.json();
const { token, userId } = loginResData;
// get user from database then:
req.session.user = {
token,
userId,
admin: true,
isLoggedIn: true,
};
await req.session.save();
res.send({ ok: true });
} catch (e) {
// We could log the error or do something different with it.
console.log({ e });
return res.status(500).send({ message: "Internal server error" });
}
}
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<!-- Favicons -->
<link rel="shortcut icon" type="icon/image" href="https://acedatasystems.com/wp-content/themes/acedata/shared/images/fav/favicon.ico">
<div th:replace="side-bar :: head"></div>
<div th:replace="side-bar :: customforaddjob"></div>
</head>
<body>
<div th:replace="side-bar :: header"></div>
<div th:replace="side-bar :: sidebar"></div>
<main id="main" class="main">
<div class="pagetitle">
<h1>Add Jobs</h1>
<nav>
<ol class="breadcrumb">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Add Job</li>
</ol>
</nav>
</div><!-- End Page Title -->
<section class="section dashboard">
<div class="body99">
<!--start of job offer form -->
<div class="body99">
<div class="card">
<div class="card-body">
<h5 class="card-title">Offer Jobs</h5>
<!-- Floating Labels Form -->
<form th:action="@{/vacancy/post}" class="row g-3" method="post" th:object="${vacancyBean}">
<div class="col-md-6">
<div class="form-floating">
<input type="text" class="form-control" id="floatingName" placeholder="Position"
name="positionName">
<label for="floatingName">Position Name</label>
</div>
</div>
<div class="col-md-3">
<div class="form-floating">
<input type="text" class="form-control" id="salary" name="salary" placeholder="-">
<label for="salary">Salary</label>
</div>
</div>
<div class="col-md-3">
<div class="form-floating">
<input type="number" class="form-control" id="numberOfPost" placeholder="Posts" name="posts">
<label for="numberOfPost">Number of Posts</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating">
<input type="text" class="form-control" id="wkd" placeholder="-" readonly
style="pointer-events: none; border: none;">
<label for="wkd">Choose Working Days</label>
</div>
</div>
<div class="col-md-6">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="mondayCheckbox" value="Mon" name="workingDays"
checked>
<label class="form-check-label" for="mondayCheckbox">
Monday
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="tuesdayCheckbox" value="Tue" name="workingDays"
checked>
<label class="form-check-label" for="tuesdayCheckbox">
Tuesday
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="wednesdayCheckbox" value="Wed"
name="workingDays" checked>
<label class="form-check-label" for="wednesdayCheckbox">
Wednesday
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="thursdayCheckbox" value="Thu" name="workingDays"
checked>
<label class="form-check-label" for="thursdayCheckbox">
Thursday
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="fridayCheckbox" value="Fri" name="workingDays"
checked>
<label class="form-check-label" for="fridayCheckbox">
Friday
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="saturdayCheckbox" value="Sat"
name="workingDays">
<label class="form-check-label" for="saturdayCheckbox">
Saturday
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="sundayCheckbox" value="Sun" name="workingDays">
<label class="form-check-label" for="sundayCheckbox">
Sunday
</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating">
<input type="text" class="form-control" id="wkh" placeholder="-" readonly
style="pointer-events: none; border: none;">
<label for="wkh">Choose Working Hours</label>
</div>
</div>
<div class="col-md-3">
<div class="form-floating">
<input type="time" class="form-control" id="workFrom" name="workingHourFrom">
<label for="workFrom">From</label>
</div>
</div>
<div class="col-md-3">
<div class="form-floating">
<input type="time" class="form-control" id="workTo" name="workingHourTo">
<label for="workTo">To</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating">
<input type="text" class="form-control" id="jobtype" placeholder="-" readonly
style="pointer-events: none; border: none;">
<label for="jobtype">Choose Job Types</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating">
<div class="form-check">
<input class="form-check-input" type="radio" name="jobType" id="fullTime" value="Fulltime"
checked>
<label class="form-check-label" for="fullTime">
Full Time
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="jobType" id="partTime" value="Parttime">
<label class="form-check-label" for="partTime">
Part Time
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="jobType" id="workFrom" value="Workfromhome">
<label class="form-check-label" for="workFrom">
Work From Home
</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-floating">
<input type="text" class="form-control" placeholder="-" readonly
style="pointer-events: none; border: none;">
<label for="department">Choose Department</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating">
<select class="form-select " id="department" aria-label="Job Location" name="departmentId">
<option value="" disabled selected>Choose Department</option>
<!-- Add more location options as needed -->
</select>
<label for="department">Department</label>
</div>
</div>
<div class="col-12">
<div class="form-floating">
<textarea class="form-control" id="description" style="height: 100px;" name="description"
placeholder="-"></textarea>
<label for="description">Job Description</label>
</div>
</div>
<div class="col-12">
<div class="form-floating" id="respo">
<textarea class="form-control" id="responsibility" style="height: 100px;" name="responsibilities"
placeholder="-"></textarea>
<!-- <label for="responsibility">Job Responsibilities</label> -->
</div>
</div>
<div class="col-12">
<div class="form-floating" id="requ">
<textarea class="form-control" id="requirement" style="height: 100px;" name="requirements"
placeholder="-"></textarea>
<!-- <label for="requirement">Job Requirements</label> -->
</div>
</div>
<div class="col-12">
<div class="form-floating" id="prefer">
<textarea class="form-control" id="preference" style="height: 100px;" name="preference"
placeholder="-"></textarea>
<!-- <label for="preference">Preference</label> -->
</div>
</div>
<hr>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</form><!-- End floating Labels Form -->
</div>
</div>
</div>
<!--end of job offer form -->
<div id="myDiv" style="display: none;" th:text="${session.success}"></div>
</section>
</main><!-- End #main -->
<div th:replace="side-bar :: footer"></div>
<div th:replace="side-bar :: scripts"></div>
</body>
</html>
|
use std::fmt::Display;
use bitvec::vec::BitVec;
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Phase {
pr,
pi,
nr,
ni,
}
impl Phase {
pub fn mul(&self, rhs: &Phase) -> Phase {
match (self, rhs) {
(Phase::pr, Phase::pr) => Phase::pr,
(Phase::pr, Phase::pi) => Phase::pi,
(Phase::pr, Phase::nr) => Phase::nr,
(Phase::pr, Phase::ni) => Phase::ni,
(Phase::pi, Phase::pr) => Phase::pi,
(Phase::pi, Phase::pi) => Phase::nr,
(Phase::pi, Phase::nr) => Phase::ni,
(Phase::pi, Phase::ni) => Phase::pr,
(Phase::nr, Phase::pr) => Phase::nr,
(Phase::nr, Phase::pi) => Phase::ni,
(Phase::nr, Phase::nr) => Phase::pr,
(Phase::nr, Phase::ni) => Phase::pi,
(Phase::ni, Phase::pr) => Phase::ni,
(Phase::ni, Phase::pi) => Phase::pr,
(Phase::ni, Phase::nr) => Phase::pi,
(Phase::ni, Phase::ni) => Phase::nr,
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Pauli {
I,
X,
Y,
Z,
}
impl Pauli {
pub fn mul(&self, rhs: &Pauli) -> (Phase, Pauli) {
match (self, rhs) {
(Pauli::I, Pauli::I) => (Phase::pr, Pauli::I),
(Pauli::I, Pauli::X) => (Phase::pr, Pauli::X),
(Pauli::I, Pauli::Y) => (Phase::pr, Pauli::Y),
(Pauli::I, Pauli::Z) => (Phase::pr, Pauli::Z),
(Pauli::X, Pauli::I) => (Phase::pr, Pauli::X),
(Pauli::X, Pauli::X) => (Phase::pr, Pauli::I),
(Pauli::X, Pauli::Y) => (Phase::pi, Pauli::Z),
(Pauli::X, Pauli::Z) => (Phase::ni, Pauli::Y),
(Pauli::Y, Pauli::I) => (Phase::pr, Pauli::Y),
(Pauli::Y, Pauli::X) => (Phase::ni, Pauli::Z),
(Pauli::Y, Pauli::Y) => (Phase::pr, Pauli::I),
(Pauli::Y, Pauli::Z) => (Phase::pi, Pauli::X),
(Pauli::Z, Pauli::I) => (Phase::pr, Pauli::Z),
(Pauli::Z, Pauli::X) => (Phase::pi, Pauli::Y),
(Pauli::Z, Pauli::Y) => (Phase::ni, Pauli::X),
(Pauli::Z, Pauli::Z) => (Phase::pr, Pauli::I),
}
}
}
#[derive(Debug, Clone)]
pub struct ExperimentalPauliString {
phase: Phase,
pub x_string: BitVec,
pub z_string: BitVec,
}
#[derive(Debug, Clone)]
pub struct PauliString {
pub phase: Phase,
pub string: Vec<Pauli>, // TODO: how to store pauli string? currently using a string, should use a bitvec
}
impl PauliString {
// TODO: Should really use regex for this?
// TODO: Add phase?
pub fn from(input: String) -> Self {
let paulis = input
.into_bytes()
.into_iter()
.map(|x| match x {
b'I' => Pauli::I,
b'X' => Pauli::X,
b'Y' => Pauli::Y,
b'Z' => Pauli::Z,
_ => panic!("Encountered non-pauli character in input string"),
})
.collect();
PauliString {
phase: Phase::pr,
string: paulis,
}
}
pub fn index(&self, index: usize) -> Pauli {
self.string
.get(index)
.expect("Bad PauliString index")
.clone()
}
pub fn len(&self) -> usize {
self.string.len()
}
pub fn new() -> Self {
PauliString {
phase: Phase::pr,
string: Vec::new(),
}
}
pub fn push(&mut self, p: Pauli) {
self.string.push(p);
}
pub fn set_phase(&mut self, phase: Phase) {
self.phase = phase;
}
pub fn mul(&self, rhs: &PauliString) -> PauliString {
let mut tot_phase = Phase::pr;
if self.len() != rhs.len() {
PauliString::new()
} else {
let mut ps = PauliString::new();
for ix in 0..self.len() {
let (tmp_phase, pauli) = self.index(ix).mul(&rhs.index(ix));
tot_phase = tot_phase.mul(&tmp_phase);
ps.push(pauli);
}
ps.set_phase(tot_phase);
ps
}
}
pub fn commutes(&self, rhs: &PauliString) -> bool {
let self_on_left = self.mul(rhs);
let self_on_right = rhs.mul(self);
for ix in 0..self.len() {
if self_on_left.index(ix) != self_on_right.index(ix) {
return false;
}
}
if self_on_left.phase != self_on_right.phase {
return false;
}
true
}
pub fn anti_commutes(&self, rhs: &PauliString) -> bool {
let self_on_left = self.mul(rhs);
let self_on_right = rhs.mul(self);
for ix in 0..self.len() {
if self_on_left.index(ix) != self_on_right.index(ix) {
return false;
}
}
if self_on_left.phase != self_on_right.phase.mul(&Phase::nr) {
return false;
}
true
}
}
impl Display for PauliString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let _ = f.write_str(match self.phase {
Phase::pr => "+",
Phase::pi => "+i",
Phase::nr => "-",
Phase::ni => "-i",
});
for pauli in self.string.iter() {
let _ = f.write_str(match pauli {
Pauli::I => "I",
Pauli::X => "X",
Pauli::Y => "Y",
Pauli::Z => "Z",
});
}
Ok(())
}
}
|
import Link, { LinkProps } from 'next/link';
import { cn } from '@/lib/utils';
import { VariantProps } from 'class-variance-authority';
import { FC } from 'react';
import { textVariants } from '../text/h1';
import H3 from '../text/h3';
interface LogoProps extends LinkProps, VariantProps<typeof textVariants> {
className?: string;
children?: React.ReactNode;
}
const Logo: FC<LogoProps> = ({
className,
children,
textType,
intent,
hover,
href = '/',
...props
}) => {
return (
<Link href={href} {...props}>
<H3
className={cn(
textVariants({
className,
intent,
textType,
hover
})
)}
>
{children}
</H3>
</Link>
);
};
export default Logo;
|
;;; SPDX-FileCopyrightText: 2024 Jomco B.V.
;;; SPDX-FileCopyrightText: 2024 Topsector Logistiek
;;; SPDX-FileContributor: Joost Diepenmaat <joost@jomco.nl
;;; SPDX-FileContributor: Remco van 't Veer <remco@jomco.nl>
;;;
;;; SPDX-License-Identifier: AGPL-3.0-or-later
(ns dil-demo.erp.web
(:require [clojure.string :as string]
[compojure.core :refer [routes DELETE GET POST]]
[dil-demo.master-data :as d]
[dil-demo.otm :as otm]
[dil-demo.store :as store]
[dil-demo.web-utils :as w]
[ring.util.response :refer [redirect]])
(:import (java.time LocalDateTime)
(java.util Date UUID)))
(defn list-consignments [consignments {:keys [eori->name]}]
[:main
[:section.actions
[:a.button.primary {:href "consignment-new"} "Nieuwe order aanmaken"]]
(when-not (seq consignments)
[:article.empty
[:p "Nog geen klantorders geregistreerd.."]])
(for [{:keys [id ref goods load unload carrier status]} consignments]
[:article
[:header
[:div.status (otm/status-titles status)]
[:div.ref-date ref " / " (:date load)]
[:div.from-to (-> load :location-eori eori->name) " → " (:location-name unload)]]
[:div.goods goods]
[:div.carrier (-> carrier :eori eori->name)]
[:footer.actions
(when (= otm/status-draft status)
[:a.button.primary {:href (str "consignment-" id)
:title "Eigenschappen aanpassen"}
"Aanpassen"])
(when (= otm/status-draft status)
[:a.button.secondary {:href (str "publish-" id)
:title "Opdracht versturen naar locatie en vervoerder"}
"Versturen"])
(w/delete-button (str "consignment-" id))]])])
(defn edit-consignment [consignment {:keys [carriers warehouses]}]
(let [{:keys [status ref load unload goods carrier]} consignment
;; add empty option
carriers (into {nil nil} carriers)]
[:form {:method "POST"}
(w/anti-forgery-input)
[:section
(w/field {:name "status", :value status,
:label "Status", :type "select",
:list otm/status-titles})
(w/field {:name "ref", :value ref,
:label "Klantorder nr.", :type "number",
:required true})]
[:section
(w/field {:name "load[date]", :type "date",
:label "Ophaaldatum", :value (:date load)})
(w/field {:name "load[location-eori]", :value (:location-eori load), ;; EORIs?!
:label "Ophaaladres", :type "select",
:list warehouses, :required true})
(w/field {:name "load[remarks]", :value (:remarks load),
:label "Opmerkingen", :type "textarea"})]
[:section
(w/field {:name "unload[date]", :value (:date unload),
:label "Afleverdatum", :type "date"})
(w/field {:name "unload[location-name]", :value (:location-name unload),
:label "Afleveradres", :type "text",
:list (keys d/locations), :required true})
(w/field {:name "unload[remarks]", :value (:remarks unload),
:label "Opmerkingen", :type "textarea"})]
[:section
(w/field {:name "goods", :value goods,
:label "Goederen", :type "text",
:list d/goods, :required true})
(w/field {:name "carrier[eori]", :value (:eori carrier),
:label "Vervoerder", :type "select",
:list carriers, :required true})]
[:section.actions
[:button {:type "submit"} "Opslaan"]
[:a.button {:href "."} "Annuleren"]]]))
(defn deleted-consignment [{:keys [explanation]}]
[:div
[:section
[:div.actions
[:a.button {:href "."} "Terug naar overzicht"]]]
(w/explanation explanation)])
(defn publish-consignment [consignment {:keys [eori->name warehouse-addresses]}]
(let [{:keys [status ref load unload goods carrier]} consignment]
[:form {:method "POST"}
(w/anti-forgery-input)
(when (not= otm/status-draft status)
[:div.flash.flash-warning
"Let op! Deze opdracht is al verzonden!"])
[:section.details
[:dl
[:div
[:dt "Klantorder nr."]
[:dd ref]]
[:div
[:dt "Ophaaldatum"]
[:dd (:date load)]]
[:div
[:dt "Afleverdatum"]
[:dd (:date unload)]]
[:div
[:dt "Vervoerder"]
[:dd (-> carrier :eori eori->name)]]]]
[:section.trip
[:fieldset.load-location
[:legend "Ophaaladres"]
[:h3 (-> load :location-eori eori->name)]
(when-let [address (-> load :location-eori warehouse-addresses)]
[:pre address])
(when-not (string/blank? (:remarks load))
[:blockquote.remarks (:remarks load)])]
[:fieldset.unload-location
[:legend "Afleveradres"]
[:h3 (:location-name unload)]
(when-let [address (-> unload :location-name d/locations)]
[:pre address])
(when-not (string/blank? (:remarks unload))
[:blockquote.remarks (:remarks unload)])]]
[:section.goods
[:fieldset
[:legend "Goederen"]
[:pre goods]]]
[:div.actions
[:button {:type "submit"
:onclick "return confirm('Zeker weten?')"}
"Versturen"]
[:a.button {:href "."} "Annuleren"]]]))
(defn published-consignment [consignment
{:keys [eori->name]}
{:keys [explanation]}]
[:div
[:section
[:p "Transportopdracht verstuurd naar locatie "
[:q (-> consignment :load :location-eori eori->name)]
" en vervoerder "
[:q (-> consignment :carrier :eori eori->name)]
"."]
[:div.actions
[:a.button {:href "."} "Terug naar overzicht"]]]
(w/explanation explanation)])
(defn get-consignments [store]
(->> store :consignments vals (sort-by :creation-date) (reverse)))
(defn get-consignment [store id]
(get-in store [:consignments id]))
(defn min-ref [user-number]
(let [dt (LocalDateTime/now)]
(+ (* user-number
100000000)
(* (- (.getYear dt) 2000)
1000000)
(* (.getDayOfYear dt)
1000))))
(defn next-consignment-ref [store user-number]
(let [refs (->> store
(get-consignments)
(map :ref)
(map parse-long))]
(str (inc (apply max (min-ref user-number) refs)))))
(defn make-handler [{:keys [eori id site-name]}]
{:pre [(keyword? id) site-name]}
(let [slug (name id)
render (fn render [title main flash & {:keys [slug-postfix]}]
(w/render-body (str slug slug-postfix)
main
:flash flash
:title title
:site-name site-name))
params-> (fn params-> [params]
(-> params
(select-keys [:id :status :ref :load :unload :goods :carrier])
(assoc-in [:owner :eori] eori)))]
(routes
(GET "/" {:keys [flash master-data ::store/store]}
(render "Orders"
(list-consignments (get-consignments store) master-data)
flash))
(GET "/consignment-new" {:keys [flash master-data ::store/store user-number]}
(render "Order aanmaken"
(edit-consignment
{:ref (next-consignment-ref store user-number)
:load {:date (w/format-date (Date.))}
:unload {:date (w/format-date (Date.))}
:status otm/status-draft}
master-data)
flash))
(POST "/consignment-new" {:keys [params]}
(let [consignment (-> params
(params->)
(assoc :id (str (UUID/randomUUID))))]
(-> "."
(redirect :see-other)
(assoc :flash {:success (str "Order " (:ref consignment) " aangemaakt")})
(assoc ::store/commands [[:put! :consignments consignment]]))))
(GET "/consignment-:id" {:keys [flash master-data ::store/store]
{:keys [id]} :params}
(when-let [consignment (get-consignment store id)]
(render (str "Order " (:ref consignment) " aanpassen")
(edit-consignment consignment master-data)
flash)))
(POST "/consignment-:id" {:keys [params]}
(let [consignment (params-> params)]
(-> "."
(redirect :see-other)
(assoc :flash {:success (str "Order " (:ref consignment) " aangepast")})
(assoc ::store/commands [[:put! :consignments consignment]]))))
(DELETE "/consignment-:id" {:keys [::store/store]
{:keys [id]} :params}
(when-let [consignment (get-consignment store id)]
(-> "deleted"
(redirect :see-other)
(assoc :flash {:success (str "Order " (:ref consignment) " verwijderd")})
(assoc ::store/commands [[:delete! :consignments id]]))))
(GET "/deleted" {:keys [flash]}
(render "Order verwijderd"
(deleted-consignment flash)
flash))
(GET "/publish-:id" {:keys [flash master-data ::store/store]
{:keys [id]} :params}
(when-let [consignment (get-consignment store id)]
(render (str "Order " (:ref consignment) " naar locatie en vervoerder sturen")
(publish-consignment consignment master-data)
flash)))
(POST "/publish-:id" {:keys [master-data ::store/store]
{:keys [id]} :params}
(when-let [consignment (get-consignment store id)]
(let [consignment (assoc consignment :status otm/status-requested)
transport-order (otm/consignment->transport-order consignment)
trip (otm/consignment->trip consignment)]
(-> (str "published-" id)
(redirect :see-other)
(assoc :flash {:success (str "Order " (:ref consignment) " verstuurd")
:explanation [["Stuur OTM Transportopdracht naar WMS van DC"
{:otm-object (otm/->transport-order transport-order master-data)}]
["Stuur OTM Trip naar TMS van Vervoerder"
{:otm-object (otm/->trip trip master-data)}]]})
(assoc ::store/commands [[:put! :consignments consignment]
[:publish! ;; to warehouse WMS
:transport-orders
(-> consignment :load :location-eori)
transport-order]
[:publish! ;; to carrier TMS
:trips
(-> consignment :carrier :eori)
trip]])))))
(GET "/published-:id" {:keys [flash master-data ::store/store]
{:keys [id]} :params}
(when-let [consignment (get-consignment store id)]
(render (str "Order "
(:ref consignment)
" verstuurd")
(published-consignment consignment master-data flash)
flash))))))
|
#一、封装数据属性:明确的区分内外,控制外部对隐藏的属性的操作行为
class People:
def __init__(self,name,age):
self.__name=name
self.__age=age
def tell_info(self):
print("Name:<%s> Age:<%s>" %(self.__name,self.__age))
def set_info(self,name,age):
if not isinstance(name,str):
print("名字必须是字符串类型")
return
if not isinstance(age,int):
print("年龄必须是数字类型")
return
self.__name=name
self.__age=age
p=People('egon',18)
p.set_info('fdas',19)
p.tell_info()
#二、隔离复杂度
|
package com.example.bundletest;
import android.app.Activity;
import android.content.Intent;
import android.net.MailTo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button commit = (Button)findViewById(R.id.commit);
commit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText name=(EditText)findViewById(R.id.name);
EditText passwd=(EditText)findViewById(R.id.passwd);
RadioButton male = (RadioButton)findViewById(R.id.male);
//RadioButton female = (RadioButton)findViewById(R.id.female);
String gender = male.isChecked()?"男":"女";
Person p = new Person(name.getText().toString(), passwd.getText().toString(), gender);
Bundle data = new Bundle();
data.putSerializable("person", p);
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
intent.putExtras(data);
startActivity(intent);
}
});
}
}
|
"""Module for defining agents that interact with LLMs for conversational and UI responses."""
from typing import Callable, List
import traceback
from langchain.schema import StrOutputParser
from langchain.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate, PromptTemplate
from langchain.output_parsers import PydanticOutputParser
from langchain_core.messages import HumanMessage, AIMessage
from pydantic import ValidationError
from llm_utils.pydantic_models import Output, QuestionAnswer, PropertyRating
from llm_utils.config_loader import load_few_shot_examples, load_config
from llm_utils.stream_handler import DebugHandler
class Agent:
"""Base class for agents interacting with LLMs."""
def __init__(self, model):
self.model = model
self.config = load_config()
self.example_prompt = ChatPromptTemplate.from_messages(
[
("human", "{input}"),
("ai", "{output}"),
]
)
def update_model(self, model):
"""Updates the agent's model."""
self.model = model
def get_model(self):
"""Returns the agent's model."""
return self.model
class ConversationalAgent(Agent):
"""Agent for handling conversations."""
def __init__(self, model):
super().__init__(model)
self.memory = []
self.system_prompt = self.config["conversational_prompt"]
def __call__(self, persona: str, cars: str, stream_handler: Callable) -> str:
prompt = PromptTemplate(
template="{system_prompt}\n{cars}\n{memory}",
input_variables=["persona", "cars"],
partial_variables={"system_prompt": self.system_prompt, "memory": '\n'.join([str(msg) for msg in self.memory])},
)
chain = (
prompt
| self.model
| StrOutputParser()
)
config = {"callbacks": [stream_handler]}
response = chain.invoke(input={"persona": persona, "cars": cars}, config=config)
self.memory.append(AIMessage(role="assistant", content=response))
return response
class QuestioningAgent(Agent):
"""Agent for generating responses based on a list of properties."""
def __init__(self, model):
super().__init__(model)
self.system_prompt = self.config["questioning_prompt"]
def __call__(self, properties: List[str], persona: str) -> str:
properties = ", ".join(properties)
parser = PydanticOutputParser(pydantic_object=QuestionAnswer)
prompt = PromptTemplate(
template="{system_prompt}\n{persona}\n{format_instructions}\nThe Properties you need to create a question for: {properties}",
input_variables=["properties", "persona"],
partial_variables={"system_prompt": self.system_prompt,
"format_instructions": parser.get_format_instructions()},
)
chain = (
prompt
| self.model
| parser
)
handler = DebugHandler()
config = {"callbacks": [handler]}
retries = 3
for attempt in range(retries):
try:
validated_data = chain.invoke(
input={"properties": properties, "persona": persona}, config=config)
return validated_data.dict()
except ValidationError as e:
print(f"Validation error on attempt {attempt+1}: {e}")
if attempt == retries - 1:
return None
print("Retrying...")
except Exception as e:
print(f"Unexpected error: {traceback.format_exc()} - {e}")
return None
class PropertyMatchingAgent(Agent):
"""Agent for generating responses based on a question and user's answer."""
def __init__(self, model):
super().__init__(model)
self.system_prompt = self.config["property_matching_prompt"]
def __call__(self, question: str, user_answer: str, properties: List[str]) -> PropertyRating:
properties = ", ".join(properties)
parser = PydanticOutputParser(pydantic_object=PropertyRating)
prompt = PromptTemplate(
template="{system_prompt}\nQuestion: {question}\nUser Answer: {user_answer}\nProperties: {properties}\n{format_instructions}",
input_variables=["question", "user_answer"],
partial_variables={"system_prompt": self.system_prompt,
"format_instructions": parser.get_format_instructions(),
"properties": properties
},
)
chain = (
prompt
| self.model
| parser
)
handler = DebugHandler()
config = {"callbacks": [handler]}
retries = 3 # Number of retries
for attempt in range(retries):
try:
validated_data = chain.invoke(
input={"question": question, "user_answer": user_answer}, config=config)
return validated_data.dict()
except ValidationError as e:
print(f"Validation error on attempt {attempt+1}: {e}")
if attempt == retries - 1:
return None
print("Retrying...")
except Exception as e:
print(f"Unexpected error: {traceback.format_exc()} - {e}")
return None
class UIAgent(Agent):
"""Agent for generating UI responses based on model outputs."""
def __init__(self, model):
super().__init__(model)
self.system_prompt = self.config["ui_prompt"]
def __call__(self, message) -> str:
parser = PydanticOutputParser(pydantic_object=Output)
prompt = PromptTemplate(
template="{system_prompt}\n{format_instructions}\n{message}",
input_variables=["message"],
partial_variables={"system_prompt": self.system_prompt,
"format_instructions": parser.get_format_instructions()},
)
chain = (
prompt
| self.model
| parser
)
handler = DebugHandler()
config = {"callbacks": [handler]}
retries = 3 # Number of retries
for attempt in range(retries):
try:
validated_data = chain.invoke(
input={"message": message}, config=config)
return validated_data.dict()
except ValidationError as e:
print(f"Validation error on attempt {attempt+1}: {e}")
if attempt == retries - 1:
return None
print("Retrying...")
except Exception as e:
print(f"Unexpected error: {traceback.format_exc()} - {e}")
return None
|
import { createSlice } from '@reduxjs/toolkit'
import { RootState } from './store'
export type Country = {
_id: number;
name: string;
capital: string;
nativeName: string;
area: string;
population: number;
alpha2Code: string;
alpha3Code: string;
location: { latitude: number; longitude: number; }
borders: { name: string; location: { latitude: number; longitude: number; } }[]
distanceToOtherCountries: { countryName: string; distanceInKm: number; }[]
topLevelDomains: { name: string; }[]
subregion: { name: string; }
}
const INITIAL_STATE: Country = {
_id: 0,
name: "",
capital: "",
nativeName: "",
area: "",
population: 0,
alpha2Code: "",
alpha3Code: "",
location: { latitude: 0, longitude: 0 },
borders: [],
distanceToOtherCountries: [],
topLevelDomains: [{ name: "" }],
subregion: { name: '' }
}
export const slice = createSlice({
name: 'country',
initialState: INITIAL_STATE,
reducers: {
setCountry(state, { payload }) {
return { ...state, ...payload }
},
resetCountry() {
return { ...INITIAL_STATE }
},
}
})
export const { setCountry, resetCountry } = slice.actions
export const countrySelector = (state: RootState) => state.country
export default slice.reducer
|
<template>
<!-- старый пароль -->
<form class="form_password" v-if="getModalSave" @submit.prevent="save_new_password">
<div class="wrapper_form_register_input">
<div class="input-errors" v-for="(error, index) of v$.old_password.$errors" :key="index">
<div class="error-msg" v-if="error.$message === 'Value is required'">
Введите пароль указанный при регистрации
</div>
</div>
<div class="wrapper_error_login" v-if="getErrorPassword">
<p class="error_password">{{ getErrorPassword }}</p>
</div>
<div class="wrapper_form_change_password">
<div class="wrapper_form_change_password_label">
<label class="change_password_label" for="old_password">Старый пароль:</label>
</div>
<div class="wrapper_form_change_password_input">
<input class="form_register_input" id="old_password" type="password" placeholder="Укажите Ваш старый пароль"
v-model="check_old_password" :class="{ invalid: (v$.old_password.$error) }">
</div>
</div>
</div>
<!-- новый пароль -->
<div class="wrapper_form_register_input">
<div class="input-errors" v-for="(error, index) of v$.new_password.$errors" :key="index">
<div class="error-msg" v-if="error.$message === 'This field should be at least 8 characters long'">
Пароль должен состоять минимум из 8 символов
</div>
</div>
<div class="wrapper_form_change_password">
<div class="wrapper_form_change_password_label">
<label class="change_password_label" for="old_password">Новый пароль:</label>
</div>
<div class="wrapper_form_change_password_input">
<input class="form_register_input" id="new_password" type="password" placeholder="Укажите новый пароль"
@change="setCheckNewPassword" v-model="check_new_password" :class="{ invalid: (v$.new_password.$error) }">
</div>
</div>
</div>
<!-- повторный новый пароль -->
<div class="wrapper_form_register_input">
<div class="input-errors">
<div class="error-msg" v-if="getDouble_new_password">Пароли не свопадают</div>
</div>
<div class="wrapper_form_change_password">
<div class="wrapper_form_change_password_label">
<label class="change_password_label" for="old_password">Повторите пароль:</label>
</div>
<div class="wrapper_form_change_password_input">
<input class="form_register_input" id="new_password_confirmation" type="password"
placeholder="Повторите новый пароль" @input="setCheckNewPassword" v-model="check_new_password_confirmation">
</div>
</div>
</div>
<div class="wrapper_save_password_btn">
<UIbtn class="save_password_btn" type="submit" :disabled="v$.$invalid">
Сохранить пароль
</UIbtn>
<UIbtn class="save_password_btn" @click.prevent="setCloseChangePassword">
Отменить
</UIbtn>
</div>
</form>
<div v-else class="wrapper_save_password">
<div>
<p class="save_password">Ваш был пароль изменен!</p>
</div>
<div>
<UIbtn class="btn_save_password" @click.prevent="setCloseChangePassword">OK</UIbtn>
</div>
</div>
</template>
<script>
import { useVuelidate } from "@vuelidate/core";
import { required, minLength, maxLength } from "@vuelidate/validators";
import { mapMutations, mapGetters, mapState, mapActions } from "vuex";
import UIbtn from "./UI/UIbtn.vue";
export default {
name: "ChangePassword",
components: { UIbtn },
setup() {
return { v$: useVuelidate() };
},
data() {
return {};
},
validations: {
old_password: { required },
new_password: { required, min: minLength(8), max: maxLength(30) },
new_password_confirmation: { required },
},
methods: {
...mapMutations({
setCloseChangePassword: "updatePasswordStore/setCloseChangePassword",
setOld_password: "updatePasswordStore/setOld_password",
setNew_password: "updatePasswordStore/setNew_password",
setNew_password_confirmation: "updatePasswordStore/setNew_password_confirmation",
setCheckNewPassword: "updatePasswordStore/setCheckNewPassword",
setErrorPassword: "updatePasswordStore/setErrorPassword",
setModalSave: "updatePasswordStore/setModalSave"
}),
...mapActions({ updatePasword: "updatePasswordStore/updatePasword" }),
//изменение старого пароля
save_new_password() {
if (!this.getDouble_new_password) { //если пароли совпадают
let user = {
old_password: this.getOld_password,
new_password: this.getNew_password
};
this.updatePasword(user)
.then(() => {
this.setModalSave(false);
})
.catch((err) => {
if (err.err) {
this.setErrorPassword(JSON.stringify(err.err).slice(1, -1));
}
this.setOld_password("");
this.setNew_password("");
this.setNew_password_confirmation("");
console.log("Изменение пароля завершилось с ошибкой: " + JSON.stringify(err));
});
}
},
},
computed: {
...mapGetters({
getDouble_new_password: "updatePasswordStore/getDouble_new_password",
getNew_password: "updatePasswordStore/getNew_password",
getNew_password_confirmation: "updatePasswordStore/getNew_password_confirmation",
getOld_password: "updatePasswordStore/getOld_password",
getErrorPassword: "updatePasswordStore/getErrorPassword",
getModalSave: "updatePasswordStore/getModalSave"
}),
...mapState({
old_password: (state) => state.updatePasswordStore.old_password,
new_password: (state) => state.updatePasswordStore.new_password,
new_password_confirmation: (state) => state.updatePasswordStore.new_password_confirmation,
}),
check_old_password: {
get() {
return this.getOld_password;
},
set(value) {
this.setOld_password(value);
this.v$.old_password.$touch();
}
},
check_new_password: {
get() {
return this.getNew_password;
},
set(value) {
this.setNew_password(value);
this.v$.new_password.$touch();
}
},
check_new_password_confirmation: {
get() {
return this.getNew_password_confirmation;
},
set(value) {
this.setNew_password_confirmation(value);
this.v$.new_password_confirmation.$touch();
}
},
},
}
</script>
<style scoped>
.form_password {
display: flex;
flex-direction: column;
display: flex;
flex-direction: column;
align-items: center;
margin: 10px;
}
.wrapper_form_register_input {
display: flex;
flex-direction: column;
margin-top: 10px;
}
.wrapper_form_change_password {
display: flex;
align-items: center;
}
.wrapper_form_change_password_label {
margin-right: 5px;
width: 140px;
}
.change_password_label {
font-size: 13.5px;
font-family: Russo One, fantasy, sans-serif;
}
.wrapper_form_change_password_input {
width: 200px;
}
.form_register_input {
height: 30px;
width: 100%;
}
.error-msg {
margin-left: 5px;
color: red;
font-size: 14px;
}
.wrapper_save_password_btn {
display: flex;
justify-content: center;
}
.save_password_btn {
width: 150px;
margin: 10px;
display: flex;
justify-content: center;
}
.error_password {
color: red;
margin: 5px;
font-size: 14px;
}
.wrapper_save_password {
display: flex;
flex-direction: column;
align-items: center;
margin: 20px;
}
.save_password {
font-size: 18px;
margin: 10px;
font-family: Russo One, fantasy, sans-serif;
}
.btn_save_password {
width: 100px;
height: 35px;
margin-top: 10px;
}
</style>
|
{% extends 'base.html' %}
{% block content %}
<section class="container">
<div class="content-wrap">
<div class="content">
<header class="article-header">
<h1 class="article-title"><a href="#" title="{{ article.title }}" >{{ article.title }}</a></h1>
<div class="article-meta"> <span class="item article-meta-time">
<time class="time" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="发表时间:{{ article.created_time|date:'Y-m-d'}}"><i class="glyphicon glyphicon-time"></i>{{ article.created_time|date:'Y-m-d'}}</time>
</span> <span class="item article-meta-source" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="{{ article.user.username }}"><i class="glyphicon glyphicon-globe"></i>{{ article.user.username }}</span> <span class="item article-meta-category" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="{{ article.category }}"><i class="glyphicon glyphicon-list"></i> <a href="#" title="{{ article.category }}" >{{ article.category }}</a></span> <span class="item article-meta-views" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="浏览量:{{ article.vnum }}"><i class="glyphicon glyphicon-eye-open"></i>{{ article.vnum }}</span> <span class="item article-meta-comment" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="评论量"><i class="glyphicon glyphicon-comment"></i> {{ article.comment_set.count }}</span> </div>
</header>
<article class="article-content">
{{ article.content|safe }}
<div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a><a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a><a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a></div>
<script> window._bd_share_config = { "common": { "bdSnsKey": {}, "bdText": "", "bdMini": "2", "bdMiniList": false, "bdPic": "", "bdStyle": "1", "bdSize": "32" }, "share": {} }; with (document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=0.js?cdnversion=' + ~(-new Date() / 36e5)];</script>
</article>
<div class="article-tags">标签:
{% for tag in article.tag.all %}
<a href="{% url 'boke:list' %}?tid={{ tag.id }}" rel="tag" >{{ tag.name }}</a>
{% endfor %}
</div>
<div class="relates">
<div class="title">
<h3>相关推荐</h3>
</div>
<ul>
{% for art in recommend_arts %}
{% if art.id != article.id %}
<li><a href="{% url 'boke:detail' id=art.id %}" title="" >{{ art.title }}</a></li>
{% endif %}
{% endfor %}
</ul>
</div>
<div class="title" id="comment">
<h3>评论</h3>
</div>
<div id="respond">
<form id="comment-form" name="" action="{% url 'boke:comment' %}" method="POST">
{% csrf_token %}
<div class="comment">
<div class="comment-box">
<textarea placeholder="您的评论或留言(必填)" name="content" id="comment-textarea" cols="100%" rows="3" tabindex="3"></textarea>
<div class="comment-ctrl">
<input type="text" name="id" value="{{ article.id }}" style="visibility: hidden ">
<div class="comment-prompt" style="display: none;"> <i class="fa fa-spin fa-circle-o-notch"></i> <span class="comment-prompt-text">评论正在提交中...请稍后</span> </div>
<div class="comment-success" style="display: none;"> <i class="fa fa-check"></i> <span class="comment-prompt-text">评论提交成功...</span> </div>
<button type="submit" name="comment-submit" id="comment-submit" tabindex="4">评论</button>
</div>
</div>
</div>
</form>
</div>
<div id="postcomments">
<ol id="comment_list" class="commentlist">
{% for comment in comments %}
<li class="comment-content"><span class="comment-f">{{ forloop.revcounter }}</span><div class="comment-main"><p><a class="address" href="#" rel="nofollow" target="_blank">{{ comment.user }}</a><span class="time">( {{ comment.created_time|date:'Y-m-d H:m:s'}})</span><br>{{ comment.content }}</p></div></li></ol>
{% endfor %}
</div>
</div>
</div>
<aside class="sidebar">
<div class="fixed">
<div class="widget widget-tabs">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#notice" aria-controls="notice" role="tab" data-toggle="tab" draggable="false">统计信息</a></li>
<li role="presentation"><a href="#contact" aria-controls="contact" role="tab" data-toggle="tab" draggable="false">联系站长</a></li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane contact active" id="notice">
<h2>日志总数:
888篇
</h2>
<h2>网站运行:
<span id="sitetime">88天 </span></h2>
</div>
<div role="tabpanel" class="tab-pane contact" id="contact">
<h2>QQ:
<a href="" target="_blank" rel="nofollow" data-toggle="tooltip" data-placement="bottom" title="" draggable="false" data-original-title="QQ:577211782">577211782</a>
</h2>
<h2>Email:
<a href="mailto:577211782@qq.com" target="_blank" data-toggle="tooltip" rel="nofollow" data-placement="bottom" title="" draggable="false" data-original-title="Email:577211782@qq.com">577211782@qq.com</a></h2>
</div>
</div>
</div>
<div class="widget widget_search">
<form class="navbar-form" action="{% url 'boke:list' %}" method="get">
<div class="input-group">
<input type="text" name="kw" class="form-control" size="35" placeholder="请输入关键字" maxlength="15" autocomplete="off">
<span class="input-group-btn">
<button class="btn btn-default btn-search" type="submit">搜索</button>
</span> </div>
</form>
</div>
</div>
<div class="widget widget_hot">
<h3>最新评论文章</h3>
<ul>
{% for art in newcoms_art %}
<li><a title="{{ art.title }}" href="{% url 'boke:detail' id=art.id %}" ><span class="thumbnail">
<img class="thumb" data-original="{{ MEDIA_URL }}{{ art.cover }}" src="{{ MEDIA_URL }}{{ art.cover }}" alt="{{ art.title }}" style="display: block;">
</span><span class="text">{{ art.title }}</span><span class="muted"><i class="glyphicon glyphicon-time"></i>
{{ article.created_time|date:'Y-m-d'}}
</span><span class="muted"><i class="glyphicon glyphicon-eye-open"></i>{{ art.vnum }}</span></a></li>
{% endfor %}
</ul>
</div>
<div class="widget widget_sentence">
<a href="#" target="_blank" rel="nofollow" title="MZ-NetBlog主题" >
<img style="width: 100%" src="images/ad.jpg" alt="MZ-NetBlog主题" ></a>
</div>
<div class="widget widget_sentence">
<a href="#" target="_blank" rel="nofollow" title="专业网站建设" >
<img style="width: 100%" src="images/201610241224221511.jpg" alt="专业网站建设" ></a>
</div>
</aside>
</section>
{% endblock %}
|
import { FaCartPlus } from "react-icons/fa";
import { CgProfile } from "react-icons/cg";
import { Link, NavLink } from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "../../provider/AuthProvider";
import useCart from "../../Hooks/useCart";
const Navbar = () => {
const { user, LogOut } = useContext(AuthContext);
const [cart] = useCart();
const hendleLogout = () => {
return LogOut();
}
const submenu = (
<>
<li><Link to='/'>HOME</Link></li>
<li><a href="#">CONTACT US</a></li>
<li><a href="#">DASHBOARD</a></li>
<li><Link to='/menu'>OUR MENU</Link> </li>
<li><Link to='/our_shop/salad'>OUR SHOP</Link></li>
<li><Link to='/secret'>secret</Link></li>
</>
);
return (
<div className=" navbar fixed z-10 max-w-screen-lg mx-auto opacity-55 bg-black text-white">
<div className="navbar max-w-screen-lg mx-auto py-6">
<div className="navbar-start">
<div className="dropdown">
<button tabIndex={0} className="btn btn-ghost lg:hidden">
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h8m-8 6h16" />
</svg>
</button>
<ul tabIndex={0} className="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 rounded-box w-52 text-black">
{submenu}
</ul>
</div>
<a className="btn btn-ghost normal-case text-xl" href="#">BISTRO BOSS</a>
</div>
<div className="navbar-center hidden lg:flex">
<ul className="menu menu-horizontal font-extrabold font-serif px-1">
{submenu}
</ul>
</div>
<div className="navbar-end hidden lg:flex items-center space-x-4">
<NavLink to='/dashboard/my-cart'>
<button className="flex items-center gap-4">
<FaCartPlus size={24} />
{user ? <div className="badge badge-secondary">+{cart.length}</div> : <div className="badge badge-secondary">0</div>}
</button>
</NavLink>
{
user ? < button onClick={hendleLogout} > <a className="btn btn-ghost">SIGN OUT</a></button> :
<Link to='/login'> <a className="btn btn-ghost">SIGN IN</a></Link>
}
{
user ? <img src={user?.photoURL} alt="" className="w-10 h-10 rounded-full" />
: <CgProfile size={24} />
}
</div>
</div>
</div>
);
};
export default Navbar;
|
<?php
if ( ! function_exists( 'mildhill_core_add_page_social_share_options' ) ) {
/**
* Function that add general options for this module
*/
function mildhill_core_add_page_social_share_options() {
$qode_framework = qode_framework_get_framework_root();
$page = $qode_framework->add_options_page(
array(
'scope' => MILDHILL_CORE_OPTIONS_NAME,
'type' => 'admin',
'slug' => 'social-share',
'icon' => 'fa fa-book',
'title' => esc_html__( 'Social Share', 'mildhill-core' ),
'description' => esc_html__( 'Global settings related to social networks', 'mildhill-core' )
)
);
if ( $page ) {
$social_networks = mildhill_core_social_networks_list();
foreach ( $social_networks as $network => $params ) {
$page->add_field_element(
array(
'field_type' => 'yesno',
'name' => 'qodef_enable_share_' . $network,
'title' => sprintf( esc_html__( 'Enable %s Share', 'mildhill-core' ), $params['label'] ),
'default_value' => 'yes'
)
);
if ( $network == 'twitter' ) {
$page->add_field_element(
array(
'field_type' => 'text',
'name' => 'qodef_twitter_via',
'title' => esc_html__( 'Twitter Via Text', 'mildhill-core' ),
'default_value' => esc_html__( '@QodeInteractive', 'mildhill-core' ),
'dependency' => array(
'show' => array(
'qodef_enable_share_twitter' => array(
'values' => 'yes',
'default_value' => 'yes'
)
)
)
)
);
}
}
// Hook to include additional options after module options
do_action( 'mildhill_core_action_after_social_share_options_map', $page );
}
}
add_action( 'mildhill_core_action_default_options_init', 'mildhill_core_add_page_social_share_options', mildhill_core_get_admin_options_map_position( 'social-share' ) );
}
|
export interface ingredientType {
_id: string;
name: string;
type: string;
proteins: number;
fat: number;
carbohydrates: number;
calories: number;
price: number;
image: string;
image_mobile: string;
image_large: string;
__v: number;
uuid: string;
position?: 'top' | 'bottom' | undefined;
locker?: boolean;
}
export interface ingredientTypeForTesting {
_id: string;
name: string;
type: string;
proteins: number;
fat: number;
carbohydrates: number;
calories: number;
price: number;
image: string;
image_mobile: string;
image_large: string;
__v: number;
uuid?: string;
position?: 'top' | 'bottom' | undefined;
locker?: boolean;
}
export interface orderType {
_id: string;
name: string;
type: string;
price: number;
image: string;
image_mobile: string;
image_large: string;
position: string;
locker: boolean;
}
export interface ConstructorState {
burderConstructor: {
bun: ingredientType[];
ingredients: ingredientType[];
};
totalPrice: Number;
}
export interface OrderArray {
success?: boolean;
orders: Order[];
total: number;
totalToday: number;
}
export interface Order {
ingredients: string[];
_id: string;
status: string;
number: number;
name?: string;
createdAt: string;
updatedAt: string;
}
|
import React from 'react'
import { Box, CardContent, CardMedia, Typography, Card } from '@mui/material'
import { CheckCircle } from '@mui/icons-material'
import { demoProfilePicture, demoChannelTitle } from '../utils/constants'
const DetailedChannelCard = ({ channelDetail }) => {
if (!channelDetail.avatar) return 'Loading...'
return (
<Box
sx={{
boxShadow: 'none',
borderRadius: '20px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '180px',
margin: 'auto',
mt: '20px',
px: '4px'
}}
>
<Card
sx={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', background: 'transparent' }}
>
<CardMedia
image={channelDetail?.avatar[2]?.url || demoProfilePicture}
alt={channelDetail?.title}
sx={{ border: '1px solid #c9c9c9', borderRadius: '50%', height: { xs: '80px', sm: '120px', md: '180px' }, width: { xs: '80px', sm: '120px', md: '180px' }, mb: 2 }}
component='img'
/>
<CardContent sx={{ display: 'flex', flexDirection: 'column' }}>
<Typography variant='h6' fontWeight='bold' color='white'>
{channelDetail?.title || demoChannelTitle}
<CheckCircle sx={{ fontSize: 14, color: "gray", ml: '5px' }} />
</Typography>
<Typography variant='subtitle1' color='#a6a6a6' >
{`${channelDetail?.username} • ${channelDetail?.stats?.subscribersText} • ${channelDetail?.stats?.videosText}`}
</Typography>
</CardContent>
</Card>
</Box>
)
}
export default DetailedChannelCard
|
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:esri="http://www.esri.com/2008/ags"
initialize="application_initializeHandler(event)"
pageTitle="ConvexHull example">
<!--
This sample shows how to take advantage of the convexHull() method
on a GeometryService.
-->
<fx:Script>
<![CDATA[
import com.esri.ags.Graphic;
import com.esri.ags.SpatialReference;
import com.esri.ags.events.DrawEvent;
import com.esri.ags.events.GeometryServiceEvent;
import com.esri.ags.geometry.Geometry;
import com.esri.ags.geometry.MapPoint;
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
protected function application_initializeHandler(event:FlexEvent):void
{
drawTool.activate(DrawTool.EXTENT);
}
private function drawEndHandler(event:DrawEvent):void
{
convexHullResultGraphicsLayer.clear();
var geometries:Array = [];
var extent:Extent = event.graphic.geometry as Extent;
var graphics:ArrayCollection = ArrayCollection(myFeatureLayer.graphicProvider);
for each (var graphic:Graphic in graphics)
{
//if point is within drawn extent, highlight it
if (extent.contains(MapPoint(graphic.geometry)))
{
graphic.symbol = highlightedSymbol;
geometries.push(MapPoint(graphic.geometry));
}
//else if point was previously highlighted, reset its symbology
else if (graphic.symbol == highlightedSymbol)
{
graphic.symbol = defaultSymbol;
}
}
// find convex hull for the selected points
geometryService.convexHull(geometries, new SpatialReference(4326));
}
private function convexHullCompleteHandler(event:GeometryServiceEvent):void
{
var graphic:Graphic = new Graphic(Geometry(event.result));
switch (Geometry(event.result).type)
{
case Geometry.MAPPOINT:
{
graphic.symbol = convexHullPoint;
break;
}
case Geometry.POLYLINE:
{
graphic.symbol = convexHullPolyline;
break;
}
case Geometry.POLYGON:
{
graphic.symbol = convexHullPolygon;
break;
}
}
convexHullResultGraphicsLayer.add(graphic);
}
]]>
</fx:Script>
<fx:Declarations>
<esri:SimpleMarkerSymbol id="defaultSymbol"
alpha="0.5"
color="0x0000FF"
size="12">
<esri:SimpleLineSymbol/>
</esri:SimpleMarkerSymbol>
<esri:SimpleMarkerSymbol id="highlightedSymbol"
color="0xFF0000"
size="12">
<esri:SimpleLineSymbol/>
</esri:SimpleMarkerSymbol>
<esri:SimpleFillSymbol id="convexHullPolygon"
alpha="0.5"
style="solid">
<esri:SimpleLineSymbol width="2" color="0xFFFFFF"/>
</esri:SimpleFillSymbol>
<esri:SimpleLineSymbol id="convexHullPolyline"
width="3"
color="0xFFFFFF"/>
<esri:SimpleMarkerSymbol id="convexHullPoint" color="0xFFFFFF"/>
<esri:DrawTool id="drawTool"
drawEnd="drawEndHandler(event)"
fillSymbol="{convexHullPolygon}"
map="{myMap}"/>
<esri:GeometryService id="geometryService"
convexHullComplete="convexHullCompleteHandler(event)"
url="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"/>
</fx:Declarations>
<s:layout>
<s:VerticalLayout paddingTop="7"/>
</s:layout>
<s:Label fontSize="18"
fontWeight="bold"
text="Calculate Convex Hull"/>
<s:Label width="100%"
fontSize="13"
text="Draw a rectangle around a group of points to calculate the minimum bounding polygon ('convex hull') of the selected points."/>
<esri:Map id="myMap">
<esri:extent>
<esri:Extent xmin="-13661000" ymin="4452000" xmax="-13561000" ymax="4601000">
<esri:SpatialReference wkid="102100"/>
</esri:Extent>
</esri:extent>
<esri:ArcGISTiledMapServiceLayer url="http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"/>
<esri:FeatureLayer id="myFeatureLayer"
outFields="[CITY_NAME]"
symbol="{defaultSymbol}"
url="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/0"/>
<esri:GraphicsLayer id="convexHullResultGraphicsLayer"/>
</esri:Map>
</s:Application>
|
const Usuario = require('../models/Usuarios');
exports.crearUsuario = async(req, res) => {
try {
let usuario = new Usuario(req.body)
await usuario.save()
res.json(usuario)
} catch (error) {
console.log(error)
res.status(500).json({ msg: 'Ups, algo paso, comuníquese con el administrador' })
}
}
exports.buscarUsuarios = async(req, res) => {
try {
const usuarios = await Usuario.find()
res.json(usuarios)
} catch (error) {
console.log(error)
res.status(500).json({ msg: 'Ups, algo paso, comuníquese con el administrador' })
}
}
exports.buscarUnUsuario = async(req, res) => {
try {
const usuario = await Usuario.findById(req.params.id)
if (!usuario) {
res.status(404).json({ mensaje: 'El usuario no existe' })
return
}
res.json(usuario)
} catch (error) {
console.log(error)
res.status(500).json({ msg: 'Ups, algo paso, comuníquese con el administrador' })
}
}
exports.buscarUnUsuarioPorNombre = async(req, res) => {
try {
const usuario = await Usuario.find({ nombre: req.params.nombre })
if (!usuario) {
res.status(404).json({ mensaje: 'El usuario no existe' })
return
}
res.json(usuario)
} catch (error) {
console.log(error)
res.status(500).json({ msg: 'Ups, algo paso, comuníquese con el administrador' })
}
}
exports.actualizarUsuario = async(req, res) => {
try {
const { nombre, apellido, correo, password, direccion, ciudad } = req.body
let dataUsuario = await Usuario.findById(req.params.id)
if (!dataUsuario) {
res.status(404).json({ mensaje: 'El usuario no existe' })
return
}
dataUsuario.nombre = nombre
dataUsuario.apellido = apellido
dataUsuario.correo = correo
dataUsuario.password = password
dataUsuario.direccion = direccion
dataUsuario.ciudad = ciudad
dataUsuario = await Usuario.findOneAndUpdate({ _id: req.params.id }, dataUsuario)
res.json(dataUsuario)
} catch (error) {
console.log(error)
res.status(500).json({ msg: 'Ups, algo paso, comuníquese con el administrador' })
}
}
exports.eliminarUsuario = async(req, res) => {
try {
const usuario = await Usuario.findById(req.params.id)
if (!usuario) {
res.status(404).json({ mensaje: 'El usuario no existe' })
return
}
await Usuario.findOneAndRemove({ _id: req.params.id })
res.status(200).json({ mensaje: 'El usuario fue eliminado' })
} catch (error) {
console.log(error)
res.status(500).json({ msg: 'Ups, algo paso, comuníquese con el administrador' })
}
}
|
package ru.anime.okami.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import java.util.Set;
@Entity
@Table(name = "roles")
@Data
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Role implements GrantedAuthority {
@Id
private int id;
@Column(unique = true)
private String name;
@Override
public String getAuthority() {
return name;
}
@ManyToMany(mappedBy = "roles")
private Set<User> users;
public Role(String name) {
this.name = name;
}
}
|
import { useEffect, useState } from "react";
import "./Weather.scss";
import axios from "axios";
import { MdOutlineLocationOn } from "react-icons/md";
import { WiSunrise, WiSunset } from "react-icons/wi";
const Weather = () => {
const [data, setData] = useState<Data | null>(null);
const [location, setLocation] = useState("Pune");
const url = `https://api.openweathermap.org/data/2.5/weather?q=${location}&units=metric&appid=146f21d5dd7e67d75fc1ffbbcbe370ba`;
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(url);
setData(response.data);
} catch (error) {
console.error(error);
}
};
fetchData();
}, [location]);
const getFormattedTime = (timestamp: number) => {
const date = new Date(timestamp * 1000);
return date.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
});
};
const sunriseTime = data ? getFormattedTime(data.sys.sunrise) : null;
const sunsetTime = data ? getFormattedTime(data.sys.sunset) : null;
type Data = {
name: string;
weather: [{ main: string }];
main: {
temp: number;
pressure: number;
humidity: number;
};
sys: {
sunrise: number;
sunset: number;
country: string;
};
};
return (
<div className="weather">
{data?.name && (
<div className="weather-data">
<h1 className="temp">{Math.round(data.main.temp)}°C</h1>
<h3 className="main">{data.weather[0].main}</h3>
<br />
<MdOutlineLocationOn />
<span className="location">
{data.name}, {data.sys ? data.sys.country : null}
</span>
<br />
{/* <span className="">
Pressure: {data.main.pressure}
<br />
Humidity: {data.main.humidity}
<br />
</span> */}
<WiSunrise size={18} /> {sunriseTime}
<span className="sun">
<WiSunset size={18} /> {sunsetTime}
</span>
</div>
)}
</div>
);
};
export default Weather;
|
class Solution {
public:
string shortestCommonSupersequence(string str1, string str2) {
int n=str1.size();
int m=str2.size();
/**************************************************************************
***********************************LCS Code********************************
**************************************************************************/
//0 means -1
// n/m means n-1/m-1
vector<vector<int>> dp(n+1,vector<int>(m+1,-1));
for(int i=0;i<=n;i++) {
dp[i][0]=0;
}
for(int i=0;i<=m;i++) {
dp[0][i]=0;
}
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
if(str1[i-1]==str2[j-1]) {
dp[i][j]=1+dp[i-1][j-1];
} else {
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
}
/**************************************************************************
***************************************************************************
**************************************************************************/
int i=str1.size();
int j=str2.size();
string ans="";
while(i>0 && j>0) {
if(str1[i-1]==str2[j-1]) {
ans.push_back(str1[i-1]);
i--;
j--;
} else if(dp[i-1][j]>dp[i][j-1]) {
ans.push_back(str1[i-1]);
i--;
} else {
ans.push_back(str2[j-1]);
j--;
}
}
while(j>0) {
ans.push_back(str2[j-1]);
j--;
}
while(i>0) {
ans.push_back(str1[i-1]);
i--;
}
reverse(ans.begin(),ans.end());
return ans;
}
};
|
# Sha256
```solidity
// (1)
sha256(TvmSlice slice) returns (uint256)
// (2)
sha256(bytes b) returns (uint256)
// (3)
sha256(string str) returns (uint256)
```
1. Computes the SHA-256 hash. If the bit-length of `slice` is not divisible by eight, throws a cell underflow [exception](../../troubleshooting/tvm-exception-codes.md). References of `slice` are not used to compute the hash. Only data bits located in the root cell of `slice` are used.
2. Computes the SHA-256 hash only for the first 127 bytes. If `bytes.length > 127` then `b[128], b[129], b[130] ...` elements are ignored.
3. Same as for `bytes`: only the first 127 bytes are taken into account.
See also [tvm.hash()](hashing-and-cryptography.md#hash) to compute representation hash of the whole tree of cells.
|
import Foundation
import NetworkExtension
class VPNProfile: ObservableObject {
let manager: NEVPNManager
var connection: NEVPNConnection
@Published var status: NEVPNStatus
private var observer: Any?
init(_ manager: NEVPNManager) {
self.manager = manager
connection = manager.connection
status = manager.connection.status
}
deinit {
unregister()
}
func register() {
observer = NotificationCenter.default.addObserver(
forName: NSNotification.Name.NEVPNStatusDidChange,
object: manager.connection,
queue: .main
) { [weak self] notification in
guard let self else { return }
self.connection = notification.object as! NEVPNConnection
self.status = self.connection.status
}
}
private func unregister() {
if let observer {
NotificationCenter.default.removeObserver(observer)
}
}
func start() async throws {
if let configuration = manager.protocolConfiguration {
configuration.includeAllNetworks = SharedPreferences.includeAllNetworks
configuration.excludeLocalNetworks = SharedPreferences.excludeLocalNetworks
configuration.enforceRoutes = SharedPreferences.enforceRoutes
manager.protocolConfiguration = configuration
}
manager.isEnabled = true
try await manager.saveToPreferences()
try manager.connection.startVPNTunnel()
}
func stop() {
manager.connection.stopVPNTunnel()
}
static func load() async throws -> VPNProfile? {
let managers = try await NETunnelProviderManager.loadAllFromPreferences()
if managers.isEmpty {
return nil
}
let profile = VPNProfile(managers[0])
return profile
}
static func install() async throws -> VPNProfile {
let manager = NETunnelProviderManager()
manager.localizedDescription = "utun interface"
let tunnelProtocol = NETunnelProviderProtocol()
tunnelProtocol.providerBundleIdentifier = "\(FilePath.packageName).extension"
tunnelProtocol.serverAddress = "sing-box"
manager.protocolConfiguration = tunnelProtocol
manager.isEnabled = true
try await manager.saveToPreferences()
return VPNProfile(manager)
}
}
|
import { ObjectType, Field, InputType } from '@nestjs/graphql';
@ObjectType()
class AddressOutputDto {
@Field()
address1: string;
@Field()
address2: string;
@Field()
city_id: string;
@Field()
state_id: string;
@Field()
pin: number;
}
interface IAddress {
address1: string;
address2: string;
city_id: string;
state_id: string;
pin: number;
}
@ObjectType()
class SpouseDetailOutputDto {
@Field()
name: string;
@Field()
contact: number;
@Field()
dob: string;
@Field()
special_instruction: string;
@Field()
picture: string;
}
interface ISpouseDetail {
name: string;
contact: number;
dob: string;
special_instruction: string;
picture: string;
}
@ObjectType()
export class BuyerOutputDto {
@Field()
name: string;
@Field()
contact_no: number;
@Field(() => AddressOutputDto)
address: IAddress;
@Field()
referral: string;
@Field()
email: string;
@Field()
status: string;
@Field()
dealer: string;
@Field()
dob: string;
@Field()
doa: string;
@Field(() => SpouseDetailOutputDto)
spouse_details: ISpouseDetail;
}
|
import propTypes from 'prop-types';
import React from 'react';
import Header from '../component/Header';
import MusicCard from '../component/MusicCard';
import getMusics from '../services/musicsAPI';
import { addSong, removeSong, getFavoriteSongs } from '../services/favoriteSongsAPI';
import Loading from './Loading';
class Album extends React.Component {
constructor(props) {
super(props);
this.state = {
response: [],
artistName: '',
albumName: '',
isLoading: false,
};
}
componentDidMount() {
this.getMusicsResponse();
}
isFavoriteSong = async (id) => {
const favoriteSongs = await getFavoriteSongs();
const isFavorite = favoriteSongs.some((song) => song.trackId === +id);
return isFavorite;
}
verifyFavoriteSongs = () => {
// const { response } = this.state;
// response.forEach((song) => {
// console.log('entrou no foreach');
// this.isFavoriteSong(song.trackId)
// .then((data) => {
// if (data) {
// const songElement = document.getElementById(song.trackId);
// songElement.checked = true;
// }
// });
// });
}
getMusicsResponse = async () => {
const { match: { params: { id } } } = this.props;
this.setState({
response: await getMusics(id),
}, this.getInfosAlbum);
}
getInfosAlbum = () => {
const { response } = this.state;
this.setState({
artistName: response[0].artistName,
albumName: response[0].collectionName,
});
}
getMusicById = (id) => {
const { response } = this.state;
return response.find((music) => music.trackId === +id);
}
handleInputChange = async (event) => {
this.setState({ isLoading: true });
const musicId = event.target.id;
const isFavorite = await this.isFavoriteSong(musicId);
const music = this.getMusicById(musicId);
if (isFavorite) {
await removeSong(music);
} else {
await addSong(music);
}
this.setState({ isLoading: false });
}
render() {
const { response, artistName, albumName, isLoading } = this.state;
return (
<div data-testid="page-album">
<Header />
{ isLoading ? <Loading /> : (
<div>
<h2>Album</h2>
<h3 data-testid="artist-name">{ artistName }</h3>
<h3 data-testid="album-name">{ albumName }</h3>
{ response.map((obj) => {
if (response.indexOf(obj) === 0) return '';
return (
<div key={ obj.trackId }>
<MusicCard
amgArtistIdValue={ obj.amgArtistId }
trackNameValue={ obj.trackName }
previewUrlValue={ obj.previewUrl }
trackIdValue={ obj.trackId }
handleInputChange={ this.handleInputChange }
isFavorite={ this.isFavoriteSong }
/>
</div>
);
})}
</div>
)}
</div>
);
}
}
Album.propTypes = {
match: propTypes.objectOf(propTypes.object).isRequired,
params: propTypes.objectOf(propTypes.object).isRequired,
};
export default Album;
|
// Casper
const {
CasperServiceByJsonRPC,
DeployUtil,
Contracts,
} = require("casper-js-sdk");
const confirmDeploy = require("../utils/confirmDeploy");
const getDeployedHashes = require("../utils/getDeployedHashes");
const findHighestBidder = require("../utils/findHighestBidder");
// const client = new CasperServiceByJsonRPC("http://3.136.227.9:7777/rpc");
const client = new CasperServiceByJsonRPC(
"https://rpc.testnet.casperlabs.io/rpc"
);
const contract = new Contracts.Contract(client);
// Get the models
const db = require("../models");
const getBidPurseUref = require("../utils/getBidPurseUref");
const Auctions = db.auctions;
const Nfts = db.nfts;
const Bids = db.bids;
const Purses = db.purses;
// When an auction is initialized, this controller is
// called to update the off-chain server
async function startAuction(req, res) {
try {
const tokenId = req.body.tokenId;
const foundNft = await Nfts.findOne({ where: { tokenId } });
if (foundNft == null) {
return res.status(400).send("NFT not found");
}
if (foundNft.inAuction == true) {
return res.status(400).send("NFT already in another live auction");
}
const newAuction = {
tokenId,
nftId: req.body.nftId,
userId: req.body.userId,
deployerKey: req.body.deployerKey,
deployHash: req.body.deployHash,
startDate: req.body.startDate,
endDate: req.body.endDate,
minimumPrice: req.body.minimumPrice,
approved: false,
status: "pending",
};
const createdAuction = await Auctions.create(newAuction);
foundNft.auctionId = createdAuction.id;
foundNft.inAuction = true;
await foundNft.save();
return res.status(200).send(createdAuction);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred");
}
}
async function openAuction(req, res) {
try {
const auctionId = req.params.auctionId;
const foundAuction = await Auctions.findOne({ where: { id: auctionId } });
if (foundAuction == null) {
return res.status(404).send("Auction not found");
}
foundAuction.status = "open";
await foundAuction.save();
return res.status(200).send(`Auction ${auctionId} opened`);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred");
}
}
async function closeAuction(req, res) {
try {
const auctionId = req.params.auctionId;
const foundAuction = await Auctions.findOne({ where: { id: auctionId } });
if (foundAuction == null) {
return res.status(404).send("Auction not found");
}
const foundBids = await Bids.findAll({ where: { auctionId } });
const foundNft = await Nfts.findOne({
where: { tokenId: foundAuction.tokenId },
});
if (foundBids.length > 0) {
// Find highest bidder
const highestBidder = findHighestBidder(foundBids);
if (foundNft == null) {
return res.status(404).send("Auction has invalid NFT");
}
// Update auction NFT owner
foundNft.ownerKey = highestBidder.bidder;
}
foundNft.inAuction = false;
foundAuction.status = "close";
await foundNft.save();
await foundAuction.save();
return res.status(200).send(`Auction ${auctionId} closed`);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred");
}
}
async function updateAuctionHashes(req, res) {
try {
const deployHash = req.body.deployHash;
const packageHash = req.body.packageHash;
const contractHash = req.body.contractHash;
const auction = await Auctions.findOne({
where: { deployHash: deployHash },
});
if (!auction) {
return res.status(404).send("Auction not found");
}
auction.packageHash = packageHash;
auction.contractHash = contractHash;
const updatedAuction = await auction.save();
return res.status(200).send(updatedAuction);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred" + JSON.stringify(error));
}
}
async function addBidOnAuction(req, res) {
try {
const auctionId = req.body.auctionId;
const bid = req.body.bid;
const bidder = req.body.bidder;
const userId = req.body.userId;
// Check if bidder has already bidded
const foundBid = await Bids.findOne({ where: { auctionId, bidder } });
if (foundBid == null) {
const newBid = {
auctionId,
bid,
bidder,
userId,
};
const createdBid = await Bids.create(newBid);
return res.status(200).send("Bid added successfully");
} else {
foundBid.bid = bid;
await foundBid.save();
return res.status(200).send("Bid updated successfully");
}
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred");
}
}
async function saveBidPurseInfo(req, res) {
try {
// const uref = req.body.uref;
const name = req.body.name;
const deployHash = req.body.deployHash;
const deployerKey = req.body.deployerKey;
const userId = req.body.userId;
const amount = req.body.amount;
const newPurse = {
name,
deployHash,
deployerKey,
userId,
amount,
};
const createdPurse = await Purses.create(newPurse);
return res.status(200).send(createdPurse);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred");
}
}
async function updatePurseUref(req, res) {
try {
const purseId = req.params.purseId;
const foundPurse = await Purses.findOne({ where: { id: purseId } });
if (foundPurse == null) {
return res.status(404).send("Purse not found");
}
foundPurse.uref = req.body.uref;
const savedPurse = await foundPurse.save();
return res.status(200).send(savedPurse);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred");
}
}
async function deletePurse(req, res) {
try {
const purseId = req.params.purseId;
await Purses.destroy({ where: { id: purseId } });
return res.status(200).send("Bid purse deleted successfully.");
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred");
}
}
async function getAllAuctions(req, res) {
try {
const foundAuctions = await Auctions.findAll({
include: { all: true, nested: true },
});
return res.status(200).send(foundAuctions);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred.");
}
}
async function getAuctionByNft(req, res) {
const nftId = req.params.nftId;
try {
const foundAuctions = await Auctions.findOne({
where: {
nftId: nftId,
},
include: { all: true, nested: true },
});
return res.status(200).send(foundAuctions);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred.");
}
}
async function getPurseInfo(req, res) {
try {
const deployHash = req.params.deployHash;
const purseInfo = await getBidPurseUref(deployHash);
if (purseInfo == "") {
return res.status(400).send("No purse found");
}
return res.status(200).send(purseInfo);
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred.");
}
}
async function deleteAuction(req, res) {
try {
const auctionId = req.params.auctionId;
await Auctions.destroy({ where: { id: auctionId } });
const foundNft = await Nfts.findOne({ where: { auctionId } });
if (foundNft !== null) {
foundNft.inAuction = false;
await foundNft.save();
}
return res.status(200).send("Auction deleted successfully.");
} catch (error) {
console.error(error);
return res.status(500).send("An error occurred.");
}
}
// Blockchain deploys
async function deployBidPurse(req, res) {
try {
const signedDeployJSON = req.body.signedDeployJSON;
const signedDeploy = DeployUtil.deployFromJson(signedDeployJSON).unwrap();
const { deployHash } = await client.deploy(signedDeploy);
// const result = await confirmDeploy(deployHash);
// const hashes = await getDeployedHashes(deployHash);
// if (hashes == "") {
// return res.status(500).send("Error in getting hashes");
// }
// contract.setContractHash(hashes.contractHash);
// const bidPurse = await contract.queryContractData(["---here----"]);
return res.status(200).json({ deployHash });
} catch (error) {
console.error(error);
return res
.status(500)
.send("Auction deployBidPurse: Error deploying on-chain");
}
}
async function deployAuction(req, res) {
try {
const tokenId = req.body.tokenId;
const foundNft = await Nfts.findOne({ where: { tokenId } });
if (foundNft == null) {
return res.status(400).send("NFT not found");
}
if (foundNft.inAuction == true) {
return res.status(400).send("NFT already in another live auction");
}
const signedDeployJSON = req.body.signedDeployJSON;
const signedDeploy = DeployUtil.deployFromJson(signedDeployJSON).unwrap();
const { deployHash } = await client.deploy(signedDeploy);
// const result = await confirmDeploy(deployHash);
// const hashes = await getDeployedHashes(deployHash);
// if (hashes == "") {
// return res.status(500).send("Error in getting hashes");
// }
return res.status(200).json({ deployHash });
} catch (error) {
console.error(error);
return res
.status(500)
.send("Auction deployAuction: Error deploying on-chain");
}
}
async function getHashes(req, res) {
try {
const deployedHash = req.params.deployHash;
const result = await confirmDeploy(deployedHash);
const hashes = await getDeployedHashes(deployedHash);
if (result == "") {
return res.status(500).send("Error in getting hashes");
}
return res.status(200).json({ hashes });
} catch (error) {
console.error(error);
return res
.status(500)
.send("Error fetching result :" + JSON.stringify(error));
}
}
async function deploySigned(req, res) {
try {
const signedDeployJSON = req.body.signedDeployJSON;
const deploy = DeployUtil.deployFromJson(signedDeployJSON).unwrap();
const deployHash = await client.putDeploy(deploy);
const result = await confirmDeploy(deployHash);
res.status(200).send(deployHash);
} catch (error) {
console.error(error);
res.status(500).send("Auction deploySigned: Error deploying on-chain");
}
}
module.exports = {
startAuction,
openAuction,
closeAuction,
updateAuctionHashes,
addBidOnAuction,
saveBidPurseInfo,
updatePurseUref,
deletePurse,
getHashes,
getAuctionByNft,
getPurseInfo,
getAllAuctions,
deleteAuction,
deployBidPurse,
deployAuction,
deploySigned,
};
|
let canvas = document.querySelector("#canvas");
let ctx = canvas.getContext("2d");
let width = canvas.width;
let height = canvas.height;
const MAX_COMPUTER_SPEED = 6;
let ballPosition;
const BALL_SIZE = 10;
let xSpeed;
let ySpeed;
function initBall() {
ballPosition = { x: 20, y: 30 };
xSpeed = 8;
ySpeed = 4;
}
const PADDLE_WIDTH = 5;
const PADDLE_HEIGHT = 50;
const PADDLE_OFFSET = 10;
let leftPaddleTop = 10;
let rightPaddleTop = 30;
let leftScore = 0;
let rightScore = 0;
let gameOver = false;
document.addEventListener("mousemove", (e) => {
rightPaddleTop = e.y - canvas.offsetTop;
console.log(e);
});
function draw() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = "white";
ctx.fillRect(ballPosition.x, ballPosition.y, BALL_SIZE, BALL_SIZE);
ctx.fillRect(PADDLE_OFFSET, leftPaddleTop, PADDLE_WIDTH, PADDLE_HEIGHT);
ctx.fillRect(
width - PADDLE_WIDTH - PADDLE_OFFSET,
rightPaddleTop,
PADDLE_WIDTH,
PADDLE_HEIGHT
);
ctx.font = "30px monospace";
ctx.textAlign = "left";
ctx.fillText(leftScore.toString(), 50, 50);
ctx.textAlign = "right";
ctx.fillText(rightScore.toString(), width - 50, 50);
}
function followBall() {
let ball = {
top: ballPosition.y,
bottom: ballPosition.y + BALL_SIZE,
};
let leftPaddle = {
top: leftPaddleTop,
bottom: leftPaddleTop + PADDLE_HEIGHT,
};
if (ball.top < leftPaddle.top) {
leftPaddleTop -= MAX_COMPUTER_SPEED;
} else if (ball.bottom > leftPaddle.bottom) {
leftPaddleTop += MAX_COMPUTER_SPEED;
}
}
function update() {
ballPosition.x += xSpeed;
ballPosition.y += ySpeed;
followBall();
}
function checkPaddleCollision(ball, paddle) {
return (
ball.left < paddle.right &&
ball.right > paddle.left &&
ball.top < paddle.bottom &&
ball.bottom > paddle.top
);
}
function adjustAngle(distanceFromTop, distanceFromBottom) {
if (distanceFromTop < 0) {
ySpeed -= 0.5;
} else if (distanceFromBottom < 0) {
ySpeed += 0.5;
}
}
function checkCollision() {
let ball = {
left: ballPosition.x,
right: ballPosition.x + BALL_SIZE,
top: ballPosition.y,
bottom: ballPosition.y + BALL_SIZE,
};
let leftPaddle = {
left: PADDLE_OFFSET,
right: PADDLE_OFFSET + PADDLE_WIDTH,
top: leftPaddleTop,
bottom: leftPaddleTop + PADDLE_HEIGHT,
};
let rightPaddle = {
left: width - PADDLE_WIDTH - PADDLE_OFFSET,
right: width - PADDLE_OFFSET,
top: rightPaddleTop,
bottom: rightPaddleTop + PADDLE_HEIGHT,
};
if (checkPaddleCollision(ball, leftPaddle)) {
let distanceFromTop = ball.top - leftPaddle.top;
let distanceFromBottom = leftPaddle.bottom - ball.bottom;
adjustAngle(distanceFromTop, distanceFromBottom);
xSpeed = Math.abs(xSpeed);
}
if (checkPaddleCollision(ball, rightPaddle)) {
let distanceFromTop = ball.top - rightPaddle.top;
let distanceFromBottom = rightPaddle.bottom - ball.bottom;
adjustAngle(distanceFromTop, distanceFromBottom);
xSpeed = -Math.abs(xSpeed);
}
if (ball.left < 0) {
rightScore++;
initBall();
}
if (ball.right > width) {
leftScore++;
initBall();
}
if (leftScore > 9 || rightScore > 9) {
gameOver = true;
}
if (ball.left < 0 || ball.right > width) {
xSpeed = -xSpeed;
}
if (ball.top < 0 || ball.bottom > height) {
ySpeed = -ySpeed;
}
}
function drawGameOver() {
ctx.fillStyle = "white";
ctx.font = "30px monospace";
ctx.textAlign = "center";
ctx.fillText("GAME OVER", width / 2, height / 2);
}
function gameLoop() {
draw();
update();
checkCollision();
if (gameOver) {
draw();
drawGameOver();
} else {
setTimeout(gameLoop, 20);
}
}
initBall();
gameLoop();
|
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:my_mobile_app/common/enums/input_state.dart';
import 'package:my_mobile_app/common/widgets/input/common_helper_text.dart';
import 'package:my_mobile_app/constants/asset_paths.dart';
import 'package:my_mobile_app/constants/custom_typography.dart';
import 'package:my_mobile_app/constants/palette.dart';
class CommonTextField extends StatefulWidget {
const CommonTextField({
this.controller,
this.hintText,
this.showLabel = false,
this.labelText,
this.helperText,
this.margin = EdgeInsets.zero,
this.obscureText = false,
this.options = const TextFieldOptions(),
this.backgroundColor,
this.cursorColor,
this.hasLeadingIcon = false,
this.hasTrailingIcon = false,
this.trailingIconData,
this.radius,
this.hintStyle,
this.onChanged,
this.inputFormatters,
super.key,
});
final TextEditingController? controller;
final ({InputState state, String text})? Function(String?)? helperText;
final String? hintText;
final bool showLabel;
final String? labelText;
final EdgeInsets margin;
final bool obscureText;
final TextFieldOptions options;
final Color? backgroundColor;
final Color? cursorColor;
final bool hasLeadingIcon;
final bool hasTrailingIcon;
final TextFieldIconData? trailingIconData;
final double? radius;
final TextStyle? hintStyle;
final void Function(String)? onChanged;
final List<TextInputFormatter>? inputFormatters;
@override
State<CommonTextField> createState() => _CommonTextFieldState();
}
class _CommonTextFieldState extends State<CommonTextField> {
final FocusNode focusNode = FocusNode();
InputState currentState = InputState.none;
String currentHelperText = '';
@override
void initState() {
super.initState();
focusNode.addListener(_handleFocusChange);
}
@override
void dispose() {
focusNode
..removeListener(_handleFocusChange)
..dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: widget.margin,
child: ValueListenableBuilder<TextEditingValue>(
valueListenable: widget.controller ?? TextEditingController(),
builder: (_, value, __) {
_updateHelperText(value);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_TextField(
focusNode: focusNode,
widget: widget,
backgroundColor: widget.backgroundColor,
radius: widget.radius,
textFieldColor: _getTextFieldColor(),
hintTextColor: _getHintTextColor(),
borderWidth: _getBorderWidth(),
hintStyle: widget.hintStyle,
onChanged: widget.onChanged,
),
const SizedBox(height: 2),
if (currentHelperText.isNotEmpty)
CommonHelperText(
text: currentHelperText,
inputState: currentState,
),
],
);
},
),
);
}
void _handleFocusChange() {
setState(() {});
}
void _updateHelperText(TextEditingValue value) {
final helperTextInfo = widget.helperText?.call(value.text);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
if (helperTextInfo != null) {
setState(() {
currentState = helperTextInfo.state;
currentHelperText = helperTextInfo.text;
});
} else {
setState(() {
currentState = InputState.none;
currentHelperText = '';
});
}
}
});
}
Color _getTextFieldColor() {
if (!widget.options.enabled) {
return Colors.transparent;
} else if (focusNode.hasFocus) {
switch (currentState) {
case InputState.none:
return widget.options.customColor ?? Palette.calPolyGreen;
case InputState.error:
return Palette.error;
case InputState.success:
return Palette.success;
}
} else {
return Palette.black.withOpacity(0.5);
}
}
Color _getHintTextColor() {
switch (currentState) {
case InputState.none:
return Palette.black.withOpacity(0.5);
case InputState.error:
return Palette.error;
case InputState.success:
return Palette.success;
}
}
double _getBorderWidth() =>
focusNode.hasFocus && currentState == InputState.none ? 2 : 1;
}
class _TextField extends StatelessWidget {
const _TextField({
required this.focusNode,
required this.widget,
required this.hintTextColor,
required this.textFieldColor,
this.backgroundColor,
this.radius,
this.borderWidth = 1,
this.hintStyle,
this.onChanged,
});
final FocusNode focusNode;
final CommonTextField widget;
final Color textFieldColor;
final Color hintTextColor;
final Color? backgroundColor;
final double? radius;
final double? borderWidth;
final TextStyle? hintStyle;
final void Function(String)? onChanged;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
// height: 48,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(
left: 20,
right: 20,
top: _showLabelCheck() ? 10 : 15,
bottom: _showLabelCheck() ? 15 : 15,
),
decoration: BoxDecoration(
border: Border.all(
width: borderWidth ?? 1,
color: textFieldColor,
),
borderRadius: BorderRadius.circular(radius ?? 20),
color: widget.options.enabled ? Colors.transparent : Palette.black.withOpacity(0.2),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_showLabelCheck())
Text(
widget.labelText ?? 'default_search_hint_text'.tr(),
style: CustomTypography.body4.copyWith(
color: hintTextColor,
),
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.hasLeadingIcon)
_TextFieldIcon(
isLeading: true,
iconColor: hintTextColor,
),
Expanded(
child: TextField(
autocorrect: widget.options.autocorrect,
controller: widget.controller,
onChanged: widget.onChanged,
cursorColor: widget.cursorColor,
decoration: InputDecoration.collapsed(
hintText: !focusNode.hasFocus
? widget.hintText ?? 'default_search_hint_text'.tr()
: '',
hintStyle: hintStyle ?? CustomTypography.body2.copyWith(
color: Palette.black.withOpacity(0.6),
),
),
enabled: widget.options.enabled,
obscureText: widget.obscureText,
focusNode: focusNode,
keyboardType: widget.options.keyboardType,
maxLines: widget.options.isMultiline
? widget.options.multilineNo
: 1,
minLines: widget.options.isMultiline
? widget.options.multilineNo
: 1,
style: CustomTypography.body2,
textAlignVertical: TextAlignVertical.center,
textInputAction: widget.options.textInputAction,
inputFormatters: widget.inputFormatters,
),
),
if (widget.hasTrailingIcon)
_TextFieldIcon(
isLeading: false,
iconColor: hintTextColor,
iconData: widget.trailingIconData,
),
],
),
],
),
);
}
bool _showLabelCheck() {
return widget.showLabel;
}
}
class _TextFieldIcon extends StatelessWidget {
const _TextFieldIcon({
required this.isLeading,
required this.iconColor,
this.iconData,
});
final bool isLeading;
final Color iconColor;
final TextFieldIconData? iconData;
@override
Widget build(BuildContext context) {
return InkWell(
splashColor: Colors.transparent,
onTap: iconData?.onTap,
child: Padding(
padding: EdgeInsets.only(
left: isLeading ? 0 : 15,
right: isLeading ? 15 : 0,
),
child: Image.asset(
iconData?.path ?? AssetPaths.placeholderIcon,
width: 30,
gaplessPlayback: true,
color: iconColor,
),
),
);
}
}
/// Used to determine the behaviour of the textfield.
class TextFieldOptions {
const TextFieldOptions({
this.autocorrect = true,
this.enabled = true,
this.isMultiline = false,
this.multilineNo = 5,
this.keyboardType = TextInputType.text,
this.textInputAction = TextInputAction.next,
this.customColor,
});
final bool autocorrect;
final bool enabled;
/// Determines whether the TF should be a large one or a single-line one.
final bool isMultiline;
final int multilineNo;
final TextInputType keyboardType;
final TextInputAction textInputAction;
final Color? customColor;
}
class TextFieldIconData {
const TextFieldIconData({
required this.path,
this.onTap,
});
final String path;
final VoidCallback? onTap;
}
|
package com.nowcoder.community.controller;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.CommunityConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@Slf4j
public class HomeController implements CommunityConstant {
@Autowired
private DiscussPostService discussPostService;
@Autowired
private UserService userService;
@Autowired
private LikeService likeService;
/**
* 首页
* @param model
* @param page
* @return
*/
@RequestMapping(path = "/index",method = RequestMethod.GET)
public String getIndexPage(Model model, Page page,@RequestParam(name = "orderMode",defaultValue = "0") int orderMode) {
log.info("显示帖子:{}",model);
page.setRows(discussPostService.findDiscussPostRows(0));
page.setPath("/index?orderMode="+orderMode);
List<DiscussPost> discussPostsList = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
List<Map<String, Object>>discussPosts = new ArrayList<>();
for (DiscussPost discussPost : discussPostsList) {
Map<String, Object> map=new HashMap<>();
map.put("post", discussPost);
int userId = discussPost.getUserId();
User user = userService.findUserById(userId);
map.put("user",user);
Long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
map.put("likeCount", likeCount);
discussPosts.add(map);
}
model.addAttribute("discussPosts", discussPosts);
model.addAttribute("orderMode", orderMode);
return "/index";
}
@RequestMapping(path = "/error",method = RequestMethod.GET)
public String getErrorPage() {
return "/error/500";
}
@RequestMapping(path = "/denied",method = RequestMethod.GET)
public String getDeniedPage() {
return "/error/404";
}
}
|
package org.bigbluebutton.model.whiteboard {
import mx.graphics.SolidColorStroke;
import org.bigbluebutton.view.navigation.pages.whiteboard.WhiteboardCanvas;
import spark.primitives.Path;
public class PencilAnnotation extends DrawingAnnotation {
private var _thickness:int = 1;
private var _transparency:Boolean = false;
private var _path:Path;
public function PencilAnnotation(type:String, anID:String, whiteboardID:String, status:String, color:Number, thickness:Number, transparency:Boolean, points:Array) {
super(type, anID, whiteboardID, status, color, points);
_thickness = thickness;
_transparency = transparency;
}
public function get thickness():int {
return _thickness;
}
public function get transparency():Boolean {
return _transparency;
}
override public function update(an:Annotation):void {
if (an.anID == anID) {
super.update(an);
_thickness = PencilAnnotation(an).thickness;
_transparency = PencilAnnotation(an).transparency;
_points = PencilAnnotation(an).points;
}
}
override public function draw(canvas:WhiteboardCanvas, zoom:Number):void {
if (!_path) {
_path = new Path();
}
_path.stroke = new SolidColorStroke(uint(color), thickness * zoom);
var graphicsCommands:String = "";
graphicsCommands += "M ";
graphicsCommands += denormalize(points[0], canvas.width) + " " + denormalize(points[1], canvas.height) + "\n";
for (var i:int = 2; i < points.length; i += 2) {
graphicsCommands += "L ";
graphicsCommands += denormalize(points[i], canvas.width) + " " + denormalize(points[i + 1], canvas.height) + "\n";
}
_path.data = graphicsCommands;
if (!canvas.containsElement(_path)) {
canvas.addElement(_path);
}
}
override public function remove(canvas:WhiteboardCanvas):void {
if (canvas.containsElement(_path)) {
canvas.removeElement(_path);
}
}
override public function get annotation():Object
{
var ao:Object = super.annotation;
ao["thickness"] = _thickness;
ao["transparency"] = _transparency;
ao["points"] = _points;
return ao;
}
}
}
|
package com.example.recyclerview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ColorAdaptor extends RecyclerView.Adapter<ColorAdaptor.ColorHolder> {
private ArrayList<ColorItem> colorItems;
private Context context;
public ColorAdaptor(ArrayList<ColorItem> colorItems, Context context) {
this.colorItems = colorItems;
this.context = context;
}
@NonNull
@Override
public ColorHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.color_item, parent, false);
return new ColorHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ColorHolder holder, int position) {
ColorItem colorItem = colorItems.get(position);
holder.imageView.setColorFilter(colorItem.getColor());
}
@Override
public int getItemCount() {
return colorItems.size();
}
public class ColorHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public ColorHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
|
import React, { useState } from 'react';
import {Box, TextField, Typography, Button, CircularProgress, Alert, AlertTitle} from "@mui/material";
const SaveConfig = ({ connString, onFinish }) => {
const [formData, setFormData] = useState({
connectionName: '',
systemName: '',
systemVersion: ''
});
const [loading, setLoading] = useState(false);
const [alertType, setAlertType] = useState(null);
const [alertMessage, setAlertMessage] = useState('');
const [loader, setLoader] = useState(false);
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: value,
}));
};
const handleSubmit = async (event) => {
event.preventDefault();
setLoading(true);
const connectionData = {
conn_string: connString,
name: formData.connectionName,
system: formData.systemName,
version: formData.systemVersion
};
try {
const response = await fetch('http://localhost:8000/api/db_access/add_connection', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(connectionData),
});
const responseData = await response.json();
if (!response.ok) {
setAlertType('error')
setAlertMessage(`Database connection failed! ${responseData.detail}`)
setLoader(false)
} else {
setAlertType('success')
setAlertMessage(responseData?.message)
setLoader(false)
}
onFinish();
} catch (error) {
setAlertType('error')
console.error('Error testing connection:', JSON.stringify(error));
setAlertMessage(error.detail)
setLoader(false)
} finally {
setLoading(false);
}
};
return (
<Box>
<Typography variant="h5">Final Step: Add Connection Name</Typography>
<form onSubmit={handleSubmit} autoComplete="off">
<TextField
label="Connection Name"
variant="outlined"
name={'connectionName'}
value={formData.connectionName}
onChange={handleChange}
required
fullWidth
margin="normal"
/>
<TextField
label="System Name"
variant="outlined"
name={'systemName'}
value={formData.systemName}
onChange={handleChange}
required
fullWidth
margin="normal"
/>
<TextField
label="System Version"
variant="outlined"
name={'systemVersion'}
value={formData.systemVersion}
onChange={handleChange}
required
fullWidth
margin="normal"
/>
<Box sx={{display: 'flex', flexDirection: 'row', pt: 2}}>
<Box sx={{flex: '1 1 auto'}}/>
<Button type="submit" variant="contained" color="primary" disabled={loading}>
{ loader ? <CircularProgress size={24} /> : 'Submit' }
</Button>
</Box>
</form>
{/* Alert for success */}
{alertType === 'success' && (
<Alert severity="success">
<AlertTitle>Success</AlertTitle>
<Typography variant="body1">{alertMessage}</Typography>
</Alert>
)}
{/* Alert for error */}
{alertType === 'error' && (
<Alert severity="error">
<AlertTitle>Error</AlertTitle>
<Typography variant="body1">{alertMessage}</Typography>
</Alert>
)}
</Box>
);
};
export default SaveConfig;
|
using System.ComponentModel;
namespace SpreadsheetEngine
{
public abstract class Cell : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged; // Event handler, idk why the ? fixes the green squiggly but it does
private int rowIndex; // Cell y-coordinate
private char columnIndex; // Cell x-coordinate
protected string text = string.Empty; // Raw value of cell
protected string value = string.Empty; // Computed value of cell
/// <summary>
/// Cell Constructor
/// </summary>
/// <param name="rowIndex">The cell's y-coordinate</param>
/// <param name="columnIndex">The cell's x-coordinate</param>
public Cell(int rowIndex, char columnIndex)
{
this.rowIndex = rowIndex;
this.columnIndex = columnIndex;
}
// RowIndex property
public int RowIndex
{ get { return rowIndex; } }
// ColumnIndex property
public char ColumnIndex
{ get { return columnIndex; } }
// Text property, notifies event subscribers
public string Text
{
get { return text; }
set
{
// If the text is being set to the exact same text then just ignore it.
// Do not invoke the property change event
if (this.text == value)
{
return;
}
// If the text is actually being changed then update the protected field
text = value;
this.NotifyPropertyChanged("Text");
}
}
// Value property, notifies event subscribers
public string Value
{
get { return value; }
// Only classes within the same assembly can set the value
internal set
{
this.value = value;
this.NotifyPropertyChanged("Value");
}
}
// This method is from the MSDN documentation on implementing INotifyPropertyChanged
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
#In this file: Visualisations for Final_Gini Dataset
#Requires - CSV of gini index scores for each small area being compared.
#Need shapefiles to make maps
## If a package is installed, it will be loaded. If any
## are not, the missing package(s) will be installed
## from CRAN and then loaded.
Packages = c("plyr","tidyverse","dplyr","kableExtra")
## Now load or install&load all
package.check <- lapply(
Packages,
FUN = function(x) {
if (!require(x, character.only = TRUE)) {
install.packages(x, dependencies = TRUE)
library(x, character.only = TRUE)
}
}
)
#Import Gini Index Data
Full_Gini = read.csv("Full_Gini.csv")%>%select(-1)
#Set N - how many LAs you want to see
n = 10
Most_Dispersed_In = Full_Gini%>%
select(c("LAD", "Gini_In"))%>%
arrange(-Gini_In)%>%
mutate(Rank = c(1:nrow(.)))%>%
filter(., Rank%in%c((nrow(.)-(n-1)):(nrow(.))))%>%
mutate(Rank = rev(c(1:n)))%>%
arrange(-Rank)%>%
rename(In=LAD)%>%
mutate(In = paste0(In, " (",round(Gini_In,3), ")"))%>%
select(-"Gini_In")
Most_Dispersed_Out = Full_Gini%>%
select(c("LAD", "Gini_Out"))%>%
arrange(-Gini_Out)%>%
mutate(Rank = c(1:nrow(.)))%>%
filter(., Rank%in%c((nrow(.)-(n-1)):(nrow(.))))%>%
#select(-"Gini_Out")%>%
mutate(Rank = rev(c(1:n)))%>%
arrange(-Rank)%>%
rename(Out = LAD)%>%
mutate(Out = paste0(Out, " (",round(Gini_Out,3), ")"))%>%
select(-"Gini_Out")
Dispersed = merge(Most_Dispersed_In,Most_Dispersed_Out, by = "Rank")%>%
arrange(-Rank)
rm(Most_Dispersed_In,Most_Dispersed_Out)
Most_Focused_In = Full_Gini%>%
select(c("LAD", "Gini_In"))%>%
arrange(Gini_In)%>%
mutate(Rank = rev(c(1:nrow(.))))%>%
filter(., Rank%in%c(1:n))%>%
arrange(Rank)%>%
rename(In = LAD)%>%
mutate(In = paste0(In, " (",round(Gini_In,3), ")"))%>%
select(-"Gini_In")
Most_Focused_Out = Full_Gini%>%
select(c("LAD", "Gini_Out"))%>%
arrange(Gini_Out)%>%
mutate(Rank = rev(c(1:nrow(.))))%>%
filter(., Rank%in%c(1:n))%>%
arrange(Rank)%>%
rename(Out = LAD)%>%
mutate(Out = paste0(Out, " (",round(Gini_Out,3), ")"))%>%
select(-"Gini_Out")
Focused = merge(Most_Focused_In,Most_Focused_Out, by = "Rank")
rm(Most_Focused_In,Most_Focused_Out)
Rankings = Focused%>%
bind_rows(set_names(rep(NA, ncol(.)), colnames(.)))%>%
rbind(.,Dispersed)%>%
mutate(" " = " ")%>%
mutate(Category = " ")%>%
select(c("Category", "Rank", "In", " ", "Out"))%>%
replace(is.na(.), " ")
Rankings[c(1,((2*n)+1)), "Category"]<-c("Most Focused", "Most Dispersed")
Caption = "Most Focused and Most Dispersed Migration Fields, 2019"
Table = Rankings
Table %>%
kbl(caption= Caption,
format= "html",
col.names = names(Table),
align="r") %>%
kable_classic(full_width = F, html_font = "helvetica")
|
package com.example.nasa_app.adapter
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.nasa_app.DetailedImageView
import com.example.nasa_app.R
import com.example.nasa_app.model.RoverPhoto
class RoverPhotoAdapter(private var roverPhotos: MutableList<RoverPhoto>) :
RecyclerView.Adapter<RoverPhotoAdapter.ViewHolder>() {
lateinit var context: Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
context = parent.context
val view =
LayoutInflater.from(parent.context).inflate(R.layout.recycler_marsinfo, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val roverPhoto = roverPhotos[position]
Glide.with(holder.itemView.context)
.load(roverPhoto.imgSrc)
.placeholder(R.color.black)
.error(androidx.appcompat.R.color.error_color_material_dark)
.into(holder.imageView)
holder.textViewSol.text = "Sol: ${roverPhoto.sol}"
holder.textViewEarthDate.text = "Earth Date: ${roverPhoto.earthDate}"
holder.roverName.text = "Rover Name: ${roverPhoto.rover.name}"
holder.roverID.text = "Rover Id: ${roverPhoto.id}"
holder.cameraName.text = "Rover Id: ${roverPhoto.camera.fullName}"
holder.imageView.setOnClickListener {
val intent = Intent(context, DetailedImageView::class.java)
intent.putExtra("image_url", roverPhoto.imgSrc)
context.startActivity(intent)
}
}
override fun getItemCount(): Int {
return roverPhotos.size
}
fun setData(newRoverPhotos: List<RoverPhoto>) {
roverPhotos.clear()
roverPhotos.addAll(newRoverPhotos)
notifyDataSetChanged()
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val imageView: ImageView = itemView.findViewById(R.id.imageView)
val roverID: TextView = itemView.findViewById(R.id.roverID)
val textViewSol: TextView = itemView.findViewById(R.id.textViewSol)
val textViewEarthDate: TextView = itemView.findViewById(R.id.textViewEarthDate)
val roverName: TextView = itemView.findViewById(R.id.roverName)
val cameraName: TextView = itemView.findViewById(R.id.cameraName)
}
}
|
import type { Game } from '../types';
const mocks = {
utils: {
generateId: jest.fn(),
},
};
jest.mock('../utils', () => ({ ...mocks.utils }));
import { createGame, updateGameScore } from '../game';
describe('module game', () => {
describe('function createGame', () => {
mocks.utils.generateId.mockReturnValue('123abc');
it('creates an instance of Game', () => {
expect(createGame('Foo', 'Bar')).toEqual({
id: '123abc',
homeTeamName: 'Foo',
awayTeamName: 'Bar',
homeScore: 0,
awayScore: 0,
});
});
});
describe('function updateGameScore', () => {
it('updates a game with the given score and returns a new game', () => {
const game: Game = {
id: 'test',
homeTeamName: 'a',
awayTeamName: 'b',
homeScore: 0,
awayScore: 0,
};
const updatedGame = updateGameScore(game, 1, 2);
expect(updatedGame).not.toBe(game);
expect(updatedGame).toEqual({
id: 'test',
homeTeamName: 'a',
awayTeamName: 'b',
homeScore: 1,
awayScore: 2,
});
});
});
});
|
package bank;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/**
* Security class is in charge of the login process and authentication services for bank transactions.
* A Security object will be generated when the
* {@link Bank} class is initialised. Functions are utilised to validate the authenticity of a user. Uses the
* <a href="https://cryptobook.nakov.com/mac-and-key-derivation/pbkdf2">PBKDF2 Algorithm</a> from the
* <a href="https://docs.oracle.com/javase/8/docs/api/index.html?javax/crypto/SecretKeyFactory.html">SecretKeyFactory</a>
* library for encryption.
* <p><pre>
* General usage flow:
* - Use {@link #Security(int) Security()} constructor to start the security session in the bank
* - Use {@link #validatePassword(int, String)} for an existing account's login process
* - OR use {@link #createNewPass(int, String)} for adding a new account and then use <code>validatePassword()</code> to log user in
* - Use <code>createNewPass()</code> to also change account credentials
* - Use {@link #generateTransactionOTP(int, int)} followed by {@link #validateOTP(int, String)} for the OTP process
* </pre></p>
* Dependency: UserPass.csv data file for storing account ID and encrypted password pairs
*/
public class Security {
/** Account Credentials of all bank customers
* Key: Int User ID, Val: [String Hashed Account Password Value,Salt Value] */
private HashMap<Integer,List<String>> userPwdMap = new HashMap<>();
/** A record of currently active OTPs. Key: User ID Val:[otpVal,otpValidTime] */
private HashMap<Integer, List<String>> otpMap = new HashMap<>();
/** OTP will be valid for the duration in seconds */
private int otpExpirySeconds;
/** Standard date and time display format to be used for methods */
private DateTimeFormatter standardDateTimeFormat = DateTimeFormatter.ofPattern("dd/MM/yy HH:mm:ss");
/**
* Constructor for security class called on Bank initialisation. Creates a Security class object.
* Sets the OTP validity duration
* and populates @see #userPwdMap with values from the password CSV file, UserPass.csv.
* @param otpExpirySeconds OTP validity duration in seconds
*/
public Security(int otpExpirySeconds){
this.otpExpirySeconds = otpExpirySeconds;
String filePath = "data\\UserPass.csv";
try(BufferedReader reader = new BufferedReader(new FileReader(filePath))){
String line;
String accInfo[];
Boolean firstLine = true;
while ((line = reader.readLine()) != null){ // populates the userPwdMap with Account log-in credentials
if (firstLine == true){
firstLine = false;
continue;
}
accInfo = line.split(",");
userPwdMap.put(Integer.parseInt(accInfo[0]), List.of(accInfo[1],accInfo[2])); // exception handler for parsing salt and pwd
}
} catch (IOException e){
e.printStackTrace();
System.err.println("Unable to locate UserPass.csv in path " + filePath);
}
}
/**
* Used to generate a one-time user password specific to the user's account for transaction validations.
* Pre-requisite: Account specified in userID must be part of the system's security database (in UserPass.csv)
* Adds the OTP to the Hashmap otpMap Key: userId, Value: [otpString,otpValidTime].
* Password will be valid within the duration specified in otpExpirySeconds.
* @param userId Account ID value
* @param passLength Specifies the OTP string length
*/
public void generateTransactionOTP(int userId, int passLength){
if (this.userPwdMap.containsKey(userId)){
if (passLength <= 0){
System.err.println("OTP Length cannot be less than 1.");
} else {
SecureRandom randomNum = new SecureRandom();
String otpString = "";
// generates the OTP String value additively using the RNG
for (int i = 0; i< passLength; ++i){
otpString = otpString + Integer.toString(randomNum.nextInt(10));
}
LocalDateTime otpValidTime = LocalDateTime.now().plusSeconds(otpExpirySeconds); // sets the OTP expiry date and time
String timeString = standardDateTimeFormat.format(otpValidTime);
System.out.println("Generated OTP: " + otpString + " is valid until " + timeString);
this.otpMap.put(userId, List.of(otpString, timeString));
}
} else {
throw new IllegalArgumentException("User ID not found in database.");
}
}
/**
* Checks if the input argument matches the one found in OTP hashmap, otpMap
* Method has 3 conditions: Valid User ID, Non-expired OTP and Correct One-time password value
* If any of the three conditions fail, return a False value.
* Otherwise, clear the OTP record from otpMap and return True.
* @param userId Integer key variable to use for getting OTP information from otpMap
* @param otpString One-time password user input value to compare against existing OTP records
* @return boolean true on successful validation, false for failed
*/
public boolean validateOTP(int userId, String otpString){
if (!otpMap.containsKey(userId)){
System.err.println("User's OTP has not been generated yet.");
}
else {
String expString = otpMap.get(userId).get(1); // gets the expiry time-date string value from otpMap
LocalDateTime expDateTime = LocalDateTime.parse(expString, standardDateTimeFormat); // casts String into a LDT datatype
LocalDateTime nowTime = LocalDateTime.now();
if (nowTime.isAfter(expDateTime)){
System.out.println("OTP has expired, please generate a new OTP");
otpMap.remove(userId);
}
else {
String storedOtp = otpMap.get(userId).get(0);
if (otpString.equals(storedOtp)){
System.out.println("OTP is correct.");
otpMap.remove(userId); // removes generated OTP from the otpMap
return true;
}
else {
System.out.println("OTP is incorrect please try again.");
}
}
}
return false;
}
/**
* Generates a randomised salt value to add to plain-text password before hashing.
* @return 16 byte salt value
*/
private byte[] generateSalt(){
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
/**
* Converts plain-text passString arg into an encrypted string by adding a
* cryptographic salt to the plain-text and then hashing it
* @param passString Plain-text password string
* @param salt Account-specific salt byte array
* @return Encrypted password in a byte array
*/
public byte[] hashPassword(String passString, byte[] salt){
//byte[] salt = saltString.getBytes();
try {
PBEKeySpec spec = new PBEKeySpec(passString.toCharArray(), salt, 1000, 64*8);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hashedVal = factory.generateSecret(spec).getEncoded();
return hashedVal;
} catch (NoSuchAlgorithmException error) {
System.err.println("Hashing Algo cannot be located, returning null value.");
} catch (InvalidKeySpecException error) {
System.err.println(error);
}
return null;
}
/**
* Converts byte array into a hexadecimal string twice the length of the input array.
* @param arr Byte array of hashed password
* @return Converted character string encoded with byte array values
*/
private String byteToString(byte[] arr){
BigInteger bi = new BigInteger(1, arr);
String hex = bi.toString(16);
int paddingLength = (arr.length * 2) - hex.length();
if(paddingLength > 0){
return String.format("%0" +paddingLength + "d", 0) + hex;
}else{
return hex;
}
}
/**
* Converts hexadecimal string into byte array by translating the character values
* into byte values.
* @param hex The hexadecimal string
* @return Converted byte array
*/
private static byte[] fromHex(String hex){
byte[] bytes = new byte[hex.length() / 2];
for(int i = 0; i < bytes.length ;i++)
{
bytes[i] = (byte)Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return bytes;
}
/**
* Iterates over the two input argument array bytes and
* checks for differences using bitwise XOR.
* @param arr1 First hashed byte array
* @param arr2 Second hashed byte array
* @return True if arr1 and arr2 are same, False if different
*/
private boolean iterCompare(byte[] arr1, byte[] arr2){
int arr_diff = arr1.length ^ arr2.length; // XOR()
for(int i=0;i<arr1.length && i<arr2.length;i++){
arr_diff = arr_diff | (arr1[i] ^ arr2[i]); // arr_diff OR (arr1 byte XOR arr2 byte)
}
return arr_diff == 0;
}
/**
* Checks if input password matches password stored in password Hashmap, userPwdMap.
* @param userId User's account identification number
* @param password Plain-text password user is attempting to login with
* @return Succesful Login: True, Unsuccesful: False
*/
public Boolean validatePassword(int userId, String password){
if (userPwdMap.containsKey(userId)){
byte[] storedPass = fromHex(userPwdMap.get(userId).get(0));
byte[] salt = fromHex(userPwdMap.get(userId).get(1));
byte[] attemptPass = hashPassword(password, salt);
if (iterCompare(storedPass, attemptPass)){
System.out.println("Login successful.");
return true;
} else {
System.out.println("Login unsuccesful, please try again.");
}
} else {
System.err.println("User log in credentials not found.");
}
return false;
}
/**
* Sets a new encrypted password and salt for user account in the userPwdMap.
* If no account is associated with userId argument, create a new record in userPwd with password and hashvalue
* For existing account, changes existing password and hash values associated with account.
* @param userId User account ID to add/change password for
* @param password Plain-text password value
*/
public void createNewPass(int userId, String password){
byte[] salt = generateSalt();
byte[] hashVal;
hashVal = hashPassword(password, salt);
if (userPwdMap.containsKey(userId)) {
System.out.println("Password has been updated!");
}
else {
System.out.println("Password has been set for account.");
}
userPwdMap.put(userId, List.of(byteToString(hashVal), byteToString(salt)));
}
public static void main(String[] args) {
Security secSession = new Security(60);
//Scanner scanner = new Scanner(System.in);
//byte[] pwd = secSession.hashPassword(1, "tehcbing", secSession.generateSaltt());
//System.out.println(pwd);
//scanner.close();
//secSession.createNewPass(2, "tehcbing");
//secSession.createNewPass(3, "kopicbing");
byte[] salty = fromHex("c053f9f5f74a8a9ab12a2ca39c42b128");
byte[] pwd1 = secSession.hashPassword("icelemontea", salty);
byte[] pwd2 = secSession.hashPassword("icelemonteh", salty);
if(secSession.iterCompare(pwd1,pwd2)){
System.out.println("Password match");
}
secSession.validatePassword(1,"icelemontea");
}
}
|
import 'package:flutter/material.dart';
import 'package:heydodo/src/config/constants/colors.dart';
import 'package:heydodo/src/config/constants/utils.dart';
class EmptyListMessage extends StatelessWidget {
final String message;
final String actionLabel;
final void Function()? onPressed;
const EmptyListMessage(
{super.key,
required this.message,
required this.actionLabel,
required this.onPressed});
@override
Widget build(BuildContext context) {
return SliverFillRemaining(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
message,
style:
const TextStyle(color: HeyDoDoColors.secondary, fontSize: 18.0),
),
const SizedBox(
height: heyDoDoPadding * 2,
),
GestureDetector(
onTap: onPressed,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: heyDoDoPadding * 5, vertical: heyDoDoPadding * 2),
decoration: BoxDecoration(
color: HeyDoDoColors.secondary,
borderRadius: BorderRadius.circular(24.0)),
child: Text(
actionLabel,
style: const TextStyle(
color: HeyDoDoColors.white,
fontSize: 16.0,
fontWeight: FontWeight.w500),
),
),
)
],
));
}
}
|
from flask import Flask, json, jsonify, request
from json import JSONEncoder
from model.twit import Twit
#from flask.json import JSONEncoder
twits = []
app = Flask(__name__)
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Twit):
return {"body": obj.body, "author": obj.author}
else:
return super().default(obj)
app.json_encoder = CustomJSONEncoder
@app.route("/ping", methods=["GET"])
def ping():
return jsonify({"response": "pong"})
@app.route("/twit", methods=["POST"])
def create_twit():
"""{"body": "Hello There", "author": "aqaguy"}"""
twit_json = request.get_json()
twit = Twit(twit_json["body"], twit_json["author"])
twits.append(twit)
return jsonify({"status": "success"})
@app.route("/twit", methods=["GET"])
def read_twits():
return jsonify({"twits": twits})
if __name__ == "__main__":
app.run(debug=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.