text
stringlengths
184
4.48M
<?php /** * LICENSE: The MIT License (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://github.com/azure/azure-storage-php/LICENSE * * 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. * * PHP version 5 * * @category Microsoft * @package MicrosoftAzure\Storage\Table\Models * @author Azure Storage PHP SDK <dmsh@microsoft.com> * @copyright 2016 Microsoft Corporation * @license https://github.com/azure/azure-storage-php/LICENSE * @link https://github.com/azure/azure-storage-php */ namespace MicrosoftAzure\Storage\Table\Models; /** * Holds optional parameters for queryEntities API * * @category Microsoft * @package MicrosoftAzure\Storage\Table\Models * @author Azure Storage PHP SDK <dmsh@microsoft.com> * @copyright 2016 Microsoft Corporation * @license https://github.com/azure/azure-storage-php/LICENSE * @version Release: 0.10.2 * @link https://github.com/azure/azure-storage-php */ class QueryEntitiesOptions extends TableServiceOptions { /** * @var Query */ private $_query; /** * @var string */ private $_nextPartitionKey; /** * @var string */ private $_nextRowKey; /** * Constructs new QueryEntitiesOptions object. */ public function __construct() { $this->_query = new Query(); } /** * Gets query. * * @return Query */ public function getQuery() { return $this->_query; } /** * Sets query. * * You can either sets the whole query *or* use the individual query functions * like (setTop). * * @param string $query The query instance. * * @return none */ public function setQuery($query) { $this->_query = $query; } /** * Gets entity next partition key. * * @return string */ public function getNextPartitionKey() { return $this->_nextPartitionKey; } /** * Sets entity next partition key. * * @param string $nextPartitionKey The entity next partition key value. * * @return none */ public function setNextPartitionKey($nextPartitionKey) { $this->_nextPartitionKey = $nextPartitionKey; } /** * Gets entity next row key. * * @return string */ public function getNextRowKey() { return $this->_nextRowKey; } /** * Sets entity next row key. * * @param string $nextRowKey The entity next row key value. * * @return none */ public function setNextRowKey($nextRowKey) { $this->_nextRowKey = $nextRowKey; } /** * Gets filter. * * @return Filters\Filter */ public function getFilter() { return $this->_query->getFilter(); } /** * Sets filter. * * You can either use this individual function or use setQuery to set the whole * query object. * * @param Filters\Filter $filter value. * * @return none. */ public function setFilter($filter) { $this->_query->setFilter($filter); } /** * Gets top. * * @return integer. */ public function getTop() { return $this->_query->getTop(); } /** * Sets top. * * You can either use this individual function or use setQuery to set the whole * query object. * * @param integer $top value. * * @return none. */ public function setTop($top) { $this->_query->setTop($top); } /** * Adds a field to select fields. * * You can either use this individual function or use setQuery to set the whole * query object. * * @param string $field The value of the field. * * @return none. */ public function addSelectField($field) { $this->_query->addSelectField($field); } /** * Gets selectFields. * * @return array. */ public function getSelectFields() { return $this->_query->getSelectFields(); } /** * Sets selectFields. * * You can either use this individual function or use setQuery to set the whole * query object. * * @param array $selectFields value. * * @return none. */ public function setSelectFields($selectFields) { $this->_query->setSelectFields($selectFields); } }
import { useContext } from "react"; import { TransactionsContext } from "../context/TransactionContext"; import dummyData from "../utils/dummyData"; import { shortenAddress } from "../utils/shortenAddress"; import useFetch from "../hooks/useFetch"; import { Loader } from './'; // transactions card comp const TransactionCard = ({ addressTo, addressFrom, timestamp, message, keyword, amount }) => { const gifUrl = useFetch({ keyword }); return ( <div className="bg-[#181918] m-4 flex flex-1 2xl:max-w-[450px] sm:min-w-[270px] sm:max-w-[300px] flex-col p-3 rounded-md hover:shadow-2xl "> <div className="flex flex-col items-center w-full mt-3"> <div className="justify-start w-full mb-6 p-2"> <a href={`https://ropsten.etherscan.io/address/${addressFrom}`} target="_blank" rel="noponer noreferrer" className=""> <p className="text-white text-base rounded-md p-1 bg-gray-600 mb-1">From: {shortenAddress(addressFrom)}</p> </a> <a href={`https://ropsten.etherscan.io/address/${addressTo}`} target="_blank" rel="noponer noreferrer" className=""> <p className="text-white text-base rounded-md p-1 bg-gray-600">To: {shortenAddress(addressTo)}</p> </a> <p className="text-white text-base">Amount: {amount} eth</p> {message && ( <> <p className="text-white">Message: {message}</p> </> )} </div> {/* gif */} <div> <img src={gifUrl} alt="gif" className="w-full h-56 2x:h-96 rounded-md shadow-lg"/> </div> <div className="bg-black p-3 px-5 w-max rounded-3xl -mt-5 shadow-2xl"> <p className="text-[#37c7da] font-bolder">{timestamp}</p> </div> </div> </div> ) }; const Transactions = () => { const { currentAccount, transactions } = useContext(TransactionsContext); return ( <div className="flex w-full justify-center items-center 2xl:px-20 gradient-bg-transactions"> <div className="flex flex-col md:p-12 sm:py-12 px-4"> {currentAccount ? ( <h1 className="text-white text-center my-2 text-xl">Latest Trasnsactions</h1> ) : ( <h1 className="text-white text-center my-2 text-xl">Connect your account to see the lastest chain</h1> )} {/* latest trns */} {/* <div className="flex flex-wrap justify-center items-center mt-10"> {dummyData.reverse().map((Transaction, i) => ( <TransactionCard key={i} {...Transaction }/> ))} </div> */} {transactions.length ? ( <div className="flex flex-wrap justify-center items-center mt-10"> {transactions.reverse().map((Transaction, i) => ( <TransactionCard key={i} {...Transaction }/> ))} </div> ) : <> <Loader/> <p className="text-center text-white text-xs">Please wait...</p> </> } </div> </div> ) } export default Transactions;
'use client' import Avatar from '@/app/components/Avatar'; import useOtherUser from '@/app/hooks/UseOtherUsers'; import { Conversation, User } from '@prisma/client'; import Link from 'next/link'; import { useMemo, useState } from 'react'; import { HiChevronLeft, HiEllipsisHorizontal } from 'react-icons/hi2'; import ProfileDrawer from './ProfileDrawer'; interface Props { conversation: Conversation & { users: User[] }; } const Header: React.FC<Props> = ({ conversation }) => { const otherUser = useOtherUser(conversation); const [drawer, setDrawer] = useState(false) const statusText = useMemo(() => { if (conversation.isGroup) { return `${conversation.users.length} members`; } return 'Active'; }, [conversation]); return ( <> <ProfileDrawer data={conversation} isOpen={drawer} onClick={() => setDrawer(false)} /> <div className=" bg-white w-full flex border-b-[1px] sm:px-4 py-4 px-4 lg:px-6 justify-between shadow-sm " > <div className="flex gap-3 items-center"> <Link className=" lg:hidden block text-sky-500 hover:text-sky-600 transition cursor-pointer " href="/conversations" > <HiChevronLeft size={32} /> </Link> <Avatar user={otherUser} /> <div className="flex flex-col"> <div className="text-sm font-light text-neutral-500"> {statusText} </div> </div> </div> <HiEllipsisHorizontal size={32} onClick={() => setDrawer(true)} className=" text-sky-500 cursor-pointer hover:text-sky-600 transition" /> </div> </> ); }; export default Header;
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query'; import { useEffect } from 'react'; import { BankAccount } from '../account.types'; import { addSavedAccount, getSavedAccounts } from '../services/accounts.firebase'; import { getInstitutionAccount } from '../services/accounts.nordigen'; import { getRequisition } from './services/institutions.nordigen'; import { getUserRequisitions } from './services/requisitions.firebase'; export const saveRequisitionAccounts = async (uid: string) => { const userRequisitions = await getUserRequisitions(uid); const requisitions = await Promise.all( userRequisitions.map((requisition) => getRequisition(requisition.id)), ); const getAccountReqs = requisitions.flatMap((requisition) => requisition.accounts.map((accountId) => getInstitutionAccount(accountId)), ); const institutionAccounts = await Promise.all(getAccountReqs); const savedAccounts = await getSavedAccounts(uid); const savedAccountIds = savedAccounts.map((account) => account.id); const saveAccountsReqs = institutionAccounts .filter((account) => !savedAccountIds.includes(account.id)) .map((account) => addSavedAccount(uid, account)); return Promise.all(saveAccountsReqs); }; export const useRequisition = (uid: string) => { const queryClient = useQueryClient(); const { data: userRequisitions = [], isSuccess: requisitionsSuccess } = useQuery( ['userRequisitions'], () => getUserRequisitions(uid), ); const requisitionQueryResults = useQueries({ queries: userRequisitions.map((userRequisition) => { return { queryKey: ['userRequisition', userRequisition.id], queryFn: () => getRequisition(userRequisition.id), enabled: requisitionsSuccess, }; }), }); const requisitions = requisitionQueryResults.map((result) => result.data); const institutionAccountsQueryResults = useQueries({ queries: requisitions.flatMap((requisition) => { if (!requisition) { return []; } return requisition.accounts.flatMap((accountId) => { const query = { queryKey: ['institutionAccount', accountId], queryFn: () => getInstitutionAccount(accountId), enabled: !!requisition, }; return query; }); }), }); const savedAccountIdsResult = useQuery(['savedAccounts'], () => getSavedAccounts(uid), { select: (accounts) => accounts.map((account) => account.id), }); const { mutateAsync, isLoading, isSuccess, error } = useMutation((account: BankAccount) => addSavedAccount(uid, account), ); useEffect(() => { const areInstitutionAccountsLoaded = institutionAccountsQueryResults.every( (result) => result.isSuccess, ); if (areInstitutionAccountsLoaded && savedAccountIdsResult.isSuccess) { const institutionAccounts = institutionAccountsQueryResults.map((result) => result.data!); const savedAccountIds = savedAccountIdsResult.data; const unsavedAccounts = institutionAccounts.filter( (account) => !savedAccountIds.includes(account.id), ); if (unsavedAccounts.length) { return; } const mutationReqs = unsavedAccounts.map((account) => mutateAsync(account)); Promise.all(mutationReqs).then(() => queryClient.invalidateQueries(['savedAccounts'])); } }, [mutateAsync, institutionAccountsQueryResults, savedAccountIdsResult, queryClient]); return { isLoading, isSuccess, error, }; };
// // WizardDomainViewController.swift // GenericApp // // Created by Eric Bariaux on 18/06/2022. // Copyright © 2022 OpenRemote. All rights reserved. // import UIKit import MaterialComponents.MaterialTextFields import ORLib class WizardDomainViewController: UIViewController { var configManager: ConfigManager? var domainName: String? @IBOutlet weak var domainTextInput: ORTextInput! @IBOutlet weak var nextButton: MDCRaisedButton! @IBOutlet var boxView: UIView! override func viewDidLoad() { super.viewDidLoad() let orGreenColor = UIColor(named: "or_green") nextButton.backgroundColor = orGreenColor nextButton.tintColor = UIColor.white boxView.layer.cornerRadius = 10 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) domainTextInput.textField?.delegate = self domainTextInput.textField?.autocorrectionType = .no domainTextInput.textField?.autocapitalizationType = .none domainTextInput.textField?.returnKeyType = .next } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Segues.goToWizardAppView { switch configManager!.state { case .selectApp(_, let apps): let appViewController = segue.destination as! WizardAppViewController appViewController.apps = apps appViewController.configManager = self.configManager default: fatalError("Invalid state for segue") } } else if segue.identifier == Segues.goToWizardRealmView { switch configManager!.state { case .selectRealm(_, _, let realms): let realmViewController = segue.destination as! WizardRealmViewController realmViewController.realms = realms realmViewController.configManager = self.configManager default: fatalError("Invalid state for segue") } } else if segue.identifier == Segues.goToWebView { let orViewController = segue.destination as! ORViewcontroller switch configManager!.state { case .complete(let project): orViewController.targetUrl = project.targetUrl default: fatalError("Invalid state for segue") } } } @IBAction func nextButtonpressed(_ sender: UIButton) { if let domain = domainName { requestAppConfig(domain) } } } extension WizardDomainViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == domainTextInput.textField { if let s = domainTextInput.textField?.text { domainName = s.replacingCharacters(in: Range(range, in: s)!, with: string).trimmingCharacters(in: .whitespacesAndNewlines) nextButton.isEnabled = !(domainName?.isEmpty ?? true) } else { nextButton.isEnabled = false } } return true } fileprivate func requestAppConfig(_ domain: String) { configManager = ConfigManager(apiManagerFactory: { url in HttpApiManager(baseUrl: url) }) async { do { let state = try await configManager!.setDomain(domain: domain) print("State \(state)") switch state { case .selectDomain: // Something wrong, we just set the domain let alertView = UIAlertController(title: "Error", message: "Error occurred getting app config. Check your input and try again", preferredStyle: .alert) alertView.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertView, animated: true, completion: nil) case .selectApp: self.performSegue(withIdentifier: Segues.goToWizardAppView, sender: self) case .selectRealm: self.performSegue(withIdentifier: Segues.goToWizardRealmView, sender: self) case.complete: self.performSegue(withIdentifier: Segues.goToWebView, sender: self) } } catch { let alertView = UIAlertController(title: "Error", message: "Error occurred getting app config. Check your input and try again", preferredStyle: .alert) alertView.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertView, animated: true, completion: nil) } } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let input = textField.text, !input.isEmpty else { return false } if textField == domainTextInput.textField, let domain = domainName { domainTextInput.textField?.resignFirstResponder() requestAppConfig(domain) } return true } }
<script lang="ts"> import { client, Audit } from "../../clients"; import { PUBLIC_BLOG_TABLE } from "$env/static/public"; import Textarea from "$lib/textarea.svelte"; import { goto } from "$app/navigation"; let id: string; let title: string; let authors: string; let content: string; const today = new Date(); const createdAt = new Date( today.getTime() - today.getTimezoneOffset() * 60000 ) .toISOString() .slice(0, 10); async function create() { if (!$client) return; const result = await $client.put({ Item: { id: id, authors: authors.split(",").map((a) => a.trim()), title: title, createdAt: createdAt, content: content, }, TableName: PUBLIC_BLOG_TABLE, ConditionExpression: "attribute_not_exists(id)", }); $Audit?.event({ eventName: "createBlog", resource: { TableName: PUBLIC_BLOG_TABLE, BlogID: id }, }); goto(`/blogs/${id}`); } </script> <form class="space-y-5" on:submit={create}> <div class="flex flex-col"> <label for="createdAt">Päivämäärä </label> <span class="opacity-80 text-sm">Ohje: muodossa YYYY-MM-DD.</span> <input id="createdAt" value={createdAt} required class="border-2 rounded px-3 py-1 my-2 disabled:opacity-60" /> </div> <div class="flex flex-col"> <label for="id">Slug/ID</label> <span class="opacity-80 text-sm"> Ohje: osoiteriville (esim. evon.fi/blog/ESIMERKKI) tuleva uniikki tunniste. Tätä ei voi muuttaa myöhemmin. </span> <input id="id" bind:value={id} required class="border-2 rounded px-3 py-1 my-2 disabled:opacity-60" /> </div> <div class="flex flex-col"> <label for="title">Otsikko</label> <input id="title" bind:value={title} required class="border-2 rounded px-3 py-1 my-2 disabled:opacity-60" /> </div> <div class="flex flex-col"> <label for="authors">Tekijät</label> <span class="opacity-80 text-sm"> Ohje: pilkulla erotettu lista AuthorID:tä. </span> <input id="authors" bind:value={authors} required class="border-2 rounded px-3 py-1 my-2 disabled:opacity-60" /> </div> <div class="flex flex-col"> <label for="content">Sisältö</label> <span class="opacity-80 text-sm"> Ohje: <a href="https://commonmark.org/help/" class="underline"> CommonMark </a> -markdown tyylillä formatoitua tekstiä. </span> <Textarea id="content" bind:content required /> </div> <button type="submit" class="w-full bg-indigo-500 hover:bg-indigo-700 disabled:opacity-60 transition px-3 py-2 rounded text-white" > Tallenna </button> </form>
.\" @(#)getmsg.2 1.1 92/07/30 SMI; from S5R3 .TH GETMSG 2 "21 January 1990" .SH NAME getmsg \- get next message from a stream .SH SYNOPSIS .nf .ft B #include <stropts.h> .ft .LP .ft B .nf int getmsg(fd, ctlptr, dataptr, flags) int fd; struct strbuf *ctlptr; struct strbuf *dataptr; int *flags; .ft .fi .SH DESCRIPTION .IX "getmsg()" "" "\fLgetmsg()\fP \(em get next message from stream" .LP .B getmsg(\|) retrieves the contents of a message (see .BR intro (2)) located at the .B stream head read queue from a .SM STREAMS file, and places the contents into user specified buffer(s). The message must contain either a data part, a control part or both. The data and control parts of the message are placed into separate buffers, as described below. The semantics of each part is defined by the .SM STREAMS module that generated the message. .LP .I fd specifies a file descriptor referencing an open .BR stream . .I ctlptr and .I dataptr each point to a .B strbuf structure that contains the following members: .LP .RS .nf .ft B .ta 1i 1.7i 2.5i int maxlen; /* maximum buffer length */ int len; /* length of data */ char *buf; /* ptr to buffer */ .ft R .fi .DT .RE .LP where .B buf points to a buffer in which the data or control information is to be placed, and .B maxlen indicates the maximum number of bytes this buffer can hold. On return, .B len contains the number of bytes of data or control information actually received, or is 0 if there is a zero-length control or data part, or is \-1 if no data or control information is present in the message. .I flags may be set to the values 0 or .SB RS_HIPRI and is used as described below. .LP .I ctlptr is used to hold the control part from the message and .I dataptr is used to hold the data part from the message. If .I ctlptr (or .IR dataptr ) is a .SM NULL pointer or the .B maxlen field is \-1, the control (or data) part of the message is not processed and is left on the .B stream head read queue and .B len is set to \-1. If the .B maxlen field is set to 0 and there is a zero-length control (or data) part, that zero-length part is removed from the read queue and .B len is set to 0. If the .I maxlen field is set to 0 and there are more than zero bytes of control (or data) information, that information is left on the read queue and .B len is set to 0. If the .I maxlen field in .I ctlptr or .I dataptr is less than, respectively, the control or data part of the message, .I maxlen bytes are retrieved. In this case, the remainder of the message is left on the .B stream head read queue and a non-zero return value is provided, as described below under .SM RETURN VALUES\s0. If information is retrieved from a .B priority message, .I flags is set to .SB RS_HIPRI on return. .LP By default, .B getmsg(\|) processes the first priority or non-priority message available on the .B stream head read queue. However, a process may choose to retrieve only priority messages by setting .I flags to .SM .BR RS_HIPRI \s0. In this case, .B getmsg(\|) will only process the next message if it is a priority message. .LP If .SB O_NDELAY has not been set, .B getmsg(\|) blocks until a message, of the type(s) specified by .I flags (priority or either), is available on the .B stream head read queue. If .SB O_NDELAY has been set and a message of the specified type(s) is not present on the read queue, .B getmsg(\|) fails and sets .B errno to .SM EAGAIN\s0. .LP If a hangup occurs on the .B stream from which messages are to be retrieved, .B getmsg(\|) will continue to operate normally, as described above, until the .B stream head read queue is empty. Thereafter, it will return 0 in the .B len fields of .I ctlptr and .IR dataptr . .br .ne 20 .SH RETURN VALUES .LP .B getmsg(\|) returns a non-negative value on success: .RS .TP 25 0 A full message was read successfully. .TP .SM MORECTL More control information is waiting for retrieval. Subsequent .B getmsg(\|) calls will retrieve the rest of the message. .TP .SM MOREDATA More data are waiting for retrieval. Subsequent .B getmsg(\|) calls will retrieve the rest of the message. .TP \s-1MORECTL\s0 | \s-1MOREDATA\s0 Both types of information remain. .RE .LP On failure, .B getmsg(\|) returns \-1 and sets .B errno to indicate the error. .SH ERRORS .TP 15 .SM EAGAIN The .SB O_NDELAY flag is set, and no messages are available. .TP .SM EBADF .I fd is not a valid file descriptor open for reading. .TP .SM EBADMSG The queued message to be read is not valid for .BR getmsg(\|) . .TP .SM EFAULT .IR ctlptr , .IR dataptr , or .I flags points to a location outside the allocated address space. .TP .SM EINTR A signal was caught during the .B getmsg(\|) system call. .TP .SM EINVAL An illegal value was specified in .IR flags . .IP The .B stream referenced by .I fd is linked under a multiplexor. .TP .SM ENOSTR A \fBstream\fP is not associated with .IR fd . .LP A .B getmsg(\|) can also fail if a .SM STREAMS error message had been received at the .B stream head before the call to .BR getmsg(\|) . The error returned is the value contained in the .SM STREAMS error message. .SH "SEE ALSO" .BR intro (2), .BR poll (2), .BR putmsg (2), .BR read (2V), .BR write (2V)
import pygame pygame.init() WIDTH, HEIGHT = 700,500 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("PingPongPython") FPS = 60 WHITE = (255,255,255) BLACK = (0,0,0) PADDLE_WIDHT,PADDLE_HEIGHT = 20, 100 BALL_RADIUS = 7 WINNING_SCORE = 10 SCORE_FONT = pygame.font.SysFont("comicsans", 48) class Paddle: COLOR = WHITE VEL = 4 def __init__(self, x ,y ,width, height): self.x = self.original_x = x self.y = self.original_y = y self.width = width self.height = height def draw(self,win): pygame.draw.rect(win, self.COLOR, (self.x, self.y, self.width, self.height)) def move(self,up=True): if up: self.y -= self.VEL else: self.y += self.VEL def reset(self): self.x = self.original_x self.y = self.original_y #criando a bola class Ball: MAX_VEL = 5 COLOR = WHITE def __init__(self,x,y,radius): self.x = self.original_x = x self.y = self.original_y = y self.radius = radius self.x_vel = self.MAX_VEL self.y_vel = 0 def draw(self,win): pygame.draw.circle(win, self.COLOR, (self.x, self.y),self.radius) #criando eixos para mover a bola def move(self): self.x += self.x_vel self.y += self.y_vel def reset(self): self.x = self.original_x self.y = self.original_y self.y_vel = 0 self.x_vel *= -1 #criando a barreiras def draw(win,paddles,ball,left_score,right_score): win.fill(BLACK) left_score_text = SCORE_FONT.render(f"{left_score}",1,WHITE) right_score_text= SCORE_FONT.render(f"{right_score}",1,WHITE) win.blit(left_score_text,(WIDTH//4 - left_score_text.get_width()//2,20)) win.blit(right_score_text,(WIDTH * (3/4) - right_score_text.get_width()//2,20)) for paddle in paddles: paddle.draw(win) for i in range(10,HEIGHT,HEIGHT//20): if i % 2 == 1: continue pygame.draw.rect(win,WHITE,(WIDTH//2 - 5,i,10,HEIGHT//20)) ball.draw(win) pygame.display.update() #colisão da bola no campo def hand_collision(ball,left_paddle, right_paddle): if ball.y + ball.radius >= HEIGHT: ball.y_vel *= -1 elif ball.y - ball.radius <= 0: ball.y_vel *= -1 #fazer com que a bola se encontre nas barreiras if ball.x_vel < 0: if ball.y >= left_paddle.y and ball.y <= left_paddle.y + left_paddle.height: if ball.x - ball.radius <= left_paddle.x + left_paddle.width: ball.x_vel *= -1 middle_y = left_paddle.y + left_paddle.height/2 difference_in_y = middle_y - ball.y reduction_factor = (left_paddle.height/2)/ball.MAX_VEL y_vel = difference_in_y / reduction_factor ball.y_vel = -1 * y_vel else: if ball.y >= right_paddle.y and ball.y <= right_paddle.y + right_paddle.height: if ball.x + ball.radius >= right_paddle.x: ball.x_vel *= -1 middle_y = right_paddle.y + right_paddle.height/2 difference_in_y = middle_y - ball.y reduction_factor = (right_paddle.height/2)/ball.MAX_VEL y_vel = difference_in_y / reduction_factor ball.y_vel = -1 * y_vel #movimentando as barreiras def handle_paddle_movement(keys,left_paddle, right_paddle): if keys[pygame.K_w] and left_paddle.y - left_paddle.VEL >= 0: left_paddle.move(up=True) if keys[pygame.K_s] and left_paddle.y + left_paddle.VEL + left_paddle.height <= HEIGHT: left_paddle.move(up=False) if keys[pygame.K_UP] and right_paddle.y - right_paddle.VEL >= 0: right_paddle.move(up=True) if keys[pygame.K_DOWN]and right_paddle.y + right_paddle.VEL + right_paddle.height <= HEIGHT: right_paddle.move(up=False) def main(): run = True clock = pygame.time.Clock() left_paddle = Paddle(10,HEIGHT//2 - PADDLE_HEIGHT//2,PADDLE_WIDHT,PADDLE_HEIGHT) right_paddle = Paddle(WIDTH - 10 - PADDLE_WIDHT,HEIGHT//2 - PADDLE_HEIGHT//2,PADDLE_WIDHT,PADDLE_HEIGHT) ball = Ball(WIDTH//2,HEIGHT//2,BALL_RADIUS) left_score = 0 right_score = 0 while run: clock.tick(FPS) draw(WIN, [left_paddle,right_paddle],ball,left_score,right_score) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False break keys = pygame.key.get_pressed() handle_paddle_movement(keys, left_paddle,right_paddle) ball.move() hand_collision(ball,left_paddle,right_paddle) if ball.x < 0: right_score += 1 ball.reset() elif ball.x > WIDTH: left_score += 1 ball.reset() won = False if left_score >= WINNING_SCORE: won = True win_text = "left player won!" elif right_score >= WINNING_SCORE: won = True win_text = "right player won!" if won: text = SCORE_FONT.render(win_text,1,WHITE) WIN.blit(text,(WIDTH//2 - text.get_width()//2,HEIGHT//2 - text.get_height()//2)) pygame.display.update() pygame.time.delay(5000) ball.reset() left_paddle.reset() right_paddle.reset() left_score = 0 right_score = 0 pygame.quit() if __name__ == '__main__': main()
import { StyledMain, StyledUl } from "./style"; import { useState, useEffect } from "react"; import { Api } from "../API"; import { ToastContainer, toast } from "react-toastify"; import ModalStyled from "../Modal"; export default function Main() { const [openPost, setOpenPost] = useState(false); const [openEdit, setOpenEdit] = useState(false); const [list, setList] = useState([]); const [update, setUpdate] = useState(false); const [item, setItem] = useState(""); const [err, setErr] = useState(false); const [suc, setSuc] = useState(false); const id = JSON.parse(window.localStorage.getItem("@Khub:user")); useEffect(() => { setTimeout(() => { Api.get(`users/${id}`) .then((res) => { const techs = res.data.techs; const inicial = techs.filter((value) => value.status === 'Iniciante') const inter = techs.filter((value) => value.status === 'Intermediário') const avan = techs.filter((value) => value.status === 'Avançado') setList([...inicial, ...inter, ...avan]); }) .catch((err) => console.log(err)); }, 1000) }, [update]); useEffect(() => { if (suc === true) { toast.success("Operação concluída com sucesso!", { position: "top-right", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); setSuc(false); } }, [suc]); useEffect(() => { if (err === true) { toast.error("Ops! Algo deu errado.", { position: "top-right", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); setErr(false); } }, [err]); return ( <StyledMain> <ModalStyled open={openPost} setOpen={setOpenPost} h1="Cadastrar Tecnologia" setUpdate={setUpdate} update={update} item={item} setErr={setErr} setSuc={setSuc} /> <ModalStyled open={openEdit} setOpen={setOpenEdit} h1="Editar Tecnologia" setUpdate={setUpdate} check={true} update={update} item={item} setErr={setErr} setSuc={setSuc} /> <div className="title"> <h3>Tecnologias</h3> <button onClick={() => { setOpenPost(true); setItem(""); }} > + </button> </div> <StyledUl> {list && list.map(({ id, status, title }) => { return ( <li key={id} onClick={() => { setOpenEdit(true); setItem({ id: id, status: status, title: title }); }} > <p>{title}</p> <span>{status}</span> </li> ); })} </StyledUl> <ToastContainer sx={{ backgroundColor: "var(--grey2)", width: "10px" }} position="top-right" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover /> </StyledMain> ); }
#ifndef VEHICLE_H #define VEHICLE_H #include <iostream> #include "VehicleType.h" class Vehicle { private: std::string _id; std::string _brand; float prize; VehicleType _Vtype; public: Vehicle(std::string _id, std::string _brand, float prize, VehicleType _Vtype); Vehicle(std::string _id, std::string _brand, VehicleType _Vtype); //Vehicle(const Vehicle& val) = default; virtual ~Vehicle() { std::cout<<"Vehicle with id: " << _id <<"Destructed"; } virtual float CalculateTax() = 0; //<-- abstract function std::string id() const { return _id; } std::string brand() const { return _brand; } float getPrize() const { return prize; } VehicleType vtype() const { return _Vtype; } }; #endif // VEHICLE_H
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF‐8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>注册</title> <!--css--> <link rel="stylesheet" href="/layui/css/layui.css"> <link rel="stylesheet" href="/layui/icon-extend/iconfont.css"> <link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon"> <!--js--> <script th:src="@{/js/jquery.js}"></script> <style> .layui-input { width: 350px; } #input-vercode { width: 120px; } form { width: 480px; margin: auto; } #input-official-license > input { width: 60px; } /*分散对齐*/ label { text-align: justify; text-justify: distribute-all-lines; text-align-last: justify; } </style> </head> <body> <div class="layui-tab layui-tab-brief"> <ul class="layui-tab-title" style="text-align: center"> <li class="layui-this">普通用户注册</li> <li>院校官方注册</li> </ul> <div class="layui-tab-content"> <!--普通用户注册--> <div class="layui-tab-item layui-show" style="margin-top: 30px"> <form class="layui-form" style="width: 480px;margin: auto"> <!--用户名--> <div class="layui-form-item"> <label class="layui-form-label" for="input-username">用户名</label> <div class="layui-input-block"> <div class="layui-inline"> <input id="input-username" type="text" name="username" placeholder="请输入手机号或邮箱" autocomplete="off" class="layui-input"> </div> </div> </div> <!--密码--> <div class="layui-form-item"> <label class="layui-form-label" for="input-password">密码</label> <div class="layui-input-block"> <div class="layui-inline"> <input id="input-password" type="password" name="password" placeholder="请输入6-12位密码,可包含数字和大小写字母" autocomplete="off" class="layui-input"> </div> </div> </div> <!--确认密码--> <div class="layui-form-item"> <label class="layui-form-label" for="input-confirm">确认密码</label> <div class="layui-input-block"> <div class="layui-inline"> <input id="input-confirm" type="password" name="confirm" placeholder="请确认密码" autocomplete="off" class="layui-input"> </div> </div> </div> <!--验证码--> <div class="layui-form-item"> <label class="layui-form-label" for="input-vercode">验证码</label> <div class="layui-input-block"> <div class="layui-inline"> <input id="input-vercode" type="text" name="vercode" placeholder="请输入验证码" autocomplete="off" class="layui-input"> </div> <div class="layui-inline"> <canvas id="canvas-vercode" width="120" height="40"></canvas> </div> </div> </div> <!--提交按钮--> <div class="layui-form-item"> <div class="layui-input-block"> <button id="btn-submit" type="button" class="layui-btn layui-btn-radius" style="width: 240px;"> 注册 </button> </div> </div> </form> </div> <!--院校官方注册--> <div class="layui-tab-item" style="margin-top: 30px"> <form class="layui-form" lay-filter="test"> <!--院校名称--> <div class="layui-form-item"> <label class="layui-form-label" for="select-official-name">院校名称</label> <div class="layui-input-block"> <div class="layui-inline"> <select id="select-official-name" name="name" lay-search> <option value="">请选择院校</option> </select> </div> <br> <tip style="display: inline-block;font-size: 10px;color: #a29c9c;"> * 注册完成后,院校代码即为登录账号 </tip> </div> </div> <!--授权码--> <div class="layui-form-item"> <label class="layui-form-label" for="input-official-license">官方授权码</label> <div class="layui-input-block"> <div class="layui-inline" id="input-official-license"> <input id="license-1" type="text" autocomplete="off" class="layui-input layui-input-inline" maxlength="4"> <div class="layui-form-mid">-</div> <input id="license-2" type="text" autocomplete="off" class="layui-input layui-input-inline" maxlength="4"> <div class="layui-form-mid">-</div> <input id="license-3" type="text" autocomplete="off" class="layui-input layui-input-inline" maxlength="4"> <div class="layui-form-mid">-</div> <input id="license-4" type="text" autocomplete="off" class="layui-input layui-input-inline" maxlength="4"> </div> <br> <tip style="display: inline-block;font-size: 10px;color: #a29c9c;"> * 请联系院校官方获取注册授权码 </tip> </div> </div> <!--密码--> <div class="layui-form-item"> <label class="layui-form-label" for="input-official-password">密码</label> <div class="layui-input-block"> <div class="layui-inline"> <input id="input-official-password" type="password" name="password" placeholder="请输入6-18位密码,可包含数字和大小写字母" autocomplete="off" class="layui-input"> </div> </div> </div> <!--确认密码--> <div class="layui-form-item"> <label class="layui-form-label" for="input-official-confirm">确认密码</label> <div class="layui-input-block"> <div class="layui-inline"> <input id="input-official-confirm" type="password" name="confirm" placeholder="请确认密码" autocomplete="off" class="layui-input"> </div> </div> </div> <!--提交按钮--> <div class="layui-form-item"> <div class="layui-input-block"> <button id="btn-submit-2" type="button" class="layui-btn layui-btn-radius" style="width: 240px;">注册 </button> </div> </div> </form> </div> </div> </div> <script th:src="@{/layui/layui.js}"></script> <script th:src="@{/js/register.js}"></script> <script> layui.use(['jquery', 'layer', 'form'], function () { const $ = layui.jquery, layer = layui.layer, form = layui.form, regex_psw = /^([A-Z]|[a-z]|[0-9]){6,12}$/, regex_phone = /^1[3456789]\d{9}$/,//手机号正则表达式 regex_mail = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;//邮箱 /********************************* 用户注册 ***********************************/ //初始化验证码 let vercode = verifyCode('#canvas-vercode', 120, 40); //点击换一张验证码 $("#canvas-vercode").click(function () { vercode = verifyCode('#canvas-vercode', 120, 40); }) //注册提交 $("#btn-submit").click(function () { let username = $("#input-username").val(), password = $("#input-password").val(), confirm = $("#input-confirm").val(), inputcode = $("#input-vercode").val(); if (username === '' || password === '' || confirm === '' || inputcode === '') { layer.msg('请将注册信息填写完整', { time: 2000 }) } else if (!regex_phone.test(username) && !regex_mail.test(username)) {//用户名格式验证 layer.msg('用户名格式不正确', { time: 1000 }) } else if (!regex_psw.test(password)) {//密码格式验证 layer.msg('密码格式不正确', { time: 1000 }) } else if (password !== confirm) {//确认密码验证 layer.msg('两次密码输入不一致', { time: 1000 }) } else if (inputcode !== vercode) {//验证码验证 layer.msg('验证码不正确', { time: 1000 }) vercode = verifyCode('#canvas-vercode', 120, 40); } else { //2. 注册验证 $.post("/user/register/check", { username: username }, function (data) { if (data.code === 400) {//已注册 layer.msg('账号已注册', { icon: 2, time: 1000 }) } else if (data.code === 200) {//未注册 $.post("/user/register", { username: username, password: password }, function (data) { if (data.code === 200) { layer.msg('注册成功,欢迎登录', { icon: 1, time: 1000 }, function () { const index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引 parent.layer.close(index); //再执行关闭 }) } else { layer.msg('注册失败', { icon: 2, time: 1000 }) } }, "json") } }, "json") } }) /********************************* 院校注册 ***********************************/ //信息初始化 $.get("/uni/all", function (data) { $.each(data, function (i, value) { $("#select-official-name").append('<option value="' + value.code + '">' + '(' + value.code + ') ' + value.name + '</option>'); }) form.render('select', 'test'); }, "json") //注册 $("#btn-submit-2").click(function () { let officialCode = $("#select-official-name option:selected").val(), license1 = $("#license-1").val(), license2 = $("#license-2").val(), license3 = $("#license-3").val(), license4 = $("#license-4").val(), psw = $("#input-official-password").val(), confirm = $("#input-official-confirm").val(); if (officialCode === '' || license1 === '' || license2 === '' || license3 === '' || license4 === '' || psw === '' || confirm === '') { layer.msg('请将注册信息填写完整', { time: 2000 }) } else if (!regex_psw.test(psw)) {//密码格式校验 layer.msg('密码格式不正确', { time: 2000 }) } else if (psw !== confirm) {//确认密码校验 layer.msg('两次密码输入不一致', { time: 2000 }) } else { $.post("/official/register/check", { code: officialCode, license: license1 + license2 + license3 + license4 }, function (data) { if (data.code === 200) { $.post("/official/register", { code: officialCode, password: psw, }, function (data) { if (data.code === 200) { layer.msg(data.msg, { icon: 1, time: 1000 }, function () { const index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引 parent.layer.close(index); //再执行关闭 }) } else { layer.msg(data.msg, { icon: 2, time: 1000 }) } }, "json") } else if (data.code === 400) { layer.msg(data.msg, { time: 2000 }) } }, "json") } }) }) </script> </body> </html>
class HashTable<T = any> { //创建一个数组,用来存放链地址中的链(数组) storage: [string, T][][] = []; //定义数组的长度 private length: number = 7 //记录已经存放元素的个数 private count: number = 0 /** * 哈希函数,将key映射称index * @param key 转换的key * @param max 数组的长度(最大的数值) * @returns 索引值 */ private hashFunc (key: string, max: number): number { //1.计算hashCode cats=>60337(27为底的时候) let hashCode = 0 const length = key.length for (let i = 0; i < length; i++) { //霍纳法则计算hashCode //charCode(i)是拿到i位置的code值 hashCode = 31 * hashCode + key.charCodeAt(i) } //求出索引值 const index = hashCode % max return index } /** * 传入一个数字,判断是否是质数 * @param number 要判断是数字 * @returns 是否是一个质数 */ isPrime (number: number): boolean { if (number === 1) return false for (let i = 2; i < number; i++) { if (number % i == 0) { return false } } return true } /** * 传入新的质数 * @param number 传入的数字 * @returns 返回新的质数 */ private getNextPrime (number: number): number { let newPrime = number while (!this.isPrime(number)) { newPrime++ } return newPrime } //扩容或者缩容操作 private resize (newLength: number) { //判断newlength是否是质数 this.length = this.getNextPrime(newLength) //设置新长度 //获取原来所有的数据,并且重新放人到新的容量数组中 //1.对数据今昔初始化 const oldStorage = this.storage this.storage = [] this.count = 0 // 2.获取原来数据,放入新扩容的数组中 oldStorage.forEach(bucket => { if (!bucket) return for (let i = 0; i < bucket.length; i++) { const tuple = bucket[i] this.put(tuple[0], tuple[1]) } }) } //插入/修改 put (key: string, value: T) { //1.根据key获取数组中对应的索引值 const index = this.hashFunc(key, this.length) //2.取出索引值对应位置的数组(桶) let bucket = this.storage[index] // 3.判断bucket是否有值 if (!bucket) { bucket = [] this.storage[index] = bucket } //4.确定已经有了一个数组,但是数组中是否已经存在key不确定 let isUpdate = false for (let i = 0; i < bucket.length; i++) { const tuple = bucket[i] const tupleKey = tuple[0] if (tupleKey === key) { //修改/更新操作 tuple[1] = value isUpdate = true } } //5.如果上面的代码没有进行覆盖,那么就在这里添加 if (!isUpdate) { bucket.push([key, value]) this.count++ //发现loadFactor比例大于0.75就直接扩容 const loadFactor = this.count / this.length if (loadFactor > 0.75) { this.resize(this.length * 2) } } } //用key来获取对应的value值 get (key: string): T | undefined { //1.获取key通过哈希函数生成对应的index const index = this.hashFunc(key, this.length) // 2.获取bucket,就是数组里面的数组 const bucket = this.storage[index] if (bucket === undefined) return undefined //3.对bucket遍历 for (let i = 0; i < bucket.length; i++) { const tuple = bucket[i] const tupleKey = tuple[0] const tupleValue = tuple[1] if (tupleKey === key) { // return tupleValue } } return undefined } // 删除操作 delete (key: string): T | undefined { //1.获取key通过哈希函数生成对应的index const index = this.hashFunc(key, this.length) // 2.获取bucket,就是数组里面的数组 const bucket = this.storage[index] if (bucket === undefined) return undefined //3.对bucket遍历 for (let i = 0; i < bucket.length; i++) { const tuple = bucket[i] const tupleKey = tuple[0] const tupleValue = tuple[1] if (tupleKey === key) { //从i的位置删除一个 bucket.splice(i, 1) this.count-- //发现loadFactor比例小于0.25就直接扩容 const loadFactor = this.count / this.length if (loadFactor < 0.25 && this.length > 7) { this.resize(Math.floor(this.length / 2)) } return tupleValue } } return undefined } } const hashTable = new HashTable(); hashTable.put("aaa", 100) hashTable.put("ccc", 200) hashTable.put("ddd", 300) hashTable.put("eee", 400) // hashTable.put("fff", 500) // hashTable.put("ggg", 500) // hashTable.put("hhh", 500) // hashTable.put("jhg", 500) // hashTable.put("sadf", 500) console.log(hashTable.storage); export default HashTable
/* * Wave, containers provisioning service * Copyright (c) 2023, Seqera Labs * * 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, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 <https://www.gnu.org/licenses/>. */ package io.seqera.wave.service.aws import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import java.util.regex.Pattern import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheLoader import com.google.common.cache.LoadingCache import com.google.common.util.concurrent.UncheckedExecutionException import groovy.transform.Canonical import groovy.transform.CompileStatic import groovy.util.logging.Slf4j import io.seqera.wave.util.StringUtils import jakarta.inject.Singleton import software.amazon.awssdk.auth.credentials.AwsBasicCredentials import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.ecr.EcrClient import software.amazon.awssdk.services.ecr.model.GetAuthorizationTokenRequest import software.amazon.awssdk.services.ecrpublic.model.GetAuthorizationTokenRequest as GetPublicAuthorizationTokenRequest import software.amazon.awssdk.services.ecrpublic.EcrPublicClient /** * Implement AWS ECR login service * * @author Paolo Di Tommaso <paolo.ditommaso@gmail.com> */ @Slf4j @Singleton @CompileStatic class AwsEcrService { static final private Pattern AWS_ECR_PRIVATE = ~/^(\d+)\.dkr\.ecr\.([a-z\-\d]+)\.amazonaws\.com/ static final private Pattern AWS_ECR_PUBLIC = ~/public\.ecr\.aws/ @Canonical private static class AwsCreds { String accessKey String secretKey String region boolean ecrPublic } @Canonical static class AwsEcrHostInfo { String account String region } private CacheLoader<AwsCreds, String> loader = new CacheLoader<AwsCreds, String>() { @Override String load(AwsCreds creds) throws Exception { return creds.ecrPublic ? getLoginToken1(creds.accessKey, creds.secretKey, creds.region) : getLoginToken0(creds.accessKey, creds.secretKey, creds.region) } } private LoadingCache<AwsCreds, String> cache = CacheBuilder<AwsCreds, String> .newBuilder() .maximumSize(10_000) .expireAfterWrite(3, TimeUnit.HOURS) .build(loader) private EcrClient ecrClient(String accessKey, String secretKey, String region) { EcrClient.builder() .region( Region.of(region)) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) .build() } private EcrPublicClient ecrPublicClient(String accessKey, String secretKey, String region) { EcrPublicClient.builder() .region( Region.of(region)) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) .build() } protected String getLoginToken0(String accessKey, String secretKey, String region) { log.debug "Getting AWS ECR auth token - region=$region; accessKey=$accessKey; secretKey=${StringUtils.redact(secretKey)}" final client = ecrClient(accessKey,secretKey,region) final resp = client.getAuthorizationToken(GetAuthorizationTokenRequest.builder().build() as GetAuthorizationTokenRequest) final encoded = resp.authorizationData().get(0).authorizationToken() return new String(encoded.decodeBase64()) } protected String getLoginToken1(String accessKey, String secretKey, String region) { log.debug "Getting AWS ECR public auth token - region=$region; accessKey=$accessKey; secretKey=${StringUtils.redact(secretKey)}" final client = ecrPublicClient(accessKey,secretKey,region) final resp = client.getAuthorizationToken(GetPublicAuthorizationTokenRequest.builder().build() as GetPublicAuthorizationTokenRequest) final encoded = resp.authorizationData().authorizationToken() return new String(encoded.decodeBase64()) } /** * Get AWS ECR login token * * @param accessKey The AWS access key * @param secretKey The AWS secret key * @param region The AWS region * @return The ECR login token. The token is made up by the aws username and password separated by a `:` */ String getLoginToken(String accessKey, String secretKey, String region, boolean isPublic) { assert accessKey, "Missing AWS accessKey argument" assert secretKey, "Missing AWS secretKet argument" assert region, "Missing AWS region argument" try { // get the token from the cache, if missing the it's automatically // fetch using the AWS ECR client return cache.get(new AwsCreds(accessKey,secretKey,region,isPublic)) } catch (UncheckedExecutionException | ExecutionException e) { throw e.cause } } /** * Parse AWS ECR host name and return a pair made of account id and region code * * @param host * The ECR host name e.g. {@code 195996028523.dkr.ecr.eu-west-1.amazonaws.com} * @return * A pair holding the AWS account Id as first element and the AWS region as second element. * If the value provided is not a valid ECR host name the {@code null} is returned */ AwsEcrHostInfo getEcrHostInfo(String host) { if( !host ) return null final m = AWS_ECR_PRIVATE.matcher(host) if( m.find() ) return new AwsEcrHostInfo(m.group(1), m.group(2)) final n = AWS_ECR_PUBLIC.matcher(host) if( n.find() ) return new AwsEcrHostInfo(null, 'us-east-1') return null } static boolean isEcrHost(String registry) { registry ? AWS_ECR_PRIVATE.matcher(registry).find() || AWS_ECR_PUBLIC.matcher(registry).find() : false } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Create Room</title> <!-- Bootstrap CSS link --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="..." crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" th:fragment="header"> <!-- Navigation bar --> <!-- ... --> </nav> <br /> <div class="container"> <div class="row col-md-8 offset-md-2"> <div class="card"> <div class="card-header"> <h2 class="text-center">Find a room</h2> </div> <div class="card-body"> <!-- Room creation form --> <form th:action="@{/filterrooms}" method="post"> <div class="form-group mb-3"> <label class="form-label">Capacity</label> <input class="form-control" name="capacity" type="number" /> </div> <div class="form-check mb-3"> <input class="form-check-input" type="checkbox" name="hasWhiteboard" id="hasWhiteboard"> <label class="form-check-label" for="hasWhiteboard">Has Whiteboard</label> </div> <div class="form-check mb-3"> <input class="form-check-input" type="checkbox" name="hasProjector" id="hasProjector" /> <label class="form-check-label" for="hasProjector">Need Projector</label> </div> <div class="form-check mb-3"> <input class="form-check-input" type="checkbox" name="hasConferenceCall" id="hasConferenceCall" /> <label class="form-check-label" for="hasConferenceCall">Need Conference Call</label> </div> <div class="form-group mb-3"> <button class="btn btn-primary" type="submit">Search for rooms</button> </div> </form> <!-- Display filtered rooms --> <!-- Display filtered rooms --> <!-- Display filtered rooms --> <div th:if="${filteredRooms != null and not #lists.isEmpty(filteredRooms)}"> <h2 class="text-center">Found Rooms</h2> <table class="table"> <thead> <tr> <th>Room Name</th> <th>Capacity</th> <th>Actions</th> <!-- Add a new column for actions --> </tr> </thead> <tbody> <!-- Iterate over filteredRooms and display room information --> <tr th:each="room : ${filteredRooms}"> <td th:text="${room.name}"></td> <td th:text="${room.capacity}"></td> <td> <!-- Fix the syntax for constructing the URL with room.id --> <a th:href="@{'/bookroom/' + ${room.room_id}}" class="btn btn-primary">Reserve Room</a> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </body> </html>
"use server"; import { revalidatePath } from "next/cache"; import Product from "../models/product.model"; import { connectToDB } from "../mongoose"; import { scrapeAmazonProduct } from "../Scraper"; import { getAveragePrice, getHighestPrice, getLowestPrice } from "../utils"; import { User } from "@/types"; import genrateEmailBody from "../Nodemailer"; export async function scrapeAndStoreProduct(productUrl: string) { if (!productUrl) return; try { connectToDB(); const scrapedProduct = await scrapeAmazonProduct(productUrl); if (!scrapedProduct) return; let product = scrapedProduct; const existingProduct = await Product.findOne({ url: scrapedProduct.url }).maxTimeMS(30000);; if (existingProduct) { const updatedPriceHistory: any = [ ...existingProduct.priceHistory, { price: scrapedProduct.currentPrice }, ]; product = { ...scrapedProduct, priceHistory: updatedPriceHistory, lowestPrice: getLowestPrice(updatedPriceHistory), highestPrice: getHighestPrice(updatedPriceHistory), averagePrice: getAveragePrice(updatedPriceHistory), }; } const newProduct = await Product.findOneAndUpdate( { url: scrapedProduct.url }, product, { upsert: true, new: true } ); revalidatePath(`/products/${newProduct._id}`); } catch (error: any) { throw new Error(`Failed to create/update product: ${error.message}`); } } export async function getProductById(productId: string) { try { connectToDB(); const product = await Product.findOne({ _id: productId }); if (!product) return null; return product; } catch (error) { console.log(error); } } export async function getAllProducts(){ try{ connectToDB(); const products = await Product.find(); return products; }catch(error){ console.log(error); } } export async function getSimilarProducts(productId: string){ try{ connectToDB(); const currentProduct = await Product.findById(productId); if(!currentProduct) return null const similarProduct = await Product.find({_id:{$ne: productId}}).limit(3) return similarProduct; }catch(err){ console.log(err); } } export async function addUserEmailToProduct(productId: string, email: string) { try { const product = await Product.findById(productId); if (!product) return; const userExists = product.users.some((user: User) => user.email === userEmail); await product.save(); const emailContent = genrateEmailBody(product, "Welcome"); await sendEmail(emailContent, [userEmail]); } catch (error) { console.log(error); } } function genrateEmailBody(product: any, arg1: string): any { throw new Error("Function not implemented."); }
from pathlib import Path from libcst import parse_module, CSTNode, CSTVisitor, Call # 定义一个访问器来查找特定模式 class CustomAnalyzer(CSTVisitor): def __init__(self): super().__init__() # 调用父类的构造函数 self.function_calls = [] def visit_Call(self, node: "Call") -> None: # 检查是否是函数调用 if isinstance(node.func, CSTNode): self.function_calls.append(node.func) super().visit_Call(node) # 调用父类的方法 def analyze_flask_codebase(flask_repo_path, output_file): with open(output_file, 'w', encoding='utf-8') as output: # 遍历 Flask 代码库中的所有 Python 文件 for python_file in flask_repo_path.glob("**/*.py"): with python_file.open("r", encoding="utf-8") as file: try: # 尝试解析当前文件 module = parse_module(file.read()) # 初始化自定义分析器 analyzer = CustomAnalyzer() module.visit(analyzer) # 输出分析结果到文件 output.write(f"File analyzed: {python_file}\n") output.write(f"Function calls found: {analyzer.function_calls}\n") output.write("\n") except Exception as e: output.write(f"Error analyzing {python_file}: {e}\n") def main(): # Flask 代码库的根目录 flask_repo_path = Path("./flask-main") output_file = "call_result.txt" analyze_flask_codebase(flask_repo_path, output_file) if __name__ == "__main__": main()
//DobreaMariusDorian2127lab6pb3 package Problema3; interface Int1{ int a=0; int b=0; static void sum(int a,int b) { } //prototip de metoda } package Problema3; interface Int2{ double a=0; double b=0; static void product(double a,double b) { }; //prototip de metoda } package Problema3; public class Class1 implements Int1 { protected double a,b; Class1(int a,int b){ this.a = a; this.b = b; System.out.print("Constructor cu parametrii de tip int :"+"a="+a+"\n b="+b); } Class1(double a,double b){ this.a = a; this.b = b; System.out.print("Constructor cu parametrii: "+"\n a="+a+"\n b="+b); } public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } } package Problema3; import Problema3.Int1; import Problema3.Int2; import java.util.Scanner; import Problema3.Class1; public class Class2 extends Class1 implements Int1, Int2 { Class2( int a, int b) { super(a, b); // TODO Auto-generated constructor stub } Class2( double a, double b) { super(a, b); // TODO Auto-generated constructor stub } public static void sum(int a,int b){ int c= a+b; System.out.println("\n Suma celor doua numere este: "+c); } public static void product(double a, double b) { double c= a*b; System.out.println("\nProdusul celor doua numere este: "+String.format("%.3f", c)); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("a="); int a = sc.nextInt(); System.out.println("b="); int b = sc.nextInt(); Class2 obiect = new Class2(a,b); obiect.sum(a,b); System.out.println("x="); double x = sc.nextDouble(); System.out.println("y="); double y = sc.nextDouble(); Class2 obiect2 = new Class2(x,y); obiect2.product(x,y); } }
class UsersController < ApplicationController before_action :load_user, :logged_in_user, except: %i(index new create) before_action :correct_user, only: %i(edit update) def index @users = User.load_user.paginate page: params[:page], per_page: Settings.user.per_page end def new @user = User.new end def create @user = User.new user_params if @user.save @user.send_activation_email flash[:info] = t "users.activate_email" redirect_to root_url else render :new end end def show; end def edit; end def update if @user.update_attributes user_params flash[:success] = t "users.user_update_success" redirect_to @user else render :edit end end private def user_params params.require(:user).permit :name, :email, :address, :password, :password_confirmation end def correct_user redirect_to root_path unless current_user? @user end end
#pragma once #include <queue> #include "./cell_point.hpp" namespace Algorithms { // Pair of distance and CellPoint that will be stored in the priority queue. typedef std::pair<int, Algorithms::CellPoint> DistanceCell; class DistanceCellComparator { public: bool operator() (DistanceCell a, DistanceCell b) { // In case the 'a' has greater distance from the starting node than 'b'. Then we want it to come latter in the priority queue, after the 'b'. // We return true, because if we would use < instead and return it then, we would keep getting the pairs with the maximum distance. // That is because by default the priority queue is maximum priority queue, and it thinks that we will use the <. // If you want to find the longest distance instead of the shortest, then change this to <. return (a.first > b.first); } }; // Custom Priority Queue. typedef std::priority_queue<DistanceCell, std::vector<DistanceCell>, DistanceCellComparator> DistanceQueue; }
import classnames from 'classnames' import { forwardRef } from 'react' type EntryIndicatorProps = { focused: boolean onMouseEnter: () => void onClick: () => void children: React.ReactNode } const EntryIndicator = forwardRef<HTMLDivElement, EntryIndicatorProps>( ({ focused, onMouseEnter, onClick, children }, ref) => { return ( /* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */ <div ref={ref} className={classnames('rp-entry-indicator', { 'rp-entry-indicator-focused': focused, })} onClick={onClick} onMouseEnter={onMouseEnter} > {children} </div> ) } ) EntryIndicator.displayName = 'EntryIndicator' export default EntryIndicator
import { TbLocationFilled } from "react-icons/tb"; import { BsFillBookmarkFill } from "react-icons/bs"; import { AiOutlineFileDone } from "react-icons/ai"; import Tag from "./Tag/GreyTag"; import { useDispatch, useSelector } from "react-redux"; import { setJobdetails } from "../redux/JobDetailsSlice"; import BlueTag from "./Tag/BlueTag"; import { useNavigate } from "react-router-dom"; import GreyTag from "./Tag/GreyTag"; import { setBookmark } from "../redux/BookmarkedJobSlice"; import { setAppliedJobs } from "../redux/AppliedJobSlice"; const JobCard = ({ jobDetails, isBookmarked ,isApplied}) => { const dispatch = useDispatch(); const navigate = useNavigate(); // console.log(jobDetails) // console.log(jobDetails); const jobDetailsLocal = { jobTitle: jobDetails?.job_title, employerLogo: jobDetails?.employer_logo, employerName: jobDetails?.employer_name, publisher: jobDetails?.job_publisher, jobCity: jobDetails?.job_city, jobIsRemote: jobDetails?.job_is_remote, jobEmploymentTitle: jobDetails?.job_employment_type, skills: jobDetails?.job_required_skills, experience: jobDetails?.job_required_experience, education: jobDetails?.job_required_education, postedOn: jobDetails?.job_publisher, applyLink: jobDetails?.job_apply_link, }; const handleClick = () => { dispatch(setJobdetails(jobDetails)); const windowWidth = window.innerWidth; windowWidth < 1024 && navigate(`/jobDetails/${jobDetails?.job_id}`); }; // const dataExists34 = localStorage.getItem("careerPlus_bookmarked"); // console.log(JSON.parse(dataExists34)); const handleBookMarkClick = () => { const dataExists = localStorage.getItem("careerPlus_bookmarked"); if (dataExists) { // If user has already bookmarked jobs before -> // 1. If this job is already bookmarked then remove it from bookmark list // 2. If it is not bookmarked , then add it to bookmark list const temp = JSON.parse(dataExists); let bookmarkedJobs = temp?.bookmarkedJobs; if (isBookmarked) { // If job is already bookmarked , remove it from list let jobDetailsUpdated1 = bookmarkedJobs.filter( (jobDetailsTemp) => jobDetailsTemp.job_id !== jobDetails?.job_id ); const updatedTemp1 = { bookmarkedJobs: jobDetailsUpdated1, }; localStorage.setItem( "careerPlus_bookmarked", JSON.stringify(updatedTemp1) ); } else { // If job is not bookmarked , add it to the list let jobDetailsUpdated2 = [...bookmarkedJobs, jobDetails]; const updatedTemp2 = { bookmarkedJobs: jobDetailsUpdated2, }; localStorage.setItem( "careerPlus_bookmarked", JSON.stringify(updatedTemp2) ); } } else { const temp = { bookmarkedJobs: [jobDetails], }; localStorage.setItem("careerPlus_bookmarked", JSON.stringify(temp)); } const dataExists2 = localStorage.getItem("careerPlus_bookmarked"); console.log(JSON.parse(dataExists2)); dispatch(setBookmark(JSON.parse(dataExists2))); console.log(JSON.parse(dataExists2)); }; const handleAppliedClick = () => { const dataExists = localStorage.getItem("careerPlus_applied"); if (dataExists) { // If user has already bookmarked jobs before -> // 1. If this job is already bookmarked then remove it from bookmark list // 2. If it is not bookmarked , then add it to bookmark list const temp = JSON.parse(dataExists); let appliedJobs = temp?.appliedJobs; if (isApplied) { // If job is already bookmarked , remove it from listisBookmarked let jobDetailsUpdated1 = appliedJobs.filter( (jobDetailsTemp) => jobDetailsTemp.job_id !== jobDetails?.job_id ); const updatedTemp1 = { appliedJobs: jobDetailsUpdated1, }; localStorage.setItem( "careerPlus_applied", JSON.stringify(updatedTemp1) ); } else { // If job is not bookmarked , add it to the list let jobDetailsUpdated2 = [...appliedJobs, jobDetails]; const updatedTemp2 = { appliedJobs: jobDetailsUpdated2, }; localStorage.setItem( "careerPlus_applied", JSON.stringify(updatedTemp2) ); } } else { const temp = { appliedJobs: [jobDetails], }; localStorage.setItem("careerPlus_applied", JSON.stringify(temp)); } const dataExists2 = localStorage.getItem("careerPlus_applied"); console.log(JSON.parse(dataExists2)); dispatch(setAppliedJobs(JSON.parse(dataExists2))); console.log(JSON.parse(dataExists2)); }; return ( <div className=" border w-[100%] rounded-xl px-4 py-4 font-lato cursor-pointer" onClick={handleClick} > {/* 1.Head */} <div className="flex flex-col gap-2 max-md:gap-1 mb-2"> {/* 1.1.Job Title */} <div className="font-extrabold text-[20px] max-md:text-[18px] opacity-75 flex justify-between items-center"> {/* 1.1.1 Job Title */} <p>{jobDetailsLocal.jobTitle}</p> {/* 1.1.2 Save & Applied Button */} <div className="flex gap-3 "> <BsFillBookmarkFill onClick={(e) => { e.stopPropagation(); handleBookMarkClick(); }} className={`${isBookmarked && "text-[#0071BD]"} `} /> <AiOutlineFileDone size={25} onClick={(e) => { e.stopPropagation(); handleAppliedClick(); }} className={`${isApplied && "text-[#0071BD]"} `} /> </div> </div> {/* 1.2.Company Logo & Name */} <div className="flex items-center gap-4 w-full text-[18px] max-md:text-[16px]"> {/* {jobDetailsLocal.employerLogo && ( <img src={jobDetailsLocal.employerLogo} alt="" className="w-[15%]" /> )} */} <p className="opacity-75 ">{jobDetailsLocal.employerName}</p> </div> {/* 1.3.Location & postedOn tag*/} <div className="flex justify-between items-center"> <div> {(jobDetailsLocal?.jobCity || jobDetailsLocal?.jobIsRemote || jobDetails?.job_state || jobDetails?.job_country) && ( <div className="flex items-center gap-1 text-[16px] max-md:text-[14px] opacity-75"> <TbLocationFilled /> <p> {jobDetailsLocal.jobIsRemote && "Remote "} {jobDetails?.job_city || jobDetails?.job_state || jobDetails?.job_country} </p> </div> )} </div> <div> <BlueTag tagTitle={jobDetailsLocal?.publisher} /> </div> </div> </div> <hr /> {/* 2.Body */} <div className="mt-2 flex flex-col gap-2 max-md:gap-1"> {/* 2.1.Employment Type */} <div className=""> <GreyTag tagTitle={jobDetailsLocal.jobEmploymentTitle} /> </div> {/* 2.2.Skills */} {jobDetailsLocal.skills && ( <div className="flex gap-2"> <span className="text-[17px] opacity-75 font-[600]">Skills: </span> <div className="flex flex-wrap gap-2"> {jobDetailsLocal.skills?.map((skill, i) => ( <div key={i}> <GreyTag tagTitle={skill} /> </div> ))} </div> </div> )} {/* 2.3.Experience */} {jobDetailsLocal?.experience?.required_experience_in_months && ( <div className="text-[17px]"> <span className="opacity-75 font-[600]">Experience : </span> <span className="opacity-75"> {jobDetailsLocal.experience.required_experience_in_months / 12}{" "} years </span> </div> )} </div> </div> ); }; export default JobCard;
package com.guroomsoft.icms.biz.code.service; import com.guroomsoft.icms.biz.code.dao.ItemDAO; import com.guroomsoft.icms.biz.code.dto.Item; import com.guroomsoft.icms.biz.code.dto.ItemReq; import com.guroomsoft.icms.common.exception.CDatabaseException; import com.guroomsoft.icms.sap.JcoClient; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Slf4j @Service @RequiredArgsConstructor public class ItemService { private static String RFC_NAME = "ZMM_ICMS_EXPORT_MASTER_S"; // 품목 I/F private static String RFC_IN_PLANTS = "I_WERKS"; // RFC IMPORT 플랜트 코드 목록 private static String RFC_TABLE_NAME = "T_HEADER"; // RFC TABLE NAME private final JcoClient jcoClient; private final ItemDAO itemDAO; /** * 품목 목록 * @param cond * @return */ @Transactional(readOnly = true) public List<Item> findItem(ItemReq cond) throws Exception { try { List<Item> resultSet = itemDAO.selectItem(cond); return resultSet; } catch (Exception e) { log.error(e.getMessage()); throw new CDatabaseException(); } } @Transactional(readOnly = true) public int getTotalItemCount(ItemReq cond) throws Exception { try { return itemDAO.getTotalItemCount(cond); } catch (Exception e) { log.error(e.getMessage()); throw new CDatabaseException(); } } public int downloadItemFromSap(LinkedHashMap<String, Object> params, Long reqUserUid) throws Exception { try { jcoClient.getFunction(RFC_NAME); LinkedHashMap<String, Object> impParams = new LinkedHashMap<>(); if (params.containsKey("plantCd")) { impParams.put(RFC_IN_PLANTS, params.get("plantCd")); // 공급업체코드 } log.info(impParams.toString()); jcoClient.setImportParam(impParams); jcoClient.runRunction(); ArrayList<Map<String, Object>> dataSet = jcoClient.getTable(RFC_TABLE_NAME); // convert to object list ArrayList<Item> dataRows = convertToItem(dataSet); // save DB return loadToDB(dataRows, reqUserUid); } catch (Exception e) { log.error("👉 Fail to get jco function"); log.error(e.getMessage()); } return 0; } public ArrayList<Item> convertToItem(ArrayList<Map<String, Object>> dataSet) { if (dataSet == null || dataSet.isEmpty()) { return null; } ArrayList<Item> resultList = new ArrayList<>(); for (Map<String, Object> dataItem : dataSet) { Item dataRow = new Item(); dataRow.setIfSeq((String)dataItem.get("ZIFSEQ")); // 인터페이스 번호 S0000000000000000075 dataRow.setIfType(StringUtils.defaultString((String)dataItem.get("ZIFTYPE"))); // 인터페이스 유형 TEST dataRow.setPlantCd((String)dataItem.get("WERKS")); // 플랜트 코드 dataRow.setItemNo((String)dataItem.get("MATNR")); // 자재번호 dataRow.setItemNm((String)dataItem.get("MAKTX")); // 자재내역 dataRow.setUnit((String)dataItem.get("MEINS")); // 기본단위 dataRow.setCarModel((String)dataItem.get("ZZPRJT")); // 차종 dataRow.setUseAt((String)dataItem.get("ZUSEID")); // 사용여부 dataRow.setIfResult(StringUtils.defaultString((String)dataItem.get("ZIF_RESULT"))); // 메시지 유형 S : 성공 / E : 오류 dataRow.setIfMessage(StringUtils.defaultString((String)dataItem.get("ZIF_MESSAGE"))); // 메시지 resultList.add(dataRow); } return resultList; } public int loadToDB(ArrayList<Item> dataRows, Long reqUserUid) { int totalUpdated = 0; Long userUid = 1L; if (reqUserUid != null) { userUid = reqUserUid; } for (Item item : dataRows) { int t = 0; try { item.setRegUid(userUid); // 유효성 체크 if (StringUtils.isBlank(item.getPlantCd()) || StringUtils.isBlank(item.getItemNo()) || StringUtils.isBlank(item.getItemNm()) ) { log.debug(">>> SKIP {}", item.toString() ); continue; } log.debug(item.toString()); int updated = itemDAO.mergeItem2(item); if (updated > 0) { totalUpdated++; } } catch (Exception e1) { log.error("👉 fail to save {}", item); } } return totalUpdated; } }
module App exposing (..) import Html exposing (Html, beginnerProgram, div, button, text) import Html.Events exposing (onClick) type alias Model = Int model : Model model = 0 type Msg = Increment | Decrement update : Msg -> Model -> Model update msg model = case msg of Increment -> model + 1 Decrement -> model - 1 view : Model -> Html Msg view model = div [] [ button [ onClick Decrement ] [ text "-" ] , div [] [ text (toString model) ] , button [ onClick Increment ] [ text "+" ] ] main : Program Never Model Msg main = beginnerProgram { model = model, view = view, update = update }
package com.javiersan.prueba.controllers; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties.Pageable; import org.springframework.dao.DataAccessException; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import com.javiersan.prueba.exceptions.NaveNotFoundException; import com.javiersan.prueba.models.entity.Nave; import com.javiersan.prueba.models.service.INaveService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @CrossOrigin(origins = {"http://localhost:4200"}) @RestController @RequestMapping("/api") @Api(value = "Controlador Naves", description = "Esta API tiene un CRUD para naves") public class NavesRestController { protected final Log logger = LogFactory.getLog(this.getClass()); @Autowired private INaveService naveService; @Secured({"ROLE_USER"}) @RequestMapping(value = "/listar", method = RequestMethod.GET) @ApiOperation(value = "Lista todas las naves", notes = "retorna un listado paginado de todas las naves") public String indice(@RequestParam(name = "page", defaultValue = "0") int page, Model model) { Pageable pageRequest = pageRequest.of(page, 4); Page<Nave> naves = naveService.findAll(pageRequest); PageRender<Nave> pageRender = new PageRender<Nave>("/listar", naves); model.addAttribute("titulo", "Listado de naves"); model.addAttribute("naves", naves); model.addAttribute("page", pageRender); return "listar"; } @Secured({"ROLE_USER"}) @GetMapping("/naves/{id}") @ApiOperation(value = "busca una nave por su id", notes = "retorna la nave con el id indicado") public ResponseEntity<?> mostrar(@PathVariable Long id) { Nave nave = naveService.findById(id).orElseThrow( () -> new NaveNotFoundException("Error, la nave no exite")); return new ResponseEntity<Nave>(nave,HttpStatus.OK); } @GetMapping(value = "/nave/{term}", produces = { "application/json" }) @ApiOperation(value = "Busca las naves que coincidan con el término dado", notes = "retorna en el body una lista de las naves que contienen ese término ") public @ResponseBody List<Nave> cargarNaves(@PathVariable String term) { return naveService.findByName(term); } @Secured("ROLE_ADMIN") @PostMapping("/naves") @ApiOperation(value = "Crea una nave nueba en la base de datos", notes = "retorna un objeto con la response y el httpStatus correspondiente") public ResponseEntity<?> crear(@Valid @PathVariable Nave nave, BindingResult result) { Nave naveNueva = null; Map<String, Object> respuesta = new HashMap<>(); if(result.hasErrors()) { List<String> errors = result.getFieldErrors() .stream() .map(err -> { return "El campo '" + err.getField() +"' " + err.getDefaultMessage(); }) .collect(Collectors.toList()); respuesta.put("errors", errors); return new ResponseEntity<Map<String,Object>>(respuesta, HttpStatus.BAD_REQUEST); } naveNueva = naveService.save(nave); respuesta.put("mensaje", "La nave ha sido creado con éxito!"); respuesta.put("nave", naveNueva); return new ResponseEntity<Map<String,Object>>(respuesta, HttpStatus.CREATED); } @Secured("ROLE_ADMIN") @PutMapping("/naves/{id}") @ApiOperation(value = "Editar unna nave de la base de datos", notes = "retorna retorna un objeto con la response y el httpStatus correspondiente ") public ResponseEntity<?> editar(@Valid @RequestParam Nave nave, BindingResult result, @PathVariable Long id) { Nave naveActual = naveService.findById(id); Nave naveEditada = null; Map<String, Object> respuesta = new HashMap<>(); if(result.hasErrors()) { List<String> errors = result.getFieldErrors() .stream() .map(err -> { return "El campo '" + err.getField() +"' " + err.getDefaultMessage(); }) .collect(Collectors.toList()); respuesta.put("errors", errors); return new ResponseEntity<Map<String,Object>>(respuesta, HttpStatus.BAD_REQUEST); } naveActual.setNombre(nave.getNombre()); naveActual.setModelo(nave.getModelo()); naveActual.setCreateAt(nave.getCreateAt()); naveEditada = naveService.save(naveActual); respuesta.put("mensaje", "La nave ha sido actualizada con éxito!"); respuesta.put("nave", naveEditada); return new ResponseEntity<Map<String,Object>>(respuesta, HttpStatus.CREATED); } @Secured("ROLE_ADMIN") @DeleteMapping("/naves/{id}") @ApiOperation(value = "Borra la nave con id pasado por usuario de la base de datos", notes = "retorna una response y el httpStatus correspondiente") public ResponseEntity<?> eliminar(@PathVariable Long id) { Map<String, Object> respuesta = new HashMap<>(); naveService.delete(id); respuesta.put("mensaje", "La nave ha sido eliminada con éxito!"); return new ResponseEntity<Map<String,Object>>(respuesta, HttpStatus.OK); } }
import { ApolloClient, ApolloLink, InMemoryCache, NormalizedCacheObject } from "@apollo/client"; import { onError } from "@apollo/client/link/error"; import { createUploadLink } from "apollo-upload-client"; import { useMemo } from "react"; let apolloClient: ApolloClient<NormalizedCacheObject>; const createApolloClient = (): ApolloClient<NormalizedCacheObject> => { // Define link for error handling const errorLink = onError(({ graphQLErrors, networkError }) => { // Only developers should see these error messages if (import.meta.env.PROD) return; if (graphQLErrors) { graphQLErrors.forEach(({ message, locations, path }) => { console.error("GraphQL error occurred"); console.error(`Path: ${path}`); console.error(`Location: ${locations}`); console.error(`Message: ${message}`); }); } if (networkError) { console.error("GraphQL network error occurred", networkError); } }); // Determine origin of API server let uri: string; // If running locally if (window.location.host.includes("localhost") || window.location.host.includes("192.168.0.")) { uri = `http://${window.location.hostname}:${import.meta.env.VITE_PORT_SERVER ?? "5330"}/api/v1`; } // If running on server else { uri = import.meta.env.VITE_SERVER_URL && import.meta.env.VITE_SERVER_URL.length > 0 ? `${import.meta.env.VITE_SERVER_URL}/v1` : `http://${import.meta.env.VITE_SITE_IP}:${import.meta.env.VITE_PORT_SERVER ?? "5330"}/api/v1`; } // Define link for handling file uploads const uploadLink = createUploadLink({ uri, credentials: "include", }); // Create Apollo client return new ApolloClient({ cache: new InMemoryCache(), link: ApolloLink.from([errorLink, uploadLink]), }); }; export const initializeApollo = (): ApolloClient<NormalizedCacheObject> => { const _apolloClient = apolloClient ?? createApolloClient(); if (!apolloClient) apolloClient = _apolloClient; return _apolloClient; }; export const useApollo = (): ApolloClient<NormalizedCacheObject> => { const store = useMemo(() => initializeApollo(), []); return store; };
import { useState, useEffect } from "react"; import { useLocation} from 'react-router-dom' import { Link } from "react-router-dom" import Trim from './trim.js'; import Card from '@mui/material/Card'; import CardContent from '@mui/material/CardContent'; import Typography from '@mui/material/Typography'; function ShowIndividualStudent() { const location = useLocation(); const student = new URLSearchParams(location.search).get("student") || "COMSCI"; const cohort = new URLSearchParams(location.search).get("cohort") || "COMSCI1"; const [modules, setModules] = useState([]); const [students, setStudents] = useState([]); const [grades, setGrades] = useState([]); const [isLoaded, setIsLoaded] = useState(false); useEffect(() => { if (students.length === 0) { fetch(`http://127.0.0.1:8000/api/student/${student}/`) .then((req) => req.json()) .then((data) => { setStudents(data); setIsLoaded(true); console.log(cohort); }) .catch((err) => console.log(err)); } }, [student]); useEffect(() => { console.log(cohort); }, [cohort]); useEffect(() => { if (modules.length === 0) { fetch(`http://127.0.0.1:8000/api/module/?delivered_to=${cohort} `) .then((req) => req.json()) .then((data) => { setModules(data); setIsLoaded(true); }) .catch((err) => console.log(err)); } }, [student]); useEffect(() => { if (grades.length === 0) { fetch(`http://127.0.0.1:8000/api/grade/?student=${student}`) .then((req) => req.json()) .then((data) => { setGrades(data); setIsLoaded(true); }) .catch((err) => console.log(err)); } }, [students]); if (!isLoaded) { return <p>Loading...</p>; } const DisplayGrades = () => { //if (!Array.isArray(facts)) { // return null; // or some other fallback element //} return grades.map((elem) => <Typography sx={{ mb: 1.5 }} color="text.secondary"> <ul> <li>Module: { Trim(elem.module)}</li> <li>Ca Mark: {elem.ca_mark} </li> <li>Exam Mark: { elem.exam_mark } </li> <li>Total Grade: { elem.total_grade }</li> </ul> </Typography> ); }; return <div> <div> <h1>{students.first_name} { students.last_name }</h1> <h2>Student ID: {students.student_id }</h2> <h2>Cohort: {cohort} </h2> <p1>Email: {students.email}</p1> <Link to={`/gradeform?student=${students.student_id}&cohort=${Trim(students.cohort)}`}> <p>Change students grade</p> </Link> </div> <div> <h2>Grades:</h2> <Card sx={{ minWidth: 275 }}> <CardContent> { DisplayGrades() } </CardContent> </Card> </div> </div>; } export default ShowIndividualStudent;
import React, { useEffect, useState } from 'react'; import { URL_ATTRIBUTE_KEY, PROJECT_ATTRIBUTE_KEY, TOKEN_ATTRIBUTE_KEY, } from 'components/constants'; const authTypeAttributesOptions = [{ value: 'OAUTH', label: 'ApiKey' }]; const DEFAULT_FORM_CONFIG = { authType: 'OAUTH', }; export const IntegrationFormFields = (props) => { const { initialize, disabled, initialData, ...extensionProps } = props; const { components: { FieldErrorHint, FieldElement, FieldText, Dropdown, FieldTextFlex }, validators: { requiredField, btsUrl, btsProjectKey, btsIntegrationName }, } = extensionProps; useEffect(() => { initialize(initialData); }, []); const [authTypeState, setAuthTypeState] = useState(!initialData[TOKEN_ATTRIBUTE_KEY]); const onChangeAuthTypeAttributesMode = (value) => { if (value === authTypeState) { return; } setAuthTypeState(value); if (!value) { props.change(TOKEN_ATTRIBUTE_KEY, ''); } }; return ( <> <FieldElement name="integrationName" label="Integration Name" validate={btsIntegrationName} disabled={disabled} isRequired > <FieldErrorHint provideHint={false}> <FieldText maxLength={55} defaultWidth={false} /> </FieldErrorHint> </FieldElement> <FieldElement name={URL_ATTRIBUTE_KEY} label="Link to BTS" validate={btsUrl} disabled={disabled} isRequired > <FieldErrorHint provideHint={false}> <FieldText defaultWidth={false} /> </FieldErrorHint> </FieldElement> <FieldElement name={PROJECT_ATTRIBUTE_KEY} label="Project key in BTS" validate={btsProjectKey} disabled={disabled} isRequired > <FieldErrorHint provideHint={false}> <FieldText maxLength={55} defaultWidth={false} /> </FieldErrorHint> </FieldElement> <FieldElement name="authType" disabled={disabled} label="Authorization type"> <FieldErrorHint provideHint={false}> <Dropdown disabled={disabled} value={authTypeState} onChange={onChangeAuthTypeAttributesMode} options={authTypeAttributesOptions} defaultWidth={false} /> </FieldErrorHint> </FieldElement> <FieldElement name={TOKEN_ATTRIBUTE_KEY} disabled={disabled} label="Token" validate={requiredField} isRequired > <FieldErrorHint provideHint={false}> <FieldTextFlex /> </FieldErrorHint> </FieldElement> </> ); }; IntegrationFormFields.defaultProps = { initialData: DEFAULT_FORM_CONFIG, };
### Codes to create Figure 1 in the article ################################################################################################################### ### This material is provided to the aims of reproducibility and replicability of the findings reported in the paper: ### Antonio Preti, Sara Siddi, Marcello Vellante, Rosanna Scanu, Tamara Muratore, Mersia Gabrielli, ### Debora Tronci, Carmelo Masala, Donatella Rita Petretto ### Bifactor structure of the schizotypal personality questionnaire (SPQ). Psychiatry Research, 2015, submitted. ### Principal Investigator of the study: ### Antonio Preti, M.D. ### Centro Medico Genneruxi ### Via Costantinopoli 42, 09129 Cagliari – Italy ### e-mail: apreti@tin.it ### Cagliari (Italy), August 27, 2015. ### The codes and the data are provided as free software, under the terms ### of the GNU General Public License as published by the Free Software Foundation, ### either version 3 of the License, or any later version. ### This material is distributed in the hope that it will be useful, ### but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ### See the GNU General Public License for more details. ### You can consult the GNU General Public License ### at: http://www.gnu.org/licenses/. ### Please, also consult the "General statement" for information on how to use and cut these codes. ################################################################################################################### ######################################################################## ### ### SPQ - Codes to create Figure 1 in the article ### ######################################################################## library(diagram) ### set thye space on the window par(mar = c(1,1,1,1), mfrow = c(2, 2)) ### Unidimensional model ### pos = (1,9) indicates that one element will be in row 1, 9 elements will be in position 2 ### box.type --> va specificata la sequenza attesa delle forme del box names <- c("","","IF","","", "ESA","","", "MT","","", "UPE","Unidimensional","", "OB", "","","NCF", "","","OS","","", "CA", "","","S") M <- matrix(nrow = 27, ncol = 27, byrow = TRUE, data = 0) M[3,13] <- ""; M[6,13]<- ""; M[9,13]<- ""; M[12,13]<- ""; M[15,13]<- ""; M[18, 13]<- ""; M[21, 13]<- ""; M[24, 13]<- ""; M[27, 13] <- "" plotmat(M, pos = c(3,3,3,3,3,3,3,3,3), curve = 0, name = names, lwd = 1, box.lwd = 1.5, cex.txt = 0.8, box.type = c("none", "none","rect","none", "none","rect","none", "none","rect","none", "none","rect","round", "none","rect", "none", "none","rect", "none", "none","rect", "none", "none","rect", "none", "none","rect"), box.size = c(0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.15,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1), box.prop = 0.5, relsize = 0.75) ### Correlated traits model names <- c("","","IF", "","", "MT","","", "UPE", "Pos","","OB", "","", "OS","","","S", "","","ESA","Neg","","NCF","","","CA") M <- matrix(nrow = 27, ncol = 27, byrow = TRUE, data = 0) curves <- matrix(nrow = ncol(M), ncol = ncol(M), 0) ### THis fixes the curvature of the arrows at 0 all over the matrix curves[10,22] <- curves[22,10] <- 0.2 ### This change the curvature of the arrows at the prespecified edges M[3,10] <- ""; M[6,10]<- ""; M[9,10]<- ""; M[12,10]<- ""; M[15,10]<- ""; M[18,10]<- ""; M[21,22]<- ""; M[24,22]<- ""; M[27,22]<- ""; M[10,22]<- ""; M[22,10] <- "" plotmat(M, pos = c(3,3,3,3,3,3,3,3,3), curve = curves, name = names, lwd = 1, box.lwd = 1.5, cex.txt = 0.8, box.type = c("none", "none","rect","none", "none","rect","none", "none","rect","circle", "none","rect","none", "none","rect", "none", "none","rect","none", "none","rect","circle", "none","rect","none", "none","rect"), box.prop = 0.5, relsize = 0.85) ### Second order model names <- c("", "", "IF", "", "", "MT","", "", "UPE", "", "Pos","OB", "2nd Order", "", "OS", "", "Neg", "S", "", "", "ESA","", "", "NCF","", "", "CA") M <- matrix(nrow = 27, ncol = 27, byrow = TRUE, data = 0) curves <- matrix(nrow = ncol(M), ncol = ncol(M), 0) ### THis fixes the curvature of the arrows at 0 all over the matrix M[3,11] <- ""; M[6,11] <- ""; M[9,11] <- ""; M[12,11]<- ""; M[15,11]<- ""; M[11,13]<- ""; M[17,13]<- ""; M[18,11]<- ""; M[21,17]<- ""; M[24,17]<- ""; M[27,17]<- ""; plotmat(M, pos = c(3,3,3,3,3,3,3,3,3), curve = curves, name = names, lwd = 1, box.lwd = 1.5, cex.txt = 0.8, box.type = c("none", "none","rect","none", "none","rect","none", "none","rect","none", "circle", "rect", "ellipse", "none", "rect", "none", "circle", "rect", "none", "none","rect","none", "none","rect","none", "none","rect"), box.prop = 0.5, relsize = 0.85) ### Bifactor model names <- c("", "IF", "", "","MT", "", "","UPE", "", "Pos","OB", "", "","OS","General", "", "S","", "","ESA","", "Neg", "NCF","", "", "CA","") M <- matrix(nrow = 27, ncol = 27, byrow = TRUE, data = 0) curves <- matrix(nrow = ncol(M), ncol = ncol(M), 0) ### THis fixes the curvature of the arrows at 0 all over the matrix M[2,10] <- ""; M[5, 10]<- ""; M[8, 10]<- ""; M[11, 10]<- ""; M[14, 10]<- ""; M[17, 10]<- ""; M[20, 22]<- ""; M[23, 22]<- ""; M[26, 22] <- "" M[2,15] <- ""; M[5,15]<- ""; M[8,15]<- ""; M[11,15]<- ""; M[14,15]<- ""; M[17,15]<- ""; M[20, 15]<- ""; M[23, 15]<- ""; M[26, 15] <- "" plotmat(M, pos = c(3,3,3,3,3,3,3,3,3), curve = curves, name = names, lwd = 1, box.lwd = 1.5, cex.txt = 0.8, box.type = c("none", "rect","none","none", "rect","none","none", "rect","none","circle", "rect","none","none", "rect","ellipse", "none", "rect","none","none", "rect","none","circle", "rect","none","none", "rect","none"), box.prop = 0.5, relsize = 0.85) ### par(mfrow = c(1, 1)) ### after saving, dev.off()
"""Calculation and processing of holding token allocations. Contains policy functions (PF) and state update functions (SUF). Functions: holding_agent_allocation (PF): Policy function to calculate the agent holding. update_agents_after_holding (SUF): Function to update agent holding allocations update_utilties_after_holding (SUF): Function to update holding token allocations. """ # POLICY FUNCTIONS def holding_agent_allocation(params, substep, state_history, prev_state, **kwargs): """ Policy function to calculate the agent holding. """ # get parameters holding_share = params['holding_share']/100 initial_lp_token_allocation = params['initial_lp_token_allocation'] token_payout_apr = params['holding_apr'] / 100 # get state variables agents = prev_state['agents'].copy() liquidity_pool = prev_state['liquidity_pool'].copy() #rewards token_after_adoption = liquidity_pool['lp_tokens_after_adoption'] # policy logic # initialize policy logic variables agent_utility_sum = 0 agent_utility_rewards_sum = 0 agents_holding_allocations = {} agents_holding_rewards = {} # calculate the staking apr token allocations and removals for each agent if token_payout_apr > 0 and holding_share > 0: for agent in agents: utility_tokens = agents[agent]['a_utility_tokens'] + agents[agent]['a_utility_from_holding_tokens'] # get the new agent utility token allocations from vesting, airdrops, incentivisation, and previous timestep holdings agents_holding_allocations[agent] = utility_tokens * holding_share # calculate the amount of tokens that shall be allocated to the staking apr utility from this timestep agent_utility_sum += agents_holding_allocations[agent] # sum up the total amount of tokens allocated to the staking apr utility for this timestep #rewards agents_holding_rewards[agent] = [(agents[agent]['a_tokens'] - agents[agent]['a_tokens_staked_remove'] - agents[agent]['a_tokens_staking_vesting_rewards'] - agents[agent]['a_tokens_staking_minting_rewards'] + agents_holding_allocations[agent]) * token_payout_apr/12 if agents[agent]['a_type'] != 'protocol_bucket' else 0][0] # calculate the amount of tokens that shall be rewarded to the agent for staking for this timestep agent_utility_rewards_sum += agents_holding_rewards[agent] # sum up the total amount of tokens rewarded to the agent for staking for this timestep return {'agents_holding_allocations': agents_holding_allocations, 'agents_holding_rewards': agents_holding_rewards, 'agent_utility_sum': agent_utility_sum, 'agent_utility_rewards_sum': agent_utility_rewards_sum} # STATE UPDATE FUNCTIONS def update_agents_after_holding(params, substep, state_history, prev_state, policy_input, **kwargs): """ Function to update agent holding allocations """ # get parameters holding_payout_source = params['holding_payout_source'] # get state variables updated_agents = prev_state['agents'].copy() # get policy input agents_holding_allocations = policy_input['agents_holding_allocations'] agents_holding_rewards = policy_input['agents_holding_rewards'] agent_utility_rewards_sum = policy_input['agent_utility_rewards_sum'] # update logic if agents_holding_rewards != {}: for agent in updated_agents: updated_agents[agent]['a_tokens'] += (agents_holding_allocations[agent] + agents_holding_rewards[agent]) # subtract tokens from payout source agent if updated_agents[agent]['a_name'].lower() in holding_payout_source.lower(): updated_agents[agent]['a_tokens'] -= agent_utility_rewards_sum return ('agents', updated_agents) def update_utilties_after_holding(params, substep, state_history, prev_state, policy_input, **kwargs): """ Function to update holding token allocations. """ # get parameters # get state variables updated_utilities = prev_state['utilities'].copy() # get policy input agent_utility_sum = policy_input['agent_utility_sum'] agent_utility_rewards_sum = policy_input['agent_utility_rewards_sum'] # update logic updated_utilities['u_holding_rewards'] = agent_utility_rewards_sum updated_utilities['u_holding_allocation'] = (agent_utility_sum) updated_utilities['u_holding_allocation_cum'] += (agent_utility_sum) return ('utilities', updated_utilities)
USB Connector USB connector node represents physical USB connector. It should be a child of USB interface controller. Required properties: - compatible: describes type of the connector, must be one of: "usb-a-connector", "usb-b-connector", "usb-c-connector". Optional properties: - label: symbolic name for the connector, - type: size of the connector, should be specified in case of USB-A, USB-B non-fullsize connectors: "mini", "micro". - self-powered: Set this property if the usb device that has its own power source. Optional properties for usb-b-connector: - id-gpios: an input gpio for USB ID pin. - vbus-gpios: an input gpio for USB VBUS pin, used to detect presence of VBUS 5V. see gpio/gpio.txt. - vbus-supply: a phandle to the regulator for USB VBUS if needed when host mode or dual role mode is supported. Particularly, if use an output GPIO to control a VBUS regulator, should model it as a regulator. see regulator/fixed-regulator.yaml - pinctrl-names : a pinctrl state named "default" is optional - pinctrl-0 : pin control group see pinctrl/pinctrl-bindings.txt Optional properties for usb-c-connector: - power-role: should be one of "source", "sink" or "dual"(DRP) if typec connector has power support. - try-power-role: preferred power role if "dual"(DRP) can support Try.SNK or Try.SRC, should be "sink" for Try.SNK or "source" for Try.SRC. - data-role: should be one of "host", "device", "dual"(DRD) if typec connector supports USB data. Required properties for usb-c-connector with power delivery support: - source-pdos: An array of u32 with each entry providing supported power source data object(PDO), the detailed bit definitions of PDO can be found in "Universal Serial Bus Power Delivery Specification" chapter 6.4.1.2 Source_Capabilities Message, the order of each entry(PDO) should follow the PD spec chapter 6.4.1. Required for power source and power dual role. User can specify the source PDO array via PDO_FIXED/BATT/VAR/PPS_APDO() defined in dt-bindings/usb/pd.h. - sink-pdos: An array of u32 with each entry providing supported power sink data object(PDO), the detailed bit definitions of PDO can be found in "Universal Serial Bus Power Delivery Specification" chapter 6.4.1.3 Sink Capabilities Message, the order of each entry(PDO) should follow the PD spec chapter 6.4.1. Required for power sink and power dual role. User can specify the sink PDO array via PDO_FIXED/BATT/VAR/PPS_APDO() defined in dt-bindings/usb/pd.h. - op-sink-microwatt: Sink required operating power in microwatt, if source can't offer the power, Capability Mismatch is set. Required for power sink and power dual role. Required nodes: - any data bus to the connector should be modeled using the OF graph bindings specified in bindings/graph.txt, unless the bus is between parent node and the connector. Since single connector can have multiple data buses every bus has assigned OF graph port number as follows: 0: High Speed (HS), present in all connectors, 1: Super Speed (SS), present in SS capable connectors, 2: Sideband use (SBU), present in USB-C. Examples -------- 1. Micro-USB connector with HS lines routed via controller (MUIC): muic-max77843@66 { ... usb_con: connector { compatible = "usb-b-connector"; label = "micro-USB"; type = "micro"; }; }; 2. USB-C connector attached to CC controller (s2mm005), HS lines routed to companion PMIC (max77865), SS lines to USB3 PHY and SBU to DisplayPort. DisplayPort video lines are routed to the connector via SS mux in USB3 PHY. ccic: s2mm005@33 { ... usb_con: connector { compatible = "usb-c-connector"; label = "USB-C"; ports { #address-cells = <1>; #size-cells = <0>; port@0 { reg = <0>; usb_con_hs: endpoint { remote-endpoint = <&max77865_usbc_hs>; }; }; port@1 { reg = <1>; usb_con_ss: endpoint { remote-endpoint = <&usbdrd_phy_ss>; }; }; port@2 { reg = <2>; usb_con_sbu: endpoint { remote-endpoint = <&dp_aux>; }; }; }; }; }; 3. USB-C connector attached to a typec port controller(ptn5110), which has power delivery support and enables drp. typec: ptn5110@50 { ... usb_con: connector { compatible = "usb-c-connector"; label = "USB-C"; power-role = "dual"; try-power-role = "sink"; source-pdos = <PDO_FIXED(5000, 2000, PDO_FIXED_USB_COMM)>; sink-pdos = <PDO_FIXED(5000, 2000, PDO_FIXED_USB_COMM) PDO_VAR(5000, 12000, 2000)>; op-sink-microwatt = <10000000>; }; };
import { Stats } from 'lib/constants' import { AbilityEidolon, precisionRound } from 'lib/conditionals/utils' import { baseComputedStatsObject, ComputedStatsObject } from 'lib/conditionals/conditionalConstants.ts' import { Eidolon } from 'types/Character' import { ConditionalMap, ContentItem } from 'types/Conditionals' import { CharacterConditional, PrecomputedCharacterConditional } from 'types/CharacterConditional' import { Form } from 'types/Form' const Jingliu = (e: Eidolon): CharacterConditional => { const { basic, skill, ult, talent } = AbilityEidolon.ULT_TALENT_3_SKILL_BASIC_5 const talentCrBuff = talent(e, 0.50, 0.52) let talentHpDrainAtkBuffMax = talent(e, 1.80, 1.98) talentHpDrainAtkBuffMax += (e >= 4) ? 0.30 : 0 const basicScaling = basic(e, 1.00, 1.10) const skillScaling = skill(e, 2.00, 2.20) const skillEnhancedScaling = skill(e, 2.50, 2.75) const ultScaling = ult(e, 3.00, 3.24) const content: ContentItem[] = [ { name: 'talentEnhancedState', id: 'talentEnhancedState', formItem: 'switch', text: 'Enhanced state', title: 'Crescent Transmigration', content: `When Jingliu has 2 stacks of Syzygy, she enters the Spectral Transmigration state with her Action Advanced by 100% and her CRIT Rate increases by ${precisionRound(talentCrBuff * 100)}%. Then, Jingliu's Skill "Transcendent Flash" becomes enhanced and turns into "Moon On Glacial River," and becomes the only ability she can use in battle.`, }, { name: 'talentHpDrainAtkBuff', id: 'talentHpDrainAtkBuff', formItem: 'slider', text: 'HP drain ATK buff', title: 'Crescent Transmigration - ATK Bonus', content: `When Jingliu uses an attack in the Spectral Transmigration state, she consumes HP from all other allies and Jingliu's ATK increases based on the total HP consumed from all allies in this attack, capped at ${precisionRound(talentHpDrainAtkBuffMax * 100)}% of her base ATK, lasting until the current attack ends.`, min: 0, max: talentHpDrainAtkBuffMax, percent: true, }, { id: 'e1CdBuff', name: 'e1CdBuff', formItem: 'switch', text: 'E1 ult active', title: 'E1 Moon Crashes Tianguan Gate', content: `E1: When using her Ultimate or Enhanced Skill, Jingliu's CRIT DMG increases by 24% for 1 turn. If only one enemy target is attacked, the target will additionally be dealt Ice DMG equal to 100% of Jingliu's ATK.`, disabled: e < 1, }, { id: 'e2SkillDmgBuff', name: 'e2SkillDmgBuff', formItem: 'switch', text: 'E2 skill buff', title: 'E2 Crescent Shadows Qixing Dipper', content: `E2: After using Ultimate, increases the DMG of the next Enhanced Skill by 80%.`, disabled: e < 2, }, ] return { content: () => content, teammateContent: () => [], defaults: () => ({ talentEnhancedState: true, talentHpDrainAtkBuff: talentHpDrainAtkBuffMax, e1CdBuff: true, e2SkillDmgBuff: true, }), teammateDefaults: () => ({ }), precomputeEffects: (request: Form) => { const r: ConditionalMap = request.characterConditionals const x = Object.assign({}, baseComputedStatsObject) // Skills x[Stats.CR] += (r.talentEnhancedState) ? talentCrBuff : 0 x[Stats.ATK_P] += ((r.talentEnhancedState) ? r.talentHpDrainAtkBuff : 0) as number // Traces x[Stats.RES] += (r.talentEnhancedState) ? 0.35 : 0 x.ULT_BOOST += (r.talentEnhancedState) ? 0.20 : 0 // Eidolons x[Stats.CD] += (e >= 1 && r.e1CdBuff) ? 0.24 : 0 x[Stats.CD] += (e >= 6 && r.talentEnhancedState) ? 0.50 : 0 // Scaling x.BASIC_SCALING += basicScaling x.SKILL_SCALING += (r.talentEnhancedState) ? skillEnhancedScaling : skillScaling x.SKILL_SCALING += (e >= 1 && r.talentEnhancedState && request.enemyCount == 1) ? 1 : 0 x.ULT_SCALING += ultScaling x.ULT_SCALING += (e >= 1 && request.enemyCount == 1) ? 1 : 0 x.FUA_SCALING += 0 // BOOST x.SKILL_BOOST += (e >= 2 && r.talentEnhancedState && r.e2SkillDmgBuff) ? 0.80 : 0 x.BASIC_TOUGHNESS_DMG += 30 x.SKILL_TOUGHNESS_DMG += 60 x.ULT_TOUGHNESS_DMG += 60 return x }, precomputeMutualEffects: (_x: ComputedStatsObject, _request: Form) => { }, calculateBaseMultis: (c: PrecomputedCharacterConditional) => { const x = c.x x.BASIC_DMG += x.BASIC_SCALING * x[Stats.ATK] x.SKILL_DMG += x.SKILL_SCALING * x[Stats.ATK] x.ULT_DMG += x.ULT_SCALING * x[Stats.ATK] x.FUA_DMG += 0 }, } } Jingliu.label = 'Jingliu' export default Jingliu
import tensorflow as tf from tensorflow.keras import layers, Model, Input, regularizers from residualBlocks import residual_cell from convNetArchitecture import conv_block, de_conv_block class CRVAE(Model): """ The encoder and decoder of the FAE framework """ def __init__(self, latent_dim, channels): super(CRVAE, self).__init__() self.latent_dim = latent_dim self.channels = channels # Encoder encoder_inputs = Input(shape=(32, 32, self.channels)) en = conv_block(encoder_inputs, filters=64) en = residual_cell(en, filters=64) en = conv_block(en, filters=128) en = residual_cell(en, filters=128) en = conv_block(en, filters=256) en = residual_cell(en, filters=256) en = conv_block(en, filters=512) en = residual_cell(en, filters=512) en = layers.Flatten()(en) mean = layers.Dense(self.latent_dim)(en) log_var = layers.Dense(self.latent_dim)(en) self.encoder = Model(encoder_inputs, [mean, log_var]) # Decoder decoder_inputs = Input(shape=(self.latent_dim, )) de = layers.Dense(2 * 2 * 512)(decoder_inputs) de = layers.Reshape(target_shape=(2, 2, 512))(de) de = layers.Activation('relu')(de) de = de_conv_block(de, filters=512) de = residual_cell(de, filters=512) de = de_conv_block(de, filters=256) de = residual_cell(de, filters=256) de = de_conv_block(de, filters=128) de = residual_cell(de, filters=128) de = de_conv_block(de, filters=64) de = residual_cell(de, filters=64) decoder_outputs = layers.Conv2DTranspose(filters=self.channels, kernel_size=3, padding='same')(de) self.decoder = Model(decoder_inputs, decoder_outputs) # Deep dense net c_inputs = Input(shape=(latent_dim,)) c = layers.Dense(2048, kernel_regularizer=regularizers.l2(0.001))(c_inputs) c = layers.Activation('relu')(c) c = layers.Dropout(0.3)(c) c = layers.Dense(512, kernel_regularizer=regularizers.l2(0.001))(c) c = layers.Activation('relu')(c) c = layers.Dropout(0.3)(c) c = layers.Dense(512, kernel_regularizer=regularizers.l2(0.001))(c) c = layers.Activation('relu')(c) c = layers.Dropout(0.3)(c) c = layers.Dense(self.latent_dim, kernel_regularizer=regularizers.l2(0.001))(c) self.grouper = Model(c_inputs, c) @tf.function def sample(self, eps=None): if eps is None: eps = tf.random.normal(shape=(100, self.latent_dim)) return self.decode(eps, apply_sigmoid=True) def decode(self, z, apply_sigmoid=False): remake = self.decoder(z) if apply_sigmoid: washed = tf.sigmoid(remake) return washed return remake def group(self, mean): clusters = self.grouper(mean) return clusters class Discriminator(Model): """ The Discriminator of the FAE framework """ def __init__(self, channels): super(Discriminator, self).__init__() self.channels = channels discriminator_inputs = Input(shape=(32, 32, self.channels)) dis = conv_block(discriminator_inputs, filters=32) dis = residual_cell(dis, filters=32) dis = conv_block(dis, filters=64) dis = residual_cell(dis, filters=64) dis = conv_block(dis, filters=512) dis = residual_cell(dis, filters=512) dis = layers.Flatten()(dis) discriminator_outputs = layers.Dense(1)(dis) self.discriminator = Model(discriminator_inputs, discriminator_outputs) @tf.function def discriminate(self, x): return self.discriminator(x)
#include <Wire.h> /*~ Librería I2C ~*/ #include <LiquidCrystal_I2C.h> /*~ Librería LCD ~*/ /*~ Página para crear iconos personalizados ~*/ /*~ https://maxpromer.github.io/LCD-Character-Creator/ ~*/ /*~ Los siguientes arrays contienen un caracter, es decir se indica que pixel se enciendo o apaga dependiendo si es 1 o 0 ~*/ /*~ Icono o caracter 1 ~*/ byte caracter1 [ ] = { B11111, /*~ ⬜⬛⬛⬛⬜~*/ B01110, /*~ ⬜⬛⬜⬛⬜~*/ B00100, /*~ ⬜⬛⬛⬛⬜~*/ B01110, /*~ ⬛⬛⬛⬛⬛~*/ B11111, /*~ ⬜⬜⬛⬜⬜~*/ B01110, /*~ ⬜⬜⬛⬜⬜~*/ B00100, /*~ ⬜⬛⬛⬛⬜~*/ B01110 /*~ ⬛⬜⬜⬜⬛~*/ }; /*~ Icono o caracter 2 ~*/ byte caracter2 [ ] = { B11111, /*~ ⬛⬛⬛⬛⬛~*/ B10001, /*~ ⬛⬜⬜⬜⬛~*/ B10001, /*~ ⬛⬜⬜⬜⬛~*/ B11111, /*~ ⬛⬛⬛⬛⬛~*/ B11111, /*~ ⬛⬛⬛⬛⬛~*/ B11111, /*~ ⬛⬛⬛⬛⬛~*/ B11111, /*~ ⬛⬛⬛⬛⬛~*/ B11011 /*~ ⬛⬛⬜⬛⬛~*/ }; LiquidCrystal_I2C lcd ( 0x27, 16, 2 ); /*~ Instancia de la clase para el manejo de la pantalla ( Dirección I2C, columnas, filas ) ~*/ void setup ( void ) { lcd.init ( ); /*~ Inicializar la pantalla LCD ~*/ lcd.createChar ( 0, caracter1 ); /*~ Indicar al programa que genere un caracter a partir del array de bits. ~*/ lcd.createChar ( 1, caracter2 ); /*~ Indicar al programa que genere otro un caracter. ~*/ } void loop ( void ) { lcd.backlight ( ); /*~ Encender la luz de fondo. ~*/ delay ( 1000 ); /*~ Esperar 1 segundo. ~*/ lcd.noBacklight ( ); /*~ Apagar la luz de fondo. ~*/ delay ( 1000 ); /*~ Esperar 1 segundo. ~*/ lcd.backlight ( ); /*~ Encender la luz de fondo. ~*/ lcd.setCursor ( 0, 0 ); /*~ ( columnas, filas) Ubicamos el cursor en la primera posición(columna:0) de la primera línea(fila:0) ~*/ lcd.write ( 0 ); /*~ Mostramos nuestro primer icono o caracter ~*/ delay ( 1000 ); /*~ Esperar 1 segundo ~*/ lcd.clear ( ); /*~ Limpiar pantalla ~*/ lcd.setCursor ( 0, 1 ); /*~ ( columnas, filas) Ubicamos el cursor en la primera posición(columna:0) de la segunda línea(fila:1) ~*/ lcd.write ( 1 ); /*~ Mostramos nuestro segundo icono o caracter ~*/ delay ( 1000 ); /*~ Esperar 1 segundo ~*/ lcd.clear ( ); /*~ Limpiar pantalla ~*/ lcd.setCursor ( 0, 0 ); /*~ ( columnas, filas) Ubicamos el cursor en la primera posición(columna:0) de la primera línea(fila:0) ~*/ lcd.print ( "Emmanuel" ); /*~ Mostrar una cadena de texto (no exceder 16 caracteres por línea)~*/ delay ( 1000 ); /*~ Esperar 1 segundo ~*/ for ( uint8_t i = 0; i < ( 40 ); i++ ) { /*~ Este ciclo es para que se vea como se recorren los caracteres, si no es colocado se vería muy rápido ~*/ lcd.scrollDisplayRight ( ); /*~ Recorrer caracteres de derecha a izquierda ~*/ delay ( 100 ); /*~ Esperar 100 milisegundos ~*/ } for ( uint8_t i = 0; i < ( 40 ); i++ ) { /*~ Este ciclo es para que se vea como se recorren los caracteres, si no es colocado se vería muy rápido ~*/ lcd.scrollDisplayLeft ( ); /*~ Recorrer caracteres de izquierda a derecha ~*/ delay ( 100 ); /*~ Esperar 100 milisegundos ~*/ } lcd.clear ( ); /*~ Limpiar pantalla ~*/ }
"use client"; import Link from "next/link"; import { toast } from "react-toastify"; import { SubmitButton } from "./SubmitButton"; import Image from "next/image"; import { useFormState } from "react-dom"; import { userSignup } from "../../../actions/user/auth"; import { useEffect } from "react"; import { useRouter } from "next/navigation"; const SignUpForm = () => { const [state, submitAction] = useFormState(userSignup, null); const router = useRouter(); useEffect(() => { if (state?.status !== 200) { toast.error(state?.message, { position: "top-right", autoClose: 1800, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, onClose: () => { document.getElementById("singupForm").reset(); }, }); } else if (state?.status === 200) { toast.success(state?.message, { position: "top-right", autoClose: 1800, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, onClose: () => { document.getElementById("singupForm").reset(); router.replace("/login"); }, }); } }, [router, state]); return ( <> <div className="min-h-screen"> <div className="flex min-h-full flex-col justify-center px-6 py-12 lg:px-8"> <div className="sm:mx-auto sm:w-full sm:max-w-sm flex flex-col items-center justify-center"> <Image src="/logo.svg" alt="logo" height={10} width={10} style={{ width: "4rem" }} priority={true} /> <h2 className="mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900"> Sign up for an Account </h2> </div> <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm"> <form action={submitAction} className="space-y-6" id="singupForm"> <div> <label htmlFor="name" className="block text-sm font-medium leading-6 text-gray-900" > Name </label> <div className="mt-2"> <input id="name" name="name" type="text" autoComplete="name" minLength={3} required className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6 p-2 disabled:cursor-not-allowed disabled:bg-gray-300 disabled:opacity-50" /> </div> </div> <div> <label htmlFor="email" className="block text-sm font-medium leading-6 text-gray-900" > Email address </label> <div className="mt-2"> <input id="email" name="email" type="email" autoComplete="email" required className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6 p-2 disabled:cursor-not-allowed disabled:bg-gray-300 disabled:opacity-50" /> </div> </div> <div> <label htmlFor="password" className="block text-sm font-medium leading-6 text-gray-900" > Password </label> <div className="mt-2"> <input id="password" name="password" type="password" minLength={6} autoComplete="current-password" required className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6 p-2 disabled:cursor-not-allowed disabled:bg-gray-300 disabled:opacity-50" /> </div> </div> <div> <SubmitButton title="Sign up" size="full" /> </div> </form> <p className="mt-10 text-center text-sm text-gray-500"> Already have an account? &nbsp; <Link href={"/login"} className="font-semibold leading-6 text-blue-600 hover:text-blue-500" > Login </Link> </p> </div> </div> </div> </> ); }; export default SignUpForm;
# frozen_string_literal: true module ThemeStore end class ThemeStore::GitImporter COMMAND_TIMEOUT_SECONDS = 20 attr_reader :url def initialize(url, private_key: nil, branch: nil) @url = GitUrl.normalize(url) @temp_folder = "#{Pathname.new(Dir.tmpdir).realpath}/discourse_theme_#{SecureRandom.hex}" @private_key = private_key @branch = branch end def import! clone! if version = Discourse.find_compatible_git_resource(@temp_folder) begin execute "git", "cat-file", "-e", version rescue RuntimeError => e tracking_ref = execute "git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}" remote_name = tracking_ref.split("/", 2)[0] execute "git", "fetch", remote_name, "#{version}:#{version}" end begin execute "git", "reset", "--hard", version rescue RuntimeError raise RemoteTheme::ImportError.new( I18n.t("themes.import_error.git_ref_not_found", ref: version), ) end end end def commits_since(hash) commit_hash, commits_behind = nil commit_hash = execute("git", "rev-parse", "HEAD").strip commits_behind = begin execute("git", "rev-list", "#{hash}..HEAD", "--count").strip rescue StandardError -1 end [commit_hash, commits_behind] end def version execute("git", "rev-parse", "HEAD").strip end def cleanup! FileUtils.rm_rf(@temp_folder) end def real_path(relative) fullpath = "#{@temp_folder}/#{relative}" return nil unless File.exist?(fullpath) # careful to handle symlinks here, don't want to expose random data fullpath = Pathname.new(fullpath).realpath.to_s if fullpath && fullpath.start_with?(@temp_folder) fullpath else nil end end def all_files Dir.glob("**/*", base: @temp_folder).reject { |f| File.directory?(File.join(@temp_folder, f)) } end def [](value) fullpath = real_path(value) return nil unless fullpath File.read(fullpath) end protected def redirected_uri first_clone_uri = @uri.dup first_clone_uri.path.gsub!(%r{/\z}, "") first_clone_uri.path += "/info/refs" first_clone_uri.query = "service=git-upload-pack" redirected_uri = FinalDestination.resolve(first_clone_uri.to_s, http_verb: :get) if redirected_uri&.path.ends_with?("/info/refs") redirected_uri.path.gsub!(%r{/info/refs\z}, "") redirected_uri.query = nil redirected_uri else @uri end rescue StandardError @uri end def raise_import_error! raise RemoteTheme::ImportError.new(I18n.t("themes.import_error.git")) end def clone! begin @uri = URI.parse(@url) rescue URI::Error raise_import_error! end case @uri&.scheme when "http", "https" clone_http! when "ssh" clone_ssh! else raise RemoteTheme::ImportError.new(I18n.t("themes.import_error.git_unsupported_scheme")) end end def clone_args(url, config = {}) args = ["git"] config.each { |key, value| args.concat(["-c", "#{key}=#{value}"]) } args << "clone" args.concat(["--single-branch", "-b", @branch]) if @branch.present? args.concat([url, @temp_folder]) args end def clone_http! uri = redirected_uri raise_import_error! unless %w[http https].include?(@uri.scheme) addresses = FinalDestination::SSRFDetector.lookup_and_filter_ips(uri.host) unless addresses.empty? env = { "GIT_TERMINAL_PROMPT" => "0" } args = clone_args( uri.to_s, "http.followRedirects" => "false", "http.curloptResolve" => "#{uri.host}:#{uri.port}:#{addresses.join(",")}", ) begin Discourse::Utils.execute_command(env, *args, timeout: COMMAND_TIMEOUT_SECONDS) rescue RuntimeError end end end def clone_ssh! raise_import_error! unless @private_key.present? with_ssh_private_key do |ssh_folder| # Use only the specified SSH key env = { "GIT_SSH_COMMAND" => "ssh -i #{ssh_folder}/id_rsa -o IdentitiesOnly=yes -o IdentityFile=#{ssh_folder}/id_rsa -o StrictHostKeyChecking=no", } args = clone_args(@url) begin Discourse::Utils.execute_command(env, *args, timeout: COMMAND_TIMEOUT_SECONDS) rescue RuntimeError raise_import_error! end end end def with_ssh_private_key ssh_folder = "#{Pathname.new(Dir.tmpdir).realpath}/discourse_theme_ssh_#{SecureRandom.hex}" FileUtils.mkdir_p ssh_folder File.write("#{ssh_folder}/id_rsa", @private_key) FileUtils.chmod(0600, "#{ssh_folder}/id_rsa") yield ssh_folder ensure FileUtils.rm_rf ssh_folder end def execute(*args) Discourse::Utils.execute_command(*args, chdir: @temp_folder, timeout: COMMAND_TIMEOUT_SECONDS) end end
<?php namespace _5balloons\LivewireTooltip; use Livewire\Component; use Livewire\Attributes\On; /** Usage * <a class="tooltip-link" tooltip-method="\App\Directory\Class::methodName">Link Name</a> * or * <a class="tooltip-link" tooltip-method="\App\Directory\Class::methodName" data-param1="value">Link Name</a> */ class Tooltip extends Component { public $toolTipMethod = null; public $toolTipHtml = null; public function render() { return <<<'HTML' <div> <style> #tooltip[data-show] { display: block; z-index: 100; } #tooltip { display: none; background-color: #333; color: white; padding: 5px 10px; border-radius: 4px; font-size: 14px; } .loading-spinner { width: 1rem; /* Equivalent to w-4 */ height: 1rem; /* Equivalent to h-4 */ border-style: solid; /* Equivalent to border-solid */ display: inline-block; /* Equivalent to inline-block */ border-width: 0 0 2px 0; /* Equivalent to border-b-2 */ border-color: white; /* Equivalent to border-white */ border-radius: 9999px; /* Equivalent to rounded-full */ animation: spin 1s linear infinite; /* Equivalent to animate-spin */ } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } </style> <div wire:ignore.self id="tooltip"> <div class="flex"> <div > {!! $toolTipHtml !!} </div> <div wire:loading> <div class="loading-spinner"></div> </div> </div> </div> @script <script> let tooltipLinks = document.querySelectorAll('.tooltip-link'); let tooltip = document.getElementById('tooltip'); let popperInstance = null; tooltipLinks.forEach(el => { el.addEventListener('mouseover', event => { let placement = event.target.getAttribute('data-placement') || 'top'; // Default to 'top' if not specified const popperInstance = Popper.createPopper(event.target, tooltip, { placement: placement, modifiers: [ { name: 'offset', options: { offset: [0, 8], // Adjust based on your needs }, }, ], }); // Function to show tooltip function showTooltip() { tooltip.setAttribute('data-show', ''); tooltip.classList.remove('hidden'); popperInstance.update(); } // Function to hide tooltip function hideTooltip() { tooltip.removeAttribute('data-show'); tooltip.classList.add('hidden'); if (popperInstance) { popperInstance.destroy(); } } let classAndMethod = event.target.getAttribute('tooltip-method'); let params = {}; Object.entries(event.target.dataset).forEach(([key, value]) => { if (key.startsWith('param')) { params[key] = value; } }); // Dispatch event to fetch content Livewire.dispatchTo('livewire-tooltip', 'tooltip-mouseover', {classAndMethod : classAndMethod, parameters: params}); // Show the tooltip showTooltip(); el.addEventListener('mouseout', event => { // Hide the tooltip hideTooltip(); }); }); }); </script> @endscript </div> HTML; } #[On('tooltip-mouseover')] public function fetchContent($classAndMethod, $parameters){ // Split the class and method using '::' as the delimiter [$className, $methodName] = $this->parseClassAndMethodName($classAndMethod); //try{ // Check if the class and method is callable if (is_callable([$className, $methodName])) { $paramValues = array_values($parameters); // Call the static method dynamically and store the result $result = call_user_func_array($classAndMethod, $paramValues); // Check if the result is a view instance if ($result instanceof \Illuminate\View\View) { // Render the view to a string $this->toolTipHtml = $result->render(); } elseif (is_string($result)) { // Use the string directly $this->toolTipHtml = $result; } else { // Handle other types of return values or set an error message $this->toolTipHtml = 'Invalid content for tooltip.'; } } else { // Method not callable, handle error $this->toolTipHtml = 'Error: Method not found or not callable.'; } // }catch(\Exception $e){ // $this->toolTipHtml = 'Error fetching tooltip content'; // } } #[On('tooltip-mouseout')] public function clearContent(){ $this->toolTipHtml = ''; } protected function parseClassAndMethodName($tooltipMethod) { // Find the position of the first parenthesis (if any) $parenthesisPos = strpos($tooltipMethod, '('); // If there's no parenthesis, assume there are no parameters if ($parenthesisPos === false) { // Split by '::' to get class and method [$className, $methodName] = explode('::', $tooltipMethod); } else { // Extract the substring up to the first parenthesis $classAndMethod = substr($tooltipMethod, 0, $parenthesisPos); // Split by '::' to get class and method [$className, $methodName] = explode('::', $classAndMethod); } return [$className, $methodName]; } }
import { sortBy, sortStrings } from "common/collections"; import { BooleanLike, classes } from "common/react"; import { ComponentType, createComponentVNode, InfernoNode } from "inferno"; import { VNodeFlags } from "inferno-vnode-flags"; import { sendAct, useBackend, useLocalState } from "../../../../backend"; import { Box, Button, Dropdown, NumberInput, Stack } from "../../../../components"; import { createSetPreference, PreferencesMenuData } from "../../data"; import { ServerPreferencesFetcher } from "../../ServerPreferencesFetcher"; export const sortChoices = sortBy<[string, InfernoNode]>(([name]) => name); export type Feature< TReceiving, TSending = TReceiving, TServerData = undefined, > = { name: string; component: FeatureValue< TReceiving, TSending, TServerData >; category?: string; description?: string; }; /** * Represents a preference. * TReceiving = The type you will be receiving * TSending = The type you will be sending * TServerData = The data the server sends through preferences.json */ type FeatureValue< TReceiving, TSending = TReceiving, TServerData = undefined, > = ComponentType<FeatureValueProps< TReceiving, TSending, TServerData >>; export type FeatureValueProps< TReceiving, TSending = TReceiving, TServerData = undefined, > = { act: typeof sendAct, featureId: string, handleSetValue: (newValue: TSending) => void, serverData: TServerData | undefined, shrink?: boolean, value: TReceiving, }; export const FeatureColorInput = (props: FeatureValueProps<string>) => { return ( <Button onClick={() => { props.act("set_color_preference", { preference: props.featureId, }); }}> <Stack align="center" fill> <Stack.Item> <Box style={{ background: props.value.startsWith("#") ? props.value : `#${props.value}`, border: "2px solid white", "box-sizing": "content-box", height: "11px", width: "11px", ...(props.shrink ? { "margin": "1px", } : {}), }} /> </Stack.Item> {!props.shrink && ( <Stack.Item> Change </Stack.Item> )} </Stack> </Button> ); }; export type FeatureToggle = Feature<BooleanLike, boolean>; export const CheckboxInput = ( props: FeatureValueProps<BooleanLike, boolean> ) => { return (<Button.Checkbox checked={!!props.value} onClick={() => { props.handleSetValue(!props.value); }} />); }; export const CheckboxInputInverse = ( props: FeatureValueProps<BooleanLike, boolean> ) => { return (<Button.Checkbox checked={!props.value} onClick={() => { props.handleSetValue(!props.value); }} />); }; export const createDropdownInput = <T extends string | number = string>( // Map of value to display texts choices: Record<T, InfernoNode>, dropdownProps?: Record<T, unknown>, ): FeatureValue<T> => { return (props: FeatureValueProps<T>) => { return (<Dropdown selected={props.value} displayText={choices[props.value]} onSelected={props.handleSetValue} width="100%" options={sortChoices(Object.entries(choices)) .map(([dataValue, label]) => { return { displayText: label, value: dataValue, }; })} {...dropdownProps} />); }; }; export type FeatureChoicedServerData = { choices: string[]; display_names?: Record<string, string>; icons?: Record<string, string>; }; export type FeatureChoiced = Feature<string, string, FeatureChoicedServerData>; const capitalizeFirstLetter = (text: string) => ( text.toString().charAt(0).toUpperCase() + text.toString().slice(1) ); export const StandardizedDropdown = (props: { choices: string[], disabled?: boolean, displayNames: Record<string, InfernoNode>, onSetValue: (newValue: string) => void, value: string, }) => { const { choices, disabled, displayNames, onSetValue, value, } = props; return (<Dropdown disabled={disabled} selected={value} onSelected={onSetValue} width="100%" displayText={displayNames[value]} options={ choices .map(choice => { return { displayText: displayNames[choice], value: choice, }; }) } />); }; export const FeatureDropdownInput = ( props: FeatureValueProps<string, string, FeatureChoicedServerData> & { disabled?: boolean, }, ) => { const serverData = props.serverData; if (!serverData) { return null; } const displayNames = serverData.display_names || Object.fromEntries( serverData.choices.map(choice => [choice, capitalizeFirstLetter(choice)]) ); return (<StandardizedDropdown choices={sortStrings(serverData.choices)} disabled={props.disabled} displayNames={displayNames} onSetValue={props.handleSetValue} value={props.value} />); }; export type FeatureWithIcons<T> = Feature< { value: T }, T, FeatureChoicedServerData >; export const FeatureIconnedDropdownInput = ( props: FeatureValueProps<{ value: string, }, string, FeatureChoicedServerData>, ) => { const serverData = props.serverData; if (!serverData) { return null; } const icons = serverData.icons; const textNames = serverData.display_names || Object.fromEntries( serverData.choices.map(choice => [choice, capitalizeFirstLetter(choice)]) ); const displayNames = Object.fromEntries( Object.entries(textNames).map(([choice, textName]) => { let element: InfernoNode = textName; if (icons && icons[choice]) { const icon = icons[choice]; element = ( <Stack> <Stack.Item> <Box className={classes([ "preferences32x32", icon, ])} style={{ "transform": "scale(0.8)", }} /> </Stack.Item> <Stack.Item grow> {element} </Stack.Item> </Stack> ); } return [choice, element]; }) ); return (<StandardizedDropdown choices={sortStrings(serverData.choices)} displayNames={displayNames} onSetValue={props.handleSetValue} value={props.value.value} />); }; export type FeatureNumericData = { minimum: number, maximum: number, step: number, } export type FeatureNumeric = Feature<number, number, FeatureNumericData>; export const FeatureNumberInput = ( props: FeatureValueProps<number, number, FeatureNumericData> ) => { if (!props.serverData) { return <Box>Loading...</Box>; } return (<NumberInput onChange={(e, value) => { props.handleSetValue(value); }} minValue={props.serverData.minimum} maxValue={props.serverData.maximum} step={props.serverData.step} value={props.value} />); }; export const FeatureValueInput = (props: { feature: Feature<unknown>, featureId: string, shrink?: boolean, value: unknown, act: typeof sendAct, }, context) => { const { data } = useBackend<PreferencesMenuData>(context); const feature = props.feature; const [predictedValue, setPredictedValue] = useLocalState( context, `${props.featureId}_predictedValue_${data.active_slot}`, props.value, ); const changeValue = (newValue: unknown) => { setPredictedValue(newValue); createSetPreference(props.act, props.featureId)(newValue); }; return ( <ServerPreferencesFetcher render={serverData => { return createComponentVNode( VNodeFlags.ComponentUnknown, feature.component, { act: props.act, featureId: props.featureId, serverData: serverData && serverData[props.featureId], shrink: props.shrink, handleSetValue: changeValue, value: predictedValue, }); }} /> ); };
import React from "react"; import {InputBase} from "../../../../common/base-input/base-input"; import {KComponent} from "../../../../common/k-component"; import {Select} from "../../../../common/select/select"; import {userInfo} from "../../../../../common/states/user-info"; import {customHistory} from "../../../routes"; export class UserInfoForm extends KComponent { constructor(props) { super(props); this.state = { loading: false }; }; generateError =() => { let {err, form} = this.props; let {email, CMT, employeeID} = form.getData(); let msg = { "email_existed": `Email ${email} đã tồn tại!`, "CMT_existed": `CMT ${CMT} đã tồn tại!`, "employeeID_existed": `Mã nhân viên ${employeeID} đã tồn tại!`, }; return (err.hasOwnProperty("message") && msg.hasOwnProperty(err.message)) ? msg[err.message] : "Đã có lỗi xảy ra!"; }; render() { let {form, err, onChange: propsOnChange, renderNavigate = () => null, editEmp = false} = this.props; return ( <div className="user-info-form"> <div className="m-form m-form--fit m-form--label-align-right m-form--state"> {err && ( <div className="row"> <div className="server-error pb-3 col"> <p> {this.generateError()} </p> </div> </div> ) } {(!editEmp && form.getPathData("employeeID")) && ( <div className="row"> <div className="emp-id-wrap pb-5 col"> <div> Mã nhân viên: <span className="emp-id"> {form.getPathData("employeeID")}</span> </div> </div> </div> ) } {editEmp && ( <div className="row"> <div className="col-6"> {form.enhanceComponent("employeeID", ({error, onEnter, onChange, ...others}) => ( <InputBase className="uif-input pt-0" error={error} id={"employeeID"} onKeyDown={onEnter} onChange={e => { propsOnChange(); onChange(e); }} type={"text"} label={"Mã nhân viên"} {...others} /> ), true)} </div> </div> )} <div className="row "> <div className="col-6"> {form.enhanceComponent("name", ({error, onEnter, onChange, ...others}) => ( <InputBase className="uif-input pt-0" error={error} id={"name"} onKeyDown={onEnter} onChange={e => { propsOnChange(); onChange(e); }} type={"text"} label={"Tên đầy đủ"} {...others} /> ), true)} </div> <div className="col-6"> {form.enhanceComponent("gender", ({value, onChange}) => ( <Select className="uif-input pt-0" options={[{label: "Nam", value: 0}, {label: "Nữ", value:1}]} value={value} onChange={e => { propsOnChange(); onChange(e.target.value) }} label={"Giới tính"} placeholder="Chọn giới tính" /> ), true)} </div> </div> <div className="row"> <div className="col-6"> {form.enhanceComponent("address", ({error, onEnter, onChange, ...others}) => ( <InputBase className="uif-input pt-0" error={error} id={"address"} onKeyDown={onEnter} onChange={e => { propsOnChange(); onChange(e); }} type={"text"} label={"Địa chỉ"} {...others} /> ), true)} </div> <div className="col-6"> {form.enhanceComponent("phone", ({error, onEnter, onChange, ...others}) => ( <InputBase className="uif-input pt-0" error={error} id={"phone"} onKeyDown={onEnter} onChange={e => { propsOnChange(); onChange(e); }} type={"text"} label={"Số điện thoại"} {...others} /> ), true)} </div> </div> <div className="row"> <div className="col-6"> {form.enhanceComponent("email", ({error, onEnter, onChange, ...others}) => ( <InputBase className="uif-input pt-0" error={error} id={"email"} onKeyDown={onEnter} onChange={e => { propsOnChange(); onChange(e); }} type={"text"} label={"Email"} {...others} /> ), true)} </div> <div className="col-6"> {form.enhanceComponent("CMT", ({error, onEnter, onChange, ...others}) => ( <InputBase className="uif-input pt-0" error={error} id={"cmt"} onKeyDown={onEnter} onChange={e => { propsOnChange(); onChange(e); }} type={"text"} label={"Chứng minh thư"} {...others} /> ), true)} </div> </div> <div className="row"> <div className="col optional-nav"> {renderNavigate()} </div> </div> </div> </div> ); } }
import "./globals.css"; import { Inter, Poppins } from "next/font/google"; import { ClerkProvider } from "@clerk/nextjs"; import { ModalProvider } from "@/provider/modal-provider"; import { ToasterProvider } from '@/provider/toast-provider'; import { ThemeProvider } from "@/provider/theme-provider" const font = Poppins({weight: "400", subsets: ["latin"]}); // Inter({ subsets: ["latin"] }); export const metadata = { title: "Megalinks admin Dashboard", description: "Share editing resources with everyone", }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <ClerkProvider> <html lang="en"> <body className={font.className}> <ThemeProvider attribute="class" defaultTheme="system" enableSystem> <ToasterProvider /> <ModalProvider /> {children} </ThemeProvider> </body> </html> </ClerkProvider> ); }
import java.util.Arrays; import java.util.Iterator; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; import org.apache.spark.api.java.function.Function2; import org.apache.spark.api.java.function.PairFunction; import scala.Tuple2; /** * @author liujinlin * @date 2023/11/2 */ public class JavaWordCount { public static void main(String[] args) { SparkConf conf = new SparkConf().setAppName("wordcount").setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); JavaRDD<String> lines = sc.textFile("/Users/liu/input.txt"); JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() { public Iterator<String> call(String line) throws Exception { return Arrays.asList(line.split("\\s")).iterator(); } }); JavaPairRDD<String, Integer> pairs = words.mapToPair( new PairFunction<String, String, Integer>() { public Tuple2<String, Integer> call(String word) throws Exception { return new Tuple2<String, Integer>(word, 1); } }); JavaPairRDD<String, Integer> wordcount = pairs.reduceByKey( new Function2<Integer, Integer, Integer>() { public Integer call(Integer v1, Integer v2) throws Exception { return v1 + v2; } }); for (Tuple2<String, Integer> pair: wordcount.collect()) { System.out.println(pair._1 + ": " + pair._2); } sc.close(); } }
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; use Hash; class RegisterController extends Controller { public function showRegistrationForm() { return view('register'); } public function register(Request $request) { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8|confirmed', ]); User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); // Después de registrar al usuario, redirige al usuario a la página de inicio de sesión return redirect('/login')->with('success', '¡Registro exitoso! Por favor inicia sesión.'); } }
using System.Collections.Concurrent; using CloudPillar.Agent.Wrappers; using CloudPillar.Agent.Entities; using Shared.Entities.Messages; using Shared.Entities.Twin; using CloudPillar.Agent.Handlers.Logger; using Shared.Entities.Services; using Microsoft.Extensions.Options; using System.Security.AccessControl; using System.IO.Compression; namespace CloudPillar.Agent.Handlers; public class FileDownloadHandler : IFileDownloadHandler { private readonly IFileStreamerWrapper _fileStreamerWrapper; private readonly ID2CMessengerHandler _d2CMessengerHandler; private readonly IStrictModeHandler _strictModeHandler; private readonly ITwinReportHandler _twinReportHandler; private readonly ISignatureHandler _signatureHandler; private readonly StrictModeSettings _strictModeSettings; private readonly IServerIdentityHandler _serverIdentityHandler; private static List<FileDownload> _filesDownloads = new List<FileDownload>(); private readonly ILoggerHandler _logger; private readonly ICheckSumService _checkSumService; private readonly DownloadSettings _downloadSettings; public FileDownloadHandler(IFileStreamerWrapper fileStreamerWrapper, ID2CMessengerHandler d2CMessengerHandler, IStrictModeHandler strictModeHandler, ITwinReportHandler twinReportHandler, ILoggerHandler loggerHandler, ICheckSumService checkSumService, ISignatureHandler signatureHandler, IServerIdentityHandler serverIdentityHandler, IOptions<StrictModeSettings> strictModeSettings, IOptions<DownloadSettings> options) { _fileStreamerWrapper = fileStreamerWrapper ?? throw new ArgumentNullException(nameof(fileStreamerWrapper)); _d2CMessengerHandler = d2CMessengerHandler ?? throw new ArgumentNullException(nameof(d2CMessengerHandler)); _strictModeHandler = strictModeHandler ?? throw new ArgumentNullException(nameof(strictModeHandler)); _twinReportHandler = twinReportHandler ?? throw new ArgumentNullException(nameof(twinReportHandler)); _signatureHandler = signatureHandler ?? throw new ArgumentNullException(nameof(signatureHandler)); _logger = loggerHandler ?? throw new ArgumentNullException(nameof(loggerHandler)); _checkSumService = checkSumService ?? throw new ArgumentNullException(nameof(checkSumService)); _downloadSettings = options?.Value ?? throw new ArgumentNullException(nameof(options)); _strictModeSettings = strictModeSettings.Value ?? throw new ArgumentNullException(nameof(strictModeSettings)); _serverIdentityHandler = serverIdentityHandler ?? throw new ArgumentNullException(nameof(serverIdentityHandler)); } public bool AddFileDownload(ActionToReport actionToReport) { var fileDownload = GetDownloadFile(actionToReport.ReportIndex, ((DownloadAction)actionToReport.TwinAction).Source, actionToReport.ChangeSpecId); if (fileDownload == null) { var destPath = ((DownloadAction)actionToReport.TwinAction).DestinationPath; var existFile = _filesDownloads.Any(item => string.IsNullOrWhiteSpace(destPath) || _fileStreamerWrapper.GetFullPath(item.Action.DestinationPath) == _fileStreamerWrapper.GetFullPath(destPath)); if (existFile) { _logger.Warn($"File {destPath} is already exist in download list"); return false; } fileDownload = new FileDownload { ActionReported = actionToReport }; _filesDownloads.Add(fileDownload); } fileDownload.Action.Sign = ((DownloadAction)actionToReport.TwinAction).Sign; return true; } public async Task InitFileDownloadAsync(ActionToReport actionToReport, CancellationToken cancellationToken) { var file = GetDownloadFile(actionToReport.ReportIndex, ((DownloadAction)actionToReport.TwinAction).Source, actionToReport.ChangeSpecId); if (file != null) { try { _strictModeHandler.CheckFileAccessPermissions(TwinActionType.SingularDownload, file.Action.DestinationPath); if (await ChangeSignExists(file, cancellationToken)) { ArgumentNullException.ThrowIfNullOrEmpty(file.Action.DestinationPath); var isCreatedDownloadDirectory = InitDownloadPath(file); var destPath = GetDestinationPath(file); var isFileExist = _fileStreamerWrapper.FileExists(destPath); if (file.Report.Status == StatusType.InProgress && !isFileExist) // init inprogress file if it not exist { file.TotalBytesDownloaded = 0; file.Report.Progress = 0; file.Report.Status = StatusType.Pending; file.Report.CompletedRanges = ""; } else { var isBlocked = await HandleBlockedStatusAsync(file, isFileExist, destPath, isCreatedDownloadDirectory, cancellationToken); if (!isBlocked) { if (file.Report.Status == StatusType.Unzip) { await HandleCompletedDownloadAsync(file, cancellationToken); } else { if (isFileExist && file.TotalBytesDownloaded == 0) { file.TotalBytesDownloaded = _fileStreamerWrapper.GetFileLength(destPath); } if (file.Report.Status != StatusType.InProgress) { await _d2CMessengerHandler.SendFileDownloadEventAsync(cancellationToken, file.ActionReported.ChangeSpecId, file.Action.Source, file.ActionReported.ReportIndex); } else { await CheckIfNotRecivedDownloadMsgToFile(file, cancellationToken); } } } } } } catch (Exception ex) { HandleDownloadException(ex, file); } finally { if (file.Report.Status != null) { await SaveReportAsync(file, cancellationToken); } } } else { _logger.Error($"InitFileDownloadAsync, There is no active download for message {actionToReport.ReportIndex}"); } } private async Task<bool> HandleBlockedStatusAsync(FileDownload file, bool isFileExist, string destPath, bool isCreatedDownloadDirectory, CancellationToken cancellationToken) { if (file.Report.Status == StatusType.Blocked) { file.Report.Status = StatusType.Pending; } if ((isFileExist || (!isCreatedDownloadDirectory && file.Action.Unzip)) && file.Report.Status is not StatusType.InProgress && file.Report.Status is not StatusType.Unzip) { SetBlockedStatus(file, DownloadBlocked.FileAlreadyExist, cancellationToken); } else if (!_fileStreamerWrapper.isSpaceOnDisk(destPath, file.TotalBytes)) { SetBlockedStatus(file, DownloadBlocked.NotEnoughSpace, cancellationToken); } else if (!HasWritePermissionOnDir(Path.GetDirectoryName(file.Action.DestinationPath))) { SetBlockedStatus(file, DownloadBlocked.AccessDenied, cancellationToken); } return file.Report.Status == StatusType.Blocked; } private async Task<bool> ChangeSignExists(FileDownload file, CancellationToken cancellationToken) { if (!string.IsNullOrWhiteSpace(file?.Action?.Sign)) { return true; } if (!_strictModeSettings.StrictMode) { _logger.Info("No sign file key is sent, sending for signature"); await SendForSignatureAsync(file?.ActionReported, cancellationToken); return false; } else { throw new ArgumentNullException("Sign file key is required"); } } private void SetBlockedStatus(FileDownload file, DownloadBlocked resultCode, CancellationToken cancellationToken) { file.Report.Status = StatusType.Blocked; file.Report.ResultCode = resultCode.ToString(); _logger.Info($"File {file.Action.DestinationPath} sending blocked status, ResultCode: {resultCode}"); if (!cancellationToken.IsCancellationRequested) { Task.Run(async () => WaitInBlockedBeforeDownload(file, cancellationToken)); } } private async Task WaitInBlockedBeforeDownload(FileDownload file, CancellationToken cancellationToken) { await Task.Delay(TimeSpan.FromMinutes(_downloadSettings.BlockedDelayMinutes), cancellationToken); var fileDownload = GetDownloadFile(file.ActionReported.ReportIndex, file.Action.Source, file.ActionReported.ChangeSpecId); if (!cancellationToken.IsCancellationRequested && fileDownload is not null) { await InitFileDownloadAsync(file.ActionReported, cancellationToken); } } private async Task CheckIfNotRecivedDownloadMsgToFile(FileDownload file, CancellationToken cancellationToken) { var downloadedBytes = file.TotalBytesDownloaded; var existRanges = file.Report.CompletedRanges; await Task.Delay(TimeSpan.FromSeconds(_downloadSettings.CommunicationDelaySeconds), cancellationToken); if (!cancellationToken.IsCancellationRequested) { var isSameDownloadBytes = downloadedBytes == file.TotalBytesDownloaded && existRanges == file.Report.CompletedRanges; if (isSameDownloadBytes) { _logger.Info($"CheckIfNotRecivedDownloadMsgToFile no change in download bytes, file {file.Action.Source}, report index {file.ActionReported.ReportIndex}"); var ranges = string.Join(",", GetExistRangesList(existRanges)); await _d2CMessengerHandler.SendFileDownloadEventAsync(cancellationToken, file.ActionReported.ChangeSpecId, file.Action.Source, file.ActionReported.ReportIndex, ranges); } } } private async Task SendForSignatureAsync(ActionToReport actionToReport, CancellationToken cancellationToken) { actionToReport.TwinReport.Status = StatusType.SentForSignature; SignFileEvent signFileEvent = new SignFileEvent() { MessageType = D2CMessageType.SignFileKey, ActionIndex = actionToReport.ReportIndex, FileName = ((DownloadAction)actionToReport.TwinAction).Source, BufferSize = SharedConstants.SIGN_FILE_BUFFER_SIZE, PropName = actionToReport.ReportPartName, ChangeSpecId = actionToReport.ChangeSpecId, ChangeSpecKey = actionToReport.ChangeSpecKey }; await _d2CMessengerHandler.SendSignFileEventAsync(signFileEvent, cancellationToken); } private void HandleDownloadException(Exception ex, FileDownload file) { _logger.Error(ex.Message); file.Report.Status = StatusType.Failed; file.Report.ResultText = ex.Message; file.Report.ResultCode = ex.GetType().Name; file.Report.Progress = null; file.Report.CompletedRanges = null; if (file.Action.Unzip) { _fileStreamerWrapper.DeleteFolder(file.Action.DestinationPath); } else { _fileStreamerWrapper.DeleteFile(GetDestinationPath(file)); } } private string GetDestinationPath(FileDownload file) { return file.Action.Unzip ? _fileStreamerWrapper.Combine(file.Action.DestinationPath, file.Action.Source) : file.Action.DestinationPath; } private bool InitDownloadPath(FileDownload file) { var extention = _fileStreamerWrapper.GetExtension(file.Action.DestinationPath); if (file.Action.Unzip) { if (_fileStreamerWrapper.GetExtension(file.Action.Source)?.Equals(".zip", StringComparison.OrdinalIgnoreCase) == false) { throw new ArgumentException("No zip file is sent"); } } else if (string.IsNullOrEmpty(extention)) { throw new ArgumentException($"Destination path {file.Action.DestinationPath} is not a file."); } var directory = file.Action.Unzip ? file.Action.DestinationPath : Path.GetDirectoryName(file.Action.DestinationPath); if (!string.IsNullOrWhiteSpace(directory) && !_fileStreamerWrapper.DirectoryExists(directory)) { _fileStreamerWrapper.CreateDirectory(directory); return true; } return false; } public bool HasWritePermissionOnDir(string directoryPath) { DirectoryInfo directoryInfo = _fileStreamerWrapper.CreateDirectoryInfo(directoryPath); DirectorySecurity directorySecurity = _fileStreamerWrapper.GetAccessControl(directoryInfo); AuthorizationRuleCollection accessRules = _fileStreamerWrapper.GetAccessRules(directorySecurity); var rules = accessRules?.Cast<FileSystemAccessRule>(); if (rules is not null && rules.Any(x => x.AccessControlType == AccessControlType.Deny)) { return false; } return true; } private void HandleFirstMessageAsync(FileDownload file, DownloadBlobChunkMessage message) { file.TotalBytes = message.FileSize; _strictModeHandler.CheckSizeStrictMode(TwinActionType.SingularDownload, file.TotalBytes, file.Action.DestinationPath); file.Stopwatch.Start(); } private async Task HandleCompletedDownloadAsync(FileDownload file, CancellationToken cancellationToken) { file.Stopwatch?.Stop(); var destPath = GetDestinationPath(file); var isVerify = await _signatureHandler.VerifyFileSignatureAsync(destPath, file.Action.Sign); if (isVerify) { file.Report.ResultCode = file.Report.ResultText = null; if (file.Action.Unzip) { file.Report.Status = StatusType.Unzip; await _twinReportHandler.UpdateReportActionAsync(Enumerable.Repeat(file.ActionReported, 1), cancellationToken); UnzipFileAsync(destPath, file.Action.DestinationPath); _fileStreamerWrapper.DeleteFile(destPath); _logger.Info($"Download complete, file {file.Action.Source}, report index {file.ActionReported.ReportIndex}"); } file.Report.Status = StatusType.Success; file.Report.Progress = 100; } else { var message = $"File {file.Action.DestinationPath} signature is not valid, the file will be deleted."; _logger.Error(message); throw new Exception(message); } } private async Task HandleEndRangeDownloadAsync(string filePath, DownloadBlobChunkMessage message, FileDownload file, CancellationToken cancellationToken) { var isRangeValid = await VerifyRangeCheckSumAsync(filePath, message.RangeStartPosition.GetValueOrDefault(), message.RangeEndPosition.GetValueOrDefault(), message.RangeCheckSum); if (!isRangeValid) { await _d2CMessengerHandler.SendFileDownloadEventAsync(cancellationToken, message.ChangeSpecId, message.FileName, file.ActionReported.ReportIndex, message.RangeIndex.ToString(), message.RangeStartPosition, message.RangeEndPosition); file.TotalBytesDownloaded -= (long)(message.RangeEndPosition - message.RangeStartPosition).GetValueOrDefault(); if (file.TotalBytesDownloaded < 0) { file.TotalBytesDownloaded = 0; } } else { file.Report.CompletedRanges = AddRange(file.Report.CompletedRanges, message.RangeIndex); } } private FileDownload? GetDownloadFile(int actionIndex, string fileName, string changeSpecId) { var file = _filesDownloads.FirstOrDefault(item => item.ActionReported.ReportIndex == actionIndex && item.Action.Source == fileName && (string.IsNullOrWhiteSpace(changeSpecId) || item.ActionReported.ChangeSpecId == changeSpecId)); return file; } public async Task HandleDownloadMessageAsync(DownloadBlobChunkMessage message, CancellationToken cancellationToken) { var file = GetDownloadFile(message.ActionIndex, message.FileName, message.ChangeSpecId); if (file == null) { _logger.Error($"There is no active download for message {message.GetMessageId()}"); return; } var filePath = GetDestinationPath(file); try { var fileLength = Math.Max(file.TotalBytes - _fileStreamerWrapper.GetFileLength(filePath), message.Offset + message.Data?.Length ?? 0); if (!_fileStreamerWrapper.isSpaceOnDisk(filePath, fileLength)) { SetBlockedStatus(file, DownloadBlocked.NotEnoughSpace, cancellationToken); _fileStreamerWrapper.DeleteFile(GetDestinationPath(file)); } if (file.Report.Status == StatusType.Blocked) { _logger.Info($"File {file.Action.DestinationPath} is blocked, message {message.GetMessageId()}"); return; } if (!string.IsNullOrWhiteSpace(message.Error)) { throw new Exception($"Backend error: {message.Error}"); } if (!file.Stopwatch.IsRunning) { HandleFirstMessageAsync(file, message); } await _fileStreamerWrapper.WriteChunkToFileAsync(filePath, message.Offset, message.Data); var downloadedFileBytes = _fileStreamerWrapper.GetFileLength(filePath); _strictModeHandler.CheckSizeStrictMode(TwinActionType.SingularDownload, downloadedFileBytes, file.Action.DestinationPath); if (message.RangeCheckSum != null) { await HandleEndRangeDownloadAsync(filePath, message, file, cancellationToken); } if (file.Report.CompletedRanges == GetCompletedRangesString(message.RangesCount)) { await HandleCompletedDownloadAsync(file, cancellationToken); } else { file.Report.Progress = CalculateBytesDownloadedPercent(file, message.Data.Length, message.Offset); file.Report.Status = StatusType.InProgress; file.Report.ResultCode = file.Report.ResultText = null; Task.Run(async () => CheckIfNotRecivedDownloadMsgToFile(file, cancellationToken)); } } catch (Exception ex) { HandleDownloadException(ex, file); } finally { await SaveReportAsync(file, cancellationToken); } } private string GetCompletedRangesString(int? rangesCount) { return rangesCount switch { 1 => "0", 2 => "0,1", _ => $"0-{rangesCount - 1}" }; } private async Task SaveReportAsync(FileDownload file, CancellationToken cancellationToken) { try { await _twinReportHandler.UpdateReportActionAsync(Enumerable.Repeat(file.ActionReported, 1), cancellationToken); if (file.Report.Status == StatusType.Failed || file.Report.Status == StatusType.Success) { RemoveFileFromList(file.ActionReported.ReportIndex, file.Action.Source, file.ActionReported.ChangeSpecId); await UpdateKnownIdentities(cancellationToken); } } catch (Exception ex) { _logger.Error($"SaveReportAsync failed message: {ex.Message}"); } } private float CalculateBytesDownloadedPercent(FileDownload file, long bytesLength, long offset) { const double KB = 1024.0; file.TotalBytesDownloaded += bytesLength; double progressPercent = Math.Round(file.TotalBytesDownloaded / (double)file.TotalBytes * 100, 2); double throughput = file.TotalBytesDownloaded / file.Stopwatch.Elapsed.TotalSeconds / KB; progressPercent = Math.Min(progressPercent, 99); // for cases that chunk in range send twice _logger.Info($"%{progressPercent:00} @pos: {offset:00000000000} Throughput: {throughput:0.00} KiB/s"); return (float)progressPercent; } private async Task<bool> VerifyRangeCheckSumAsync(string filePath, long startPosition, long endPosition, string checkSum) { long lengthToRead = endPosition - startPosition; byte[] data = _fileStreamerWrapper.ReadStream(filePath, startPosition, lengthToRead); var streamCheckSum = await _checkSumService.CalculateCheckSumAsync(data); return checkSum == streamCheckSum; } /// <summary> /// Modifies a string of numerical ranges by adding a specified integer to the existing ranges. /// </summary> /// <param name="rangesString">String of comma-separated numerical ranges.</param> /// <param name="rangeIndex">Integer to be added to the ranges.</param> /// <returns>Modified and sorted string of numerical ranges.</returns> /// /// <example> /// Example usage: /// <code> /// string modifiedRanges = AddRange("1-5,7,10-12", 9);//"1-5,7,9-12"; /// </code> /// </example> private string AddRange(string rangesString, int rangeIndex) { var ranges = GetExistRangesList(rangesString); ranges.Add(rangeIndex); ranges.Sort(); var newRangeString = string.Join(",", ranges.Distinct() .Select((value, index) => (value, index)) .GroupBy(pair => pair.value - pair.index) .Select(group => group.Select((pair, i) => pair.value)) .Select(range => range.Count() == 1 ? $"{range.First()}" : range.Count() == 2 ? $"{range.First()},{range.Last()}" : $"{range.First()}-{range.Last()}") .ToList()); return newRangeString; } private List<int> GetExistRangesList(string rangesString) { var ranges = new List<int>(); if (!string.IsNullOrWhiteSpace(rangesString)) { ranges = rangesString.Split(',') .SelectMany(part => part.Contains('-') ? Enumerable.Range( int.Parse(part.Split('-')[0]), int.Parse(part.Split('-')[1]) - int.Parse(part.Split('-')[0]) + 1) : new[] { int.Parse(part) }) .ToList(); } return ranges; } private void RemoveFileFromList(int actionIndex, string fileName, string changeSpecId) { _filesDownloads.RemoveAll(item => (item.Action.Source == fileName || item.ActionReported.ReportIndex == actionIndex) && item.ActionReported.ChangeSpecId == changeSpecId); } public void InitDownloadsList(List<ActionToReport> actions = null) { _filesDownloads.RemoveAll(item => GetFileFromAction(actions, item) == null); } private ActionToReport? GetFileFromAction(List<ActionToReport> actions, FileDownload fileDownload) { var file = actions?.FirstOrDefault(item => item.ReportIndex == fileDownload.ActionReported.ReportIndex && ((DownloadAction)item.TwinAction).Source == fileDownload.Action.Source && (string.IsNullOrWhiteSpace(fileDownload.ActionReported.ChangeSpecId) || item.ChangeSpecId == fileDownload.ActionReported.ChangeSpecId)); return file; } private async Task UpdateKnownIdentities(CancellationToken cancellationToken) { if (_filesDownloads.Count == 0 && !cancellationToken.IsCancellationRequested) { await _serverIdentityHandler.UpdateKnownIdentitiesFromCertificatesAsync(cancellationToken); } } public void UnzipFileAsync(string zipPath, string destinationPath) { using (ZipArchive archive = _fileStreamerWrapper.OpenZipFile(zipPath)) { foreach (ZipArchiveEntry entry in archive.Entries) { string completeFileName = _fileStreamerWrapper.Combine(destinationPath, entry.FullName); _fileStreamerWrapper.CreateDirectory(_fileStreamerWrapper.GetDirectoryName(completeFileName)!); if (!entry.FullName.EndsWith("/")) { entry.ExtractToFile(completeFileName, overwrite: true); _fileStreamerWrapper.SetLastWriteTimeUtc(completeFileName, entry.LastWriteTime.UtcDateTime); } } } } }
import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { BullRootModuleOptions, SharedBullConfigurationFactory, } from '@nestjs/bull'; @Injectable() export class BullSharedOptions implements SharedBullConfigurationFactory { constructor(private configService: ConfigService) {} createSharedConfiguration(): | Promise<BullRootModuleOptions> | BullRootModuleOptions { return { redis: { host: this.configService.get('REDIS_HOST'), port: this.configService.get('REDIS_PORT'), password: this.configService.get('REDIS_PASSWORD'), }, } as BullRootModuleOptions; } }
package com.intelligent.bot.service.sys.impl; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.exceptions.ValidateException; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.intelligent.bot.api.midjourney.loadbalancer.DiscordInstance; import com.intelligent.bot.api.midjourney.loadbalancer.DiscordLoadBalancer; import com.intelligent.bot.api.midjourney.support.DiscordAccountHelper; import com.intelligent.bot.base.exception.E; import com.intelligent.bot.base.result.B; import com.intelligent.bot.dao.DiscordAccountConfigDao; import com.intelligent.bot.model.DiscordAccountConfig; import com.intelligent.bot.model.base.BaseDeleteEntity; import com.intelligent.bot.model.base.BasePageHelper; import com.intelligent.bot.model.mj.doman.DiscordAccount; import com.intelligent.bot.model.mj.doman.ReturnCode; import com.intelligent.bot.model.req.sys.admin.DiscordAccountConfigAdd; import com.intelligent.bot.model.req.sys.admin.DiscordAccountConfigUpdate; import com.intelligent.bot.service.sys.IDiscordAccountConfigService; import com.intelligent.bot.utils.mj.AsyncLockUtils; import lombok.extern.log4j.Log4j2; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.time.Duration; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service @Transactional(rollbackFor = E.class) @Log4j2 public class DiscordAccountConfigServiceImpl extends ServiceImpl<DiscordAccountConfigDao, DiscordAccountConfig> implements IDiscordAccountConfigService { @Resource DiscordAccountHelper discordAccountHelper; @Resource DiscordLoadBalancer discordLoadBalancer; @Override public B<Page<DiscordAccountConfig>> queryPage(BasePageHelper req) { Page<DiscordAccountConfig> page = new Page<>(req.getPageNumber(),req.getPageSize()); return B.okBuild(baseMapper.queryPage(page)); } @Override public B<String> add(DiscordAccountConfigAdd req) { Long count = this.lambdaQuery() .eq(DiscordAccountConfig::getChannelId, req.getChannelId()) .or().eq(DiscordAccountConfig::getGuildId, req.getGuildId()) .count(); if(count > 0){ throw new E("账号信息已存在"); } DiscordAccountConfig discordAccountConfig = BeanUtil.copyProperties(req, DiscordAccountConfig.class); this.save(discordAccountConfig); DiscordAccount discordAccount = addAccount(discordAccountConfig); if(discordAccount.getState() == 1){ return B.okBuild("账号信息验证成功,已连接"); } return B.okBuild(); } @Override public B<String> update(DiscordAccountConfigUpdate req) { DiscordAccountConfig oldConfig = this.getById(req.getId()); DiscordAccountConfig discordAccountConfig = null; if(null != req.getChannelId() && null != req.getGuildId()){ Long count = this.lambdaQuery() .eq( DiscordAccountConfig::getChannelId, req.getChannelId()) .or().eq(DiscordAccountConfig::getGuildId, req.getGuildId()) .ne(DiscordAccountConfig::getId,req.getId()) .count(); if(count > 0){ throw new E("账号信息已存在"); } discordAccountConfig = BeanUtil.copyProperties(req, DiscordAccountConfig.class); }else { discordAccountConfig = oldConfig; discordAccountConfig.setState(req.getState()); } this.updateById(discordAccountConfig); this.discordLoadBalancer.remove(oldConfig); if(req.getState() == 1 ){ DiscordAccount discordAccount = addAccount(discordAccountConfig); if(discordAccount.getState() == 1){ return B.okBuild("账号信息验证成功,已连接"); } } return B.okBuild(); } @Override public B<Void> delete(BaseDeleteEntity req) { this.removeByIds(req.getIds()); return B.okBuild(); } @Override public DiscordAccount addAccount(DiscordAccountConfig configAccount) { DiscordAccount account = new DiscordAccount(); BeanUtil.copyProperties(configAccount, account); account.setId(configAccount.getChannelId()); DiscordInstance instance = this.discordAccountHelper.createDiscordInstance(account); if (null != account.getState() && account.getState() == 1) { List<DiscordInstance> instances = this.discordLoadBalancer.getAllInstances(); try { instance.startWss(); AsyncLockUtils.LockObject lock = AsyncLockUtils.waitForLock("wss:" + account.getChannelId(), Duration.ofSeconds(10)); if (ReturnCode.SUCCESS != (null == lock.getCode() ? 0 : lock.getCode())) { throw new ValidateException(lock.getDescription()); } instances.add(instance); } catch (Exception e) { log.error("Account({}) init fail, disabled: {}", account.getDisplay(), e.getMessage()); account.setState(0); } Set<String> enableInstanceIds = instances.stream().filter(DiscordInstance::isAlive).map(DiscordInstance::getInstanceId).collect(Collectors.toSet()); log.info("当前可用账号数 [{}] - {}", enableInstanceIds.size(), String.join(", ", enableInstanceIds)); } return account; } }
--- title: "2\\. Metabolic Rates" author: - name: Marguerite Butler url: https://butlerlab.org affiliation: School of Life Sciences, University of Hawaii affiliation_url: https://manoa.hawaii.edu/lifesciences/ description: "The different types of metabolic rates and what influences them" date: 2023-08-28 format: html: default pdf: default categories: [module 2, week 2, BMR, SMR, RMR, AMR, DMR ] --- # Pre-class materials ::: {.callout-note} ## Read ahead **Before class, you can prepare by reading the following materials:** 1. \[[Discussion Questions and reading assignment](../../discussions/Discussion_Week_2.pdf)\] Note that there are readings from your textbook (Withers, 1992) as well as Hill Wise and Anderson \[[(HWA)](https://drive.google.com/drive/folders/1ONGdTPdeQz2lgGgAiWyZ_yGRmmcNSwoV)\]. (These are on the shared google drive). ::: ### Announcements/Reminders - HW1 is [posted](../../homework/HW1metabolism.pdf) - You should have your book. $20 from SoLS Office St. John 101. - Turn in your Library Day worksheet in class. - Please friend me on Discord/ __Always tag your partners on anything group-related__ - Labs this Week - Meet at Honolulu Zoo at 1:30pm. LMK if you need a ride from campus. [Read Lab 2](../../labs/Lab2-zoo/Lab2.qmd). Bring: - Your lab notebook - A timing device (e.g. your phone) - Sun screen, hat, and sunglasses. It will be hot and sunny! - Water - One hardcopy of Lab 1 to turn in ### Week 2 Discussion Groups | Group | Partner 1 | Partner 2 | Partner 3 | |----|----|----|----|----| | 1 | Adry | Kirsten | Maisie | | 2 | Justin | Mayuka | Alvin | | 3 | Anna | Krystal | Morgan| | 4 | Matthew | Christina | Sasha | | 5 | Logan M | Richard | Logan B | | 6 | Kylie | Garrett | Jessica | ## Successful Discussions - [__Encourage equal participation__]{style="color: blue"} - [Take turns going first]{style="color: blue"} - __Dig deeper__ into a subject - Bring out __everyone's ideas__ - Explore and evaluate __arguments__ - Provide a forum for __pitching ideas__ and __practicing vocabulary__ - Are interactive, evaluate strengths and soft-spots # 2a. Metabolism and how do we measure the cost of being alive? {{< video https://youtu.be/NRrgZQrEiWc?si=1jk4xxtXYrrzjq5N&t=90 >}} ![](../../images/LiveFastDieYoung.png) ![Where metabolism comes from](../../images/AerobicRespiration.png) ## Discussion Questions 1. What is BMR and SMR? Why do we need both? What is the difference between BMR/SMR and RMR? What is AMR and MMR? 2. What is absolute aerobic scope and factorial aerobic scope? Is it specific to an activity? Why? What are the rough rules of thumb for how much higher RMR, AMR, and MMR are above BMR or SMR for active endotherms vs ectotherms? (Look in Withers). If you knew an animal’s RMR and the types of activity it did, what strategy could you use to estimate DMR (Daily Metabolic Rate)? ![An example of Metabolic Scope](../../images/MetabolicScope.png) 3. We know that MR varies by animal size and taxonomic group. If we knew the cost of running in a 70kg human (letʻs say approximately 10x BMR), how can we use this information to estimate the cost of the same activity in a different animal? What is the justification? ![Table 4-10 from Withers 1992](../../images/Table4-10notes.png) 4. What is direct and indirect calorimetry? Why can we metabolism by measuring an animal's heat production (think thermodynamics)? When we try to measure metabolism by measuring heat, or O2, or CO2 -- which methods are good for aerobic vs. anaerobic metabolism? ![](../../images/DirectCalorimetry.png) ![](../../images/BombCalorimetry.png) ![](../../images/Respirometry.png) # For Next Time - Meet at the Honolulu Zoo at 1:30pm - in front of main entrance - Add your fossil [here](https://docs.google.com/spreadsheets/d/1KarnLss0eE1tCsvq0mVCyLTtLD0Hf4m6RYuX9tSXb-0/edit#gid=0) - Continue the discussion! NOTE: We will discuss Anaerobic metabolism last (Friday) - HW1 due Friday # 2b. Size and Scaling ::: callout-note ## Reminders and materials 1. \[[Scaling Example](../../discussions/2.ScalingExample.pdf)\] 2. \[[Discussion Questions](../../discussions/Discussion_Week_2.pdf)\] Jump to Q6 3. \[[Slide Deck](../../powerpoints/2.Metabolism.pdf)\] 4. An exciting addition to our teaching team: Allison Fisher 5. Friday Class will be held on \[[Zoom](https://hawaii.zoom.us/j/95180706058)\] Please join using your UHID 6. \[[HW1](../../homework/HW1metabolism.pdf)\] Due Friday at midnight, written by hand. Submit in person or on Laulima 7. After Friday class, please fill out _Discussion Evaluations_ - look for email from __TEAMMATES__ ::: ## Scaling Podcast {{< video https://youtu.be/_NDNa_3Bon8 >}} ## If you would like some more review (optional) ### A walk through of BMR scaling equations {{< video https://youtu.be/uqGEBgspTI0 >}} ### Refresher on log_10, lines, and how much to feed your elephant {{< video https://youtu.be/sO9fLmkaVB8 >}} # For Next Week - Holiday on Monday - Labs will be back in EDM101 - Look ahead to the lecture post for 3. Temperature. Watch podcasts, etc. - Add your fossil [here](https://docs.google.com/spreadsheets/d/1KarnLss0eE1tCsvq0mVCyLTtLD0Hf4m6RYuX9tSXb-0/edit#gid=0) - HW1 due Friday Sept 1 at midnight - Due in two weeks \[[Background Bullet Points](../../projects/2023-09-06-design-background)\]
import { newScreenPoint, type ScreenPoint } from '@/oxyplot' /** * Provides functionality to decimate lines. */ export class Decimator { /** * Decimates lines by reducing all points that have the same integer x value to a maximum of 4 points (first, min, max, last). * @param input The input points. * @param output The decimated points. */ public static decimate(input: ScreenPoint[], output: ScreenPoint[]): void { if (input === undefined || input.length === 0) { return } let point = input[0] let currentX = Math.round(point.x) let currentMinY = Math.round(point.y) let currentMaxY = currentMinY let currentFirstY = currentMinY let currentLastY = currentMinY for (let i = 1; i < input.length; ++i) { point = input[i] const newX = Math.round(point.x) const newY = Math.round(point.y) if (newX !== currentX) { Decimator.addVerticalPoints(output, currentX, currentFirstY, currentLastY, currentMinY, currentMaxY) currentFirstY = currentLastY = currentMinY = currentMaxY = newY currentX = newX continue } if (newY < currentMinY) { currentMinY = newY } if (newY > currentMaxY) { currentMaxY = newY } currentLastY = newY } // Keep from adding an extra point for last currentLastY = currentFirstY === currentMinY ? currentMaxY : currentMinY Decimator.addVerticalPoints(output, currentX, currentFirstY, currentLastY, currentMinY, currentMaxY) } /** * Adds vertical points to the result list. * @param result The result. * @param x The x coordinate. * @param firstY The first y. * @param lastY The last y. * @param minY The minimum y. * @param maxY The maximum y. */ private static addVerticalPoints( result: ScreenPoint[], x: number, firstY: number, lastY: number, minY: number, maxY: number, ): void { result.push(newScreenPoint(x, firstY)) if (firstY === minY) { if (minY !== maxY) { result.push(newScreenPoint(x, maxY)) } if (maxY !== lastY) { result.push(newScreenPoint(x, lastY)) } return } if (firstY === maxY) { if (maxY !== minY) { result.push(newScreenPoint(x, minY)) } if (minY !== lastY) { result.push(newScreenPoint(x, lastY)) } return } if (lastY === minY) { if (minY !== maxY) { result.push(newScreenPoint(x, maxY)) } } else if (lastY === maxY) { if (maxY !== minY) { result.push(newScreenPoint(x, minY)) } } else { result.push(newScreenPoint(x, minY)) result.push(newScreenPoint(x, maxY)) } result.push(newScreenPoint(x, lastY)) } }
@model SciaSquash.Model.Entities.Player @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm("Edit", "Player", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Player</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.PlayerID) <div class="form-group"> @Html.Label("Image", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <div> @Html.Partial("PlayerAvatarPartial", new SciaSquash.Web.ViewModels.Shared.PlayerAvatarPartialViewModel { Player = Model, Height = 150.0, Width = 150.0 }) </div> </div> </div> <div class="form-group"> @Html.Label("Upload new image:", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <div> <input type="file" name="Image" class="form-control" /> </div> </div> </div> <div class="form-group"> @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.NickName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.NickName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.NickName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
# AWS EFS CSI driver Amazon Elastic File System (Amazon EFS) provides serverless, fully elastic file storage so that you can share file data without provisioning or managing storage capacity and performance. The Amazon EFS Container Storage Interface (CSI) driver provides a CSI interface that allows Kubernetes clusters running on AWS to manage the lifecycle of Amazon EFS file systems. This topic shows you how to deploy the Amazon EFS CSI driver to your Amazon EKS cluster. <!-- BEGIN_TF_DOCS --> ## Requirements | Name | Version | |------|---------| | <a name="requirement_terraform"></a> [terraform](#requirement\_terraform) | >= 1.0 | | <a name="requirement_aws"></a> [aws](#requirement\_aws) | >= 5.3.0 | | <a name="requirement_helm"></a> [helm](#requirement\_helm) | >= 2.10.1 | | <a name="requirement_kubernetes"></a> [kubernetes](#requirement\_kubernetes) | >= 2.22.0 | ## Providers | Name | Version | |------|---------| | <a name="provider_aws"></a> [aws](#provider\_aws) | >= 5.3.0 | | <a name="provider_helm"></a> [helm](#provider\_helm) | >= 2.10.1 | | <a name="provider_kubernetes"></a> [kubernetes](#provider\_kubernetes) | >= 2.22.0 | ## Modules No modules. ## Resources | Name | Type | |------|------| | [aws_iam_role.efs_csi_driver](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | | [aws_iam_role_policy_attachment.efs_csi_driver](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | | [helm_release.efs_csi](https://registry.terraform.io/providers/hashicorp/helm/latest/docs/resources/release) | resource | | [kubernetes_service_account.efs_csi_driver](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/service_account) | resource | ## Inputs | Name | Description | Type | Default | Required | |------|-------------|------|---------|:--------:| | <a name="input_csi_driver_image_pull_secrets"></a> [csi\_driver\_image\_pull\_secrets](#input\_csi\_driver\_image\_pull\_secrets) | CSI driver image pull secrets | `string` | n/a | yes | | <a name="input_csi_driver_name"></a> [csi\_driver\_name](#input\_csi\_driver\_name) | CSI driver name | `string` | n/a | yes | | <a name="input_csi_driver_namespace"></a> [csi\_driver\_namespace](#input\_csi\_driver\_namespace) | CSI driver namespace | `string` | n/a | yes | | <a name="input_csi_driver_node_selector"></a> [csi\_driver\_node\_selector](#input\_csi\_driver\_node\_selector) | CSI driver node selector | `any` | n/a | yes | | <a name="input_csi_driver_repository"></a> [csi\_driver\_repository](#input\_csi\_driver\_repository) | CSI driver repository | `string` | n/a | yes | | <a name="input_csi_driver_version"></a> [csi\_driver\_version](#input\_csi\_driver\_version) | CSI driver version | `string` | n/a | yes | | <a name="input_efs_csi_image"></a> [efs\_csi\_image](#input\_efs\_csi\_image) | EFS CSI image | `string` | n/a | yes | | <a name="input_efs_csi_tag"></a> [efs\_csi\_tag](#input\_efs\_csi\_tag) | EFS CSI tag | `string` | n/a | yes | | <a name="input_external_provisioner_image"></a> [external\_provisioner\_image](#input\_external\_provisioner\_image) | External provisioner image | `string` | n/a | yes | | <a name="input_external_provisioner_tag"></a> [external\_provisioner\_tag](#input\_external\_provisioner\_tag) | External provisioner tag | `string` | n/a | yes | | <a name="input_livenessprobe_image"></a> [livenessprobe\_image](#input\_livenessprobe\_image) | Livenessprobe image | `string` | n/a | yes | | <a name="input_livenessprobe_tag"></a> [livenessprobe\_tag](#input\_livenessprobe\_tag) | Livenessporbe tag | `string` | n/a | yes | | <a name="input_node_driver_registrar_image"></a> [node\_driver\_registrar\_image](#input\_node\_driver\_registrar\_image) | Node driver registrar image | `string` | n/a | yes | | <a name="input_node_driver_registrar_tag"></a> [node\_driver\_registrar\_tag](#input\_node\_driver\_registrar\_tag) | Node driver registrar tag | `string` | n/a | yes | | <a name="input_oidc_arn"></a> [oidc\_arn](#input\_oidc\_arn) | Cluster oidc arn | `string` | n/a | yes | | <a name="input_oidc_url"></a> [oidc\_url](#input\_oidc\_url) | Cluster oidc url | `string` | n/a | yes | | <a name="input_tags"></a> [tags](#input\_tags) | Tags for EFS CSI driver | `map(string)` | n/a | yes | ## Outputs | Name | Description | |------|-------------| | <a name="output_efs_csi_id"></a> [efs\_csi\_id](#output\_efs\_csi\_id) | EFS CSI Id | <!-- END_TF_DOCS -->
"use client" import Image from "next/image" import { useOrganization, useOrganizationList } from "@clerk/nextjs" import { cn } from "@/lib/utils" import { Hint } from "@/components/hint" interface ItemProps { id: string name: string imageUrl: string } export const Item = ({ id, name, imageUrl } : ItemProps ) => { const { organization } = useOrganization() const { setActive } = useOrganizationList() const isActive = organization?.id === id const handleImageClick = () => { if (!setActive) return setActive({ organization: id }) } return ( <div className="aspect-square relative"> <Hint label={name} side="right" align="start" sideOffset={18} > <Image src={imageUrl} alt={name} fill onClick={handleImageClick} className={cn("rounded-lg cursor-pointer opacity-75 hover:opacity-100 transition duration-100", isActive && "opacity-100")} /> </Hint> </div> ) }
package com.rk.afterstart import android.app.KeyguardManager import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.hardware.biometrics.BiometricPrompt import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.CancellationSignal import android.text.InputType import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.annotation.RequiresApi import androidx.compose.ui.platform.textInputServiceFactory import androidx.core.app.ActivityCompat import androidx.core.view.marginLeft import androidx.core.view.marginRight import com.google.android.material.dialog.MaterialAlertDialogBuilder class BioMetric : AppCompatActivity() { private var cancellation: CancellationSignal? = null private val authenticationCallback: BiometricPrompt.AuthenticationCallback get() = @RequiresApi(Build.VERSION_CODES.P) object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) { super.onAuthenticationError(errorCode, errString) NotifyUser("Authentication Error $errString") } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult?) { super.onAuthenticationSucceeded(result) NotifyUser("Authentication Success!!!") // startActivity(Intent(this@BioMetric, MainActivity::class.java)) } } @RequiresApi(Build.VERSION_CODES.P) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_secret_page) checkBioMetricSupport() findViewById<Button>(R.id.Authenticate).setOnClickListener { val biometricPrompt = BiometricPrompt.Builder(this) .setTitle("Authentication") .setSubtitle("Authentication is required") .setDescription("this app uses fingerprint protection to keep your data secure") .setNegativeButton( "Use Password", this.mainExecutor, DialogInterface.OnClickListener { dialog, which -> showPasswordDialog() }) .build() biometricPrompt.authenticate(getCancelationSignal(),mainExecutor,authenticationCallback) } } private fun getCancelationSignal(): CancellationSignal { cancellation = CancellationSignal() cancellation?.setOnCancelListener { NotifyUser("Authentication was canceled by user") } return cancellation as CancellationSignal } private fun checkBioMetricSupport(): Boolean { val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager if (!keyguardManager.isKeyguardSecure) { NotifyUser("Fingerprint authentication has not been enabled in settings") } if (ActivityCompat.checkSelfPermission( this, android.Manifest.permission.USE_BIOMETRIC ) != PackageManager.PERMISSION_GRANTED ) { NotifyUser("Fingerprint authentication permission is not enabled") return false } return if (packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { true } else { true } } private fun NotifyUser(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } private fun showPasswordDialog() { var inputEditText = EditText(this) inputEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD inputEditText.hint="Enter Password" val passwordPrompt = MaterialAlertDialogBuilder(this) .setTitle("Authentication") .setMessage("Enter your password") .setView(inputEditText) .setPositiveButton("OK") { dialog, which -> val enteredPassword = inputEditText.text.toString() // Check if entered password is correct if (enteredPassword == "123456") { NotifyUser("Password authentication successful") // Proceed to the next screen or perform desired action } else { NotifyUser("Invalid password") // Handle invalid password scenario } } .setNegativeButton("Cancel", null) .setCancelable(false) .create() passwordPrompt.show() } }
from typing import Optional import sklearn.naive_bayes as skl_nb import sklearn.dummy as skl_dummy import sklearn.linear_model as skl_lm import sklearn.ensemble as skl_ensemble import lib_processing TRAIN_MAX_INSTANCES: Optional[int] = None TEST_MAX_INSTANCES: Optional[int] = None def main() -> None: print("embedding") run_tests("dataset/train_embedding.csv", "dataset/dev_embedding.csv") print("tfidf") run_tests("dataset/train_tfidf.csv", "dataset/dev_tfidf.csv") def run_tests(train_file: str, test_file: str) -> None: (train_instances_wid, train_actual_labels, train_feature_column_names)\ = lib_processing.preprocess_labelled_data(train_file, TRAIN_MAX_INSTANCES) (test_instances_wid, test_actual_labels, test_feature_column_names)\ = lib_processing.preprocess_labelled_data(test_file, TEST_MAX_INSTANCES) # remove identity columns train_instances_noid = lib_processing.remove_identity_columns(train_instances_wid) test_instances_noid = lib_processing.remove_identity_columns(test_instances_wid) print("-- zero-R baseline") baseline_model = skl_dummy.DummyClassifier(strategy="prior") baseline_model.fit(train_instances_noid, train_actual_labels) baseline_predictions: list[int] = baseline_model.predict(test_instances_noid) lib_processing.eval_labels(baseline_predictions, test_actual_labels) print("-- NB") nb_gaussian = skl_nb.GaussianNB() nb_gaussian.fit(train_instances_noid, train_actual_labels) nb_predictions: list[int] = nb_gaussian.predict(test_instances_noid) lib_processing.eval_labels(nb_predictions, test_actual_labels) print("-- sklearn logistic_regression, iter=300") logreg_default = skl_lm.LogisticRegression(max_iter=300) logreg_default.fit(train_instances_noid, train_actual_labels) logreg_default_predictions: list[int] = logreg_default.predict(test_instances_noid) lib_processing.eval_labels(logreg_default_predictions, test_actual_labels) print("-- SGD Classifier default") sgd_model = skl_lm.SGDClassifier( loss="log_loss", shuffle=False ) sgd_model.fit(train_instances_noid, train_actual_labels) sgd_predictions: list[int] = sgd_model.predict(test_instances_noid) lib_processing.eval_labels(sgd_predictions, test_actual_labels) print("-- SGD Classifier lrate=0.1") sgd_model = skl_lm.SGDClassifier( loss="log_loss", learning_rate="constant", eta0=0.1, shuffle=False) sgd_model.fit(train_instances_noid, train_actual_labels) sgd_predictions: list[int] = sgd_model.predict(test_instances_noid) lib_processing.eval_labels(sgd_predictions, test_actual_labels) print("-- SGD Classifier lrate=0.01") sgd_model = skl_lm.SGDClassifier( loss="log_loss", learning_rate="constant", eta0=0.01, shuffle=False) sgd_model.fit(train_instances_noid, train_actual_labels) sgd_predictions: list[int] = sgd_model.predict(test_instances_noid) lib_processing.eval_labels(sgd_predictions, test_actual_labels) print("-- Ensemble Classifier") voting_model = skl_ensemble.VotingClassifier(estimators=[("sgd", sgd_model), ("logreg_default", logreg_default), ("nb_gaussian", nb_gaussian)], voting="hard") voting_model.fit(train_instances_noid, train_actual_labels) voting_predictions = voting_model.predict(test_instances_noid) lib_processing.eval_labels(voting_predictions, test_actual_labels) if __name__ == "__main__": main()
import 'package:firebase_auth/firebase_auth.dart'; class UserModel { late String phoneNumber; late String uid; late List<String> usersList; late List<String> groupList; UserModel({ required this.usersList, required this.groupList, required this.uid, required this.phoneNumber, }); //from map factory UserModel.fromMap(Map<String, dynamic> json) { return UserModel( phoneNumber: json['phoneNumber'] as String, uid: json['uid'] as String, usersList: (json['usersList'] as List<dynamic>).map((e) => e as String).toList(), groupList: (json['groupList'] as List<dynamic>).map((e) => e as String).toList(), ); } //to map Map<String, dynamic> toMap() { return { "uid": uid, "phoneNumber": phoneNumber, "groupList": groupList, "usersList": usersList, }; } } abstract class AuthBase { Future<UserModel> currentUser(); Stream<UserModel> get onAuthStateChanged; Future<void> signOut(); } class Auth implements AuthBase { final _firebaseAuth = FirebaseAuth.instance; UserModel _userFromFirebase(User? user) { return UserModel( uid: user!.uid, phoneNumber: user.phoneNumber!, groupList: [], usersList: []); } @override Future<UserModel> currentUser() async { final user = _firebaseAuth.currentUser; return _userFromFirebase(user); } @override Stream<UserModel> get onAuthStateChanged { return _firebaseAuth.authStateChanges().map(_userFromFirebase); } @override Future<void> signOut() async { await _firebaseAuth.signOut(); } }
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; use App\Models\Admin; class Register extends Mailable { use Queueable, SerializesModels; public $name; public $email; public $password; /** * Create a new message instance. * * @return void */ public function __construct(Admin $admin, $password) { $this->name = $admin->name; $this->email = $admin->email; $this->password = $password; // password or verification Code } /** * Build the message. * * @return $this */ public function build() { return $this->view('emails.Register') ->from(env('MAIL_USERNAME'),'Cartakk')->subject('Registration Credentials'); } }
import 'package:flutter/material.dart'; import '../models/alert_alignment.dart'; import '../widgets/custom_progress_indicator.dart'; class AlertOverlay extends StatefulWidget { final Duration duration; final Color backgroundColor; final Color accentColor; final IconData icon; final String title; final AlertAlignment alertAlignment; final double radius; const AlertOverlay({ Key? key, required this.duration, required this.backgroundColor, required this.accentColor, required this.icon, required this.title, required this.alertAlignment, required this.radius, }) : super(key: key); @override State<AlertOverlay> createState() => _AlertOverlayState(); } class _AlertOverlayState extends State<AlertOverlay> with TickerProviderStateMixin { AnimationController? animationController; Animation<double>? animation; double progress = 0.0; @override void initState() { animationController = AnimationController(vsync: this, duration: const Duration(seconds: 1)); animation = CurveTween(curve: Curves.fastOutSlowIn).animate(animationController!); animationController!.forward(); super.initState(); } @override void dispose() { animationController!.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Positioned( left: MediaQuery.of(context).size.width * 0.025, width: MediaQuery.of(context).size.width * 0.95, bottom: widget.alertAlignment == AlertAlignment.bottom ? MediaQuery.of(context).padding.bottom + kBottomNavigationBarHeight + 30 : null, top: widget.alertAlignment == AlertAlignment.top ? MediaQuery.of(context).padding.top + 30 : null, child: FadeTransition( opacity: animation!, child: ClipRRect( borderRadius: BorderRadius.circular(widget.radius), child: Material( child: Column( children: [ Container( color: widget.backgroundColor, padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15), width: MediaQuery.of(context).size.width * 0.95, child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Flexible( child: Text( widget.title, style: const TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500, ), ), ), Icon( widget.icon, color: Colors.white, ), ], ), ), CustomProgressIndicator( animationController: animationController, color: Colors.white, backgroundColor: widget.accentColor, ), ], ), ), ), ), ); } }
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Portifólio</title> <link rel="stylesheet" href="./css/style.css"> <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'> </head> <body> <header class="header"> <a href="#home" class="logo">Leonardo <span>Blanco</span></a> <i class='bx bx-menu' id="menu-icon"></i> <nav class="navbar"> <a href="#home" class="active">Home</a> <a href="#about">About</a> <a href="#projects">Projects</a> <a href="#skills">Skills</a> </nav> </header> <section class="home" id="home"> <div class="home-content"> <h3>Hi</h3> <h1>It's <span>Leonardo</span></h1> <h3 class="text-animation">I'm a <span></span></h3> <p>Sou desenvolvedor full stack, desde o desenvolvimento back-end ao front-end e implementação de soluções com bancos de dados. Estou sempre em busca de descobertas para criar soluções de alta qualidade.</p> <div class="social-icons"> <a href="https://www.linkedin.com/in/leonardo-blanco-perez/"><i class='bx bxl-linkedin-square' ></i></a> <a href="https://github.com/LeoBlanco123"><i class='bx bxl-github' ></i></a> </div> <a href="./curriculo/Currículo-Leonardo.pdf" download="Currículo Leonardo" class="btn">Download CV</a> </div> <div class="home-img"> <img src="./img/foto-perfil.png" alt=""> </div> </section> <section class="about" id="about"> <div class="about-img"> <img src="./img/foto-perfil.png" alt=""> </div> <div class="about-content"> <h2 class="heading">About <span>Me</span></h2> <h3 class="text-animation"><span></span></h3> <p>💻 Desenvolvedor Full Stack desde de 2023. <br>🎓 Cursando Análise e Desenvolvimento de Sistemas na FIAP. <br>💡 Interrese pelo desenvolvimento de aplicações back-end e front-end. <br>🚀 Buscando uma oportunidade de atuar com desenvolvedor</p> <a href="https://github.com/LeoBlanco123" class="btn">Read More</a> </div> </section> <section class="projects" id="projects"> <h2 class="heading">Projects</h2> <div class="projects-container"> <div class="projects-box"><img src="./img/pokemon.png" alt=""> <div class="projects-info"> <a href="https://leoblanco123.github.io/pokemon/"><i class="bx bx-link"></i></a> </div> </div> <div class="projects-box"><img src="./img/java-jersey.png" alt=""> <div class="projects-info"> <a href="https://github.com/LeoBlanco123/Api-Jersey-Java"><i class="bx bx-link"></i></a> </div> </div> <div class="projects-box"><img src="./img/Oracle-Python.webp" alt=""> <div class="projects-info"> <a href="https://github.com/LeoBlanco123/connection-python-db"><i class="bx bx-link"></i></a> </div> </div> <div class="projects-box"><img src="./img/buscador.png" alt=""> <div class="projects-info"> <a href="https://busca-cep-cyan.vercel.app/"><i class="bx bx-link"></i></a> </div> </div> <div class="projects-box"><img src="./img/img5.avif" alt=""> <div class="projects-info"> <h4>Loading</h4> <a href=""><i class="bx bx-link"></i></a> </div> </div> <div class="projects-box"><img src="./img/img5.avif" alt=""> <div class="projects-info"> <h4>Loading</h4> <a href=""><i class="bx bx-link"></i></a> </div> </div> </div> </section> <section class="skills" id="skills"> <h2 class="heading">Skills</h2> <div class="skill-bars"> <div class="bar"> <div class="info"> <span>Html</span> <div class="progress-line html"> <span></span> </div> </div> </div> <div class="bar"> <div class="info"> <span>Css</span> <div class="progress-line css"> <span></span> </div> </div> </div> <div class="bar"> <div class="info"> <span>JavaScript</span> <div class="progress-line javascript"> <span></span> </div> </div> </div> <div class="bar"> <div class="info"> <span>React</span> <div class="progress-line react"> <span></span> </div> </div> </div> <div class="bar"> <div class="info"> <span>Next Js</span> <div class="progress-line next"> <span></span> </div> </div> </div> <div class="bar"> <div class="info"> <span>Python</span> <div class="progress-line python"> <span></span> </div> </div> </div> <div class="bar"> <div class="info"> <span>Java</span> <div class="progress-line java"> <span></span> </div> </div> </div> <div class="bar"> <div class="info"> <span>C#</span> <div class="progress-line csharp"> <span></span> </div> </div> </div> </div> </section> <footer class="footer"> <div class="social"> <a href="https://www.linkedin.com/in/leonardo-blanco-perez/"><i class='bx bxl-linkedin-square' ></i></a> <a href="https://github.com/LeoBlanco123"><i class='bx bxl-github' ></i></a> </div> <ul class="list"> <li> <a href="#">FAQ</a> </li> <li> <a href="#about">About Me</a> </li> <li> <a href="#footer">Contact</a> </li> <li> <a href="#">Privacy Policy</a> </li> </ul> <p class="copyright">© Leonardo Blanco | All Rights Reserved</p> </footer> <script src="./js/script.js"></script> </body> </html>
<x-app-layout> <x-slot name="style"> @vite(['resources/css/app.css', 'resources/js/app.js', 'resources/css/style.css']) </x-slot> <x-slot name="banner"> <img src="{{ asset('storage/images/banner-4.jpg') }}" style="width: 100%; height: auto;"> </x-slot> <main> @if (!empty($routes)) <section class="section2"> <div class="container mt-5"> <ul class="nav nav-tabs product-nav-tabs product-tabs" role="tablist"> @foreach ($routes as $name => $route) <li class="nav-item"> <a class="nav-link {{ str_starts_with(url()->current(), $route) ? 'active' : 'pro-nav-link' }} fs-4" data-toggle="tab" href="{{ $route }}">{{ $name }}</a> </li> @endforeach </ul> </div> </section> @endif <section class="box-30"> <div class="container"> <!-- <h2 class="text-center mb-4 fw-bold">場景介紹</h2> --> <div class="row"> @if (!empty($q) && $products->isEmpty()) <p>抱歉,找不到與 "{{ $q }}" 相關的商品。</p> @else @foreach ($products as $product) <div class="col-sm-6 col-md-3 mb-4"> <div class="card bg-light p-1"> <img src="{{ asset('storage/images/sticker/gundam/STMG01G.jpg') }}" alt="" href="#" class="card-img-top w-100"> <div class="card-body"> <p class="text-black fs-4 text-left">{{ $product->name }}</p> <p class="text-muted fs-5 text-left">{{ $product->sub_name }}</p> <h3 class="card-text text-danger font-weight-bold"> NT$&nbsp;{{ $product->price }}</h3> <a href="{{ route('products.show', [ 'id' => $product->id, 'slug' => str($product->name)->slug('-', null), ]) }}" class="stretched-link"> </a> <a href="#" class="btn btn-dark w-100">加入購物車</a> </div> </div> </div> @endforeach @endif </div> </div> </section> {{ $products->appends(['q' => $q ?? ''])->links() }} </main> </x-app-layout>
package heap_pq; import java.util.Comparator; import java.util.PriorityQueue; /** * The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, * and the median is the mean of the two middle values. * * For example, for arr = [2,3,4], the median is 3. * For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5. * * Implement the MedianFinder class: * * MedianFinder() initializes the MedianFinder object. * void addNum(int num) adds the integer num from the data stream to the data structure. * double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted. * * Input * ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] * [[], [1], [2], [], [3], []] * Output * [null, null, null, 1.5, null, 2.0] * * Explanation * MedianFinder medianFinder = new MedianFinder(); * medianFinder.addNum(1); // arr = [1] * medianFinder.addNum(2); // arr = [1, 2] * medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) * medianFinder.addNum(3); // arr[1, 2, 3] * medianFinder.findMedian(); // return 2.0 * * Constraints: * * -105 <= num <= 105 * There will be at least one element in the data structure before calling findMedian. * At most 5 * 104 calls will be made to addNum and findMedian. * * Follow up: * If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution? * If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution? */ public class FindMedianFromDataStream { /* * keep two heaps (or priority queues): * * Max-heap small has the smaller half of the numbers. Min-heap large has * the larger half of the numbers. This gives me direct access to the one or * two middle values (they're the tops of the heaps), so getting the median * takes O(1) time. And adding a number takes O(log n) time. * * Supporting both min- and max-heap is more or less cumbersome, depending * on the language, so I simply negate the numbers in the heap in which I * want the reverse of the default order. To prevent this from causing a bug * with -231 (which negated is itself, when using 32-bit ints), I use * integer types larger than 32 bits. * * Using larger integer types also prevents an overflow error when taking * the mean of the two middle numbers. I think almost all solutions posted * previously have that bug. * * Update: These are pretty short already, but by now I wrote even shorter * ones. */ public static void main(String[] args) { FindMedianFromDataStream mediun = new FindMedianFromDataStream(); mediun.addNum(2); mediun.addNum(3); //System.out.println(mediun.findMedian()); mediun.addNum(4); //mediun.addNum(5); //mediun.addNum(6); System.out.println(maxpq.peek()); System.out.println(minpq.peek()); System.out.println(mediun.findMedian()); } private static PriorityQueue<Integer> maxpq; private static PriorityQueue<Integer> minpq; public FindMedianFromDataStream() { minpq = new PriorityQueue<Integer>(); maxpq = new PriorityQueue<Integer>(Comparator.reverseOrder()); } public void addNum(int num) { maxpq.offer(num); minpq.offer(maxpq.poll()); if(maxpq.size()<minpq.size()) { maxpq.offer(minpq.poll()); } } public double findMedian() { return (maxpq.size()==minpq.size())?((maxpq.peek()+minpq.peek())/2.0): maxpq.peek(); } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {HomeComponent} from "./pages/home/home.component"; import {CalcComponent} from "./pages/calc/calc.component"; import {AboutComponent} from "./pages/about/about.component"; const routes: Routes = [ {path : 'home', component : HomeComponent}, {path : 'calc' , component : CalcComponent}, {path : 'about', component : AboutComponent}, {path : '**', redirectTo : 'home'} ]; @NgModule({ imports: [RouterModule.forRoot(routes,{useHash:true})], exports: [RouterModule] }) export class AppRoutingModule { }
import React from "react"; import ReactDOM from "react-dom/client"; import swiggy_logo from "../swiggy_logo.png"; /** * * Header * - Logo * - Nav items * Body * - Search * - Restaurant Container * - RestaurentCard * - img * - Name of Res, Star Rating, Cuisine, Delivery Title * Footer * - Copyright * - Links * - Address * - Contact * * */ const resList = [ { card: { card: { "@type": "type.googleapis.com/swiggy.presentation.food.v2.Restaurant", info: { id: "298791", name: "Kabab Biryani Corner", cloudinaryImageId: "6ad23ea25d7f0dd202c3dbd660df2a46", locality: "Vivek Nagar", areaName: "Richmond Road", costForTwo: "₹200 for two", cuisines: ["Biryani", "Kebabs", "Chinese", "Indian"], avgRating: 3.8, parentId: "113069", avgRatingString: "3.8", totalRatingsString: "100+", sla: { deliveryTime: 31, lastMileTravel: 4.3, serviceability: "SERVICEABLE", slaString: "30-35 mins", lastMileTravelString: "4.3 km", iconType: "ICON_TYPE_EMPTY", }, availability: { nextCloseTime: "2024-04-04 05:00:00", opened: true, }, badges: {}, isOpen: true, aggregatedDiscountInfoV2: { header: "25% OFF", shortDescriptionList: [ { discountType: "Percentage", operationType: "RESTAURANT", }, ], descriptionList: [ { meta: "25% off on all orders", discountType: "Percentage", operationType: "RESTAURANT", }, ], }, type: "F", badgesV2: { entityBadges: { textBased: {}, imageBased: {}, textExtendedBadges: {}, }, }, orderabilityCommunication: { title: {}, subTitle: {}, message: {}, customIcon: {}, }, differentiatedUi: { displayType: "ADS_UI_DISPLAY_TYPE_ENUM_DEFAULT", differentiatedUiMediaDetails: { mediaType: "ADS_MEDIA_ENUM_IMAGE", lottie: {}, video: {}, }, }, reviewsSummary: {}, displayType: "RESTAURANT_DISPLAY_TYPE_DEFAULT", restaurantOfferPresentationInfo: {}, externalRatings: { aggregatedRating: { rating: "--", }, }, ratingsDisplayPreference: "RATINGS_DISPLAY_PREFERENCE_SHOW_SWIGGY", }, analytics: {}, cta: { link: "swiggy://menu?restaurant_id=298791&source=collection&query=Biryani", text: "RESTAURANT_MENU", type: "DEEPLINK", }, widgetId: "collectionV5RestaurantListWidget_SimRestoRelevance_food", }, relevance: { type: "RELEVANCE_TYPE_ON_MENU_RETURN", sectionId: "MENU_RETURN_FOOD", }, }, }, { card: { card: { "@type": "type.googleapis.com/swiggy.presentation.food.v2.Restaurant", info: { id: "93498", name: "Behrouz Biryani", cloudinaryImageId: "a4ffed13eb197c6df43dfe1c756560e5", locality: "Rashtriya Vidyalaya Rd", areaName: "Jayanagar", costForTwo: "₹500 for two", cuisines: [ "Biryani", "North Indian", "Kebabs", "Mughlai", "Lucknowi", "Hyderabadi", "Desserts", "Beverages", ], avgRating: 4.2, parentId: "1803", avgRatingString: "4.2", totalRatingsString: "1K+", sla: { deliveryTime: 31, lastMileTravel: 4.1, serviceability: "SERVICEABLE", slaString: "30-35 mins", lastMileTravelString: "4.1 km", iconType: "ICON_TYPE_EMPTY", }, availability: { nextCloseTime: "2024-04-04 03:00:00", opened: true, }, badges: { textExtendedBadges: [ { iconId: "guiltfree/GF_Logo_android_3x", shortDescription: "options available", fontColor: "#7E808C", }, ], }, isOpen: true, aggregatedDiscountInfoV2: { header: "50% OFF", shortDescriptionList: [ { meta: "Use SWIGGY50", discountType: "Percentage", operationType: "RESTAURANT", }, ], descriptionList: [ { meta: "50% off up to ₹100 | Use code SWIGGY50", discountType: "Percentage", operationType: "RESTAURANT", }, ], }, type: "F", badgesV2: { entityBadges: { textExtendedBadges: { badgeObject: [ { attributes: { description: "", shortDescription: "options available", fontColor: "#7E808C", iconId: "guiltfree/GF_Logo_android_3x", }, }, ], }, textBased: {}, imageBased: {}, }, }, orderabilityCommunication: { title: {}, subTitle: {}, message: {}, customIcon: {}, }, differentiatedUi: { displayType: "ADS_UI_DISPLAY_TYPE_ENUM_DEFAULT", differentiatedUiMediaDetails: { mediaType: "ADS_MEDIA_ENUM_IMAGE", lottie: {}, video: {}, }, }, reviewsSummary: {}, displayType: "RESTAURANT_DISPLAY_TYPE_DEFAULT", restaurantOfferPresentationInfo: {}, externalRatings: { aggregatedRating: { rating: "--", }, }, ratingsDisplayPreference: "RATINGS_DISPLAY_PREFERENCE_SHOW_SWIGGY", }, analytics: {}, cta: { link: "swiggy://menu?restaurant_id=93498&source=collection&query=Biryani", text: "RESTAURANT_MENU", type: "DEEPLINK", }, widgetId: "collectionV5RestaurantListWidget_SimRestoRelevance_food", }, relevance: { type: "RELEVANCE_TYPE_ON_MENU_RETURN", sectionId: "MENU_RETURN_FOOD", }, }, }, { card: { card: { "@type": "type.googleapis.com/swiggy.presentation.food.v2.Restaurant", info: { id: "63048", name: "Sharief Bhai", cloudinaryImageId: "5015204e6868e99a2e4d84880af68c5a", locality: "Frazer Town", areaName: "Frazer Town", costForTwo: "₹400 for two", cuisines: [ "Biryani", "Kebabs", "Mughlai", "Arabian", "South Indian", "Rolls & Wraps", "Street Food", "Fast Food", "Desserts", "Beverages", ], avgRating: 4.3, parentId: "5734", avgRatingString: "4.3", totalRatingsString: "10K+", sla: { deliveryTime: 31, lastMileTravel: 4.7, serviceability: "SERVICEABLE", slaString: "30-35 mins", lastMileTravelString: "4.7 km", iconType: "ICON_TYPE_EMPTY", }, availability: { nextCloseTime: "2024-04-04 03:01:00", opened: true, }, badges: { imageBadges: [ { imageId: "Rxawards/_CATEGORY-Biryani.png", description: "Delivery!", }, ], }, isOpen: true, aggregatedDiscountInfoV2: { header: "40% OFF", shortDescriptionList: [ { meta: "Use TRYNEW", discountType: "Percentage", operationType: "RESTAURANT", }, ], descriptionList: [ { meta: "40% off up to ₹80 | Use code TRYNEW", discountType: "Percentage", operationType: "RESTAURANT", }, ], }, type: "F", badgesV2: { entityBadges: { imageBased: { badgeObject: [ { attributes: { imageId: "Rxawards/_CATEGORY-Biryani.png", description: "Delivery!", }, }, ], }, textExtendedBadges: {}, textBased: {}, }, }, orderabilityCommunication: { title: {}, subTitle: {}, message: {}, customIcon: {}, }, differentiatedUi: { displayType: "ADS_UI_DISPLAY_TYPE_ENUM_DEFAULT", differentiatedUiMediaDetails: { mediaType: "ADS_MEDIA_ENUM_IMAGE", lottie: {}, video: {}, }, }, reviewsSummary: {}, displayType: "RESTAURANT_DISPLAY_TYPE_DEFAULT", restaurantOfferPresentationInfo: {}, externalRatings: { aggregatedRating: { rating: "4.0", ratingCount: "1K+", }, source: "GOOGLE", sourceIconImageId: "v1704440323/google_ratings/rating_google_tag", }, ratingsDisplayPreference: "RATINGS_DISPLAY_PREFERENCE_SHOW_SWIGGY", }, analytics: {}, cta: { link: "swiggy://menu?restaurant_id=63048&source=collection&query=Biryani", text: "RESTAURANT_MENU", type: "DEEPLINK", }, widgetId: "collectionV5RestaurantListWidget_SimRestoRelevance_food", }, relevance: { type: "RELEVANCE_TYPE_ON_MENU_RETURN", sectionId: "MENU_RETURN_FOOD", }, }, }, { card: { card: { "@type": "type.googleapis.com/swiggy.presentation.food.v2.Restaurant", info: { id: "575063", name: "Veg Daawat by Behrouz", cloudinaryImageId: "2b579171cefc545ce6479e21c0016798", locality: "Rashtriya Vidyalaya Road", areaName: "Jayanagar", costForTwo: "₹700 for two", cuisines: [ "Biryani", "North Indian", "Kebabs", "Mughlai", "Lucknowi", "Hyderabadi", "Desserts", "Beverages", ], avgRating: 4, veg: true, parentId: "344904", avgRatingString: "4.0", totalRatingsString: "10+", sla: { deliveryTime: 28, lastMileTravel: 4.1, serviceability: "SERVICEABLE", slaString: "25-30 mins", lastMileTravelString: "4.1 km", iconType: "ICON_TYPE_EMPTY", }, availability: { nextCloseTime: "2024-04-04 03:00:00", opened: true, }, badges: { imageBadges: [ { imageId: "v1695133679/badges/Pure_Veg111.png", description: "pureveg", }, ], }, isOpen: true, aggregatedDiscountInfoV2: { header: "50% OFF", shortDescriptionList: [ { meta: "Use SWIGGY50", discountType: "Percentage", operationType: "RESTAURANT", }, ], descriptionList: [ { meta: "50% off up to ₹100 | Use code SWIGGY50", discountType: "Percentage", operationType: "RESTAURANT", }, ], }, type: "F", badgesV2: { entityBadges: { textBased: {}, imageBased: { badgeObject: [ { attributes: { imageId: "v1695133679/badges/Pure_Veg111.png", description: "pureveg", }, }, ], }, textExtendedBadges: {}, }, }, orderabilityCommunication: { title: {}, subTitle: {}, message: {}, customIcon: {}, }, differentiatedUi: { displayType: "ADS_UI_DISPLAY_TYPE_ENUM_DEFAULT", differentiatedUiMediaDetails: { mediaType: "ADS_MEDIA_ENUM_IMAGE", lottie: {}, video: {}, }, }, reviewsSummary: {}, displayType: "RESTAURANT_DISPLAY_TYPE_DEFAULT", restaurantOfferPresentationInfo: {}, externalRatings: { aggregatedRating: { rating: "--", }, }, ratingsDisplayPreference: "RATINGS_DISPLAY_PREFERENCE_SHOW_SWIGGY", }, analytics: {}, cta: { link: "swiggy://menu?restaurant_id=575063&source=collection&query=Biryani", text: "RESTAURANT_MENU", type: "DEEPLINK", }, widgetId: "collectionV5RestaurantListWidget_SimRestoRelevance_food", }, relevance: { type: "RELEVANCE_TYPE_ON_MENU_RETURN", sectionId: "MENU_RETURN_FOOD", }, }, }, { card: { card: { "@type": "type.googleapis.com/swiggy.presentation.food.v2.Restaurant", info: { id: "224868", name: "Ambur Dum Biriyani", cloudinaryImageId: "t04etzr7nwfwal3afwtn", locality: "Binnamangala", areaName: "Indiranagar", costForTwo: "₹300 for two", cuisines: ["Indian", "Mughlai"], avgRating: 3.9, parentId: "31395", avgRatingString: "3.9", totalRatingsString: "1K+", sla: { deliveryTime: 33, lastMileTravel: 6.2, serviceability: "SERVICEABLE", slaString: "30-35 mins", lastMileTravelString: "6.2 km", iconType: "ICON_TYPE_EMPTY", }, availability: { nextCloseTime: "2024-04-10 00:00:00", opened: true, }, badges: {}, isOpen: true, aggregatedDiscountInfoV2: { header: "30% OFF", shortDescriptionList: [ { meta: "Use TRYNEW", discountType: "Percentage", operationType: "RESTAURANT", }, ], descriptionList: [ { meta: "30% off up to ₹75 | Use code TRYNEW", discountType: "Percentage", operationType: "RESTAURANT", }, ], }, type: "F", badgesV2: { entityBadges: { textExtendedBadges: {}, textBased: {}, imageBased: {}, }, }, orderabilityCommunication: { title: {}, subTitle: {}, message: {}, customIcon: {}, }, differentiatedUi: { displayType: "ADS_UI_DISPLAY_TYPE_ENUM_DEFAULT", differentiatedUiMediaDetails: { mediaType: "ADS_MEDIA_ENUM_IMAGE", lottie: {}, video: {}, }, }, reviewsSummary: {}, displayType: "RESTAURANT_DISPLAY_TYPE_DEFAULT", restaurantOfferPresentationInfo: {}, externalRatings: { aggregatedRating: { rating: "--", }, }, ratingsDisplayPreference: "RATINGS_DISPLAY_PREFERENCE_SHOW_SWIGGY", }, analytics: {}, cta: { link: "swiggy://menu?restaurant_id=224868&source=collection&query=Biryani", text: "RESTAURANT_MENU", type: "DEEPLINK", }, widgetId: "collectionV5RestaurantListWidget_SimRestoRelevance_food", }, relevance: { type: "RELEVANCE_TYPE_ON_MENU_RETURN", sectionId: "MENU_RETURN_FOOD", }, }, }, { card: { card: { "@type": "type.googleapis.com/swiggy.presentation.food.v2.Restaurant", info: { id: "170539", name: "Donne Biryani Adda", cloudinaryImageId: "FOOD_CATALOG/IMAGES/CMS/2024/3/17/387fd175-df96-4e5d-a07e-2b44d18fbe42_1985a561-1b08-4538-a39f-f1c61ce2b3b1.jpg_compressed", locality: "Appareddy Palya", areaName: "Indiranagar", costForTwo: "₹200 for two", cuisines: ["Biryani", "South Indian", "Desserts", "Beverages"], avgRating: 3.7, parentId: "20115", avgRatingString: "3.7", totalRatingsString: "1K+", sla: { deliveryTime: 26, lastMileTravel: 6.2, serviceability: "SERVICEABLE", slaString: "25-30 mins", lastMileTravelString: "6.2 km", iconType: "ICON_TYPE_EMPTY", }, availability: { nextCloseTime: "2024-04-04 03:00:00", opened: true, }, badges: {}, isOpen: true, aggregatedDiscountInfoV2: { header: "40% OFF", shortDescriptionList: [ { meta: "Use TRYNEW", discountType: "Percentage", operationType: "RESTAURANT", }, ], descriptionList: [ { meta: "40% off up to ₹80 | Use code TRYNEW", discountType: "Percentage", operationType: "RESTAURANT", }, ], }, type: "F", badgesV2: { entityBadges: { textBased: {}, imageBased: {}, textExtendedBadges: {}, }, }, orderabilityCommunication: { title: {}, subTitle: {}, message: {}, customIcon: {}, }, differentiatedUi: { displayType: "ADS_UI_DISPLAY_TYPE_ENUM_DEFAULT", differentiatedUiMediaDetails: { mediaType: "ADS_MEDIA_ENUM_IMAGE", lottie: {}, video: {}, }, }, reviewsSummary: {}, displayType: "RESTAURANT_DISPLAY_TYPE_DEFAULT", restaurantOfferPresentationInfo: {}, externalRatings: { aggregatedRating: { rating: "--", }, }, ratingsDisplayPreference: "RATINGS_DISPLAY_PREFERENCE_SHOW_SWIGGY", }, analytics: {}, cta: { link: "swiggy://menu?restaurant_id=170539&source=collection&query=Biryani", text: "RESTAURANT_MENU", type: "DEEPLINK", }, widgetId: "collectionV5RestaurantListWidget_SimRestoRelevance_food", }, relevance: { type: "RELEVANCE_TYPE_ON_MENU_RETURN", sectionId: "MENU_RETURN_FOOD", }, }, }, { card: { card: { "@type": "type.googleapis.com/swiggy.presentation.food.v2.Restaurant", info: { id: "440349", name: "Sultan dum biryani", cloudinaryImageId: "d5qph22phd4yrebcisie", locality: "1st Stage", areaName: "Indiranagar", costForTwo: "₹300 for two", cuisines: ["Biryani", "Desserts"], avgRating: 3.9, parentId: "265464", avgRatingString: "3.9", totalRatingsString: "100+", sla: { deliveryTime: 33, lastMileTravel: 6.2, serviceability: "SERVICEABLE", slaString: "30-35 mins", lastMileTravelString: "6.2 km", iconType: "ICON_TYPE_EMPTY", }, availability: { nextCloseTime: "2024-04-10 00:00:00", opened: true, }, badges: {}, isOpen: true, aggregatedDiscountInfoV2: { header: "30% OFF", shortDescriptionList: [ { meta: "Use TRYNEW", discountType: "Percentage", operationType: "RESTAURANT", }, ], descriptionList: [ { meta: "30% off up to ₹75 | Use code TRYNEW", discountType: "Percentage", operationType: "RESTAURANT", }, ], }, type: "F", badgesV2: { entityBadges: { textBased: {}, imageBased: {}, textExtendedBadges: {}, }, }, orderabilityCommunication: { title: {}, subTitle: {}, message: {}, customIcon: {}, }, differentiatedUi: { displayType: "ADS_UI_DISPLAY_TYPE_ENUM_DEFAULT", differentiatedUiMediaDetails: { mediaType: "ADS_MEDIA_ENUM_IMAGE", lottie: {}, video: {}, }, }, reviewsSummary: {}, displayType: "RESTAURANT_DISPLAY_TYPE_DEFAULT", restaurantOfferPresentationInfo: {}, externalRatings: { aggregatedRating: { rating: "--", }, }, ratingsDisplayPreference: "RATINGS_DISPLAY_PREFERENCE_SHOW_SWIGGY", }, analytics: {}, cta: { link: "swiggy://menu?restaurant_id=440349&source=collection&query=Biryani", text: "RESTAURANT_MENU", type: "DEEPLINK", }, widgetId: "collectionV5RestaurantListWidget_SimRestoRelevance_food", }, relevance: { type: "RELEVANCE_TYPE_ON_MENU_RETURN", sectionId: "MENU_RETURN_FOOD", }, }, }, ]; const Header = () => { return ( <div className="header"> <div className="logo-container"> <img className="logo" src={swiggy_logo} alt="Swiggy Logo" /> </div> <div className="nav-items"> <ul> <li>Home</li> <li>About Us</li> <li>Contact Us</li> <li>Cart</li> </ul> </div> </div> ); }; const RestaurantCard = (props) => { const { resData } = props; const { cloudinaryImageId, name, cuisines, avgRating, costForTwo, id } = resData.card.card?.info; return ( <div className="res-card"> <img className="res-logo" alit="res-logo" src={ "https://media-assets.swiggy.com/swiggy/image/upload/fl_lossy,f_auto,q_auto,w_660/" + cloudinaryImageId } /> <h3>{name}</h3> <h4>{cuisines}</h4> <h4>{avgRating} stars</h4> <h4>{costForTwo}</h4> </div> ); }; const Body = () => { return ( <div className="body"> <div className="search">Search</div> <div className="res-container"> {resList.map((restaurant, index) => ( <RestaurantCard key={index} resData={restaurant} /> ))} </div> </div> ); }; const AppLayout = () => { return ( <div className="app"> <Header /> <Body /> </div> ); }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<AppLayout />);
import datetime from DAO import assignment_dao from sdms_bot_creating import bot from templates import notification from aiogram import types, Dispatcher from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from services.authorization_service import whitelist from keyboards.auth_menu_keyboard import auth_keyboard from aiogram.dispatcher.filters.state import State, StatesGroup from keyboards.assignment_keyboards.assignment_menu import a_menu from keyboards.assignment_keyboards.cancel_assignment_keyboard import cancel_a from keyboards.recipient_keyboard import recipient_for_admin, recipient_for_head posts = ['ADMIN', 'HEAD', 'SPEC'] class Assignment(StatesGroup): # Assignment State class recipient = State() name = State() desc = State() owner = State() name_for_cancel = State() delegated = State() name_for_delegated = State() async def assignments_menu(message: types.Message): if message.from_user.id not in whitelist: await bot.send_message(message.from_user.id, notification.auth_notification, reply_markup=auth_keyboard) else: await bot.send_message(message.from_user.id, "Выберите опцию:", reply_markup=a_menu) async def create_new_assignment(message: types.Message): if message.from_user.id not in whitelist: await bot.send_message(message.from_user.id, notification.auth_notification, reply_markup=auth_keyboard) elif whitelist[message.from_user.id][0] == 'SPEC': await bot.send_message(message.from_user.id, notification.cant_give_assignments[0]) elif whitelist[message.from_user.id][0] == 'HEAD': await Assignment.recipient.set() await bot.send_message(message.from_user.id, notification.recipient_assignment, reply_markup=recipient_for_head) else: await Assignment.recipient.set() await bot.send_message(message.from_user.id, notification.recipient_assignment, reply_markup=recipient_for_admin) async def cancel_creating_assignment(message: types.Message, state: FSMContext): current_state = await state.get_state() if current_state is None: return await state.finish() await bot.send_message(message.from_user.id, notification.cancel_notifications[1], reply_markup=a_menu) async def recipient_assignment(message: types.Message, state=FSMContext): async with state.proxy() as data: data['recipient'] = message.text if message.text == 'ADMIN': await bot.send_message(message.from_user.id, notification.cant_give_assignments[1], reply_markup=a_menu) await state.finish() elif whitelist[message.from_user.id][0] == 'HEAD' and message.text == 'HEAD' or \ whitelist[message.from_user.id][0] == 'ADMIN' and data['recipient'] == 'ADMIN': await bot.send_message(message.from_user.id, notification.cant_give_assignments[1], reply_markup=a_menu) await state.finish() elif message.text not in posts: await bot.send_message(message.from_user.id, notification.user_doesnt_exist, reply_markup=a_menu) await state.finish() else: await Assignment.next() await bot.send_message(message.from_user.id, notification.assignment_name, reply_markup=cancel_a) async def name_assignment(message: types.Message, state=FSMContext): async with state.proxy() as data: data['name'] = message.text exits_records = assignment_dao.check_on_exists(data['name']) if exits_records: await bot.send_message(message.from_user.id, notification.assignment_already_exist) await state.finish() elif not exits_records: await Assignment.next() await bot.send_message(message.from_user.id, notification.assignment_desc) async def desc_assignment(message: types.Message, state: FSMContext): async with state.proxy() as data: data['desc'] = message.text await owner_assignment(message, state) async def owner_assignment(message: types.Message, state: FSMContext): date = datetime.datetime.now().date() async with state.proxy() as data: owner = whitelist[message.from_user.id][0] assignment_dao.create_assignment(data['name'], data['desc'], date, owner, data['recipient']) await bot.send_message(message.from_user.id, notification.assignment_ready, reply_markup=a_menu) await state.finish() async def start_cancel_assignment(message: types.Message): if message.from_user.id not in whitelist: await bot.send_message(message.from_user.id, notification.auth_notification, reply_markup=auth_keyboard) elif whitelist[message.from_user.id][0] == 'SPEC': await bot.send_message(message.from_user.id, notification.cant_cancel_assignment) else: await Assignment.name_for_cancel.set() await bot.send_message(message.from_user.id, notification.assignment_name) async def cancel_canceling_assignment(message: types.Message, state: FSMContext): current_state = await state.get_state() if current_state is None: return await state.finish() await bot.send_message(message.from_user.id, notification.cancel_notifications[2]) async def cancel_assignment(message: types.Message, state: FSMContext): async with state.proxy() as data: data['name_for_cancel'] = message.text owner = assignment_dao.search_owner_by_a_name(data['name_for_cancel']) a_id = assignment_dao.search_a_id_by_a_name(data['name_for_cancel']) if owner is None: await bot.send_message(message.from_user.id, notification.assignment_doesnt_exist, reply_markup=a_menu) await state.finish() elif owner[0] == 'ADMIN' and whitelist[message.from_user.id][0] != 'ADMIN': await bot.send_message(message.from_user.id, notification.cant_cancel_assignment) await state.finish() else: assignment_dao.cancel_assignment(a_id[0]) await bot.send_message(message.from_user.id, notification.assignment_cancel) await state.finish() async def assignment_delegate(message: types.Message): if message.from_user.id not in whitelist: await bot.send_message(message.from_user.id, notification.auth_notification, reply_markup=auth_keyboard) elif whitelist[message.from_user.id][0] == 'SPEC': await bot.send_message(message.from_user.id, notification.cant_delegated_assignment) else: await Assignment.delegated.set() await bot.send_message(message.from_user.id, notification.delegated_recipient) async def cancel_delegated_assignment(message: types.Message, state: FSMContext): current_state = await state.get_state() if current_state is None: return await state.finish() await bot.send_message(message.from_user.id, notification.cancel_notifications[3], reply_markup=a_menu) async def post_for_delegated(message: types.Message, state: FSMContext): async with state.proxy() as data: data['delegated'] = message.text if message.text == 'ADMIN' or message.text == 'HEAD': await bot.send_message(message.from_user.id, notification.cant_delegated_admin, reply_markup=a_menu) await state.finish() else: await Assignment.next() await bot.send_message(message.from_user.id, notification.assignment_name) async def name_for_delegated(message: types.Message, state: FSMContext): async with state.proxy() as data: data['name_for_delegated'] = message.text a_id = assignment_dao.search_a_id_by_a_name(message.text) a_active = assignment_dao.check_on_active(a_id[0]) if a_id is None: await bot.send_message(message.from_user.id, notification.assignment_doesnt_exist) await state.finish() elif a_id is not None: if a_active[0] == 'Закрыто': await bot.send_message(message.from_user.id, notification.a_is_closed, reply_markup=a_menu) await state.finish() else: await bot.send_message(message.from_user.id, notification.a_is_closed, reply_markup=a_menu) assignment_dao.delegated_assignment(data['delegated'], a_id[0]) await bot.send_message(message.from_user.id, notification.delegated_success) await state.finish() async def find_all_assignments(message: types.Message): if message.from_user.id not in whitelist: await bot.send_message(message.from_user.id, notification.auth_notification, reply_markup=auth_keyboard) else: if whitelist[message.from_user.id][0] == 'ADMIN': admin_assignments = assignment_dao.find_all_assignment() if not admin_assignments: await bot.send_message(message.from_user.id, notification.no_active_assignment) else: assignment = "\n📃 ".join(admin_assignments) await bot.send_message(message.from_user.id, f"{notification.all_assignments} \n\n📃 {assignment}") elif whitelist[message.from_user.id][0] == 'HEAD': head_assignments = assignment_dao.find_all_assignment_for_head() if not head_assignments: await bot.send_message(message.from_user.id, notification.no_active_assignment) else: assignment = "\n📃 ".join(head_assignments) await bot.send_message(message.from_user.id, f"{notification.all_assignments} \n\n📃 {assignment}") elif whitelist[message.from_user.id][0] == 'SPEC': spec_assignments = assignment_dao.find_all_assignment_for_spec() if not spec_assignments: await bot.send_message(message.from_user.id, notification.no_active_assignment) else: assignment = "\n📃 ".join(spec_assignments) await bot.send_message(message.from_user.id, f"{notification.all_assignments} \n\n📃 {assignment}") def assignment_register(dp: Dispatcher): dp.register_message_handler(assignments_menu, Text(equals="поручения", ignore_case=True)) dp.register_message_handler(create_new_assignment, Text(equals='новое поручение', ignore_case=True), state=None) dp.register_message_handler(cancel_creating_assignment, Text(equals='отменить создание', ignore_case=True), state="*") dp.register_message_handler(recipient_assignment, state=Assignment.recipient) dp.register_message_handler(name_assignment, state=Assignment.name) dp.register_message_handler(desc_assignment, state=Assignment.desc) dp.register_message_handler(owner_assignment, state=Assignment.owner) dp.register_message_handler(find_all_assignments, Text(equals="все поручения", ignore_case=True)) dp.register_message_handler(start_cancel_assignment, Text(equals="закрыть поручение", ignore_case=True), state=None) dp.register_message_handler(cancel_canceling_assignment, Text(equals="отменить закрытие", ignore_case=True), state="*") dp.register_message_handler(cancel_assignment, state=Assignment.name_for_cancel) dp.register_message_handler(assignment_delegate, Text(equals="делегировать поручение", ignore_case=True), state=None) dp.register_message_handler(cancel_delegated_assignment, Text(equals='отменить делегирование', ignore_case=True), state="*") dp.register_message_handler(post_for_delegated, state=Assignment.delegated) dp.register_message_handler(name_for_delegated, state=Assignment.name_for_delegated)
# Flashcards Make flashcards to capture all of your *knowledge*, aka anything you learn *about the test*. !!! note "Terminology note" On this page, and elsewhere in *the lightweight LSAT*, I use this format to describe flashcards: > "Side A" / "Side B" ## Anki I strongly recommend using **Anki**, an open-source program that helps you review your flashcards efficiently using spaced repetition. !!! info "" Go here to download [Anki][anki] !!! tip "Anki tips" [This comic ][comic]{:target="_blank"} explains how spaced repetition systems like Anki help you learn better. [This video ][anki-settings]{:target="_blank"} can help you figure out what the Anki settings do and how you can adjust them. The [official manual ][anki-manual]{:target="_blank"} is also useful. ## Memorize everything you can If something about the test is memorizable, memorize it. Memorizing will save you precious time and brain-power on test day. !!! example When you learn on [this page][reason] that there are 3 families of reasoning questions, then you can make a flashcard to make sure that knowledge sticks in your brain: > "What are the 3 families of reasoning questions?" / "(1) argue; (2) describe; and (3) infer" When you review that card you may realize that you don't actually *understand* the differences. That tells you that you have more reading to do, and more flashcards to make, perhaps like: > "What distinguishes the describe family from the argue family?" / "You won't have to criticize the argument on describe Qs" ## Keep flashcards simple As a general rule, stick to one idea per card. Simpler cards makes it easier to test your knowledge. When you review, it will be more obvious when you get it wrong. Meaning, simple flashcards make it easier to be honest with yourself. !!! warning "Skills are hard to memorize" To memorize a skill, consider using the format: "When I see X / I will do Y." For more complex skills, consider making a [checklist] instead of a flashcard. ??? idea "Law School Connection" I wish I'd known about Anki before law school. You'll look like a savant in class if you make 1-3 flashcards about the (a) holding, (b) key facts, and (c) core reasoning for every case you read. [anki]: https://apps.ankiweb.net/ [comic]: https://ncase.me/remember/ [anki-settings]: https://www.youtube.com/watch?v=uLfczzq9z_8 [anki-manual]: https://docs.ankiweb.net/getting-started.html [checklist]: checklists.md [reason]: ../reason/reason.md
import style from './index.module.css'; import { useDispatch } from '../..'; import { useNavigate } from "react-router-dom"; import { FC, useEffect } from 'react'; import { wsFeedInit, wsFeedCloseConnection } from '../../services/actions/ws-feed'; import { TStore, TWSAnOrder } from '../../utils/types'; import OrderLI from '../order-li'; import { useSelector } from '../..'; const Feed: FC = () => { const dispatch = useDispatch() const navigate = useNavigate() const getFeed = (store: TStore) => store.feed const { totalToday, total, orders, wsConnected, error } = useSelector(getFeed) const onClick = (order: TWSAnOrder) => { navigate(`/feed/${order.number}`, {state: {modalReferer: '/feed/'}}) } useEffect(() => { dispatch(wsFeedInit()) return () => {dispatch(wsFeedCloseConnection())} }, []) return ( <> {!wsConnected && !error && ( <div className={style.placeholder}> <p className="text text_type_main-large">Загружаю историю заказов..</p> </div> )} {!wsConnected && error && ( <div className={style.placeholder}> <p className="text text_type_main-large">Произошла ошибка при подключении</p> </div> )} {wsConnected && ( <> <div className={style.feedWrap}> <p className="text text_type_main-large">Лента заказов</p> <ol className={`${style.feed} scrollable`}> {orders.map((x) => <OrderLI key={x['_id']} {...x} onClick={onClick} />)} </ol> </div> <div className={style.statsWrap}> <div className={style.tableau}> <div className={style.tableauBox}> <p className="text text_type_main-medium">Готовы:</p> <ol className={style.tableauOL}> {orders.filter((x) => x.status === 'done').slice(0, 10).map((x) => ( <li key={x['_id']} className={style.tableauLI}> <p className="text text_type_main-medium" style={{color: '#00cccc'}}>{x['number']}</p> </li> ))} </ol> </div> <div className={style.tableauBox}> <p className="text text_type_main-medium">В работе:</p> <ol className={style.tableauOL}> {orders.filter((x) => x.status === 'pending').slice(0, 10).map((x) => ( <li key={x['_id']} className={style.tableauLI}> <p className="text text_type_main-medium">{x['number']}</p> </li> ))} </ol> </div> </div> <p className="text text_type_main-medium">Выполнено за всё время:</p> <h3 className={`${style.metrics} text text_type_digits-large`}>{total}</h3> <p className="text text_type_main-medium">Выполнено за сегодня:</p> <h3 className={`${style.metrics} text text_type_digits-large`}>{totalToday}</h3> </div> </> )} </> ) } export default Feed;
import express, { Request, Response } from "express"; import { ApolloServer } from "@apollo/server"; import { expressMiddleware } from "@apollo/server/express4"; import { InMemoryLRUCache } from "@apollo/utils.keyvaluecache"; import { applyMiddleware } from "graphql-middleware"; import { makeExecutableSchema } from "@graphql-tools/schema"; import dotenv from "dotenv"; import cors from "cors"; import cookieSession from "cookie-session"; import Redis from "ioredis"; import { typeDefs } from "./graphql/typedefs"; import resolvers from "./graphql/resolvers"; import { middleware } from "./middlewares"; import dbConnect from "./db"; import models from "./models"; dotenv.config(); const app = express(); export const redisClient = new Redis({ host: process.env.REDIS_HOST, port: 6379, }); const port = process.env.PORT || 8080; // app.set("trust proxy", 1); app.use(cors({ credentials: true, origin: process.env.ORIGIN_URL })); app.use(express.json({ limit: "50mb" })); app.use(express.urlencoded({ extended: true })); app.use( cookieSession({ signed: false, }) ); dbConnect(); const schema = makeExecutableSchema({ typeDefs, resolvers }); const schemaWithMiddleware = applyMiddleware(schema, middleware); const startServer = async () => { //Create an instance of Apollo Server const server: ApolloServer = new ApolloServer({ schema: schemaWithMiddleware, cache: new InMemoryLRUCache({ maxSize: Math.pow(2, 20) * 100, // ~100MiB ttl: 300, // 5 minutes (in seconds) }), }); await server.start(); app.use( "/graphql", // cors<cors.CorsRequest>({ // origin: "http://localhost:3000", // credentials: true, // }), expressMiddleware(server, { context: async ({ req }) => ({ req: req, client: redisClient, models: models, }), }) ); redisClient.on("connect", () => console.log("Redis Client connected")); redisClient.on("error", (err) => console.log("Redis Client Error", err)); app.get("/", (req: Request, res: Response) => { res.json({ data: "api working" }); }); app.listen(port, () => { console.log(`🚀 Server ready at at http://localhost:${port}`); // console.log(`gql path is ${apolloServer.graphqlPath}`); }); }; startServer();
package com.example.demo.domain; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.HashSet; import java.util.Set; @Entity @Data @AllArgsConstructor @NoArgsConstructor @Builder @Table(name = "types") public class Type { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; @OneToMany(mappedBy = "type",fetch = FetchType.LAZY) private Set<Product> products = new HashSet<>(); public Type(Integer id, String name) { this.id = id; this.name = name; } }
package com.shopcuatao.bangiay.dtos; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.persistence.Column; import jakarta.validation.constraints.Min; import lombok.*; import java.time.LocalDate; import java.util.Date; import java.util.List; @AllArgsConstructor @NoArgsConstructor @Getter @Setter @Builder public class OrderDTO { @JsonProperty("user_id") private int userId; @JsonProperty("full_name") private String fullName; @JsonProperty("email") private String email; @JsonProperty("phone_number") private String phoneNumber; private String note; private String status; @Min(value = 0,message = "tong tien >0") @JsonProperty("total_money") private Float totalMoney; @JsonProperty("shipping_method") private String shippingMethod; @JsonProperty("shipping_adress") private String shippingAdress; @JsonProperty("shipping_date") private Date shippingDate; @JsonProperty( "payment_method") private String payMentmethod; private boolean active; @JsonProperty("cart_item") List<CartItemDTO> cartItemDTOS; }
package com.mikyegresl.valostat.features.agent.details import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.LocalOverscrollConfiguration import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.material.Card import androidx.compose.material.Divider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil.compose.AsyncImage import com.mikyegresl.valostat.R import com.mikyegresl.valostat.base.model.ValoStatLocale import com.mikyegresl.valostat.base.model.agent.AgentAbilityDto import com.mikyegresl.valostat.base.model.agent.AgentOriginDto import com.mikyegresl.valostat.base.model.agent.AgentRoleDto import com.mikyegresl.valostat.common.compose.ShowingErrorState import com.mikyegresl.valostat.common.compose.ShowingLoadingState import com.mikyegresl.valostat.common.compose.TopBarBackButton import com.mikyegresl.valostat.features.agent.agentAbilitiesMock import com.mikyegresl.valostat.features.video.player.exoplayer.ExoAudioPlayer import com.mikyegresl.valostat.ui.dimen.ElemSize import com.mikyegresl.valostat.ui.dimen.Padding import com.mikyegresl.valostat.ui.theme.ValoStatTypography import com.mikyegresl.valostat.ui.theme.mainTextDark import com.mikyegresl.valostat.ui.theme.secondaryBackgroundDark import com.mikyegresl.valostat.ui.theme.secondaryTextDark import com.mikyegresl.valostat.ui.theme.surfaceDark import com.mikyegresl.valostat.ui.theme.washWhite import com.mikyegresl.valostat.ui.widget.gradientModifier import org.koin.androidx.compose.koinViewModel private const val TAG = "AgentDetailsScreen" data class AgentDetailsActions( val onBackPressed: () -> Unit = {} ) @Preview @Composable fun PreviewAgentAbilityItem() { AgentAbilityItem( modifier = Modifier, ability = agentAbilitiesMock().first() ) } @Composable fun AgentDetailsScreen( agentId: String, locale: ValoStatLocale, viewModel: AgentDetailsViewModel = koinViewModel(), onBackPressed: () -> Unit ) { LaunchedEffect(agentId, locale) { viewModel.dispatchIntent(AgentDetailsIntent.UpdateAgentDetailsIntent(agentId, locale)) } val state = viewModel.state.collectAsStateWithLifecycle() when (val viewState = state.value) { is AgentDetailsScreenState.AgentDetailsDataState -> { AgentDetailsAsDataState( modifier = Modifier, state = viewState, actions = AgentDetailsActions( onBackPressed = onBackPressed ) ) } is AgentDetailsScreenState.AgentDetailsLoadingState -> { ShowingLoadingState() } is AgentDetailsScreenState.AgentDetailsErrorState -> { ShowingErrorState(errorMessage = viewState.t.message) } } } @OptIn(ExperimentalFoundationApi::class) @Composable fun AgentDetailsAsDataState( modifier: Modifier = Modifier, state: AgentDetailsScreenState.AgentDetailsDataState, actions: AgentDetailsActions ) { val context = LocalContext.current val lifecycleOwner = LocalLifecycleOwner.current val scope = rememberCoroutineScope() val audioPlayer = remember { ExoAudioPlayer( context = context, mediaUrl = state.details.voiceLine.voiceline.wave, lifecycleOwner = lifecycleOwner, uiCoroutineScope = scope, ) } val playerModifier = Modifier CompositionLocalProvider(LocalOverscrollConfiguration provides null) { LazyColumn( modifier = modifier .fillMaxSize() ) { item { AgentDetailsTopBar( title = state.details.displayName, imageSrc = state.details.fullPortrait ) { actions.onBackPressed() } } item { AgentDescriptionItem( modifier = Modifier .fillMaxWidth() .padding( top = Padding.Dp16, start = Padding.Dp32, end = Padding.Dp32 ), state = state, playerView = { DisposableEffect( audioPlayer.RenderPlayerView(modifier = playerModifier) ) { onDispose { audioPlayer.releaseResources() } } } ) } agentAbilities( abilities = state.details.abilities ).invoke(this) } } } @Composable fun AgentDetailsTopBar( title: String, imageSrc: String, onBackPressed: () -> Unit ) { val screenHeight = LocalConfiguration.current.screenHeightDp val containerMinHeight by remember { mutableStateOf((screenHeight / 1.8).dp) } val containerMaxHeight by remember { mutableStateOf((screenHeight / 1.7).dp) } Column( modifier = gradientModifier( 35f, .55f to surfaceDark, .55f to secondaryBackgroundDark ) .fillMaxWidth() .heightIn(containerMinHeight, containerMaxHeight) ) { Row( modifier = Modifier .fillMaxWidth() .padding( top = Padding.Dp24, start = Padding.Dp24, end = Padding.Dp24 ), horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically ) { TopBarBackButton(onBackPressed = onBackPressed) Text( modifier = Modifier .weight(1f), text = title, textAlign = TextAlign.Center, style = ValoStatTypography.subtitle1 ) } AsyncImage( modifier = Modifier.fillMaxSize(), model = imageSrc, contentScale = ContentScale.FillWidth, contentDescription = title ) } } @Composable fun AgentDescriptionItem( modifier: Modifier = Modifier, state: AgentDetailsScreenState.AgentDetailsDataState, playerView: @Composable () -> Unit ) { val commonRowModifier = Modifier.fillMaxWidth() val dividerModifier = Modifier.padding(vertical = Padding.Dp8) Column( modifier = modifier ) { Spacer(Modifier.padding(vertical = Padding.Dp16)) AgentOriginSection( modifier = commonRowModifier, origin = state.origin ) Divider( modifier = dividerModifier, color = washWhite, thickness = 1.dp ) AgentRoleSection( modifier = commonRowModifier, role = state.details.role ) Divider( modifier = dividerModifier, color = washWhite, thickness = 1.dp ) PointsForUltimateSection( modifier = commonRowModifier, pointsForUltimate = state.pointsForUltimate.toString() ) Divider( modifier = dividerModifier, color = washWhite, thickness = 1.dp ) VoiceLineSection( modifier = commonRowModifier, playerView = playerView ) Divider( modifier = dividerModifier, color = washWhite, thickness = 1.dp ) Text( text = state.details.description, style = ValoStatTypography.caption ) Divider( modifier = dividerModifier, color = washWhite, thickness = 1.dp ) } } @Composable fun AgentOriginSection( modifier: Modifier = Modifier, origin: AgentOriginDto ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "${stringResource(id = R.string.origin)}:", style = ValoStatTypography.caption.copy(color = secondaryTextDark) ) Row( verticalAlignment = Alignment.CenterVertically ) { AsyncImage( model = origin.iconUrl, contentDescription = stringResource(id = origin.countryName) ) Spacer(modifier = Modifier.padding(horizontal = Padding.Dp4)) Text( text = stringResource(id = origin.countryName), style = ValoStatTypography.caption ) } } } @Composable fun AgentRoleSection( modifier: Modifier = Modifier, role: AgentRoleDto ) { Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "${stringResource(id = R.string.role)}:", style = ValoStatTypography.caption.copy(color = secondaryTextDark) ) Row( verticalAlignment = Alignment.CenterVertically ) { AsyncImage( modifier = Modifier.size(ElemSize.Dp16), model = role.displayIcon, contentScale = ContentScale.Fit, contentDescription = stringResource(id = R.string.role) ) Spacer(modifier = Modifier.padding(horizontal = Padding.Dp4)) Text( text = role.displayName, style = ValoStatTypography.caption ) } } } @Composable fun PointsForUltimateSection( modifier: Modifier = Modifier, pointsForUltimate: String, ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "${stringResource(id = R.string.points_for_ulti)}:", style = ValoStatTypography.caption.copy(color = secondaryTextDark) ) Text( text = pointsForUltimate, style = ValoStatTypography.caption ) } } @Composable fun VoiceLineSection( modifier: Modifier = Modifier, playerView: @Composable () -> Unit ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "${stringResource(id = R.string.voiceline)}:", style = ValoStatTypography.caption.copy(color = secondaryTextDark) ) playerView() } } fun agentAbilities( abilities: List<AgentAbilityDto> ) : LazyListScope.() -> Unit = { item { Text( modifier = Modifier.padding(vertical = Padding.Dp16, horizontal = Padding.Dp32), text = stringResource(id = R.string.abilities), style = ValoStatTypography.caption.copy(color = secondaryTextDark) ) } abilities.forEach { item { AgentAbilityItem(ability = it) Spacer(modifier = Modifier.padding(vertical = Padding.Dp16)) } } } @Composable fun AgentAbilityItem( modifier: Modifier = Modifier, ability: AgentAbilityDto ) { Card( modifier = modifier .fillMaxWidth() .padding(horizontal = Padding.Dp32), border = BorderStroke(1.dp, secondaryTextDark) ) { Column( modifier = Modifier.padding(Padding.Dp16) ) { Text( text = ability.displayName, style = ValoStatTypography.caption.copy(color = secondaryTextDark) ) Row( modifier = Modifier.padding(Padding.Dp8), verticalAlignment = Alignment.CenterVertically ) { AsyncImage( modifier = Modifier.size(ElemSize.Dp36), model = ability.displayIcon, contentDescription = ability.displayName ) Spacer(modifier = Modifier.padding(horizontal = Padding.Dp4)) Text( text = "${stringResource(id = R.string.type)}: ", style = ValoStatTypography.caption.copy(color = secondaryTextDark) ) Text( text = ability.slot, style = ValoStatTypography.subtitle2 ) } Text( text = buildAnnotatedString { val descCaption = "${stringResource(id = R.string.description)}: " withStyle( style = SpanStyle( color = secondaryTextDark, fontSize = 14.sp ) ) { append(descCaption) } withStyle( style = SpanStyle( color = mainTextDark, fontSize = 13.sp ) ) { append(ability.description) } }, style = ValoStatTypography.caption ) } } }
const displayCalc = document.querySelector('.display'); const allBtns = document.querySelectorAll('button'); let operator = ''; let currentValue = ''; let previousValue = ''; let exp = ''; let hasDecimal = false; allBtns.forEach((buttons) => { buttons.addEventListener('click', handleClick); }); document.addEventListener('keydown', handleKey); function updateDisplay(value) { displayCalc.textContent = value; } function handleClick(event) { const button = event.target; if (button.classList.contains('operands')) { appendNumber(button.textContent); } else if (button.classList.contains('operators')) { appendOperator(button.textContent); } else if (button.classList.contains('clearAll')) { clearDisplay(); } else if (button.classList.contains('delete')) { deletePreviousDigit(); } else if (button.classList.contains('decimal')) { addDecimal(); } else if (button.classList.contains('equal')) { performOperation(); } } function handleKey(event) { event.preventDefault(); const keyPress = event.key; if (isOperator(keyPress)) { appendOperator(keyPress); } else if (keyPress >= '0' && keyPress <= '9') { appendNumber(keyPress); } else if (keyPress === '.') { addDecimal(); } else if (keyPress === '%') { appendOperator('%'); } else if (keyPress === 'Escape' || keyPress === 'Delete') { clearDisplay(); } else if (keyPress === 'Backspace') { deletePreviousDigit(); } else if (keyPress === 'Enter') { performOperation(); } } function isOperator(symbol) { if (symbol === '+' || symbol === '-' || symbol === '*' || symbol === '/') { return true; } else { return false; } } function appendNumber(operands) { currentValue += operands; exp += operands; updateDisplay(exp); } function appendOperator(op) { if (currentValue === '') return; //will display nothing if theres no value entered first if (op == '%') { currentValue = parseFloat(currentValue) / 100; } else { performOperation(); //this will evaluate the first the operation if another operator is entered operator = op; previousValue = currentValue; currentValue = ''; } exp += op; updateDisplay(exp); } function performOperation() { if (currentValue === '' || operator === '') return; //will not display nothing if theres no value and operator entered let firstValue = parseFloat(previousValue); let secondValue = parseFloat(currentValue); let result = 0; switch (operator) { case '+': result = firstValue + secondValue; break; case '-': result = firstValue - secondValue; break; case 'x': case '*': result = firstValue * secondValue; break; case '÷': case '/': if (secondValue == 0) { updateDisplay('Error cannot be divided by 0'); return; } result = firstValue / secondValue; break; } currentValue = result; previousValue = ''; operator = ''; exp = currentValue; hasDecimal = false; updateDisplay(currentValue); } function clearDisplay() { currentValue = ''; previousValue = ''; operator = ''; exp = ''; hasDecimal = false; updateDisplay(''); } function deletePreviousDigit() { updateDisplay(displayCalc.textContent.slice(0, -1)); exp = exp.slice(0, -1); } function addDecimal() { if (!hasDecimal) { currentValue += '.'; exp += '.'; hasDecimal = true; } updateDisplay(currentValue); }
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree, } from '@angular/router'; import { map, Observable, take } from 'rxjs'; import { AuthService } from 'app/core/services/auth.service'; @Injectable({ providedIn: 'root', }) export class LoggedGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.authService.userSubject.pipe( take(1), map((user) => { const isAuthenticated: boolean = !!user; return isAuthenticated ? true : this.router.createUrlTree(['/auth/login']); }) ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "forge-std/Test.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import "../../utils/fixtures/OffersLoansRefinancesFixtures.sol"; import "../../../interfaces/niftyapes/offers/IOffersStructs.sol"; import "../../../interfaces/niftyapes/lending/ILendingStructs.sol"; import "../../../interfaces/niftyapes/lending/ILendingEvents.sol"; contract TestSupplyCErc20 is Test, OffersLoansRefinancesFixtures { function setUp() public override { super.setUp(); } function _test_supplyCErc20_works(uint128 amount) private { if (integration) { vm.startPrank(daiWhale); daiToken.transfer(borrower1, daiToken.balanceOf(daiWhale)); vm.stopPrank(); } else { daiToken.mint(borrower1, 3672711471 ether); } vm.startPrank(borrower1); daiToken.approve(address(cDAIToken), daiToken.balanceOf(borrower1)); cDAIToken.mint(daiToken.balanceOf(borrower1)); vm.assume(amount > 0); vm.assume(amount < cDAIToken.balanceOf(borrower1)); uint256 balanceBefore = liquidity.getCAssetBalance(borrower1, address(cDAIToken)); assertEq(balanceBefore, 0); cDAIToken.approve(address(liquidity), amount); uint256 cTokensTransferred = liquidity.supplyCErc20(address(cDAIToken), amount); vm.stopPrank(); uint256 balanceAfter = liquidity.getCAssetBalance(borrower1, address(cDAIToken)); assertEq(balanceAfter, cTokensTransferred); } function test_fuzz_supplyCErc20_works(uint128 amount) public { _test_supplyCErc20_works(amount); } function test_unit_supplyCErc20_works() public { uint128 amount = 100000000; _test_supplyCErc20_works(amount); } }
import { useCallback, useState } from 'react' import toast from 'react-hot-toast' import { useTranslation } from 'react-i18next' import { useSetRecoilState } from 'recoil' import { genericTokenBalancesSelector } from '@dao-dao/state' import { Loader, useCachedLoading, useChain, useDaoInfoContext, } from '@dao-dao/stateless' import { TokenType } from '@dao-dao/types' import { convertDenomToMicroDenomWithDecimals } from '@dao-dao/utils' import { SuspenseLoader } from '../../../../../../components' import { useCw20CommonGovernanceTokenInfoIfExists } from '../../../../../../voting-module-adapter/react/hooks/useCw20CommonGovernanceTokenInfoIfExists' import { refreshStatusAtom } from '../../atoms' import { usePostRequest } from '../../hooks/usePostRequest' import { Cw20Token, NativeToken, NewSurveyFormData, NewSurveyRequest, } from '../../types' import { NewSurveyForm as StatelessNewSurveyForm } from '../stateless/NewSurveyForm' export const NewSurveyForm = () => { const { t } = useTranslation() const { chain_id: chainId } = useChain() const { coreAddress } = useDaoInfoContext() // Get CW20 governance token address from voting module adapter if exists, so // we can make sure to load it with all cw20 balances, even if it has not been // explicitly added to the DAO. const { denomOrAddress: governanceTokenAddress } = useCw20CommonGovernanceTokenInfoIfExists() ?? {} // This needs to be loaded via a cached loadable to avoid displaying a loader // when this data updates on a schedule. Manually trigger a suspense loader // the first time when the initial data is still loading. const availableTokensLoading = useCachedLoading( genericTokenBalancesSelector({ chainId, address: coreAddress, cw20GovernanceTokenAddress: governanceTokenAddress, // Only load tokens in native account. filter: { account: { chainId, address: coreAddress, }, }, }), [] ) const postRequest = usePostRequest() const setRefreshStatus = useSetRecoilState( refreshStatusAtom({ daoAddress: coreAddress, }) ) const [loading, setLoading] = useState(false) const onCreate = useCallback( async (surveyData: NewSurveyFormData) => { // Need balances to be loaded. if (availableTokensLoading.loading) { toast.error(t('error.loadingData')) return } setLoading(true) try { const survey: NewSurveyRequest = { ...surveyData, // Convert date strings to dates and back, to ensure they are in the // local timezone. contributionsOpenAt: new Date( surveyData.contributionsOpenAt ).toISOString(), contributionsCloseRatingsOpenAt: new Date( surveyData.contributionsCloseRatingsOpenAt ).toISOString(), ratingsCloseAt: new Date(surveyData.ratingsCloseAt).toISOString(), // Split up cw20 and native tokens, and convert amount decimals. attributes: surveyData.attributes.map(({ tokens, ...attribute }) => { const nativeTokens: NativeToken[] = [] const cw20Tokens: Cw20Token[] = [] tokens.forEach(({ denomOrAddress, amount }) => { const nativeDecimals = availableTokensLoading.data.find( ({ token }) => token.type === TokenType.Native && token.denomOrAddress === denomOrAddress )?.token.decimals const cw20Decimals = availableTokensLoading.data.find( ({ token }) => token.type === TokenType.Cw20 && token.denomOrAddress === denomOrAddress )?.token.decimals if (cw20Decimals !== undefined) { cw20Tokens.push({ address: denomOrAddress, amount: convertDenomToMicroDenomWithDecimals( amount, cw20Decimals ).toString(), }) } else if (nativeDecimals !== undefined) { nativeTokens.push({ denom: denomOrAddress, amount: convertDenomToMicroDenomWithDecimals( amount, nativeDecimals ).toString(), }) } else { // Should never happen, but just in case. throw new Error( `Could not find decimals for token with denom or address '${denomOrAddress}'.` ) } }) return { ...attribute, nativeTokens, cw20Tokens, } }), } await postRequest(`/${coreAddress}`, { survey }) toast.success(t('success.compensationCycleCreated')) // Reload status on success. setRefreshStatus((id) => id + 1) } catch (err) { console.error(err) toast.error(err instanceof Error ? err.message : JSON.stringify(err)) } finally { setLoading(false) } }, [coreAddress, availableTokensLoading, postRequest, setRefreshStatus, t] ) return ( <SuspenseLoader fallback={<Loader />} forceFallback={ // Manually trigger since we are using a cached loadable but want to // wait for this. We use the loadable to prevent re-rendering when the // data is updated on a schedule. availableTokensLoading.loading } > <StatelessNewSurveyForm availableTokens={ availableTokensLoading.loading ? [] : availableTokensLoading.data.map(({ token }) => token) } loading={loading} onCreate={onCreate} /> </SuspenseLoader> ) }
import React from "react"; import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader import { Carousel } from "react-responsive-carousel"; import { BiArrowBack } from "react-icons/bi"; import { slideOne, slideTwo, slideThree } from "@/public"; import Image from "next/image"; import Wrapper from "./Wrapper"; import ProductCard from "./ProductCard"; const BannerSlide = () => { return ( <> <div className="max-w-[1360px] mx-auto text-[20px]"> <Carousel autoPlay={true} infiniteLoop={true} showThumbs={false} showIndicators={false} showStatus={false} renderArrowPrev={(clickHandler, hasPrev) => ( <div onClick={clickHandler} className="absolute right-[31px] md:right-[51px] bottom-0 w-[30px] md:w-[50px] h-[30px] md:h-[50px] bg-black z-10 flex items-center justify-center cursor-pointer hover:opacity-70 text-white" > <BiArrowBack className="text-sm md:text-lg" /> </div> )} renderArrowNext={(clickHandler, hasNext) => ( <div onClick={clickHandler} className="absolute right-0 bottom-0 w-[30px] md:w-[50px] h-[30px] md:h-[50px] bg-black z-10 flex items-center justify-center cursor-pointer hover:opacity-70 text-white" > <BiArrowBack className="rotate-180 text-sm md:text-lg" /> </div> )} > <div> <Image src={slideOne} alt="jordan shoes" /> <div className="px-[15px] md:px-[40px] py-[10px] md:py-[25px] font-oswald bg-white absolute bottom-[25px] md:bottom-[75px] left-0 text-black/[0.9] text-[15px] md:text-[30px] uppercase font-medium cursor-pointer hover:opacity-90"> Shop now </div> </div> <div> <Image src={slideTwo} alt="jordan shoes" /> <div className="px-[15px] md:px-[40px] py-[10px] md:py-[25px] font-oswald bg-white absolute bottom-[25px] md:bottom-[75px] left-0 text-black/[0.9] text-[15px] md:text-[30px] uppercase font-medium cursor-pointer hover:opacity-90"> Shop now </div> </div> <div> <Image src={slideThree} alt="jordan shoes" /> <div className="px-[15px] md:px-[40px] py-[10px] md:py-[25px] font-oswald bg-white absolute bottom-[25px] md:bottom-[75px] left-0 text-black/[0.9] text-[15px] md:text-[30px] uppercase font-medium cursor-pointer hover:opacity-90"> Shop now </div> </div> </Carousel> </div> <Wrapper> {/* heading and paragaph start */} <div className="text-center max-w-[800px] mx-auto my-[50px] md:my-[80px]" // style={{ border: "2px solid black" }} > <div className="text-[28px] md:text-[34px] mb-5 font-semibold leading-tight"> Cushioning for Your Miles </div> <div className="text-md md:text-xl"> A lightweight Nike ZoomX midsole is combined with increased stack heights to help provide cushioning during extended stretches of running. </div> </div> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 my-14 px-5 md:px-0"> {/* {products?.data?.map((product) => ( <ProductCard key={product?.id} data={product} /> ))} */} <ProductCard src={1} /> <ProductCard src={2} /> <ProductCard src={3} /> <ProductCard src={4} /> <ProductCard src={5} /> <ProductCard src={6} /> {/* <ProductCard src={7} /> */} </div> </Wrapper> </> ); }; export default BannerSlide;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/styles.css"> <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet" /> <title>Layout de 8 partes</title> </head> <body> <header class="header"> <a href="">Logo</a> <div class="menu-esquerda"> <ul class="menu"> <li><a href="">Condomínios</a></li> <li><a href="">Fórum</a></li> <li><a href="">Guia</a></li> <li><a href="">Artigos</a></li> <li><a href="">Ferramentas</a></li> </ul> </div> <div class="menu-direita"> <ul class="menu"> <li><a href="">Cotar imóvel</a></li> <li><a href="">Planos</a></li> <li><a href="">Entrar</a></li> </ul> <button>CADASTRE-SE</button> </div> <div class="menuHamburguer" id="menuHamburguer" onclick="abrirMenu()"> <span id="burguer" class="material-symbols-outlined">menu</span> </div> </header> <div class="menu-lateral" id="menuLateral"> <ul class="menu"> <li><a href="">Condomínios</a></li> <li><a href="">Fórum</a></li> <li><a href="">Guia</a></li> <li><a href="">Artigos</a></li> <li><a href="">Ferramentas</a></li> <li><a href="">Cotar imóvel</a></li> <li><a href="">Planos</a></li> <li><a href="">Entrar</a></li> </ul> </div> <div class="container"> <div class="reparticao-1"> <div class="card"> <div class="fundo-feminino"> <div class="image-focada"> <img src="images/feminino.jpg"> </div> </div> <div class="legenda"> <h1>Nome Corretora</h1> <p>3.000 pontos</p> <a href="#" id="link" onclick="trocaTexto1()"> <p id="verTelefone1">ver telefone</p> </a> </div> <div class="fundo-masculino"> <div class="image-focada"> <img src="images/masculino.jpg"> </div> </div> <div class="legenda"> <h1>Nome Corretor</h1> <p>3.000 pontos</p> <a href="#" id="link" onclick="trocaTexto2()"> <p id="verTelefone2">ver telefone</p> </a> </div> </div> </div> <div class="reparticao-2"> <div class="card"> <h1>Mande uma mensagem:</h1> <input type="text" placeholder="Digite seu CPF" id="cpf" maxlength="14"> <input type="text" placeholder="Digite seu telefone" id="telefone" maxlength="14"> <textarea name="assunto" id="assunto" cols="40" rows="5" placeholder="Digite o assunto"></textarea> <button onclick="exibirMensagem()">Enviar Mensagem</button> </div> </div> <div class="reparticao-3"> <div class="card"> <h1>Regra de 3</h1> <div class="card-interno"> <input type="text" placeholder="60" id="primeiroValor" required> <p>_____</p> <input type="text" placeholder="100" id="segundoValor" required> <input type="text" placeholder="30" id="terceiroValor" required> <p>_____</p> <input class="resultado" type="text" id="result"> </div> <button class="calcular" onclick="realizaCalculo()">Calcular</button> </div> </div> <div class="reparticao-4"> <div class="card"> <img src="images/casa.jpg"> </div> <div class="button"> <button id="buttonModel">ABRIR IMAGEM NO MODEL</button> </div> <dialog class="dialogModal" id="dialogModal"> <div class="cardModal"> <div class="head"> <a class="buttonClose" id="buttonClose">X</a> </div> <hr/> <img src="images/casa.jpg"> </div> </dialog> </div> <div class="reparticao-5"> <div class="card" id="capture"> <div class="card-interno"> <img src="images/casa.jpg"> <div class="imovelGuide"> Imovel Guide </div> </div> </div> <div class="button"> <button onclick="print()">Download</button> </div> </div> <div class="reparticao-6"> <div class="card"> <img src="images/casa.jpg"> </div> </div> </div> <footer class="footer"> <div class="menu-esquerda"> <nav> <ul class="menu"> <li><a href="">Termos</a></li> <li><a href="">Contatos</a></li> <li><a href="">Sobre</a></li> </ul> </nav> </div> <div class="menu-direita"> <p>Copyright 2022. Todos os direitos reservados</p> </div> <a href="">Logo</a> </footer> <script src="script.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </body> </html>
<script lang="ts"> import { account } from "$lib/state/account.state"; import { abbreviate, slugify } from "$lib/util/functions"; import { Avatar, Button, RoleBadge } from "$lib/ui/util"; import { ArrowDownSLine, ArrowLeftRightLine, ArrowRightSLine, ArrowUpSLine, BookLine, CheckLine, CloseLine, CupLine, EyeLine, Link, LogoutCircleLine, QuillPenLine, Settings5Line } from "svelte-remixicon"; import { slide } from "svelte/transition"; import type { Profile } from "$lib/models/accounts"; import { pushPanel } from "$lib/ui/user/guide/guide.state"; import { SettingsPanel, LogOutPanel } from "./settings"; import { createForm } from "felte"; import { Presence, type ProfileForm } from "$lib/models/accounts"; import { postReq, type ResponseError } from "$lib/http"; import toast from "svelte-french-toast"; import { TextArea, TextField } from "$lib/ui/forms"; let profileSwitcherOpen = false; let showAddForm = false; function selectProfile(profile: Profile) { $account.currProfile = profile; profileSwitcherOpen = false; } const { form, errors, isSubmitting } = createForm({ onSubmit: async (values, context) => { const formInfo: ProfileForm = { username: values.username, presence: Presence.Offline, bio: values.bio }; const response = await postReq<Profile>(`/accounts/create-profile`, formInfo); if ((response as Profile).id) { $account.profiles = [...$account.profiles, response as Profile]; toast.success(`Profile added!`); context.reset(); showAddForm = false; } else { const error = response as ResponseError; toast.error(error.message); } }, validate: (values) => { const errors = { username: "", bio: "" }; if (!values.username || values.username.length < 3 || values.username.length > 36) { errors.username = "Usernames must be between 3 and 36 characters in length"; } if (values.bio && (values.bio.length < 3 || values.username.length > 120)) { errors.bio = "Profile bios must be between 3 and 120 characters in length"; } return errors; }, initialValues: { username: null, presence: Presence.Offline, bio: null, tagline: null } }); </script> {#if $account.account && $account.currProfile} <div class="guide-section mt-2 bg-zinc-300 dark:bg-zinc-600"> <div class="h-[6rem] overflow-hidden w-full relative"> {#if $account.currProfile.bannerArt !== null && $account.currProfile.bannerArt !== undefined} <img src={$account.currProfile.bannerArt} class="h-full w-full object-cover" alt="profile avatar" /> {:else} <div class="h-full w-full absolute" style="background: var(--accent);"> <!--intentionally left blank--> </div> {/if} </div> <div class="flex items-center px-4 my-2"> <Avatar src={$account.currProfile.avatar} size="72px" borderWidth="1px" /> <div class="ml-2"> <a class="text-ellipsis overflow-hidden" href="/profile/{$account.currProfile.id}/{slugify( $account.currProfile.username )}" > <h3 class="text-2xl">{$account.currProfile.username}</h3> </a> <RoleBadge roles={$account.account.roles} size="large" /> </div> </div> <div class="w-full flex items-center justify-center border-t border-zinc-400 dark:border-zinc-500 mt-0.5" > <a class="stat-box hover:bg-zinc-400 dark:hover:bg-zinc-500" href="/profile/{$account.currProfile.id}/{slugify( $account.currProfile.username )}/works" > <div class="stat"> <QuillPenLine size="18.4px" class="mr-1" /> <span class="select-none">{abbreviate($account.currProfile.stats.works)}</span> </div> <div class="stat-label">Works</div> </a> <a class="stat-box border-l border-r border-zinc-400 dark:border-zinc-500 hover:bg-zinc-400 dark:hover:bg-zinc-500" href="/profile/{$account.currProfile.id}/{slugify( $account.currProfile.username )}/blogs" > <div class="stat"> <CupLine size="18.4px" class="mr-1" /> <span class="select-none">{abbreviate($account.currProfile.stats.blogs)}</span> </div> <div class="stat-label">Blogs</div> </a> <a class="stat-box hover:bg-zinc-400 dark:hover:bg-zinc-500" href="/profile/{$account.currProfile.id}/{slugify( $account.currProfile.username )}/followers" > <div class="stat"> <EyeLine size="18.4px" class="mr-1" /> <span class="select-none" >{abbreviate($account.currProfile.stats.followers)}</span > </div> <div class="stat-label">Follows</div> </a> </div> </div> <div class="guide-section bg-zinc-300 dark:bg-zinc-600"> <a class="guide-button group" href="/profile/{$account.currProfile.id}/{slugify( $account.currProfile.username )}/works/new" > <BookLine size="24px" class="mr-2" /> <span>Create New Work</span> <Link size="18px" class="text-zinc-400 dark:text-zinc-500 group-hover:text-zinc-400" /> </a> <a class="guide-button group" href="/profile/{$account.currProfile.id}/{slugify( $account.currProfile.username )}/blogs/new" > <CupLine size="24px" class="mr-2" /> <span>Create New Blog</span> <Link size="18px" class="text-zinc-400 dark:text-zinc-500 group-hover:text-zinc-400" /> </a> </div> <div class="guide-section bg-zinc-300 dark:bg-zinc-600"> <button class="guide-button group" on:click={() => (profileSwitcherOpen = !profileSwitcherOpen)} > <ArrowLeftRightLine size="24px" class="mr-2" /> <span>Switch Profile</span> {#if profileSwitcherOpen} <ArrowUpSLine size="18px" class="text-zinc-400 dark:text-zinc-500 group-hover:text-zinc-400" /> {:else} <ArrowDownSLine size="18px" class="text-zinc-400 dark:text-zinc-500 group-hover:text-zinc-400" /> {/if} </button> {#if profileSwitcherOpen} <div transition:slide={{ delay: 0, duration: 150 }}> {#if showAddForm} <form class="px-2 pb-2" use:form> <TextField name="username" type="text" title="Username" placeholder="A New Face" errorMessage={$errors.username} /> <TextArea name="bio" title="Bio (Optional)" placeholder="Just another somebody" errorMessage={$errors.bio} /> <div class="flex items-center justify-center"> <Button type="submit" loading={$isSubmitting} loadingText="Saving..."> <CheckLine class="button-icon" /> <span class="button-text">Submit</span> </Button> <div class="mx-0.5" /> <Button type="button" on:click={() => (showAddForm = false)}> <CloseLine class="button-icon" /> <span class="button-text">Cancel</span> </Button> </div> </form> {:else} <div class="flex items-center justify-center my-2"> {#each $account.profiles as profile} <button class="profile-button" on:click={() => selectProfile(profile)}> <Avatar src={profile.avatar} size="72px" borderWidth="1px" /> <span>Alyx, Of Many Figments</span> </button> {/each} {#if $account.profiles.length < 3} <button class="profile-button" on:click={() => (showAddForm = !showAddForm)} > <span class="w-[72px] h-[72px] text-6xl font-extralight rounded-full border-2 border-dashed" > <span class="relative top-1"> + </span> </span> <span>Add Profile</span> </button> {/if} </div> {/if} </div> {/if} </div> {:else if $account.account} <div class="px-4 mb-2"> <h5 class="text-xl justify-self-start">Select Profile</h5> {#if showAddForm} <form class="px-2 pb-2" use:form> <TextField name="username" type="text" title="Username" placeholder="A New Face" kind="primary" errorMessage={$errors.username} /> <TextArea name="bio" title="Bio (Optional)" placeholder="Just another somebody" kind="primary" errorMessage={$errors.bio} /> <div class="flex items-center justify-center"> <Button type="submit" loading={$isSubmitting} loadingText="Saving..."> <CheckLine class="button-icon" /> <span class="button-text">Submit</span> </Button> <div class="mx-0.5" /> <Button type="button" on:click={() => (showAddForm = false)}> <CloseLine class="button-icon" /> <span class="button-text">Cancel</span> </Button> </div> </form> {:else} <div class="flex items-center justify-center"> {#each $account.profiles as profile} <button class="profile-button" on:click={() => selectProfile(profile)}> <Avatar src={profile.avatar} size="72px" borderWidth="1px" /> <span>{profile.username}</span> </button> {/each} {#if $account.profiles.length < 3} <button class="profile-button" on:click={() => (showAddForm = !showAddForm)}> <span class="w-[72px] h-[72px] text-6xl font-extralight rounded-full border-2 border-dashed" > <span class="relative top-1"> + </span> </span> <span>Add Profile</span> </button> {/if} </div> {/if} </div> {/if} <div class="guide-section bg-zinc-300 dark:bg-zinc-600"> <button class="guide-button group" on:click={() => pushPanel(SettingsPanel)}> <Settings5Line size="24px" class="mr-2" /> <span>Settings</span> <ArrowRightSLine size="18px" class="text-zinc-400 dark:text-zinc-500 group-hover:text-zinc-400" /> </button> <button class="guide-button group" on:click={() => pushPanel(LogOutPanel)}> <LogoutCircleLine size="24px" class="mr-2" /> <span>Log Out</span> <ArrowRightSLine size="18px" class="text-zinc-400 dark:text-zinc-500 group-hover:text-zinc-400" /> </button> </div>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>switch button</title> </head> <style> body{ display: flex; justify-content: center; align-items: center; min-height: 100vh; } #diy-button{ --width: 150px; --height: 40px; --btn-width: calc(var(--width) / 2); --move: 0px; width: var(--width); height: var(--height); border: 3px solid #ccc; background-color: #eee; border-radius: var(--height); box-shadow: inset 0px 0px 12px rgba(0, 0, 0, .2); } #switch{ display: block; text-align: center; line-height: var(--height); font-family: sans-serif; color: #fff; font-weight: bold; width: var(--btn-width); height: inherit; background-color: #fff; border-radius: inherit; cursor: pointer; box-shadow: inset 0px 0px 6px rgba(3, 3, 3, .25), 0px 2px 4px rgba(0, 0, 0, .3); transform: translateX( clamp(0px, var(--move), var(--btn-width)) ); background-color:salmon; transition: .25s all ease; } </style> <body> <div id="diy-button"><span id="switch">OFF</span></div> </body> <script> const btn = document.querySelector("#switch"); const container = document.querySelector("#diy-button"); btn.onclick = (e) => { let moved = container.style.getPropertyValue("--move"); if (moved == "" || moved == "0px") { container.style.setProperty('--move', '75px'); btn.style.backgroundColor = "#99CC99"; btn.innerHTML = "ON"; } else { container.style.setProperty('--move', '0px'); btn.style.backgroundColor = "salmon"; btn.innerHTML = "OFF"; } } </script> </html>
import unittest import sys from concurrent.futures import ThreadPoolExecutor as _Executor import time import os sys.path.append("server") import server.app as _app from server.fleetv2_http_api.models.message import Message, Payload, DeviceId from server.enums import MessageType class Test_Waiting_For_Statuses_To_Become_Available(unittest.TestCase): def setUp(self) -> None: self.app = _app.get_test_app( db_location="test_db.db", request_timeout_s=0.2, base_url="/v2/protocol/" ) self.deviceA_id = DeviceId(module_id=7, type=8, role="test_device", name="Test Device") self.deviceB_id = DeviceId(module_id=9, type=10, role="test_device", name="Test Device") self.payload = Payload(MessageType.STATUS, "JSON", {"phone": "1234567890"}) self.statusA = Message(device_id=self.deviceA_id, payload=self.payload) self.statusB = Message(device_id=self.deviceB_id, payload=self.payload) self.error_payload = Payload(MessageType.STATUS_ERROR, "JSON", {"phone": "1234567890"}) self.status_error = Message(device_id=self.deviceA_id, payload=self.error_payload) def test_awaited_statuses_are_returned_if_some_status_is_sent_in_other_thread(self): with _Executor(max_workers=2) as executor, self.app.app.test_client() as c: future = executor.submit(c.get, "/status/test_company/test_car?wait=True") time.sleep(0.1) executor.submit(c.post, "/status/test_company/test_car", json=[self.statusA, self.status_error]) response = future.result() self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json), 2) self.assertEqual(response.json[0]["device_id"], self.deviceA_id.to_dict()) def test_all_relevant_statuses_sent_in_one_thread_are_returned_in_second_waiting_thread(self): with _Executor(max_workers=2) as executor, self.app.app.test_client() as c: future = executor.submit(c.get, "/status/test_company/test_car?wait=True") time.sleep(0.1) executor.submit( c.post, "/status/test_company/test_car", json=[self.statusA, self.statusB, self.status_error], ) response = future.result() self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json), 3) self.assertEqual(response.json[0]["device_id"], self.deviceA_id.to_dict()) self.assertEqual(response.json[1]["device_id"], self.deviceB_id.to_dict()) def test_404_code_and_empty_list_of_statuses_is_returned_after_timeout_is_exceeded(self): with _Executor(max_workers=2) as executor, self.app.app.test_client() as c: future = executor.submit(c.get, "/status/test_company/test_car?wait=True") response = future.result() self.assertEqual(response.status_code, 404) self.assertEqual(response.json, []) def tearDown(self) -> None: if os.path.isfile("test_db.db"): os.remove("test_db.db") class Test_Waiting_Request_Ignores_Statuses_Send_To_Other_Cars(unittest.TestCase): def setUp(self) -> None: self.app = _app.get_test_app( db_location="test_db.db", request_timeout_s=0.2, base_url="/v2/protocol/" ) self.deviceA_id = DeviceId(module_id=7, type=8, role="test_device", name="Test Device") self.deviceB_id = DeviceId(module_id=9, type=10, role="test_device", name="Test Device") self.payload = Payload(MessageType.STATUS, "JSON", {"phone": "1234567890"}) self.error_payload = Payload(MessageType.STATUS_ERROR, "JSON", {"phone": "1234567890"}) self.statusA = Message(device_id=self.deviceA_id, payload=self.payload) self.statusB = Message(device_id=self.deviceB_id, payload=self.payload) self.status_error = Message(device_id=self.deviceA_id, payload=self.error_payload ) def test_status_for_other_car_than_awaited_is_not_send_to_waiting_thread(self): with _Executor(max_workers=2) as executor, self.app.app.test_client() as c: future = executor.submit(c.get, "/status/company/car_x?wait=True") time.sleep(0.1) executor.submit(c.post, "/status/company/car_y", json=[self.statusA, self.statusB, self.status_error]) response = future.result() self.assertEqual(response.status_code, 404) self.assertEqual(len(response.json), 0) def test_status_for_other_company_than_awaited_is_not_send_to_waiting_thread(self): with _Executor(max_workers=2) as executor, self.app.app.test_client() as c: future = executor.submit(c.get, "/status/company_x/car?wait=True") time.sleep(0.1) executor.submit(c.post, "/status/company_y/car", json=[self.statusA, self.statusB]) response = future.result() self.assertEqual(response.status_code, 404) self.assertEqual(len(response.json), 0) def test_waiting_thread_responds_after_relevant_status_is_sent(self): with _Executor(max_workers=2) as executor, self.app.app.test_client() as c: future = executor.submit(c.get, "/status/company/car?wait=True") time.sleep(0.05) # This status does not trigger response from the waiting thread executor.submit(c.post, "/status/company/some_other_car", json=[self.statusA]) time.sleep(0.05) # This status triggers response from the waiting thread executor.submit(c.post, "/status/company/car", json=[self.statusB]) response = future.result() self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json), 1) self.assertEqual(response.json[0]["device_id"], self.deviceB_id.to_dict()) def tearDown(self) -> None: if os.path.isfile("test_db.db"): os.remove("test_db.db") if __name__ == "__main__": # pragma: no cover unittest.main()
// ------------------------------------------------------------------------------------------ // Copyright (c) Natsuneko. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // ------------------------------------------------------------------------------------------ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Plana.Composition.Abstractions; using Plana.Composition.Abstractions.Analysis; using Plana.Composition.Extensions; namespace Plana.Composition.RenameSymbols; internal class CSharpSymbolsWalker(ISolution solution, IDocument document, IPlanaSecureRandom random, bool isRenameNamespaces, bool isRenameClasses, bool isRenameProperties, bool isRenameFields, bool isRenameMethods, bool isRenameVariables, Dictionary<ISymbol, string> dict) : CSharpSyntaxWalker { private static readonly List<string> Messages = [ "Awake", "FixedUpdate", "LateUpdate", "OnAnimatorIK", "OnAnimatorMove", "OnApplicationFocus", "OnApplicationPause", "OnApplicationQuit", "OnAudioFilterRead", "OnBecameInvisible", "OnBecameVisible", "OnCollisionEnter", "OnCollisionEnter2D", "OnCollisionExit", "OnCollisionExit2D", "OnCollisionStay", "OnCollisionStay2D", "OnConnectedToServer", "OnControllerColliderHit", "OnDestroy", "OnDisable", "OnDisconnectedFromServer", "OnDrawGizmos", "OnDrawGizmosSelected", "OnEnable", "OnFailedToConnect", "OnFailedToConnectToMasterServer", "OnGUI", "OnJoinBreak", "OnJoinBreak2D", "OnMasterServerEvent", "OnMouseDown", "OnMouseDrag", "OnMouseEnter", "OnMouseExit", "OnMouseOver", "OnMouseUp", "OnMouseUpAsButton", "OnNetworkInstantiate", "OnParticleCollision", "OnParticleSystemStopped", "OnParticleTrigger", "OnParticleUpdateJobScheduled", "OnPlayerConnected", "OnPlayerDisconnected", "OnPostRender", "OnPreCull", "OnPreRender", "OnRenderImage", "OnRenderObject", "OnSerializeNetworkView", "OnTransformChildrenChanged", "OnTransformParentChanged", "OnTriggerEnter", "OnTriggerEnter2D", "OnTriggerExit", "OnTriggerExit2D", "OnTriggerStay", "OnTriggerStay2D", "OnValidate", "OnWillRenderObject", "Reset", "Start", "Update" ]; private static AnnotationComment NetworkingAnnotation => new("networking"); private string SetIdentifier(ISymbol symbol, string prefix = "_", string suffix = "") { if (dict.TryGetValue(symbol, out var val)) return val; var identifier = $"{prefix}0x{random.GetGlobalUniqueAlphaNumericalString(8)}{suffix}"; dict.Add(symbol, identifier); return identifier; } public override void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) { if (isRenameProperties && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetIdentifier(symbol); } base.VisitEnumMemberDeclaration(node); } public override void VisitParameter(ParameterSyntax node) { var hasAnnotationComment = node.Parent?.Parent is CSharpSyntaxNode declaration && declaration.HasAnnotationComment(); if (isRenameVariables && !hasAnnotationComment) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) { var identifier = SetIdentifier(symbol); // if IParameterSymbol is inside TypeDeclarationSyntax.ParameterList, it acts as IPropertySymbol or IFieldSymbol var unknown = node.Parent?.Parent; if (unknown is TypeDeclarationSyntax decl) { var t = document.SemanticModel.GetDeclaredSymbol(decl); var symbols = document.SemanticModel.LookupSymbols(decl.ParameterList!.FullSpan.End); var act = symbols.FirstOrDefault(w => w.ContainingType?.Equals(t, SymbolEqualityComparer.Default) == true && w.Name == symbol.Name); if (act != null) dict.TryAdd(act, identifier); } } } base.VisitParameter(node); } public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) { var hasAnnotationComment = node.Parent?.Parent is CSharpSyntaxNode declaration && declaration.HasAnnotationComment(); if ((isRenameFields || isRenameVariables) && !hasAnnotationComment) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) switch (symbol) { case IFieldSymbol when isRenameFields: case ILocalSymbol when isRenameVariables: SetIdentifier(symbol); break; } } base.VisitVariableDeclarator(node); } public override void VisitForEachStatement(ForEachStatementSyntax node) { if (isRenameVariables && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetIdentifier(symbol); } base.VisitForEachStatement(node); } private string KeepOriginalName(ISymbol symbol, string? name = null) { dict.Add(symbol, name ?? symbol.Name); return name ?? symbol.Name; } #region classes public override void VisitClassDeclaration(ClassDeclarationSyntax node) { if (isRenameClasses && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) { bool IsAttribute(INamedTypeSymbol t) { if (t.BaseType == null) return false; if (t.BaseType.Equals(typeof(Attribute).ToSymbol(document.SemanticModel), SymbolEqualityComparer.Default)) return true; return false; } if (IsAttribute(symbol)) { var identifier = SetIdentifier(symbol, suffix: "Attribute"); var constructorName = identifier.Substring(0, identifier.Length - "Attribute".Length); var constructors = symbol.Constructors; foreach (var constructor in constructors) dict.TryAdd(constructor, constructorName); } else { SetIdentifier(symbol); } } } base.VisitClassDeclaration(node); } public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { if (isRenameClasses && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetIdentifier(symbol); } base.VisitInterfaceDeclaration(node); } public override void VisitRecordDeclaration(RecordDeclarationSyntax node) { if (isRenameClasses && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetIdentifier(symbol); } base.VisitRecordDeclaration(node); } public override void VisitEnumDeclaration(EnumDeclarationSyntax node) { if (isRenameClasses && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetIdentifier(symbol); } base.VisitEnumDeclaration(node); } #endregion #region methods public override void VisitMethodDeclaration(MethodDeclarationSyntax node) { if (isRenameMethods && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetMethodIdentifier(symbol); } base.VisitMethodDeclaration(node); } private string SetMethodIdentifier(IMethodSymbol symbol) { if (dict.TryGetValue(symbol.OriginalDefinition, out var val)) return val; var original = symbol.OriginalDefinition; // check methods declared in source if (original.OverriddenMethod is not null) { var overridden = original.OverriddenMethod; var isExternalDefinition = overridden.Locations.Any(w => w.IsInMetadata); if (isExternalDefinition) return KeepOriginalName(symbol, overridden.Name); if (overridden.IsAnyDeclarationIsNotInWorkspace(solution)) return KeepOriginalName(symbol, overridden.Name); } if (original.Locations.Any(w => w.IsInMetadata)) return KeepOriginalName(symbol); if (original.IsAnyDeclarationIsNotInWorkspace(solution)) return KeepOriginalName(symbol); var @interface = symbol.GetInterfaceSymbol(); if (@interface is IMethodSymbol s) { var infer = dict.GetValueOrDefault(s) ?? dict.GetValueOrDefault(s.OriginalDefinition); if (string.IsNullOrWhiteSpace(infer)) infer = SetMethodIdentifier(s); dict.Add(symbol, infer); return infer; } if (original.Equals(symbol, SymbolEqualityComparer.Default)) { var identifier = $"_0x{random.GetGlobalUniqueAlphaNumericalString(8)}"; dict.Add(original, identifier); return identifier; } // not match signature if (!MeaningEqualitySymbolComparator.Default.Equals(symbol, original)) { var identifier = SetMethodIdentifier(original); dict.Add(symbol, identifier); return identifier; } return string.Empty; } #endregion #region properties public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { if (isRenameProperties && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetPropertyIdentifier(symbol); } base.VisitPropertyDeclaration(node); } private string SetPropertyIdentifier(IPropertySymbol symbol) { if (dict.TryGetValue(symbol.OriginalDefinition, out var val)) return val; var original = symbol.OriginalDefinition; if (original.IsAnyDeclarationIsNotInWorkspace(solution)) return KeepOriginalName(original); var @interface = symbol.GetInterfaceSymbol(); if (@interface is IPropertySymbol s) { var infer = dict.GetValueOrDefault(s) ?? dict.GetValueOrDefault(s.OriginalDefinition); if (string.IsNullOrWhiteSpace(infer)) infer = SetPropertyIdentifier(s); dict.Add(symbol, infer); return infer; } if (original.Equals(symbol, SymbolEqualityComparer.Default)) { var identifier = $"_0x{random.GetGlobalUniqueAlphaNumericalString(8)}"; dict.Add(original, identifier); return identifier; } throw new InvalidOperationException(); } #endregion #region namespace public override void VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) { if (isRenameNamespaces && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetNamespaceIdentifier(symbol); } base.VisitFileScopedNamespaceDeclaration(node); } public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) { if (isRenameNamespaces && !node.HasAnnotationComment()) { var symbol = document.SemanticModel.GetDeclaredSymbol(node); if (symbol != null) SetNamespaceIdentifier(symbol); } base.VisitNamespaceDeclaration(node); } private void SetNamespaceIdentifier(INamespaceSymbol symbol) { if (dict.ContainsKey(symbol)) return; if (symbol.IsAnyDeclarationIsNotInWorkspace(solution)) return; if (symbol.ContainingNamespace.IsGlobalNamespace) { // root namespace var original = symbol.OriginalDefinition; if (original.Equals(symbol, SymbolEqualityComparer.Default)) { var identifier = $"_0x{random.GetGlobalUniqueAlphaNumericalString(8)}"; dict.Add(original, identifier); return; } } else { var stack = new Stack<INamespaceSymbol>(); var current = symbol; while (true) { if (current.IsGlobalNamespace) break; stack.Push(current); current = current.ContainingNamespace; } while (stack.Count > 0) { var s = stack.Pop(); if (dict.ContainsKey(s.OriginalDefinition)) continue; var identifier = $"_0x{random.GetGlobalUniqueAlphaNumericalString(8)}"; dict.Add(s.OriginalDefinition, identifier); } return; } throw new InvalidOperationException(); } #endregion }
# Modified code from https://github.com/rois-codh/kmnist/blob/master/download_data.py import requests import os try: from tqdm import tqdm except ImportError: tqdm = lambda x, total, unit: x # If tqdm doesn't exist, replace it with a function that does nothing print('**** Could not import tqdm. Please install tqdm for download progressbars! (pip install tqdm) ****') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # Kuzushiji-49 (49 classes, 28x28, 270k examples) # NumPy data format (.npz) # Download mapping just in case or for fun to_download = ['http://codh.rois.ac.jp/kmnist/dataset/k49/k49-train-imgs.npz', 'http://codh.rois.ac.jp/kmnist/dataset/k49/k49-train-labels.npz', 'http://codh.rois.ac.jp/kmnist/dataset/k49/k49-test-imgs.npz', 'http://codh.rois.ac.jp/kmnist/dataset/k49/k49-test-labels.npz', 'http://codh.rois.ac.jp/kmnist/dataset/k49/k49_classmap.csv'] # Download a list of files def download_list(url_list, force=False): for url in url_list: path = url.split('/')[-1] output_path = os.path.join(BASE_DIR, path) if os.path.exists(output_path) and not force: print(f'Skipping downloaded file {path}. Use force param to overwrite.') continue r = requests.get(url, stream=True) with open(output_path, 'wb') as f: total_length = int(r.headers.get('content-length')) print('Downloading {} - {:.1f} MB'.format(path, (total_length / 1024000))) for chunk in tqdm(r.iter_content(chunk_size=1024), total=int(total_length / 1024) + 1, unit="KB"): if chunk: f.write(chunk) print('All dataset files downloaded!') def prepare(force=False): download_list(to_download, force)
package threading; class Mythr implements Runnable{ private String name; public Mythr(String name){ this.name=name;//if super(name)....in thread class there is already a constructor which takes the name } public void run(){ int i = 0; while (i<10) { System.out.println(i + "I am a thread"+ name); i++; } } } public class threadconstructor { public static void main(String[] args) { Mythr t = new Mythr("Harry"); Thread t1 = new Thread(t,"t1"); Mythr t2 = new Mythr("Chandan"); Thread t3 = new Thread(t2,"t3"); t1.start(); t3.start(); System.out.println("The id of the thread is " + t1.getId()); System.out.println("The id of the thread is " + t3.getId()); System.out.println("The name of the thread t1 is " + t1.getName()); System.out.println("The name of the thread t2 is " + t3.getName()); } }
import { Data } from "plotly.js"; import { useEffect, useState } from "react"; import Plot from "react-plotly.js"; interface Props {} export const ScatterChart = ({}: Props) => { const [data, setData] = useState<Data[]>([]); const fetchData = async () => { const response1 = await fetch("http://127.0.0.1:8000/data/"); const data1 = await response1.json(); const x1 = data1.map((d: any) => d.x); const y1 = data1.map((d: any) => d.y); const response2 = await fetch("http://127.0.0.1:8000/data/"); const data2 = await response2.json(); const x2 = data2.map((d: any) => d.x); const y2 = data2.map((d: any) => d.y); setData([ { x: x1, y: y1, mode: "markers", type: "scatter", name: "プロット1", marker: { color: "blue" }, }, { x: x2, y: y2, mode: "markers", type: "scatter", name: "プロット2", marker: { color: "red" }, }, ]); }; useEffect(() => { fetchData(); }, []); if (!data?.length) return null; return ( <Plot data={data} layout={{ width: 800, height: 600, title: "散布図", xaxis: { title: "X軸" }, yaxis: { title: "Y軸" }, }} /> ); };
const functions = require("firebase-functions"); const admin = require("firebase-admin"); const axios = require("axios"); const { Configuration, OpenAIApi } = require("openai"); const cors = require("cors")({ origin: true }); const db = admin.firestore(); const configuration = new Configuration({ apiKey: "", }); const openai = new OpenAIApi(configuration); exports.analyzeJsonData = functions.https.onRequest((req, res) => { cors(req, res, async () => { try { // Получение json данных и id пользователя из тела запроса const { jsonData, responseId } = req.body.data; // Проверка, что jsonData и userId были переданы if (!jsonData || !responseId) { console.log("Error: jsonData and userId are required"); res.status(400).send("jsonData and userId are required"); return; } console.log(`Received jsonData: ${JSON.stringify(jsonData)}`); console.log(`Received responseId: ${responseId}`); // Анализ json данных с использованием GPT-3.5 const completion = await openai.createChatCompletion({ model: "gpt-4o", messages: [ { role: "system", content: "Ты рекрутер. Твоя задача проанализировать чат между рекрутером и соискателем, проанализировать его и выдать саммари чата", }, { role: "user", content: `Проанализируй следующий чат между рекрутером и соискателем и выдай саммари чата по всем заданным вопросам. Выбери основные посылы соискателя в каждом вопросе, проанализируй их, и выдай свой анализ и основные посылы. Игнорируй первое сообшение в json с ролью system Данные: ${JSON.stringify(jsonData)}`, }, ], max_tokens: 1000, }); const analysisResult = completion.data.choices[0].message.content; // Запись результата в Firestore await db.collection("response").doc(responseId).update({ chat_summary: analysisResult, isResumeParsingFinished: true, }); // Отправка ответа res.status(200).json({ message: analysisResult }); } catch (error) { console.error("Error during data analysis:", error); if (error.response && error.response.status === 429) { res .status(429) .json({ error: "Превышен лимит запросов к API OpenAI. Попробуйте позже.", }); } else { res.status(500).json({ error: "Ошибка при анализе данных" }); } } }); });
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Diagnostics; namespace BA66UsbFrontend.Content.Weather { public enum WeatherUnits { Standard, Metric, Imperial } public abstract class OpenWeatherMapContent : ContentBase { protected static readonly Dictionary<WeatherUnits, string> weatherUnitsDict = new() { { WeatherUnits.Standard, "standard" }, { WeatherUnits.Metric, "metric" }, { WeatherUnits.Imperial, "imperial" }, }; protected static readonly Dictionary<WeatherUnits, string> weatherSuffixDict = new() { { WeatherUnits.Standard, " K" }, { WeatherUnits.Metric, "°C" }, { WeatherUnits.Imperial, "°F" }, }; static readonly TimeSpan updateDelay = TimeSpan.FromMinutes(15.0); static readonly string baseUri = "http://api.openweathermap.org/"; static readonly string currentWeatherEndpoint = "data/2.5/weather"; static readonly string geocodingZipEndpoint = "geo/1.0/zip"; static readonly HttpClientHandler clientHandler = new(); static readonly HttpClient client = new(clientHandler) { Timeout = TimeSpan.FromSeconds(3.0) }; public bool ForceUpdate { get; set; } = true; readonly Stopwatch updateStopwatch = Stopwatch.StartNew(); Report lastReport = new(); protected static async Task<Location> GetLocation() { if (string.IsNullOrEmpty(Program.Configuration.WeatherApiKey)) return new(); try { var uri = $"{baseUri}{geocodingZipEndpoint}?zip={Program.Configuration.WeatherPostcode},{Program.Configuration.WeatherCountry}&appid={Program.Configuration.WeatherApiKey}"; var response = await client.GetAsync(uri).ConfigureAwait(false); return JsonConvert.DeserializeObject<Location>(await response.Content.ReadAsStringAsync()); } catch { return new(); } } protected async Task<Report> GetCurrentWeather() { if (string.IsNullOrEmpty(Program.Configuration.WeatherApiKey)) return new(); try { if (!weatherUnitsDict.TryGetValue(Program.Configuration.WeatherUnits, out string unit)) throw new Exception($"Unsupported or invalid weather unit '{Program.Configuration.WeatherUnits}' selected"); if (updateStopwatch.Elapsed >= updateDelay || ForceUpdate) { updateStopwatch.Restart(); ForceUpdate = false; var location = await GetLocation(); var uri = $"{baseUri}{currentWeatherEndpoint}?lat={location?.Latitude}&lon={location?.Longitude}&units={unit}&appid={Program.Configuration.WeatherApiKey}"; var response = await client.GetAsync(uri).ConfigureAwait(false); lastReport = new Report(location, JObject.Parse(await response.Content.ReadAsStringAsync())); } } catch { ForceUpdate = false; } return lastReport; } } }
<?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Models\Order; use App\Models\OrderItem; use App\Models\Product; use Illuminate\Support\Facades\DB; use PDF; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class OrderController extends Controller { public function PendingOrders() { $orders = Order::where('status','pending')->orderBy('id','DESC')->get(); return view('backend.orders.pending_orders',compact('orders')); } public function PendingOrdersDetails($id) { $order = Order::with('division','district','state','user')->where('id',$id)->first(); $orderItem = OrderItem::with('product')->where('order_id',$id)->orderBy('id','DESC')->get(); return view('backend.orders.pending_orders_details',compact('order','orderItem')); } public function ConfirmOrders() { $orders = Order::where('status','confirm')->orderBy('id','DESC')->get(); return view('backend.orders.confirmed_orders',compact('orders')); } public function ProcessingOrders() { $orders = Order::where('status','processing')->orderBy('id','DESC')->get(); return view('backend.orders.processing_orders',compact('orders')); } public function PickedOrders() { $orders = Order::where('status','picked')->orderBy('id','DESC')->get(); return view('backend.orders.picked_orders',compact('orders')); } public function ShippedOrders() { $orders = Order::where('status','shipped')->orderBy('id','DESC')->get(); return view('backend.orders.shipped_orders',compact('orders')); } public function DeliveredOrders() { $orders = Order::where('status','delivered')->orderBy('id','DESC')->get(); return view('backend.orders.delivered_orders',compact('orders')); } public function CancelOrders() { $orders = Order::where('status','cancel')->orderBy('id','DESC')->get(); return view('backend.orders.cancel_orders',compact('orders')); } //PendingToConfirm public function PendingToConfirm($id) { Order::findOrFail($id)->update([ 'status'=>'confirm', ]); $notification = array( 'message' => 'Order Confirm Successfully', 'alert-type' => 'success' ); return redirect()->route('pending-orders')->with($notification); } //ConfirmToProcessing public function ConfirmToProcessing($id) { Order::findOrFail($id)->update([ 'status'=>'processing', ]); $notification = array( 'message' => 'Order Processing Successfully', 'alert-type' => 'success' ); return redirect()->route('confirm-orders')->with($notification); } //ProcessingToPicked public function ProcessingToPicked($id) { Order::findOrFail($id)->update([ 'status'=>'picked', ]); $notification = array( 'message' => 'Order Picked Successfully', 'alert-type' => 'success' ); return redirect()->route('processing-orders')->with($notification); } //PickedToShipped public function PickedToShipped($id) { Order::findOrFail($id)->update([ 'status'=>'shipped', ]); $notification = array( 'message' => 'Order Shipped Successfully', 'alert-type' => 'success' ); return redirect()->route('picked-orders')->with($notification); } //ShippedToDelivered public function ShippedToDelivered($id) { $product = OrderItem::where('order_id',$id)->get(); foreach ($product as $item){ Product::where('id',$item->product_id) ->update([ 'product_qty'=>DB::raw('product_qty-'.$item->qty) ]); } Order::findOrFail($id)->update([ 'status'=>'delivered', ]); $notification = array( 'message' => 'Order Delivered Successfully', 'alert-type' => 'success' ); return redirect()->route('shipped-orders')->with($notification); } //DeliveredToCancel public function DeliveredToCancel($id) { Order::findOrFail($id)->update([ 'status'=>'cancel', ]); $notification = array( 'message' => 'Order Cancel Successfully', 'alert-type' => 'success' ); return redirect()->route('delivered-orders')->with($notification); } //AdminInvoiceDownload public function AdminInvoiceDownload($id){ $order = Order::with('division','district','state','user')->where('id',$id)->first(); $orderItem = OrderItem::with('product')->where('order_id',$id)->orderBy('id','DESC')->get(); $pdf = PDF::loadView('backend.orders.order_invoice',compact('order','orderItem'))->setPaper('a4')->setOptions([ 'tempDir' => public_path(), 'chroot' => public_path(), ]); return $pdf->download('invoice.pdf'); } }
# template-gas Template for Google Apps Script project. ## Tech stack - [Docker](https://www.docker.com/) - [Node.js](https://nodejs.org/) - [pnpm](https://pnpm.io/) - [clasp](https://github.com/google/clasp) - [Jest](https://jestjs.io/) ## Develop with containers - Install [Docker Desktop](https://www.docker.com/products/docker-desktop/) - Install [Visual Studio Code](https://code.visualstudio.com/) - Install [Docker extension for VS Code](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-docker) - Install [Dev Containers extension for VS Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) See also: - [Docker extension for Visual Studio Code](https://code.visualstudio.com/docs/containers/overview) - [Developing inside a Container using Visual Studio Code Remote Development](https://code.visualstudio.com/docs/remote/containers) ## Clasp - Enable the Google Apps Script API: https://script.google.com/home/usersettings ![Enable Apps Script API](https://user-images.githubusercontent.com/744973/54870967-a9135780-4d6a-11e9-991c-9f57a508bdf0.gif) - Login: ```sh clasp login ``` - Create **src** folder and create/clone your project: ```sh mkdir src clasp clone "1u-jqvFWtxsQE1Db_CqaWKc3jpDTXDWFFDUVOlloHlk0EmZ8MWtK3MJIk" --rootDir src ``` In this example **1u-jqvFWtxsQE1Db_CqaWKc3jpDTXDWFFDUVOlloHlk0EmZ8MWtK3MJIk** is script id. - Push/Pull modications ```sh clasp push clasp pull ```
<?php namespace backend\controllers; use common\models\Employee; use common\models\EmployeeMeta; use common\models\EmployeeSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use Yii; use yii\web\Response; use yii\db\Query; /** * EmployeeController implements the CRUD actions for Employee model. */ class EmployeeController extends Controller { /** * @inheritDoc */ public function behaviors() { return array_merge( parent::behaviors(), [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ] ); } /** * Lists all Employee models. * * @return string */ public function actionIndex() { $searchModel = new EmployeeSearch(); $searchModel->company_id = 1; //denso $dataProvider = $searchModel->search($this->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'queryParams' => $this->request->queryParams, ]); } /** * Displays a single Employee model. * @param int $id ID * @return string * @throws NotFoundHttpException if the model cannot be found */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Employee model. * If creation is successful, the browser will be redirected to the 'view' page. * @return string|\yii\web\Response */ public function actionCreate() { $model = new Employee(); if ($this->request->isPost) { if ($model->load($this->request->post())) { $transaction = db()->beginTransaction(); try { if ($model->save()) { $modelMeta = new EmployeeMeta(); $modelMeta->employee_id = $model->id; $modelMeta->meta_key = 'company_code'; $modelMeta->meta_value = (string) $model->company_code; if (!$modelMeta->save()) { var_dump($modelMeta->meta_value); var_dump($modelMeta->errors); exit; } } else { dump($model->errors); exit; } $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } catch (\Exception $exception) { $transaction->rollBack(); $errors[] = 'DB Error'; dump($exception->getMessage()); exit(); } } } else { $model->loadDefaultValues(); } return $this->render('create', [ 'model' => $model, ]); } /** * Updates an existing Employee model. * If update is successful, the browser will be redirected to the 'view' page. * @param int $id ID * @return string|\yii\web\Response * @throws NotFoundHttpException if the model cannot be found */ public function actionUpdate($id) { $model = $this->findModel($id); $model->company_code = $model->meta['company_code']; if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } return $this->render('update', [ 'model' => $model, ]); } /** * Deletes an existing Employee model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param int $id ID * @return \yii\web\Response * @throws NotFoundHttpException if the model cannot be found */ public function actionDelete($id) { // $this->findModel($id)->delete(); $model = $this->findModel($id); $model->status = $model::STATUS_DELETE; $model->save(); return $this->redirect(['index']); } /** * Finds the Employee model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param int $id ID * @return Employee the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Employee::findOne(['id' => $id])) !== null) { return $model; } throw new NotFoundHttpException('The requested page does not exist.'); } public function actionList($q = null, $id = null) { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $out = ['results' => ['id' => '', 'text' => '']]; if (!is_null($q)) { $query = new Query; $query->select(['code AS id', 'CONCAT(title, \' \',firstname, \' \', lastname, \' : \', code) AS text']) ->from('employee') ->where([ 'or', ['like', 'firstname', $q], ['like', 'lastname', $q], ['like', 'firstname_en', $q], ['like', 'lastname_en', $q], ['like', 'code', $q], ]) ->limit(20); $command = $query->createCommand(); $data = $command->queryAll(); $out['results'] = array_values($data); } elseif ($id > 0) { $out['results'] = ['id' => $id, 'text' => Employee::find($id)->fullname]; } return $out; } public function actionListX() { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $out = ['results' => ['id' => '', 'text' => '']]; // For List Query Behave List if (isset($_GET['search']['term']) && strlen($_GET['search']['term']) > 0) { $behave = Employee::findBySql("select id, concat(title,' ',firstname, ' ', lastname) as text from employee where company_id = :id and (firstname like :search or lastname like :search or title like :search) and status = :employeeStatus ", [ ':id' => user()->company_id, ':search' => '%' . $_GET['search']['term'] . '%', ':employeeStatus' => Employee::STATUS_ACTIVE ])->asArray()->all(); return ['results' => $behave]; } return []; } }
@extends('layouts.admin.app') @section('title',translate('messages.parcel_category')) @section('content') <div class="content container-fluid"> <!-- Page Header --> <div class="page-header"> <h1 class="page-header-title"> <span class="page-header-icon"> <img src="{{asset('public/assets/admin/img/parcel.png')}}" class="w--26" alt=""> </span> <span> {{translate('messages.parcel_category')}} </span> </h1> </div> <!-- End Page Header --> <div class="card"> <div class="card-body"> <form action="{{route('admin.parcel.category.store')}}" method="post" enctype="multipart/form-data"> @csrf <div class="row g-3"> @php($language=\App\Models\BusinessSetting::where('key','language')->first()) @php($language = $language->value ?? null) @php($defaultLang = str_replace('_', '-', app()->getLocale())) @if($language) <div class="col-12"> <ul class="nav nav-tabs mb-3 border-0"> <li class="nav-item"> <a class="nav-link lang_link active" href="#" id="default-link">{{translate('messages.default')}}</a> </li> @foreach (json_decode($language) as $lang) <li class="nav-item"> <a class="nav-link lang_link" href="#" id="{{ $lang }}-link">{{ \App\CentralLogics\Helpers::get_language_name($lang) . '(' . strtoupper($lang) . ')' }}</a> </li> @endforeach </ul> </div> @endif <div class="col-md-6"> @if ($language) <div class="lang_form" id="default-form"> <div class="form-group"> <label class="input-label" for="default_name">{{translate('messages.name')}} ({{ translate('messages.default') }})</label> <input type="text" name="name[]" id="default_name" class="form-control" placeholder="{{translate('messages.new_item')}}" > </div> <input type="hidden" name="lang[]" value="default"> <div class="form-group"> <label class="input-label" for="description">{{translate('messages.short_description')}} ({{ translate('messages.default') }})</label> <textarea type="text" name="description[]" class="form-control ckeditor" ></textarea> </div> </div> @foreach(json_decode($language) as $lang) <div class="d-none lang_form" id="{{$lang}}-form"> <div class="form-group"> <label class="input-label" for="{{$lang}}_name">{{translate('messages.name')}} ({{strtoupper($lang)}})</label> <input type="text" name="name[]" id="{{$lang}}_name" class="form-control" placeholder="{{translate('messages.new_item')}}" > </div> <input type="hidden" name="lang[]" value="{{$lang}}"> <div class="form-group"> <label class="input-label" for="description">{{translate('messages.short_description')}} ({{strtoupper($lang)}})</label> <textarea type="text" name="description[]" class="form-control ckeditor" ></textarea> </div> </div> @endforeach @else <div id="default-form"> <div class="form-group"> <label class="input-label" for="exampleFormControlInput1">{{translate('messages.name')}} ({{ translate('messages.default') }})</label> <input type="text" name="name[]" class="form-control" placeholder="{{translate('messages.new_item')}}" required> </div> <input type="hidden" name="lang[]" value="default"> <div class="form-group"> <label class="input-label" for="exampleFormControlInput1">{{translate('messages.short_description')}}</label> <textarea type="text" name="description[]" class="form-control ckeditor"></textarea> </div> </div> @endif {{-- <div class="form-group mb-0"> <label class="input-label">{{translate('messages.module')}}</label> <select name="module_id" id="module_id" required class="form-control js-select2-custom" data-placeholder="{{translate('messages.select_module')}}"> <option value="" selected disabled>{{translate('messages.select_module')}}</option> @foreach(\App\Models\Module::parcel()->get() as $module) <option value="{{$module->id}}" >{{$module->module_name}}</option> @endforeach </select> </div> --}} <input name="position" value="0" class="initial-hidden"> </div> <div class="col-md-6"> <div class="h-100 d-flex flex-column"> <label class="text-center d-block mt-auto"> {{translate('messages.image')}} <small class="text-danger">* ( {{translate('messages.ratio')}} 200x200)</small> </label> <div class="text-center py-3 my-auto"> <img class="img--120" id="viewer" src="{{asset('public/assets/admin/img/900x400/img1.jpg')}}" alt="image"/> </div> <div class="custom-file"> <input type="file" name="image" id="customFileEg1" class="custom-file-input" accept=".jpg, .png, .jpeg, .gif, .bmp, .tif, .tiff|image/*" required> <label class="custom-file-label" for="customFileEg1">{{translate('messages.choose_file')}}</label> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="input-label text-capitalize">{{translate('messages.per_km_shipping_charge')}}</label> <input type="number" step=".01" min="0" placeholder="{{translate('messages.per_km_shipping_charge')}}" class="form-control" name="parcel_per_km_shipping_charge"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="input-label text-capitalize">{{translate('messages.minimum_shipping_charge')}}</label> <input type="number" step=".01" min="0" placeholder="{{translate('messages.minimum_shipping_charge')}}" class="form-control" name="parcel_minimum_shipping_charge"> </div> </div> <div class="col-12"> <div class="btn--container justify-content-end"> <button type="reset" id="reset_btn" class="btn btn--reset">{{translate('messages.reset')}}</button> <button type="submit" class="btn btn--primary">{{translate('messages.Add Parcel Category')}}</button> </div> </div> </div> </form> </div> </div> <div class="card mt-3"> <div class="card-header py-2 border-0"> <div class="search--button-wrapper"> <h5 class="card-title"> {{translate('messages.parcel_category_list')}} <span class="badge badge-soft-dark ml-2" id="itemCount">{{$parcel_categories->total()}}</span> </h5> </div> </div> <div class="card-body p-0"> <div class="table-responsive datatable-custom"> <table id="columnSearchDatatable" class="table table-borderless table-thead-bordered table-align-middle" data-hs-datatables-options='{ "isResponsive": false, "isShowPaging": false, "paging":false, }'> <thead class="thead-light"> <tr> <th class="border-0">{{ translate('messages.SL') }}</th> <th class="border-0">{{translate('messages.id')}}</th> <th class="border-0">{{translate('messages.name')}}</th> <th class="border-0">{{translate('messages.module')}}</th> <th class="border-0">{{translate('messages.status')}}</th> <th class="border-0 text-center">{{translate('messages.orders_count')}}</th> <th class="border-0 text-center">{{translate('messages.per_km_shipping_charge')}}</th> <th class="border-0 text-center">{{translate('messages.minimum_shipping_charge')}}</th> <th class="border-0 text-center">{{translate('messages.action')}}</th> </tr> </thead> <tbody id="table-div"> @foreach($parcel_categories as $key=>$category) <tr> <td>{{$key+$parcel_categories->firstItem()}}</td> <td>{{$category->id}}</td> <td> <span class="d-block font-size-sm text-body"> {{Str::limit($category['name'], 20,'...')}} </span> </td> <td> <span class="d-block font-size-sm text-body"> {{Str::limit($category->module->module_name, 15,'...')}} </span> </td> <td> <label class="toggle-switch toggle-switch-sm" for="stocksCheckbox{{$category->id}}"> <input type="checkbox" data-url="{{route('admin.parcel.category.status',[$category['id'],$category->status?0:1])}}" class="toggle-switch-input redirect-url" id="stocksCheckbox{{$category->id}}" {{$category->status?'checked':''}}> <span class="toggle-switch-label"> <span class="toggle-switch-indicator"></span> </span> </label> </td> <td> <div class="text-center"> {{$category->orders_count}} </div> </td> <td> <div class="text-center"> {{$category->parcel_per_km_shipping_charge?\App\CentralLogics\Helpers::format_currency($category->parcel_per_km_shipping_charge): 'N/A'}} </div> </td> <td> <div class="text-center"> {{$category->parcel_minimum_shipping_charge?\App\CentralLogics\Helpers::format_currency($category->parcel_minimum_shipping_charge): 'N/A'}} </div> </td> <td> <div class="btn--container justify-content-center"> <a class="btn action-btn btn--primary btn-outline-primary" href="{{route('admin.parcel.category.edit',[$category['id']])}}" title="{{translate('messages.edit_category')}}"><i class="tio-edit"></i> </a> <a class="btn action-btn btn--danger btn-outline-danger form-alert" href="javascript:" data-id="category-{{$category['id']}}" data-message="{{ translate('Want to delete this category') }}" title="{{translate('messages.delete_category')}}"><i class="tio-delete-outlined"></i> </a> <form action="{{route('admin.parcel.category.destroy',[$category['id']])}}" method="post" id="category-{{$category['id']}}"> @csrf @method('delete') </form> </div> </td> </tr> @endforeach </tbody> </table> </div> </div> @if(count($parcel_categories) !== 0) <hr> @endif <div class="page-area"> {!! $parcel_categories->links() !!} </div> @if(count($parcel_categories) === 0) <div class="empty--data"> <img src="{{asset('/assets/admin/svg/illustrations/sorry.svg')}}" alt="public"> <h5> {{translate('no_data_found')}} </h5> </div> @endif </div> </div> @endsection @push('script_2') <script> "use strict"; $(document).on('ready', function () { // INITIALIZATION OF DATATABLES // INITIALIZATION OF SELECT2 $('.js-select2-custom').each(function () { let select2 = $.HSCore.components.HSSelect2.init($(this)); }); }); function readURL(input) { if (input.files && input.files[0]) { let reader = new FileReader(); reader.onload = function (e) { $('#viewer').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#customFileEg1").change(function () { readURL(this); }); $(".lang_link").click(function(e){ e.preventDefault(); $(".lang_link").removeClass('active'); $(".lang_form").addClass('d-none'); $(this).addClass('active'); let form_id = this.id; let lang = form_id.substring(0, form_id.length - 5); console.log(lang); $("#"+lang+"-form").removeClass('d-none'); if(lang == '{{$defaultLang}}') { $(".from_part_2").removeClass('d-none'); } else { $(".from_part_2").addClass('d-none'); } }); $('#reset_btn').click(function(){ $('#module_id').val(null).trigger('change'); $('#viewer').attr('src', "{{asset('public/assets/admin/img/900x400/img1.jpg')}}"); }) </script> @endpush
#pragma once #include <cstring> #include <type_traits> namespace vx { namespace math { // https://stackoverflow.com/questions/13888210/extremely-slow-bilinear-interpolation-compared-to-opencv // https://www.youtube.com/watch?v=_htjjOdXbmA /// @brief Apply bilinear filtering to an image. /// /// This function applies bilinear filtering to an image and /// maps the result to a new image. The images are assumed to be of /// the same format and have the same channel count in each pixel. /// /// @tparam channel_type The channel type of the image (must be an arithmetic /// type). /// @tparam float_type The floating-point type to use in floating-point /// calculations (defaults to float). /// /// @param src Pointer to the source image data. /// @param src_width Width of the source image. /// @param src_height Height of the source image. /// @param dst Pointer to the destination image data. /// @param dst_width Width of the destination image. /// @param dst_height Height of the destination image. /// @param channels Number of channels in the image pixels. template <typename channel_type, typename float_type = float> inline constexpr void filter_bilinear( const uint8_t* src, size_t src_width, size_t src_height, uint8_t* dst, size_t dst_width, size_t dst_height, size_t channels ) { static_assert(std::is_arithmetic<channel_type>::value, "channel_type must be arithmatic type"); static_assert(std::is_floating_point<float_type>::value, "float_type must be floating point type"); constexpr float_type min = static_cast<float_type>(std::numeric_limits<channel_type>::min()); constexpr float_type max = static_cast<float_type>(std::numeric_limits<channel_type>::max()); assert(src != nullptr); assert(dst != nullptr); const size_t pixel_size = sizeof(channel_type) * channels; if (dst_width == 0 || dst_height == 0 || channels == 0) { return; } if (src_width == 0 || src_height == 0) { std::memset(dst, 0, dst_width * dst_height * pixel_size); return; } const size_t src_row_size = src_width * pixel_size; const size_t dst_row_size = dst_width * pixel_size; const size_t srcxmax = src_width - 1; const size_t srcymax = src_height - 1; // Compute scaling factors for width and height const float_type xscale = static_cast<float_type>(src_width) / dst_width; const float_type yscale = static_cast<float_type>(src_height) / dst_height; // Loop over each row in the destination image for (size_t y = 0; y < dst_height; ++y) { // Map the vertical offset back to the source image to figure out what row // should be sampled from // We offset by -0.5 to align with the center of the source pixels const float_type srcyfrac = y * yscale - static_cast<float_type>(0.5); // Calculate pointer to the current row in the source image size_t srcy = static_cast<size_t>(srcyfrac); const uint8_t* srcrow = &src[src_row_size * srcy]; // Calculate the offset required to get the source pixel above or below const size_t dy = static_cast<size_t>(srcy < srcymax) * src_row_size; // Calculate the pointer to the destination pixel (the pixel that will be written to) uint8_t* dstpx = &dst[dst_row_size * y]; // Interpolation weights for y-coordinate const float_type fy2 = srcyfrac - srcy; const float_type fy = static_cast<float_type>(1) - fy2; // Loop over each column in the destination image for (size_t x = 0; x < dst_width; ++x, dstpx += pixel_size) { // Map the horizontal offset back to the source image to figure out what column // should be sampled from // We offset by -0.5 to align with the center of the source pixels const float_type srcxfrac = x * xscale - static_cast<float_type>(0.5); // Calculate pointer to the current pixel in the source image to sample from const size_t srcx = static_cast<size_t>(srcxfrac); const uint8_t* srcpx = &srcrow[srcx * pixel_size]; // Calculate the offset required to get the source pixel to the left or right const size_t dx = static_cast<size_t>(srcx < srcxmax) * pixel_size; // Interpolation weights for x-coordinate const float_type fx2 = srcxfrac - srcx; const float_type fx = static_cast<float_type>(1) - fx2; // Array of pointers to the four neighboring pixels used in interpolation const channel_type* pixels[4] = { reinterpret_cast<const channel_type*>(srcpx), reinterpret_cast<const channel_type*>(srcpx + dx), reinterpret_cast<const channel_type*>(srcpx + dy), reinterpret_cast<const channel_type*>(srcpx + dx + dy) }; channel_type* dst_pixel = reinterpret_cast<channel_type*>(dstpx); // Array of weights corresponding to each neighboring pixel const float_type weights[4] = { fx * fy, fx2 * fy, fx * fy2, fx2 * fy2 }; // Loop over each channel for (size_t c = 0; c < channels; ++c) { // Perform bilinear interpolation using the four neighboring pixels and weights const float_type px = ( pixels[0][c] * weights[0] + pixels[1][c] * weights[1] + pixels[2][c] * weights[2] + pixels[3][c] * weights[3] ); dst_pixel[c] = static_cast<channel_type>(std::clamp(px, min, max)); } } } } /// @brief Apply bilinear filtering to an image with a packed pixel format. /// /// This function applies bilinear filtering to an image and /// maps the result to a new image. The images are assumed to be of /// the same format and have the same channel count in each pixel. /// /// @tparam pixel_type The data type used to pack the pixels (must be an /// arithmetic type). /// @tparam float_type The floating-point type to use in floating-point /// calculations (defaults to float). /// /// @param src Pointer to the source image data. /// @param src_width Width of the source image. /// @param src_height Height of the source image. /// @param dst Pointer to the destination image data. /// @param dst_width Width of the destination image. /// @param dst_height Height of the destination image. /// @param channels Number of channels in the image pixels. /// @param channel_masks Pointer to an array of masks for each pixel channel. /// @param channel_shifts Pointer to an array of shifts for each pixel channel. template <typename pixel_type, typename float_type = float> inline constexpr void filter_bilinear( const uint8_t* src, size_t src_width, size_t src_height, uint8_t* dst, size_t dst_width, size_t dst_height, size_t channels, const pixel_type* channel_masks, const uint8_t* channel_shifts ) { static_assert(std::is_arithmetic<pixel_type>::value, "pixel_type must be arithmatic type"); static_assert(std::is_floating_point<float_type>::value, "float_type must be floating point type"); assert(src != nullptr); assert(dst != nullptr); assert(channel_masks != nullptr); assert(channel_shifts != nullptr); const size_t pixel_size = sizeof(pixel_type); if (dst_width == 0 || dst_height == 0 || channels == 0) { return; } if (src_width == 0 || src_height == 0) { std::memset(dst, 0, dst_width * dst_height * pixel_size); return; } const size_t src_row_size = src_width * pixel_size; const size_t dst_row_size = dst_width * pixel_size; const size_t srcxmax = src_width - 1; const size_t srcymax = src_height - 1; // Compute scaling factors for width and height const float_type xscale = static_cast<float_type>(src_width) / dst_width; const float_type yscale = static_cast<float_type>(src_height) / dst_height; // Loop over each row in the destination image for (size_t y = 0; y < dst_height; ++y) { // Map the vertical offset back to the source image to figure out what row // should be sampled from // We offset by -0.5 to align with the center of the source pixels const float_type srcyfrac = y * yscale - static_cast<float_type>(0.5); // Calculate pointer to the current row in the source image size_t srcy = static_cast<size_t>(srcyfrac); const uint8_t* srcrow = &src[src_row_size * srcy]; // Calculate the offset required to get the source pixel above or below const size_t dy = static_cast<size_t>(srcy < srcymax) * src_row_size; // Calculate the pointer to the destination pixel (the pixel that will be written to) uint8_t* dstpx = &dst[dst_row_size * y]; // Interpolation weights for y-coordinate const float_type fy2 = srcyfrac - srcy; const float_type fy = static_cast<float_type>(1) - fy2; // Loop over each column in the destination image for (size_t x = 0; x < dst_width; ++x, dstpx += pixel_size) { // Map the horizontal offset back to the source image to figure out what column // should be sampled from // We offset by -0.5 to align with the center of the source pixels const float_type srcxfrac = x * xscale - static_cast<float_type>(0.5); // Calculate pointer to the current pixel in the source image to sample from const size_t srcx = static_cast<size_t>(srcxfrac); const uint8_t* srcpx = &srcrow[srcx * pixel_size]; // Calculate the offset required to get the source pixel to the left or right const size_t dx = static_cast<size_t>(srcx < srcxmax) * pixel_size; // Interpolation weights for x-coordinate const float_type fx2 = srcxfrac - srcx; const float_type fx = static_cast<float_type>(1) - fx2; // Array of pointers to the four neighboring pixels used in interpolation const pixel_type* pixels[4] = { reinterpret_cast<const pixel_type*>(srcpx), reinterpret_cast<const pixel_type*>(srcpx + dx), reinterpret_cast<const pixel_type*>(srcpx + dy), reinterpret_cast<const pixel_type*>(srcpx + dx + dy) }; pixel_type* dst_pixel = reinterpret_cast<pixel_type*>(dstpx); // Array of weights corresponding to each neighboring pixel const float_type weights[4] = { fx * fy, fx2 * fy, fx * fy2, fx2 * fy2 }; // Loop over each channel for (size_t c = 0; c < channels; ++c) { // Perform bilinear interpolation using the four neighboring pixels and weights const float_type px = ( ((*pixels[0] & channel_masks[c]) >> channel_shifts[c]) * weights[0] + ((*pixels[1] & channel_masks[c]) >> channel_shifts[c]) * weights[1] + ((*pixels[2] & channel_masks[c]) >> channel_shifts[c]) * weights[2] + ((*pixels[3] & channel_masks[c]) >> channel_shifts[c]) * weights[3] ); *dst_pixel |= (static_cast<pixel_type>(std::clamp( px, static_cast<float_type>(0), static_cast<float_type>(channel_masks[c] >> channel_shifts[c]) )) << channel_shifts[c]); } } } } } }
//package com.conseller.conseller.user; // //import com.conseller.conseller.TestConfig; //import com.conseller.conseller.entity.User; //import com.conseller.conseller.user.dto.request.EmailAndNameRequest; //import com.conseller.conseller.user.enums.AccountBanks; //import com.conseller.conseller.user.enums.UserStatus; //import org.aspectj.lang.annotation.Before; //import org.junit.jupiter.api.BeforeAll; //import org.junit.jupiter.api.BeforeEach; //import org.junit.jupiter.api.DisplayName; //import org.junit.jupiter.api.Test; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; //import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; //import org.springframework.context.annotation.Import; // //import javax.persistence.EntityManager; //import java.util.Optional; // //import static org.assertj.core.api.Assertions.*; // //@Import({TestConfig.class}) //@DataJpaTest //public class UserRepositoryTest { // // private static final String REFRESH_TOKEN = "zzxcv76zxd8vy32"; // // @Autowired // private UserRepository userRepository; // // @Autowired // private TestEntityManager testEntityManager; // // static private User user; // // @BeforeAll // static void setupUser() { // user = User.builder() // .userId("test123123") // .userPassword("test123456!") // .userNickname("회원가입테스트용1") // .userPhoneNumber("01050945330") // .userGender('M') // .userAge(27) // .userName("테스트") // .userAccount("0234691047826307") // .userAccountBank(AccountBanks.fromString("신한은행").getBank()) // .userEmail("test1@gmail.com") // .userDeposit(0) // .userStatus(UserStatus.ACTIVE.getStatus()) // .userRestrictCount(0) // .refreshToken(REFRESH_TOKEN) // .build(); // } // // @BeforeEach // void initPersistenceContext() { // testEntityManager.clear(); // } // // @Test // @DisplayName("올바른 회원정보를 저장한다") // public void save() throws Exception { // // //given // userRepository.save(user); // // // when // Optional<User> savedUser = userRepository.findByUserId(user.getUserId()); // // //then // assertThat(savedUser.isPresent()).isTrue(); // } // // @Test // @DisplayName("해당 id의 유저 정보를 가져온다.") // void findByUserId() { // // // given // userRepository.save(user); // // //when // Optional<User> findUser = userRepository.findByUserId(user.getUserId()); // // // then // assertThat(findUser.isPresent()).isTrue(); // assertThat(findUser.get().getUserId()).isEqualTo(user.getUserId()); // } // // @Test // @DisplayName("없는 id일 경우에 null을 반환한다.") // void returnNullFindById() { // // // given // String userId = "test12345"; // // // when // Optional<User> findUser = userRepository.findByUserId(userId); // // // then // assertThat(findUser.isEmpty()).isTrue(); // } // // @Test // @DisplayName("이메일과 이름이 일치하는 유저의 정보를 불러올 수 있다.") // void findUserEmailAndUserName() { // // // given // userRepository.save(user); // // String userEmail = "test1@gmail.com"; // String userName = "테스트"; // // // when // Optional<User> findUser = userRepository.findByUserEmailAndUserName(userEmail, userName); // // // then // assertThat(findUser.isPresent()).isTrue(); // } // // @Test // @DisplayName("유저의 id를 통해 refreshToken을 가져온다.") // void getRefreshToken() { // // // given // userRepository.save(user); // // // when // String findRefreshToken = userRepository.findRefreshTokenByUserId("test123123") // .orElseThrow(() -> new RuntimeException("찾지 못함.")); // // // then // assertThat(findRefreshToken).isEqualTo(REFRESH_TOKEN); // } // // @Test // @DisplayName("이미 존재하는 유저 id일 경우에 true를 반환한다.") // void existsUserId() { // // // given // userRepository.save(user); // // // when // boolean isExists = userRepository.existsByUserId("test123123"); // // // then // System.out.println(isExists); // assertThat(isExists).isTrue(); // } //}
package ru.sorbo.inventory.framework; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; import ru.sorbo.inventory.domain.entity.CoreRouter; import ru.sorbo.inventory.domain.vo.IPAddress; import ru.sorbo.inventory.domain.vo.Identifier; import ru.sorbo.inventory.domain.vo.Model; import ru.sorbo.inventory.domain.vo.RouterType; import ru.sorbo.inventory.domain.vo.Vendor; import ru.sorbo.inventory.framework.adapters.input.generic.RouterManagementGenericAdapter; public class RouterTest extends FrameworkTestData { RouterManagementGenericAdapter routerManagementGenericAdapter; public RouterTest() { this.routerManagementGenericAdapter = new RouterManagementGenericAdapter(); loadData(); } @Test public void retrieveRouter() { var id = Identifier.withId("b832ef4f-f894-4194-8feb-a99c2cd4be0c"); var actualId = routerManagementGenericAdapter. retrieveRouter(id).getId(); assertEquals(id, actualId); } @Test public void createRouter() { var ipAddress = "40.0.0.1"; var routerId = this. routerManagementGenericAdapter.createRouter( Vendor.DLINK, Model.XYZ0001, IPAddress.fromAddress(ipAddress), locationA, RouterType.EDGE).getId(); var router = this.routerManagementGenericAdapter.retrieveRouter(routerId); assertEquals(routerId, router.getId()); assertEquals(Vendor.DLINK, router.getVendor()); assertEquals(Model.XYZ0001, router.getModel()); assertEquals(ipAddress, router.getIp().getIpAddress()); assertEquals(locationA, router.getLocation()); assertEquals(RouterType.EDGE, router.getRouterType()); } @Test public void addRouterToCoreRouter() { var routerId = Identifier.withId("b832ef4f-f894-4194-8feb-a99c2cd4be0b"); var coreRouterId = Identifier.withId("b832ef4f-f894-4194-8feb-a99c2cd4be0c"); var actualRouter = (CoreRouter)this.routerManagementGenericAdapter. addRouterToCoreRouter(routerId,coreRouterId); assertEquals(routerId, actualRouter.getRouters().get(routerId).getId()); } @Test public void removeRouterFromCoreRouter(){ var routerId = Identifier.withId("b832ef4f-f894-4194-8feb-a99c2cd4be0a"); var coreRouterId = Identifier.withId("b832ef4f-f894-4194-8feb-a99c2cd4be0c"); var removedRouter = this.routerManagementGenericAdapter. removeRouterFromCoreRouter(routerId, coreRouterId); var coreRouter = (CoreRouter)this.routerManagementGenericAdapter .retrieveRouter(coreRouterId); assertEquals(routerId, removedRouter.getId()); assertFalse(coreRouter.getRouters().containsKey(routerId)); } @Test public void removeRouter() { var routerId = Identifier.withId("b832ef4f-f894-4194-8feb-a99c2cd4be0b"); var router = this.routerManagementGenericAdapter.removeRouter(routerId); assertEquals(null, router); } }
from core.base import Base from core.openGLUtils import OpenGLUtils from core.attribute import Attribute from core.uniform import Uniform from OpenGL.GL import * # mover un triángulo alrededor de la pantalla con las arrow teclas class Test(Base): def initialize(self): print("Inicializando programa ...") vsCode = """ in vec3 position; uniform vec3 translation; void main() { vec3 pos = position + translation; gl_Position = vec4(pos.x, pos.y, pos.z, 1.0); } """ fsCode = """ out vec4 fragColor; void main() { fragColor = vec4(1.0,1.0,0.0,1.0); } """ self.programRef = OpenGLUtils.initializeProgram( vsCode, fsCode) #vertex array object vaoRef = glGenVertexArrays(1) glBindVertexArray(vaoRef) # attributes positionData = [[ 0.0, 0.2, 0.0], [ 0.2,-0.2, 0.0], [-0.2,-0.2, 0.0]] positionAttribute = Attribute("vec3", positionData) positionAttribute.associateVariable(self.programRef, "position") self.vertexCount = len(positionData) #uniforms self.translationUniform = Uniform("vec3", [0.0,0.0,0.0]) self.translationUniform.locateVariable(self.programRef, "translation") def update(self): glUseProgram(self.programRef) glClear( GL_COLOR_BUFFER_BIT ) #amount to move triangle distance = 0.01 if self.input.isKeyPressed("left"): self.translationUniform.data[0] -= distance if self.input.isKeyPressed("right"): self.translationUniform.data[0] += distance if self.input.isKeyPressed("down"): self.translationUniform.data[1] -= distance if self.input.isKeyPressed("up"): self.translationUniform.data[1] += distance self.translationUniform.uploadData() glDrawArrays(GL_TRIANGLES, 0, self.vertexCount) # create instance and run Test().run()
import { Link } from 'react-router-dom'; import { Icon } from 'components/ReusableComponents'; import { useIsCourseContentUserBar, useAppSelector } from 'hooks'; interface IProps { lesson_number: number; lesson_type: string; lesson_title: string; lesson_time_minutes: number; } export const LessonItem = ({lesson_number, lesson_type, lesson_title, lesson_time_minutes}: IProps) => { const { isCourseContentInUserBar, courseId, lesson } = useIsCourseContentUserBar(); const lessonUniqueId = `${courseId}/${lesson_number}`; const userLessonData = useAppSelector(state => state.userProgressClientData.lessons_progress.find(item => item.lessonId === lessonUniqueId)); const isCurrentLesson = lesson_number === +lesson!; const playGrey = lesson_type === 'video' && isCurrentLesson === false && (!userLessonData || userLessonData?.isWatched === false); const articleGrey = lesson_type === 'article' && isCurrentLesson === false; const currentPlay = lesson_type === 'video' && isCurrentLesson && (!userLessonData || (userLessonData?.isWatched === false && userLessonData?.isOnPlay === false)); const currentArticle = lesson_type === 'article' && isCurrentLesson; const finishedGrey = lesson_type === 'video' && isCurrentLesson === false && userLessonData?.isWatched === true && userLessonData.isOnPlay === false && userLessonData.isOnPause === false; const finishedYellow = lesson_type === 'video' && isCurrentLesson === true && userLessonData?.isWatched === true && userLessonData.isOnPlay === false && userLessonData.isOnPause === false; const onPlayedYellow = lesson_type === 'video' && isCurrentLesson === true && userLessonData?.isOnPlay === true && userLessonData.isOnPause === false; return ( <> <Link to={isCourseContentInUserBar ? `/course/${lessonUniqueId}` : `${lesson_number}`}> <div className="flex items-start gap-4 w-[408px]"> {playGrey && <Icon name="play" color="grey" wrapStyle="wrap-round-normal" wrapColor="grey"/>} {articleGrey && <Icon name="file" color="grey" wrapStyle="wrap-round-normal" wrapColor="grey"/>} {currentPlay && <Icon name="play" wrapStyle="wrap-round-normal" wrapColor="yellow"/>} {currentArticle && <Icon name="file" wrapStyle="wrap-round-normal" wrapColor="yellow"/>} {finishedGrey && <Icon name="check" color="grey" wrapStyle="wrap-round-normal" wrapColor="grey"/>} {finishedYellow && <Icon name="check" wrapStyle="wrap-round-normal" wrapColor="yellow"/>} {onPlayedYellow && <Icon name="pause" wrapStyle="wrap-round-normal" wrapColor="yellow"/>} <div className="pt-1.5"> <span className="text-style__body2--medium mb-1">{lesson_number}. {lesson_title}</span> <div className="text-Grey flex items-center gap-1.5 text-style__body3--regular"> <Icon name="clock" size="small"/> {lesson_time_minutes} min </div> </div> </div> </Link> </> ); };
import { useEffect, useState } from "react" export default function MousePointer() { const [mouseCoords, setMouseCoords] = useState({ x: 0, y: 0 }) const [isTouchEnabled, setIsTouchEnabled] = useState(false) useEffect(() => { const handleWindowMouseMove = (event: MouseEvent) => { setTimeout(() => { setMouseCoords({ x: event.clientX, y: event.clientY, }); }, 50) }; window.addEventListener('mousemove', handleWindowMouseMove); return () => { window.removeEventListener( 'mousemove', handleWindowMouseMove, ); }; }, []); useEffect(() => { setIsTouchEnabled( ('ontouchstart' in window) || (navigator.maxTouchPoints > 0) ) }) return ( <div style={{ top: mouseCoords.y, left: mouseCoords.x }} className={`${isTouchEnabled ? "hidden" : ""} fixed pointer-events-none translate-x-[-50%] translate-y-[-50%] w-[20px] h-[20px] bg-hemerald rounded-full blur-sm z-[100000]`} > </div> ) }
// // QuestionTextCell.swift // BMW Games // // Created by Natalia Givojno on 5.12.22. // import UIKit class QuestionTextCell: UITableViewCell { static var reuseID = "QuestionTextCell" private lazy var backgroundCellView: UIView = { var view = UIView() view.backgroundColor = UIColor(red:111/255, green:111/255, blue:111/255, alpha: 0.3) view.layer.cornerRadius = 10 return view }() private lazy var titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 //не в одну строку label.lineBreakMode = .byWordWrapping //разбить по словам т.е. перенос по словам label.font = UIFont.boldSystemFont(ofSize: 20) return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) //напрямую инициализатор не вызывается т.к. спрятан внутри dequeueReusableCell из QuizGameVC в let cell = ... // и он вызывает этот инициализатор, при этом создает очередь и складывает ячейки и их переиспользует setupViews() setupConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Private private func setupViews() { contentView.addSubview(backgroundCellView) contentView.addSubview(titleLabel) } private func setupConstraints() { backgroundCellView.snp.makeConstraints{make in make.top.bottom.left.right.equalTo(contentView).inset(10) } titleLabel.snp.makeConstraints{make in make.top.bottom.left.right.equalTo(backgroundCellView).inset(30) } } //MARK: - Public //функция configure которая принимает нашу модель Question из QuestionResponse func configure(_ model: Question?) { titleLabel.text = model?.text ?? "" // ?? "" - иначе пустая строка } }
from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * import PySpin import matplotlib.pyplot as plt import sys import keyboard import numpy as np import time import cv2 class CameraThread(QThread): imageAcquired = pyqtSignal(QPixmap) global continue_recording continue_recording = True def initialise(self): """ Example entry point; notice the volume of data that the logging event handler prints out on debug despite the fact that very little really happens in this example. Because of this, it may be better to have the logger set to lower level in order to provide a more concise, focused log. :return: True if successful, False otherwise. :rtype: bool """ result = True # Retrieve singleton reference to system object self.system = PySpin.System.GetInstance() # Get current library version version = self.system.GetLibraryVersion() print('Library version: %d.%d.%d.%d' % (version.major, version.minor, version.type, version.build)) # Retrieve list of cameras from the system self.cam_list = self.system.GetCameras() num_cameras = self.cam_list.GetSize() print('Number of cameras detected: %d' % num_cameras) # Finish if there are no cameras if num_cameras == 0: # Clear camera list before releasing system self.cam_list.Clear() # Release system instance self.system.ReleaseInstance() print('Not enough cameras!') input('Done! Press Enter to exit...') return False return result def exit(self): self.captureStop = True def endAcquisition(self): # Release reference to camera # NOTE: Unlike the C++ examples, we cannot rely on pointer objects being automatically # cleaned up when going out of scope. # The usage of del is preferred to assigning the variable to None. del self.cam # Clear camera list before releasing system self.cam_list.Clear() # Release system instance self.system.ReleaseInstance() print('Acquisition ended.') def run(self): self.run_single_camera() pass def snap(self): self.cam = self.cam_list[0] self.captureStop = False try: result = True nodemap_tldevice = self.cam.GetTLDeviceNodeMap() # Initialize camera self.cam.Init() # Retrieve GenICam nodemap nodemap = self.cam.GetNodeMap() except PySpin.SpinnakerException as ex: print('Error: %s' % ex) result = False sNodemap = self.cam.GetTLStreamNodeMap() # Change bufferhandling mode to NewestOnly node_bufferhandling_mode = PySpin.CEnumerationPtr(sNodemap.GetNode('StreamBufferHandlingMode')) if not PySpin.IsReadable(node_bufferhandling_mode) or not PySpin.IsWritable(node_bufferhandling_mode): print('Unable to set stream buffer handling mode.. Aborting...') return False # Retrieve entry node from enumeration node node_newestonly = node_bufferhandling_mode.GetEntryByName('NewestOnly') if not PySpin.IsReadable(node_newestonly): print('Unable to set stream buffer handling mode.. Aborting...') return False # Retrieve integer value from entry node node_newestonly_mode = node_newestonly.GetValue() # Set integer value from entry node as new value of enumeration node node_bufferhandling_mode.SetIntValue(node_newestonly_mode) print('*** IMAGE ACQUISITION ***\n') try: node_acquisition_mode = PySpin.CEnumerationPtr(nodemap.GetNode('AcquisitionMode')) if not PySpin.IsReadable(node_acquisition_mode) or not PySpin.IsWritable(node_acquisition_mode): print('Unable to set acquisition mode to continuous (enum retrieval). Aborting...') return False # Retrieve entry node from enumeration node node_acquisition_mode_continuous = node_acquisition_mode.GetEntryByName('Continuous') if not PySpin.IsReadable(node_acquisition_mode_continuous): print('Unable to set acquisition mode to continuous (entry retrieval). Aborting...') return False # Retrieve integer value from entry node acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue() # Set integer value from entry node as new value of enumeration node node_acquisition_mode.SetIntValue(acquisition_mode_continuous) print('Acquisition mode set to continuous...') # Begin acquiring images # # *** NOTES *** # What happens when the camera begins acquiring images depends on the # acquisition mode. Single frame captures only a single image, multi # frame catures a set number of images, and continuous captures a # continuous stream of images. # # *** LATER *** # Image acquisition must be ended when no more images are needed. self.cam.BeginAcquisition() print('Acquiring images...') # Retrieve device serial number for filename # # *** NOTES *** # The device serial number is retrieved in order to keep cameras from # overwriting one another. Grabbing image IDs could also accomplish # this. device_serial_number = '' node_device_serial_number = PySpin.CStringPtr(nodemap_tldevice.GetNode('DeviceSerialNumber')) if PySpin.IsReadable(node_device_serial_number): device_serial_number = node_device_serial_number.GetValue() print('Device serial number retrieved as %s...' % device_serial_number) # # Figure(1) is default so you can omit this line. Figure(0) will create a new window every time program hits this line # fig = plt.figure(1) # # Close the GUI when close event happens # fig.canvas.mpl_connect('close_event', self.handle_close) image_result = self.cam.GetNextImage(100) while image_result.IsIncomplete(): print('Image incomplete with image status %d ...' % image_result.GetImageStatus()) # Getting the image data as a numpy array image_data = image_result.GetNDArray() # plt.imshow(image_data, cmap='gray') # plt.pause(0.001) # plt.clf() height,width = image_data.shape imgOut = np.zeros((height,width,3)) imgOut[:,:,0] = image_data bytesPerLine = 3*width arrCombined = np.require(imgOut, np.uint8, 'C') qImg = QImage(arrCombined.data, width, height, bytesPerLine, QImage.Format_RGB888) pixmap = QPixmap.fromImage(qImg) # Draws an image on the current figure self.imageAcquired.emit(pixmap.scaled(720,512, aspectRatioMode=Qt.KeepAspectRatio)) image_result.Release() self.cam.EndAcquisition() except PySpin.SpinnakerException as ex: print('Error: %s' % ex) return False return True def acquire_and_display_images(self, nodemap, nodemap_tldevice): """ This function continuously acquires images from a device and display them in a GUI. :param cam: Camera to acquire images from. :param nodemap: Device nodemap. :param nodemap_tldevice: Transport layer device nodemap. :type cam: CameraPtr :type nodemap: INodeMap :type nodemap_tldevice: INodeMap :return: True if successful, False otherwise. :rtype: bool """ global continue_recording continue_recording = True sNodemap = self.cam.GetTLStreamNodeMap() # Change bufferhandling mode to NewestOnly node_bufferhandling_mode = PySpin.CEnumerationPtr(sNodemap.GetNode('StreamBufferHandlingMode')) if not PySpin.IsReadable(node_bufferhandling_mode) or not PySpin.IsWritable(node_bufferhandling_mode): print('Unable to set stream buffer handling mode.. Aborting...') return False # Retrieve entry node from enumeration node node_newestonly = node_bufferhandling_mode.GetEntryByName('NewestOnly') if not PySpin.IsReadable(node_newestonly): print('Unable to set stream buffer handling mode.. Aborting...') return False # Retrieve integer value from entry node node_newestonly_mode = node_newestonly.GetValue() # Set integer value from entry node as new value of enumeration node node_bufferhandling_mode.SetIntValue(node_newestonly_mode) print('*** IMAGE ACQUISITION ***\n') try: node_acquisition_mode = PySpin.CEnumerationPtr(nodemap.GetNode('AcquisitionMode')) if not PySpin.IsReadable(node_acquisition_mode) or not PySpin.IsWritable(node_acquisition_mode): print('Unable to set acquisition mode to continuous (enum retrieval). Aborting...') return False # Retrieve entry node from enumeration node node_acquisition_mode_continuous = node_acquisition_mode.GetEntryByName('Continuous') if not PySpin.IsReadable(node_acquisition_mode_continuous): print('Unable to set acquisition mode to continuous (entry retrieval). Aborting...') return False # Retrieve integer value from entry node acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue() # Set integer value from entry node as new value of enumeration node node_acquisition_mode.SetIntValue(acquisition_mode_continuous) print('Acquisition mode set to continuous...') # Begin acquiring images # # *** NOTES *** # What happens when the camera begins acquiring images depends on the # acquisition mode. Single frame captures only a single image, multi # frame catures a set number of images, and continuous captures a # continuous stream of images. # # *** LATER *** # Image acquisition must be ended when no more images are needed. self.cam.BeginAcquisition() print('Acquiring images...') # Retrieve device serial number for filename # # *** NOTES *** # The device serial number is retrieved in order to keep cameras from # overwriting one another. Grabbing image IDs could also accomplish # this. device_serial_number = '' node_device_serial_number = PySpin.CStringPtr(nodemap_tldevice.GetNode('DeviceSerialNumber')) if PySpin.IsReadable(node_device_serial_number): device_serial_number = node_device_serial_number.GetValue() print('Device serial number retrieved as %s...' % device_serial_number) # Close program print('Press enter to close the program..') # # Figure(1) is default so you can omit this line. Figure(0) will create a new window every time program hits this line # fig = plt.figure(1) # # Close the GUI when close event happens # fig.canvas.mpl_connect('close_event', self.handle_close) print(f'Recording: {continue_recording}') init = 1 # Retrieve and display images while(continue_recording): try: # Retrieve next received image # # *** NOTES *** # Capturing an image houses images on the camera buffer. Trying # to capture an image that does not exist will hang the camera. # # *** LATER *** # Once an image from the buffer is saved and/or no longer # needed, the image must be released in order to keep the # buffer from filling up. image_result = self.cam.GetNextImage(100) # Ensure image completion if image_result.IsIncomplete(): print('Image incomplete with image status %d ...' % image_result.GetImageStatus()) else: print('Image captured') # Getting the image data as a numpy array image_data = image_result.GetNDArray() # plt.imshow(image_data, cmap='gray') # plt.pause(0.001) # plt.clf() # time.sleep(5) # if init==1: # time.sleep(5) # init=0 height,width = image_data.shape imgOut = np.zeros((height,width,3)) imgOut[:,:,0] = image_data bytesPerLine = 3*width arrCombined = np.require(imgOut, np.uint8, 'C') qImg = QImage(arrCombined.data, width, height, bytesPerLine, QImage.Format_RGB888) pixmap = QPixmap.fromImage(qImg) # Draws an image on the current figure self.imageAcquired.emit(pixmap.scaled(720,512, aspectRatioMode=Qt.KeepAspectRatio)) print('Image emitted') # if init==1: # time.sleep(10) # init=0 # print('time passed') # Interval in plt.pause(interval) determines how fast the images are displayed in a GUI # Interval is in seconds. time.sleep(0.1) # Clear current reference of a figure. This will improve display speed significantly # If user presses enter, close the program if self.captureStop==True: print('Program is closing...') # Close figure # plt.close('all') # input('Done! Press Enter to exit...') continue_recording=False # Release image # # *** NOTES *** # Images retrieved directly from the camera (i.e. non-converted # images) need to be released in order to keep from filling the # buffer. image_result.Release() print('image released') except PySpin.SpinnakerException as ex: print('Error: %s' % ex) return False # End acquisition # # *** NOTES *** # Ending acquisition appropriately helps ensure that devices clean up # properly and do not need to be power-cycled to maintain integrity. self.cam.EndAcquisition() except PySpin.SpinnakerException as ex: print('Error: %s' % ex) return False return True def run_single_camera(self): """ This function acts as the body of the example; please see NodeMapInfo example for more in-depth comments on setting up cameras. :param cam: Camera to run on. :type cam: CameraPtr :return: True if successful, False otherwise. :rtype: bool """ self.cam = self.cam_list[0] self.captureStop = False try: result = True nodemap_tldevice = self.cam.GetTLDeviceNodeMap() # Initialize camera self.cam.Init() # Retrieve GenICam nodemap nodemap = self.cam.GetNodeMap() # Acquire images result &= self.acquire_and_display_images(nodemap, nodemap_tldevice) # # Deinitialize camera # self.cam.DeInit() except PySpin.SpinnakerException as ex: print('Error: %s' % ex) result = False # try: # self.endAcquisition() # except PySpin.SpinnakerException as ex: # print('Error: %s' % ex) # result = False print('Program Exited') return result class MainWindow(QWidget): def __init__(self): super().__init__() self.displayImage = QPixmap('./images/MTF graph.png') self.cameraFunctions = CameraThread() self.setWindowTitle("My App") self.setGeometry(100, 100, 800, 800) self.l = QGridLayout() self.setLayout(self.l) self.display = QLabel('image') self.display.setPixmap(self.displayImage.scaled(1080,720, aspectRatioMode=Qt.KeepAspectRatio)) self.l.addWidget(self.display,0,0,3,1) self.btnInitCam = QPushButton('Initialise') self.btnInitCam.clicked.connect(self.initCamera) self.l.addWidget(self.btnInitCam,0,1) self.btnPlay = QPushButton('Snapshot') self.btnPlay.clicked.connect(self.snapshot) self.l.addWidget(self.btnPlay,1,1) self.btnPlay = QPushButton('Play') self.btnPlay.clicked.connect(self.playPressed) self.l.addWidget(self.btnPlay,2,1) self.btnStop = QPushButton('Stop') self.btnStop.clicked.connect(self.stopPressed) self.l.addWidget(self.btnStop,3,1) self.cameraFunctions.initialise() # self.btnInitCam.setEnabled(False) # self.btnPlay.setEnabled(True) # self.btnStop.setEnabled(False) #SLOTS self.cameraFunctions.imageAcquired.connect(self.updateDisplay) def initCamera(self): # self.btnInitCam.setEnabled(False) # self.btnPlay.setEnabled(True) # self.btnStop.setEnabled(False) self.cameraFunctions.initialise() def snapshot(self): self.cameraFunctions.snap() def playPressed(self): # self.btnInitCam.setEnabled(False) # self.btnPlay.setEnabled(False) # self.btnStop.setEnabled(True) self.cameraFunctions.run() return def stopPressed(self): # self.btnInitCam.setEnabled(True) # self.btnPlay.setEnabled(False) # self.btnStop.setEnabled(False) self.cameraFunctions.exit() # self.cameraFunctions.terminate() return def updateDisplay(self, imagePixmap): self.display.setPixmap(imagePixmap) print('image updated') if __name__ == '__main__': import sys app = QApplication(sys.argv) app.setStyle("Fusion") palette = QPalette() palette.setColor(QPalette.Window, QColor(53, 53, 53)) palette.setColor(QPalette.WindowText, Qt.white) palette.setColor(QPalette.Base, QColor(25, 25, 25)) palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) palette.setColor(QPalette.ToolTipBase, Qt.white) palette.setColor(QPalette.ToolTipText, Qt.white) palette.setColor(QPalette.Text, Qt.white) palette.setColor(QPalette.Button, QColor(53, 53, 53)) palette.setColor(QPalette.ButtonText, Qt.white) palette.setColor(QPalette.BrightText, Qt.red) palette.setColor(QPalette.Link, QColor(42, 130, 218)) palette.setColor(QPalette.Highlight, QColor(42, 130, 218)) palette.setColor(QPalette.HighlightedText, Qt.black) app.setPalette(palette) window = MainWindow() window.show() sys.exit(app.exec())
import * as actionTypes from './actionTypes'; import axios, { AxiosError, AxiosResponse } from 'axios'; import { Dispatch } from 'react'; import { IQuestion } from '../reducers/quiz'; import { AppState } from "~/index"; interface CategoriesServerData { results: IQuestion[]; }; export const initQuiz = () => { return (dispatch: Dispatch<actionTypes.AllActions>, getState: () => AppState ) => { const apiURL = getState().startPage.settings.apiURL; dispatch(reset()); dispatch(fetchQuestionsStart()); axios.get(apiURL) .then((response: AxiosResponse<CategoriesServerData>) => { dispatch(fetchQuestionsSuccess(response.data.results)); }) .then( () => { dispatch(shuffleAnswers()); dispatch(quizStarted()) }) .catch((err: AxiosError) => { dispatch(fetchQuestionsFail(err)) }); } } export const fetchQuestionsStart = (): actionTypes.fetchQuestionsStart => { return { type: actionTypes.FETCH_QUESTIONS_START, } } export const fetchQuestionsSuccess = (data: IQuestion[]): actionTypes.fetchQuestionsSuccess => { return { type: actionTypes.FETCH_QUESTIONS_SUCCESS, questions: data, } } export const fetchQuestionsFail = (error: AxiosError): actionTypes.fetchQuestionsFail<AxiosError> => { return { type: actionTypes.FETCH_QUESTIONS_FAIL, error: error, } } export const shuffleAnswers = (): actionTypes.shuffleAnswers => { return { type: actionTypes.SHUFFLE_ANSWERS, } } export const quizStarted = (): actionTypes.quizStarted => { return { type: actionTypes.QUIZ_STARTED, } } export const quizQuit = (): actionTypes.quizQuit => { return { type: actionTypes.QUIZ_QUIT, } } export const endQuiz = (): actionTypes.endQuiz => { return { type: actionTypes.QUIZ_ENDED, } } export const reset = (): actionTypes.resetQuiz => { return { type: actionTypes.RESET_QUIZ, } }
// Copyright 2021 Crown Copyright (Single Trade Window) // // 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 uk.gov.cabinetoffice.bpdg.stw.tradetariffapi.service; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Optional; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import uk.gov.cabinetoffice.bpdg.stw.tradetariffapi.domain.AdditionalCode; import uk.gov.cabinetoffice.bpdg.stw.tradetariffapi.domain.GeographicalArea; import uk.gov.cabinetoffice.bpdg.stw.tradetariffapi.domain.Measure; import uk.gov.cabinetoffice.bpdg.stw.tradetariffapi.domain.MeasureType; import uk.gov.cabinetoffice.bpdg.stw.tradetariffapi.domain.TradeType; public class MeasureFiltererTest { private final MeasureFilterer measureFilterer = new MeasureFilterer(); @Nested class FilterRestrictiveMeasures { @Test @DisplayName( "Trade Type as IMPORT and measures are assigned to a group country where there are no countries assigned") void shouldIgnoreMeasureWhereGeographicalAreaIsGroupAndNoCountriesUnderThem() { Measure geographicalAreaWithNoCountriesMeasures = Measure.builder() .id("1") .measureType( MeasureType.builder().id("1").seriesId("B").description("Measure Type 1").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("").id("1080").build()) .build(); Measure measureRelatedToUSA = Measure.builder() .id("2") .measureType( MeasureType.builder().id("2").seriesId("B").description("Measure Type 2").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea( GeographicalArea.builder() .description("United States of America") .id("US") .build()) .build(); List<Measure> measureResponse = List.of(geographicalAreaWithNoCountriesMeasures, measureRelatedToUSA); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "US"); assertThat(filteredMeasures).containsExactlyInAnyOrder(measureRelatedToUSA); } @Test @DisplayName("Trade Type as IMPORT and measures are assigned to a single country") void importSingleCountry() { Measure measureRelatedToChina = Measure.builder() .id("1") .measureType( MeasureType.builder().id("1").seriesId("B").description("Measure Type 1").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToUSA = Measure.builder() .id("2") .measureType( MeasureType.builder().id("2").seriesId("B").description("Measure Type 2").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea( GeographicalArea.builder() .description("United States of America") .id("US") .build()) .build(); List<Measure> measureResponse = List.of(measureRelatedToChina, measureRelatedToUSA); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures).containsExactlyInAnyOrder(measureRelatedToChina); } @Test @DisplayName("Measures applicable to both trade types") void shouldDealWithMessagesWhichAreApplicableForTheTradeType() { Measure measureRelatedToExportOnly = Measure.builder() .id("1") .measureType( MeasureType.builder().id("1").seriesId("B").description("Measure Type 1").build()) .applicableTradeTypes(List.of(TradeType.EXPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToImportAndExport = Measure.builder() .id("2") .measureType( MeasureType.builder().id("2").seriesId("B").description("Measure Type 2").build()) .applicableTradeTypes(List.of(TradeType.IMPORT, TradeType.EXPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToImportsOnly = Measure.builder() .id("3") .measureType( MeasureType.builder().id("3").seriesId("B").description("Measure Type 3").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); List<Measure> measureResponse = List.of( measureRelatedToExportOnly, measureRelatedToImportAndExport, measureRelatedToImportsOnly); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures) .containsExactlyInAnyOrder(measureRelatedToImportAndExport, measureRelatedToImportsOnly); filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.EXPORT, "CN"); assertThat(filteredMeasures) .containsExactlyInAnyOrder(measureRelatedToImportAndExport, measureRelatedToExportOnly); } @Test @DisplayName( "Trade Type as EXPORT and measures are assigned to a single country and global area (ERGA OMNES)") void export_single_country_and_global_area() { Measure measureRelatedToChina = Measure.builder() .id("1") .applicableTradeTypes(List.of(TradeType.EXPORT)) .measureType( MeasureType.builder().id("1").seriesId("B").description("Measure Type 1").build()) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToErgaOmnes = Measure.builder() .id("2") .applicableTradeTypes(List.of(TradeType.EXPORT)) .measureType( MeasureType.builder().id("2").seriesId("B").description("Measure Type 2").build()) .geographicalArea( GeographicalArea.builder() .description("ERGA OMNES") .id("1011") .childrenGeographicalAreas(Set.of("CN", "US")) .build()) .build(); List<Measure> measureResponse = List.of(measureRelatedToChina, measureRelatedToErgaOmnes); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.EXPORT, "CN"); assertThat(filteredMeasures) .containsExactlyInAnyOrder(measureRelatedToChina, measureRelatedToErgaOmnes); } @Test @DisplayName("should return measure related to ERGA OMNES for EU country") void should_return_measure_any_country_erga_omnes() { Measure measureRelatedToErgaOmnes = Measure.builder() .id("1") .measureType( MeasureType.builder().id("1").seriesId("B").description("Measure Type 1").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea( GeographicalArea.builder() .description("ERGA OMNES") .id("1011") .childrenGeographicalAreas(Set.of("EU")) .build()) .build(); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures( List.of(measureRelatedToErgaOmnes), TradeType.IMPORT, "FR"); assertThat(filteredMeasures).containsExactlyInAnyOrder(measureRelatedToErgaOmnes); } @Test @DisplayName("Should return only the measure to the most specific geographical area") void shouldReturnTheMeasureToTheMostSpecificGeographicalArea() { Measure measureRelatedToChina = Measure.builder() .id("1") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("1").seriesId("B").description("Measure Type 1").build()) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToErgaOmnes = Measure.builder() .id("2") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("1").seriesId("B").description("Measure Type 1").build()) .geographicalArea( GeographicalArea.builder() .description("ERGA OMNES") .id("1011") .childrenGeographicalAreas(Set.of("CN", "US")) .build()) .build(); List<Measure> measureResponse = List.of(measureRelatedToChina, measureRelatedToErgaOmnes); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures).containsExactlyInAnyOrder(measureRelatedToChina); } @Test @DisplayName("Should not return measures if the given country is excluded") void shouldNotReturnExcludedCountry() { Measure measureRelatedToChina = Measure.builder() .id("1") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("1").seriesId("B").description("Measure Type 1").build()) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToErgaOmnes = Measure.builder() .id("2") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("2").seriesId("B").description("Measure Type 2").build()) .excludedCountries(Set.of("CN")) .geographicalArea( GeographicalArea.builder() .description("ERGA OMNES") .id("1011") .childrenGeographicalAreas(Set.of("CN", "US")) .build()) .build(); List<Measure> measureResponse = List.of(measureRelatedToChina, measureRelatedToErgaOmnes); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures).containsExactlyInAnyOrder(measureRelatedToChina); } @Test @DisplayName("Any Measures with a disallowed series ID should not be returned") void shouldExcludeDisallowedSeriesId() { Measure seriesIdCMeasure = Measure.builder() .id("1") .measureType( MeasureType.builder().id("1").seriesId("C").description("Measure Type 1").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure seriesIdAMeasure = Measure.builder() .id("2") .measureType( MeasureType.builder().id("2").seriesId("A").description("Measure Type 2").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); List<Measure> measureResponse = List.of(seriesIdCMeasure, seriesIdAMeasure); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures).containsExactlyInAnyOrder(seriesIdAMeasure); } @ParameterizedTest @ValueSource(strings = {"464", "481", "482", "483", "484", "495", "496", "730"}) void shouldExcludeDisallowedMeasureId(String disallowedMeasureId) { Measure measureWithDisallowedId = Measure.builder() .id("1") .measureType( MeasureType.builder() .id(disallowedMeasureId) .seriesId("A") .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure seriesIdAMeasure = Measure.builder() .id("3") .measureType( MeasureType.builder().id("3").seriesId("A").description("Measure Type 3").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); List<Measure> measureResponse = List.of(measureWithDisallowedId, seriesIdAMeasure); List<Measure> filteredMeasures = measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures).containsExactlyInAnyOrder(seriesIdAMeasure); } } @Nested class FilterTaxesMeasures { @Test @DisplayName("Trade Type as IMPORT and measures are assigned to a single country") void importSingleCountry() { Measure measureRelatedToChina = Measure.builder() .id("1") .measureType( MeasureType.builder().id("1").seriesId("C").description("Measure Type 1").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToUSA = Measure.builder() .id("2") .measureType( MeasureType.builder().id("2").seriesId("D").description("Measure Type 2").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea( GeographicalArea.builder() .description("United States of America") .id("US") .build()) .build(); List<Measure> measureResponse = List.of(measureRelatedToChina, measureRelatedToUSA); List<Measure> filteredMeasures = measureFilterer.getTaxAndDutyMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures).containsExactlyInAnyOrder(measureRelatedToChina); } @Test @DisplayName( "Trade Type as EXPORT and measures are assigned to a single country and global area (ERGA OMNES)") void export_single_country_and_global_area() { Measure measureRelatedToChina = Measure.builder() .id("1") .applicableTradeTypes(List.of(TradeType.EXPORT)) .measureType( MeasureType.builder().id("1").seriesId("C").description("Measure Type 1").build()) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToErgaOmnes = Measure.builder() .id("2") .applicableTradeTypes(List.of(TradeType.EXPORT)) .measureType( MeasureType.builder().id("2").seriesId("D").description("Measure Type 2").build()) .geographicalArea( GeographicalArea.builder() .description("ERGA OMNES") .id("1011") .childrenGeographicalAreas(Set.of("CN", "US")) .build()) .build(); List<Measure> measureResponse = List.of(measureRelatedToChina, measureRelatedToErgaOmnes); List<Measure> filteredMeasures = measureFilterer.getTaxAndDutyMeasures(measureResponse, TradeType.EXPORT, "CN"); assertThat(filteredMeasures) .containsExactlyInAnyOrder(measureRelatedToChina, measureRelatedToErgaOmnes); } @Test @DisplayName("should return measure related to ERGA OMNES for EU country") void shouldReturnMeasureAssignedToAnyCountryErgaOmnes() { Measure measureRelatedToErgaOmnes = Measure.builder() .id("1") .measureType( MeasureType.builder().id("1").seriesId("C").description("Measure Type 1").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea( GeographicalArea.builder() .description("ERGA OMNES") .id("1011") .childrenGeographicalAreas(Set.of("EU")) .build()) .build(); List<Measure> filteredMeasures = measureFilterer.getTaxAndDutyMeasures( List.of(measureRelatedToErgaOmnes), TradeType.IMPORT, "FR"); assertThat(filteredMeasures).containsExactlyInAnyOrder(measureRelatedToErgaOmnes); } @Test @DisplayName( "Should return the measures for a specific geographical area as well as measures applicable to a country group if that specific geographical area is also a part of the group") void shouldReturnTheMeasureToTheMostSpecificGeographicalArea() { Measure measureRelatedToChina = Measure.builder() .id("1") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("1").seriesId("C").description("Measure Type 1").build()) .geographicalArea(GeographicalArea.builder().description("China").id("KE").build()) .build(); Measure measureRelatedToGSP = Measure.builder() .id("2") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("2").seriesId("D").description("Measure Type 2").build()) .geographicalArea( GeographicalArea.builder() .description("GSP Countries") .id("1020") .childrenGeographicalAreas(Set.of("KE", "US")) .build()) .build(); Measure measureRelatedToSomeOtherCountries = Measure.builder() .id("3") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("3").seriesId("J").description("Measure Type 3").build()) .geographicalArea( GeographicalArea.builder() .description("Other group of countries") .id("1021") .childrenGeographicalAreas(Set.of("CH", "US")) .build()) .build(); List<Measure> filteredMeasures = measureFilterer.getTaxAndDutyMeasures( List.of( measureRelatedToChina, measureRelatedToGSP, measureRelatedToSomeOtherCountries), TradeType.IMPORT, "KE"); assertThat(filteredMeasures) .containsExactlyInAnyOrder(measureRelatedToChina, measureRelatedToGSP); } @Test @DisplayName("Should not return measures if the given country is excluded") void shouldNotReturnExcludedCountry() { Measure measureRelatedToChina = Measure.builder() .id("1") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("1").seriesId("C").description("Measure Type 1").build()) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); Measure measureRelatedToErgaOmnes = Measure.builder() .id("2") .applicableTradeTypes(List.of(TradeType.IMPORT)) .measureType( MeasureType.builder().id("2").seriesId("D").description("Measure Type 2").build()) .excludedCountries(Set.of("CN")) .geographicalArea( GeographicalArea.builder() .description("ERGA OMNES") .id("1011") .childrenGeographicalAreas(Set.of("CN", "US")) .build()) .build(); List<Measure> filteredMeasures = measureFilterer.getTaxAndDutyMeasures( List.of(measureRelatedToChina, measureRelatedToErgaOmnes), TradeType.IMPORT, "CN"); assertThat(filteredMeasures).containsExactlyInAnyOrder(measureRelatedToChina); } @ParameterizedTest @CsvSource({"C", "D", "J", "P", "Q"}) @DisplayName("Measures with certain series id should be included") void shouldIncludeMeasuresWithTaxRelatedSeriesId(String seriesId) { Measure seriesIdMeasure = Measure.builder() .id("1") .measureType( MeasureType.builder() .id("1") .seriesId(seriesId) .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); List<Measure> measureResponse = List.of(seriesIdMeasure); List<Measure> filteredMeasures = measureFilterer.getTaxAndDutyMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures).containsExactlyInAnyOrder(seriesIdMeasure); } @ParameterizedTest @CsvSource({ "A", "B", "E", "F", "G", "H", "I", "K", "L", "M", "N", "O", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }) @DisplayName("Measures with series id which are not related to tax should not be included") void shouldExcludeMeasuresWhichAreNotTaxRelated(String seriesId) { Measure seriesIdMeasure = Measure.builder() .id("1") .measureType( MeasureType.builder() .id("1") .seriesId(seriesId) .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); List<Measure> measureResponse = List.of(seriesIdMeasure); List<Measure> filteredMeasures = measureFilterer.getTaxAndDutyMeasures(measureResponse, TradeType.IMPORT, "CN"); assertThat(filteredMeasures).isEmpty(); } } @Nested class AdditionCodeFiltering { @Test @DisplayName( "When a non-residual additional code is present in request, then of all the Measures with an additional code, only return the one with the matching additional code.") void shouldExcludeAllOtherMeasuresWithAdditionalCodesWhenNonResidualAdditionalCodeInRequest() { Measure measureWithAdditionalCode1 = Measure.builder() .id("1") .measureType( MeasureType.builder() .id("475") .seriesId("B") .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .additionalCode( AdditionalCode.builder().code("4200").description("Procyon lotor").build()) .build(); Measure measureWithAdditionalCode2 = Measure.builder() .id("2") .measureType( MeasureType.builder() .id("475") .seriesId("B") .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .additionalCode( AdditionalCode.builder().code("4201").description("Canis lupus").build()) .build(); Measure measureWithAdditionalCode3 = Measure.builder() .id("3") .measureType( MeasureType.builder() .id("475") .seriesId("B") .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .additionalCode( AdditionalCode.builder().code("4202").description("Martes zibellina").build()) .build(); Measure seriesIdAMeasureWithNoAdditionalCode = Measure.builder() .id("4") .measureType( MeasureType.builder().id("2").seriesId("A").description("Measure Type 2").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); List<Measure> measureResponse = List.of( measureWithAdditionalCode1, measureWithAdditionalCode2, measureWithAdditionalCode3, seriesIdAMeasureWithNoAdditionalCode); List<Measure> filteredMeasures = measureFilterer.maybeFilterByAdditionalCode( measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "CN"), Optional.of("4202")); assertThat(filteredMeasures) .containsExactlyInAnyOrder( measureWithAdditionalCode3, seriesIdAMeasureWithNoAdditionalCode); } @Test @DisplayName( "When a residual additional code is present in request, then exclude all the Measures with an additional code.") void shouldExcludeAllMeasuresWithAdditionalCodesWhenResidualAdditionalCodeInRequest() { Measure measureWithAdditionalCode1 = Measure.builder() .id("1") .measureType( MeasureType.builder() .id("475") .seriesId("B") .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .additionalCode( AdditionalCode.builder().code("4200").description("Procyon lotor").build()) .build(); Measure measureWithAdditionalCode2 = Measure.builder() .id("2") .measureType( MeasureType.builder() .id("475") .seriesId("B") .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .additionalCode( AdditionalCode.builder().code("4201").description("Canis lupus").build()) .build(); Measure measureWithAdditionalCode3 = Measure.builder() .id("3") .measureType( MeasureType.builder() .id("475") .seriesId("B") .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .additionalCode( AdditionalCode.builder().code("4202").description("Martes zibellina").build()) .build(); Measure measureWithAdditionalCode4 = Measure.builder() .id("4") .measureType( MeasureType.builder() .id("475") .seriesId("B") .description("Measure Type 1") .build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .additionalCode(AdditionalCode.builder().code("4999").description("Other").build()) .build(); Measure seriesIdAMeasureWithNoAdditionalCode = Measure.builder() .id("5") .measureType( MeasureType.builder().id("2").seriesId("A").description("Measure Type 2").build()) .applicableTradeTypes(List.of(TradeType.IMPORT)) .geographicalArea(GeographicalArea.builder().description("China").id("CN").build()) .build(); List<Measure> measureResponse = List.of( measureWithAdditionalCode1, measureWithAdditionalCode2, measureWithAdditionalCode3, measureWithAdditionalCode4, seriesIdAMeasureWithNoAdditionalCode); List<Measure> filteredMeasures = measureFilterer.maybeFilterByAdditionalCode( measureFilterer.getRestrictiveMeasures(measureResponse, TradeType.IMPORT, "CN"), Optional.of("4999")); assertThat(filteredMeasures).containsExactlyInAnyOrder(seriesIdAMeasureWithNoAdditionalCode); } } }
#include <LiquidCrystal.h> LiquidCrystal lcd(8, 9, 10, 11, 12, 13); // LCD connected to these pins as rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13 #include <Servo.h> Servo myservo; const int stepPin = 7; // Stepper Motor as Extruder step pin 7 const int dirPin = 6; // stepper Motor as Extruder Direction pin 6 #define leftButton 2 #define rightButton 3 int cm = 0; void setup() { lcd.begin(16, 2); // Define columns and rows on LCD lcd.print("By: ");// Display Initial Massage on the display lcd.setCursor(0, 1); lcd.print("Dilpreet BHOGAL"); delay(5000); lcd.clear(); lcd.setCursor(0, 0); lcd.print("SELT LENGTH INCH"); lcd.setCursor(0, 1); lcd.print("DEC"); lcd.setCursor(13, 1); lcd.print("INC"); delay(100); myservo.attach(4); // Servo motor for cutting attached to Pin 4 myservo.write(90); // Write servo with initial open angle for cutter pinMode(stepPin, OUTPUT); // Define two pins as Outputs for Stepper pinMode(dirPin, OUTPUT); Serial.begin(9600); Serial.print("System is Started"); Serial.println(); pinMode(leftButton, INPUT_PULLUP); pinMode(rightButton, INPUT_PULLUP); } void loop() { if (digitalRead(rightButton)&& !digitalRead(leftButton) == 1) { if (cm == 8) { cm = 8; } else { cm += 1; } lcd.clear(); lcd.setCursor(5, 0); lcd.print("CM ="); lcd.setCursor(0, 1); lcd.print("DEC"); lcd.setCursor(10, 0); lcd.print(cm); lcd.setCursor(13, 1); lcd.print("INC"); } if (digitalRead(leftButton)&& !digitalRead(rightButton) == 1) { if (cm == 0) { cm = 0; } else { cm -= 1; } lcd.clear(); lcd.setCursor(5, 0); lcd.print("CM ="); lcd.setCursor(0, 1); lcd.print("DEC"); lcd.setCursor(10, 0); lcd.print(cm); lcd.setCursor(13, 1); lcd.print("INC"); } Serial.print(cm); delay(500); if (digitalRead(rightButton)&& digitalRead(leftButton) == 1) { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Processing......"); digitalWrite(dirPin,LOW); for(int x = 0; x < cm*160; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } delay(2000); myservo.write(20); delay(2000); myservo.write(90); delay(2000); lcd.clear(); lcd.setCursor(0, 0); lcd.print("Cutting Done"); delay(5000); lcd.clear(); lcd.setCursor(5, 0); lcd.print("CM ="); lcd.setCursor(0, 1); lcd.print("DEC"); lcd.setCursor(10, 0); lcd.print(cm); lcd.setCursor(13, 1); lcd.print("INC"); } // myservo.write(20); // myservo.write(20); // delay(2000); // myservo.write(90); // digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction // Makes 200 pulses for making one full cycle rotation // for(int x = 0; x < 200; x++) // { // digitalWrite(stepPin,HIGH); // delayMicroseconds(500); // digitalWrite(stepPin,LOW); // delayMicroseconds(500); // } // delay(1000); // One second delay }
import axios from 'axios'; import * as actionTypes from './actiontypes'; export const fetchAssignments = (token, courseID) => { return (dispatch) => { dispatch(fetchAssignmentsStart()); const url = `http://127.0.0.1:8000/api/${courseID}/assignment/list/`; const headers = { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` }; axios .get(url, { headers }) .then((res) => { const assignments = res.data; dispatch(fetchAssignmentsSuccess(assignments)); }) .catch((err) => { dispatch(fetchAssignmentsFail(err)); }); }; }; const fetchAssignmentsStart = () => { return { type: actionTypes.FETCH_ASSIGNMENTS_START, }; }; const fetchAssignmentsSuccess = (assignments) => { return { type: actionTypes.FETCH_ASSIGNMENTS_SUCCESS, assignments, }; }; const fetchAssignmentsFail = (error) => { return { type: actionTypes.FETCH_ASSIGNMENTS_FAIL, error, }; }; export const createAssignment = ( token, courseID, title, dueDate, fullGrade, assignmentFile ) => { return (dispatch) => { dispatch(createAssignmentStart()); const url = `http://127.0.0.1:8000/api/${courseID}/assignment/add/`; console.log(url) const headers = { 'Content-Type': 'application/json', Authorization: `Token ${token}`, }; const formData = new FormData(); formData.append('title', title); formData.append('courseId', courseID); formData.append('due_date', dueDate); formData.append('full_grade', fullGrade); formData.append('assignment_files', assignmentFile); axios .post(url, formData, { headers }) .then((res) => { dispatch(createAssignmentSuccess()); }) .catch((err) => { dispatch(createAssignmentFail(err)); }); }; }; const createAssignmentStart = () => { return { type: actionTypes.CREATE_ASSIGNMENT_START, }; }; const createAssignmentSuccess = () => { return { type: actionTypes.CREATE_ASSIGNMENT_SUCCESS, }; }; const createAssignmentFail = (error) => { return { type: actionTypes.CREATE_ASSIGNMENT_FAIL, error, }; }; export const fetchAssignmentDetails = (token, courseID, assignmentID) => { return dispatch => { dispatch(fetchAssignmentDetailsStart()); const url = `http://127.0.0.1:8000/api/${courseID}/${assignmentID}/detail/`; const headers = { 'Authorization': `Token ${token}`, }; axios.get(url, { headers }) .then(res => { const assignmentDetails = res.data; dispatch(fetchAssignmentDetailsSuccess(assignmentDetails)); }) .catch(err => { dispatch(fetchAssignmentDetailsFail(err)); }); }; }; const fetchAssignmentDetailsStart = () => { return { type: actionTypes.FETCH_ASSIGNMENT_DETAILS_START }; }; const fetchAssignmentDetailsSuccess = (assignmentDetails) => { return { type: actionTypes.FETCH_ASSIGNMENT_DETAILS_SUCCESS, assignmentDetails }; }; const fetchAssignmentDetailsFail = error => { return { type: actionTypes.FETCH_ASSIGNMENT_DETAILS_FAIL, error }; };
import Button from '@material-ui/core/Button'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import Grid from '@material-ui/core/Grid'; import Paper from '@material-ui/core/Paper'; import { styled } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Typography from '@material-ui/core/Typography'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { ACCOUNTS_LOADED } from '../../../constants/actionsTypes'; import api_agents from '../../../middleware/api_agent'; const StyledTableRow = styled(TableRow)(({ theme }) => ({ '&:nth-of-type(odd)': { backgroundColor: theme.palette.action.hover, }, // hide last border '&:last-child td, &:last-child th': { border: 0, }, })); class AccountsList extends Component { componentWillMount() { if (!this.props.accountsList) { // run getAllAccounts api when accounts list is undefined this.props.loadAccounts(api_agents.Accounts.getAllAccounts()); } } processWithdral = (event) => { event.preventDefault(); alert("Success") } renderWithdrawalButton = (balance, accountType) => { if(accountType === 'savings') { return( <Button color="primary" onClick={this.processWithdral.bind(this)} variant="contained" disabled={balance > 0 ? false : true}> Withdraw </Button> ) } else { return ( <Button color="primary" onClick={this.processWithdral.bind(this)} variant="contained" disabled={balance > -500 ? false : true}> Withdraw </Button> ) } } renderTableFooter = (totalBalance) => { return( <TableHead> <TableRow> <TableCell className="footerCopy">Balance</TableCell> <TableCell className="footerCopy" align="left"></TableCell> <TableCell className="footerCopy" align="left">ZAR {totalBalance}</TableCell> </TableRow> </TableHead> ) } render() { // check if its we are getting results as an array and if contains values if (typeof this.props.accountsList !== 'undefined' && this.props.accountsList.length > 0) { const accountsList = this.props.accountsList; // list of accounts from the state const renderAccounts = Object.keys(accountsList).map((key) =>{ const accountNumber = accountsList[key].account_number; const accountType = accountsList[key].account_type; const balance = accountsList[key].balance; return( <StyledTableRow key={key}> <TableCell scope="row"> {accountNumber} </TableCell> <TableCell align="left">{accountType}</TableCell> <TableCell align="left">ZAR {balance}</TableCell> <TableCell align="right"> {this.renderWithdrawalButton(balance, accountType)} </TableCell> </StyledTableRow> ) }); return( <Grid item md={12} container spacing={0} alignItems="center" justifyContent="center" direction="column" > <Grid md={6} container alignItems="center" justifyContent="center" item> <Card elevation={5}> <TableContainer component={Paper}> <CardHeader title="Account List" /> <Table sx={{ minWidth: 700 }} aria-label="customized table"> <TableHead> <TableRow> <TableCell>Account Number</TableCell> <TableCell align="left">Account Type</TableCell> <TableCell align="left">Balance</TableCell> <TableCell align="left"></TableCell> </TableRow> </TableHead> <TableBody> {renderAccounts} </TableBody> {this.renderTableFooter(this.props?.accountsList.reduce((a,v) => a = a - -v.balance , 0 ))} </Table> </TableContainer> </Card> </Grid> </Grid> ) } else { return ( <Grid item md={12} container spacing={0} alignItems="center" justifyContent="center" direction="column" > <Grid md={6} container alignItems="center" justifyContent="center" item> <Card elevation={5}> <Grid md={12} container alignItems="center" justifyContent="center" item> <Typography variant="h2" className="noAccountsMessage" > ERROR: No accounts to display please contact administrator </Typography> </Grid> </Card> </Grid> </Grid> ) } } } const mapStateToProps = state => { return { accountsList: state.accounts.accountsList }}; const mapDispatchToProps = dispatch => ({ loadAccounts: (payload) => dispatch({type: ACCOUNTS_LOADED, payload, skipTracking: true}) }); export default connect(mapStateToProps, mapDispatchToProps)(AccountsList);
<template> <div class="bg-container"> <div class="form-container"> <pv-card> <template #header> <div class="header"> <div class="logo-container"> <img class="logo" src="src/assets/logo.png" alt="logo"> <span>AgriPure</span> </div> </div> </template> <template #content> <div class="content"> <div class="btn-container"> <RouterLink to="/login"> <pv-button text raised>Log in</pv-button> </RouterLink> <RouterLink to="/register"> <pv-button text raised>Sign up</pv-button> </RouterLink> </div> <form @submit.prevent="submitForm"> <br> <pv-inputText v-model="firstName" type="text" placeholder="First Name" /> <br> <pv-inputText v-model="lastName" type="text" placeholder="Last Name" /> <br> <pv-inputText v-model="username" type="text" placeholder="Username" /> <br> <pv-inputText v-model="email" type="text" placeholder="Email" /> <br> <pv-inputText v-model="password" type="password" placeholder="Password" /> <br> <pv-button type="submit" raised>Submit</pv-button> </form> </div> </template> </pv-card> </div> </div> </template> <script> import { defineComponent } from 'vue'; import { useRouter } from 'vue-router'; import AuthApiService from '../services/auth-api.service'; export default defineComponent({ name: 'register-component', setup() { const router = useRouter(); return { router, }; }, data() { return { firstName: '', lastName: '', username: '', email: '', password: '', }; }, methods: { submitForm() { const registerData = { firstName: this.firstName, lastName: this.lastName, username: this.username, email: this.email, password: this.password, }; AuthApiService.signUp(registerData) .then(() => { this.router.push('/login'); }) .catch(error => { console.error('Error en el registro:', error); }); }, }, }); </script> <style scoped> .bg-container { width: 100%; height: 100vh; background-color: rgb(44, 43, 43); display: grid; } .form-container { display: flex; justify-content: center; width: 100%; padding: 3rem 0; justify-self: center; align-self: center; } .p-card { display: flex; flex-direction: column; width: 100%; height: fit-content; max-width: 30rem; margin: 0 1rem; padding: 2rem 0; border-radius:20px; background-color: rgb(63, 63, 63); color:white; } .header { flex-direction: column; } .logo-container { display: flex; align-items: center; justify-content: center; width: 100%; } .logo-container img { width: 6rem; border-radius: 9999px; } .logo-container span { margin-left: 1rem; font-size: 3.5rem; line-height: 1; } .content { margin: 0 2rem; } .content form { display: flex; flex-direction: column; margin: 1rem 0; } .content form button[type=submit] { background: rgb(47, 153, 47); border-color: rgb(47, 153, 47); justify-content: center; margin-top: 1rem; } .btn-container { display: flex; align-items: center; justify-content: center; background-color: rgb(53, 53, 53); margin: 0 0 1rem; padding: .25rem; border-radius: 6px; } .btn-container .p-button { width: 100%; color:white; justify-content: center; } .btn-container .p-button.active { background: rgb(47, 153, 47); } .btn-container > * + * { margin-left: .25rem; } @media (max-width: 599.98px) { card { padding: 1rem 0; } .content { margin: 1rem; } .logo-container { flex-direction: column; } .logo-container span { margin-top: 1rem; margin-left: 0; font-size: 2.5rem; } } </style>
#include <iostream> #include <fstream> #include "the6.h" void print_adj_list(std::vector< std::vector< std::pair<int,int> > >& adj_list) { int N = adj_list.size(); if (N == 0) { std::cout << "list is empty!" << std::endl; return; } for (int v=0;v<N;v++) { std::cout << v << "\t{"; for (auto p : adj_list[v]) { std::cout << " (" << p.first << "," << p.second << ")"; } std::cout << " }\n"; } return; } // you can use this if you want to print the adj list as a matrix void print_adj_list_as_matrix(std::vector< std::vector< std::pair<int,int> > >& adj_list) { int N = adj_list.size(); if (N == 0) { std::cout << "list is empty!" << std::endl; return; } int** matrix; matrix = new int*[N]; for(int temp=0; temp < N; temp++) matrix[temp] = new int[N]; for (int i=0; i<N; i++){ for (int j=0; j<N; j++){ matrix[i][j] = -1; // no edge } } for (int i=0; i<N; i++){ for (std::pair<int,int> x: adj_list[i]) { matrix[i][x.first] = x.second; } } for (int i=0; i<N; i++){ for (int j=0; j<N; j++){ if (matrix[i][j] == -1) std::cout << "- "; else std::cout << matrix[i][j] << " "; } std::cout << std::endl; } for(int i=0; i<N; i++) delete[] matrix[i]; delete[] matrix; return; } void read_from_file(std::vector< std::vector<std::pair<int,int> > >& bond_energies, std::vector< std::vector<std::pair<int,int> > >& molecule_structure){ char addr[]= "inp01.txt"; // 01-05 are available std::ifstream infile (addr); if (!infile.is_open()){ std::cout << "File \'"<< addr << "\' can not be opened. Make sure that this file exists." << std::endl; return; } int V_p1, E_p1, V_p2, E_p2; infile >> V_p1 >> E_p1; bond_energies.resize(V_p1); for (int l=0; l<E_p1; l++) { int v1, v2, w; infile >> v1 >> v2 >> w; bond_energies[v1].push_back(std::make_pair(v2,w)); bond_energies[v2].push_back(std::make_pair(v1,w)); } infile >> V_p2 >> E_p2; molecule_structure.resize(V_p2); for (int l=0; l<E_p2; l++) { int v1, v2, w; infile >> v1 >> v2 >> w; molecule_structure[v1].push_back(std::make_pair(v2,w)); molecule_structure[v2].push_back(std::make_pair(v1,w)); } infile.close(); } int main(){ std::vector< std::vector< std::pair<int,int> > > bond_energies; std::vector< std::vector< std::pair<int,int> > > molecule_structure; std::vector< std::vector< std::pair<int,int> > > lowest_energy_structure; std::vector<int> chain; int longest_chain_size, lowest_total_energy; read_from_file(bond_energies, molecule_structure); lowest_energy_structure.resize(bond_energies.size()); lowest_total_energy = find_structure(bond_energies, lowest_energy_structure); std::cout << "PART 1: " << std::endl << "Bond energy graph:" << std::endl; print_adj_list(bond_energies); std::cout << "Graph of the lowest energy structure found:" << std::endl; print_adj_list(lowest_energy_structure); std::cout << "Total energy of the lowest energy structure: " << lowest_total_energy << std::endl; longest_chain_size = find_longest_chain(molecule_structure,chain); std::cout << "PART 2: " << std::endl << "Molecule structure graph:" << std::endl; print_adj_list(molecule_structure); std::cout << "Atom count in longest chain: " << longest_chain_size << std::endl; std::cout << "Longest chain:" << std::endl; std::cout << "(" << chain[0] << ")"; for (int i=1; i<chain.size(); i++) { std::cout << " - (" << chain[i] << ")"; } return 0; }