text stringlengths 184 4.48M |
|---|
import React from 'react';
import { HeadFC, PageProps } from 'gatsby';
import {
Badge,
Box,
Button,
Divider,
Heading,
Spinner,
Stack,
Text,
Tooltip,
useDisclosure
} from '@chakra-ui/react';
import { EditIcon } from '@chakra-ui/icons';
import dayjs from 'dayjs';
import { Avatar, BackButton, HoveredLink, LayoutDashboard } from '@/components';
import { DATE_FORMAT } from '@/constants';
import { useUserContext } from '@/contexts';
import { TaskForm } from '@/forms';
import { useTaskDetails } from '@/hooks';
import { getComplexityColour, getFullName, getPriorityColour, getStatusColour } from '@/helpers';
import { DeleteTaskDialog } from '@/modals';
export const Head: HeadFC = () => <title>Task | AgileScope</title>;
const TaskPage = ({ params }: PageProps): React.ReactElement => {
const { taskId } = params;
const { isLoading, data } = useTaskDetails(taskId);
const { currentUser } = useUserContext();
const { isOpen, onOpen, onClose } = useDisclosure();
if (isLoading || !data) {
return <Spinner size="xl" color="green" />;
}
const TASK_DETAILS = data?.task as TTask;
const TASK_OWNER = TASK_DETAILS?.createdBy;
const CURRENT_USER_OWNS_TASK = currentUser?._id === TASK_OWNER?._id;
return (
<main>
<LayoutDashboard>
<BackButton />
<Box
display="flex"
flexDirection={{ base: 'column', md: 'row' }}
gap="1rem"
justifyContent="space-between"
alignItems={{ base: 'flex-start', md: 'center' }}
mt="0.5rem"
mb="1.5rem"
>
<Box>
<Text fontSize="2xl" fontWeight="semibold">
Task:
</Text>
<Heading as="h1" size="2xl" mb="0.25rem">
{TASK_DETAILS.title}
</Heading>
<Box fontSize="xs" fontStyle="italic">
<Text>
Created by{' '}
<strong>
{currentUser?._id === TASK_OWNER._id ? 'you' : getFullName(TASK_OWNER)}{' '}
</strong>
on {dayjs(TASK_DETAILS.createdAt).format(DATE_FORMAT)}
</Text>
<Text>
Last updated on {dayjs(TASK_DETAILS.updatedAt).format('YYYY-MM-DD hh:mm a')}
</Text>
</Box>
</Box>
<Tooltip
label={`Only the original task creator (${getFullName(
TASK_OWNER
)}) can make modifications`}
hasArrow
isDisabled={CURRENT_USER_OWNS_TASK}
>
<Stack direction="row" ml={{ base: 0, md: '2rem' }}>
<Button
colorScheme="green"
leftIcon={<EditIcon />}
onClick={onOpen}
isDisabled={!CURRENT_USER_OWNS_TASK}
>
Update
</Button>
<DeleteTaskDialog taskId={taskId} isDisabled={!CURRENT_USER_OWNS_TASK} />
</Stack>
</Tooltip>
</Box>
<TaskForm {...{ isOpen, onClose, task: TASK_DETAILS }} />
<Text fontSize="lg" color="gray.500" mb="1rem">
{TASK_DETAILS.description || 'No description for this task'}
</Text>
<Divider />
<Box display="flex" flexWrap="wrap" gap={{ base: '2rem', md: '4rem' }} my="1rem">
<Stack justifyContent="space-between" alignItems="flex-start">
<Heading as="h3" fontSize="xl">
Assigned to
</Heading>
<Avatar user={TASK_DETAILS.assignedTo} size="sm" showName />
</Stack>
<Stack justifyContent="space-between" alignItems="flex-start">
<Heading as="h3" fontSize="xl">
Project
</Heading>
<HoveredLink to={`/projects/${TASK_DETAILS.project._id}`}>
{TASK_DETAILS.project.title}
</HoveredLink>
</Stack>
<Stack justifyContent="space-between" alignItems="flex-start">
<Heading as="h3" fontSize="xl">
Sprint
</Heading>
<HoveredLink to={`/sprints?sprintId=${TASK_DETAILS.sprint._id}`}>
{TASK_DETAILS.sprint.name}
</HoveredLink>
</Stack>
</Box>
<Divider />
<Box display="flex" flexWrap="wrap" gap={{ base: '2rem', md: '4rem' }} my="1rem">
<Stack justifyContent="space-between" alignItems="flex-start">
<Heading as="h3" fontSize="xl">
Complexity
</Heading>
<Badge colorScheme={getComplexityColour(TASK_DETAILS.complexity)}>
{TASK_DETAILS.complexity}
</Badge>
</Stack>
<Stack justifyContent="space-between" alignItems="flex-start">
<Heading as="h3" fontSize="xl">
Priority
</Heading>
<Badge colorScheme={getPriorityColour(TASK_DETAILS.priority)}>
{TASK_DETAILS.priority}
</Badge>
</Stack>
<Stack justifyContent="space-between" alignItems="flex-start">
<Heading as="h3" fontSize="xl">
Status
</Heading>
<Badge colorScheme={getStatusColour(TASK_DETAILS.status)}>{TASK_DETAILS.status}</Badge>
</Stack>
<Stack justifyContent="space-between" alignItems="flex-start">
<Heading as="h3" fontSize="xl">
Due date
</Heading>
<Text>
{TASK_DETAILS.dueDate ? dayjs(TASK_DETAILS.dueDate).format(DATE_FORMAT) : '-'}
</Text>
</Stack>
{TASK_DETAILS.completedAt && (
<Stack justifyContent="space-between" alignItems="flex-start">
<Heading as="h3" fontSize="xl">
Completed at
</Heading>
<Text>{dayjs(TASK_DETAILS.completedAt).format(DATE_FORMAT)}</Text>
</Stack>
)}
</Box>
</LayoutDashboard>
</main>
);
};
export default TaskPage; |
### A PHP application for tracking expenses using Custom PHP web framework(MVC)
Framework feature:
1. Routeing Handle
2. Middleware handle
2. Template Engine
3. Dependency Injection Using Container
4. Form Validation
5. Database Connection Using PDO
6. Error Handle
Application Feature:
1. Authentication.
2. Transaction CRUD.
3. Receipt CRUD.
4. File handling.
## How to run
### Setup Database (Postgres)
1. `sudo nano /etc/php/8.1/apache2/php.ini`. Replace your php version.
2. And uncomment extension=pdo_pgsql, extension=pgsql.
3. Now install required driver in ubuntu for `sudo apt install php8.1-pgsql`.
4. Now you should connect postgres using PDO.
5. NB: PostgreSql should install in you machine. Also if you want
you can use Mysql.
### Env variable setup
. Create .env file in project root directory.
```
APP_ENV=development
DB_DRIVER=pgsql
DB_HOST=localhost
DB_PORT=3306
DB_NAME=******
DB_USER=******
DB_PASS=******
```
### Install dependencies
1. ```composer install```
### Run db script to generate table
1. ```composer run-script db```
### Setup Apache Server In Ubuntu
1. Run `cd /etc/apache2/sites-available`
2. Create new file named expense_tracker.conf `sudo nano expense_tracker.conf`
3. Put below content in this expense_tracker.conf file
```
<VirtualHost *:80>
ServerName expense-tracker.local
DocumentRoot /path_to_public_directory_of_project/public
<Directory /path_to_public_directory_of_project/public>
Require all granted
AllowOverride None
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.php [L]
</Directory>
</VirtualHost>
```
4. Now edit this file `sudo nano /etc/apache2/apache2.conf`.
5. Put this line bottom of the file `ServerName expense-tracker.local`.
6. Now disable default page for apache. So that we can use 80 port. `sudo a2dissite 000-default.conf`.
7. Now run below commands to restart & enable our our created conf file.
```
sudo a2ensite expense_tracker.conf
sudo apachectl configtest
sudo service apache2 restart
```
8. Now you should access site in your local machine using <b>expense-tracker.local</b> |
import {t} from 'i18next';
import {z, ZodIssueCode, type ZodErrorMap} from 'zod';
import {
ACCEPTED_IMAGE_EXTENSIONS,
ACCEPTED_IMAGE_MIME_TYPES,
ACCEPTED_IMPORT_FILE_EXTENSIONS,
ACCEPTED_IMPORT_MIME_TYPES,
MAX_FILE_SIZE,
MAX_FILE_SIZE_MB,
} from '~/config/system';
export const zodImage = z
.custom<File>((v) => v instanceof File, {
message: t('common.validation.required'),
})
.refine((file) => ACCEPTED_IMAGE_MIME_TYPES.includes(file.type), {
message: t('common.validation.imageFileType', {
mimeTypes: ACCEPTED_IMAGE_EXTENSIONS.join(', '),
}),
})
.refine((file) => file.size < MAX_FILE_SIZE, {
message: t('common.validation.maxFileSize', {
size: `${MAX_FILE_SIZE_MB}MB`,
}),
});
export const zodExcel = z
.custom<File>((v) => v instanceof File, {
message: t('common.validation.required'),
})
.refine((file) => ACCEPTED_IMPORT_MIME_TYPES.includes(file.type), {
message: t('common.validation.fileType', {
mimeTypes: ACCEPTED_IMPORT_FILE_EXTENSIONS.join(', '),
}),
})
.refine((file) => file.size < MAX_FILE_SIZE, {
message: t('common.validation.maxFileSize', {
size: `${MAX_FILE_SIZE_MB}MB`,
}),
});
export const zodCustomErrorMap: ZodErrorMap = (issue, ctx) => {
if (issue.code === ZodIssueCode.invalid_type) {
if (issue.expected === 'string' || issue.expected === 'number') {
return {message: t('common.validation.required')};
}
return {message: t('common.validation.invalidInput')};
}
return {message: ctx.defaultError};
}; |
let currentQuestion = 0;
let score = 0;
const questions = [
{
question: "Qual é o nome do vírus que causa a COVID-19?",
choices: [
"SARS-CoV-2",
"H1N1",
"Ebola",
"HIV"
],
correctAnswer: "SARS-CoV-2"
},
{
question: "Quais são os sintomas comuns da COVID-19?",
choices: [
"Febre, tosse e dor de cabeça",
"Dor de garganta e dor nas costas",
"Náusea e vômito",
"Dor nos olhos e coriza"
],
correctAnswer: "Febre, tosse e dor de cabeça"
},
{
question: "Qual é a principal forma de prevenção da COVID-19?",
choices: [
"Vacinação",
"Uso de antibióticos",
"Inalação de vapor",
"Exercícios físicos intensos"
],
correctAnswer: "Vacinação"
},
{
question: "Quanto tempo deve durar o isolamento de alguém com COVID-19?",
choices: [
"2 dias",
"5 dias",
"10 dias",
"14 dias"
],
correctAnswer: "14 dias"
},
{
question: "Qual é a principal forma de transmissão da COVID-19?",
choices: [
"Contato com superfícies contaminadas",
"Transmissão pelo ar",
"Insetos vetores",
"Água contaminada"
],
correctAnswer: "Transmissão pelo ar"
},
{
question: "Quais são os sintomas mais comuns da COVID-19?",
choices: [
"Dor de estômago e febre alta",
"Febre, tosse seca, perda de paladar e olfato",
"Dor nas costas e dor de cabeça",
"Erupção cutânea e náuseas"
],
correctAnswer: "Febre, tosse seca, perda de paladar e olfato"
},
{
question: "O uso de máscaras faciais é recomendado para quê?",
choices: [
"Proteger os olhos",
"Evitar a transmissão de vírus",
"Manter o rosto aquecido",
"Prevenir o câncer de pele"
],
correctAnswer: "Evitar a transmissão de vírus"
},
{
question: "O que significa 'quarentena'?",
choices: [
"Um filme de ação",
"Ficar em casa por 40 dias",
"Isolamento de pessoas doentes",
"Um período de 14 dias de isolamento para prevenir a propagação da doença"
],
correctAnswer: "Um período de 14 dias de isolamento para prevenir a propagação da doença"
},
{
question: "Qual grupo de idade tem maior risco de complicações graves pela COVID-19?",
choices: [
"Crianças",
"Pessoas jovens e saudáveis",
"Pessoas idosas",
"Adolescentes"
],
correctAnswer: "Pessoas idosas"
},
{
question: "Quando a pandemia de COVID-19 foi oficialmente declarada pela OMS?",
choices: [
"Janeiro de 2020",
"Março de 2020",
"Dezembro de 2019",
"Abril de 2020"
],
correctAnswer: "Março de 2020"
}
];
function startQuiz() {
const startButton = document.getElementById("start-button");
const startScreen = document.getElementById("start-screen");
const quizScreen = document.getElementById("quiz-screen");
startScreen.style.display = "none";
quizScreen.style.display = "block";
displayQuestion();
}
// Vincule o evento de clique ao botão de início
const startButton = document.getElementById("start-button");
startButton.addEventListener("click", startQuiz);
function displayQuestion() {
clearButtonStyles();
const questionElement = document.getElementById("question");
const choicesElement = document.getElementById("choices");
const incorrectAnswerText = document.getElementById("incorrect-answer");
const explanationContainer = document.getElementById("explanation-container");
const nextButton = document.querySelector(".next-button");
if (currentQuestion < questions.length) {
questionElement.textContent = questions[currentQuestion].question;
choicesElement.innerHTML = "";
questions[currentQuestion].choices.forEach(choice => {
const button = document.createElement("button");
button.textContent = choice;
button.onclick = () => checkAnswer(choice);
choicesElement.appendChild(document.createElement("li")).appendChild(button);
});
incorrectAnswerText.textContent = ""; // Limpar a resposta incorreta da pergunta anterior
explanationContainer.style.display = "none";
nextButton.style.display = "none"; // Esconder o botão "Próxima Pergunta"
} else {
showResult();
}
}
function checkAnswer(answer) {
const correctAnswer = questions[currentQuestion].correctAnswer;
const choiceButtons = document.querySelectorAll("#choices button");
const incorrectAnswerText = document.getElementById("incorrect-answer");
const nextButton = document.querySelector(".next-button");
const explanationContainer = document.getElementById("explanation-container");
if (answer === correctAnswer) {
score++;
incorrectAnswerText.textContent = ""; // Limpar a resposta incorreta
nextButton.style.display = "block"; // Mostrar o botão "Próxima Pergunta"
// Mudar a cor do botão correto para verde
choiceButtons.forEach(button => {
if (button.textContent === correctAnswer) {
button.style.backgroundColor = "green";
}
});
// Exibir mensagem de resposta correta
explanationContainer.style.display = "block";
explanationContainer.innerHTML = "Resposta correta!";
explanationContainer.style.color = "green";
} else {
incorrectAnswerText.textContent = `Resposta incorreta. A resposta correta é: ${correctAnswer}`;
nextButton.style.display = "block"; // Mostrar o botão "Próxima Pergunta"
// Mudar a cor do botão errado para vermelho
choiceButtons.forEach(button => {
if (button.textContent === answer) {
button.style.backgroundColor = "red";
}
});
// Limpar a mensagem de resposta correta
explanationContainer.style.display = "none";
}
}
function nextQuestion() {
currentQuestion++;
displayQuestion();
}
function showResult() {
const questionContainer = document.getElementById("question-container");
const resultContainer = document.createElement("div");
resultContainer.classList.add("result-container");
const resultElement = document.createElement("h2");
resultElement.classList.add("result-text");
const restartButton = document.createElement("button");
restartButton.classList.add("restart-button");
restartButton.addEventListener("click", returnToStart);
const resultImage = document.createElement("img"); // Adicione a tag <img> para a imagem
resultImage.setAttribute("src", "imagens/covid.jpeg"); // Substitua pelo caminho da sua imagem
resultImage.setAttribute("alt", "Imagem de resultado"); // Adicione um atributo alt para acessibilidade
resultImage.classList.add("result-image");
questionContainer.style.display = "none";
resultElement.textContent = `Você acertou ${score} de ${questions.length} perguntas.`;
resultContainer.appendChild(resultImage); // Adicione a imagem à div de resultado
resultContainer.appendChild(resultElement);
restartButton.textContent = "Recomeçar";
resultContainer.appendChild(restartButton);
// Ocultar o botão "Próxima Pergunta" na página de resultado
const nextButton = document.querySelector(".next-button");
nextButton.style.display = "none";
questionContainer.insertAdjacentElement('afterend', resultContainer);
resultContainer.style.display = "block";
}
function returnToStart() {
location.reload();
}
// Atribua o evento de clique ao botão "Recomeçar" aqui, uma vez é suficiente.
// const restartButton = document.querySelector(".restart-button");
// restartButton.addEventListener("click", returnToStart);
function clearButtonStyles() {
const buttons = document.querySelectorAll("#choices button");
buttons.forEach(button => {
button.style.backgroundColor = '#467EEC';
});
}
displayQuestion(); |
package com.services.impl;
import com.dtos.CoursDto;
import com.entities.Cours;
import com.repositories.CoursRepository;
import com.services.CoursService;
import org.springframework.stereotype.Service;
import javax.persistence.EntityNotFoundException;
import java.util.ArrayList;
import java.util.List;
@Service("coursService")
public class CoursServiceImpl implements CoursService {
private final CoursRepository coursRepository;
public CoursServiceImpl(CoursRepository coursRepository) {
this.coursRepository = coursRepository;
}
@Override
public CoursDto saveCours(CoursDto coursDto) {
// Converts the dto to the user entity
Cours cours = courDtoToEntity(coursDto);
// Save the user entity
cours = coursRepository.save(cours);
// Return the new dto
return courEntityToDto(cours);
}
@Override
public CoursDto getCoursById(Long coursId) {
Cours cours = coursRepository.findById(coursId).orElseThrow(() -> new EntityNotFoundException("Cours not found"));
return courEntityToDto(cours);
}
@Override
public boolean deleteCours(Long coursId) {
coursRepository.deleteById(coursId);
return true;
}
@Override
public List<CoursDto> getAllCours() {
List<CoursDto> coursDtos = new ArrayList<>();
List<Cours> cours = coursRepository.findAll();
cours.forEach(cour -> coursDtos.add(courEntityToDto(cour)));
return coursDtos;
}
/**
* Map cours dto to cours entity
*/
private CoursDto courEntityToDto(Cours cour){
CoursDto coursDto = new CoursDto();
coursDto.setId(cour.getId());
coursDto.setIntitule(cour.getIntitule());
coursDto.setVacataires(cour.getVacataires());
return coursDto;
}
/**
* Map cours entity to cours dto
*/
private Cours courDtoToEntity(CoursDto courDto){
Cours cour = new Cours();
cour.setId(courDto.getId());
cour.setIntitule(courDto.getIntitule());
cour.setVacataires(courDto.getVacataires());
return cour;
}
} |
package Ejercicio33;
import java.util.Scanner;
public class Empleado extends Persona {
private int codigoEmpleado;
private int horasExtras;
private String compañiaSeguro;
public Empleado(String nombre, String direccion, String ciudad, int codigoEmpleado, int horasExtras,
String compañiaSeguro) {
super(nombre, direccion, ciudad);
this.codigoEmpleado = codigoEmpleado;
this.horasExtras = horasExtras;
this.compañiaSeguro = compañiaSeguro;
}
public static Empleado leer() {
Scanner scanner = new Scanner(System.in);
System.out.println("Ingrese nombre: ");
String nombre = scanner.nextLine();
System.out.println("Ingrese dirección: ");
String direccion = scanner.nextLine();
System.out.println("Ingrese ciudad: ");
String ciudad = scanner.nextLine();
System.out.println("Ingrese codigo de empleado: ");
int codigoEmpleado = scanner.nextInt();
scanner.nextLine();
System.out.println("Ingrese horas extras: ");
int horasExtras = scanner.nextInt();
scanner.nextLine();
System.out.println("Ingrese compañia de seguros: ");
String compañiaSeguro = scanner.nextLine();
return new Empleado(nombre, direccion, ciudad, codigoEmpleado, horasExtras, compañiaSeguro);
}
@Override
public void mostrar() {
System.out.println("Nombre: " + this.getNombre());
System.out.println("Dirección: " + this.getDireccion());
System.out.println("Ciudad: " + this.getDireccion());
System.out.println("Codigo de empleado: " + this.codigoEmpleado);
System.out.println("Horas Extras: " + this.horasExtras);
System.out.println("Compañía de seguros: " + this.compañiaSeguro);
}
public void enviarSalario() {
System.out.println("Salario enviado a " + this.getNombre() + " a la dirección " + this.getDireccion());
}
public int getCodigoEmpleado() {
return codigoEmpleado;
}
public void setCodigoEmpleado(int codigoEmpleado) {
this.codigoEmpleado = codigoEmpleado;
}
public int getHorasExtras() {
return horasExtras;
}
public void setHorasExtras(int horasExtras) {
this.horasExtras = horasExtras;
}
public String getCompañiaSeguro() {
return compañiaSeguro;
}
public void setCompañiaSeguro(String compañiaSeguro) {
this.compañiaSeguro = compañiaSeguro;
}
} |
import React from "react";
import { valueMultiDropdownType } from "@components/MultiDropdown/MultiDropdown";
import rootStore from "@store/RootStore";
import { useSearchParams } from "react-router-dom";
import CategoryDropdown from "./components/CategoryDropdown";
import CoinsContainer from "./components/CoinsContainer";
import Search from "./components/Search";
import styles from "./Main.module.scss";
const Main = () => {
const [queryParams, setQueryParams] = useSearchParams();
const setPage = React.useCallback(
(number: number) => {
setQueryParams({ ...rootStore.query.params, page: String(number) });
},
[rootStore.query.params, setQueryParams]
);
const setSearch = React.useCallback(
(search: string) =>
setQueryParams({ ...rootStore.query.params, search, page: "1" }),
[rootStore.query.params, setQueryParams]
);
const setCategory = React.useCallback(
(category: valueMultiDropdownType) => {
setQueryParams({
...rootStore.query.params,
category: category ? category : "",
page: "1",
});
},
[rootStore.query.params, setQueryParams]
);
return (
<div className={styles.main}>
<Search setSearch={setSearch} />
<CategoryDropdown setCategory={setCategory} />
<CoinsContainer setPage={setPage} />
</div>
);
};
export default React.memo(Main); |
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
Query,
} from '@nestjs/common';
import { ResumesService } from './resumes.service';
import { CreateResumeDto, CreateUserCvDto } from './dto/create-resume.dto';
import { UpdateResumeDto } from './dto/update-resume.dto';
import { ResponseMessage } from 'src/decorators/responseMessage';
import { User } from 'src/decorators/getReqUser';
import { IUser } from 'src/users/users.interface';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('resumes')
@Controller('resumes')
export class ResumesController {
constructor(private readonly resumesService: ResumesService) {}
@ResponseMessage('create a resume success')
@Post()
create(@Body() createUserCvDto: CreateUserCvDto, @User() user: IUser) {
return this.resumesService.create(createUserCvDto, user);
}
@ResponseMessage('Fetch resumes with paginate')
@Get()
findAll(
@Query('current') current: string,
@Query('pageSize') pageSize: string,
@Query() qs: string,
) {
return this.resumesService.findAll(+current, +pageSize, qs);
}
@ResponseMessage('Fetch resumes By Id')
@Get(':id')
findOne(@Param('id') id: string) {
return this.resumesService.findOne(id);
}
@ResponseMessage("update resumes'status success")
@Patch(':id')
update(
@Param('id') id: string,
@Body('status') status: string,
@User() user: IUser,
) {
return this.resumesService.update(id, status, user);
}
@ResponseMessage('delete resume')
@Delete(':id')
remove(@Param('id') id: string, @User() user: IUser) {
return this.resumesService.remove(id, user);
}
@ResponseMessage("Fetch user's resume by user")
@Post('by-user')
findByUser(@User() user: IUser) {
return this.resumesService.findByUser(user);
}
} |
<?php
namespace App\Entity;
use App\Entity\Trait as HelperTrait;
use App\Repository\ProductRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
#[ORM\HasLifecycleCallbacks]
#[ORM\Entity(repositoryClass: ProductRepository::class)]
/**
* @author Aléki <alexlegras@hotmail.com>
* @access public
* @version 1
*
* This class represent a product, this entity is use to show data product to front user.
* This is class use Lifecycle callback throught traits.
*
*/
class Product
{
use HelperTrait\TimestampableWithIdTrait;
use HelperTrait\DeletableTrait;
#[ORM\Column(length: 255, nullable:false, type: Types::STRING)]
private ?string $name = null;
#[ORM\ManyToOne(inversedBy: 'products')]
private ?ProductCategory $category = null;
#[ORM\OneToMany(mappedBy: 'product', targetEntity: ProductReference::class)]
private Collection $productReferences;
#[ORM\Column(type: Types::BOOLEAN, nullable: false, options: ['default' => false])]
private bool $isFavorite;
public function __construct()
{
$this->productReferences = new ArrayCollection();
}
/**
* Product Name getter
*
* @return string|null
*/
public function getName(): ?string
{
return $this->name;
}
/**
* Product Name setter
*
* @param string $name
* @return static
*/
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
/**
* Product category getter
*
* @return ProductCategory|null
*/
public function getCategory(): ?ProductCategory
{
return $this->category;
}
/**
* Product categroy setter
*
* @param ProductCategory|null $category
* @return static-
*/
public function setCategory(?ProductCategory $category): static
{
$this->category = $category;
return $this;
}
/**
* @return Collection<int, ProductReferences>
*/
public function getProductReferences(): Collection
{
return $this->productReferences;
}
public function addProductReference(ProductReference $productReference): static
{
if (!$this->productReferences->contains($productReference)) {
$this->productReferences->add($productReference);
$productReference->setProduct($this);
}
return $this;
}
/**
* Remove one or many productReferences from a product
*
* @param mixed $productReference
* @return static
*/
public function removeProductReference(mixed $productReference): static
{
if ($this->productReferences->removeElement($productReference)) {
// set the owning side to null (unless already changed)
if ($productReference->getProduct() === $this) {
$productReference->setProduct(null);
}
}
return $this;
}
/**
* Method use by SluggableTrait to get valid source to slug
*
* @return string
*/
public function getValueToSlugify(): string {
return $this->name;
}
/**
* Get the value of isFavorite
*/
public function getIsFavorite()
{
return $this->isFavorite;
}
/**
* Set the value of isFavorite
*
* @return self
*/
public function setIsFavorite($isFavorite)
{
$this->isFavorite = $isFavorite;
return $this;
}
} |
#pragma once
#include <stdint.h>
#include <stdio.h>
#include <vector>
#include <set>
#include <map>
using namespace std;
// piece types
const uint8_t PAWN = 0;
const uint8_t KNIGHT = 1;
const uint8_t BISHOP = 2;
const uint8_t ROOK = 3;
const uint8_t QUEEN = 4;
const uint8_t KING = 5;
// color types
const uint8_t WHITE = 8;
const uint8_t BLACK = 16;
// square color types
const uint8_t LIGHT_SQUARE = 1;
const uint8_t DARK_SQUARE = 0;
const uint8_t NULL_SQUARE = 2;
// castle types
const uint8_t CASTLE_QUEEN = 1;
const uint8_t CASTLE_KING = 2;
// other enums
const uint8_t NO_ENPASS = 0x80; // set bit 7 only to designate no empass
const uint8_t ENPASS_AVAIL_MASK = 0x40; // set bit 6 to designate an enpass is possible in the given position - bits [5:0] designate the enpass square
// game end reasons
const uint8_t DRAW = 0; // DRAW is not to be used as a game end reason, but as a winner enum in addition to WHITE and BLACK
// no game end
const uint8_t NO_GAME_END = 0;
// wins
const uint8_t CHECKMATE = 0; // WHITE | CHECKMATE => white win by checkmate, BLACK | CHECKMATE => black win by checkmate
const uint8_t TIMEOUT = 1; // WHITE | TIMEOUT => white win by timeout, BLACK | TIMEOUT => black win by timeout
const uint8_t RESIGNATION = 2; // WHITE | RESIGNATION => white win by resignation, BLACK | RESIGNATION => black win by resignation
// draws
const uint8_t STALEMATE = 3;
const uint8_t REPITION = 4;
const uint8_t FIFTY_MOVE = 5;
const uint8_t INSUFICIENT_MATERIAL = 6;
const uint8_t AGREEMENT = 7;
/*
A p_id (piece id) is a 5 bit value that is in the form <color>|<piece>
ie.
WHITE | KING = 0b01110 // White King
BLACK | KING = 0b10110 // Black King
WHITE | PAWN = 0b01001 // White Pawn
*/
#define piece(p_id) ((p_id) & 0b00111) // Gives the piece type of a p_id
#define color(p_id) ((p_id) & 0b11000) // Gives the color type of a p_id
#define rank(square_id) ((square_id) / 8)
#define file(square_id) ((square_id) % 8)
#define square_id(rank, file) ((rank) * 8 + (file))
#define square_color(square_id) ((((square_id) >> 3) ^ (square_id)) & 1)
#define enpass_avail(enpass_info) (((enpass_info) & ENPASS_AVAIL_MASK) != 0)
#define enpass_square(enpass_info) ((enpass_info) & 0b00111111)
#define other_color(color) (24 - (color))
#define square_name(square_id) (square_names[square_id])
// Gives the square_id of the king of specified color
#define king_pos(color) state->king_pos[((color) >> 3) - 1]
// Gives boolean representing the ability of the king of given color to castle
// on the given side - True does not imply that the castle is valid, simply that
// is possible for it to become valid.
#define castle_avail(color, side) state->castling_avail[((color) >> 2) - (side)]
// Sets the castling availability to false while updating the zobrist hash
#define disable_castle(color, side) { \
if(castle_avail((color), (side))) { \
castle_avail((color), (side)) = false; \
state->zobrist ^= zobrist_castle_avail((color), (side)); \
}}
// performs move while updating the zobrist hash
// Used when move.move_type == MOVE_NORMAL
#define move_piece_check_capture(move) { \
if(state->squares[move.to_square] != 0) { \
state->zobrist ^= zobrist_piece_at((move).to_square, state->squares[(move).to_square]); \
} \
state->zobrist ^= zobrist_piece_at((move).from_square, state->squares[(move).from_square]) \
^ zobrist_piece_at((move).to_square, state->squares[(move).from_square]); \
state->squares[(move).to_square] = state->squares[(move).from_square]; \
state->squares[(move).from_square] = 0; \
}
// performs move while updating the zobrist hash
// Should only be used when a capture is impossible or handled seperately
#define move_piece_no_capture(move) { \
state->zobrist ^= zobrist_piece_at((move).from_square, state->squares[(move).from_square]) \
^ zobrist_piece_at((move).to_square, state->squares[(move).from_square]); \
state->squares[(move).to_square] = state->squares[(move).from_square]; \
state->squares[(move).from_square] = 0; \
}
/*
An end_code is a 5 bit value that is in the form <winner>|<reason>
The winner may be one of WHITE, BLACK, or DRAW
The reasons [CHECKMATE, TIMEOUT, RESIGNATION] must have either WHITE or BLACK as the winner
The reasons [STALEMATE, REPITITION, FIFTY_MOVE, INSUFICIENT_MATERIAL, AGREEMENT] must have DRAW as the winner
Any combination of winner and reason not listed above is an invalid end_code and may have undefined behavior
ie.
WHITE | CHECKMATE // white win by checkmate
BLACK | RESIGNATION // black win by resignation
DRAW | STALEMATE = STALEMATE // draw by stalemate
DRAW | FIFTY_MOVE = FIFTY_MOVE // draw by fifty move rule
*/
#define winner(end_code) ((end_code) & 0b11000)
#define reason(end_code) ((end_code) & 0b00111)
#define game_end(end_code) ((end_code) != 0)
#define draw(end_code) (((end_code) & 0b11000) == 0)
extern const char* square_names[64];
struct BoardState;
struct Board;
#include "move.h"
#include "chess_containers.h"
struct BoardState {
uint8_t squares[64]; // array of p_ids or NULL for empty - indecies correstend to squares { 0: A1, 1: B1, ... 7: H1, 8: A2, ... }
uint8_t king_pos[2]; // [<White>, <Black>]
uint8_t turn; // WHITE or BLACK
uint8_t castling_avail[4]; // [<White Kingside>, <White Queenside>, <Black Kingside>, <Black Queenside>]
uint8_t enpass_info; // bit [7] == 1 -> no_enpass ; bit[6] == 1 -> an enpass move is available ; bit[5:0] = the square id of the enpass square ; if bit [7] is set all other bits must be 0
uint8_t clock; // set to zero on a capture or pawn move, incremented otherwise - draw if clock == 100
uint16_t halfmoves; // number of halfmoves since the start of the game
uint64_t zobrist; // current zobrist hash
Composition composition; // current set and counts of pices on the board
uint8_t game_end_reason;
bool operator==(const BoardState& other) const; // determine equality in terms of three-fold repitition rule
};
struct Board {
BoardState* state;
vector<BoardState> stateStack;
// Methods
Board();
Board(const char* fen);
Board(string fen) : Board(fen.c_str()) {};
Board(BoardState state);
void attackSquares(SquareSet& attack_squares, uint8_t color, SquareSet& check_path_end);
void checksAndPins(SquareSet& check_path, bool& check, bool& double_check,
map<uint8_t, SquareSet >& pinned_squares);
MoveGenerator legalMoves();
void setGameEndReason();
bool isDrawRepitition();
bool isDrawFiftyMove();
bool isDrawInsuficientMaterial();
// move is not checked to be legal
// move not legal => undefined behavior
void makeMove(Move move);
void unmakeMove();
string get_fen();
uint64_t genZobrist();
}; |
1. Intro
--> Model in MVC contains a set of classes that represent data and the logic to manage that data.
--> For data, we will use Employee class
--> For retrieving and saving data, we will use MockEmployeeRepository class
--> In addition to the Employee class that represent the data, model also contains the class that manages the model data.
-----------------------------------------------------------------------------------
2. Employee Class
--> Make new folder in project : Models
--> Make new file in that : Employee.cs
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Department { get; set; }
}
-----------------------------------------------------------------------------------
3. Interface for manage model class
--> To manage the data i.e to retrieve and save employee data we are going to use the following IEmployeeRepository service.
--> Make new interface in Models folder --> IEmployeeRepository.cs
--> This interface will be useful in dependency injection
public interface IEmployeeRepository
{
Employee GetEmployee(int Id);
}
-----------------------------------------------------------------------------------
4. MockEmployeeRepository
--> This is the class which stores functions for retrieving data, posting data, updating data, deleting data.
--> All crud operations for model class will be done by this class
--> This class implements Interface to provide this class to other classes as dependency injection, not as creating objects.
--> Dependency injection makes our application flexible and easily unit testable
-----------------------------------------------------------------------------------
public class MockEmployeeRepository : IEmployeeRepository
{
private List<Employee> _employeeList;
public MockEmployeeRepository()
{
_employeeList = new List<Employee>()
{
new Employee() { Id = 1, Name = "Mary", Department = "HR", Email = "mary@pragimtech.com" },
new Employee() { Id = 2, Name = "John", Department = "IT", Email = "john@pragimtech.com" },
new Employee() { Id = 3, Name = "Sam", Department = "IT", Email = "sam@pragimtech.com" },
};
}
public Employee GetEmployee(int Id)
{
return this._employeeList.FirstOrDefault(e => e.Id == Id);
}
}
-----------------------------------------------------------------------------------
5. Controller Class
public class HomeController : Controller
{
public IEmployeeRepository _employeeRepository { get; set; }
public HomeController(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
public string index()
{
return _employeeRepository.GetEmployee(1).Name;
}
}
--> Above code will give error because we need to register dependency injection in startup file.
-----------------------------------------------------------------------------------
6. Summary
1. Model --> describes data
2. ModelRepository --> gives functions for retrieving, creating, updating and deleting data
3. Interface --> Give option for dependency injection
----------------------------------------------------------------------------------- |
# EasyAdminUltimate
**EasyAdminUltimate** is a comprehensive and enhanced template for EasyAdmin that offers a wide range of additional features and ready-to-use functionalities. This robust platform is designed to facilitate the creation of powerful dashboards with minimal effort, making it suitable for various projects. Below is a detailed description of each feature provided by EasyAdminUltimate.
### EAU Services & Models
- [Affiliation Service](./features/affiliation-service.md)
- [Affix (Form Option)](./features/affix.md)
- [Configuration Service](./features/configuration-service.md)
- [Abstract Controllers](./features/controllers.md)
- [Javascript Payload](./features/js-payload.md)
- [Modal Service](./features/modal-service.md)
- [Table Builder Utility](./features/table-builder.md)
- [User Properties & Fields](./features/user-property-field-config.md)
## Features
### 1. Security System
EasyAdminUltimate includes a complete security system out of the box. This system encompasses:
- **Registration**: Allows new users to create an account.
- **Login**: Enables users to access their accounts securely.
- **Forgot Password**: Provides a mechanism for users to reset their passwords if they forget them.
;
### 2. General Purpose Entities
The template comes with general-purpose entities that are versatile and can be adapted to suit various projects. These entities include pre-configured fields and validation rules, saving developers significant time and effort.
### 3. User CRUD Controller
EasyAdminUltimate offers a user-friendly CRUD (Create, Read, Update, Delete) controller for managing user data. This controller ensures that managing user information is seamless and efficient.

### 4. Affiliation Program
The template includes an affiliation program module, which allows you to set up and manage an affiliate marketing system. This feature helps in tracking referrals and commissions, thus facilitating marketing efforts.
### 5. Genealogy and Hierarchy Tree System
With the genealogy and hierarchy tree system, you can visualize and manage relationships and structures in a hierarchical manner. This is particularly useful for applications that require a clear representation of relationships, such as family trees or organizational charts.

### 6. Media File Upload Manager
The media file upload manager simplifies the process of uploading, organizing, and managing media files. This feature supports various file types and ensures that media management is straightforward and efficient.

### 7. Header and Footer Content Placement Manager
EasyAdminUltimate provides a content placement manager for headers and footers, allowing you to easily customize and manage the content displayed in these sections. This feature supports dynamic content and ensures that your headers and footers are always up-to-date.

### 8. Additional Features
EasyAdminUltimate also includes a variety of other features that enhance its functionality and usability. These additional features are designed to provide a comprehensive solution for building and managing dashboards effectively.

---
If you have any questions or need further assistance, please feel free to contact us at [support@example.com](mailto:support@example.com). |
//
// PreviewView.swift
// netflix
//
// Created by Zach Bazov on 30/09/2022.
//
import UIKit
final class PreviewView: UIView {
private var viewModel: PreviewViewViewModel!
private(set) var mediaPlayerView: MediaPlayerView!
private(set) lazy var imageView = createImageView()
init(on parent: UIView, with viewModel: DetailViewModel) {
self.viewModel = .init(with: viewModel.media)
super.init(frame: .zero)
parent.addSubview(self)
self.constraintToSuperview(parent)
self.viewDidConfigure()
self.mediaPlayerView = createMediaPlayer(on: parent, view: self, with: viewModel)
}
required init?(coder: NSCoder) { fatalError() }
deinit {
mediaPlayerView = nil
viewModel = nil
mediaPlayerView = nil
}
private func createMediaPlayer(on parent: UIView,
view: PreviewView,
with viewModel: DetailViewModel) -> MediaPlayerView {
let mediaPlayerView = MediaPlayerView(on: view, with: viewModel)
mediaPlayerView.prepareToPlay = { [weak self] isPlaying in
isPlaying ? self?.imageView.isHidden(true) : self?.imageView.isHidden(false)
}
mediaPlayerView.delegate?.player(mediaPlayerView.mediaPlayer,
willReplaceItem: mediaPlayerView.viewModel.item)
mediaPlayerView.delegate?.playerDidPlay(mediaPlayerView.mediaPlayer)
parent.addSubview(mediaPlayerView)
mediaPlayerView.constraintToSuperview(parent)
return mediaPlayerView
}
private func createImageView() -> UIImageView {
let imageView = UIImageView(frame: bounds)
imageView.contentMode = .scaleAspectFit
addSubview(imageView)
return imageView
}
private func viewDidConfigure() {
AsyncImageFetcher.shared.load(
url: viewModel.url,
identifier: viewModel.identifier) { [weak self] image in
asynchrony { self?.imageView.image = image }
}
}
} |
package com.ross.jettrivia.screens
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ross.jettrivia.data.DataWrapper
import com.ross.jettrivia.model.QuestionItem
import com.ross.jettrivia.repository.QuestionRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class QuestionsViewModel @Inject constructor(private val repository: QuestionRepository) : ViewModel() {
val data: MutableState<DataWrapper<ArrayList<QuestionItem>>> = mutableStateOf(
DataWrapper(questions = null, loading = true, e = null)
)
init {
getAllQuestions()
}
private fun getAllQuestions() {
viewModelScope.launch {
data.value.loading = true
data.value = repository.getAllQuestions()
data.value.questions?.let { list ->
data.value.loading = list.isEmpty()
}
}
}
fun getTotalQuestionCount(): Int {
return data.value.questions?.toMutableList()?.size!!
}
} |
import os
os.chdir('../')
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class DataTransformationConfig:
root_dir: Path
data_path: Path
tokenizer_name: Path
from textSummarizer.constants import *
from textSummarizer.utils.common import read_yaml, create_directories
class ConfigurationManager:
def __init__(
self,
config_filepath=CONFIG_FILE_PATH,
params_filepath=PARAMS_FILE_PATH):
self.config = read_yaml(config_filepath)
self.params = read_yaml(params_filepath)
create_directories([self.config.artifacts_root])
def get_data_transformation_config(self) -> DataTransformationConfig:
config = self.config.data_transformation
create_directories([config.root_dir])
data_transformation_config = DataTransformationConfig(
root_dir=config.root_dir,
data_path=config.data_path,
tokenizer_name=config.tokenizer_name
)
return data_transformation_config
import os
from textSummarizer.logging import logger
from transformers import AutoTokenizer
from datasets import load_dataset, load_from_disk
class DataTransformation:
def __init__(self, config=DataTransformationConfig):
self.config = config
self.tokenizer = AutoTokenizer.from_pretrained(config.tokenizer_name)
def convert_examples_to_features(self, example_batch):
input_encodings = self.tokenizer(example_batch['dialogue'], max_length=1024, truncation=True)
with self.tokenizer.as_target_tokenizer():
target_encodings = self.tokenizer(example_batch['summary'], max_length=128, truncation=True)
return {
'input_ids': input_encodings['input_ids'],
'attention_mask': input_encodings['attention_mask'],
'labels': target_encodings['input_ids']
}
def convert(self):
dataset_samsam = load_from_disk(self.config.data_path)
dataset_samsam_pt = dataset_samsam.map(self.convert_examples_to_features, batched=True)
dataset_samsam_pt.save_to_disk(os.path.join(self.config.root_dir, "samsam_dataset"))
# STEP - 6
# Update the pipeline
try:
config = ConfigurationManager()
data_transformation_config = config.get_data_transformation_config()
data_transformation = DataTransformation(config=data_transformation_config)
data_transformation.convert()
except Exception as e:
raise e |
import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { TypeOrmModule } from '@nestjs/typeorm'
import { AuthModule } from './auth/auth.module'
import { CategoryModule } from './category/category.module'
import { CityModule } from './city/city.module'
import { EmailModule } from './email/email.module'
import { ResponseModule } from './response/response.module'
import { ResumeModule } from './resume/resume.module'
import { UserModule } from './user/user.module'
import { VacancyModule } from './vacancy/vacancy.module'
import { FilesModule } from './files/files.module'
import { CloudinaryModule } from './cloudinary/cloudinary.module'
import { CompanyModule } from './company/company.module'
import { ChatModule } from './chat/chat.module'
@Module({
imports: [
UserModule,
AuthModule,
CompanyModule,
VacancyModule,
CategoryModule,
CityModule,
ResumeModule,
ResponseModule,
EmailModule,
FilesModule,
CloudinaryModule,
ChatModule,
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('DB_HOST'),
port: +configService.get('DB_PORT'),
username: configService.get('DB_USERNAME'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_NAME'),
entities: ['dist/**/*.entity{.ts,.js}'],
migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
cli: {
migrationsDir: __dirname + '/migrations/',
},
autoLoadEntities: true,
synchronize: true,
migrationsRun: process.env.NODE_ENV === 'production',
}),
inject: [ConfigService],
}),
],
})
export class AppModule {} |
import './App.css';
import Navbar from './Components/Navbar/Navbar';
import { BrowserRouter,Routes,Route } from 'react-router-dom';
import { Shop } from './Pages/Shop';
import { ShopCategory } from './Pages/ShopCategory';
import { Product } from './Pages/Product';
import { Cart } from './Pages/Cart';
import { LoginSignup } from './Pages/LoginSignup';
import Footer from './Components/Footer/Footer';
import men_banner from './Components/Assets/banner_mens.png'
import women_banner from './Components/Assets/banner_women.png'
import kids_banner from './Components/Assets/banner_kids.png'
function App() {
return (
<div>
<BrowserRouter>
<Navbar/>
<Routes>
<Route path='/' element={<Shop/>}/>
<Route path='/mens' element={<ShopCategory banner={men_banner} category="men"/>}/>
<Route path='/womens' element={<ShopCategory banner={women_banner} category="women"/>}/>
<Route path='/kids' element={<ShopCategory banner={kids_banner} category="kid"/>}/>
<Route path='/product' element={<Product/>}>
<Route path=':productId' element={<Product/>}/>
</Route>
<Route path='/cart' element={<Cart/>}/>
<Route path='/login' element={<LoginSignup/>}/>
</Routes>
<Footer/>
</BrowserRouter>
</div>
);
}
export default App; |
### 🔥 Hé toi, jeune Padawan, commence par publier ta première instance AWS avec Terraform
Mini Cours ^^
# 🌐 Introduction à Terraform
## ❓ Qu'est-ce que Terraform ?
- 🛠 Un outil d'**Infrastructure as Code (IaC)** développé par HashiCorp.
- ✨ Permet de définir et de provisionner l'infrastructure cloud à l'aide de code.
## 🚀 Pourquoi utiliser Terraform ?
- 🔄 Gestion automatisée et reproductible des infrastructures.
- ☁️ Prise en charge de multiples fournisseurs de cloud, dont AWS, Azure, Google Cloud, etc.
## 📚 Concepts de base de Terraform
- **Providers**: Les plugins qui permettent l'interaction avec les API des fournisseurs de cloud.
- **Resources**: Les éléments d'infrastructure à créer (par exemple, instances, réseaux, etc.).
- **State**: Le fichier qui enregistre l'état actuel de l'infrastructure.
## 📦 Installation de Terraform
- Guide étape par étape pour installer Terraform sur différentes plateformes (Windows, MacOS, Linux).
## 🏗 Exemple Pratique : Déployer une Instance AWS
### 🛠 Configuration initiale
- Installation de l'AWS CLI et configuration des credentials AWS.
- Création d'un répertoire pour votre projet Terraform.
### 📝 Écriture du code Terraform
- Création d'un fichier principal, généralement nommé `main.tf`.
- Configuration du provider AWS :
```hcl
provider "aws" {
region = "us-west-2"
}
Définir une instance EC2
Ajout de la ressource d'instance EC2 dans main.tf :
```
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
```
### 🚀 Initialisation et déploiement
Exécution de ```terraform init ``` pour initialiser le répertoire.
Exécution de ```terraform plan ``` pour voir un aperçu des changements.
Exécution de ```terraform apply ``` pour créer l'infrastructure.
### 🧹 Nettoyage
Utilisation de ```terraform destroy ```pour supprimer l'infrastructure lorsque vous avez terminé. |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.genDefaultLookupConfig = exports.LookupSelectVaultModeOnCreateEnum = exports.LookupSelectionModeEnum = void 0;
/**
* Enum definition of possible lookup selection behavior values
*/
var LookupSelectionModeEnum;
(function (LookupSelectionModeEnum) {
LookupSelectionModeEnum["extract"] = "extract";
LookupSelectionModeEnum["link"] = "link";
LookupSelectionModeEnum["none"] = "none";
})(LookupSelectionModeEnum = exports.LookupSelectionModeEnum || (exports.LookupSelectionModeEnum = {}));
var LookupSelectVaultModeOnCreateEnum;
(function (LookupSelectVaultModeOnCreateEnum) {
LookupSelectVaultModeOnCreateEnum["smart"] = "smart";
LookupSelectVaultModeOnCreateEnum["alwaysPrompt"] = "alwaysPrompt";
})(LookupSelectVaultModeOnCreateEnum = exports.LookupSelectVaultModeOnCreateEnum || (exports.LookupSelectVaultModeOnCreateEnum = {}));
/**
* Generates default {@link LookupConfig}
* @returns LookupConfig
*/
function genDefaultLookupConfig() {
return {
note: {
selectionMode: LookupSelectionModeEnum.extract,
confirmVaultOnCreate: true,
vaultSelectionModeOnCreate: LookupSelectVaultModeOnCreateEnum.smart,
leaveTrace: false,
bubbleUpCreateNew: true,
/**
* Experimentally set.
*
* At the time of testing:
*
* At previous threshold of 0.5 string 'dendron' matched
* 'scratch.2021.06.15.104331.make-sure-seeds-are-initialized-on-startup' with score 0.42.
* Which is too fuzzy of a match.
*
* 'rename' fuzzy matches 'dendron.scratch.2020.11.07.publish-under-original-filenames' with 0.16.
*
* For reference
* 'dendron rename' matches 'dendron.dev.design.commands.rename' with 0.001.
*
* Having this score too high gets too unrelated matches which pushes the
* 'Create New' entry out of the view.
* --------------------------------------------------------------------------------
*
* Note if you are going to be tweaking this value it is highly suggested to add a
* temporary piece of code To be able to see the all the results that are matched by
* fuse engine along with their scores, inside {@link FuseEngine.queryNote}
* */
fuzzThreshold: 0.2,
},
};
}
exports.genDefaultLookupConfig = genDefaultLookupConfig;
//# sourceMappingURL=lookup.js.map |
import {DspAPIRequest} from 'api/dsp.api';
import {useCancelRequest} from 'hooks';
import {useMutation, useQueryClient} from 'react-query';
import {GET_DSPS} from './constants';
/**
* Update a Dsp
*/
export function useEditDsp() {
const {cancelToken} = useCancelRequest();
const client = useQueryClient();
return useMutation(
({dspId, data}) =>
DspAPIRequest.editDsp({
id: dspId,
data,
options: {cancelToken}
}),
{
onError: (err, variables, rollback) => {
return typeof rollback === 'function' ? rollback() : null;
},
onSettled: () => {
client.invalidateQueries([GET_DSPS]);
}
}
);
} |
/*
* GUIClasses.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
#include "../lib/GameConstants.h"
#include "../lib/ResourceSet.h"
#include "../lib/CConfigHandler.h"
#include "../widgets/CArtifactHolder.h"
#include "../widgets/CGarrisonInt.h"
#include "../widgets/Images.h"
#include "../windows/CWindowObject.h"
class CGDwelling;
class CreatureCostBox;
class IMarket;
class CCreaturePic;
class MoraleLuckBox;
class CHeroArea;
class CMinorResDataBar;
class CSlider;
class CComponentBox;
class CTextInput;
class CListBox;
class CLabelGroup;
class CToggleButton;
class CToggleGroup;
class CVolumeSlider;
class CGStatusBar;
class CTextBox;
class CResDataBar;
class CHeroWithMaybePickedArtifact;
/// Recruitment window where you can recruit creatures
class CRecruitmentWindow : public CWindowObject
{
class CCreatureCard : public CIntObject, public std::enable_shared_from_this<CCreatureCard>
{
CRecruitmentWindow * parent;
std::shared_ptr<CCreaturePic> animation;
bool selected;
public:
const CCreature * creature;
si32 amount;
void select(bool on);
CCreatureCard(CRecruitmentWindow * window, const CCreature * crea, int totalAmount);
void clickLeft(tribool down, bool previousState) override;
void clickRight(tribool down, bool previousState) override;
void showAll(SDL_Surface * to) override;
};
std::function<void(CreatureID,int)> onRecruit; //void (int ID, int amount) <-- call to recruit creatures
int level;
const CArmedInstance * dst;
std::shared_ptr<CGStatusBar> statusBar;
std::shared_ptr<CCreatureCard> selected;
std::vector<std::shared_ptr<CCreatureCard>> cards;
std::shared_ptr<CSlider> slider;
std::shared_ptr<CButton> maxButton;
std::shared_ptr<CButton> buyButton;
std::shared_ptr<CButton> cancelButton;
std::shared_ptr<CLabel> title;
std::shared_ptr<CLabel> availableValue;
std::shared_ptr<CLabel> toRecruitValue;
std::shared_ptr<CLabel> availableTitle;
std::shared_ptr<CLabel> toRecruitTitle;
std::shared_ptr<CreatureCostBox> costPerTroopValue;
std::shared_ptr<CreatureCostBox> totalCostValue;
void select(std::shared_ptr<CCreatureCard> card);
void buy();
void sliderMoved(int to);
void showAll(SDL_Surface * to) override;
public:
const CGDwelling * const dwelling;
CRecruitmentWindow(const CGDwelling * Dwelling, int Level, const CArmedInstance * Dst, const std::function<void(CreatureID,int)> & Recruit, int y_offset = 0);
void availableCreaturesChanged();
};
/// Split window where creatures can be split up into two single unit stacks
class CSplitWindow : public CWindowObject
{
std::function<void(int, int)> callback;
int leftAmount;
int rightAmount;
int leftMin;
int rightMin;
std::shared_ptr<CLabel> title;
std::shared_ptr<CSlider> slider;
std::shared_ptr<CCreaturePic> animLeft;
std::shared_ptr<CCreaturePic> animRight;
std::shared_ptr<CButton> ok;
std::shared_ptr<CButton> cancel;
std::shared_ptr<CTextInput> leftInput;
std::shared_ptr<CTextInput> rightInput;
void setAmountText(std::string text, bool left);
void setAmount(int value, bool left);
void sliderMoved(int value);
void apply();
public:
/**
* creature - displayed creature
* callback(leftAmount, rightAmount) - function to call on close
* leftMin, rightMin - minimal amount of creatures in each stack
* leftAmount, rightAmount - amount of creatures in each stack
*/
CSplitWindow(const CCreature * creature, std::function<void(int, int)> callback, int leftMin, int rightMin, int leftAmount, int rightAmount);
};
/// Raised up level window where you can select one out of two skills
class CLevelWindow : public CWindowObject
{
std::shared_ptr<CAnimImage> portrait;
std::shared_ptr<CButton> ok;
std::shared_ptr<CLabel> mainTitle;
std::shared_ptr<CLabel> levelTitle;
std::shared_ptr<CAnimImage> skillIcon;
std::shared_ptr<CLabel> skillValue;
std::shared_ptr<CComponentBox> box; //skills to select
std::function<void(ui32)> cb;
void selectionChanged(unsigned to);
public:
CLevelWindow(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, std::function<void(ui32)> callback);
~CLevelWindow();
};
/// Town portal, castle gate window
class CObjectListWindow : public CWindowObject
{
class CItem : public CIntObject
{
CObjectListWindow * parent;
std::shared_ptr<CLabel> text;
std::shared_ptr<CPicture> border;
public:
const size_t index;
CItem(CObjectListWindow * parent, size_t id, std::string text);
void select(bool on);
void clickLeft(tribool down, bool previousState) override;
};
std::function<void(int)> onSelect;//called when OK button is pressed, returns id of selected item.
std::shared_ptr<CIntObject> titleWidget;
std::shared_ptr<CLabel> title;
std::shared_ptr<CLabel> descr;
std::shared_ptr<CListBox> list;
std::shared_ptr<CButton> ok;
std::shared_ptr<CButton> exit;
std::vector< std::pair<int, std::string> > items;//all items present in list
void init(std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr);
void exitPressed();
public:
size_t selected;//index of currently selected item
std::function<void()> onExit;//optional exit callback
/// Callback will be called when OK button is pressed, returns id of selected item. initState = initially selected item
/// Image can be nullptr
///item names will be taken from map objects
CObjectListWindow(const std::vector<int> &_items, std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr, std::function<void(int)> Callback);
CObjectListWindow(const std::vector<std::string> &_items, std::shared_ptr<CIntObject> titleWidget_, std::string _title, std::string _descr, std::function<void(int)> Callback);
std::shared_ptr<CIntObject> genItem(size_t index);
void elementSelected();//call callback and close this window
void changeSelection(size_t which);
void keyPressed (const SDL_KeyboardEvent & key) override;
};
class CSystemOptionsWindow : public CWindowObject
{
private:
std::shared_ptr<CLabel> title;
std::shared_ptr<CLabelGroup> leftGroup;
std::shared_ptr<CLabelGroup> rightGroup;
std::shared_ptr<CButton> load;
std::shared_ptr<CButton> save;
std::shared_ptr<CButton> restart;
std::shared_ptr<CButton> mainMenu;
std::shared_ptr<CButton> quitGame;
std::shared_ptr<CButton> backToMap; //load and restart are not used yet
std::shared_ptr<CToggleGroup> heroMoveSpeed;
std::shared_ptr<CToggleGroup> enemyMoveSpeed;
std::shared_ptr<CToggleGroup> mapScrollSpeed;
std::shared_ptr<CVolumeSlider> musicVolume;
std::shared_ptr<CVolumeSlider> effectsVolume;
std::shared_ptr<CToggleButton> showReminder;
std::shared_ptr<CToggleButton> quickCombat;
std::shared_ptr<CToggleButton> spellbookAnim;
std::shared_ptr<CToggleButton> fullscreen;
std::shared_ptr<CButton> gameResButton;
std::shared_ptr<CLabel> gameResLabel;
SettingsListener onFullscreenChanged;
//functions bound to buttons
void bloadf(); //load game
void bsavef(); //save game
void bquitf(); //quit game
void breturnf(); //return to game
void brestartf(); //restart game
void bmainmenuf(); //return to main menu
void selectGameRes();
void setGameRes(int index);
void closeAndPushEvent(int eventType, int code = 0);
public:
CSystemOptionsWindow();
};
class CTavernWindow : public CWindowObject
{
public:
class HeroPortrait : public CIntObject
{
public:
std::string hoverName;
std::string description; // "XXX is a level Y ZZZ with N artifacts"
const CGHeroInstance * h;
void clickLeft(tribool down, bool previousState) override;
void clickRight(tribool down, bool previousState) override;
void hover (bool on) override;
HeroPortrait(int & sel, int id, int x, int y, const CGHeroInstance * H);
private:
int *_sel;
const int _id;
std::shared_ptr<CAnimImage> portrait;
};
//recruitable heroes
std::shared_ptr<HeroPortrait> h1;
std::shared_ptr<HeroPortrait> h2; //recruitable heroes
int selected;//0 (left) or 1 (right)
int oldSelected;//0 (left) or 1 (right)
std::shared_ptr<CButton> thiefGuild;
std::shared_ptr<CButton> cancel;
std::shared_ptr<CButton> recruit;
const CGObjectInstance * tavernObj;
std::shared_ptr<CLabel> title;
std::shared_ptr<CLabel> cost;
std::shared_ptr<CTextBox> rumor;
std::shared_ptr<CGStatusBar> statusBar;
CTavernWindow(const CGObjectInstance * TavernObj);
~CTavernWindow();
void recruitb();
void thievesguildb();
void show(SDL_Surface * to) override;
};
class CExchangeWindow : public CWindowObject, public CGarrisonHolder, public CWindowWithArtifacts
{
std::array<std::shared_ptr<CHeroWithMaybePickedArtifact>, 2> herosWArt;
std::array<std::shared_ptr<CLabel>, 2> titles;
std::vector<std::shared_ptr<CAnimImage>> primSkillImages;//shared for both heroes
std::array<std::vector<std::shared_ptr<CLabel>>, 2> primSkillValues;
std::array<std::vector<std::shared_ptr<CAnimImage>>, 2> secSkillIcons;
std::array<std::shared_ptr<CAnimImage>, 2> specImages;
std::array<std::shared_ptr<CAnimImage>, 2> expImages;
std::array<std::shared_ptr<CLabel>, 2> expValues;
std::array<std::shared_ptr<CAnimImage>, 2> manaImages;
std::array<std::shared_ptr<CLabel>, 2> manaValues;
std::array<std::shared_ptr<CAnimImage>, 2> portraits;
std::vector<std::shared_ptr<LRClickableAreaWTextComp>> primSkillAreas;
std::array<std::vector<std::shared_ptr<LRClickableAreaWTextComp>>, 2> secSkillAreas;
std::array<std::shared_ptr<CHeroArea>, 2> heroAreas;
std::array<std::shared_ptr<LRClickableAreaWText>, 2> specialtyAreas;
std::array<std::shared_ptr<LRClickableAreaWText>, 2> experienceAreas;
std::array<std::shared_ptr<LRClickableAreaWText>, 2> spellPointsAreas;
std::array<std::shared_ptr<MoraleLuckBox>, 2> morale;
std::array<std::shared_ptr<MoraleLuckBox>, 2> luck;
std::shared_ptr<CButton> quit;
std::array<std::shared_ptr<CButton>, 2> questlogButton;
std::shared_ptr<CGStatusBar> statusBar;
std::shared_ptr<CGarrisonInt> garr;
public:
std::array<const CGHeroInstance *, 2> heroInst;
std::array<std::shared_ptr<CArtifactsOfHero>, 2> artifs;
void updateGarrisons() override;
void questlog(int whichHero); //questlog button callback; whichHero: 0 - left, 1 - right
void updateWidgets();
CExchangeWindow(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID queryID);
~CExchangeWindow();
};
/// Here you can buy ships
class CShipyardWindow : public CWindowObject
{
std::shared_ptr<CPicture> bgWater;
std::shared_ptr<CAnimImage> bgShip;
std::shared_ptr<CLabel> title;
std::shared_ptr<CLabel> costLabel;
std::shared_ptr<CAnimImage> woodPic;
std::shared_ptr<CAnimImage> goldPic;
std::shared_ptr<CLabel> woodCost;
std::shared_ptr<CLabel> goldCost;
std::shared_ptr<CButton> build;
std::shared_ptr<CButton> quit;
std::shared_ptr<CGStatusBar> statusBar;
public:
CShipyardWindow(const std::vector<si32> & cost, int state, int boatType, const std::function<void()> & onBuy);
};
/// Puzzle screen which gets uncovered when you visit obilisks
class CPuzzleWindow : public CWindowObject
{
private:
int3 grailPos;
std::shared_ptr<CPicture> logo;
std::shared_ptr<CLabel> title;
std::shared_ptr<CButton> quitb;
std::shared_ptr<CResDataBar> resDataBar;
std::vector<std::shared_ptr<CPicture>> piecesToRemove;
std::vector<std::shared_ptr<CPicture>> visiblePieces;
ui8 currentAlpha;
public:
void showAll(SDL_Surface * to) override;
void show(SDL_Surface * to) override;
CPuzzleWindow(const int3 & grailPos, double discoveredRatio);
};
/// Creature transformer window
class CTransformerWindow : public CWindowObject, public CGarrisonHolder
{
class CItem : public CIntObject
{
public:
int id;//position of creature in hero army
bool left;//position of the item
int size; //size of creature stack
CTransformerWindow * parent;
std::shared_ptr<CAnimImage> icon;
std::shared_ptr<CLabel> count;
void move();
void clickLeft(tribool down, bool previousState) override;
void update();
CItem(CTransformerWindow * parent, int size, int id);
};
const CArmedInstance * army;//object with army for transforming (hero or town)
const CGHeroInstance * hero;//only if we have hero in town
const CGTownInstance * town;//market, town garrison is used if hero == nullptr
std::shared_ptr<CLabel> titleLeft;
std::shared_ptr<CLabel> titleRight;
std::shared_ptr<CTextBox> helpLeft;
std::shared_ptr<CTextBox> helpRight;
std::vector<std::shared_ptr<CItem>> items;
std::shared_ptr<CButton> all;
std::shared_ptr<CButton> convert;
std::shared_ptr<CButton> cancel;
std::shared_ptr<CGStatusBar> statusBar;
public:
void makeDeal();
void addAll();
void updateGarrisons() override;
CTransformerWindow(const CGHeroInstance * _hero, const CGTownInstance * _town);
};
class CUniversityWindow : public CWindowObject
{
class CItem : public CIntObject
{
std::shared_ptr<CAnimImage> icon;
std::shared_ptr<CAnimImage> topBar;
std::shared_ptr<CAnimImage> bottomBar;
std::shared_ptr<CLabel> name;
std::shared_ptr<CLabel> level;
public:
int ID;//id of selected skill
CUniversityWindow * parent;
void showAll(SDL_Surface * to) override;
void clickLeft(tribool down, bool previousState) override;
void clickRight(tribool down, bool previousState) override;
void hover(bool on) override;
int state();//0=can't learn, 1=learned, 2=can learn
CItem(CUniversityWindow * _parent, int _ID, int X, int Y);
};
const CGHeroInstance * hero;
const IMarket * market;
std::shared_ptr<CAnimation> bars;
std::vector<std::shared_ptr<CItem>> items;
std::shared_ptr<CButton> cancel;
std::shared_ptr<CGStatusBar> statusBar;
std::shared_ptr<CIntObject> titlePic;
std::shared_ptr<CLabel> title;
std::shared_ptr<CTextBox> clerkSpeech;
public:
CUniversityWindow(const CGHeroInstance * _hero, const IMarket * _market);
void makeDeal(int skill);
};
/// Confirmation window for University
class CUnivConfirmWindow : public CWindowObject
{
std::shared_ptr<CTextBox> clerkSpeech;
std::shared_ptr<CLabel> name;
std::shared_ptr<CLabel> level;
std::shared_ptr<CAnimImage> icon;
CUniversityWindow * owner;
std::shared_ptr<CGStatusBar> statusBar;
std::shared_ptr<CButton> confirm;
std::shared_ptr<CButton> cancel;
std::shared_ptr<CAnimImage> costIcon;
std::shared_ptr<CLabel> cost;
void makeDeal(int skill);
public:
CUnivConfirmWindow(CUniversityWindow * PARENT, int SKILL, bool available);
};
/// Garrison window where you can take creatures out of the hero to place it on the garrison
class CGarrisonWindow : public CWindowObject, public CGarrisonHolder
{
std::shared_ptr<CLabel> title;
std::shared_ptr<CAnimImage> banner;
std::shared_ptr<CAnimImage> portrait;
std::shared_ptr<CGarrisonInt> garr;
public:
std::shared_ptr<CButton> quit;
CGarrisonWindow(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits);
void updateGarrisons() override;
};
/// Hill fort is the building where you can upgrade units
class CHillFortWindow : public CWindowObject, public CGarrisonHolder
{
private:
static const int slotsCount = 7;
//todo: mithril support
static const int resCount = 7;
const CGObjectInstance * fort;
const CGHeroInstance * hero;
std::shared_ptr<CLabel> title;
std::shared_ptr<CHeroArea> heroPic;
std::array<std::shared_ptr<CAnimImage>, resCount> totalIcons;
std::array<std::shared_ptr<CLabel>, resCount> totalLabels;
std::array<std::shared_ptr<CButton>, slotsCount> upgrade;//upgrade single creature
std::array<int, slotsCount + 1> currState;//current state of slot - to avoid calls to getState or updating buttons
//there is a place for only 2 resources per slot
std::array< std::array<std::shared_ptr<CAnimImage>, 2>, slotsCount> slotIcons;
std::array< std::array<std::shared_ptr<CLabel>, 2>, slotsCount> slotLabels;
std::shared_ptr<CButton> upgradeAll;
std::shared_ptr<CButton> quit;
std::shared_ptr<CGarrisonInt> garr;
std::shared_ptr<CGStatusBar> statusBar;
std::string getDefForSlot(SlotID slot);
std::string getTextForSlot(SlotID slot);
void makeDeal(SlotID slot);//-1 for upgrading all creatures
int getState(SlotID slot); //-1 = no creature 0=can't upgrade, 1=upgraded, 2=can upgrade
public:
CHillFortWindow(const CGHeroInstance * visitor, const CGObjectInstance * object);
void updateGarrisons() override;//update buttons after garrison changes
};
class CThievesGuildWindow : public CWindowObject
{
const CGObjectInstance * owner;
std::shared_ptr<CGStatusBar> statusBar;
std::shared_ptr<CButton> exitb;
std::shared_ptr<CMinorResDataBar> resdatabar;
std::vector<std::shared_ptr<CLabel>> rowHeaders;
std::vector<std::shared_ptr<CAnimImage>> columnBackgrounds;
std::vector<std::shared_ptr<CLabel>> columnHeaders;
std::vector<std::shared_ptr<CAnimImage>> cells;
std::vector<std::shared_ptr<CPicture>> banners;
std::vector<std::shared_ptr<CAnimImage>> bestHeroes;
std::vector<std::shared_ptr<CTextBox>> primSkillHeaders;
std::vector<std::shared_ptr<CLabel>> primSkillValues;
std::vector<std::shared_ptr<CAnimImage>> bestCreatures;
std::vector<std::shared_ptr<CLabel>> personalities;
public:
CThievesGuildWindow(const CGObjectInstance * _owner);
}; |
"""
First three functions adapted from https://github.com/zongyi-li/fourier_neural_operator/blob/master/utilities3.py
and https://github.com/nickhnelsen/FourierNeuralMappings
"""
import torch
import operator
from functools import reduce
import numpy as np
import scipy.io
# import hdf5storage
import pdb
import yaml
import gc
#################################################
#
# utilities
#
#################################################
def to_torch(x, to_float=True):
"""
send input numpy array to single precision torch tensor
"""
if to_float:
if np.iscomplexobj(x):
x = x.astype(np.complex64)
else:
x = x.astype(np.float32)
return torch.from_numpy(x)
def validate(f, fhat):
'''
Helper function to compute relative L^2 error of approximations.
Takes care of different array shape interpretations in numpy.
INPUTS:
f : array of high-fidelity function values
fhat : array of approximation values
OUTPUTS:
error : float, relative error
'''
f, fhat = np.asarray(f).flatten(), np.asarray(fhat).flatten()
return np.linalg.norm(f-fhat) / np.linalg.norm(f)
def dataset_with_indices(cls):
"""
Modifies the given Dataset class to return a tuple data, target, index
instead of just data, target.
# Reference: https://discuss.pytorch.org/t/how-to-retrieve-the-sample-indices-of-a-mini-batch/7948/19
"""
def __getitem__(self, index):
data, target = cls.__getitem__(self, index)
return data, target, index
return type(cls.__name__, (cls,), {'__getitem__': __getitem__,})
def dataset_with_indices(cls):
"""
Modifies the given Dataset class to return a tuple data, target, index
instead of just data, target.
# Reference: https://discuss.pytorch.org/t/how-to-retrieve-the-sample-indices-of-a-mini-batch/7948/19
"""
def __getitem__(self, index):
data, target = cls.__getitem__(self, index)
return data, target, index
return type(cls.__name__, (cls,), {'__getitem__': __getitem__,})
class H1Loss(object):
"""
loss function with rel/abs H1 loss
"""
def __init__(self, d=2, size_average=True, reduction=True, eps=1e-6):
# super(LpLoss, self).__init__()
self.d = d
self.p = 2
self.reduction = reduction
self.size_average = size_average
self.eps =eps
def rel_H1(self, x, y):
num_examples = x.size()[0]
grid_edge = x.size()[-1]
x = torch.squeeze(x)
y = torch.squeeze(y)
h = 1.0 / (grid_edge - 1.0)
x_grad = torch.gradient(x,dim = (-2,-1), spacing = h)
x_grad1 = x_grad[0].unsqueeze(1) # Component 1 of the gradient
x_grad2 = x_grad[1].unsqueeze(1) # Component 2 of the gradient
x_grad = torch.cat((x_grad1, x_grad2), 1) # num_examples, (grad component) 2, (\chi_1, \chi_2) 2, grid_edge, grid_edge
y_grad = torch.gradient(y, dim = (-2,-1), spacing = h)
y_grad1 = y_grad[0].unsqueeze(1) # Component 1 of the gradient
y_grad2 = y_grad[1].unsqueeze(1) # Component 2 of the gradient
y_grad = torch.cat((y_grad1, y_grad2), 1)
diff_norms = torch.norm(x.reshape(num_examples,-1) - y.reshape(num_examples,-1), self.p, 1)
diff_grad_norms = torch.norm(x_grad.reshape(num_examples, -1) - y_grad.reshape(num_examples, -1), self.p, 1)
diff_norms = (diff_norms**2 + diff_grad_norms**2)**(1/2)
y_norms = ((torch.norm(y.reshape(num_examples,-1), self.p, 1))**2 + (torch.norm(y_grad.reshape(num_examples,-1), self.p, 1))**2)**(1/2)
y_norms += self.eps # prevent divide by zero
rel_norms = torch.div(diff_norms,y_norms)
if self.reduction:
if self.size_average:
return torch.mean(rel_norms)
else:
return torch.median(rel_norms)
return rel_norms
def squared_H1(self, x, y):
num_examples = x.size()[0]
grid_edge = x.size()[-1]
x = torch.squeeze(x) # shape is num_examples x channels_out x grid_edge x grid_edge
y = torch.squeeze(y) # shape is num_examples x channels_out x grid_edge x grid_edge
h = 1.0 / (grid_edge - 1.0)
x_grad = torch.gradient(x, dim = (-2,-1), spacing = h)
x_grad1 = x_grad[0].unsqueeze(1) # Component 1 of the gradient
x_grad2 = x_grad[1].unsqueeze(1) # Component 2 of the gradient
x_grad = torch.cat((x_grad1, x_grad2), 1) # num_examples, (grad component) 2, (\chi_1, \chi_2) 2, grid_edge, grid_edge
y_grad = torch.gradient(y, dim = (-2,-1), spacing = h)
y_grad1 = y_grad[0].unsqueeze(1) # Component 1 of the gradient
y_grad2 = y_grad[1].unsqueeze(1) # Component 2 of the gradient
y_grad = torch.cat((y_grad1, y_grad2), 1) # num_examples, 2, grid_edge, grid_edge
diff_L2 = h*torch.norm(x.reshape(num_examples,-1) - y.reshape(num_examples,-1), 2, dim = 1)
grad_euclidean = torch.norm(x_grad - y_grad, 2, dim = 1)
diff_grad_L2 = h*torch.norm(grad_euclidean.reshape(num_examples,-1),2,1)
sum_sq = diff_L2**2 + diff_grad_L2**2
if self.reduction:
if self.size_average:
return torch.mean(sum_sq)
else:
return torch.sum(sum_sq)
return sum_sq
class LpLoss(object):
"""
loss function with rel/abs Lp norm loss
"""
def __init__(self, d=2, p=2, size_average=True, reduction=True, eps=1e-6):
super(LpLoss, self).__init__()
if not (d > 0 and p > 0):
raise ValueError("Dimension d and Lp-norm type p must be postive.")
self.d = d
self.p = p
self.reduction = reduction
self.size_average = size_average
self.eps =eps
def abs(self, x, y):
num_examples = x.size()[0]
#Assume uniform mesh
h = 1.0 / (x.size()[-1] - 1.0)
all_norms = (h**(self.d/self.p))*torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), self.p, 1)
pdb.set_trace()
if self.reduction:
if self.size_average:
return torch.mean(all_norms)
else:
return torch.sum(all_norms)
return all_norms
def rel(self, x, y):
num_examples = x.size()[0]
diff_norms = torch.norm(x.reshape(num_examples,-1) - y.reshape(num_examples,-1), self.p, 1)
y_norms = torch.norm(y.reshape(num_examples,-1), self.p, 1)
y_norms += self.eps # prevent divide by zero
mean_y_norm = torch.mean(y_norms)
if self.reduction:
if self.size_average:
return torch.mean(diff_norms/mean_y_norm)
else:
return torch.sum(diff_norms/mean_y_norm)
return diff_norms/mean_y_norm
def __call__(self, x, y):
return self.squared_H1(x, y)
class Sobolev_Loss(object):
'''
Loss object to compute H_1 loss or W_{1,p} loss, relative or absolute
Assumes input shape is (num_examples, channels_out, grid_edge, grid_edge)
Returns array of shape (num_examples,)
'''
def __init__(self, d=2, p=2, eps = 1e-6):
self.d = d
self.p = p
self.eps =eps
def compute_grad(self,x):
grid_edge = x.size()[-1]
h = 1.0 / (grid_edge - 1.0)
x_grad = torch.gradient(x, dim = (-2,-1), spacing = h)
x_grad1 = x_grad[0].unsqueeze(1) # Component 1 of the gradient
x_grad2 = x_grad[1].unsqueeze(1) # Component 2 of the gradient
x_grad = torch.cat((x_grad1, x_grad2), 1)
return x_grad
def Lp_norm(self,x):
num_examples = x.size()[0]
h = 1.0 / (x.size()[-1] - 1.0)
return torch.norm(x.reshape(num_examples,-1), self.p, dim=1)*h**(self.d/self.p)
def Lp_err(self,x,y):
return self.Lp_norm(x-y)
def Lp_rel_err(self,x,y):
return self.Lp_err(x,y)/(self.Lp_norm(y) + self.eps)
def W1p_norm(self,x):
x_grad = self.compute_grad(x)
return (self.Lp_norm(x)**self.p + self.Lp_norm(x_grad)**self.p)**(1/self.p)
def W1p_err(self,x,y):
return self.W1p_norm(x-y)
def W1p_rel_err(self,x,y):
return self.W1p_err(x,y)/(self.W1p_norm(y)+self.eps)
def count_params(model):
"""
print the number of parameters
"""
c = 0
for p in list(model.parameters()):
c += reduce(operator.mul,
list(p.size()+(2,) if p.is_complex() else p.size()))
return c
def convert_A_to_matrix_shape(A):
'''
input shape is (num_examples,3,grid_edge,grid_edge)
output shape is (num_examples,2,2,grid_edge,grid_edge)
'''
# Add off-diagonal entry back to A
num_examples = A.size()[0]
grid_edge = A.size()[-1]
off_diag = A[:,1,:,:].unsqueeze(1)
A = torch.cat((A[:,:2,:,:],off_diag,A[:,2:,:,:]),1)
A = torch.reshape(A,(num_examples,2,2,grid_edge,grid_edge))
return A
def compute_Abar(A, chi):
'''
Computes Abar from A and chi
Abar = \int_{\Td} (A + A\grad\chi^T) dx
chi has shape (num_examples, 2, grid_edge, grid_edge)
A has shape (num_examples, 2,2, grid_edge, grid_edge)
Returns Abar of shape (num_examples, 2,2)
'''
num_examples = chi.size()[0]
grid_edge = chi.size()[-1]
h = 1.0 / (grid_edge - 1.0)
# Compute grad chi
chi_grad = torch.gradient(chi, dim = (-2,-1), spacing = h)
chi_grad1 = chi_grad[0].unsqueeze(1) # Component 1 of the gradient
chi_grad2 = chi_grad[1].unsqueeze(1) # Component 2 of the gradient
chi_grad = torch.cat((chi_grad1, chi_grad2), 1)
# Compute integrand
# Multiply A (axes 1 and 2) by chi_grad (axis 1)
integrand = A + torch.einsum('iablm,ibdlm->iadlm',A,chi_grad)
Abars = torch.sum(integrand, dim = (-2,-1))*h**2
return Abars
def format_data(A_input, chi1_true, chi2_true, gridsize):
# Reshape data
sgc = gridsize
(N_data, N_nodes,dummy1, dummy2) = np.shape(A_input)
data_output1 = np.transpose(chi1_true[:,:]) # N_data, N_nodes
data_output2 = np.transpose(chi2_true[:,:]) # N_data, N_nodes
data_input = np.reshape(A_input, (N_data,sgc, sgc,4))
data_input = np.delete(data_input,2,axis = 3) # Symmetry of A: don't need both components
# Input shape (of x): (batch, channels_in, nx_in, ny_in)
data_input = np.transpose(data_input, (0,3,1,2))
#Output shape: (batch, channels_out, nx_out, ny_out)
data_output1 = np.reshape(data_output1, (N_data,sgc, sgc))
data_output2 = np.reshape(data_output2, (N_data,sgc, sgc))
# concatenate
data_output = np.stack((data_output1,data_output2),axis = 3)
data_output = np.transpose(data_output, (0,3,1,2))
return data_input, data_output
def eval_net(net,d_out,gridsize,test_loader,b_size,USE_CUDA = False,N_data = 500):
if USE_CUDA:
gc.collect()
torch.cuda.empty_cache()
net.cuda()
y_test_approx_all = torch.zeros(N_data,d_out,gridsize,gridsize)
b = 0
with torch.no_grad():
for x,y in test_loader:
if USE_CUDA:
x = x.cuda()
y = y.cuda()
y_pred = net(x)
y_test_approx_all[b*b_size:(b+1)*b_size,:,:,:] = torch.squeeze(y_pred).cpu()
b += 1
return y_test_approx_all
def frob_arithmetic_mean_A(A):
'''
A has shape (num_examples, 2,2, grid_edge, grid_edge)
'''
h = 1.0 / (A.size()[-1] - 1.0)
mean_A = torch.sum(A,dim = (-2,-1))*h**2
return torch.norm(mean_A, 'fro', dim = (1,2))
def frob_harm_mean_A(A):
'''
A has shape (num_examples, 2,2, grid_edge, grid_edge)
'''
h = 1.0 / (A.size()[-1] - 1.0)
A = torch.reshape(A,(A.size()[0],2,2,-1))
inverses = np.array([np.array([np.linalg.inv(A[i,:,:,j]) for i in range(A.size()[0])]) for j in range(A.size()[3])])
inverses = torch.from_numpy(inverses).float()
harm_mean_A = torch.sum(inverses,dim = (0))*h**2
inv_har_mean_A = np.array([np.linalg.inv(harm_mean_A[i,:,:]) for i in range(harm_mean_A.size()[0])])
torch_inv_har_mean_A = torch.from_numpy(inv_har_mean_A).float()
return torch.norm(torch_inv_har_mean_A, 'fro', dim = (1,2))
def compute_Abar_error(A,chi_true,chi_hat):
'''
A has shape (num_examples, 2,2, grid_edge, grid_edge)
returns Abar_rel_error scaled by true frob norm
returns Abar_rel_error2 scaled by a_m - a_h
'''
Abars_true = compute_Abar(A,chi_true)
Abars_hat = compute_Abar(A,chi_hat)
Aharms = frob_harm_mean_A(A)
Ameans = frob_arithmetic_mean_A(A)
Abar_abs_error = torch.norm(Abars_true - Abars_hat, 'fro', dim = (1,2))
true_frob_norm = torch.norm(Abars_true, 'fro', dim = (1,2))
Abar_rel_error = Abar_abs_error/true_frob_norm
Abar_rel_error2 = Abar_abs_error/(Ameans - Aharms)
return Abar_rel_error, Abar_rel_error2
def loss_report(y_hat, y_true, A_true, model_path):
'''
A_true shape is (num_examples,3,grid_edge,grid_edge)
y_true shape is (num_examples,2,grid_edge,grid_edge)
'''
A = convert_A_to_matrix_shape(A_true)
H1_loss_func = Sobolev_Loss(p = 2)
W1_10_loss_func = Sobolev_Loss(p = 10)
H1_losses = H1_loss_func.W1p_err(y_hat,y_true)
H1_rel_losses = H1_loss_func.W1p_rel_err(y_hat,y_true)
W1_10_losses = W1_10_loss_func.W1p_err(y_hat,y_true)
W1_10_rel_losses = W1_10_loss_func.W1p_rel_err(y_hat,y_true)
H1_mean = torch.mean(H1_losses)
H1_med = torch.median(H1_losses)
H1_rel_mean = torch.mean(H1_rel_losses)
H1_rel_med = torch.median(H1_rel_losses)
W1_10_mean = torch.mean(W1_10_losses)
W1_10_med = torch.median(W1_10_losses)
W1_10_rel_mean = torch.mean(W1_10_rel_losses)
W1_10_rel_med = torch.median(W1_10_rel_losses)
Abar_rel_error, Abar_rel_error2 = compute_Abar_error(A,y_true,y_hat)
# Make dictionary of the errors
errors = {}
errors['H1_mean'] = H1_mean
errors['H1_med'] = H1_med
errors['H1_rel_mean'] = H1_rel_mean
errors['H1_rel_med'] = H1_rel_med
errors['W1_10_mean'] = W1_10_mean
errors['W1_10_med'] = W1_10_med
errors['W1_10_rel_mean'] = W1_10_rel_mean
errors['W1_10_rel_med'] = W1_10_rel_med
errors['Abar_rel_error_med'] = torch.median(Abar_rel_error)
errors['Abar_rel_error2_med'] = torch.median(Abar_rel_error2)
json_errors = {k: v.item() for k, v in errors.items()}
# Save dictionary to json file
with open(model_path+ '_errors.yml', 'w') as fp:
yaml.dump(json_errors, fp) |
'use client'
import { useState } from 'react'
import { Product } from '@/types/Product'
import {
Table,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { ProductsInMemory } from '../productsDb'
import { Button } from '@/components/ui/button'
import { DollarSign, Minus, Plus } from 'lucide-react'
import { formatCurrency } from '../utils/formatCurrency'
import { Dialog, DialogContent, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { ExchangeInNotes, calculateChange } from '../utils/calculateChange'
interface SelectedProductType {
product: Product
purchasedQuantity: number
}
export default function Sale() {
const [products] = useState<Product[]>(ProductsInMemory)
const [selectedProducts, setSelectedProducts] = useState<
SelectedProductType[]
>([])
const [amountPaid, setAmountPaid] = useState<number>(0)
const [moneyChange, setMoneyChange] = useState<ExchangeInNotes[]>([])
const [isPaymentModalOpened, setIsPaymentModalOpened] =
useState<boolean>(false)
const cartTotal = getTotalPrice()
function getTotalPrice() {
let total = 0
selectedProducts.forEach((data) => {
total += data.product.unitPrice * data.purchasedQuantity
})
return total
}
function handleAddProductToSelectedProducts(product: Product) {
const newSelectedProducts = [...selectedProducts]
const productAlreadySelected = newSelectedProducts.find(
(data) => data.product.name === product.name,
)
if (productAlreadySelected) {
productAlreadySelected.purchasedQuantity += 1
setSelectedProducts(newSelectedProducts)
} else {
setSelectedProducts((prevState) => [
...prevState,
{ product, purchasedQuantity: 1 },
])
}
}
function handleDecreaseProductOfSelectedProducts(product: Product) {
const newSelectedProducts = [...selectedProducts]
const productAlreadySelected = newSelectedProducts.find(
(data) => data.product.name === product.name,
)
if (productAlreadySelected) {
if (productAlreadySelected.purchasedQuantity > 0) {
productAlreadySelected.purchasedQuantity -= 1
setSelectedProducts(newSelectedProducts)
}
}
}
function handleCalculateChange() {
const moneyChange = calculateChange(cartTotal, amountPaid)
setMoneyChange(moneyChange)
}
function handleGetChangeNotesInText({ quantity, value }: ExchangeInNotes) {
if (quantity > 1 && value > 1) {
return `${quantity} notas de ${value}`
} else if (quantity === 1 && value > 1) {
return `${quantity} nota de ${value}`
} else if (quantity === 1 && value <= 1) {
if (value < 1) {
return `${quantity} moeda de ${String(value).padEnd(4, '0')}`
}
return `${quantity} moeda de ${value}`
} else if (quantity > 1 && value <= 1) {
if (value < 1) {
return `${quantity} moedas de ${String(value).padEnd(4, '0')}`
}
return `${quantity} moedas de ${value}`
}
}
function handleFinishSale() {
setAmountPaid(0)
setMoneyChange([])
setSelectedProducts([])
setIsPaymentModalOpened(false)
}
return (
<>
<main className="h-full mb-8 px-6">
<h1 className="mt-14 mb-6 text-3xl relative left-2">
Venda
<div className="size-6 bg-zinc-900 rounded-md absolute -bottom-0.5 -left-2 -z-10" />
</h1>
<div>
<Table>
<TableHeader>
<TableRow className="hover:bg-inherit">
<TableHead>Nome do produto</TableHead>
<TableHead>Quantidade em estoque</TableHead>
<TableHead>Valor</TableHead>
</TableRow>
{products.map((product, index) => (
<>
<TableRow key={product.name + index}>
<TableCell>{product.name}</TableCell>
<TableCell>{product.quantity}</TableCell>
<TableCell>{formatCurrency(product.unitPrice)}</TableCell>
<TableCell className="flex items-center justify-center gap-3">
<Button
onClick={() =>
handleDecreaseProductOfSelectedProducts(product)
}
size="icon"
>
<Minus size={18} />
</Button>
<div className="size-10 flex items-center justify-center border rounded-md">
{selectedProducts.find(
(data) => data.product.name === product.name,
)?.purchasedQuantity || 0}
</div>
<Button
onClick={() =>
handleAddProductToSelectedProducts(product)
}
size="icon"
>
<Plus size={18} />
</Button>
</TableCell>
</TableRow>
</>
))}
</TableHeader>
</Table>
</div>
</main>
<footer className="w-full px-6 py-2 flex items-center justify-between fixed bottom-1 bg-background">
<div className="flex flex-col gap-1">
<span className="text-sm text-zinc-400">
Subtotal: {formatCurrency(cartTotal)} <small>(0% de imposto)</small>
</span>
<span>Valor total: {formatCurrency(cartTotal)}</span>
</div>
<Dialog
open={isPaymentModalOpened}
onOpenChange={() => setIsPaymentModalOpened(!isPaymentModalOpened)}
>
<DialogTrigger asChild>
<Button
onClick={() => {
setMoneyChange([])
setAmountPaid(0)
setIsPaymentModalOpened(true)
}}
disabled={cartTotal === 0}
className="gap-3"
>
<DollarSign size={18} />
Seguir para pagamento
</Button>
</DialogTrigger>
<DialogContent>
{moneyChange.length > 0 ? (
<>
<p>Você deve entregar:</p>
<div>
{moneyChange.map((note, index) => (
<div key={index}>{handleGetChangeNotesInText(note)}</div>
))}
</div>
<Button onClick={() => handleFinishSale()}>
Finalizar venda
</Button>
</>
) : (
<>
<h2 className="text-xl">
Valor total: {formatCurrency(cartTotal)}
</h2>
<div className="my-4">
<Label htmlFor="payment">Valor pago:</Label>
<Input
value={amountPaid}
onChange={(event) =>
setAmountPaid(Number(event.target.value))
}
id="payment"
type="number"
/>
<Button
onClick={() => handleCalculateChange()}
className="w-full mt-3"
>
Calcular troco
</Button>
</div>
</>
)}
</DialogContent>
</Dialog>
</footer>
</>
)
} |
package Exersicis;
import java.util.Scanner;
public class tresraya {
private final static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String[][] tablero = new String[3][3];
startingGame(tablero);
}
private static String[] askName() {
System.out.println("Starting game...\n");
System.out.println("Bienvenido al juego de tres en raya !\n");
System.out.print("Introduce el nombre del primer jugador:");
String jugador1 = sc.next();
System.out.print("Introduce el nombre del segundo jugador:");
String jugador2 = sc.next();
System.out.println("Que jugador quiere empezar 1-2 ?");
int starts = sc.nextInt();
System.out.println();
while (starts != 1 && starts != 2) {
System.out.println("Que jugador quiere empezar 1-2 ?");
starts = sc.nextInt();
System.out.println();
}
return starts == 1 ? new String[] { jugador1, jugador2 } : new String[] { jugador2, jugador1 };
}
private static void startingGame(String[][] tablero) {
boolean win = false;
int countmovements = 0;
String[] j = askName(); // j[0] = player1 j[1] = player2
String ficha = askForXO(j); // Pregunto con que quiere jugar ('x' o 'o')
while (ficha != "x" && ficha != "o") {
ficha = askForXO(j);
}
showtablero(tablero); // Muestro el tablero
while (!win && countmovements != 9) {
int[] movements = askMovement(); // Pregunto el movimiento
boolean checkMovement = checkMovement(movements[0], movements[1], tablero, ficha);// Compruebo el movimiento
while (!checkMovement) {
movements = askMovement();
checkMovement = checkMovement(movements[0], movements[1], tablero, ficha);
}
tablero[movements[0]][movements[1]] = ficha; // Realiza el movimiento
updatedMatrix(tablero); // Muestro el movimiento en la matriz
countmovements++;
win = checkWinners(tablero, ficha);
if (!win && countmovements != 9) {// Si alguien a ganado no cambia la ficha
ficha = changeXO(ficha); // Cambia la ficha
}
}
results(win, ficha, countmovements, j);
}
public static void showtablero(String[][] tablero) {
System.out.println("\nEste es el tablero:\n");
for (int i = 0; i < tablero.length; i++) {
for (int j = 0; j < tablero[i].length; j++) {
tablero[i][j] = "-";
if (j == 0 || j == tablero.length - 1) {
if (j == 0) {
System.out.print("| " + tablero[i][j]);
}
if (j == tablero.length - 1) {
System.out.print(tablero[i][j] + " |");
}
} else {
System.out.print(" " + tablero[i][j] + " ");
}
}
System.out.println();
}
}
private static String askForXO(String[] j) {
String ficha;
System.out.print(j[0] + " quieres jugar con 'x' o con 'o':");
ficha = sc.next();
switch (ficha) {
case "x":
ficha = "x";
break;
case "o":
ficha = "o";
break;
default:
System.out.println("\nERROR :Caracter no reoconocido ");
}
return ficha;
}
private static String changeXO(String ficha) {
switch (ficha) {
case "x":
System.out.println("Ahora le toca a la 'o'");
ficha = "o";
break;
case "o":
System.out.println("Ahora le toca a la 'x'");
ficha = "x";
break;
}
return ficha;
}
private static boolean checkMovement(int f1, int c1, String[][] tablero, String ficha) {
if (f1 >= 0 && f1 < 3 && c1 >= 0 && c1 < 3) {
if (tablero[f1][c1] == "x" || tablero[f1][c1] == "o") {
System.out.println("\nLa casilla esta ocupada. Prueba con una que no lo este!\n");
return false;
}
return true;
}
System.out.println("\nFuera de los valores 0-2\n");
return false;
}
private static int[] askMovement() {
int f1, c1;
System.out.print("Introduce la fila:");
f1 = sc.nextInt();
System.out.println();
System.out.print("Introduce la columna:");
c1 = sc.nextInt();
System.out.println();
return new int[] { f1, c1 };
}
public static boolean checkWinners(String[][] tablero, String x) {
// Comprueba diagonal a la derecha
if (tablero[0][0].equals(x) && tablero[1][1].equals(x) && tablero[2][2].equals(x))
return true;
// Comprueba diagonal a la izquierda
if (tablero[0][2].equals(x) && tablero[1][1].equals(x) && tablero[2][0].equals(x))
return true;
// Comprueba filas y columnas
for (int i = 0; i < 3; i++) {// Comprueba filas
if (tablero[i][0].equals(x) && tablero[i][1].equals(x) && tablero[i][2].equals(x))
return true;
// Comprueba columnas
if (tablero[0][i].equals(x) && tablero[1][i].equals(x) && tablero[2][i].equals(x))
return true;
}
return false;
}
private static void updatedMatrix(String[][] tablero) {
for (int i = 0; i < tablero.length; i++) {
for (int j = 0; j < tablero[i].length; j++) {
if (j == 0) {
System.out.print("| " + tablero[i][j]);
} else if (j == tablero.length - 1) {
System.out.print(tablero[i][j] + " |");
} else {
System.out.print(" " + tablero[i][j] + " ");
}
}
System.out.println();
}
}
private static void results(boolean win, String ficha, int countmovements, String[] j) {
if (win && countmovements % 2 == 0) {
System.out.println("\nHa ganado " + j[0]);
} else if (win && countmovements % 2 != 0) {
System.out.println("\nHa ganado " + j[1]);
} else if (!win && countmovements == 9) {
System.out.println("\nEl resultado es empate");
}
}
} |
from django.http import JsonResponse
from django.core.cache import cache
import requests
from django.contrib.auth.models import User
from game.models.player.player import Player
# from django.contrib.auth import login
from random import randint
def receive_code(request):
# 申请授权令牌 access_token 和用户的 openid
data = request.GET
# 这里和web不一样,web端拒绝后直接就返回页面,这里会收到错误码
if "errcode" in data:
return JsonResponse({
'result': "apply failed",
'errcode': data['errcode'],
'errmsg': data['errmsg'],
})
code = data.get('code')
state = data.get('state')
# 如果state不存在,返回state不存在
if not cache.has_key(state):
return JsonResponse({
'result': "state not exist",
})
cache.delete(state)
apply_access_token_url = "https://www.acwing.com/third_party/api/oauth2/access_token/"
params = {
'appid': "5427",
'secret': "9be89504078c4e55981d79c5e399c200",
'code': code
}
access_token_res = requests.get(apply_access_token_url, params=params).json()
# print(access_token_res)
# 申请用户信息
access_token = access_token_res['access_token']
openid = access_token_res['openid']
# 如果acw账户对应用户已经存在,直接登录
players = Player.objects.filter(openid=openid)
if players.exists():
# acapp端不需要重新登陆
# login(request, players[0].user)
# return redirect("index")
player = players[0]
return JsonResponse({
'result': "success",
'username': player.user.username,
'photo': player.photo,
})
# 如果acw账户对应用户不存在,申请授权,用户信息
get_userinfo_url = "https://www.acwing.com/third_party/api/meta/identity/getinfo/"
params = {
"access_token": access_token,
"openid": openid
}
userinfo_res = requests.get(get_userinfo_url, params=params).json()
# 拿到用户名和头像
username = userinfo_res['username']
photo = userinfo_res['photo']
# 如果重名,额外添加数字填充
while User.objects.filter(username=username).exists():
username += str(randint(0, 9))
# 注册新用户
user = User.objects.create(username=username)
player = Player.objects.create(user=user, photo=photo, openid=openid)
# 不需要登录
# login(request, user)
# return redirect("index")
return JsonResponse({
'result': "success",
'username': player.user.username,
'photo': player.photo,
}) |
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:tiktok_clone/constants/sizes.dart';
import 'package:tiktok_clone/features/inbox/chat_detail_screen.dart';
class ChatScreen extends StatefulWidget {
static const String routeName = "chats";
static const String routeURL = "/chats";
const ChatScreen({super.key});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final GlobalKey<AnimatedListState> _key = GlobalKey<AnimatedListState>();
final List<int> _items = [];
final Duration _duration = const Duration(milliseconds: 200);
void _additem() {
if (_key.currentState != null) {
_key.currentState!.insertItem(
0,
duration: _duration,
);
_items.add(_items.length);
}
}
void _deleteItem(int index) {
if (_key.currentState != null) {
_key.currentState!.removeItem(
index,
(context, animation) => SizeTransition(
sizeFactor: animation,
child: _makeTile(index),
),
duration: _duration,
);
_items.removeAt(index);
}
}
void _onChatTap(int index) {
context.pushNamed(ChatDetailScreen.routeName, params: {"chatId": "$index"});
}
Widget _makeTile(int index) {
return ListTile(
onLongPress: () => _deleteItem(index),
onTap: () => _onChatTap(index),
key: UniqueKey(),
leading: const CircleAvatar(
radius: Sizes.size32,
foregroundImage: NetworkImage(
"https://d1telmomo28umc.cloudfront.net/media/public/avatars/wisewinshin-avatar.jpg"),
child: Text("Me"),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
"Lynn($index)",
style: const TextStyle(fontWeight: FontWeight.bold),
),
Text(
"2:16 PM",
style:
TextStyle(fontSize: Sizes.size14, color: Colors.grey.shade400),
),
],
),
subtitle: const Text("Don't forget make videos"),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 1,
title: const Text("Direct message"),
actions: [
IconButton(
onPressed: _additem,
icon: const FaIcon(
FontAwesomeIcons.plus,
),
)
],
),
body: AnimatedList(
key: _key,
padding: const EdgeInsets.symmetric(
vertical: Sizes.size12,
),
initialItemCount: 0,
itemBuilder: (context, index, animation) {
return FadeTransition(
opacity: animation,
child:
SizeTransition(sizeFactor: animation, child: _makeTile(index)),
);
},
),
);
}
} |
package com.alex.sitiy;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import org.jboss.logging.Logger;
import java.util.Map;
@Named("hello-post")
public class HelloWorldPostLambda implements RequestHandler<APIGatewayV2HTTPEvent, APIGatewayV2HTTPResponse> {
private static final Logger LOGGER = Logger.getLogger(HelloWorldPostLambda.class);
@Inject
ObjectMapper objectMapper;
@Override
public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context context) {
try {
Message message = objectMapper.readValue(event.getBody(), Message.class);
LOGGER.info(message);
return APIGatewayV2HTTPResponse.builder()
.withStatusCode(200)
.withBody("Hello %s %s".formatted(message.name(), message.surname()))
.build();
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
} |
/**
* @details Calculates the number of permutations and combinations.
* @external_link (Permutation And Combinations)[https://www.geeksforgeeks.org/permutation-and-combination/]
*/
/**
* @brief Calculates the factorial of the given number.
* @param num: integer
* @details Factorial of n = n * (n - 1) * (n - 2) * ... * 1
* @returns integer: Factorial of the number.
NaN: if negative number is provided.
*/
const factorial = (n) => {
if (n >= 0) {
if (n === 0) {
return 1
} else {
return n * factorial(n - 1)
}
} else {
return NaN
}
}
/**
* @brief Calculates the number of Permutations from the given data.
* @param
* n: integer -> number of items.
* r: integer -> number of times n is taken.
* @returns integer: The number of permutations.
NaN: if negative number is provided.
*/
const permutation = (n, r) => {
return factorial(n) / factorial(n - r)
}
/**
* @brief Calculates the number of Combinations from the given data.
* @param
* n -> number of items.
* r -> number of times n is taken.
* @returns integer: The number of combinations.
NaN: if negative number is provided.
*/
const combination = (n, r) => {
return factorial(n) / (factorial(r) * factorial(n - r))
}
// Exports the functions to be used in other files.
module.exports.factorial = factorial
module.exports.permutation = permutation
module.exports.combination = combination
/**
* @example
const funcs = require("./PermutationAndCombination.js");
console.log(funcs.factorial(5));
console.log(funcs.permutation(5, 2));
console.log(funcs.combination(5, 2));
* @output
120
20
10
*/ |
/*********************************************************************
* \file TextureSamplerBuilder.h
* \brief
*
* \author Lancelot 'Robin' Chen
* \date July 2022
*********************************************************************/
#ifndef TEXTURE_SAMPLER_BUILDER_H
#define TEXTURE_SAMPLER_BUILDER_H
#include <Frameworks/Event.h>
#include <Frameworks/EventSubscriber.h>
#include <GraphicKernel/IDeviceSamplerState.h>
#include <GraphicKernel/IGraphicAPI.h>
class TextureSamplerBuilder
{
public:
TextureSamplerBuilder();
TextureSamplerBuilder(const TextureSamplerBuilder&) = delete;
TextureSamplerBuilder(TextureSamplerBuilder&&) = delete;
~TextureSamplerBuilder();
const TextureSamplerBuilder& operator=(const TextureSamplerBuilder&) = delete;
const TextureSamplerBuilder& operator=(TextureSamplerBuilder&&) = delete;
void BuildTexture(const std::string& name, const std::string& filename, const std::string& path_id);
void BuildSampler(const std::string& name, const Enigma::Graphics::IDeviceSamplerState::SamplerStateData data);
private:
void OnTextureCreated(const Enigma::Frameworks::IEventPtr& e);
void OnTextureImageLoaded(const Enigma::Frameworks::IEventPtr& e);
void OnSamplerCreated(const Enigma::Frameworks::IEventPtr& e);
void OnSamplerResourceCreated(const Enigma::Frameworks::IEventPtr& e);
private:
Enigma::Frameworks::EventSubscriberPtr m_onTextureCreated;
Enigma::Frameworks::EventSubscriberPtr m_onTextureImageLoaded;
Enigma::Frameworks::EventSubscriberPtr m_onSamplerCreated;
Enigma::Frameworks::EventSubscriberPtr m_onSamplerResourceCreated;
std::string m_textureName;
std::string m_textureFilename;
std::string m_texturePathId;
std::string m_samplerName;
Enigma::Graphics::IDeviceSamplerState::SamplerStateData m_samplerData;
};
class TextureLoaded : public Enigma::Frameworks::IEvent
{
public:
TextureLoaded(const std::string& name) :
m_name(name) {};
const std::string& GetTextureName() { return m_name; }
private:
std::string m_name;
};
class SamplerStateBuilt : public Enigma::Frameworks::IEvent
{
public:
SamplerStateBuilt(const std::string& name) :
m_name(name) {};
const std::string& GetSamplerName() { return m_name; }
private:
std::string m_name;
};
#endif // TEXTURE_SAMPLER_BUILDER_H |
import * as assert from 'assert';
import { DecoratedClass } from 'test/fixtures/validators';
describe('ParameterValidators', function() {
describe('@cardIndex', function() {
describe('for single parameter', function() {
it('should throw error if value is negative', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method1(-1);
};
assert.throws(block, { message: 'Invalid card index -1: should be non-negative integer' });
});
it('should throw error if value is non-integer', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method1(3.1415);
};
assert.throws(block, { message: 'Invalid card index 3.1415: should be non-negative integer' });
});
it('should let pass through if value is positive integer number', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method1(1);
};
assert.doesNotThrow(block);
});
});
describe('for two parameters', function() {
it('should throw correct error if 1st value is invalid and 2nd is valid ', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method2(-1, 1);
};
assert.throws(block, { message: 'Invalid card index -1: should be non-negative integer' });
});
it('should throw correct error if 1st value is invalid and 2nd is invalid ', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method2(-1, -2);
};
assert.throws(block, { message: 'Invalid card index -2: should be non-negative integer' });
});
it('should throw correct error if 1st value is valid and 2nd is invalid ', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method2(1, -1);
};
assert.throws(block, { message: 'Invalid card index -1: should be non-negative integer' });
});
it('should let pass through if both values are valid', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method2(1, 1);
};
assert.doesNotThrow(block);
});
});
});
describe('@cardIndexesRest', function() {
describe('for single parameter', function() {
it('should throw error if value is invalid', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method3(1, 2, -3);
};
assert.throws(block, { message: 'Invalid card indexes 1, 2, -3: all should be non-negative integers' });
});
it('should let pass through if value is positive integer number', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
const result = decoratedClass.method3(1, 2, 3);
assert.equal(result, '1,2,3');
};
assert.doesNotThrow(block);
});
});
describe('@cardIndex + @cardIndexesRest', function() {
it('should let pass through if @cardIndex is valid and @cardIndexesRest is valid', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
const result = decoratedClass.method4(1, 2, 3);
assert.equal(result, '1,[2,3]');
};
assert.doesNotThrow(block);
});
it('should throw error if @cardIndex is invalid and @cardIndexesRest is valid', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method4(-1, 2, 3);
};
assert.throws(block, { message: 'Invalid card index -1: should be non-negative integer' });
});
it('should throw error if @cardIndex is valid and @cardIndexesRest is invalid', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method4(1, -2, -3);
};
assert.throws(block, { message: 'Invalid card indexes -2, -3: all should be non-negative integers' });
});
});
});
describe('@validCardNumberToTake', function() {
describe('for single parameter', function() {
it('should throw error if value is negative', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method5(-1);
};
assert.throws(block, { message: 'Invalid card number to take -1: should be non-negative integer' });
});
it('should throw error if value is non-integer', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method5(3.1415);
};
assert.throws(block, { message: 'Invalid card number to take 3.1415: should be non-negative integer' });
});
it('should let pass through if value is positive integer number', function() {
const decoratedClass = new DecoratedClass();
const block = (): void => {
decoratedClass.method5(1);
};
assert.doesNotThrow(block);
});
});
});
describe('@nonNegativeInteger', function() {
it('should throw error if value is invalid', function() {
const decoratedClass = new DecoratedClass();
assert.throws(() => decoratedClass.nonNegativeInteger(-1), { message: 'Invalid value -1: should be non-negative integer' });
});
it('should let pass through if value is valid', function() {
const decoratedClass = new DecoratedClass();
assert.doesNotThrow(() => decoratedClass.nonNegativeInteger(1));
});
});
describe('@notEmptyArrayRest', function() {
describe('for single parameter', function() {
it('should throw error if array is empty', function() {
const decoratedClass = new DecoratedClass();
assert.throws(() => decoratedClass.emptyArray(), { message: 'Invalid value: array is empty' });
});
it('should let pass through if array is not empty', function() {
const decoratedClass = new DecoratedClass();
assert.doesNotThrow(() => decoratedClass.nonEmptyArray(1, 2, 3));
});
});
});
}); |
# Activation Function Approximation Using Piecewise Linear and RL
## Description
A system for using RL to determine segment points for piecewise linear approximation of activation functions like sigmoid, SiLU(swish), GELU, et cetera. This project is part of the ISOCC2023 paper "Automated Generation of Piecewise Linear Approximations for Nonlinear Activation Functions via Curvature-based Reinforcement Learning".
## Technology Stack
- Python 3.11.2
- Stable Baselines3
- gymnasium
## Installation
``````bash
# Create virtual environment
python3.11 -m venv env
# Activate virtual environment
source env/bin/activate
# Install dependencies
pip install -r requirements.txt
``````
## Usage
- `RL_PPO_SB3.py`: Contains the RL training code and the environment setup. Modify the code to choose between sigmoid, SiLU, or GELU. After running code results are generated within the run_archive directory.
- `least_sq_approximation.py`: Solves the matrix equation and generates the piecewise linear functions.
- `points_to_function_converter.py`: Takes piecewise points to generate the variables that define the piecewise linear function.
Example usage of `points_to_function_converter.py`:
``````bash
python points_to_function_converter.py -F GELU -P -5 -4 0 1 -R -8 8 --round 5
``````
## Contributing
Contributions are welcome. Please read the contributing guidelines and code of conduct before making a pull request.
## Implementation Details
Takes inspiration from [Li et al 2022](https://doi.org/10.3390/electronics11091365) for using curvature to select piecewise linear points. We extend this by using RL (used PPO algorithm) for automated selection. The system leverages curvature as an intermediate reward and combines average and maximum error for the final reward.
Mathematical formulation:
The piecewise linear function is created given an input range, [b<sub>1</sub>, b<sub>m</sub>], and segment points (b<sub>2</sub>, ..., b<sub>m-1</sub>) using the least square method from [Li et al 2022](https://doi.org/10.3390/electronics11091365).
Range is set to [-8, 8] by default for all functions but can be modified if needed.

Where A and B are left and right asymptotes respectively (e.g., for sigmoid A = 0, B = 1, and for SiLU and GELU A = 0, B = x). Given the range and segment points, the least square method is used to find the optimal beta values (β<sub>1</sub>, β<sub>2</sub>, ..., β<sub>m</sub>) that minimizes the error, implemented using the scipy.linalg.lstsq function.

The value x_i is sampled over given range [b<sub>1</sub>, b<sub>m</sub>] an over interval 0.001. So, for interval of [-8, 8] we have a total of 16001 points being sampled (as the range is inclusive). And value y_i is the output of a given function (sigmoid, SiLU, GELU, et cetera) when x_i is the input. The above matrix can be formulated into a least square problem as follows.

The optimum <i>β<sup>*</sup></i> that minimizes the error (<i>Y - Aβ<sup>*</sup></i>) can be found using the least square method. In this implementation, it was done using the scipy.linalg.lstsq function.


## Future Work
Code cleanup and reimplementation in Jax for performance improvement are in progress.
## Examples
- Curvatures of GELU, SiLU, and sigmoid functions:

- Example of GELU, SiLU, and sigmoid functions with their piecewise linear counterparts:
- GELU:

- SiLU:

- Sigmoid:

- ImageNet-1K Classification Accuracy using the approximation functions:

## License
TBD
## Contact Information
- **Author**: Kyumin Cho
- **Email**: kmcho@postech.ac.kr
- **Affiliation**: MS-PhD student at CAD & SoC Design Lab (CSDL), Postech under Professor Kang Seokhyeong |
function oldPriority=Priority(newPriority)
% oldPriority=Priority([newPriority])
%
% Query and optionally set the execution priority of your script to
% 'newPriority' and switch from non-realtime to realtime scheduling (for
% 'newPriority' values greater than zero).
%
% Higher priority levels will reduce the chance of other running
% applications and system processes interfering with the execution timing
% of your script, or reduce the severity of interference. However, various
% factors influence the timing behaviour of your computer and its hardware,
% so while use of Priority() is one step to ensure good timing, it is not
% the only required step. The PsychDocumentation subfolder of your
% distribution as well as the Psychtoolbox Wiki contain various documents
% with tips on how to improve system timing behaviour. All else being
% equal, the Linux operating system should provide best possible timing
% behaviour out of the box, with various possibilities to tweak and tune the
% system for even better timing behaviour. Mac OSX is the second best
% choice for precise timing.
%
% OS X: ___________________________________________________________________
%
% Unlike on OS 9 and Windows, On OS X setting a high priority will not
% disable important parts of your computer such as the keybaord and hard
% drive. Priority calls the Psychtoolbox mex function MachSetPriority. For
% simple, OS-neutral control of process priority on OS X use Priority. For
% complicated, fine-grained, OS-specific control of process priority use
% MachSetPriority.
%
% At priority settings greater than 0, your script must limit MATLAB's use
% of CPU time to stay within the limits specified by the priority value.
% The consequence of failing to restrict the CPU time to the limits
% specified by the priority values is that OS X will demote MATLAB back to
% priority 0. You can check to see if this has happened by calling
% Priority with no arguments.
%
% Within a script there are two ways to limit MATLAB's use of CPU time:
%
% 1. Call "WaitSecs"
% 2. Call Screen('Flip',...)
%
% Both calls will sleep the main MATLAB thread, surrendering CPU time to
% other threads on the system until the MATLAB thread is awakened.
% WaitSecs sleeps the MATLAB thread for a specified period.
% Screen('Flip',...) sleeps the MATLAB thread until the next video blanking
% interval.
%
% The priority value corresponds to the proportion of the video frame
% period during which MATLAB is guranteed 100 percent of CPU time:
%
% GuaranteedCPUtimePerFramePeriod = priority/10 * framePeriod
%
% If your computer has multiple video displays running at different frame
% rates then Priority will choose the shortest frame period.
%
% The consequence of a thread exceeding the specified limits on CPU usage
% are that the MACH kernel will revoke its real-time priority status.
% However, the threshold at which the MACH kernel decices to revoke
% priority is not known. We have observed that at 100% CPU usage the
% Jaguar Mach kernel will revoke priority after 2.5 seconds, indepent of
% the CPU time requested when setting priority.
%
% Note that if you change the video frame rate after setting priority then
% the framePeriod which Priority used when setting the priority level will
% no longer match the true frame period. Therefore you should change the
% priority level after changing the video mode and not before.
%
%
% WINDOWS: ________________________________________________________________
%
% For the Windows version of Priority (and Rush), the priority levels set
% are "process priority levels". There are 3 priority levels available,
% levels 0, 1, and 2. Level 0 is "normal priority level", level 1 is "high
% priority level", and level 2 is "real time priority level". Combined with
% thread priority levels, they determine the absolute priority level of the
% Psychtoolbox threads. Threads are executed in a "round robin" fashion on
% Windows, with the lower priority threads getting cpu time slice only
% when no higher priority thread is ready to execute. Currently, no tests
% have been done to see what tasks are pre-empted by setting the Matlab
% process to real-time priority. It does seem to block keyboard input,
% though, so for example if you have a clut animation going on at priority
% level 2, then the force-quit key combo (Ctrl-Alt-Delete) does not work.
% However, the keyboard inputs are still sent to the message queue, so
% GetChar or GetClicks still work if they are also called at priority level
% 2.
%
% Typically you will not want to choose a higher priority than 1 unless you
% know exactly what you're doing.
%
% LINUX: __________________________________________________________________
%
% To enable use of Priority(), you must run the script
% PsychLinuxConfiguration at least once and follow its instructions.
% Normally the script will get executed automatically by our installer if
% you got Psychtoolbox via DownloadPsychtoolbox or UpdatePsychtoolbox.
% However, if you got Psychtoolbox directly from the package manager of
% your Linux distribution or from the NeuroDebian repositories, it may be
% neccessary to execute the PsychLinuxConfiguration function manually.
%
% GNU/Linux supports priority levels between 0 and 99. Zero means standard
% non-realtime timesharing operation -- Play fair with all other
% applications. Increasing values greater than zero mean realtime mode: The
% Matlab/Octave process is scheduled in realtime mode with a priority
% corresponding to the given number - higher means better, but also more
% likelihood of interfering with system processes. Try to stick to a level
% of 1 unless you have reason to go higher. Level one is usually
% sufficient, unless you run other realtime applications on the same
% machine in parallel and want to prioritize Psychtoolbox relative to those
% applications.
%
% In realtime mode, PTB will also try to lock down all of Matlab/Octaves
% memory into physical RAM, preventing it from being paged out to disk by
% the virtual memory manager. If it works, it's great! However, the amount
% of lockable memory is restricted to max. 50% of installed RAM memory on
% some older Linux setups, so if Matlab/Octave/your experiment would need
% more than 50% of available system memory, this will fail. PTB will output
% an informative warning in this case, but continue otherwise unaffected.
% Realtime scheduling will be still effective, you'll just lose the bonus
% of memory locking.
%
% On old single processor computers, be careful not to create any
% uninterruptible infinite loops in your code when running realtime,
% otherwise your system may lock up, requiring a hard reboot!
% _________________________________________________________________________
%
% see also OS X: Rush
% see also Windows: Rush
% see also OS 9: Rush, ScreenTest, RushTest, LoopTest
% NOTES:
% priorityStruct looks like this.
%
% threadID:
% flavor: 'THREAD_TIME_CONSTRAINT_POLICY'
% policy:
% period:
% computation:
% constraint:
% preemptible:
% policySize:
% policyFillSize:
% getDefault:
% isDefault:
% HISTORY:
% 4/13/97 dgp Wrote it
% 4/22/97 dgp Updated
% 5/1/97 dgp Updated
% 5/31/97 dgp Updated
% 6/3/97 dgp Updated
% 3/15/99 xmz Added comments for Windows version.
% 2/4/00 dgp Updated for Mac OS 9.
% 6/13/02 awi Cosmetic
% 12/11/03 awi Wrote documentation and scripting for OS X
% 7/16/03 awi Merged together documetation for OS X and OS 9 and
% Windows.
% 8/24/05 awi Kill and start update under standard, not time constraint
% priority.
% When raising priority, issue error and return if we fail
% to kill the update process. Do not set time contstraint
% priority.
% 2/21/06 mk Updated for Linux.
% 5/29/06 mk Merged a fix for properly restarting update process.
% Bug found & fix provided by Michael Ross.
% 8/02/06 mk Bugfix by Michael Ross merged: oldPriority was sometimes
% reported with some roundoff error.
% 8/02/06 mk We now detect if we're running on a OS-X 10.4.7 system or
% later. We do not kill and restart the system update process
% anymore in that case as it isn't necessary anymore.
% 5/15/07 mk Priority.dll on Windoze replaced by code in this M-File.
% 6/01/09 mk Enable Priority() support for OS/X + Octave-3.
% 7/10/13 mk Remove handling of update process, as we no longer support
% OSX versions < 10.6, so no need to kill/restart updated.
if ~isempty(getenv('PSYCH_IN_VM'))
% Running inside Virtual machine. We no-op. Everything else has potential
% for bogging the VM down to a standstill:
oldPriority = 0; % Dummy return - No realtime sched active.
return;
end
if IsLinux
% Linux: We do not use a separate MEX file anymore. Instead we use a
% built-in helper subroutine of Screen(), accessed via the special code -5
% when calling the 'GetMouseHelper' subfunction.
if nargin < 1
newPriority = [];
end
if isempty(newPriority)
% No priority provided: Just return the current level:
oldPriority = Screen('GetMouseHelper', -5);
else
% New priority provided: Query and return old level, set new one:
if newPriority < 0 || newPriority > 99
error('Invalid Priority level specified! Not one between 0 and 99.');
end
oldPriority = Screen('GetMouseHelper', -5, newPriority);
end
% Done for Linux:
return;
end;
if IsOSX
%Get the current settings.
[flavorNameString, priorityStruct] = MachGetPriorityFlavor;
if strcmp('THREAD_STANDARD_POLICY', flavorNameString)
oldPriority=0;
else % strcmp('THREAD_TIME_CONSTRAINT_POLICY', flavorNameString)
%Values in priority struct returned by MachGetPriorityFlavor are in ticks but should be in seconds
%it does not matter here because we are only concerned with the ratio
if priorityStruct.policy.period == 0 || priorityStruct.policy.computation == 0
%this is an illegitimate setting, so restore to standard priority
%and go from there.
MachSetStandardPriority;
oldPriority=0;
else
oldPriorityRatio= priorityStruct.policy.computation / priorityStruct.policy.period;
% Make sure we never exceed an oldPriority of 9, even in case
% of roundoff-error. Bug found and fixed by Michael Ross.
oldPriority=min(oldPriorityRatio * 10, 9);
end
end
%if no new setting is given then return
if nargin==0
return
end
%bounds check the input argument
if newPriority > 9
error('"newPriority" value exceeds maximum allowable value of 9');
elseif newPriority < 0
error('"newPriority" value is less than the minimum allowable value of 0');
end
%if the priority level calls for time constraint priority...
if newPriority > 0
% Find the frame periods. FrameRate returns the nominal frame rate, which
% for LCD displays is 0. We assume 60 in that case.
defaultFrameRate=60; %Hz
screenNumbers=Screen('Screens');
for i = 1:length(screenNumbers)
frameRates(i)=Screen('FrameRate', screenNumbers(i)); %#ok<AGROW>
end
[zeroRates, zeroRateIndices]=find(frameRates==0); %#ok<*ASGLU>
frameRates(zeroRateIndices)=defaultFrameRate;
framePeriods=1./frameRates;
% MachSetTimeConstraintPriority(periodSecs,computationSecs, constraintSecs, preemptibleFlag)
periodSecs=min(framePeriods);
computationSecs = newPriority/10 * periodSecs;
constraintSecs=computationSecs;
preemptibleFlag=1;
%set the prioirity
MachSetTimeConstraintPriority(periodSecs,computationSecs, constraintSecs, preemptibleFlag);
%if the priority level calls for standard priority then ..
else %priority==0
%restore standard priority
MachSetStandardPriority;
end
end
% Microsoft Windows?
if IsWin
% Yes. We do not use a separate MEX file anymore. Instead we use a
% built-in helper subroutine of Screen(), accessed via the special code -3
% when calling the 'GetMouseHelper' subfunction.
if nargin < 1
newPriority = [];
end
if isempty(newPriority)
% No priority provided: Just return the current level:
oldPriority = Screen('GetMouseHelper', -3);
else
% New priority provided: Query and return old level, set new one:
if newPriority<0 || newPriority>2
error('Invalid Priority level specified! Not one of 0, 1 or 2.');
end
oldPriority = Screen('GetMouseHelper', -3, newPriority);
end
% Done for Windows...
end; |
<!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>Profile</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<style>
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
#content {
flex: 1 0 auto;
}
footer {
height: 100px;
position: sticky;
bottom: 0;
}
</style>
</head>
<body>
{% include 'navbar.html' %}
<div class="container"> <!-- or use "container-fluid" for full width -->
<div id="content">
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-lg-6">
<h3>Your Profile</h3>
{% if user_data %}
<form id="edit-profile-form" action="{{ url_for('update_profile') }}" method="post">
{% for key, value in user_data.items() %}
<div class="form-group">
{% if key == "idShopper" %}
<input type="hidden" name="{{ key }}" value="{{ value }}">
{% elif key == "FirstName"%}
<label for="{{ key }}" class="form-label">First Name:</label>
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-control alphabetic-input" required><br>
{% elif key == "LastName"%}
<label for="{{ key }}" class="form-label">Last Name:</label>
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-control alphabetic-input" required><br>
{% elif key == "State" %}
<label for="{{ key }}" class="form-label">{{ key }}</label>
<select id="{{ key }}" name="{{ key }}" class="form-control">
{% set states = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'] %}
{% for state in states %}
<option value="{{ state }}" {% if state == value %}selected{% endif %}>{{ state }}</option>
{% endfor %}
</select><br>
{% elif key == "ZipCode" %}
<label for="{{ key }}" class="form-label">Zip Code:</label>
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-control zipcode-input" required><br>
{% elif key == "Phone" %}
<label for="{{ key }}" class="form-label">Phone:</label>
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-control phone-input" required><br>
{% elif key == "Email" %}
<label for="{{ key }}" class="form-label">Email:</label>
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-control email-input"><br>
{% elif key == "Country" %}
<label for="{{ key }}" class="form-label">Country:</label>
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-control" readonly><br>
{% elif key == "Promo"%}
<label for="{{ key }}" class="form-label">Promo:</label>
<input type="text" id="{{ key }}" name="{{ key }}" value="" class="form-control alphabetic-input" maxlength="1"><br>
{% else %}
<label for="{{ key }}" class="form-label">{{ key }}:</label>
{% if value %}
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-control"><br>
{% else %}
<input type="text" id="{{ key }}" name="{{ key }}" value="" class="form-control"><br>
{% endif %}
{% endif %}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Update</button>
</form>
{% else %}
<p>No data available for the user.</p>
{% endif %}
</div>
</div>
</div>
</div>
</div>
<div class="container mt-4 mb-4">
<div class="row justify-content-center">
<div class="col-lg-6">
<h3>Change Password</h3>
<form id="change-password-form" action="{{ url_for('change_password') }}" method="post">
<div class="form-group">
<label for="current-password" class="form-label">Current Password:</label>
<input type="password" id="current-password" name="current_password" class="form-control" required>
</div>
<div class="form-group">
<label for="new-password" class="form-label">New Password:</label>
<input type="password" id="new-password" name="new_password" class="form-control" required>
</div>
<div class="form-group">
<label for="confirm-new-password" class="form-label">Confirm New Password:</label>
<input type="password" id="confirm-new-password" name="confirm_new_password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary mt-4" value="Change Password">
</div>
</form>
</div>
</div>
</div>
<script>
document.querySelectorAll('.alphabetic-input').forEach(function(input) {
input.addEventListener('keydown', function(event) {
// Regular expression to match any non-alphabet character
var regex = /[^a-zA-Z]/;
if (regex.test(event.key) && !isNavigationOrDeleteKey(event)) {
// Prevent input if it's not an alphabetic character
event.preventDefault();
}
});
});
document.querySelectorAll('.zipcode-input').forEach(function(input) {
input.addEventListener('keydown', function(event) {
// Regular expression to match any non-numeric character
if (isNavigationOrDeleteKey(event)){
//pass
} else {
var regex = /[^0-9]/;
if (regex.test(event.key)) {
// Prevent input if it's not a numeric character
event.preventDefault();
} else if (input.value.length > 4){
event.preventDefault();
}
}
});
input.addEventListener('change', function(event) {
var zip = parseInt(event.target.value, 10);
// Validate if the entered ZIP code is within the valid range
if (zip < 501 || zip > 99950) {
alert('Please enter a valid ZIP code.');
event.target.value = '';
}
});
});
document.querySelectorAll('.phone-input').forEach(function(input) {
input.addEventListener('keydown', function(event) {
var regex = /[^0-9]/;
if (regex.test(event.key) && !isNavigationOrDeleteKey(event)) {
event.preventDefault();
} else if (input.value.length >= 10 && !isNavigationOrDeleteKey(event)) {
event.preventDefault();
}
});
});
document.querySelectorAll('.email-input').forEach(function(input) {
input.addEventListener('keydown', function(event) {
var regex = /[^a-zA-Z0-9@._-]/;
if (regex.test(event.key) && !isNavigationOrDeleteKey(event)) {
event.preventDefault();
}
});
});
document.getElementById('edit-profile-form').addEventListener('submit', function(event) {
var emailInput = document.querySelector('.email-input');
var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!emailRegex.test(emailInput.value)) {
alert('Please enter a valid email address.');
event.preventDefault();
} else {
// Prevent form submission
event.preventDefault();
// Send an AJAX request to the server
var xhr = new XMLHttpRequest();
xhr.open("POST", "{{ url_for('update_profile') }}", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Handle response
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
try {
var response = JSON.parse(xhr.responseText);
console.log(response);
alert(response.message);
} catch (e) {
console.error('Error parsing JSON:', e);
console.error('Response from server:', xhr.responseText);
}
}
}
// Serialize form data
var formData = new FormData(event.target);
var formParams = new URLSearchParams(formData).toString();
// Send the request
xhr.send(formParams);
}
});
document.getElementById("change-password-form").addEventListener("submit", function(event) {
var newPassword = document.getElementById("new-password").value;
var confirmNewPassword = document.getElementById("confirm-new-password").value;
if (newPassword !== confirmNewPassword) {
alert("New passwords do not match!");
event.preventDefault();
} else {
// Prevent form submission
event.preventDefault();
// Send an AJAX request to the server
var xhr = new XMLHttpRequest();
xhr.open("POST", "{{ url_for('change_password') }}", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Handle response
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
var response = JSON.parse(xhr.responseText);
alert(response.message);
// Reload the page if password was updated successfully
if (response.message === "Password successfully updated") {
window.location.reload();
}
}
}
// Serialize form data
var formData = new FormData(event.target);
var formParams = new URLSearchParams(formData).toString();
// Send the request
xhr.send(formParams);
}
});
function isNavigationOrDeleteKey(event) {
return (
event.key === 'Backspace' ||
event.key === 'Delete' ||
event.key === 'ArrowLeft' ||
event.key === 'ArrowRight'
);
}
</script>
{% include 'footer.html' %}
</body>
</html> |
const amqp = require('amqplib');
require('dotenv').config();
const processBloodRequest = require('./bloodSearchServiceLogic');
const cron = require('node-cron');
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SG_MAIL_API_KEY);
const bloodQueue = 'blood_request_queue';
const express = require('express');
const app = express();
const port = 1012;
const consumeFromRabbitMQ = async (queueName) => {
try {
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
console.log(`Connected to RabbitMQ for queue: ${queueName}`);
await channel.assertQueue(queueName, { durable: true });
console.log(`Queue '${queueName}' asserted`);
channel.prefetch(1);
console.log(`Waiting for messages on queue: ${queueName}. To exit, press CTRL+C`);
const processMessage = async (msg) => {
const currentTime = new Date().getTime();
const messageContent = JSON.parse(msg.content.toString());
console.log(`Received message from RabbitMQ on queue ${queueName}:`, messageContent);
if (messageContent.processed) {
console.log('Message already processed. Deleting from the queue.');
channel.ack(msg);
return;
}
const { selectedCity, selectedTown } = messageContent;
try {
const coordinates = await processBloodRequest.getCoordinates(selectedCity, selectedTown);
const branches = await processBloodRequest.getAllBranches();
if (branches.length === 0) {
console.log('No branches found.');
channel.ack(msg);
return;
}
let bloodSearchResult = null;
for (const branch of branches) {
try {
const branchCoordinates = await processBloodRequest.getCoordinates(branch.city, branch.town);
const distance = processBloodRequest.haversine(
coordinates.latitude,
coordinates.longitude,
branchCoordinates.latitude,
branchCoordinates.longitude
);
if (distance < 50) {
console.log(`Found a match at branch: ${branch.city}, ${branch.town}, Distance: ${distance} km`);
bloodSearchResult = await processBloodRequest.searchBlood(branch.idbranch, messageContent.bloodType, messageContent.units);
break;
} else {
console.log(`No match at branch: ${branch.city}, ${branch.town}, Distance: ${distance} km`);
}
} catch (error) {
console.error(`Error processing branch: ${branch.city}, ${branch.town}`, error);
}
}
if (bloodSearchResult === 'successful') {
console.log(`Blood search successful. Deleting message from the queue ${queueName}.`);
messageContent.processed = true;
const emailResult = await sendEmail(messageContent.email);
console.log(emailResult);
channel.ack(msg);
} else {
if (Number(messageContent.duration) > 0) {
console.log(`Blood search unsuccessful. Re-queueing message to retry queue. Remaining duration: ${messageContent.duration}`);
messageContent.duration = Math.max(0, Number(messageContent.duration) - 1);
channel.sendToQueue(queueName, Buffer.from(JSON.stringify(messageContent)));
} else {
console.log(`Blood search unsuccessful. Deleting message from the queue ${queueName} as duration is 0.`);
messageContent.processed = true;
channel.ack(msg);
}
}
} catch (error) {
console.error(`Error processing blood request on queue ${queueName}:`, error);
channel.ack(msg);
}
};
channel.consume(queueName, processMessage, { noAck: false });
} catch (error) {
console.error(`Error consuming messages from RabbitMQ on queue ${queueName}:`, error);
}
};
cron.schedule('0 1 * * *', async () => {
await consumeFromRabbitMQ(bloodQueue);
console.log('Job at 1 AM Completed');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
async function clearQueue(queueName) {
try {
const connection = await amqp.connect('amqp://localhost');
console.log('Connected to RabbitMQ');
const channel = await connection.createChannel();
console.log('Channel created');
await channel.assertQueue(queueName, { durable: true });
console.log(`Queue '${queueName}' asserted`);
const purgeResult = await channel.purgeQueue(queueName);
console.log(`Purged ${purgeResult.messageCount} messages from the queue '${queueName}'`);
await connection.close();
console.log('Connection closed');
} catch (error) {
console.error('Error clearing queue:', error);
}
}
const queueName = 'blood_request_queue';
//clearQueue(queueName);
const sendEmail = async (to) => {
const msg = {
to : to,
from: {
name: 'Health Organization',
email: 'iremsuikl@hotmail.com'
},
subject: "Blood Request",
text: "The requested blood type found",
};
try {
await sgMail.send(msg) ;
console.log('Email sent successfully.');
} catch (error) {
console.error('Error sending email:', error);
}
}; |
---
permalink: LINKS/
---
# LINKS
---
## WEEK 01
* [Operating System Tutorial](https://www.tutorialspoint.com/operating_system/index.htm) --- This website provides extensive OS-related learning resources and helpful exam questions with answers!
* [Computer Basics: Understanding Operating Systems](https://youtu.be/fkGCLIQx1MI?si=HCHo_DUbbUNTZKkI) --- This video explains the basic of operating system in a brief and fun way!
## WEEK 02
* [Linux Crash Course - nano (command-line text editor)](https://www.youtube.com/watch?v=DLeATFgGM-A) --- Nano, an alternative to the Vi editor, is my preference due to its straightforward commands, making it more user-friendly. So here is a quick guide to Nano!
* [Asymmetric Encryption - Simply explained](https://youtu.be/AQDCe585Lnc?si=RpVxaW-hLEV_uzpw) --- This is a crystal clear and must-watch video for those who are wondering what "public key" and "private key" are and their function in OS terms.
## WEEK 03
* [File Management in Linux](https://www.geeksforgeeks.org/file-management-in-linux/) --- This website provides guidance on Linux file management, including instructions for using relevant commands!
* [Files & File Systems: Crash Course Computer Science #20](https://www.youtube.com/watch?v=KN8YgJnShPM) --- The video covers computer file systems, file organization, file formats, data storage, metadata, and hierarchical file systems for efficient data management.
## WEEK 04
* [Pointers in C](https://www.youtube.com/watch?v=2ybLD6_2gKM) --- This straight-to-the-point video explains about pointers in low level memory access!
## WEEK 05
* [Introduction to Memory](https://youtu.be/PujjqfUhtNo?si=Ru-xjYLxVAXeAryn) --- You can never go wrong with a nesos academy video, check out this nesos video about memory!
## WEEK 06
* [Fork() in C Programming Language](https://www.section.io/engineering-education/fork-in-c-programming-language/) --- this website explains about fork() function some examples in C programming language.
## WEEK 07
* [How to Use SCP Command](https://linuxize.com/post/how-to-use-scp-command-to-securely-transfer-files/) --- This website has been my 'go to' when SCP command is neeeded.
## WEEK 08
* [LFS 12.0 - How to build Linux From Scratch 12.0](https://youtube.com/playlist?list=PLyc5xVO2uDsA5QPbtj_eYU8J0qrvU6315&si=OrWhRurTMIwcwcqU) --- A Thorough Step-by-Step Manual for Constructing Linux From Scratch
## WEEK 09
* [https://www.linuxfromscratch.org/](Official Linux From Scratch Website) --- This website provides the latest version of the LFS book, which is the primary resource for building your own Linux system from scratch.
* [https://www.linuxquestions.org/questions/linux-from-scratch-13/#google_vignette](LFS Forum) --- My confusion reliever, this is a popular online community and forum dedicated to Linux. The Linux From Scratch section within the forum is specifically for discussions related to the Linux From Scratch project.
## WEEK 10
* [https://www.youtube.com/watch?v=cmH5B7LjhoE](Kernotex's YouTube LFS 12.0 Ch.8) --- Kernotex's YouTube video for LFS ch.8 |
import { Dispatch } from '@reduxjs/toolkit';
import { StateScheme } from '@/app/providers/StoreProvider';
import { userActions } from '@/entities/User';
import { TestAsyncThunk } from '@/shared/lib/tests/TestAsyncThunk/TestAsyncThunk';
import { loginByUsername } from './loginByUsername';
describe('loginByUsername', () => {
let dispatch: Dispatch;
let getState: () => StateScheme;
beforeEach(() => {
dispatch = jest.fn();
getState = jest.fn();
});
const thunk = new TestAsyncThunk(loginByUsername);
test('success login', async () => {
const userValue = { username: '123', id: '1' };
thunk.api.post.mockReturnValue(Promise.resolve({ data: userValue }));
const result = await thunk.callThunk({ username: '123', password: '123' });
expect(thunk.dispatch).toHaveBeenCalledWith(userActions.setAuthData(userValue));
expect(thunk.dispatch).toHaveBeenCalledTimes(3);
expect(thunk.api.post).toHaveBeenCalled();
expect(result.meta.requestStatus).toBe('fulfilled');
expect(result.payload).toBe(userValue);
});
test('error login', async () => {
thunk.api.post.mockReturnValue(Promise.resolve({ status: 403 }));
const result = await thunk.callThunk({ username: '123', password: '123' });
expect(thunk.dispatch).toHaveBeenCalledTimes(2);
expect(thunk.api.post).toHaveBeenCalled();
expect(result.payload).toBe('error');
});
});
// test('success login', async () => {
// const userValue = { username: '123', id: '1' };
// mockedAxios.post.mockReturnValue(Promise.resolve({ data: userValue }));
// const action = loginByUsername({ username: '123', password: '123' });
// const result = await action(dispatch, getState, undefined);
// console.log(result);
// expect(dispatch).toHaveBeenCalledWith(userActions.setAuthData(userValue));
// expect(dispatch).toHaveBeenCalledTimes(3);
// expect(mockedAxios.post).toHaveBeenCalled();
// expect(result.meta.requestStatus).toBe('fulfilled');
// expect(result.payload).toBe(userValue);
// });
// test('error login', async () => {
// mockedAxios.post.mockReturnValue(Promise.resolve({ status: 403 }));
// const action = loginByUsername({ username: '123', password: '123' });
// const result = await action(dispatch, getState, undefined);
// console.log(result);
// expect(dispatch).toHaveBeenCalledTimes(2);
// expect(mockedAxios.post).toHaveBeenCalled();
// expect(result.payload).toBe('error'); |
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2020 Mitchell Wasson
// This file is part of Weaklayer Sensor.
// Weaklayer Sensor 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/>.
const sensorRegex: RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
const tokenRegex: RegExp = /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/
export interface InstallResponse {
token: string
sensor: string
expiresAt: number
issuedAt: number
}
export function normalizeInstallResponse(installResponse: InstallResponse): InstallResponse {
return {
token: installResponse.token,
sensor: installResponse.sensor,
expiresAt: installResponse.expiresAt,
issuedAt: installResponse.issuedAt
}
}
export function isInstallResponse(data: any): data is InstallResponse {
const validToken: boolean = 'token' in data && typeof data.token === 'string' && tokenRegex.test(data.token)
if (!validToken) {
return false
}
const validSensorId: boolean = 'sensor' in data && typeof data.sensor === 'string' && sensorRegex.test(data.sensor)
if (!validSensorId) {
return false
}
const validExpiresAt: boolean = 'expiresAt' in data && typeof data.expiresAt === 'number' && Number.isInteger(data.expiresAt) && data.expiresAt >= 0
if (!validExpiresAt) {
return false
}
const validIssuedAt: boolean = 'issuedAt' in data && typeof data.issuedAt === 'number' && Number.isInteger(data.issuedAt) && data.issuedAt >= 0
if (!validExpiresAt) {
return false
}
return true
} |
<!DOCTYPE html>
<html>
<head>
<title>Infinite Tracker</title>
<style>
#map {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.plane-icon {
width: 24px;
height: 24px;
background-image: url('circle.png');
background-size: cover;
}
.atc-icon {
width: 24px;
height: 24px;
background-image: url('atc.png');
background-size: cover;
}
#refresh-button {
position: fixed;
top: 10px;
right: 10px;
background-color: #003563;
color: #fff;
border-color: #0088ff;
border-width: 1px;
border-radius: 5px;
padding: 10px 20px;
cursor: pointer;
}
#last-refresh-text {
position: fixed;
top: 20px;
right: 270px;
color: white;
}
#last-refresh-time {
position: fixed;
top: 20px;
right: 160px;
color: rgb(0, 190, 0);
}
.track-line {
position: absolute;
pointer-events: none;
border-bottom: 1px solid rgb(255,51,187);
border-bottom: 1px solid;
color: rgb(255,51,187);
background-color: rgb(255,51,187);
z-index: 1000;
}
.leaflet-popup-content-wrapper {
background: #fff;
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.leaflet-popup-content {
color: #333;
}
.leaflet-popup-close-button {
position: absolute;
top: 5px;
right: 5px;
color: #999;
}
.filters {
position: fixed;
bottom: 1px;
left: 0;
right: 0;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
background-color: rgba(255, 255, 255, 0.7);
border-radius: 5px;
}
.filters label,
.filters input {
margin: 0 5px;
border-radius: 5px;
}
.filters label {
margin-right: 5px;
height: 20%;
}
</style>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
</head>
<body>
<div id="map" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%;"></div>
<button id="refresh-button">Refresh Manually</button>
<div id="last-refresh-text">Last Refresh: </div>
<div id="last-refresh-time">N/A</div>
<div class="filters">
<label for="speed-min">Min Speed (Knots):</label>
<input type="number" id="speed-min" min="0" step="10">
<label for="speed-max">Max Speed (Knots):</label>
<input type="number" id="speed-max" min="0" step="10">
<label for="altitude-min">Min Altitude (Feet):</label>
<input type="number" id="altitude-min" min="0" step="1000">
<label for="altitude-max">Max Altitude (Feet):</label>
<input type="number" id="altitude-max" min="0" step="1000">
</div>
<script>
const apiKey = "16g9z0yzub3dszefdibss5455tytdhkr";
const sessionId = "df2a8d19-3a54-4ce5-ae65-0b722186e44c";
const aircraftApiUrl = `https://api.infiniteflight.com/public/v2/sessions/${sessionId}/flights?apikey=${apiKey}`;
const atcApiUrl = `https://api.infiniteflight.com/public/v2/sessions/${sessionId}/atc?apikey=${apiKey}`;
var map = L.map('map', {
preferCanvas: true,
layers: [
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
})
]
}).setView([0, 0], 2);
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
maxZoom: 19,
}).addTo(map);
var markerLayer = L.layerGroup().addTo(map);
const aircraftMarkers = {};
const aircraftTracks = {};
function roundToZeroDecimalPlaces(number) {
return Math.round(number);
}
function updateAircraftPositions() {
const lastRefreshTimeElement = document.getElementById('last-refresh-time');
const now = new Date();
const zuluTime = `${now.getUTCHours().toString().padStart(2, '0')}:${now.getUTCMinutes().toString().padStart(2, '0')}:${now.getUTCSeconds().toString().padStart(2, '0')}`;
lastRefreshTimeElement.textContent = ` ${zuluTime} ZULU`;
const speedMin = parseInt(document.getElementById('speed-min').value) || 0;
const speedMax = parseInt(document.getElementById('speed-max').value) || Number.MAX_SAFE_INTEGER;
const altitudeMin = parseInt(document.getElementById('altitude-min').value) || 0;
const altitudeMax = parseInt(document.getElementById('altitude-max').value) || Number.MAX_SAFE_INTEGER;
fetch(aircraftApiUrl)
.then(response => response.json())
.then(data => {
const updatedAircraftIds = [];
data.result.forEach(aircraft => {
const userId = aircraft.userId;
const existingMarker = aircraftMarkers[userId];
const planeIcon = L.divIcon({
className: 'plane-icon',
iconSize: [8, 8],
html: `<div></div>`
});
let marker;
if (existingMarker) {
marker = existingMarker;
marker.setLatLng([aircraft.latitude, aircraft.longitude]);
} else {
marker = L.marker([aircraft.latitude, aircraft.longitude], { icon: planeIcon });
marker.addTo(markerLayer);
aircraftMarkers[userId] = marker;
}
const username = aircraft.username ? aircraft.username : "No username";
const flightInfo = `
<strong>Username:</strong> ${username}<br>
<strong>Callsign:</strong> ${aircraft.callsign}<br>
<strong>Altitude:</strong> ${roundToZeroDecimalPlaces(aircraft.altitude)} feet<br>
<strong>Speed:</strong> ${roundToZeroDecimalPlaces(aircraft.speed)} knots`;
marker.bindPopup(flightInfo, { autoClose: false });
// Track logic
if (!aircraftTracks[userId]) {
aircraftTracks[userId] = [];
}
aircraftTracks[userId].push([aircraft.latitude, aircraft.longitude]);
if (aircraftTracks[userId].length > 1) {
if (!aircraftMarkers[userId + '_track']) {
aircraftMarkers[userId + '_track'] = L.polyline(aircraftTracks[userId], { color: 'green' }).addTo(markerLayer);
} else {
aircraftMarkers[userId + '_track'].setLatLngs(aircraftTracks[userId]);
}
}
// Apply filters
if (
aircraft.speed >= speedMin &&
aircraft.speed <= speedMax &&
aircraft.altitude >= altitudeMin &&
aircraft.altitude <= altitudeMax
) {
updatedAircraftIds.push(userId);
}
});
// Remove markers and tracks for aircraft that are no longer present or don't match filters
Object.keys(aircraftMarkers).forEach(key => {
if (!updatedAircraftIds.includes(key.split('_')[0])) {
map.removeLayer(aircraftMarkers[key]);
delete aircraftMarkers[key];
}
});
})
.catch(error => console.error('Error fetching aircraft data:', error));
}
function updateATCPositions() {
fetch(atcApiUrl)
.then(response => response.json())
.then(atcData => {
atcData.result.forEach(atc => {
const atcIcon = L.divIcon({
className: 'atc-icon',
iconSize: [24, 24],
html: `<div></div>`
});
const atcMarker = L.marker([atc.latitude, atc.longitude], { icon: atcIcon });
atcMarker.on('click', function () {
fetch(atisApiUrl.replace('{airportIcao}', atc.airportName))
.then(response => response.json())
.then(atisData => {
const atisPopup = `<strong>ATIS at ${atc.airportName}:</strong><br>${atisData.result}`;
atcMarker.bindPopup(atisPopup, { autoClose: false });
})
.catch(error => console.error('Error fetching ATIS data:', error));
});
markerLayer.addLayer(atcMarker);
});
})
.catch(error => console.error('Error fetching ATC data:', error));
}
updateAircraftPositions();
updateATCPositions();
document.getElementById('refresh-button').addEventListener('click', function () {
updateAircraftPositions();
});
document.getElementById('speed-min').addEventListener('input', function () {
updateAircraftPositions();
});
document.getElementById('speed-max').addEventListener('input', function () {
updateAircraftPositions();
});
document.getElementById('altitude-min').addEventListener('input', function () {
updateAircraftPositions();
});
document.getElementById('altitude-max').addEventListener('input', function () {
updateAircraftPositions();
});
setInterval(updateAircraftPositions, 1000);
</script>
</body>
</html> |
.TH jfs_fscklog 8 "October 28, 2002" " " "Extract/Display JFS fsck Log"
.SH NAME
.B jfs_fscklog
\- extract a JFS fsck service log into a file and/or format and display the extracted file
.SH SYNOPSIS
.B jfs_fscklog
[
.B -d
] [
.BI -e " device"
] [
.BI -f " output.file"
] [
.B -p
] [
.B -V
]
.SH DESCRIPTION
.PP
.B jfs_fscklog
with option
.BI -e " device"
extracts the contents of either the most recent or immediately prior
(specified with option
.BR -p )
JFS fsck service log from the specified device, and writes the output to
a file. The file name may be specified with the
.B -f
option, or the default file name is
.IR <pwd>fscklog.new "."
If the
.B -p
option is used, the default file name is
.IR <pwd>fscklog.old "."
.PP
.B jfs_fscklog
with option
.B -d
formats and displays the contents of the extracted file.
.PP
.B jfs_fscklog
with options
.B -d
and
.BI -e " device"
extracts and displays the JFS fsck service log.
.SH OPTIONS
.TP
.BI \-d
Format and display a previously extracted JFS fsck service log.
.TP
.BI \-e " device"
Extract the JFS fsck service log from
.I device
and store it in a file.
.RI ( device
is the special file name corresponding to the actual device from which the fsck log will be extracted (e.g.
.BR /dev/hdb1 " )). "
.TP
.BI \-f " file.name"
Specify the file name, overriding the default file name. When used with
.B -e
.IR device ,
file.name specifies the name of the file into which the JFS fsck log will be extracted.
When used with
.BR -d ,
file.name specifies the name of the extracted file whose contents will be formatted and displayed.
.RS
.LP
.IR file.name " must be 127 characters or less in length."
.LP
.IR file.name " will be created in the present working directory unless it is fully qualified."
.RE
.TP
.BI \-p
Extract the prior log (as opposed to the most recent log).
.TP
.BI \-V
Print version information and exit (regardless of any other chosen options).
.SH EXAMPLES
.LP
Extract the most recent JFS fsck log on /dev/hda5 into
.IR <pwd>fscklog.new :
.IP
.B jfs_fscklog -e /dev/hda5
.IP
.LP
Extract the most recent JFS fsck log on /dev/hdb3 into
.IR /temp/l9651107.log :
.IP
.B jfs_fscklog -e /dev/hdb3 -f /temp/l9651107.log
.IP
.LP
Display the JFS fsck log that was extracted into
.IR /temp/l9651107.log :
.IP
.B jfs_fscklog -d -f /temp/l9651107.log
.IP
.LP
Extract and display the previous JFS fsck log from /dev/hda8:
.IP
.B jfs_fscklog -e /dev/hda8 -d -p
.IP
.SH "REPORTING BUGS"
.PP
If you find a bug in
.B JFS
or
.BR jfs_fscklog,
please report it via the bug tracking system ("Report Bugs" section) of the JFS project web site:
.nf
http://jfs.sourceforge.net/
.fi
.PP
Please send as much pertinent information as possible, including any
.B jfs_fscklog
error messages and the complete output of running
.B jfs_fsck
with the
.B \-v
option on the JFS device.
.SH SEE ALSO
.BR jfs_fsck (8),
.BR jfs_mkfs (8),
.BR jfs_tune (8),
.BR jfs_logdump (8),
.BR jfs_debugfs (8)
.SH AUTHOR
.nf
Barry Arndt (barndt@us.ibm.com)
.fi
.B jfs_fscklog
is maintained by IBM.
.nf
See the JFS project web site for more details:
http://jfs.sourceforge.net/
.fi |
import React, { useState, useEffect } from 'react';
import { Button, Card, Col, Container, Form, Row } from 'react-bootstrap';
import FlashCards from '../components/FlashCards';
import { getPracticeCards, getPracticeModeNames } from '../utils/cards';
import { getLanguageNames, getWordTypeNames } from '../utils/language';
import { getPaddingStyle } from '../utils/style';
import { getUserProfile } from '../utils/user';
const DEFAULT_PRACTICE_MODE_ID = "1";
const NUM_CARDS_OPTIONS = [10, 25, 50];
const NUM_CARDS_DEFAULT = 25;
const userNameStyle = {
fontWeight: "700",
fontSize: "large"
}
export default function PracticeCards(props) {
const [loadedUserprofile, setLoadedUserprofile] = useState(false);
const [languageId, setLanguageId] = useState(0);
const [languageIds, setLanguageIds] = useState([]);
const [languageNamesMap, setLanguageNamesMap] = useState({});
const [practiceModeId, setPracticeModeId] = useState(DEFAULT_PRACTICE_MODE_ID);
const [practiceModeNamesMap, setPracticeModeNamesMap] = useState({});
const [numCards, setNumCards] = useState(NUM_CARDS_DEFAULT);
const [isPracticing, setIsPracticing] = useState(false);
const [cards, setCards] = useState([]);
const [typeNamesMap, setTypeNamesMap] = useState({});
const [cardIdx, setCardIdx] = useState(0);
const [showTranslation, setShowTranslation] = useState(false);
useEffect(() => {
if (!loadedUserprofile) {
getUserProfile(props.userSecret).then(data => {
setLoadedUserprofile(true)
setLanguageId(data.defaultLanguageId);
setLanguageIds(data.languageIds);
getLanguageNames(props.userSecret).then(data => setLanguageNamesMap(data));
getPracticeModeNames(props.userSecret).then(data => setPracticeModeNamesMap(data));
getWordTypeNames(props.userSecret).then(data => setTypeNamesMap(data));
});
}
});
const startPracticing = () => {
const config = {practiceModeId: practiceModeId, numCards: numCards};
getPracticeCards(props.userSecret, languageId, config).then(cards => {
if (cards.length > 0) {
setCards(cards);
setIsPracticing(true);
}
})
};
const flashCards = cards.length === 0 ? <Container/>
: <FlashCards userSecret={props.userSecret} languageId={languageId} cards={cards} typeNamesMap={typeNamesMap} resetCards={() => {setCards([]); setIsPracticing(false)}} />;
return (
<Container>
<Row>
<Col xs={12} style={getPaddingStyle(20)} />
</Row>
<Row>
<Col xs={6} md={2}>
<Form.Select value={languageId} onChange={(event) => setLanguageId(event.target.value)} >
{languageIds.map(
id => <option key={id} value={id}>{languageNamesMap[id]}</option>
)}
</Form.Select>
</Col>
<Col xs={6} md={2}>
<Form.Select value={practiceModeId} onChange={(event) => setPracticeModeId(event.target.value)} >
{Object.keys(practiceModeNamesMap).map(
id => <option key={id} value={id}>{practiceModeNamesMap[id]}</option>
)}
</Form.Select>
</Col>
<Col xs={12} className="d-block d-sm-none" style={getPaddingStyle(10)} />
<Col xs={6} md={2}>
<Form.Select value={numCards} onChange={(event) => setNumCards(event.target.value)} >
{NUM_CARDS_OPTIONS.map(
n => <option key={n} value={n}>{n} Cards</option>
)}
</Form.Select>
</Col>
<Col xs={6} md={2}>
<Button variant="primary" disabled={isPracticing} onClick={startPracticing} >
Practice
</Button>
</Col>
</Row>
{flashCards}
</Container>
);
} |
SET SERVEROUTPUT ON;
SET VER OFF;
CREATE OR REPLACE PROCEDURE greeting (
pl_saluation VARCHAR2 := 'Hello',
pl_name VARCHAR2
)
AS
BEGIN
DBMS_OUTPUT.PUT_LINE(pl_saluation || CHR(32) || pl_name);
END;
/
CREATE OR REPLACE PROCEDURE
PRINT_TWO_NUMBERS(pl_greater_number NUMBER,
pl_lesser_number NUMBER)
AS BEGIN
DBMS_OUTPUT.PUT_LINE(pl_greater_number || ' is greater than '
|| pl_lesser_number || '.');
END;
/
CREATE OR REPLACE PROCEDURE
FIND_GREATEST_NUMBER(pl_number_one NUMBER,
pl_number_two NUMBER)
AS BEGIN
IF pl_number_one > pl_number_two THEN
print_two_numbers(pl_number_one, pl_number_two);
ELSIF pl_number_two > pl_number_one THEN
print_two_numbers(pl_number_two, pl_number_one);
ELSE
DBMS_OUTPUT.PUT_LINE('The two numbers are equal!');
END IF;
END;
/
CALL find_greatest_number(1, 2);
CALL find_greatest_number(pl_number_two => 1, pl_number_one => 2);
CALL find_greatest_number(2, pl_number_two => 4);
CREATE OR REPLACE PROCEDURE
insert_into_region(pl_region_name regions.region_name%TYPE,
pl_region_id regions.region_id%TYPE)
AS BEGIN
INSERT INTO
regions(region_id, region_name)
VALUES
(pl_region_id, pl_region_name);
END;
/
CREATE OR REPLACE PROCEDURE
update_region(pl_region_id regions.region_id%TYPE,
pl_region_name regions.region_name%TYPE)
AS BEGIN
UPDATE
regions
SET
region_name = pl_region_name
WHERE
region_id = pl_region_id;
END;
/
CREATE OR REPLACE PROCEDURE
delete_from_region(pl_region_id regions.region_id%TYPE)
AS BEGIN
DELETE FROM
regions
WHERE
region_id = pl_region_id;
END;
/
SELECT
*
FROM
regions;
CALL delete_from_region(1);
CALL insert_into_region('Americas', 1);
CALL update_region(1, 'Europe');
SELECT
*
FROM
regions;
CREATE OR REPLACE PROCEDURE
find_location(pl_location_id IN hr.locations.location_id%TYPE,
pl_location OUT hr.locations%ROWTYPE)
AS BEGIN
SELECT
*
INTO
pl_location
FROM
hr.locations
WHERE
location_id = pl_location_id;
END;
/
--
--PROMPT p_location_id ACCEPT 'Please enter a location ID: ';
--
--DECLARE
-- v_location_id hr.locations.location_id%TYPE;
-- v_location hr.locations%ROWTYPE;
--BEGIN
-- v_location_id := '&p_location_id';
--
-- find_location(v_location_id, v_location);
-- DBMS_OUTPUT.PUT_LINE('Found location: ' || v_location.location_id
-- || CHR(10) || 'Address: ' || v_location.street_address
-- || CHR(10) || 'Country: ' || v_location.country_id);
--EXCEPTION
-- WHEN OTHERS THEN
-- DBMS_OUTPUT.PUT_LINE('Error: No Location Found!');
--END;
--/
CREATE OR REPLACE FUNCTION
find_department_salary_average(
pl_department_name hr.departments.department_name%TYPE)
RETURN
NUMBER
AS
v_average NUMBER;
BEGIN
SELECT
avg(salary)
INTO
v_average
FROM
hr.departments d
INNER JOIN
hr.employees e
ON e.department_id = d.department_id
WHERE
UPPER(department_name) = UPPER(pl_department_name);
RETURN v_average;
END;
/
CREATE OR REPLACE FUNCTION
find_employees_by_hire_date(pl_hire_date hr.employees.hire_date%TYPE)
RETURN
NUMBER
IS
v_count_employees NUMBER;
BEGIN
SELECT
count(employee_id)
INTO
v_count_employees
FROM
hr.employees
WHERE
hire_date > pl_hire_date;
return v_count_employees;
END;
/
CREATE OR REPLACE PROCEDURE
test_find_employee_by_date(v_hire_date hr.employees.hire_date%TYPE)
AS
v_count_employees NUMBER;
BEGIN
v_count_employees := find_employees_by_hire_date(v_hire_date);
DBMS_OUTPUT.PUT_LINE(v_count_employees || ' were hired after ' || v_hire_date || '.');
END;
/
PROMPT p_hire_date ACCEPT 'Please enter a date: ';
CALL test_find_employee_by_date('&p_hire_date');
--CALL greeting(pl_name => 'Kyle Galway', pl_saluation => 'Go Away');
--
--BEGIN
-- greeting('Hello there', 'Kyle Galway');
--END;
--/ |
import { ViewIcon } from "@chakra-ui/icons";
import {
IconButton,
useDisclosure,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalFooter,
ModalBody,
ModalCloseButton,
Input,
Button,
FormLabel,
FormControl,
Image,
Text,
} from "@chakra-ui/react";
import React from "react";
const ProfileModal = ({ user, children }) => {
const { isOpen, onOpen, onClose } = useDisclosure();
return (
<>
{children ? (
<span onClick={onOpen}>{children}</span>
) : (
<IconButton
display={{ base: "flex" }}
icon={<ViewIcon />}
onClick={onOpen}
/>
)}
<Modal size={"lg"} isCentered isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent h={"400px"}>
<ModalHeader
fontSize={"40px"}
fontFamily={"Work sans"}
display={"flex"}
justifyContent={"center"}
>
{user.name}
</ModalHeader>
<ModalCloseButton />
<ModalBody
display={"flex"}
flexDir={"column"}
alignItems={"center"}
justifyContent={"center"}
pb={6}
gap={5}
>
<Image
borderRadius={"full"}
src={user.pic}
alt={user.name}
boxSize={"100px"}
/>
<Text
fontSize={{ base: "20px", md: "25px" }}
fontFamily={"work sans"}
>
Email: {user.email}
</Text>
</ModalBody>
<ModalFooter>
<Button colorScheme="blue" onClick={onClose}>
Close
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</>
);
};
export default ProfileModal; |
import React from 'react'
import styles from './Create.module.scss'
import { Exercise } from './Exercise'
export const Create_html = ({
setOpenCreate,
setOpenIcon,
setOpenExercises,
titleWorkout,
setTitleWorkout,
iconWorkout,
setIconWorkout,
colorWorkout,
setColorWorkout,
createWorkout,
listExercises,
setListExercises,
setOpenEditExercise,
setDetailExercise,
}) => {
return (
<>
<div className={styles.container}>
<div className={styles.miniContainer}>
<div className={styles.header}>
<div onClick={() => setOpenCreate(false)} className={styles.back}>
<div className='icon-prev' />
</div>
<h2>Create workout</h2>
</div>
<div className={styles.title}>
<div onClick={() => setOpenIcon(true)} className={styles.logo}>
{iconWorkout}
</div>
<form className={styles.form}>
<div className={styles.formBody}>
<input
type='text'
id='inputWorkout'
placeholder='Title workout'
onChange={e => setTitleWorkout(e.target.value)}
value={titleWorkout}
/>
<button onClick={() => setTitleWorkout('')} type='reset'>
<div className='icon-cancel' />
</button>
</div>
</form>
</div>
<h3 className={styles.titleColor}>Color training in calendar</h3>
<div className={styles.colors}>
<div
onClick={e => {
setColorWorkout(getComputedStyle(e.target).backgroundColor)
// console.log(getComputedStyle(e.target).backgroundColor);
// console.log(colorWorkout.includes(getComputedStyle(e.target).backgroundColor));
// colorWorkout.includes(getComputedStyle(e.target).backgroundColor) ?
// e.target.classList.contains('circ_1') : e.target.classList.remove('active')
}}
className={styles.circ_1}
/>
<div
onClick={e =>
setColorWorkout(getComputedStyle(e.target).backgroundColor)
}
className={styles.circ_2}
/>
<div
onClick={e =>
setColorWorkout(getComputedStyle(e.target).backgroundColor)
}
className={styles.circ_3}
/>
<div
onClick={e =>
setColorWorkout(getComputedStyle(e.target).backgroundColor)
}
className={styles.circ_4}
/>
<div
onClick={e =>
setColorWorkout(getComputedStyle(e.target).backgroundColor)
}
className={styles.circ_5}
/>
<div
onClick={e =>
setColorWorkout(getComputedStyle(e.target).backgroundColor)
}
className={styles.circ_6}
/>
<div
onClick={e =>
setColorWorkout(getComputedStyle(e.target).backgroundColor)
}
className={styles.circ_7}
/>
</div>
<div className={styles.createExercises}>
<h3>Exercises</h3>
<div
onClick={() => setOpenExercises(true)}
className={styles.addExercise}
>
<h4>Add</h4>
<div className={styles.logo}></div>
</div>
</div>
</div>
<div className={styles.listExerxises}>
{listExercises.length === 0 ? (
<div className={styles.advice}>
<h5>Add first exercise</h5>
</div>
) : (
listExercises.map((exercise, index, listExercises) => (
<Exercise
key={index}
exercise={exercise}
setOpenEditExercise={setOpenEditExercise}
setDetailExercise={setDetailExercise}
listExercises={listExercises}
/>
))
)}
</div>
</div>
<div className={styles.btn_container}>
<button onClick={e => createWorkout(e)} className={styles.btn_create}>
Create workout
</button>
</div>
</>
)
} |
package report;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import infoexchange.EnqReplies;
import infoexchange.Enquiries;
import infoexchange.EnquiriesArray;
import users.Staff;
import users.Student;
import users.Users;
import utils.InputInt;
/**
* The EnquiriesReport class implements the Report interface.
* It generates the enquiries report for Staff and Camp Comm
*
* @author Kok Chin Yi
* @version 1.0
*/
public class EnquiriesReport implements Report {
private Staff userStaff;
private Student userStudent;
private EnquiriesArray enquiriesArray;
private static String folderPath = "EnquiriesReport\\";
private ArrayList<String> createdCamps;
private Scanner sc = new Scanner(System.in);
/**
* The `EnquiriesReport` constructor is responsible for initializing the
* `EnquiriesReport` object.
* It takes two parameters: `user` of type `Users` and `enquiriesArray` of type
* `EnquiriesArray`.
*
* @param user
* @param enquiriesArray
*/
public EnquiriesReport(Users user, EnquiriesArray enquiriesArray) {
if (user instanceof Staff) {
userStaff = (Staff) user;
this.createdCamps = userStaff.getCampsInCharge();
} else if (user instanceof Student && ((Student) user).IsCampComm()) {
userStudent = (Student) user;
this.createdCamps = new ArrayList<String>();
this.createdCamps.add(userStudent.getCampCommitteeRole().getCampName());
} else {
System.out.println("You are not allowed to access Enquiries Report!");
return;
}
this.enquiriesArray = enquiriesArray;
}
/**
* The function generates a report for a selected camp, displaying a list of
* created camps and
* allowing the user to choose one.
*/
public void generateReport() {
if (createdCamps.size() == 0) {
System.out.println("You have not created any camps!");
return;
}
System.out.println("Select a camp to generate Enquiries Report for:");
for (String camp : createdCamps) {
System.out.println(createdCamps.indexOf(camp) + 1 + ". " + camp);
}
int choice;
while (true) {
try {
System.out.printf("Enter choice (Key in -1 to leave): ");
choice = InputInt.nextInt(sc);
if (choice == -1) {
return;
}
if (choice > createdCamps.size() + 1 || choice <= 0)
throw new NumberFormatException();
break;
} catch (NumberFormatException e) {
System.out.println("Invalid choice, try again! (Key in -1 to leave)");
}
}
String selectedCamp = createdCamps.get(--choice);
generateEnquriesReport(selectedCamp);
System.out.println("Generating report for " + selectedCamp + "...");
System.out.println("Find the report in EnquiriesReport");
}
/**
* The function generates a CSV report of enquiries and their replies for a
* specific camp.
*
* @param fileName The fileName parameter is a String that represents the name
* of the camp for
* which the enquiries report is being generated.
*/
private void generateEnquriesReport(String fileName) {
File file = new File(folderPath + fileName + "_EnquiriesReport.csv");
file.getParentFile().mkdirs(); // Ensure the parent directories exist
int i, j;
i = j = 0;
try (FileWriter csvWriter = new FileWriter(file)) {
for (Enquiries enquiry : enquiriesArray.getEnquiries()) {
if (enquiry.getCampName().equals(fileName)) {
i++;
csvWriter.append("Sender,");
csvWriter.append(enquiry.getSender() + "\n");
csvWriter.append("Enquiry,");
csvWriter.append(enquiry.getEnquiry() + "\n");
j = 0;
for (EnqReplies reply : enquiriesArray.getReplies()) {
if (reply.getEnquiryID().equals(enquiry.getEnquiryID())) {
j++;
csvWriter.append("Reply by,");
csvWriter.append(reply.getReplyCreator() + "\n");
csvWriter.append("Reply,");
csvWriter.append(reply.getReplyString() + "\n");
csvWriter.append("\n");
}
}
// No replies for the enquiry
if (j == 0) {
csvWriter.append("There are 0 replies for this enquiry");
csvWriter.append("\n");
}
}
}
// No Enquiries
if (i == 0)
csvWriter.append("There are 0 enquiries for this Camp");
csvWriter.append("\n");
csvWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
import { ActivityIndicator, Image, ScrollView, Text, View } from "react-native"
import { useEffect, useState } from "react";
import MyStyle from "../../styles/MyStyle";
import Apis, { endpoints } from "../../Apis";
import moment from "moment";
import { TouchableOpacity } from "react-native";
const Home = ({route, navigation}) => {
const [houses, setHouses] = useState(null);
const cateId = route.params?.cateId;
useEffect(()=>{
let url = endpoints['houses'];
if(cateId !== undefined&&cateId !== ""){
url = `${url}?category_id=${cateId}`;
}
const loadHouse = async () => {
const res = await Apis.get(url);//?category_id=
setHouses(res.data.results)
}
loadHouse();
},[cateId]);
const goToRoom = (houseId) => {
navigation.navigate("Room", {"houseId": houseId})
}
return <View style={MyStyle.container}>
<Text style={[MyStyle.address, {textAlign: "center"}]}>DANH SÁCH NHÀ TRỌ</Text>
{houses===null?<ActivityIndicator color={'green'}/>:<ScrollView>
{houses.map(c=>(
<View key={c.id} style={[MyStyle.row, {padding: 5}]}>
<View>
<TouchableOpacity onPress={()=>goToRoom(c.id)}>
<Image style={{width: 100, height: 100}} source={{uri: c.image}}/>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={()=>goToRoom(c.id)}>
<Text style={MyStyle.title}>{c.address}</Text>
<Text style={{marginLeft: 5}}>{moment(c.created_date).fromNow()}</Text>
</TouchableOpacity>
</View>
</View>
))}
</ScrollView>}
</View>
}
export default Home; |
#include <stdio.h>
#include <stdlib.h>
typedef struct Process {
char name[20];
int arrival_time;
int execution_time;
int priority;
} Process;
void sjf_with_preemption(Process processes[], int n, int time_slice, FILE *output_file) {
int current_time = 0;
Process* ready_queue[n];
int front = 0, rear = 0;
Process* current_process = NULL;
while (current_time >= 0) {
for (int i = 0; i < n; i++) {
if (processes[i].arrival_time == current_time) {
ready_queue[rear] = &processes[i];
rear++;
}
}
int shortest_index = -1;
for (int i = front; i < rear; i++) {
if (current_process == NULL || ready_queue[i]->execution_time < current_process->execution_time) {
shortest_index = i;
current_process = ready_queue[i];
}
}
if (current_process != NULL) {
if (time_slice > 0 && current_process->execution_time > time_slice) {
// Preempt the current process if using time slice
fprintf(output_file, "Executing %s for time slice %d\n", current_process->name, time_slice);
current_time += time_slice;
current_process->execution_time -= time_slice;
} else {
// Process completes
fprintf(output_file, "Executing %s for %d\n", current_process->name, current_process->execution_time);
current_time += current_process->execution_time;
current_process->execution_time = 0;
current_process = NULL;
front++;
}
} else {
current_time++;
}
int all_terminated = 1;
for (int i = 0; i < n; i++) {
if (processes[i].execution_time > 0) {
all_terminated = 0;
break;
}
}
if (all_terminated) {
break;
}
}
}
float calculate_average_turnaround_time(Process processes[], int n) {
float total_turnaround_time = 0;
for (int i = 0; i < n; i++) {
total_turnaround_time += processes[i].execution_time;
}
return total_turnaround_time / n;
}
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
Process processes[n];
for (int i = 0; i < n; i++) {
printf("Enter process name, arrival time, execution time, and priority for Process %d: ", i + 1);
scanf("%s %d %d %d", processes[i].name, &processes[i].arrival_time, &processes[i].execution_time, &processes[i].priority);
}
int time_slice;
printf("Enter the time slice (quantum) or 0 for no pre-emption: ");
scanf("%d", &time_slice);
char output_filename[100];
printf("Enter the output filename: ");
scanf("%s", output_filename);
FILE *output_file = fopen(output_filename, "w");
if (!output_file) {
printf("Error opening output file.\n");
return 1;
}
fprintf(output_file, "Execution Log:\n");
sjf_with_preemption(processes, n, time_slice, output_file);
float avg_turnaround_time = calculate_average_turnaround_time(processes, n);
fprintf(output_file, "Average Turnaround Time: %.2f\n", avg_turnaround_time);
fclose(output_file);
return 0;
} |
package handlers
import (
"net/http"
authError "github.com/MiracleX77/CN334_Animix_Store/auth/errors"
"github.com/MiracleX77/CN334_Animix_Store/auth/models"
"github.com/MiracleX77/CN334_Animix_Store/auth/usecases"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
)
type authHttpHandler struct {
authUsecase usecases.AuthUsecase
}
func NewAuthHttpHandler(authUsecase usecases.AuthUsecase) AuthHandler {
return &authHttpHandler{
authUsecase: authUsecase,
}
}
func (h *authHttpHandler) Register(c echo.Context) error {
reqBody := new(models.RegisterData)
if err := c.Bind(reqBody); err != nil {
log.Errorf("Error binding request body: %v", err)
return response(c, http.StatusBadRequest, "Bad request", nil)
}
if err := c.Validate(reqBody); err != nil {
log.Errorf("Error validating request body: %v", err)
return response(c, http.StatusBadRequest, "Bad request", nil)
}
if err := h.authUsecase.CheckData(reqBody); err != nil {
log.Errorf("Error validating request body: %v", err)
if _, ok := err.(*authError.ServerInternalError); ok {
return response(c, http.StatusInternalServerError, "Server Internal Error", nil)
} else {
return response(c, http.StatusBadRequest, err.Error(), nil)
}
}
if err := h.authUsecase.RegisterDataProcessing(reqBody); err != nil {
return response(c, http.StatusInternalServerError, "Processing Data failed", nil)
}
return response(c, http.StatusOK, "Success", nil)
}
func (h *authHttpHandler) Login(c echo.Context) error {
reqBody := new(models.LoginData)
if err := c.Bind(reqBody); err != nil {
log.Errorf("Error binding request body: %v", err)
return response(c, http.StatusBadRequest, "Bad request", nil)
}
if err := c.Validate(reqBody); err != nil {
log.Errorf("Error validating request body: %v", err)
return response(c, http.StatusBadRequest, "Bad request", nil)
}
token, err := h.authUsecase.LoginDataProcession(reqBody)
if err != nil {
log.Errorf("Error login: %v", err)
if _, ok := err.(*authError.ServerInternalError); ok {
return response(c, http.StatusInternalServerError, "Server Internal Error", nil)
} else {
return response(c, http.StatusBadRequest, err.Error(), nil)
}
}
return response(c, http.StatusOK, "Success", token)
} |
import { InformationCircleIcon } from '@heroicons/react/20/solid';
export default function Tifoid() {
return (
<div className="relative bg-white px-6 py-32 lg:px-8">
<div
className="absolute inset-x-0 -top-40 -z-9 transform-gpu overflow-hidden blur-3xl sm:-top-80"
aria-hidden="true"
>
<div
className="relative left-[calc(50%-11rem)] aspect-[1155/678] w-[36.125rem] -translate-x-1/2 rotate-[30deg] bg-gradient-to-tr from-[#80ff89] to-[#ff80b5] opacity-30 sm:left-[calc(50%-30rem)] sm:w-[72.1875rem]"
style={{
clipPath:
'polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)',
}}
/>
</div>
<div className="mx-auto max-w-3xl text-base leading-7 text-gray-700">
<figure className="mt-16">
<img
className="aspect-video rounded-xl bg-gray-50 object-cover"
src="/img/disease/tifoid01.png"
alt=""
/>
<figcaption className="mt-4 flex gap-x-2 text-sm leading-6 text-gray-500">
<InformationCircleIcon className="mt-0.5 h-5 w-5 flex-none text-gray-300" aria-hidden="true" />
Ilustrasi tifoid pada orang dewasa
</figcaption>
</figure>
<p className="mt-14 text-base font-semibold leading-7 text-green-600">#Tifoid</p>
<h1 className="mt-2 text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">Tifoid</h1>
<div className="mt-10 max-w-2xl">
<p>
Tifus (tipes) atau demam tifoid adalah penyakit yang disebabkan oleh infeksi bakteri Salmonella typhii.
Tifus dapat menular dengan cepat, umumnya melalui konsumsi makanan atau minuman yang sudah terkontaminasi
tinja yang mengandung bakteri Salmonella typhii. Pada kasus yang jarang terjadi, penularan tifus dapat
terjadi karena terpapar urine yang sudah terinfeksi bakteri Salmonella typhii.
</p>
<h3 className="mt-6 text-xl leading-8">Kasus Tifus di Indonesia</h3>
<p className="mt-2">
Hampir 100.000 penduduk Indonesia terjangkit penyakit tifus tiap tahunnya. Oleh sebab itu, penyakit tifus
dinyatakan sebagai penyakit endemik dan masalah kesehatan serius di dalam negeri. Sanitasi yang buruk dan
keterbatasan akses air bersih, diyakini merupakan penyebab utama berkembangnya penyakit tifus. Selain itu,
anak-anak lebih sering terserang tifus karena belum sempurnanya sistem kekebalan tubuh. Jika tidak segera
ditangani dengan baik, diperkirakan tiap satu dari lima orang akan meninggal karena tifus. Selain itu,
tifus juga berisiko menimbulkan komplikasi. Penanganan penyakit tifus adalah melalui pemberian obat
antibiotik. Pengobatan bisa dilakukan di rumah atau perlu dilakukan di rumah sakit, akan bergantung pada
tingkat keparahan penyakit.
</p>
<h3 className="mt-6 text-xl leading-8">Vaksinasi Tifoid</h3>
<p className="mt-2">
Di Indonesia, vaksin tifoid yang diberikan untuk mencegah tifus termasuk imunisasi yang dianjurkan oleh
pemerintah, namun belum termasuk ke dalam kategori wajib. Vaksin tifoid diberikan kepada anak-anak berusia
lebih dari 2 tahun, dan diulang tiap tiga tahun. Seperti vaksin-vaksin lainnya, vaksin tifoid tidak menjamin
perlindungan 100 persen terhadap infeksi tifus. Anak yang sudah diimunisasi tifoid pun tetap dapat
terinfeksi, namun tingkat infeksinya tidak seberat pada pasien yang belum mendapat vaksin tifoid.
Vaksinasi juga sangat dianjurkan bagi orang yang ingin bekerja atau bepergian ke daerah yang banyak kasus
penyebaran tifus. Tindakan pencegahan lain yang perlu dilakukan adalah memerhatikan makanan dan minuman yang
akan dikonsumsi, misalnya dengan menghindari makan di tempat terbuka yang mudah terpapar bakteri.
</p>
<h3 className="mt-6 text-xl leading-8">Gejala Tifus</h3>
<p className="mt-2">
Rubella atau sering disebut dengan campak Jerman adalah infeksi virus rubella yang menyebabkan kemunculan
bintik-bintik ruam merah di kulit. Virus penyebab Campak Jerman juga menyebabkan kelenjar getah bening leher
dan belakang telinga membengkak.<br />
Tanda-tanda dan gejala rubella seringkali sangat ringan sehingga sulit untuk diperhatikan, terutama pada
anak-anak. Gejala campak Jerman pada anak biasanya mulai muncul sekitar 2-3 minggu setelah tubuh mulai
terpapar virus. Berikut gejalanya:
</p>
<ul role="list" className="my-4 max-w-xl space-y-2 text-gray-600 list-disc pl-6">
<li>Demam yang meningkat secara bertahap tiap hari hingga mencapai 39°C-40°C. Demam juga akan lebih tinggi pada malam hari</li>
<li>Nyeri otot</li>
<li>Sakit kepala</li>
<li>Merasa tidak enak badan</li>
<li>Pembesaran ginjal dan hati</li>
<li>Kelelahan dan lemas</li>
<li>Berkeringat</li>
<li>Batuk kering</li>
<li>Penurunan berat badan</li>
<li>Sakit perut</li>
<li>Kehilangan nafsu makan</li>
<li>Anak-anak sering mengalami diare, sementara orang dewasa cenderung mengalami konstipasi</li>
<li>Muncul ruam pada kulit berupa bintik-bintik kecil berwarna merah muda</li>
<li>Linglung, merasa tidak tahu sedang berada di mana dan apa yang sedang terjadi di sekitar dirinya</li>
</ul>
<p className="mt-2">
Gejala tifus berkembang dari minggu ke minggu dengan ciri-ciri sebagai berikut:
</p>
<ul role="list" className="my-4 max-w-xl space-y-4 text-gray-600 list-decimal pl-6">
<li>
<strong>Minggu ke-1.</strong>Gejala-gejala awal yang patut diperhatikan, khususnya terkait perkembangan
suhu badan penderita adalah:
<ul className="my-2 max-w-xl space-y-4 text-gray-600 list-disc pl-6">
<li>Demam yang awalnya tidak tinggi, kemudian meningkat secara bertahap hingga mencapai 39-40°C. Pada minggu pertama, suhu tubuh dapat naik atau turun</li>
<li>Sakit kepala</li>
<li>Lemas dan tidak enak badan</li>
<li>Batuk kering</li>
</ul>
</li>
<li>
<strong>Minggu ke-2.</strong>Jika tidak segera ditangani, pasien akan memasuki stadium kedua dengan gejala:
<ul className="my-2 max-w-xl space-y-4 text-gray-600 list-disc pl-6">
<li>Demam tinggi yang masih berlanjut dan cenderung memburuk di malam hari, disertai denyut nadi yang lambat</li>
<li>Muncul bintik-bintik yang berwarna seperti bunga mawar di daerah perut dan dada</li>
<li>Mengigau</li>
<li>Sakit perut</li>
<li>Diare atau sembelit parah</li>
<li>Tinja umumnya berwarna kehijauan</li>
<li>Perut kembung akibat pembengkakan hati dan empedu</li>
</ul>
</li>
<li>
<strong>Minggu ke-3.</strong>Suhu tubuh menurun pada akhir minggu ketiga. Jika tidak ditangani, komplikasi bisa muncul pada tahap ini, berupa:
<ul className="my-2 max-w-xl space-y-4 text-gray-600 list-disc pl-6">
<li>Perdarahan pada usus</li>
<li>Pecahnya usus</li>
</ul>
</li>
<li>
<strong>Minggu ke-4.</strong>Demam tifoid secara berangsur-angsur akan turun. Namun tetap perlu segera
ditangani agar tidak muncul gejala-gejala lain atau menyebabkan komplikasi yang membahayakan nyawa.
Pada sebagian kasus, gejala dapat kembali muncul dua minggu setelah demam reda<br />
Segera konsultasikan kepada dokter jika mengalami demam tinggi dan beberapa gejala di atas. Ingatlah bahwa
walaupun telah menerima vaksin atau imunisasi, seseorang masih berisiko menderita tifus. Pemeriksaan juga
sebaiknya dilakukan jika terserang demam setelah berkunjung ke tempat dengan kasus penyebaran tifus yang
tinggi.
</li>
</ul>
<figure className="mt-16">
<img
className="aspect-video rounded-xl bg-gray-50 object-cover"
src="/img/disease/tifoid02.png"
alt=""
/>
<figcaption className="mt-4 flex gap-x-2 text-sm leading-6 text-gray-500">
<InformationCircleIcon className="mt-0.5 h-5 w-5 flex-none text-gray-300" aria-hidden="true" />
Ilustrasi tifoid pada anak
</figcaption>
</figure>
<h3 className="mt-6 text-xl leading-8">Penyebab Tifus</h3>
<p className="mt-2">
Tifus disebabkan oleh bakteri Salmonella typhii yang masuk ke dalam usus manusia melalui makanan atau minuman
yang terkontaminasi bakteri tersebut, hingga berkembang biak di saluran pencernaan. Gejala-gejala seperti
demam, sakit perut, sembelit, atau diare akan timbul ketika bakteri ini berkembang biak di
saluran pencernaan.<br />
Beberapa faktor risiko penyakit tifus, di antaranya:
</p>
<ul role="list" className="my-4 max-w-xl space-y-2 text-gray-600 list-disc pl-6">
<li>Sanitasi buruk. Di negara seperti Indonesia, penyebaran bakteri Salmonella typhii biasanya terjadi
melalui konsumsi air yang terkontaminasi tinja yang yang mengandung bakteri Salmonella typhii, juga dari
makanan yang dicuci dengan menggunakan air yang terkontaminasi. Kondisi ini terutama disebabkan oleh
buruknya sanitasi dan akses air bersih.
</li>
<li>Bakteri juga dapat menyebar jika orang yang telah terinfeksi tidak mencuci tangan sebelum menyentuh atau
mengolah makanan. Penyebaran bakteri terjadi ketika ada orang lain yang menyantap makanan yang tersentuh
tangan penderita.
</li>
<li>Mengonsumsi sayur-sayuran yang menggunakan pupuk dari kotoran manusia yang terinfeksi.</li>
<li>Mengonsumsi produk susu yang telah terkontaminasi.</li>
<li>Menggunakan toilet yang terkontaminasi bakteri. Anda akan terinfeksi jika menyentuh mulut sebelum
mencuci tangan setelah buang air.
</li>
<li>Melakukan seks oral dengan pembawa bakteri Salmonella typhii.</li>
</ul>
<p className="mt-2">
Jika tidak segera diobati, Salmonella typhii akan menyebar ke seluruh tubuh dengan memasuki pembuluh darah.
Gejala tifus akan diperburuk jika bakteri telah menyebar ke luar sistem pencernaan. Selain itu,
bakteri yang menyebar dapat merusak organ dan jaringan, serta menyebabkan komplikasi serius.
Kondisi yang paling umum terjadi adalah perdarahan internal atau usus bocor.
</p>
<h3 className="mt-6 text-xl leading-8">Pengobatan Tifus</h3>
<p className="mt-2">
Terapi antibiotik adalah cara efektif dalam menangani tifus dan perlu diberikan sedini mungkin.
Beberapa obat antibiotik yang digunakan untuk mengobati tifus adalah azithromycin, ciprofloxacin, atau
ceftriaxone.<br />
Perawatan tifus dilakukan di rumah sakit, tapi jika tifus lebih cepat dideteksi dan gejalanya masih
tergolong ringan, maka penanganannya bisa dilakukan secara mandiri di rumah.<br /><br />
Pengobatan Tifus di Rumah Sakit Antibiotik di rumah sakit akan diberikan dalam bentuk suntikan.
Jika diperlukan, asupan cairan dan nutrisi juga akan dimasukkan ke dalam pembuluh darah melalui infus.
Pasien perlu menggunakan antibiotik hingga hasil tes terhadap bakteri penyebab tifus benar-benar bersih.
Infus akan diberikan apabila pasien tifus disertai dengan gejala-gejala, seperti muntah terus-menerus
serta diareparah. Infus berisi cairan akan diberikan untuk mencegah kekurangan cairan tubuh (dehidrasi).
Anak yang mengalami demam tifoid bisa direkomendasikan untuk melalui perawatan di rumah sakit sebagai
tindakan pencegahan. Pada kasus yang jarang terjadi, operasi dapat dilakukan jika terjadi komplikasi yang
membahayakan nyawa, seperti perdarahan saluran pencernaan. Penderita tifus akan berangsur-angsur membaik
setelah dirawat kurang-lebih selama 3-5 hari. Tubuh akan pulih dengan perlahan-lahan hingga kondisi pasien
pulih sepenuhnya setelah beberapa minggu pascainfeksi.<br /><br />
Pengobatan Tifus di Rumah Umumnya orang yang didiagnosis tifus pada stadium awal membutuhkan pengobatan
selama 1-2 minggu dengan tablet antibiotik. Meski tubuh mulai membaik setelah 2-3 hari mengonsumsi
antibiotik, sebaiknya jangan menghentikan konsumsi sebelum antibiotik habis. Hal ini berguna untuk
memastikan agar bakteri Salmonella typhii benar-benar lenyap di dalam tubuh. Meski begitu, pemberian
antibiotik untuk mengobati tifus mulai menimbulkan masalah bagi negara-negara di Asia Tenggara.
Beberapa kelompok Salmonella typhii menjadi kebal terhadap antibiotik. Beberapa tahun terakhir,
bakteri ini juga menjadi kebal terhadap antibiotik chloramphenicol, ampicillin, dan
trimethoprim-sulfamethoxazole. Jika kondisi makin memburuk saat menjalani perawatan tifus di rumah,
segera temui dokter untuk mendapatkan penanganan yang tepat. Pada sebagian kecil penderita tifus,
penyakit ini dapat kambuh kembali. <br />
Pastikan untuk mengikuti langkah-langkah ini supaya tubuh segera pulih dan mencegah risiko tifus kambuh:
</p>
<ul role="list" className="my-4 max-w-xl space-y-2 text-gray-600 list-disc pl-6">
<li>Istirahat yang cukup</li>
<li>Makan teratur. Makan dalam porsi sedikit, tapi dalam frekuensi yang cukup sering dibandingkan dengan
makan porsi besar, tapi hanya tiga kali sehari
</li>
<li>Perbanyak minum air putih</li>
<li>Rajin mencuci tangan dengan sabun untuk mengurangi risiko penyebaran infeksi</li>
</ul>
<h3 className="mt-6 text-xl leading-8">Bakteri yang Menetap di Dalam Tubuh</h3>
<p className="mt-2">
Beberapa orang yang telah pulih dan sudah tidak menunjukkan gejala-gejala tifus, tetap dapat menderita
bakteri Salmonella typhii di dalam saluran usus selama bertahun-tahun. Sekitar lima persen penderita tifus
yang tidak menjalani pengobatan yang cukup tetapi kemudian bisa pulih, akan terus membawa bakteri ini di
dalam tubuhnya. Tanpa disadari, para pembawa (carrier) bakteri tifoid bisa menularkannya pada orang lain
melalui tinja. Untuk beberapa profesi, carrier ini mendapat perhatian khusus. Orang-orang dengan profesi
tertentu, disarankan untuk memastikan bahwa tubuhnya tidak memiliki bakteri Salmonella typhii sebelum
melakukan pekerjaannya. <br />
Profesi yang berisiko ini, antara lain:
</p>
<ul role="list" className="my-4 max-w-xl space-y-2 text-gray-600 list-disc pl-6">
<li>Profesi yang berhubungan dengan pengolahan dan penyiapan makanan</li>
<li>Perawat yang sering berhadapan atau mengurus orang yang rentan sakit</li>
<li>Pengasuh balita atau perawat lansia.</li>
</ul>
<h3 className="mt-6 text-xl leading-8">Pengobatan Tambahan saat Tifus Kambuh</h3>
<p className="mt-2">
Sebagian orang dapat mengalami gejala-gejala tifus yang kambuh seminggu setelah berakhirnya pengobatan
antibiotik. Untuk kondisi ini, biasanya dokter akan kembali meresepkan antibiotik, meski gejala-gejala
yang dirasakan tidak separah sebelumnya.<br />
Jika setelah menjalani pengobatan ternyata hasil tes pada feses atau tinja ditemukan masih adanya bakteri
Salmonella typhii, pasien akan kembali disarankan untuk mengonsumsi antibiotik selama 28 hari untuk
mematikan bakteri, sekaligus mengurangi risiko pasien menjadi carrier. Selama diagnosis masih menyatakan
adanya infeksi, sebaiknya hindari aktivitas mengolah, memasak, dan menyajikan makanan baik untuk diri
sendiri, maupun orang lain. Selain itu, pastikan juga untuk rutin mencuci tangan setelah dari kamar mandi.
</p>
<h3 className="mt-6 text-xl leading-8">Pencegahan Tifus</h3>
<p className="mt-2">
Vaksinasi tifus di Indonesia termasuk dalam jadwal imunisasi anak. Vaksinasi ini sangat dianjurkan bagi anak
berusia dua tahun dan diberikan kembali tiap tiga tahun sekali. Pemberian vaksin idealnya diberikan satu
bulan sebelum berkunjung ke tempat yang merupakan daerah endemik tifus.<br />
Beberapa reaksi dan efek samping yang mungkin muncul setelah pemberian vaksin tifus, yaitu nyeri, kemerahan,
bengkak di sekeliling area suntikan, mual, pusing, sakit perut, atau diare.<br />
Meski demikian, pemberian vaksin tifoid tidak menjamin 100 persen kebal terhadap bakteri penyebab tifus.
Risiko terserang tifoid tetap ada, meski gejala-gejala yang terjadi tidak separah gejala pada orang yang
belum memperoleh vaksin sama sekali.
</p>
<h3 className="mt-6 text-xl leading-8">Langkah Pencegahan selain Vaksin</h3>
<p className="mt-2">
Di negara-negara berkembang, bakteri tifus dapat tumbuh subur seiring meningkatnya tingkat resistensi bakteri
terhadap antibiotik untuk mengobati tifus. Ini mengakibatkan beberapa antibiotik sudah tidak mampu melawan
penyakit ini. Oleh sebab itu, perlu penyusunan dan penyuluhan mengenai daftar obat-obatan yang sudah tidak
efektif dalam menangani tifus agar pasien mendapatkan pengobatan yang tepat.<br /><br />
Untuk mencegah tifus, pemberian vaksin tifus perlu disertai dengan perbaikan sanitasi, ketersediaan air
bersih, serta penerapan pola hidup sehat sejak dini.<br />
Perhatikan hal-hal berikut ini agar terhindar dari risiko penularan tifus:
</p>
<ul role="list" className="my-4 max-w-xl space-y-2 text-gray-600 list-disc pl-6">
<li>Cuci tangan sebelum dan sesudah mengolah makanan dan minuman, serta setelah buang air kecil atau besar,
maupun usai membersihkan kotoran, misalnya saat mencuci popok bayi.
</li>
<li>Jika ingin bepergian ke tempat yang memiliki kasus penyebaran tifus, sebaiknya pastikan air yang akan
diminum sudah direbus sampai matang.
</li>
<li>Jika harus membeli minuman, sebaiknya beli air minum dalam kemasan.</li>
<li>Kurangi membeli jajanan secara sembarangan di pinggir jalan, karena mudah sekali terpapar bakteri.</li>
<li>Hindari mengonsumsi es batu yang bukan dibuat sendiri.</li>
<li>Hindari mengonsumsi buah dan sayuran mentah, kecuali terlebih dahulu dicuci dengan air bersih dan kulitnya dikupas.</li>
<li>Batasi konsumsi jenis-jenis makanan boga-bahari (seafood), terutama yang masih mentah, karena tingkat
kesegarannya sulit diketahui secara pasti.
</li>
<li>Sebaiknya gunakan air matang untuk menggosok gigi atau berkumur, terutama jika sedang berada di tempat
yang belum dijamin kebersihannya.
</li>
<li>Bersihkan kamar mandi secara teratur. Hindari bertukar barang pribadi, seperti handuk, seprai, dan
peralatan mandi. Cuci benda-benda tersebut secara terpisah di dalam air hangat.
</li>
<li>Hindari konsumsi susu yang tidak dipasteurisasi (bukan susu kemasan).</li>
<li>Konsumsi antibiotik yang diresepkan oleh dokter dan ikutilah petunjuk pemakaian yang telah diberikan.
Pengobatan antibiotik harus dilakukan hingga periode pengobatan berakhir untuk mencegah resistensi obat.
</li>
</ul>
</div>
</div>
</div>
)
} |
package com.dpiqb.client;
import com.dpiqb.Helper;
import com.dpiqb.db.DatabaseMigrateServiceForTest;
import com.dpiqb.db.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.junit.jupiter.api.*;
import java.util.List;
import java.util.Random;
public class ClientCrudServiceTest {
static HibernateUtil util;
static Session session;
static ClientCrudService clientCrudService;
@BeforeAll
public static void init(){
DatabaseMigrateServiceForTest.migrateDatabase();
util = HibernateUtil.getInstance();
clientCrudService = new ClientCrudService();
}
@BeforeEach
public void openSession() {
session = util.getSessionFactory().openSession();
}
@Test
public void createTest(){
// to create new client we need just name
String actualClientName = "Elisabeth Shaw";
Client actualClient = new Client();
actualClient.setName(actualClientName);
clientCrudService.create(actualClient);
Client expectedClient = session.get(Client.class, actualClient.getId());
Assertions.assertEquals(expectedClient.getName(), actualClient.getName());
}
@Test
public void readByIdTest(){
List<Client> actualClients = session.createQuery(
"from Client", Client.class)
.setMaxResults(5)
.list();
for (Client actualClient : actualClients) {
Client expectedClient = clientCrudService.readById(actualClient.getId());
Assertions.assertEquals(expectedClient.toString(), actualClient.toString());
}
}
@Test
public void updateTest(){
Client actualClient = Helper.getRandomClientFromDB();
actualClient.setName("Xenomorph");
clientCrudService.update(actualClient);
Client expectedClient = session.find(Client.class, actualClient.getId());
Assertions.assertEquals(expectedClient.toString(), actualClient.toString());
}
@Test
public void updateIfUserHaveNothingChangeTest(){
Client actualClient = Helper.getRandomClientFromDB();
clientCrudService.update(actualClient);
Client expectedClient = session.find(Client.class, actualClient.getId());
Assertions.assertEquals(expectedClient.toString(), actualClient.toString());
}
@Test
public void deleteByIdTest(){
List<Client> allIds = session.createQuery("select c.id from Client c", Client.class).list();
Random random = new Random();
int randInt = random.nextInt(1, allIds.size()-1);
Client actualClient = session.get(Client.class, allIds.get(randInt));
long id = actualClient.getId();
clientCrudService.deleteById(id);
Query<Client> query = session.createQuery("from Client where id = :id", Client.class);
query.setParameter("id", id);
Client expectedClient = query.stream().findFirst().orElse(null);
Assertions.assertNull(expectedClient);
}
@Test
public void readAllClientsTest(){
List<Client> expectedClients = clientCrudService.readAllClients();
List<Client> actualClients = session.createQuery("from Client", Client.class).list();
int size = actualClients.size();
for (int i = 0; i < size; i++) {
Assertions.assertEquals(expectedClients.get(i).toString(), actualClients.get(i).toString());
}
}
@AfterEach
public void closeSession(){
session.close();
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 默认传递event参数 -->
<button @click="btn1Click">按钮1</button>
<!-- 传递自定义的参数 -->
<button @click="btn2Click('dwc', age)">按钮2</button>
<!-- 传递自定义的参数和event参数,event参数需要写成$event -->
<button @click="btn3Click('cwteng', age, $event)">按钮3</button>
</div>
<script src="../lib/vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
age: 18
}
},
methods: {
btn1Click(event) {
console.log("btn1Click", event)
},
btn2Click(name, age) {
console.log("btn2Click", name, age)
},
btn3Click(name, age, event) {
console.log("btn3Click", name, age, event)
}
}
})
app.mount("#app")
</script>
</body>
</html> |
<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
<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">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="custy.css">
<link rel="shortcut icon" href="img/Here_(company)-Logo.wine.svg" type="favicon">
<title>Hackathon + | Here Technologies</title>
</head>
<body class="bg-gray-900">
<header class="fixed w-full z-30 top-0 text-gray-400 bg-gray-900 body-font">
<div class="container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center">
<a class="flex title-font font-medium items-center text-white mb-4 md:mb-0">
<img class="bg-white w-10 h-10 object-cover object-center rounded" alt="hero" src="img/Here_(company)-Logo.wine.svg">
<span class="ml-3 text-xl text-teal-500">HERE</span>
<span class="ml-2 text-xl">Technologies</span>
</a>
<nav class="md:ml-auto md:mr-auto flex flex-wrap items-center text-base justify-center">
<a class="mr-5 hover:text-teal-400 font-semibold underline hover:decoration-double" href="#home">Home</a>
<a class="mr-5 hover:text-teal-400 font-semibold underline hover:decoration-double" href="#themes">Themes</a>
<a class="mr-5 hover:text-teal-400 font-semibold underline hover:decoration-double" href="#sponsors">Sponsors</a>
<a class="mr-5 hover:text-teal-400 font-semibold underline hover:decoration-double" href="#faq">FAQs</a>
</nav>
<button id="checkIn" class="inline-flex items-center bg-gray-800 border-2 border-teal-500 py-1 px-3 focus:outline-none shadow-lg shadow-teal-500/50 hover:bg-teal-700 hover:shadow-teal-900/80 hover:text-white rounded text-base mt-4 md:mt-0">Web Check-in
<svg fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-4 h-4 ml-1" viewBox="0 0 24 24">
<path d="M5 12h14M12 5l7 7-7 7"></path>
</svg>
</button>
</div>
</header>
<section class="text-gray-400 bg-gray-900 body-font" id="home">
<div class="container mx-auto flex px-5 py-16 items-center justify-center flex-col">
<!-- <img class="lg:w-2/6 md:w-3/6 w-5/6 object-cover object-center rounded" alt="hero" src="img/Comp-a-Thon.svg"> -->
<lottie-player class="lg:w-2/6 md:w-3/6 w-5/6 object-cover object-center rounded" src="https://assets7.lottiefiles.com/packages/lf20_eb9udl65.json" mode="bounce"
background="transparent" speed="1" style="width: 900px; height: 700px;" loop autoplay>
</lottie-player>
<div class="text-center lg:w-2/3 w-full">
<h1 class="title-font sm:text-4xl text-3xl mb-4 font-medium text-white">💻 Hackathon + Hiring 💻</h1>
<p class="leading-relaxed mb-8 text-lg">
Here Technologies, the most sought-after recruiter, is back with a Hackathon that can enable them to scout the best talent from the 2024 batch for internship and full-time employment along with a cash prize.
<br><br>
The internship opportunity is offered to the 2024 batch,
while the 2025 batch can avail cash prizes and exciting goodies.
The problem statement will be shared by Here Technologies, and this is not an open-ended competition.
The future of recruitment is Hackathons. Most of the Marquee brands recruit through hackathons and we must be agile and nimble-footed
to harness these opportunities across all job portals and online coding platforms.
<br><br>
The goal of this hackathon is brainstorming, team building, and streamlining awareness. This hackathon will enable the company to find new talent, harvest new ideas, find potential coders with holistic personalities, and much more.
</p>
<div class="flex justify-center">
<a href="https://drive.google.com/file/d/1Kril2xfm0HR87PtGj-nDecz2m6MpR0Qn/view?usp=sharing" target="_blank">
<button class="inline-flex text-white bg-teal-500 border-0 py-2 px-6 focus:outline-none hover:bg-teal-700 rounded text-lg shadow-lg shadow-teal-500/50 hover:shadow-teal-900/80">Event Structure and Prizes</button>
</a>
<!-- <a href="https://drive.google.com/file/d/1pV_uMNsJF1XRxYiX_jVdRVdhRz3HD7ZU/view?usp=sharing" target="_blank">
<button class="ml-4 inline-flex text-white bg-blue-500 border-0 py-2 px-6 focus:outline-none hover:bg-gray-700 hover:text-white rounded text-lg">Teams Schedule (Day 2)</button>
</a> -->
</div>
</div>
</div>
</section>
<section>
<section class="text-gray-400 body-font bg-gray-900" id="themes">
<div class="container px-4 py-16 mx-auto">
<div class="flex flex-col text-center w-full mb-20">
<!-- <h2 class="text-xs text-purple-400 tracking-widest font-medium title-font mb-1">COMP-A-THON</h2> -->
<h1 class="sm:text-3xl text-2xl font-medium title-font mb-4 text-white underline decoration-wavy">Our Problem Statements</h1>
<p class="lg:w-2/3 mx-auto leading-relaxed text-teal-400">These are the suggested themes from our side but the participants are open to choose their own problem statements.</p>
</div>
<div class="flex flex-wrap">
<div class="lg:w-1/3 sm:w-1/2 px-8 py-6 border-l-2 border-gray-800">
<h2 class="text-lg sm:text-xl text-white font-medium title-font mb-2">20 min city</h2>
<p class="leading-relaxed text-teal-400 mb-4">First</p>
</div>
<div class="lg:w-1/3 sm:w-1/2 px-8 py-6 border-l-2 border-gray-800">
<h2 class="text-lg sm:text-xl text-white font-medium title-font mb-2">End to end trip planner</h2>
<p class="leading-relaxed text-teal-400 mb-4">Second</p>
</div>
<div class="lg:w-1/3 sm:w-1/2 px-8 py-6 border-l-2 border-gray-800">
<h2 class="text-lg sm:text-xl text-white font-medium title-font mb-2">One tap solution for emergencies</h2>
<p class="leading-relaxed text-teal-400 mb-4">Third</p>
</div>
<div class="lg:w-1/3 sm:w-1/2 px-8 py-6 border-l-2 border-gray-800">
<h2 class="text-lg sm:text-xl text-white font-medium title-font mb-2">Land/House price prediction</h2>
<p class="leading-relaxed text-teal-400 mb-4">Fourth</p>
</div>
<div class="lg:w-1/3 sm:w-1/2 px-8 py-6 border-l-2 border-gray-800">
<h2 class="text-lg sm:text-xl text-white font-medium title-font mb-2">Best Location Prediction</h2>
<p class="leading-relaxed text-teal-400 mb-4">Fifth</p>
</div>
<div class="lg:w-1/3 sm:w-1/2 px-8 py-6 border-l-2 border-gray-800">
<h2 class="text-lg sm:text-xl text-white font-medium title-font mb-2">Public Transport System (Bus)</h2>
<p class="leading-relaxed text-teal-400 mb-4">Sixth</p>
</div>
<div class="lg:w-1/3 sm:w-1/2 px-8 py-6 border-l-2 border-gray-800">
<h2 class="text-lg sm:text-xl text-white font-medium title-font mb-2">Supply Chain System</h2>
<p class="leading-relaxed text-teal-400 mb-4">Sixth</p>
</div>
<div class="lg:w-1/3 sm:w-1/2 px-8 py-6 border-l-2 border-gray-800">
<h2 class="text-lg sm:text-xl text-white font-medium title-font mb-2">High throughput low latency systems</h2>
<p class="leading-relaxed text-teal-400 mb-4">Sixth</p>
</div>
<!-- </div>
<a href="https://drive.google.com/drive/folders/1Z3PeKFJrexIkCmKahpEjEvutILEgZegS" target="_blank">
<button class="flex mx-auto mt-16 text-white bg-red-500 border-0 py-2 px-8 focus:outline-none hover:bg-red-600 rounded text-lg">Download</button>
</a> -->
</div>
</section>
</section>
<section class="text-gray-400 bg-gray-900 body-font" id="sponsors">
<div class="container px-5 py-16 mx-auto">
<div class="flex flex-col text-center w-full mb-20">
<h1 class="sm:text-3xl text-2xl font-medium title-font mb-4 text-white underline decoration-wavy">Our Sponsors! 😉</h1>
<p class="lg:w-2/3 mx-auto leading-relaxed text-teal-400">Thank these lovely sponsors for the prizes that you get.</p>
</div>
<!-- <div class="flex flex-col text-center w-full">
<h1 class="sm:text-3xl text-2xl font-medium title-font text-white">Main Sponsor</h1>
</div> -->
<!-- <div class="lg:w-1/3 sm:w-1/2 p-4">
<div class="flex relative">
<img alt="gallery" class="absolute inset-0 w-full h-full object-cover object-center bg-white" src="img/3.svg">
<div class="px-8 py-10 relative z-10 w-full border-4 border-gray-800 bg-gray-900 opacity-0 hover:opacity-100">
<h1 class="title-font text-lg font-medium text-teal-400 mb-3">Geek for Geeks</h1>
<h2 class="tracking-widest text-sm title-font font-medium text-white mb-1">The universal coding help website</h2> -->
<!-- <p class="leading-relaxed">Photo booth fam kinfolk cold-pressed sriracha leggings jianbing microdosing tousled waistcoat.</p> -->
<!-- </div>
</div>
</div> -->
<!-- <div class="flex flex-col text-center w-full">
<h1 class="sm:text-3xl text-2xl font-medium title-font text-white mb-16">Secondary Sponsors</h1>
</div> -->
<div class="flex flex-wrap -m-4">
<div class="lg:w-1/3 sm:w-1/2 p-4">
<div class="flex relative">
<img alt="gallery" class="absolute inset-0 w-full h-full object-cover object-center bg-white" src="img/1.svg">
<div class="px-8 py-10 relative z-10 w-full border-4 border-gray-800 bg-gray-900 opacity-0 hover:opacity-100">
<h1 class="title-font text-lg font-medium text-teal-400 mb-3">Bennett University</h1>
<h2 class="tracking-widest text-sm title-font font-medium text-white mb-1">Our Prestigious University</h2>
<!-- <p class="leading-relaxed">Photo booth fam kinfolk cold-pressed sriracha leggings jianbing microdosing tousled waistcoat.</p> -->
</div>
</div>
</div>
<div class="lg:w-1/3 sm:w-1/2 p-4">
<div class="flex relative">
<img alt="gallery" class="absolute inset-0 w-full h-full object-center bg-white" src="img/CAREER SERVICES LOGO.svg">
<div class="px-8 py-10 relative z-10 w-full border-4 border-gray-800 bg-gray-900 opacity-0 hover:opacity-100">
<h1 class="title-font text-lg font-medium text-teal-400 mb-3">Career Services Center</h1>
<h2 class="tracking-widest text-sm title-font font-medium text-white mb-1">The placement cell of our university</h2>
<!-- <p class="leading-relaxed">Photo booth fam kinfolk cold-pressed sriracha leggings jianbing microdosing tousled waistcoat.</p> -->
</div>
</div>
</div>
<div class="lg:w-1/3 sm:w-1/2 p-4">
<div class="flex relative">
<img alt="gallery" class="absolute inset-0 w-full h-full object-cover object-center bg-white" src="img/Here_(company)-Logo.wine.png">
<div class="px-8 py-10 relative z-10 w-full border-4 border-gray-800 bg-gray-900 opacity-0 hover:opacity-100">
<h1 class="title-font text-lg font-medium text-teal-400 mb-3">HERE Technologies</h1>
<h2 class="tracking-widest text-sm title-font font-medium text-white mb-1">Delivering powerful projects in the field of Web3</h2>
<!-- <p class="leading-relaxed">Photo booth fam kinfolk cold-pressed sriracha leggings jianbing microdosing tousled waistcoat.</p> -->
</div>
</div>
</div>
</div>
</div>
</section>
<div>
<section class=" text-gray-400 bg-gray-900" id="faq">
<div class="container px-5 py-16 mx-auto">
<div class="text-center mb-20">
<h1 class="sm:text-3xl text-2xl font-medium text-center title-font text-gray-300 mb-4 underline decoration-wavy">
Frequently Asked Questions
</h1>
<p class="text-base leading-relaxed xl:w-2/4 lg:w-3/4 mx-auto text-teal-400">
The most common questions regarding the competetion.
</p>
</div>
<div class="flex flex-wrap lg:w-4/5 sm:mx-auto sm:mb-2 -mx-2">
<div class="w-full lg:w-full px-4 py-2">
<details class="mb-4">
<summary class="font-semibold bg-teal-500 text-white rounded-md py-2 px-4">
Q1. Why is Hackathon + Hiring different?
</summary>
<span>
Hackathon + Hiring is not a normal hackathon event but instead the real life cycle of
how big tech companies/High growth startups develop their products and what they look for while recruiting new talents.
</span>
</details>
<details class="mb-4">
<summary class="font-semibold bg-teal-500 text-white rounded-md py-2 px-4">
Q2. What will be the flow of the event?
</summary>
<span>
The event will be split into 3 days over the weekend, beginning on friday (9th September) with the pitching session, then moving onto the mentoring session, the wild card entries, product mapping and
ending with the final development on Sunday(11th September). A timeline with complete details shall be released soon.
</span>
</details>
<details class="mb-4">
<summary class="font-semibold bg-teal-500 text-white rounded-md py-2 px-4">
Q3. Why should you participate?
</summary>
<span>
Well the reasons are infinite but to name a few ones: <br>
1. Guidance on how to crack technical interviews <br>
2. Getting a 1-on-1 mentoring with our Mentors <br>
3. A chance to get referrals to the MNCs and Startups <br>
4. Cash prices!! <br>
5. Goodies <br>
6. Direct Internship opportunities in certain startups <br>
7. Getting trading advice from the BU startups and indicator access for 2 months <br>
</span>
</details>
<details class="mb-4">
<summary class="font-semibold bg-teal-500 text-white rounded-md py-2 px-4">
Q4. Who are the mentors?
</summary>
<span class="px-4 py-2">
Our Mentors will be the students who have gone through the same process and now are working in the Big Tech
companies and High growth startups.
</span>
</details>
<details class="mb-4">
<summary class="font-semibold bg-teal-500 text-white rounded-md py-2 px-4">
Q5. When do registrations end?
</summary>
<span class="px-4 py-2">
Registrations close on the 6th of September at 2 pm. All interested participants
must be registered before the deadline as no registrations shall be accepted afterwards.
</span>
</details>
</div>
</div>
</div>
</section>
</div>
<footer class="text-gray-400 bg-gray-900 body-font">
<div class="container px-5 py-8 mx-auto flex items-center sm:flex-row flex-col">
<a class="flex title-font font-medium items-center md:justify-start justify-center text-white">
<!-- class="w-10 h-10 text-white p-2 bg-red-500 rounded-full" -->
<img src="img/Here_(company)-Logo.wine.svg" alt="logo here" class="w-16 h-16 text-white bg-white rounded-lg">
<span class="ml-3 text-xl text-teal-400">HERE</span>
<span class="ml-2 text-xl">Technologies</span>
</a>
<p class="text-sm text-gray-400 sm:ml-4 sm:pl-4 sm:border-l-2 sm:border-gray-800 sm:py-2 sm:mt-0 mt-4">© 2022 Career Services Cell | Bennett University. All Rights Reserved.
</p>
<!-- <span class="inline-flex sm:ml-auto sm:mt-0 mt-4 justify-center sm:justify-start">
<a class="text-gray-400" href="https://github.com/Tech-Odyssey/Namak-Shamak" target="_blank">
<i class="fab fa-github w-5 h-5 "></i>
</a>
</span> -->
</div>
</footer>
<script type="text/javascript">
const CLIENT_ID = '664854847379-nk4g3lkong4nskgl66aijf3fmkjrgt1g.apps.googleusercontent.com';
const API_KEY = 'AIzaSyAcoTuNB7G5UjWbdsWpbTxDKBzvJeAUWLY';
const DISCOVERY_DOC = 'https://sheets.googleapis.com/$discovery/rest?version=v4';
const SCOPES = 'https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/userinfo.profile';
var email;
async function microsoftFlow() {
const msalConfig = {
auth: {
clientId: "b93618fd-02b8-4f6c-91c7-d0bb8d0b1d5d", // this is a fake id
authority: "https://login.microsoftonline.com/2c5bdaf4-8ff2-4bd9-bd54-7c50ab219590",
redirectUri: "https://comp-a-thon-09.github.io/compathon/",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
const loginRequest = {
scopes: ["User.Read", "Mail.Read"],
};
myMSALObj.loginPopup(loginRequest)
.then(async (loginResponse) => {
//Login Success callback code here
email = loginResponse['account']['userName'].toLowerCase();
console.log(email)
handleAuthClick();
}).catch(function (error) {
console.log(error);
});
const tokenRequest = {
scopes: ["Mail.Read"]
};
}
let tokenClient;
let gapiInited = false;
let gisInited = false;
function gapiLoaded() {
gapi.load('client', intializeGapiClient);
}
async function intializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
document.getElementById('checkIn').style.visibility = 'hidden'
document.getElementById('checkIn').addEventListener("click", () => {
microsoftFlow();
//handleAuthClick();
})
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('checkIn').style.visibility = 'visible';
}
}
async function handleAuthClick() {
tokenClient.callback = async (resp) => {
console.log(resp['access_token'])
var apiUrl = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token='+resp['access_token'];
await fetch(apiUrl).then(response => {
return response.json();
}).then(data => {
console.log(data)
const name = data['name'];
console.log(data['name']);
try {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1_HshzUC_3Q1QTjgbUnfGLGVfQ9spofIFmpQIuW2xzos',
range: "Team Leaders!J2:J100",
}).then(async (response) => {
console.log(response.result.values);
const result = response.result;
for(var i = 0; i<result.values.length; i++) {
console.log(email === response.result.values[i][0])
if(email === response.result.values[i][0]){
var range = "Team Leaders!H"+(i+2);
console.log("Range ", range);
try {
gapi.client.sheets.spreadsheets.values.update({
spreadsheetId: '1_HshzUC_3Q1QTjgbUnfGLGVfQ9spofIFmpQIuW2xzos',
range: range,
valueInputOption: 'USER_ENTERED',
resource: {
values: [['CHECKED IN']],
},
}).then((response) => {
const result = response.result;
console.log(`${result.updatedCells} cells updated.`);
});
} catch (err) {
console.log(err);
return;
}
alert("CHECKED IN");
return;
}
}
alert('COULD NOT CHECK YOU IN. PLEASE CONTACT YOUR GIVEN POC')
const numRows = result.values ? result.values.length : 0;
console.log(`${numRows} rows retrieved.`);
});
} catch (err) {
console.log(err);
return;
}
}).catch(err => {
});
if (resp.error !== undefined) {
throw (resp);
}
};
if (gapi.client.getToken() === null) {
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
tokenClient.requestAccessToken({prompt: ''});
}
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
<script src="https://kit.fontawesome.com/c0f0e3d6c6.js" crossorigin="anonymous"></script>
</body>
</html> |
<?php
/**
* @file
* Contains \Drupal\page_manager_ui\Form\VariantPluginAddBlockForm.
*/
namespace Drupal\page_manager_ui\Form;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\page_manager\PageVariantInterface;
use Drupal\user\SharedTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides a form for adding a block plugin to a variant.
*/
class VariantPluginAddBlockForm extends VariantPluginConfigureBlockFormBase {
/**
* The block manager.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $blockManager;
/**
* Constructs a new VariantPluginFormBase.
*
* @param \Drupal\Component\Plugin\PluginManagerInterface $block_manager
* The block manager.
*/
public function __construct(SharedTempStoreFactory $tempstore, PluginManagerInterface $block_manager) {
parent::__construct($tempstore);
$this->blockManager = $block_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('user.shared_tempstore'),
$container->get('plugin.manager.block')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'page_manager_variant_add_block_form';
}
/**
* {@inheritdoc}
*/
protected function prepareBlock($plugin_id) {
$block = $this->blockManager->createInstance($plugin_id);
$block_id = $this->getVariantPlugin()->addBlock($block->getConfiguration());
return $this->getVariantPlugin()->getBlock($block_id);
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL, $block_display = NULL, $block_id = NULL) {
$form = parent::buildForm($form, $form_state, $block_display, $block_id);
$form['region']['#default_value'] = $request->query->get('region');
return $form;
}
/**
* {@inheritdoc}
*/
protected function submitText() {
return $this->t('Add block');
}
} |
package com.badr.security.config;
import jakarta.servlet.Filter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import java.net.http.HttpRequest;
import static com.badr.security.user.Permission.*;
import static com.badr.security.user.Role.ADMIN;
import static com.badr.security.user.Role.MANAGER;
import static org.springframework.http.HttpMethod.*;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity
public class SecurityConfiguration {
private final AuthenticationProvider authenticationProvider;
private final JwtAuthenticationFilter jwtAuthFilter;
private final LogoutHandler logoutHandler;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeRequests(auth -> auth
.requestMatchers("/api/v1/auth/**").permitAll()
.requestMatchers("/api/v1/management/**").hasAnyRole(ADMIN.name(),MANAGER.name())
.requestMatchers(GET ,"/api/v1/management/**").hasAnyAuthority(ADMIN_READ.name(),MANAGER_READ.name())
.requestMatchers(POST ,"/api/v1/management/**").hasAnyAuthority(ADMIN_CREATE.name(),MANAGER_CREATE.name())
.requestMatchers(PUT ,"/api/v1/management/**").hasAnyAuthority(ADMIN_UPDATE.name(),MANAGER_UPDATE.name())
.requestMatchers(DELETE ,"/api/v1/management/**").hasAnyAuthority(ADMIN_DELETE.name(),MANAGER_DELETE.name())
// .requestMatchers("/api/v1/admin/**").hasRole(ADMIN.name())
//
// .requestMatchers(GET ,"/api/v1/admin/**").hasAuthority(ADMIN_READ.name())
// .requestMatchers(POST ,"/api/v1/admin/**").hasAuthority(ADMIN_CREATE.name())
// .requestMatchers(PUT ,"/api/v1/admin/**").hasAuthority(ADMIN_UPDATE.name())
// .requestMatchers(DELETE ,"/api/v1/admin/**").hasAuthority(ADMIN_DELETE.name())
.anyRequest().authenticated()
)
.sessionManagement(sessionManagement -> sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout(logout -> {
logout.logoutUrl("/api/v1/auth/logout");
logout.addLogoutHandler(logoutHandler);
logout.logoutSuccessHandler((request, response, authentication) ->
SecurityContextHolder.clearContext());
})
;
return http.build();
}
} |
import axios from "axios";
import React, { useEffect, useState } from "react";
import Popup from "../../Popup";
import EditArticlePanel from "./EditArticlePanel";
function EditArticle(props) {
const [userData, setUserData] = useState([]);
const [article] = useState(props.article);
const [reviewerData] = useState([]);
const [type, setType] = useState("");
const [editTrigger, setEditTrigger] = useState(false);
useEffect(() => {
axios.get("http://localhost:6969/userData").then((res) => {
setUserData(res.data);
});
}, []);
return (
<div>
<i
className="fa-solid fa-book"
style={{ color: "#f67280", fontSize: "150px" }}
></i>
<br />
<br />
<br />
<table className="articleDetails">
<tbody>
<tr>
<td className="first">Status</td>
<td
className="second"
style={
article.status === "Published"
? { fontWeight: "bold", color: "#32CD32" }
: article.status === "Rejected"
? { fontWeight: "bold", color: "gray" }
: article.status === "Editing"
? { fontWeight: "bold", color: "#00BFFF" }
: article.status === "Reviewing"
? { fontWeight: "bold", color: "#DC143C" }
: article.status === "Reviewed"
? { fontWeight: "bold", color: "#8B0000" }
: { fontWeight: "bold", color: "#EFB700" }
}
>
{article.status}
<button
className="editButton"
onClick={() => {
setType("status");
setEditTrigger(true);
}}
>
<i className="fa-solid fa-pencil" />
</button>
</td>
</tr>
<tr>
<td className="first">Article ID</td>
<td className="second">{article._id}</td>
</tr>
<tr>
<td className="first">Title</td>
<td className="second">
<a href={article.path} target="_blank" rel="noopener noreferrer">
{article.title}
</a>
<button
className="editButton"
onClick={() => {
setType("title");
setEditTrigger(true);
}}
>
<i className="fa-solid fa-pencil" />
</button>
</td>
</tr>
<tr>
<td className="first">Author</td>
<td className="second">{article.author}</td>
</tr>
{userData.map((each) => {
if (article.editor === each.email) {
return (
<tr>
<td className="first">Editor</td>
<td className="second">
{each.fname} {each.lname}
</td>
</tr>
);
}
})}
<tr>
<td className="first">Reviewer</td>
<td className="second">
{article.reviewer.map((reviewer) => {
userData.map((user) => {
if (user.email === reviewer) {
reviewerData.push(user.fname + " " + user.lname);
}
});
return (
<div style={{ display: "inline" }}>
{reviewerData[article.reviewer.indexOf(reviewer)] + ", "}
</div>
);
})}
</td>
</tr>
<tr>
<td className="first">Published Year</td>
<td className="second">
{article.year}
<button
className="editButton"
onClick={() => {
setType("year");
setEditTrigger(true);
}}
>
<i className="fa-solid fa-pencil" />
</button>
</td>
</tr>
<tr>
<td className="first">Field</td>
<td className="second">
{article.field}
<button
className="editButton"
onClick={() => {
setType("field");
setEditTrigger(true);
}}
>
<i className="fa-solid fa-pencil" />
</button>
</td>
</tr>
<tr>
<td className="first">Category</td>
<td className="second">
{article.category}
<button
className="editButton"
onClick={() => {
setType("category");
setEditTrigger(true);
}}
>
<i className="fa-solid fa-pencil" />
</button>
</td>
</tr>
{article.dateline ? (
<tr>
<td className="first">Dateline</td>
<td className="second">
{article.dateline.substring(8, 10)}-
{article.dateline.substring(5, 7)}-
{article.dateline.substring(0, 4)}
<button
className="editButton"
onClick={() => {
setType("dateline");
setEditTrigger(true);
}}
>
<i className="fa-solid fa-pencil" />
</button>
</td>
</tr>
) : null}
</tbody>
</table>
<Popup
class="editPanel"
innerClass="editPanel-inner editArticlePanel"
trigger={editTrigger}
setTrigger={setEditTrigger}
>
<EditArticlePanel article={article} type={type} />
</Popup>
</div>
);
}
export default EditArticle; |
import { Pagination } from "antd";
import { ContentTableLoader } from "components";
import jsConvert from "js-convert-case";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
fetchTransaction,
updateTransaction,
} from "store/Feature/FeatureTransaction/transactionSlice";
import CurrencyFormat from "react-currency-format";
import Swal from "sweetalert2";
const BookingStatus = () => {
const dispatch = useDispatch();
const listOfTransaction = useSelector((state) => state.transactions.data);
const [transaksiList, setTransaksiList] = useState(listOfTransaction);
const [loading, setLoading] = useState(true);
const pageSize = 6;
const [dataTransaksi, setDataTransaksi] = useState({
minValue: 0,
maxValue: 20,
});
const handleChange = (value) => {
setDataTransaksi({
minValue: (value - 1) * pageSize,
maxValue: value * pageSize,
});
};
const setReload = () => {
setLoading(true);
dispatch(fetchTransaction())
.then((res) => {
const updateListOnProcess = [];
res.payload.forEach((transaksi) => {
const loweredStatus = transaksi.status.toLowerCase();
if (loweredStatus.includes("on process")) {
updateListOnProcess.push(transaksi);
}
});
setTransaksiList(updateListOnProcess);
});
setTimeout(() => {
setLoading(false);
}, 500);
};
useEffect(() => {
dispatch(fetchTransaction())
.then((res) => {
const updateListOnProcess = [];
res.payload.forEach((transaksi) => {
const loweredStatus = transaksi.status.toLowerCase();
if (loweredStatus.includes("on process")) {
updateListOnProcess.push(transaksi);
}
});
setTransaksiList(updateListOnProcess);
});
setTimeout(() => {
setLoading(false);
}, 500);
setDataTransaksi({
minValue: 0,
maxValue: 6,
});
}, [dispatch]);
const handleChangeReject = (ev, id) => {
ev.preventDefault();
const swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton:
"focus:outline-none text-white bg-fifth hover:bg-red-600 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2",
cancelButton:
"py-2.5 px-5 mr-2 mb-2 text-sm font-medium text-gray-900 focus:outline-none bg-white rounded-lg border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-4 focus:ring-gray-200",
},
buttonsStyling: false,
});
swalWithBootstrapButtons
.fire({
title: `Are you sure?`,
text: "The selected record will be rejected. Are you want to continue",
showCancelButton: true,
confirmButtonText: "Yes, Rejected",
cancelButtonText: "No, cancel",
reverseButtons: true,
})
.then((result) => {
if (result.isConfirmed) {
try {
dispatch(updateTransaction({ id, status: "rejected" }));
setReload();
Swal.fire({
icon: "error",
title: "Booking Rejected !",
text: "This user's order status has been updated, you can see in the transaction details list.",
showConfirmButton: false,
timer: 1800,
});
} catch (error) {
Swal.fire({
icon: "error",
title: "Failed",
text: "Edit Transaction Fail",
});
}
}
});
};
const handleChangeAccept = (ev, id) => {
ev.preventDefault();
const swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton:
"focus:outline-none text-white bg-success bg-opacity-90 hover:bg-success font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2",
cancelButton:
"py-2.5 px-5 mr-2 mb-2 text-sm font-medium text-gray-900 focus:outline-none bg-white rounded-lg border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-4 focus:ring-gray-200",
},
buttonsStyling: false,
});
swalWithBootstrapButtons
.fire({
title: `Are you sure?`,
text: "The selected record will be accepted. Are you want to continue",
showCancelButton: true,
confirmButtonText: "Yes, Accepted",
cancelButtonText: "No, cancel",
reverseButtons: true,
})
.then((result) => {
if (result.isConfirmed) {
try {
dispatch(updateTransaction({ id, status: "accepted" }));
setReload();
Swal.fire({
icon: "success",
title: "Booking Accepted !",
text: "This user's order status has been updated, you can see in the transaction details list.",
showConfirmButton: false,
timer: 1800,
});
} catch (error) {
Swal.fire({
icon: "error",
title: "Failed",
text: "Edit Transaction Fail",
});
}
}
});
};
return (
<>
<section className="mt-10 flex flex-col bg-white rounded-3xl drop-shadow-4xl">
<div className="p-6 space-y-6">
<div>
<h1 className="font-bold text-2xl text-left">
Recent Status Booking
</h1>
</div>
<div>
<div className="overflow-x-auto relative">
{loading ? (
<ContentTableLoader />
) : (
<table className="w-full text-sm text-left text-gray-500 space-y-6 ">
<thead className="text-xs text-gray-700 uppercase bg-gray-100 ">
<tr>
<th scope="col" className="py-3 px-6 rounded-l-2xl">
Date
</th>
<th scope="col" className="py-3 px-6">
Name
</th>
<th scope="col" className="py-3 px-6">
Type
</th>
<th scope="col" className="py-3 px-6">
Office Name
</th>
<th scope="col" className="py-3 px-6">
Price(Rp)
</th>
<th scope="col" className="py-3 px-6 rounded-r-2xl">
Action
</th>
</tr>
</thead>
<tbody>
{transaksiList
?.slice(dataTransaksi.minValue, dataTransaksi.maxValue)
.map((transaksi) => (
<tr
className="bg-white font-medium text-neutral-500"
key={transaksi.id}
>
<td className="py-4 px-6 font-medium whitespace-nowrap ">
{transaksi.check_in.date}
</td>
<td className="py-4 px-6">
{transaksi.user.full_name}
</td>
<td className="py-4 px-6">
{jsConvert.toHeaderCase(
transaksi.office.office_type
)}
</td>
<td className="py-4 px-6">
{jsConvert.toHeaderCase(
transaksi.office.office_name
)}
</td>
<td className="py-4 px-6">
<CurrencyFormat
value={transaksi.price}
displayType={"text"}
thousandSeparator={true}
prefix={"Rp."}
renderText={(value) => <div>{value}</div>}
/>
</td>
<td className="py-4 px-6">
<div className="flex items-center gap-2">
<button
onClick={(ev) =>
handleChangeReject(ev, transaksi.id)
}
className="py-2 px-4 text-sixth bg-[#FBE0DB] rounded-lg"
value="rejected"
>
Reject
</button>
<button
onClick={(ev) =>
handleChangeAccept(ev, transaksi.id)
}
className="py-2 px-4 text-[#45AF49] bg-[#DAEFDB] rounded-lg"
value="accepted"
>
Accept
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
<div className="mt-8 text-start">
<Pagination
defaultCurrent={1}
defaultPageSize={pageSize}
total={transaksiList?.length}
onChange={handleChange}
/>
</div>
</div>
</div>
</section>
</>
);
};
export default BookingStatus; |
package com.zyx.zyxojsandbox;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.zyx.zyxojsandbox.model.ExecuteCodeRequest;
import com.zyx.zyxojsandbox.model.ExecuteCodeResponse;
import com.zyx.zyxojsandbox.model.ExecuteMessage;
import com.zyx.zyxojsandbox.model.JudgeInfo;
import com.zyx.zyxojsandbox.security.DefaultSecurityManager;
import com.zyx.zyxojsandbox.utils.ProcessUtils;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* @author zyx
* @version 1.0
* @date 2024/1/8 008 16:49
*/
@Deprecated
public class JavaDockerCodeSandboxOld implements CodeSandbox {
private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
private static final Boolean FIRST_INIT = true;
private static final Long TIME_OUT = 5000L;
/**
* 设置时间限制
*/
private static final long TIME_OUT_MILLIS = 5000;
public static void main(String[] args) throws InterruptedException {
JavaDockerCodeSandboxOld javaDockerCodeSandbox = new JavaDockerCodeSandboxOld();
ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));
String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
executeCodeRequest.setCode(code);
executeCodeRequest.setLanguage("java");
ExecuteCodeResponse executeCodeResponse = javaDockerCodeSandbox.executeCode(executeCodeRequest);
System.out.println(executeCodeResponse);
}
@Override
public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) throws InterruptedException {
System.setSecurityManager(new DefaultSecurityManager());
List<String> inputList = executeCodeRequest.getInputList();
String code = executeCodeRequest.getCode();
String language = executeCodeRequest.getLanguage();
String property = System.getProperty("user.dir");
String globalCodePathName = property + File.separator + GLOBAL_CODE_DIR_NAME;
// 1.判断全局代码目录是否存在
if (!FileUtil.exist(globalCodePathName)) {
FileUtil.mkdir(globalCodePathName);
}
//分级,把用户代码隔离存放
String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
// 2.编译代码,得到class文件
String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
try {
Process compileProcess = Runtime.getRuntime().exec(compileCmd);
ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
System.out.println(executeMessage);
} catch (IOException e) {
return getErrorResponse(e);
}
// 3.创建容器,把文件复制到容器内
DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://114.55.110.155:2376").build();
String image = "openjdk:8-alpine";
if (FIRST_INIT) {
PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
@Override
public void onNext(PullResponseItem item) {
System.out.println("下载镜像:" + item.getStatus());
super.onNext(item);
}
};
pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
System.out.println("下载完成");
}
CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
HostConfig hostConfig = new HostConfig();
hostConfig.withMemory(1000 * 1000 * 100L);
hostConfig.withMemorySwap(0L);
hostConfig.withCpuCount(1L);
hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置字符串"));
hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
CreateContainerResponse createContainerResponse = containerCmd
.withHostConfig(hostConfig)
.withNetworkDisabled(true)
.withAttachStdin(true)
.withAttachStderr(true)
.withAttachStdout(true)
.withTty(true)
.exec();
System.out.println(createContainerResponse);
String responseId = createContainerResponse.getId();
List<ExecuteMessage> executeMessageList = new ArrayList<>();
for (String inputArgs : inputList) {
StopWatch stopWatch = new StopWatch();
String[] inputArgsArray = inputArgs.split(" ");
// docker exec keen_blackwell java -cp /app Main 1 3
String[] cmdArray = new String[]{"java", "-cp", "/app", "Main", "1", "3"};
dockerClient.startContainerCmd(responseId).exec();
ExecCreateCmdResponse execCreateCmdResponse = dockerClient
.execCreateCmd(responseId)
.withCmd(cmdArray)
.withAttachStdin(true)
.withAttachStderr(true)
.withAttachStdout(true)
.exec();
System.out.println("创建执行命令:" + execCreateCmdResponse);
ExecuteMessage executeMessage = new ExecuteMessage();
final String[] message = {null};
final String[] errorMessage = {null};
long time = 0L;
final boolean[] timeOut = {true};
String execId = execCreateCmdResponse.getId();
ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
@Override
public void onComplete() {
timeOut[0] = false;
super.onComplete();
}
@Override
public void onNext(Frame frame) {
StreamType streamType = frame.getStreamType();
if (StreamType.STDERR.equals(streamType)) {
errorMessage[0] = new String(frame.getPayload());
System.out.println("输出错误结果:" + errorMessage[0]);
} else {
message[0] = new String(frame.getPayload());
System.out.println("输出结果:" + message[0]);
}
super.onNext(frame);
}
};
final long[] maxMemory = {0L};
//获取占用内存
StatsCmd statsCmd = dockerClient.statsCmd(responseId);
ResultCallback<Statistics> resultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
@Override
public void onNext(Statistics statistics) {
System.out.println("内存占用:" + statistics.getMemoryStats().getUsage());
maxMemory[0] = Math.max(maxMemory[0], statistics.getMemoryStats().getUsage());
}
@Override
public void close() throws IOException {
}
@Override
public void onStart(Closeable closeable) {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
});
statsCmd.exec(resultCallback);
stopWatch.start();
dockerClient.execStartCmd(execId)
.exec(execStartResultCallback)
.awaitCompletion(TIME_OUT,MILLISECONDS);
stopWatch.stop();
time = stopWatch.getLastTaskTimeMillis();
statsCmd.close();
executeMessage.setMessage(message[0]);
executeMessage.setErrorMessage(errorMessage[0]);
executeMessage.setTime(time);
executeMessage.setMemory(maxMemory[0]);
executeMessageList.add(executeMessage);
}
ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
return executeCodeResponse;
}
/**
* 获取错误响应 错误处理
*
* @param throwable
* @return
*/
private ExecuteCodeResponse getErrorResponse(Throwable throwable) {
ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
executeCodeResponse.setOutputList(new ArrayList<>());
executeCodeResponse.setMessage(throwable.getMessage());
//表示代码沙箱错误
executeCodeResponse.setStatus(2);
executeCodeResponse.setJudgeInfo(new JudgeInfo());
return executeCodeResponse;
}
} |
import React, { useEffect, useState } from "react";
import './Loading.scss';
/**
* Loading animation
* @returns React Module to display the loading animation
* @author Noah Sternberg
* @since V1.0.0
*/
const LoadingAnimation = () => {
const [dots, setDots] = useState(0);
// Effect to show loading -> loading . -> loading .. -> loading ...
useEffect(() => {
const interval = setInterval(() => {
setDots((dots) => (dots + 1) % 4);
}, 500);
return () => {
clearInterval(interval);
};
}, []);
return <div className="animation"> {`Loading Weather Data${'.'.repeat(dots)}`} </div>;
}
export default LoadingAnimation; |
<template>
<div class="profile">
<Modal
v-if="modalActive"
:modalMessage="modalMessage"
@close-modal="closeModal"
/>
<div class="container">
<h2>Account Settings</h2>
<div class="profile-info">
<div class="initials">{{ profileInitials }}</div>
<!-- <div class="admin-badge">
<img class="icon" src="@/assets/Icons/user-crown-light.svg" alt="" />
<span>admin</span>
</div> -->
<div class="input">
<label for="firstName">First Name:</label>
<!-- mutating computed property is not a good idea, although achievable -->
<input
disabled
type="text"
id="firstName"
v-model="profileFirstName"
/>
</div>
<!-- separate the udpate data and computed property -->
<div class="input">
<label>New First Name:</label>
<input type="text" v-model="wishedFirstName" />
</div>
<!-- label attribute "for" would bind the input id: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label -->
<div class="input">
<label for="lastName">Last Name:</label>
<input disabled type="text" id="lastName" v-model="profileLastName" />
</div>
<div class="input">
<label>New Last Name:</label>
<input type="text" v-model="wishedLastName" />
</div>
<div class="input">
<label for="username">Username:</label>
<input disabled type="text" id="username" v-model="profileUsername" />
</div>
<div class="input">
<label>New Username:</label>
<input type="text" v-model="wishedUsername" />
</div>
<div class="input">
<label for="email">Email:</label>
<input disabled type="text" id="email" v-model="profileEmail" />
</div>
<button @click="updateProfile">Save Changes</button>
</div>
</div>
</div>
</template>
<script>
import { useStore } from "vuex";
import { ref, computed } from "vue";
import Modal from "@/components/Modal";
export default {
name: "Profile",
components: {
Modal,
},
setup() {
// variables
const modalMessage = ref("Changes were saved");
const modalActive = ref(null);
const wishedFirstName = ref("");
const wishedLastName = ref("");
const wishedUsername = ref("");
// state management
const store = useStore();
const updFirstName = (firstName) => {
return store.dispatch("users/updFirstName", firstName);
};
const updLastName = (lastName) => {
return store.dispatch("users/updLastName", lastName);
};
const updUsername = (userName) => {
return store.dispatch("users/updUsername", userName);
};
// functions
function updateProfile() {
if (
wishedFirstName.value.length == 0 &&
wishedLastName.value.length == 0 &&
wishedUsername.value.length == 0
) {
alert("No field has changed");
return;
}
// update the database value when necessary
wishedFirstName.value.length > 0
? updFirstName(wishedFirstName.value)
: null;
wishedLastName.value.length > 0
? updLastName(wishedLastName.value)
: null;
wishedUsername.value.length > 0
? updUsername(wishedUsername.value)
: null;
// reset the input fields
modalActive.value = !modalActive.value;
wishedFirstName.value = "";
wishedLastName.value = "";
wishedUsername.value = "";
}
function closeModal() {
modalActive.value = !modalActive.value;
}
// wrapped in a object according to the category
// to be organized and return the variables, functions, and computed properties
const storeComputed = {
profileInitials: computed(() => store.getters["users/profileInitials"]),
profileFirstName: computed(() => store.getters["users/profileFirstName"]),
profileLastName: computed(() => store.getters["users/profileLastName"]),
profileUsername: computed(() => store.getters["users/profileUsername"]),
profileEmail: computed(() => store.getters["users/profileEmail"]),
};
const vars = {
modalMessage,
modalActive,
wishedFirstName,
wishedLastName,
wishedUsername,
};
const funcs = {
updFirstName,
updLastName,
updUsername,
updateProfile,
closeModal,
};
return {
...storeComputed,
...funcs,
...vars,
};
},
};
</script>
<style lang="scss" scoped>
.profile {
.container {
max-width: 1000px;
padding: 60px 25px;
h2 {
text-align: center;
margin-bottom: 16px;
font-weight: 300;
font-size: 32px;
}
.profile-info {
border-radius: 8px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
0 2px 4px -1px rgba(0, 0, 0, 0.06);
padding: 32px;
background-color: #f1f1f1;
display: flex;
flex-direction: column;
max-width: 600px;
margin: 32px auto;
.initials {
position: initial;
width: 80px;
height: 80px;
font-size: 32px;
background-color: #303030;
color: #fff;
display: flex;
align-self: center;
align-items: center;
justify-content: center;
border-radius: 50%;
}
.admin-badge {
display: flex;
align-self: center;
color: #fff;
font-size: 14px;
padding: 8px 24px;
border-radius: 8px;
background-color: #303030;
margin: 16px 0;
text-align: center;
text-transform: capitalize;
.icon {
width: 14px;
height: auto;
margin-right: 8px;
}
}
.input {
margin: 16px 0;
label {
font-size: 14px;
display: block;
padding-bottom: 6px;
}
input {
width: 100%;
border: none;
background-color: #f2f7f6;
padding: 8px;
height: 50px;
@media (min-width: 900px) {
}
&:focus {
outline: none;
}
}
}
button {
align-self: center;
}
}
}
}
</style> |
from blogr import db
from datetime import datetime
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(50), unique = True, nullable = False)
email = db.Column(db.String(120), unique = True, nullable = False)
password = db.Column(db.Text, nullable = False)
photo = db.Column(db.String(200))
def __init__(self, username, email, password, photo = None):
self.username = username
self.email = email
self.password = password
self.photo = photo
def __repr__(self):
return f'User: "{self.username}"'
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key = True)
author = db.Column(db.Integer, db.ForeignKey('users.id'), nullable = False)
url = db.Column(db.String(100), unique = True, nullable = False)
title = db.Column(db.String(100), nullable = False)
info = db.Column(db.Text)
content = db.Column(db.Text)
created = db.Column(db.DateTime, nullable = False, default = datetime.utcnow)
def __init__(self, author, url, title, info, content):
self.author = author
self.url = url
self.title = title
self.info = info
self.content = content
def __repr__(self):
return f'Post: "{self.title}"' |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PaymentApplicationAPI.Domain.Models;
using PaymentApplicationAPI.Infrastructure.DataAccessLayer;
using PaymentApplicationAPI.Infrastructure.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace PaymentApplicationAPI.Domain.Services
{
public class OperationService :IOperationService
{
private PaymentCollectionDBContext _dbContext;
private ILogger<OperationService> _logger;
public OperationService(PaymentCollectionDBContext dbContext, ILogger<OperationService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<PaymentResultModel> CreatePayment(PaymentModel payment)
{
var result = new PaymentResultModel();
_logger.LogInformation("Start payment service");
try
{
var moneyReason = await _dbContext.MoneyReasons.FirstOrDefaultAsync(x => x.Id == payment.MoneyReasonId);
var paymentType = await _dbContext.PaymentTypes.FirstOrDefaultAsync(x => x.Id == payment.PaymentTypeId);
var paymentStatus = await _dbContext.PaymentStatuses.FirstOrDefaultAsync(x => x.Name.ToLower() == "In Progress");
//populate tables
if(moneyReason == null)
{
_logger.LogInformation("Money Reason table is empty");
await PopulateMoneyReason();
moneyReason = await _dbContext.MoneyReasons.FirstOrDefaultAsync(x => x.Id == payment.MoneyReasonId);
}
if (paymentStatus == null)
{
_logger.LogInformation("Payment Status table is empty");
await PopulatePaymentStatus();
paymentStatus = await _dbContext.PaymentStatuses.FirstOrDefaultAsync(x => x.Name.ToLower() == "In Progress".ToLower());
}
if (paymentType == null)
{
_logger.LogInformation("payment type table is empty");
await PopulatePaymentType();
paymentType = await _dbContext.PaymentTypes.FirstOrDefaultAsync(x => x.Id == payment.PaymentTypeId);
}
var payeeDetail = new PayeeDetail
{
FirstName = payment.FirstName,
LastName = payment.LastName,
Address = payment.Address,
PostCode = payment.PostCode,
PhoneNumber = payment.PhoneNumber,
Email = payment.PhoneNumber
};
_logger.LogInformation($"payment being processed,Money Reason:{moneyReason}, Payment Type: {paymentType}, Payment Status:{paymentStatus}");
if ((moneyReason != null) && (paymentType != null) && (paymentStatus != null))
{
var serviceOperation = new ServiceOperation
{
ExtraDetails = payment.ExtraDetails,
MoneyReason = moneyReason,
PayeeDetail = payeeDetail,
PaymentType = paymentType,
PaymentAmount = payment.PaymentAmount,
ReferenceId = Guid.NewGuid(),
PaymentStatus = paymentStatus
};
_dbContext.Add(serviceOperation);
_logger.LogInformation($"payment before being saved: {serviceOperation}");
await _dbContext.SaveChangesAsync();
_logger.LogInformation($"payment after being saved: {serviceOperation.ReferenceId}");
result.Status = paymentStatus.Name;
result.Success = true;
result.Message = "This has been processed";
result.Reference = serviceOperation.ReferenceId.ToString();
}
}
catch(Exception ex)
{
_logger.LogError("Error {ex}",ex);
}
return result;
}
private async Task PopulatePaymentStatus()
{
var paymentStatuses = new List<PaymentStatus>{
new PaymentStatus { Name = "In Progress" },
new PaymentStatus { Name = "Complete" },
new PaymentStatus { Name = "Cancelled" }};
_dbContext.AddRange(paymentStatuses);
await _dbContext.SaveChangesAsync();
}
private async Task PopulateMoneyReason()
{
var moneyReasons = new List<MoneyReason> {
new MoneyReason { Name = "Charity"},
new MoneyReason { Name = "Community Hall" },
new MoneyReason { Name = "Renovations" } };
_dbContext.AddRange(moneyReasons);
await _dbContext.SaveChangesAsync();
}
private async Task PopulatePaymentType()
{
var paymentTypes = new List<PaymentType> {new PaymentType { Name = "Cash" },
new PaymentType { Name = "Card" } };
_dbContext.AddRange(paymentTypes);
await _dbContext.SaveChangesAsync();
}
public async Task<List<MoneyReason>> GetMoneyReasons()
{
var result = await _dbContext.MoneyReasons.ToListAsync();
return result;
}
public async Task<List<PaymentStatus>> GetPaymentStatus()
{
var result = await _dbContext.PaymentStatuses.ToListAsync();
return result;
}
public async Task<List<PaymentType>> GetPaymentTypes()
{
var result = await _dbContext.PaymentTypes.ToListAsync();
return result;
}
public async Task<List<PaymentModelResponse>> GetPayments()
{
var result = await _dbContext.ServiceOperations.Include(x=>x.PayeeDetail).Include(x=>x.PaymentStatus).Include(x=>x.MoneyReason).ToListAsync();
var converted = ConvertFromServiceOperationToPaymentModel(result);
return converted;
}
private List<PaymentModelResponse> ConvertFromServiceOperationToPaymentModel(List<ServiceOperation> serviceOperation)
{
var result = serviceOperation.Select(x => new PaymentModelResponse
{
FirstName = x.PayeeDetail.FirstName,
LastName = x.PayeeDetail.LastName,
Address = x.PayeeDetail.Address,
Email = x.PayeeDetail.Email,
PhoneNumber = x.PayeeDetail.PhoneNumber,
PostCode = x.PayeeDetail.PostCode,
ExtraDetails = x.ExtraDetails,
MoneyReasonId = x.MoneyReason.Id,
MoneyReason = x.MoneyReason.Name,
PaymentAmount = x.PaymentAmount,
PaymentTypeId = x.PaymentTypeId,
PaymentStatus = x.PaymentStatus.Name,
PaymentStatusId = x.PaymentStatus.Id,
ReferenceNumber = x.ReferenceId
}).ToList();
return result;
}
}
} |
import axios, { AxiosRequestConfig, AxiosResponse, ResponseType } from 'axios';
import config from '@/config';
import { createPercentProgressNotification, fail, success, updateNotification } from '@/store/notificiationStore';
import { ContactInterface, SharedFileInterface } from '@/types';
import { calcExternalResourceLink } from './urlService';
import { accessDenied, PathInfoModel } from '@/store/fileBrowserStore';
import { useSocketActions } from '@/store/socketStore';
import { FileAction } from 'custom-types/file-actions.type';
import { showUserOfflineMessage } from '@/store/statusStore';
import Spinner from '@/components/Spinner.vue';
const endpoint = `${config.baseUrl}api/v2/quantum`;
export interface PathInfo {
isFile: boolean;
isDirectory: boolean;
directory: string;
path: string;
fullName: string;
name: string;
size: number;
extension: string;
createdOn: Date;
lastModified: Date;
lastAccessed: Date;
}
export interface GetShareToken {
token: string;
}
export interface EditPathInfo extends PathInfoModel {
key: string;
readToken: string;
writeToken: string;
}
export const getDirectoryContent = async (
path: string,
attachments: boolean = false
): Promise<AxiosResponse<PathInfo[]>> => {
// /user
const params = new URLSearchParams();
params.append('path', path);
if (attachments) params.append('attachments', '1');
return await axios.get<PathInfo[]>(`${config.baseUrl}api/v2/quantum/dir/content`, { params: params });
};
export const createDirectory = async (path: string, name: string): Promise<AxiosResponse<PathInfo>> => {
const body = {
path,
name: `/${name}`,
};
return await axios.post<PathInfo>(`${config.baseUrl}api/v2/quantum/dir`, body);
};
export const getFileInfo = async (
path: string,
location?: string,
attachments: boolean = false
): Promise<AxiosResponse<EditPathInfo>> => {
const params = new URLSearchParams();
params.append('path', path);
params.append('attachments', String(attachments));
if (location) params.append('location', location);
return await axios.get(`${config.baseUrl}api/v2/quantum/file/info`, { params: params });
};
export const uploadFile = async (path: string, file: File): Promise<AxiosResponse<PathInfo>> => {
const { sendHandleUploadedFile } = useSocketActions();
const formData = new FormData();
formData.append('file', file);
formData.append('path', path);
let cfg = {
headers: {
'Content-Type': 'multipart/form-data',
},
} as AxiosRequestConfig;
const notification = createPercentProgressNotification('Uploading file', file.name, 0);
cfg = {
...cfg,
onUploadProgress: function (progressEvent) {
notification.progress = Math.round((progressEvent.loaded / progressEvent.total) * 100) / 100;
if (notification.progress === 1) return;
updateNotification(notification);
},
};
try {
const response = await axios.post(`${config.baseUrl}api/v2/files/upload`, formData, cfg);
if (response.status >= 300) {
notification.title = 'Upload failed';
fail(notification);
} else {
notification.title = 'Upload Success';
success(notification);
}
const { data } = response;
if (!data.id) return;
sendHandleUploadedFile({
fileId: String(data.id),
payload: { filename: data.filename, path },
action: FileAction.ADD_TO_QUANTUM,
});
return response;
} catch (ex) {
if (ex.message === 'Request failed with status code 413') {
notification.title = 'File is too big!';
fail(notification);
return;
}
notification.title = 'Upload failed';
fail(notification);
}
};
export const deleteFile = async (path: string) => {
return await axios.delete<PathInfo>(`${config.baseUrl}api/v2/quantum/file/internal?path=${btoa(path)}`);
};
export const downloadFileEndpoint = `${config.baseUrl}api/v2/files/download/compressed`;
export const getDownloadFileEndpoint = (path: string) => {
return `${downloadFileEndpoint}?path=${btoa(path)}`;
};
export const downloadFile = async (path: string, responseType: ResponseType = 'blob') => {
return await axios.get(getDownloadFileEndpoint(path), {
responseType: responseType,
});
};
export const searchDir = async (searchTerm: string, currentDir: string) => {
const params = new URLSearchParams();
params.append('search', searchTerm);
params.append('dir', currentDir);
return await axios.get<PathInfo[]>(`${config.baseUrl}api/v2/quantum/search`, { params: params });
};
export const copyFiles = async (paths: string[], pathToPaste: string) => {
return await axios.post<PathInfo[]>(`${endpoint}/files/copy`, { paths: paths, destination: pathToPaste });
};
export const moveFiles = async (paths: string[], pathToPaste: string) => {
return await axios.post<PathInfo[]>(`${config.baseUrl}api/v2/quantum/move-files`, {
paths: paths,
destination: pathToPaste,
});
};
export const updateFile = async (path: string, content: string, location: string, token: string, key: string) => {
return await axios.post<PathInfo>(`${endpoint}/file/internal?path=${btoa(path)}&token=${token}`, {
content,
location,
status: 2,
key,
});
};
export const renameFile = async (oldPath: string, newPath: string) => {
return await axios.put<PathInfo>(`${config.baseUrl}api/v2/quantum/rename`, { from: oldPath, to: newPath });
};
export const addShare = async (userId: string, path: string, filename: string, size: number, writable: boolean) => {
return await axios.post<GetShareToken>(`${config.baseUrl}api/v2/quantum/share`, {
userId,
isWritable: writable,
path,
isPublic: false,
filename,
size,
});
};
export const removeFilePermissions = async (chatId: string, path: string, location: string) => {
return await axios.post<GetShareToken>(`${config.baseUrl}api/v2/quantum/share/permissions`, {
chatId,
path: btoa(path),
loc: location,
});
};
export const getShared = async (_shareStatus: string) => {
return await axios.get<SharedFileInterface[]>(`${config.baseUrl}api/v2/quantum/shares/shared-with-me`);
};
export const getShareWithId = async (id: string) => {
if (!id) return null;
const params = new URLSearchParams();
params.append('id', id);
params.append('attachments', 'false');
const res = await axios.get(`${config.baseUrl}api/v2/quantum/share`, { params: params });
if (!res.data) {
accessDenied.value = true;
return;
}
return <SharedFileInterface>res.data;
};
export const getFileAccessDetails = async (
owner: ContactInterface,
shareId: string,
userId: string,
path: string,
attachments: boolean
) => {
let externalUrl = `http://[${owner.location}]`;
externalUrl = calcExternalResourceLink(externalUrl);
path = encodeURIComponent(path);
let apiEndPointToCall = `/api/v2/quantum/share/info?shareId=${shareId}&userId=${userId}&path=${path}&attachments=${attachments}`;
apiEndPointToCall = encodeURIComponent(apiEndPointToCall);
externalUrl = externalUrl + apiEndPointToCall;
const res = await axios.get(externalUrl);
return <EditPathInfo>res.data;
};
export const getSharedFolderContent = async (
owner: ContactInterface,
shareId: string,
_userId: string,
path: string
) => {
let externalUrl = `http://[${owner.location}]`;
externalUrl = calcExternalResourceLink(externalUrl);
// TODO: handle in nest
let apiEndPointToCall = `/api/v1/browse/share/${shareId}/folder?path=${path}`;
apiEndPointToCall = encodeURIComponent(apiEndPointToCall);
externalUrl = externalUrl + apiEndPointToCall;
const res = await axios.get(externalUrl);
return <PathInfoModel[]>res.data;
};
export const getShareByPath = async (path: string): Promise<SharedFileInterface> => {
// TODO: handle in nest
return (await axios.get(`${endpoint}/share/path?path=${btoa(path)}`)).data;
};
export const hasSpecialCharacters = (name: string) => {
const format = /[`!@#$%^*=[\]{};':"\\|<>\/?~]/;
return format.test(name);
};
export const generateFileBrowserUrl = (
protocol: 'http' | 'https',
owner: string,
path: string,
token: string,
attachment: boolean = false
) => {
path = encodeURIComponent(path);
token = encodeURIComponent(token);
return `${protocol}://${owner}/api/v2/quantum/file/internal?path=${path}&token=${token}&attachment=${attachment}`;
};
export const generateDocumentServerConfig = (
location: string,
fileDetails: EditPathInfo,
isAttachment: boolean = false,
isLoading: boolean = false
) => {
const { path, key, readToken, writeToken, extension, name } = fileDetails;
const readUrl = generateFileBrowserUrl('http', `[${location}]`, path, readToken, isAttachment);
const writeUrl = generateFileBrowserUrl('http', `[${location}]`, path, writeToken);
const myName = window.location.host.split('.')[0];
return {
document: {
fileType: extension,
key,
title: name,
url: readUrl,
},
height: '100%',
width: '100%',
editorConfig: {
callbackUrl: writeUrl,
customization: {
chat: false,
forcesave: false,
},
user: {
id: myName,
name: myName,
},
mode: writeToken ? 'edit' : 'view',
},
showUserOfflineMessage,
isLoading,
Spinner,
accessDenied,
};
}; |
// https://www.youtube.com/watch?v=SmKM-8Q0Egw
// console.count() - counts how many times this particular line has been called
console.count();
console.count();
console.count();
console.count("label");
console.count("label");
console.countReset("label");
console.count("label");
// console.time() - starts a timer
console.time();
console.time("label");
for (let i = 0; i < 1000; i++) {
// do something
}
console.timeEnd();
console.timeLog("label");
for (let i = 0; i < 1000; i++) {
// do something
}
console.timeEnd("label");
// console.assert() - logs a message and stack trace to the console if the first argument is false
console.assert(1 === 2, "This is wrong");
console.assert(1 === 1, "This is wrong");
// console.table() - displays tabular data as a table
const users = [
{ name: "John", age: 25 },
{ name: "Jane", age: 30 },
{ name: "Jim", age: 35 },
];
// console.table(users);
console.table(users, ["name"]);
// console.group() - creates a new inline group in the console. This indents following console messages by an additional level, until console.groupEnd() is called
console.group("label");
console.log("Hello");
console.log("World");
console.groupEnd();
// console.groupCollapsed() - creates a new inline group in the console. However, the new group is created collapsed, needing to be expanded to be visible
console.groupCollapsed("label");
console.log("Hello");
console.log("World");
console.groupEnd();
console.groupCollapsed("depth 1");
console.log("Hello");
console.groupCollapsed("depth 2");
console.log("World");
console.groupCollapsed("depth 3");
console.log("!");
console.groupEnd();
console.groupEnd();
// console.log() - logs a message to the console
// %c - applies CSS style rules to the output string as specified by the second parameter
console.log(
"This is %cmessage is %cspecial💖",
`
font-style: bold;
color: white;
background: blue;
padding: 5px 10px;
border-radius: 10px
`,
`
font-style: italic;
color: black;
background: pink;
padding: 5px 10px;
border-radius: 10px;
`
); |
<x-admin-layout>
<section>
<div class="container">
@if (Session::has('success') || Session::has('error'))
<div class="alert alert-{{ Session::has('success') ? 'success' : 'danger' }} alert-dismissible fade show"
role="alert">
{{ Session::has('success') ? Session::get('success') : Session::get('error') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<script>
setTimeout(function() {
$('.alert').alert('close');
}, 3000); // Close the alert after 3 seconds (3000 milliseconds)
</script>
@endif
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<a href="{{ route('subscription.index') }}" class="btn btn-primary btn-sm">Back</a>
<h4>Add Subscription Plan</h4>
</div>
<div class="card-body">
<form action="{{ route('subscription.store') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label for="name">Plan Name</label>
<input id="name" class="form-control" type="text" name="name"
value="{{ old('name') }}">
@error('name')
<div class="text-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="description">Description (Optional)</label>
<textarea id="description" class="summernote" name="description" rows="4">{{ old('description') }}</textarea>
@error('description')
<div class="text-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="price">Price (Rs)</label>
<input id="price" class="form-control" type="number" name="price"
value="{{ old('price') }}">
@error('price')
<div class="text-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="duration">Duration</label>
<input id="duration" class="form-control" type="number" name="duration"
value="{{ old('duration') }}">
@error('duration')
<div class="text-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="type">Type</label>
<select id="type" class="form-control" name="type">
<option value="days" {{ old('type') == 'days' ? 'selected' : '' }}>
Days
</option>
<option value="months" {{ old('type') == 'months' ? 'selected' : '' }}>
Months
</option>
<option value="year" {{ old('type') == 'year' ? 'selected' : '' }}>Year</option>
</select>
@error('type')
<div class="text-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="plan">Plan</label>
<select id="plan" class="form-control" name="plan">
<option value="">Select Plan</option>
<option value="basic" {{ old('plan') == 'basic' ? 'selected' : '' }}>Basic
</option>
<option value="standard" {{ old('plan') == 'standard' ? 'selected' : '' }}>Standard
</option>
<option value="premium" {{ old('plan') == 'premium' ? 'selected' : '' }}>Premium
</option>
</select>
@error('plan')
<div class="text-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="active">Active</label>
<select id="active" name="active" class="form-control">
<option value="">Select</option>
<option value="1"{{ old('active') == '1' ? ' selected' : '' }}>Yes</option>
<option value="0"{{ old('active') == '0' ? ' selected' : '' }}>No</option>
</select>
@error('active')
<div class="text-danger">{{ $message }}</div>
@enderror
</div>
<button type="submit" class="btn btn-primary btn-md">Save Plan</button>
</form>
</div>
</div>
</div>
</section>
</x-admin-layout> |
package http
import (
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/finddiff/RuleBaseProxy/adapter/inbound"
"github.com/finddiff/RuleBaseProxy/common/cache"
N "github.com/finddiff/RuleBaseProxy/common/net"
C "github.com/finddiff/RuleBaseProxy/constant"
authStore "github.com/finddiff/RuleBaseProxy/listener/auth"
"github.com/finddiff/RuleBaseProxy/log"
)
func HandleConn(c net.Conn, in chan<- C.ConnContext, cache *cache.Cache) {
client := newClient(c.RemoteAddr(), in)
defer client.CloseIdleConnections()
conn := N.NewBufferedConn(c)
keepAlive := true
trusted := cache == nil // disable authenticate if cache is nil
for keepAlive {
request, err := ReadRequest(conn.Reader())
if err != nil {
break
}
request.RemoteAddr = conn.RemoteAddr().String()
keepAlive = strings.TrimSpace(strings.ToLower(request.Header.Get("Proxy-Connection"))) == "keep-alive"
var resp *http.Response
if !trusted {
resp = authenticate(request, cache)
trusted = resp == nil
}
if trusted {
if request.Method == http.MethodConnect {
//resp = responseWith(200)
//resp.Status = "Connection established"
//resp.ContentLength = -1
//
//if resp.Write(conn) != nil {
// break // close connection
//}
// Manual writing to support CONNECT for http 1.0 (workaround for uplay client)
if _, err = fmt.Fprintf(conn, "HTTP/%d.%d %03d %s\r\n\r\n", request.ProtoMajor, request.ProtoMinor, http.StatusOK, "Connection established"); err != nil {
break // close connection
}
in <- inbound.NewHTTPS(request, conn)
return // hijack connection
}
host := request.Header.Get("Host")
if host != "" {
request.Host = host
}
request.RequestURI = ""
RemoveHopByHopHeaders(request.Header)
RemoveExtraHTTPHostPort(request)
if request.URL.Scheme == "" || request.URL.Host == "" {
resp = responseWith(http.StatusBadRequest)
} else {
resp, err = client.Do(request)
if err != nil {
resp = responseWith(http.StatusBadGateway)
}
}
}
RemoveHopByHopHeaders(resp.Header)
if keepAlive {
resp.Header.Set("Proxy-Connection", "keep-alive")
resp.Header.Set("Connection", "keep-alive")
resp.Header.Set("Keep-Alive", "timeout=4")
}
resp.Close = !keepAlive
err = resp.Write(conn)
if err != nil {
break // close connection
}
}
conn.Close()
}
func authenticate(request *http.Request, cache *cache.Cache) *http.Response {
authenticator := authStore.Authenticator()
if authenticator != nil {
credential := ParseBasicProxyAuthorization(request)
if credential == "" {
resp := responseWith(http.StatusProxyAuthRequired)
resp.Header.Set("Proxy-Authenticate", "Basic")
return resp
}
var authed interface{}
if authed = cache.Get(credential); authed == nil {
user, pass, err := DecodeBasicProxyAuthorization(credential)
authed = err == nil && authenticator.Verify(user, pass)
cache.Put(credential, authed, time.Minute)
}
if !authed.(bool) {
log.Infoln("Auth failed from %s", request.RemoteAddr)
return responseWith(http.StatusForbidden)
}
}
return nil
}
func responseWith(statusCode int) *http.Response {
return &http.Response{
StatusCode: statusCode,
Status: http.StatusText(statusCode),
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: http.Header{},
}
} |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: riolivei <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/07 17:57:41 by riolivei #+# #+# */
/* Updated: 2023/02/23 19:01:42 by riolivei ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef PHILO_H
# define PHILO_H
# include <pthread.h>
# include <stdio.h>
# include <stdlib.h>
# include <sys/time.h>
# include <unistd.h>
# include <limits.h>
# include <stdbool.h>
# define FORK "has taken a fork"
# define EAT "is eating"
# define SLEEP "is sleeping"
# define THINK "is thinking"
# define DIED "died"
typedef struct s_args{
int nphilos;
int nmeals;
long int tdie;
long int teat;
long int tsleep;
} t_args;
typedef struct s_philos{
pthread_t id;
int meals;
int n;
long int last_meal;
pthread_mutex_t eating;
pthread_mutex_t is_dying;
struct s_values *values;
} t_philos;
typedef struct s_values{
long int start_time;
bool deaths;
bool finished;
pthread_mutex_t is_dead;
t_args args;
t_philos *philos;
pthread_mutex_t *forks;
} t_values;
//MAIN.C
int meals_left(t_values *values);
//UTILS.C
long int ft_atoi(const char *str);
int errors(int argc, char *argv[]);
void initiate(char *argv[], t_values *values);
long int get_time(void);
//UTILS2.C
void free_all_stacks(t_values *values, char c);
int died(t_philos *philos, int *count);
void message(t_philos *philos, char *str);
int check_death(t_philos *philos, int fork);
//ACTIONS.C
void thinking(t_philos *philos);
int forking(t_philos *philos);
void eating(t_philos *philos);
void sleeping(t_philos *philos);
void dying(t_philos *philos);
#endif |
# GNU Taler Wallet & Anastasis Web UI
This repository contains the implementation of a wallet for GNU Taler written
in TypeScript and Anastasis Web UI
## Dependencies
The following dependencies are required to build the wallet:
- python>=3.8
- nodejs>=12
- jq
- npm
- pnpm
- zip
## Installation
The CLI version of the wallet supports the normal GNU installation process.
```shell
./configure [ --prefix=$PREFIX ] && make install
```
### Compiling from Git
If you are compiling the code from git, you have to run `./bootstrap` before
running `./configure`.
### Building the WebExtension
The WebExtension can be built via the 'webextension' make target:
```shell
./configure && make webextension
```
This will create the zip file with the WebExtension in the directory
```
packages/taler-wallet-webextension/extension/
```
### Installing local WebExtension
Firefox:
- Settings
- Add-ons
- Manage your extension -> Debug Add-ons
- Load temporary Add-on...
- Look for the zip file under './packages/taler-wallet-webextension/extension/' folder
Chrome:
- Settings
- More tools
- Extensions
- Load unpacked
- Look for the folder under './packages/taler-wallet-webextension/extension/'
You may need to use manifest v2 or v3 depending on the browser version:
https://blog.mozilla.org/addons/2022/05/18/manifest-v3-in-firefox-recap-next-steps/
https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/
### Reviewing WebExtension UI examples
The WebExtension can be tested using example stories.
To run a live server use the 'dev-view' target
```shell
make webextension-dev-view
```
Stories are defined with a \*.stories.tsx file [1], you are free to create new or edit
some and commit them in order to create a more complete set of examples.
[1] look for them at packages/taler-wallet-webextension/src/\*_/_.stories.tsx
### WebExtension UI Components
Every group of component have a directory and a README.
Testing component is based in two main category:
- UI testing
- State transition testing
For UI testing, every story example will be taken as a unit test.
For State testing, every stateful component should have an `useStateComponent` function that will be tested in a \*.test.ts file.
### Testing WebExtension
After building the WebExtension look for the folder `extension`
Inside you will find v2 and v3 version referring to the manifest version being used.
Firefox users:
- Go to about:addons
- Then `debug addon` (or about:debugging#/runtime/this-firefox)
- Then `Load temporary addon...`
- Select the `taler-wallet-webextension-*.zip`
Chrome users:
- Settings -> More tools -> Extensions (or go to chrome://extensions/)
- `Load unpacked` button in the upper left
- Selected the `unpacked` folder in v2 or v3
# Integration Tests
This repository comes with integration tests for GNU Taler. To run them,
install the wallet first. Then use the test runner from the
taler-integrationtests package:
```shell
# List available tests
taler-wallet-cli testing list-integrationtests
# Run all tests
taler-wallet-cli testing run-integrationtests
# Run all tests matching pattern
taler-wallet-cli testing run-integrationtests $GLOB
$ Run all tests from a suite
taler-wallet-cli testing run-integrationtests --suites=wallet
```
The test runner accepts a bash glob pattern as parameter. Individual tests can
be run by specifying their name.
To check coverage, use nyc from the root of the repository and make sure that the taler-wallet-cli
from the source tree is executed, and not the globally installed one:
```
nyc ./packages/taler-wallet-cli/bin/taler-wallet-cli '*'
```
## Minimum required browser for WebEx
Can be found in:
- packages/taler-wallet-webextension/manifest-v2.json
- packages/taler-wallet-webextension/manifest-v3.json
## Anastasis Web UI
## Building for deploy
To build the Anastasis SPA run:
```shell
make anastasis-webui
```
It will run the test suite and put everything into the dist folder under the project root (packages/anastasis-webui).
You can run the SPA directly using the file:// protocol.
```shell
firefox packages/anastasis-webui/dist/ui.html
```
Additionally you can create a zip file with the content to upload into a web server:
```shell
make anastasis-webui-dist
```
It creates the zip file named `anastasis-webui.zip` |
/*
Copyright (C) 2004, 2006 Pablo Bleyer Kocik.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/** @file
PacoBlaze Arithmetic-Logic Unit.
*/
`ifndef PACOBLAZE_ALU_V_
`define PACOBLAZE_ALU_V_
`include "pacoblaze_inc.v"
`ifdef USE_ONEHOT_ENCODING
`define operation(x) operation[(x)]
`define operation_is(x) operation[(x)]
`else
`define operation(x) (x)
`define operation_is(x) (operation == (x))
`endif
module `PACOBLAZE_ALU(
operation,
shift_operation, shift_direction, shift_constant,
result, operand_a, operand_b,
`ifdef HAS_WIDE_ALU
resultw, operand_u, operand_v,
`endif
carry_in, zero_out, carry_out
`ifdef HAS_DEBUG
, debug
`endif
);
input [`operation_width-1:0] operation; ///< Main operation
input [2:0] shift_operation; ///< Rotate/shift operation
input shift_direction; ///< Rotate/shift left(0)/right(1)
input shift_constant; ///< Shift constant (0 or 1)
output reg [`operand_width-1:0] result; ///< ALU result
input [`operand_width-1:0] operand_a, operand_b; ///< ALU operands
`ifdef HAS_WIDE_ALU
output reg [`operand_width-1:0] resultw; ///< wide ALU high result
input [`operand_width-1:0] operand_u, operand_v; ///< wide ALU high operands
`endif
input carry_in; ///< Carry in
output zero_out; ///< Zero out
output reg carry_out; ///< Carry out
`ifdef HAS_DEBUG
output reg [8*`alu_debug_width:1] debug; ///< ALU debug string
reg [18*8:1] debug_rabc; ///< ALU debug operands and result
reg [7*8:1] debug_cz; ///< ALU debug flags
`endif
/** Adder/substracter second operand. */
wire [`operand_width-1:0] addsub_b =
(`operation_is(`op_sub)
|| `operation_is(`op_subcy)
`ifdef HAS_COMPARE_OPERATION
|| `operation_is(`op_compare)
`endif
) ? ~operand_b :
operand_b;
`ifdef HAS_WIDE_ALU
wire [2*`operand_width-1:0] addsubw_b =
(`operation_is(`op_subw) || `operation_is(`op_subwcy)) ? ~{operand_v, operand_b} :
{operand_v, operand_b};
`endif
/** Adder/substracter carry. */
wire addsub_carry =
(`operation_is(`op_addcy)
`ifdef HAS_WIDE_ALU
|| `operation_is(`op_addwcy)
`endif
) ? carry_in :
(`operation_is(`op_sub)
`ifdef HAS_COMPARE_OPERATION
|| `operation_is(`op_compare)
`endif
`ifdef HAS_WIDE_ALU
|| `operation_is(`op_subw)
`endif
) ? 1 : // ~b => b'
(`operation_is(`op_subcy)
`ifdef HAS_WIDE_ALU
|| `operation_is(`op_subwcy)
`endif
) ? ~carry_in : // ~b - c => b' - c
0;
/** Adder/substracter with carry. */
wire [1+`operand_width-1:0] addsub_result = operand_a + addsub_b + addsub_carry;
`ifdef HAS_WIDE_ALU
wire [1+2*`operand_width-1:0] addsubw_result =
{operand_u, operand_a} + addsubw_b + addsub_carry;
`endif
/** Shift bit value. */
// synthesis parallel_case full_case
wire shift_bit =
(shift_operation == `opcode_rr) ? operand_a[0] : // == `opcode_slx
(shift_operation == `opcode_rl) ? operand_a[7] : // == `opcode_srx
(shift_operation == `opcode_rsa) ? carry_in :
shift_constant; // == `opcode_rsc
`ifdef HAS_WIDE_ALU
wire [2*`operand_width-1:0] resultx = {resultw, result};
`endif
assign zero_out =
`ifdef HAS_MUL_OPERATION
(`operation_is(`op_mul)) ? ~|resultx :
`endif
`ifdef HAS_WIDE_ALU
(`operation_is(`op_addw) || `operation_is(`op_addwcy)
|| `operation_is(`op_subw) || `operation_is(`op_subwcy)
) ? ~|resultx :
`endif
~|result;
/*
always @(operation,
shift_operation, shift_direction, shift_constant, shift_bit,
result, operand_a, operand_b, carry_in, carry_out,
addsub_result, addsub_b, addsub_carry
`ifdef HAS_WIDE_ALU
, resultw, operand_v, addsubw_result
`endif
) begin
$display("op:%b %h (%h)=(%h),(%h)", operation, operation, result, operand_a, operand_b);
$display("as:%h=%h+%h+%b", addsub_result, operand_a, addsub_b, addsub_carry);
end
*/
// always @*
always @(operation,
shift_operation, shift_direction, shift_constant, shift_bit,
result, operand_a, operand_b, carry_in, carry_out,
addsub_result, addsub_carry
`ifdef HAS_WIDE_ALU
, resultw, operand_v, addsubw_result
`endif
) begin: on_alu
/* Defaults */
carry_out = 0;
`ifdef HAS_WIDE_ALU
resultw = operand_v;
`endif
// synthesis parallel_case full_case
`ifdef USE_ONEHOT_ENCODING
case (1'b1)
`else
case (operation)
`endif
`operation(`op_add),
`operation(`op_addcy):
{carry_out, result} = addsub_result;
`ifdef HAS_COMPARE_OPERATION
`operation(`op_compare),
`endif
`operation(`op_sub),
`operation(`op_subcy): begin
{carry_out, result} = {~addsub_result[8], addsub_result[7:0]};
end
`operation(`op_and):
result = operand_a & operand_b;
`operation(`op_or):
result = operand_a | operand_b;
`ifdef HAS_TEST_OPERATION
`operation(`op_test):
begin result = operand_a & operand_b; carry_out = ^result; end
`endif
`operation(`op_xor):
result = operand_a ^ operand_b;
`operation(`op_rs):
if (shift_direction) // shift right
{result, carry_out} = {shift_bit, operand_a};
else // shift left
{carry_out, result} = {operand_a, shift_bit};
`ifdef HAS_MUL_OPERATION
`operation(`op_mul):
{resultw, result} = operand_a * operand_b;
`endif
`ifdef HAS_WIDE_ALU
`operation(`op_addw),
`operation(`op_addwcy):
{carry_out, resultw, result} = addsubw_result;
`operation(`op_subw),
`operation(`op_subwcy):
{carry_out, resultw, result} = {~addsubw_result[16], addsubw_result[15:0]};
`endif
default:
result = operand_b;
endcase
end
`ifdef HAS_DEBUG
`include "pacoblaze_util.v"
always @(operand_a, operand_b, result)
debug_rabc = {"r=", numtohex(result[7:4]), numtohex(operand_a[3:0]), " a=", numtohex(operand_a[7:4]), numtohex(operand_a[3:0]), " b=", numtohex(operand_b[7:4]), numtohex(operand_b[3:0]), " c=", numtohex(carry_in)};
always @(carry_in, carry_out, zero_out)
debug_cz = {"C=", numtohex(carry_out), " Z=", numtohex(zero_out)};
always @(debug_rabc, debug_cz)
debug = {debug_rabc, ", ", debug_cz};
`endif // HAS_DEBUG
endmodule
`endif // PACOBLAZE_ALU_V_ |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Istok+Web:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/47c2ad24f2.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header class="purple-bg pb-2">
<nav class="navbar navbar-expand-lg navbar-dark">
<div class="container cont-ainer">
<a class="navbar-brand me-5" href="#">
<img src="images/logo.png" alt="Freedom">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse text-uppercase fw-bold mt-3" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active me-4" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link active me-4" href="#">Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link active me-4" href="#">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link active me-4">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link active">Shop</a>
</li>
</ul>
<hr class="text-white">
<button type="button" class="my-button ms-auto" data-bs-toggle="modal" data-bs-target="#login">
<i class="bi bi-person"></i> </button>
<div class="modal fade" id="login" tabindex="-1" aria-labelledby="loginLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form>
<div class="modal-header">
<h5 class="form-title" id="loginLabel">User Login</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="InputEmail1" class="form-label">Email address</label>
<input type="email" class="form-control" id="InputEmail1">
</div>
<div class="mb-3">
<label for="InputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="InputPassword1">
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="submit"
class="btn btn-lg btn-primary purple-bg my-btn-login">Enter</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</nav>
</header>
<div id="carousel-img" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carousel-img" data-bs-slide-to="0" class="active" aria-current="true"
aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carousel-img" data-bs-slide-to="1" aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carousel-img" data-bs-slide-to="2" aria-label="Slide 3"></button>
</div>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="images/slide-1.jpg" class="d-block w-100" alt="">
</div>
<div class="carousel-item">
<img src="images/slide-2.jpg" class="d-block w-100" alt="">
</div>
<div class="carousel-item">
<img src="images/slide-3.jpg" class="d-block w-100" alt="">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carousel-img" data-bs-slide="prev">
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carousel-img" data-bs-slide="next">
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="container cont-ainer my-5 py-3">
<div class="main-block text-center">
<h1 class="block-titles mb-3">La Liberté guidant le peuple</h1>
<p class="main-block-text fw-bold">La Liberté guidant le peuple est une huile sur toile d'Eugène Delacroix réalisée en 1830, inspirée de la révolution des Trois Glorieuses qui s'est passée en 1830. Présentée au public au Salon de Paris de 1831 sous le titre Scènes de barricades </p>
</div>
</div>
<div class="second-block py-5 bg-light">
<div class="container cont-ainer text-center">
<h2 class="block-titles py-3 mb-3">Postérité de l'œuvre</h2>
<div class="row py-3 justify-content-center">
<div class="col-xxl-4 col-md-6 col-sm-12 d-flex flex-column justify-content-center mt-5">
<p>
<span class="my-icon-border"><i class="bi bi-gear my-icon"></i></span>
</p>
<p class="mt-5 pt-3 my-card-text fw-bold">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni ipsa, iusto placeat quo unde rerum impedit nisi. Accusantium. Lorem ipsum dolor sit amet. ipsum dolor sit amet consectetur, numquam.
</p>
</div>
<div class="col-xxl-4 col-md-6 col-sm-12 d-flex flex-column justify-content-center mt-5">
<p>
<span class="my-icon-border"><i class="bi bi-eye my-icon"></i></span>
</p>
<p class="mt-5 pt-3 my-card-text fw-bold">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni ipsa, iusto
placeat quo unde rerum impedit nisi. Accusantium. Lorem ipsum dolor sit amet.
ipsum dolor sit amet consectetur, numquam.
</p>
</div>
<div class="col-xxl-4 col-md-6 col-sm-12 d-flex flex-column justify-content-center mt-5">
<p>
<span class="my-icon-border"><i class="bi bi-arrow-repeat my-icon"></i></span>
</p>
<p class="mt-5 pt-3 my-card-text fw-bold">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni
ipsa, iusto placeat quo unde rerum impedit nisi. Accusantium.
Lorem ipsum dolor sit amet. ipsum dolor sit amet consectetur,
numquam.
</p>
</div>
</div>
</div>
</div>
<div class="container cont-ainer py-5 text-center">
<h2 class="block-titles mb-2">Notre Equipe</h2>
<div class="row py-3 justify-content-center">
<div class="col-xxl-4 col-md-6 col-sm-12 mt-5">
<div class="card h-100 photo-picture text-start">
<img src="images/photo-1.jpg" class="photo-picture" alt="">
<div class="card-body px-0 pt-0 d-flex flex-column justify-content-between pb-0">
<h5 class="card-title text-uppercase person-name py-2 ps-2 fw-bold">Craig Garner <span class="profession">CEO</span></h5>
<p class="person-description-text pt-2 pb-5">This is a wider card with supporting text content than the first to show that equal height action.</p>
<div class="row pb-3 px-2 text-center mt-auto">
<div class="col-6 p-0 ">
<a href="#" class="facebook-link my-link fa-brands fa-facebook-f">
</a>
</div>
<div class="col-6 p-0">
<a href="#" class="google-link my-link fa-brands fa-google-plus-g"></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xxl-4 col-md-6 col-sm-12 mt-5">
<div class="card h-100 photo-picture text-start">
<img src="images/photo-2.jpg" class="photo-picture" alt="">
<div class="card-body pt-0 px-0 d-flex flex-column justify-content-between pb-0">
<h5 class="card-title text-uppercase person-name py-2 ps-2 fw-bold">Bridge Roberts <span
class="profession">Creative Genius</span></h5>
<p class="person-description-text pt-2 pb-5">This is a wider card with supporting text content
than
the first to show that equal height Lorem ipsum, dolor sit amet consectetur adipisicing elit. Perferendis, totam. Lorem ipsum dolor sit, amet consectetur adipisicing.</p>
<div class="row pb-3 px-2 text-center mt-auto">
<div class="col-6 p-0 ">
<a href="#" class="facebook-link my-link fa-brands fa-facebook-f">
</a>
</div>
<div class="col-6 p-0">
<a href="#" class="dribble-link my-link fa-brands fa-dribbble"></a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xxl-4 col-md-6 col-sm-12 mt-5">
<div class="card h-100 photo-picture text-start">
<img src="images/photo-3.jpg" class="photo-picture" alt="">
<div class="card-body pt-0 px-0 d-flex flex-column justify-content-between pb-0">
<h5 class="card-title text-uppercase person-name py-2 ps-2 fw-bold">Marage Garner <span
class="profession">Chef De Projet</span></h5>
<p class="person-description-text pt-2 pb-5">This is a wider card with supporting text content
than
the first to show that equal height Lorem ipsum, dolor </p>
<div class="row pb-3 px-2 text-center mt-auto">
<div class="col-6 p-0 ">
<a href="#" class="twitter-link my-link fa-brands fa-twitter">
</a>
</div>
<div class="col-6 p-0">
<a href="#" class="youtube-link my-link fa-brands fa-youtube-square"></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer py-4">
<div class="container cont-ainer">
Copyright © Lorem ipsum dolor sit amet consectetur adipisicing elit. Pariatur, officia?
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous">
</script>
</body>
</html> |
SET ECHO OFF
REM ***************************************************************************
REM ******************* Troubleshooting Oracle Performance ********************
REM ************************* http://top.antognini.ch *************************
REM ***************************************************************************
REM
REM File name...: access_structures_1.sql
REM Author......: Christian Antognini
REM Date........: August 2008
REM Description.: This script compares the performance of different access
REM structures in order to read a single row.
REM Notes.......: The script requires the sample schema SH. But, be careful, do
REM not run it with the user SH!
REM Parameters..: -
REM
REM You can send feedbacks or questions about this script to top@antognini.ch.
REM
REM Changes:
REM DD.MM.YYYY Description
REM ---------------------------------------------------------------------------
REM
REM ***************************************************************************
SET TERMOUT ON
SET FEEDBACK OFF
SET VERIFY OFF
SET SCAN ON
VARIABLE rid VARCHAR2(18)
@../connect.sql
SET ECHO ON
REM
REM Regular table with primary key
REM
DROP TABLE sales;
execute dbms_random.seed(0)
CREATE TABLE sales (
id,
prod_id,
cust_id,
time_id,
channel_id,
promo_id,
quantity_sold,
amount_sold,
prod_category,
CONSTRAINT sales_pk PRIMARY KEY (id)
)
AS
SELECT rownum, prod_id, cust_id, time_id, channel_id, promo_id, quantity_sold, amount_sold, prod_category
FROM sh.sales JOIN sh.products USING (prod_id)
--WHERE rownum <= 10
--WHERE rownum <= 10000
ORDER BY round(dbms_random.normal,1);
execute dbms_stats.gather_table_stats(user,'sales')
PAUSE
BEGIN
SELECT rowid INTO :rid FROM sales WHERE id = 6;
END;
/
SET AUTOTRACE TRACE STAT
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE rowid = :rid;
SELECT * FROM sales WHERE rowid = :rid;
SELECT * FROM sales WHERE rowid = :rid;
SET AUTOTRACE OFF
PAUSE
REM
REM Index-organized table
REM
DROP TABLE sales;
execute dbms_random.seed(0)
CREATE TABLE sales (
id,
prod_id,
cust_id,
time_id,
channel_id,
promo_id,
quantity_sold,
amount_sold,
prod_category,
CONSTRAINT sales_pk PRIMARY KEY (id)
)
ORGANIZATION INDEX
AS
SELECT rownum, prod_id, cust_id, time_id, channel_id, promo_id, quantity_sold, amount_sold, prod_category
FROM sh.sales JOIN sh.products USING (prod_id)
--WHERE rownum <= 10
--WHERE rownum <= 10000
ORDER BY round(dbms_random.normal,1);
execute dbms_stats.gather_table_stats(user,'sales')
PAUSE
BEGIN
SELECT rowid INTO :rid FROM sales WHERE id = 6;
END;
/
SET AUTOTRACE TRACE STAT
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE rowid = :rid;
SELECT * FROM sales WHERE rowid = :rid;
SELECT * FROM sales WHERE rowid = :rid;
SET AUTOTRACE OFF
PAUSE
REM
REM Single-table hash cluster
REM
DROP TABLE sales;
DROP CLUSTER sales_cluster;
execute dbms_random.seed(0)
CREATE CLUSTER sales_cluster (id NUMBER)
SINGLE TABLE SIZE 60 HASHKEYS 1000000;
execute dbms_random.seed(0)
CREATE TABLE sales (
id,
prod_id,
cust_id,
time_id,
channel_id,
promo_id,
quantity_sold,
amount_sold,
prod_category,
CONSTRAINT sales_pk PRIMARY KEY (id)
)
CLUSTER sales_cluster (id)
AS
SELECT rownum, prod_id, cust_id, time_id, channel_id, promo_id, quantity_sold, amount_sold, prod_category
FROM sh.sales JOIN sh.products USING (prod_id)
--WHERE rownum <= 10
--WHERE rownum <= 10000
ORDER BY round(dbms_random.normal,1);
execute dbms_stats.gather_table_stats(user,'sales')
PAUSE
BEGIN
SELECT rowid INTO :rid FROM sales WHERE id = 6;
END;
/
SET AUTOTRACE TRACE STAT
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE id = 6;
SELECT * FROM sales WHERE rowid = :rid;
SELECT * FROM sales WHERE rowid = :rid;
SELECT * FROM sales WHERE rowid = :rid;
SET AUTOTRACE OFF
PAUSE
REM
REM Cleanup
REM
DROP TABLE sales;
PURGE TABLE sales;
DROP CLUSTER sales_cluster; |
"""Classes & functions supporting compile_training_data.py."""
from bs4 import BeautifulSoup as Soup
from bs4.element import Comment
from csv import reader
from io import BytesIO
from os import mkdir
from os.path import abspath, exists, join
from PyPDF2.pdf import PdfFileReader
from requests import get
from string import ascii_letters, ascii_uppercase, printable
class Element(object):
"""Models a single cell within a table of training data."""
LABEL = 'LABEL'
URL = 'URL'
TEXT = 'TEXT'
KEYWORDS = 'KEYWORDS'
ALL_TYPES = {LABEL, URL, TEXT, KEYWORDS}
KEYWORD_CHARS = set(ascii_letters + '-, ')
LABEL_CHARS = set(ascii_uppercase + '_')
def __init__(self, string):
self.content = self.clean(string)
self.type = self.categorize(string)
@staticmethod
def clean(string):
"""Remove unprintable characters and excess whitespace."""
string = string.strip()
cleaned_string = ''.join([_ for _ in string if _ in printable])
while cleaned_string.endswith(','):
cleaned_string = cleaned_string.strip(',')
return cleaned_string
@staticmethod
def categorize(string):
"""Recognize the element type based on content."""
if len(string) == 0:
return Element.TEXT
if (' ' not in string) and string.startswith('http'):
return Element.URL
if set(string).issubset(Element.LABEL_CHARS):
return Element.LABEL
if (set(string).issubset(Element.KEYWORD_CHARS) and
(string.count(',') > string.count(' ') / 3.0)
):
return Element.KEYWORDS
return Element.TEXT
class CleanedRow(object):
def __init__(self, elements):
self.elements = elements
count = self.count(Element.URL)
if count > 1:
raise ValueError(
'Cannot have more than one URL per row. Found {}.'.format(count)
)
count = self.count(Element.LABEL)
if count > 1:
raise ValueError(
'Cannot have more than one label per row. Found {}'.format(
count
)
)
count = self.count(Element.KEYWORDS)
if count > 1:
raise ValueError(
'Cannot have more than one block of keywords per row. Found {}'.format(
count
))
self._internal_label = self.get_label_from_elements()
self.label = None
def count(self, element_type):
"""Return the number of elements matching the given type."""
if element_type not in Element.ALL_TYPES:
raise ValueError('Invalid Element type {}'.format(element_type))
return len([ele for ele in self.elements if ele.type == element_type])
def _get_element_content_matching_type(self, element_type):
"""Returns the first element matching the given type.
Returns None if no such element is found.
"""
for ele in self.elements:
if ele.type == element_type:
return ele.content
def get_label_from_elements(self):
"""Looks up the Label for the row, ignoring context from other rows."""
return self._get_element_content_matching_type(Element.LABEL)
def get_url_from_elements(self):
"""Looks up the URL on the row."""
return self._get_element_content_matching_type(Element.URL)
def get_keywords_from_elements(self):
"""Looks up the block of keywords on the row."""
return self._get_element_content_matching_type(Element.KEYWORDS)
def set_label(self, default_label):
"""Sets an explicit label, including context from previous rows."""
internal_label = self.get_label_from_elements()
if internal_label is None:
self.label = default_label
else:
self.label = self._internal_label
return self.label
class TableReader(object):
"""Reads a table of training data copied from Confluence to CSV."""
def __init__(self, filename):
self.filename = filename
self.current_label = None
self.urls = {}
self.keywords = {}
def read(self):
print('Reading from {}'.format(self.filename))
with open(self.filename, 'r') as f:
r = reader(f.readlines())
for row in r:
elements = [Element(string) for string in row]
cleaned = CleanedRow(elements)
self.process_row(cleaned)
print('Done with {}'.format(self.filename))
def process_row(self, cleaned_row):
"""Copy a single input row into lists of urls and keywords"""
self.current_label = cleaned_row.set_label(
default_label=self.current_label
)
if self.current_label is None:
return
current_url = cleaned_row.get_url_from_elements()
if current_url is not None:
if self.current_label in self.urls:
self.urls[self.current_label].add(current_url)
else:
self.urls[self.current_label] = {current_url}
current_keywords = cleaned_row.get_keywords_from_elements()
if current_keywords is not None:
current_keywords = current_keywords.split(',')
current_keywords = {word.strip() for word in current_keywords}
if self.current_label in self.keywords:
self.keywords[self.current_label] |= current_keywords
else:
self.keywords[self.current_label] = current_keywords
class PageScraper(object):
TIMEOUT = 60
HIDDEN_ELEMENTS = {'style', 'script', 'head', 'title', 'meta', 'document'}
def scrape(self, url):
"""Download the given URL and return the text."""
response = self.download_page(url)
return self.convert_to_text(response)
# Internal utility methods
def download_page(self, url):
"""Connect to and download the targeted URL. Returns the raw HTML."""
response = get(url, timeout=self.TIMEOUT)
if 300 <= response.status_code < 400:
raise IOError('Target URL has moved: {}'.format(response.reason))
elif 400 <= response.status_code < 500:
raise IOError(
'Target URL cannot be read as specified: {}'.format(
response.reason
)
)
elif response.status_code >= 500:
raise IOError(
'Target URL had an internal error: {}'.format(response.reason))
return response
def spot_visible(self, element):
"""Return True iff the given element would be visibile to a user."""
if element.parent.name in self.HIDDEN_ELEMENTS:
return False
if isinstance(element, Comment):
return False
return True
def convert_to_text(self, response):
"""Convert whatever format was read to plain text.
Chooses the converter based solely on the content-type in the headers.
"""
# Requests headers use requests.structures.CaseInsensitiveDict, so we
# don't need to worry about the case of the header key. We convert the
# content-type value to lower case to make checks simpler.
content_type = response.headers.get(
'content-type',
'text/html; charset=UTF-8'
).lower()
if 'pdf' in content_type:
return self.pdf_to_text(response.content)
elif 'html' in content_type:
return self.html_to_text(response.text)
elif 'text' not in content_type:
# Assume HTML because it's common
print(
'WARNING: Treating unrecognized content type {} as HTML.'.format(
content_type
)
)
return self.html_to_text(response.text)
return response.text
def html_to_text(self, html):
"""Strips HTML tags and other markup from the file, leaving text."""
soup = Soup(html, "html.parser")
text = soup.find_all(text=True)
visible_texts = filter(self.spot_visible, text)
return ''.join(visible_texts)
@staticmethod
def pdf_to_text(content):
"""Convert downloaded PDF into an approximate plain-text version."""
reader = PdfFileReader(BytesIO(content))
num_pages = reader.getNumPages()
return ''.join([
reader.getPage(pageNum).extractText()
for pageNum in range(num_pages)
])
class DataWriter(object):
"""Reads the specified website and writes"""
KEYWORD_FILE_NAME = 'all_keywords.csv'
def __init__(self, target_directory, table_reader, force_write=False):
self.dir = abspath(target_directory)
self.urls = table_reader.urls.copy()
self.keywords = table_reader.keywords.copy()
self.force_write = force_write
self.failed_urls = set()
self.scraper = PageScraper()
def write(self):
"""Run the Data Writer."""
self.create_dir_if_needed()
self.write_keyword_file()
self.write_scraped_pages()
print('Write complete.')
print('{} Failed URLs:'.format(len(self.failed_urls)))
print('\n'.join(self.failed_urls))
def create_dir_if_needed(self):
"""Make sure there's a directory in which to store the training data."""
if not exists(self.dir):
mkdir(self.dir)
def okay_to_write(self, filename):
"""Tests if a file exists, and if it does, if it can be overwritten."""
if exists(filename):
if self.force_write:
print('WARNING: Overwriting file {}.'.format(filename))
else:
print('ERROR: Cannot overwrite file {}.'.format(filename))
raise FileExistsError('File {} already exists.'.format(
filename
))
else:
print('Writing to {}'.format(filename))
def write_keyword_file(self):
"""Write the output keyword file."""
keyword_file = abspath(join(self.dir, self.KEYWORD_FILE_NAME))
self.okay_to_write(keyword_file)
with open(keyword_file, 'w') as kf:
for label, words in self.keywords.items():
kf.write('{}, {}\n'.format(label, ', '.join(words)))
def write_scraped_pages(self):
"""Write the scraped pages for all URLs."""
category_index = 1
category_count = len(self.urls)
for key, urls in self.urls.items():
print('Beginning category {}/{}.'.format(
category_index,
category_count
))
self.write_pages_for_category(key, urls)
def write_page_for_url(self, output_file, url):
"""Download the targeted page and save it to a file."""
self.okay_to_write(output_file)
text = self.scraper.scrape(url)
self.save_page_text(output_file, text)
@staticmethod
def save_page_text(output_file, text):
"""Saves the given text to a file."""
with open(output_file, 'w') as pf:
pf.write(text)
def write_pages_for_category(self, category, urls):
"""Write one file per URL."""
next_index = 1
for url in urls:
output_file = abspath(
join(self.dir, '{}_{}.txt'.format(category, next_index))
)
try:
self.write_page_for_url(output_file, url)
except Exception as err:
# This is very broad, but if _anything_ goes wrong in the
# processing of the page, it should be caught and logged.
# PdfReadError and RequestError are both plausible, but have no
# common superclass more specific than Exception.
print('WARNING: Target URL {} could not be read: {}'.format(
url,
err
))
self.failed_urls.add(url)
next_index += 1 |
import 'dart:developer';
import 'package:github_treasures/core/config/api_config.dart';
import 'package:github_treasures/core/data/api_client/api_response_model.dart';
import 'package:github_treasures/core/data/api_client/get_api.dart';
import 'package:github_treasures/core/data/remote/authorized_remote.dart';
import 'package:github_treasures/feature/common/resource/api_end_points.dart';
import 'package:github_treasures/feature/github_repo_list/domain/usecase/github_repo_list_uc.dart';
abstract class GithubRepoListRemote {
Future<ApiResponseModel> getList({
required GithubRepoListParams params,
});
}
class GithubRepoListRemoteImpl extends AuthorizedRemote
implements GithubRepoListRemote {
final GetApi _getApi;
const GithubRepoListRemoteImpl({
required super.authorizer,
required GetApi getApi,
}) : _getApi = getApi;
@override
Future<ApiResponseModel> getList({
required GithubRepoListParams params,
}) {
final headers = super.getAuthHeaders();
log(headers.toString(), name: "header");
return super.runThroughAuthSequence(
() => _getApi.call(
"${ApiConfig.instance.baseUrl}/${ApiEndPoints.githubRepoListSearchUrl(
query: params.query,
sort: params.sort,
order: params.order,
page: params.page.toString(),
perPage: params.perPage.toString(),
)}",
headers: super.getAuthHeaders(),
),
);
}
} |
//
// LeftCornerRightCorner.swift
// Essential-Animations
//
// Created by Ajay Gupta on 10/29/21.
//
import SwiftUI
struct LeftCornerRightCorner: View {
@State private var change = false
var body: some View {
VStack(spacing: 20){
Circle()
.foregroundColor(.orange)
.frame(width: 100, height: 100)
.offset(x: change ? 150: -150, y: change ? 700: 0)
.animation(Animation.easeInOut)
Spacer()
Button("Change"){
self.change.toggle()
}.padding(.bottom)
}.font(.title)
}
}
struct LeftCornerRightCorner_Previews: PreviewProvider {
static var previews: some View {
LeftCornerRightCorner()
}
} |
const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
import Milestone from '../Milestone.js';
export default function suite() {
beforeEach(function() {
Milestone._id = 0;
this.m = new Milestone(0, 0, "custom id", "custom descr");
});
it('has correct initial name', function() {
expect(this.m.name).to.equal("custom id");
});
it('has correct initial description', function() {
expect(this.m.description).to.equal("custom descr");
});
it('has no links attached', function() {
expect(this.m.sourceLinks).to.length(0);
expect(this.m.destinationLinks).to.length(0);
});
it('inherits img coordinates from parent class', function() {
expect(this.m).to.have.property('_img');
});
it('has image', function() {
expect(this.m.getImg()).to.be.not.null;
});
it('has id', function() {
expect(this.m.getId()).to.equal(0);
})
it('has not set tmin when created', function() {
expect(this.m.getTmin()).to.equal(null);
});
it('I can set tmin', function() {
this.m.setTmin(0);
expect(this.m.getTmin()).to.equal(0);
});
it('I can set tmin passed as a string', function() {
this.m.setTmin("5.2");
expect(this.m.getTmin()).to.equal(5.2);
});
it('Setting tmin updates graphical element', function() {
this.m.setTmin("5.2");
const el = this.m._getGraphicalElement("milestone-tmin-field");
expect(el.text()).to.equal("5.2");
});
it('I cannot set non-numeric tmin', function() {
this.m.setTmin("halo");
expect(this.m.getTmin()).to.equal(null);
});
it('Setting tmax updates graphical element', function() {
this.m.setTmax("1.2");
const el = this.m._getGraphicalElement("milestone-tmax-field");
expect(el.text()).to.equal("1.2");
});
it('clear clears all timers', function() {
this.m.setTmin("1.2");
this.m.setTmax("1.2");
this.m.setTbuffer("1.2");
this.m.clearTimes();
expect(this.m.getTmin()).to.equal(null);
expect(this.m.getTmax()).to.equal(null);
expect(this.m.getTbuffer()).to.equal(null);
});
it('clear clears all timer graphical elements', function() {
this.m.setTmin("1.2");
this.m.setTmax("1.2");
this.m.setTbuffer("1.2");
this.m.clearTimes();
const tmax = this.m._getGraphicalElement("milestone-tmax-field");
expect(tmax.text()).to.equal("");
const tmin = this.m._getGraphicalElement("milestone-tmin-field");
expect(tmin.text()).to.equal("");
const tb = this.m._getGraphicalElement("milestone-tbuff-field");
expect(tb.text()).to.equal("");
});
it('Setting tbuff updates graphical element', function() {
this.m.setTbuffer("0.5");
const el = this.m._getGraphicalElement("milestone-tbuff-field");
expect(el.text()).to.equal("0.5");
});
it('has not set tmax when created', function() {
expect(this.m.getTmax()).to.equal(null);
});
it('has not set tbuffer when created', function() {
expect(this.m.getTbuffer()).to.equal(null);
});
it('second created milestone has bigger id', function() {
const m2 = new Milestone(0, 0, "custom id", "custom descr");
expect(m2.getId()).greaterThan(this.m.getId());
});
}; |
import torch
import torch.nn as nn
class AttrProxy(object):
"""
Translates index lookups into attribute lookups.
To implement some trick which able to use list of nn.Module in a nn.Module
see https://discuss.pytorch.org/t/list-of-nn-module-in-a-nn-module/219/2
"""
def __init__(self, module, prefix):
self.module = module
self.prefix = prefix
def __getitem__(self, i):
return getattr(self.module, self.prefix + str(i))
class Propogator(nn.Module):
"""
Gated Propogator for GGNN
Using LSTM gating mechanism
"""
def __init__(self, state_dim, n_edge_types):
super(Propogator, self).__init__()
self.n_edge_types = n_edge_types
self.reset_gate = nn.Sequential(
nn.Linear(state_dim*3, state_dim),
nn.Sigmoid()
)
self.update_gate = nn.Sequential(
nn.Linear(state_dim*3, state_dim),
nn.Sigmoid()
)
self.tansform = nn.Sequential(
nn.Linear(state_dim*3, state_dim),
nn.Tanh()
)
def forward(self, state_in, state_out, state_cur, A):
n_node = A.shape[1]
A_in = A[:, :, :n_node*self.n_edge_types]
A_out = A[:, :, n_node*self.n_edge_types:]
a_in = torch.bmm(A_in, state_in)
a_out = torch.bmm(A_out, state_out)
a = torch.cat((a_in, a_out, state_cur), 2)
r = self.reset_gate(a)
z = self.update_gate(a)
joined_input = torch.cat((a_in, a_out, r * state_cur), 2)
h_hat = self.tansform(joined_input)
output = (1 - z) * state_cur + z * h_hat
return output
class GGNN(nn.Module):
"""
Gated Graph Sequence Neural Networks (GGNN)
Mode: SelectNode
Implementation based on https://arxiv.org/abs/1511.05493
"""
def __init__(self, opt):
super(GGNN, self).__init__()
self.state_dim = opt['state_dim']
# self.annotation_dim = opt.annotation_dim
self.n_edge_types = opt['n_edge_types']
# self.n_node = opt.n_node
self.n_steps = opt['n_steps']
self.in_list = nn.ModuleList()
self.out_list = nn.ModuleList()
for i in range(self.n_edge_types):
in_fc = nn.Linear(self.state_dim, self.state_dim)
out_fc = nn.Linear(self.state_dim, self.state_dim)
self.in_list.append(in_fc)
self.out_list.append(out_fc)
# Propogation Model
self.propogator = Propogator(self.state_dim, self.n_edge_types)
# Output Model
self.out = nn.Sequential(
nn.Linear(self.state_dim*2, self.state_dim),
)
self.activation = nn.Tanh()
self._initialization()
def _initialization(self):
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data.normal_(0.0, 0.02)
m.bias.data.fill_(0)
def forward(self, prop_state, A):
# embedding = prop_state
n_node = A.shape[1]
for i_step in range(self.n_steps):
in_states = []
out_states = []
for i in range(self.n_edge_types):
in_states.append(self.in_list[i](prop_state))
out_states.append(self.out_list[i](prop_state))
in_states = torch.stack(in_states).transpose(0, 1).contiguous()
in_states = in_states.view(-1, n_node*self.n_edge_types, self.state_dim)
out_states = torch.stack(out_states).transpose(0, 1).contiguous()
out_states = out_states.view(-1, n_node*self.n_edge_types, self.state_dim)
prop_state = self.propogator(in_states, out_states, prop_state, A)
return prop_state
# return output |
<template>
<div class="setting__container">
<h2 class="page__title1">アカウント設定</h2>
<div class="main__part">
<div class="menu_part">
<h3>{{ $store.getters['auth/user'].com_name }}<br/>{{ $store.getters['auth/user'].name }}様</h3>
<a :class="{ current: tab == 1 }" @click="() => { tab = 1 }">会社情報<span v-if="tab == 1"></span></a>
</div>
<div class="main_panel">
<h2 class="page__title black">{{ tab == 1 ? '会社情報' : 'ユーザー一覧' }}</h2>
<div class="table_cont" v-if="tab == 1">
<vue-good-table
:columns="columns"
:rows="rows"
:pagination-options="{
enabled: false,
}">
<template slot="table-row" slot-scope="props">
<div v-if="props.column.field == 'edit'">
<button @click="editModal" class="detail_btn">編集</button>
</div>
<div class="table_cell" v-else>
{{ props.formattedRow[props.column.field] }}
</div>
</template>
</vue-good-table>
</div>
</div>
</div>
<EditModal v-if="isShowModal" @closeModal="closeModal" />
</div>
</template>
<script>
import EditModal from '../../../components/client/EditModal.vue'
export default {
layout: 'client',
components: {
EditModal
},
data() {
return {
isShowModal: false,
tab: 1,
columns: [
{
label: '会社名/屋号',
field: 'com_name',
sortable: false
},
{
label: '住所',
field: 'address',
sortable: false
},
{
label: '電話番号',
field: 'phoneNumber',
sortable: false
},
{
label: '',
field: 'edit',
sortable: false
},
],
rows: [
{
id: 1,
com_name: '株式会社〇〇〇〇',
address: '〒500-0000 大阪府大阪市北区〇〇町1-4-4',
phoneNumber: '06-1234-1234',
},
],
}
},
methods: {
editModal() {
this.isShowModal = true
},
closeModal() {
this.isShowModal = false
this.init()
},
init() {
this.rows = []
this.rows.push({
id: this.$store.getters['auth/user'].id,
com_name: this.$store.getters['auth/user'].com_name,
address: (this.$store.getters['auth/user'].prefecture || '') + (this.$store.getters['auth/user'].city || '') + (this.$store.getters['auth/user'].building || ''),
phoneNumber: this.$store.getters['auth/user'].telephone
})
}
},
mounted() {
this.init()
}
}
</script>
<style lang="scss" scoped>
.setting__container {
padding: 20px 30px;
}
.main__part {
display: flex;
margin-top: 20px;
align-items: flex-start;
.menu_part {
width: 200px;
border: 1px solid var(--border-color);
h3 {
font-size: 14px;
text-align: center;
height: 80px;
width: 100%;
line-height: 1.6;
padding-top: 14px;
border-bottom: 1px solid var(--border-color);
position: relative;
&:after {
content: "";
position: absolute;
left: 0;
width: 10px;
background-color: var(--accent-color2);
top: 0;
height: 100%
}
}
a {
display: flex;
align-items: center;
height: 40px;
background-color: #fff;
padding-left: 21px;
padding-right: 10px;
font-size: 14px;
position: relative;
border-bottom: 1px solid var(--border-color);
color: var(--text-color);
img {
margin-left: auto;
}
&:before {
content: "";
position: absolute;
left: 0;
width: 10px;
background-color: var(--accent-color2);
top: 0;
height: 100%
}
&.current {
&:before {
content: "";
position: absolute;
left: 0;
width: 10px;
background-color: #48515D;
top: 0;
height: 100%
}
}
span {
margin-left: auto;
border-top: 6px solid transparent;
border-bottom: 6px solid transparent;
border-left: 12px solid var(--accent-color2);
}
}
}
.main_panel {
padding: 14px 20px;
background-color: #fff;
border: 1px solid var(--border-color);
width: 850px;
position: relative;
.page__title {
font-size: 14px;
}
}
}
.table_cont {
margin-top: 25px;
box-shadow: 0 3px 6px rgba($color: #000000, $alpha: 0.16);
&.table_cont1 {
width: 300px;
}
}
.detail_btn {
width: 60px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
border: 0;
background-color: var(--border-color);
color: #fff;
font-size: 12px;
}
.seal_part {
margin-top: 60px;
display: flex;
.label {
border: 1px solid var(--border-color);
height: 80px;
width: 160px;
display: flex;
align-items: center;
padding-left: 10px;
&.label1 {
height: auto;
}
}
.value {
width: 160px;
height: 80px;
border: 1px solid var(--border-color);
display: flex;
align-items: center;
padding-left: 10px;
&.value1 {
height: auto;
width: 532px;
padding-right: 18px;
padding-top: 12px;
padding-bottom: 12px;
button {
margin-left: auto;
font-size: 12px;
background-color: var(--border-color);
color: #fff;
border: 0;
width: 50px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
}
}
.seal {
width: 50px;
height: 50px;
border: 1px dotted var(--border-color);
display: flex;
align-items: center;
justify-content: center;
margin-right: auto;
span {
font-size: 8px;
}
}
&>div {
margin-right: 25px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
button {
font-size: 12px;
background-color: var(--border-color);
color: #fff;
border: 0;
width: 50px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 8px;
}
a {
width: 18px;
height: 18px;
}
}
}
}
.append_btn {
position: absolute;
right: 20px;
top: 30px;
display: flex;
align-items: center;
justify-content: center;
width: 120px;
height: 30px;
background-color: #985298;
color: #fff;
font-size: 12px;
border: 0;
img {
width: 20px;
margin-right: 4px;
}
}
.user_setting_edit_btn {
padding-top: 48px;
display: flex;
justify-content: center;
width: 300px;
button {
width: 180px;
height: 35px;
display: flex;
align-items: center;
justify-content: center;
background-color: var(--accent-color2);
color: #fff;
font-size: 14px;
border: 0;
}
}
</style> |
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React, { forwardRef, useState } from 'react';
import { Draggable } from 'react-beautiful-dnd';
import { useKanbanBlockContext } from '../KanbanBlockProvider';
import Card from './Card';
import CardAdder from './CardAdder';
import { pickPropOut } from './utils';
import withDroppable from './withDroppable';
const ColumnEmptyPlaceholder = forwardRef(
(
props: {
children: React.ReactNode;
style?: React.CSSProperties;
},
ref: any,
) => {
return (
<div ref={ref} {...props} style={{ minHeight: 'inherit', height: 'var(--column-height)', ...props.style }} />
);
},
);
ColumnEmptyPlaceholder.displayName = 'ColumnEmptyPlaceholder';
const DroppableColumn = withDroppable(ColumnEmptyPlaceholder);
function Column({
children,
index: columnIndex,
renderCard,
renderCardAdder = ({ column, onConfirm }) => <CardAdder column={column} onConfirm={onConfirm} />,
renderColumnHeader,
disableColumnDrag,
disableCardDrag,
onCardNew,
allowAddCard,
cardAdderPosition = 'top',
}) {
const { fixedBlock } = useKanbanBlockContext();
const [headerHeight, setHeaderHeight] = useState(0);
return (
<Draggable draggableId={`column-draggable-${children.id}`} index={columnIndex} isDragDisabled={disableColumnDrag}>
{(columnProvided) => {
const draggablePropsWithoutStyle = pickPropOut(columnProvided.draggableProps, 'style');
return (
<div
ref={columnProvided.innerRef}
{...draggablePropsWithoutStyle}
style={{
height: '100%',
minHeight: '28px',
display: 'inline-block',
verticalAlign: 'top',
...columnProvided.draggableProps.style,
'--column-height': fixedBlock ? `calc(100% - ${headerHeight}px)` : 'inherit',
}}
className="react-kanban-column"
data-testid={`column-${children.id}`}
>
<div
ref={fixedBlock ? (ref) => setHeaderHeight(Math.ceil(ref?.getBoundingClientRect().height || 0)) : null}
{...columnProvided.dragHandleProps}
>
{renderColumnHeader(children)}
</div>
{cardAdderPosition === 'top' && allowAddCard && renderCardAdder({ column: children, onConfirm: onCardNew })}
<DroppableColumn droppableId={String(children.id)}>
{children?.cards?.length ? (
<div
className="react-kanban-card-skeleton"
style={{
height: fixedBlock ? '100%' : undefined,
}}
>
{children.cards.map((card, index) => (
<Card
key={card.id}
index={index}
renderCard={(dragging) => renderCard(children, card, dragging)}
disableCardDrag={disableCardDrag}
>
{card}
</Card>
))}
</div>
) : (
<div className="react-kanban-card-skeleton" />
)}
</DroppableColumn>
{cardAdderPosition === 'bottom' &&
allowAddCard &&
renderCardAdder({ column: children, onConfirm: onCardNew })}
</div>
);
}}
</Draggable>
);
}
export default Column; |
/// <reference path="../interfaces.d.ts" />
import React from "react";
declare var d3: any;
class Chart extends React.Component <IAppState> {
constructor(props:IAppState) {
super(props);
this.state = {
checkedGrid : this.props.checkedGrid,
checkedLabelAxis: this.props.checkedLabelAxis
}
}
componentDidUpdate() {
if (this.props.reDraw) {
this.drawChart();
}
if (this.props.checkedGrid) {
d3.selectAll(" .tick line").attr("display", "block");
} else {
d3.selectAll(" .tick line").attr("display", "none");
}
if (this.props.checkedLabelAxis) {
d3.selectAll(".axis text").attr("display", "block");
} else {
d3.selectAll(".axis text").attr("display", "none");
}
};
render() {
return (
<svg id="svg">
</svg>
);
}
drawChart = () => {
const amountPoint : number = Number(this.props.amountPoint);
const minY : number = Number(this.props.minY);
const maxY : number = Number(this.props.maxY);
const widthSVG : number = Number(this.props.width);
const heightSVG : number = Number(this.props.height);
let data: point[] = this.props.points;
//************************************************************
// Очистка SVG
//************************************************************
d3.selectAll("svg > *").remove();
//************************************************************
// Создание осей и отступов и подключение функции зуммирования
//************************************************************
let margin : {top: number; right: number; bottom: number; left: number} =
{top: 20, right: 10, bottom: 30, left: 50},
width : number = widthSVG- margin.left - margin.right,
height : number = heightSVG - margin.top - margin.bottom;
let xScale : any = d3.scale.linear()
.domain([0, amountPoint+1])
.range([0, width]);
let yScale : any = d3.scale.linear()
.domain([minY-5, maxY+5])
.range([height, 0]);
let xAxis : any = d3.svg.axis()
.scale(xScale)
.tickSize(-height)
.tickPadding(10)
.orient("bottom");
let yAxis : any = d3.svg.axis()
.scale(yScale)
.tickPadding(10)
.tickSize(-width)
.orient("left");
let zoom : any = d3.behavior.zoom()
.x(xScale)
.y(yScale)
.scaleExtent([1, 10])
.on("zoom", zoomed);
//************************************************************
// Создание SVG-объекта
//************************************************************
let svg : any = d3.select("svg")
.call(zoom)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
//************************************************************
// Рисование line-объекта с данными на SVG
//************************************************************
let line : any = d3.svg.line()
.x(function(d:point) {return xScale(d.x); })
.y(function(d:point) { return yScale(d.y); })
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("clip-path", "url(#clip)")
.attr('stroke', 'steelblue')
.attr("d", line);
//************************************************************
// Рисование точек
//************************************************************
let points = svg.selectAll('.dots')
.data([data])
.enter()
.append("g")
.attr("class", "dots")
.attr("clip-path", "url(#clip)");
points.selectAll('.dot')
.data(data)
.enter()
.append('circle')
.attr('class','dot')
.attr("r", 2.5)
.attr('fill', "black")
.attr("transform", function(d:point) {
return "translate(" + xScale(d.x) + "," + yScale(d.y) + ")"; }
);
//************************************************************
// Функция зуммирования
//************************************************************
function zoomed() : void {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
svg.selectAll('path.line').attr('d', line);
points.selectAll('circle').attr("transform", function(d:any) {
return "translate(" + xScale(d.x) + "," + yScale(d.y) + ")"; }
);
// добавление и удаление сетки и меток
if (d3.select("#grid").property("checked")) {
d3.selectAll(" .tick line").attr("display", "block");
} else {
d3.selectAll(" .tick line").attr("display", "none");
}
if (d3.select("#tags").property("checked")) {
d3.selectAll(".axis text").attr("display", "block");
} else {
d3.selectAll(".axis text").attr("display", "none");
}
}
}
}
export default Chart; |
@using BackEndProject.Areas.Admin.ViewModels;
@model CoursesVM
@{
ViewData["Title"] = "Update";
Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
}
<div class="content-wrapper col-11">
<div class="row">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Courses</h4>
<p class="card-description">
Course Update
</p>
<h4 class="card-title" style="margin-top:40px">Current Event Photo</h4>
<div class="alert alert-danger" asp-validation-summary="ModelOnly"></div>
<img src="~/admin/images/faces/@Model.Course.Image" width="100" alt="Alternate Photo" />
<form class="forms-sample" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="Photo">Photo</label>
<input class="form-control" asp-for="Photo" placeholder="Photo">
<span asp-validation-for="Photo" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Title">Title</label>
<input class="form-control" value="@Model.Course.Title" asp-for="Title" placeholder="Title">
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Description">Description</label>
<textarea class="form-control" value="@Model.Course.Description" id="courseeditorId" asp-for="Description" placeholder="Description"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Starts">Starts</label>
<input class="form-control" value="@Model.Course.Starts" asp-for="Starts" placeholder="Starts">
<span asp-validation-for="Starts" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Duration">Duration</label>
<input class="form-control" value="@Model.Course.Duration" asp-for="Duration" placeholder="Duration">
<span asp-validation-for="Duration" class="text-danger"></span>
</div>
<div class="form-group">
<label for="ClassDuration">ClassDuration</label>
<input class="form-control" value="@Model.Course.ClassDuration" asp-for="ClassDuration" placeholder="ClassDuration">
<span asp-validation-for="ClassDuration" class="text-danger"></span>
</div>
<div class="form-group">
<label for="SkillLevel">SkillLevel</label>
<input class="form-control" value="@Model.Course.SkillLevel" asp-for="SkillLevel" placeholder="SkillLevel">
<span asp-validation-for="SkillLevel" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Language">Language</label>
<input class="form-control" value="@Model.Course.Language" asp-for="Language" placeholder="Language">
<span asp-validation-for="Language" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Students">Students</label>
<input class="form-control" value="@Model.Course.Students" asp-for="Students" placeholder="Students">
<span asp-validation-for="Students" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Assesments">Assesments</label>
<input class="form-control" value="@Model.Course.Assesments" asp-for="Assesments" placeholder="Assesments">
<span asp-validation-for="Assesments" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Fee">Fee</label>
<input class="form-control" value="@Model.Course.Fee" asp-for="Fee" placeholder="Fee">
<span asp-validation-for="Fee" class="text-danger"></span>
</div>
<div class="mt-3">
<label style="font-size:15px;font-weight:bold">Select Category: </label>
<select class="js-example-basic-multiple" id="selectCategory" name="states" multiple="multiple" style="width:100%">
@foreach(Category category in Model.Categories)
{
if(Model.CourseCategories.FirstOrDefault(c=>c.CategoryId==category.Id) !=null)
{
<option selected value="@category.Id">@category.Name</option>
}
else
{
<option value="@category.Id">@category.Name</option>
}
}
</select>
</div>
<div class="form-check form-check-flat form-check-primary">
<button type="submit" class="btn btn-warning mr-2">Update</button>
<a class="btn btn-light" asp-action="Index">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@section Scripts{
<script src="~/ckeditor/ckeditor.js"></script>
<script>
CKEDITOR.replace("courseeditorId");
</script>
} |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: apache 2.0
/*
Copyright 2022 Debond Protocol <info@debond.org>
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.
*/
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../utils/ExecutableOwnable.sol";
contract DGOVTest is ERC20, ExecutableOwnable {
address bankAddress;
mapping(address => uint256) allocatedBalance;
uint maxSupply = 1000000 ether;
uint256 maxAllocationPercentage;
constructor(
address _executableAddress
) ERC20("DGOV", "DGOV") ExecutableOwnable(_executableAddress) {}
function updateBankAddress(address _bankAddress) external onlyExecutable {
bankAddress = _bankAddress;
}
function mintAllocatedSupply(address _to, uint256 _amount) external {
_mint(_to, _amount);
allocatedBalance[_to] += _amount;
}
function mint(address _to, uint256 _amount) external {
_mint(_to, _amount);
}
function getAllocatedBalance(address _account) external view returns(uint256) {
return allocatedBalance[_account];
}
function getTotalCollateralisedSupply() external view returns(uint256) {
return totalSupply();
}
function setMaxSupply(uint256 max_supply) external returns (bool) {
maxSupply = max_supply;
return true;
}
function getMaxSupply() external view returns(uint256) {
return maxSupply;
}
function setMaxAllocationPercentage(uint256 newPercentage) external returns (bool) {
maxAllocationPercentage = newPercentage;
return true;
}
function getMaxAllocatedPercentage() external view returns(uint256) {
return maxAllocationPercentage;
}
function getBankAddress() external view returns(address) {
return bankAddress;
}
} |
package org.usvm.samples.arrays
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.usvm.CoverageZone
import org.usvm.samples.JavaMethodTestRunner
import org.usvm.test.util.checkers.eq
import org.usvm.test.util.checkers.ge
import org.usvm.test.util.checkers.ignoreNumberOfAnalysisResults
import org.usvm.util.isException
internal class IntArrayBasicsTest : JavaMethodTestRunner() {
@Test
fun testInitArray() {
checkDiscoveredPropertiesWithExceptions(
IntArrayBasics::initAnArray,
ignoreNumberOfAnalysisResults,
{ _, n, r -> n < 0 && r.isException<NegativeArraySizeException>() },
{ _, n, r -> n == 0 && r.isException<IndexOutOfBoundsException>() },
{ _, n, r -> n == 1 && r.isException<IndexOutOfBoundsException>() },
{ _, n, r ->
val resultArray = IntArray(n) { if (it == n - 1 || it == n - 2) it else 0 }
n > 1 && r.getOrNull() contentEquals resultArray
}
)
}
@Test
fun testIsValid() {
checkDiscoveredPropertiesWithExceptions(
IntArrayBasics::isValid,
ignoreNumberOfAnalysisResults,
{ _, a, _, r -> a == null && r.isException<NullPointerException>() },
{ _, a, n, r -> a != null && (n < 0 || n >= a.size) && r.isException<IndexOutOfBoundsException>() },
{ _, a, n, r -> a != null && n in a.indices && a[n] == 9 && n == 5 && r.getOrNull() == true },
{ _, a, n, r -> a != null && n in a.indices && !(a[n] == 9 && n == 5) && r.getOrNull() == false },
{ _, a, n, r -> a != null && n in a.indices && a[n] > 9 && n == 5 && r.getOrNull() == true },
{ _, a, n, r -> a != null && n in a.indices && !(a[n] > 9 && n == 5) && r.getOrNull() == false },
)
}
@Test
fun testGetValue() {
checkDiscoveredPropertiesWithExceptions(
IntArrayBasics::getValue,
ge(4),
{ _, a, _, r -> a == null && r.isException<NullPointerException>() },
{ _, a, n, r -> a != null && a.size > 6 && (n < 0 || n >= a.size) && r.isException<IndexOutOfBoundsException>() },
{ _, a, n, r -> a != null && a.size > 6 && n < a.size && r.getOrNull() == a[n] },
{ _, a, _, r -> a != null && a.size <= 6 && r.getOrNull() == -1 }
)
}
@Test
fun testSetValue() {
checkDiscoveredPropertiesWithExceptions(
IntArrayBasics::setValue,
ignoreNumberOfAnalysisResults,
{ _, _, x, r -> x <= 0 && r.getOrNull() == 0 },
{ _, a, x, r -> x > 0 && a == null && r.isException<NullPointerException>() },
{ _, a, x, r -> x > 0 && a != null && a.isEmpty() && r.getOrNull() == 0 },
{ _, a, x, r -> x in 1..2 && a != null && a.isNotEmpty() && r.getOrNull() == 1 },
{ _, a, x, r -> x > 2 && a != null && a.isNotEmpty() && r.getOrNull() == 2 }
)
}
@Test
fun testCheckFour() {
checkDiscoveredPropertiesWithExceptions(
IntArrayBasics::checkFour,
ignoreNumberOfAnalysisResults,
{ _, a, r -> a == null && r.isException<NullPointerException>() },
{ _, a, r -> a != null && a.size < 4 && r.getOrNull() == -1 },
{ _, a, r -> a != null && a.size >= 4 && a[0] != 1 && r.getOrNull() == 0 },
{ _, a, r -> a != null && a.size >= 4 && a[0] == 1 && a[1] != 2 && r.getOrNull() == 0 },
{ _, a, r -> a != null && a.size >= 4 && a[0] == 1 && a[1] == 2 && a[2] != 3 && r.getOrNull() == 0 },
{ _, a, r -> a != null && a.size >= 4 && a[0] == 1 && a[1] == 2 && a[2] == 3 && a[3] != 4 && r.getOrNull() == 0 },
{ _, a, r ->
require(a != null)
val precondition = a.size >= 4 && a[0] == 1 && a[1] == 2 && a[2] == 3 && a[3] == 4
val postcondition = r.getOrNull() == IntArrayBasics().checkFour(a)
precondition && postcondition
}
)
}
@Test
fun testNullability() {
checkDiscoveredProperties(
IntArrayBasics::nullability,
eq(3),
{ _, a, r -> a == null && r == 1 },
{ _, a, r -> a != null && a.size > 1 && r == 2 },
{ _, a, r -> a != null && a.size in 0..1 && r == 3 },
)
}
@Test
fun testEquality() {
checkDiscoveredProperties(
IntArrayBasics::equality,
eq(4),
{ _, a, _, r -> a == null && r == 1 },
{ _, a, b, r -> a != null && b == null && r == 1 },
{ _, a, b, r -> a != null && b != null && a.size == b.size && r == 2 },
{ _, a, b, r -> a != null && b != null && a.size != b.size && r == 3 },
)
}
@Test
fun testOverwrite() {
checkDiscoveredPropertiesWithExceptions(
IntArrayBasics::overwrite,
ignoreNumberOfAnalysisResults,
{ _, a, _, r -> a == null && r.isException<NullPointerException>() },
{ _, a, _, r -> a != null && a.size != 1 && r.getOrNull() == 0 },
{ _, a, b, r -> a != null && a.size == 1 && a[0] > 0 && b < 0 && r.getOrNull() == 1 },
{ _, a, b, r -> a != null && a.size == 1 && a[0] > 0 && b >= 0 && r.getOrNull() == 2 },
{ _, a, _, r -> a != null && a.size == 1 && a[0] <= 0 && r.getOrNull() == 3 },
)
}
@Test
fun testMergeArrays() {
checkDiscoveredProperties(
IntArrayBasics::mergeArrays,
ignoreNumberOfAnalysisResults,
{ _, fst, _, _ -> fst == null },
{ _, fst, snd, _ -> fst != null && snd == null },
{ _, fst, snd, r -> fst != null && snd != null && fst.size < 2 && r == null },
{ _, fst, snd, r -> fst != null && snd != null && fst.size >= 2 && snd.size < 2 && r == null },
{ _, fst, snd, r ->
require(fst != null && snd != null && r != null)
val sizeConstraint = fst.size >= 2 && snd.size >= 2 && r.size == fst.size + snd.size
val maxConstraint = fst.maxOrNull()!! < snd.maxOrNull()!!
val contentConstraint = r contentEquals (IntArrayBasics().mergeArrays(fst, snd))
sizeConstraint && maxConstraint && contentConstraint
},
{ _, fst, snd, r ->
require(fst != null && snd != null && r != null)
val sizeConstraint = fst.size >= 2 && snd.size >= 2 && r.size == fst.size + snd.size
val maxConstraint = fst.maxOrNull()!! >= snd.maxOrNull()!!
val contentConstraint = r contentEquals (IntArrayBasics().mergeArrays(fst, snd))
sizeConstraint && maxConstraint && contentConstraint
}
)
}
@Test
fun testNewArrayInTheMiddle() {
checkDiscoveredProperties(
IntArrayBasics::newArrayInTheMiddle,
ignoreNumberOfAnalysisResults,
{ _, a, _ -> a == null },
{ _, a, _ -> a != null && a.isEmpty() },
{ _, a, _ -> a != null && a.size < 2 },
{ _, a, _ -> a != null && a.size < 3 },
{ _, a, r -> a != null && a.size >= 3 && r != null && r[0] == 1 && r[1] == 2 && r[2] == 3 }
)
}
@Test
fun testNewArrayInTheMiddleMutation() {
checkThisAndParamsMutations(
IntArrayBasics::newArrayInTheMiddle,
ignoreNumberOfAnalysisResults,
{ _, _, _, arrayAfter, r ->
arrayAfter[0] == 1 && arrayAfter[1] == 2 && arrayAfter[2] == 3 && r!!.zip(arrayAfter).all { it.first == it.second }
},
checkMode = CheckMode.MATCH_PROPERTIES
)
}
@Test
fun testReversed() {
checkDiscoveredProperties(
IntArrayBasics::reversed,
ignoreNumberOfAnalysisResults,
{ _, a, _ -> a == null },
{ _, a, _ -> a != null && a.size != 3 },
{ _, a, r -> a != null && a.size == 3 && a[0] <= a[1] && r == null },
{ _, a, r -> a != null && a.size == 3 && a[0] > a[1] && a[1] <= a[2] && r == null },
{ _, a, r -> a != null && a.size == 3 && a[0] > a[1] && a[1] > a[2] && r contentEquals a.reversedArray() },
)
}
@Test
fun testUpdateCloned() {
checkDiscoveredProperties(
IntArrayBasics::updateCloned,
eq(3),
{ _, a, _ -> a == null },
{ _, a, _ -> a.size != 3 },
{ _, a, r -> a.size == 3 && r != null && r.toList() == a.map { it * 2 } },
)
}
@Test
@Disabled("TODO uses the native call jdk.internal.misc.Unsafe.getLong(java.lang.Object, long) in java.util.Arrays.equals(int[], int[])")
fun testArraysEqualsExample() {
withOptions(options.copy(coverageZone = CoverageZone.METHOD)) {
checkDiscoveredProperties(
IntArrayBasics::arrayEqualsExample,
eq(2),
{ _, a, r -> a.size == 3 && a contentEquals intArrayOf(1, 2, 3) && r == 1 },
{ _, a, r -> !(a contentEquals intArrayOf(1, 2, 3)) && r == 2 }
)
}
}
} |
/**
* @file llfloaterdaycycle.h
* @brief LLFloaterDayCycle class definition
*
* $LicenseInfo:firstyear=2007&license=viewergpl$
*
* Copyright (c) 2007-2010, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlife.com/developers/opensource/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlife.com/developers/opensource/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*
*/
#ifndef LL_LLFLOATERDAYCYCLE_H
#define LL_LLFLOATERDAYCYCLE_H
#include "llfloater.h"
#include <vector>
#include "llwlparamset.h"
#include "llwlanimator.h"
struct WLColorControl;
struct WLFloatControl;
/// convenience class for holding keys mapped to sliders
struct LLWLSkyKey
{
public:
std::string presetName;
F32 time;
};
/// Menu for all of windlight's functionality.
/// Menuing system for adjusting the atmospheric settings of the world.
class LLFloaterDayCycle : public LLFloater
{
public:
LLFloaterDayCycle(const LLSD& key);
virtual ~LLFloaterDayCycle();
/*virtual*/ BOOL postBuild();
/// initialize all
void initCallbacks(void);
/// on time slider moved
void onTimeSliderMoved(LLUICtrl* ctrl);
/// what happens when you move the key frame
void onKeyTimeMoved(LLUICtrl* ctrl);
/// what happens when you change the key frame's time
void onKeyTimeChanged(LLUICtrl* ctrl);
/// if you change the combo box, change the frame
void onKeyPresetChanged(LLUICtrl* ctrl);
/// run this when user says to run the sky animation
void onRunAnimSky(LLUICtrl* ctrl);
/// run this when user says to stop the sky animation
void onStopAnimSky(LLUICtrl* ctrl);
/// if you change the combo box, change the frame
void onTimeRateChanged(LLUICtrl* ctrl);
/// add a new key on slider
void onAddKey(LLUICtrl* ctrl);
/// delete any and all reference to a preset
void deletePreset(std::string& presetName);
/// delete a key frame
void onDeleteKey(LLUICtrl* ctrl);
/// button to load day
void onLoadDayCycle(LLUICtrl* ctrl);
/// button to save day
void onSaveDayCycle(LLUICtrl* ctrl);
/// toggle for Linden time
void onUseLindenTime(LLUICtrl* ctrl);
/// sync up sliders with day cycle structure
void syncMenu();
// makes sure key slider has what's in day cycle
void syncSliderTrack();
/// makes sure day cycle data structure has what's in menu
void syncTrack();
/// add a slider to the track
void addSliderKey(F32 time, const std::string& presetName);
private:
// map of sliders to parameters
static std::map<std::string, LLWLSkyKey> sSliderToKey;
static const F32 sHoursPerDay;
};
#endif |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Tasks', type: :request do
let!(:project) { create(:project) }
let!(:task) { create(:task, project_id: project.id) }
let!(:user) { create(:user) }
before do
allow_any_instance_of(TasksController).to receive(:current_user).and_return(user)
end
context 'when user is not authenticated' do
before do
allow_any_instance_of(TasksController).to receive(:current_user).and_return(nil)
end
it 'returns 401 status with message' do
get project_tasks_path(project_id: project.id), as: :json
expect(response).to have_http_status(401)
expect(response.body).to include(I18n.t('devise.failure.unauthenticated'))
end
end
describe 'GET /projects/:project_id/tasks' do
let!(:new_task) { create(:task, title: 'New task', project_id: project.id) }
let!(:in_progress_task) { create(:task, title: 'Task in progress', project_id: project.id, status: :in_progress) }
context 'without filter by status' do
it 'shows all tasks' do
get project_tasks_path(project_id: project.id), as: :json
expect(response).to have_http_status(200)
expect(response.body).to include(task.title)
expect(response.body).to include(new_task.title)
expect(response.body).to include(in_progress_task.title)
end
end
context 'with filter by status' do
it 'shows all tasks with specific status' do
get project_tasks_path(project_id: project.id, status: 'new'), as: :json
expect(response).to have_http_status(200)
expect(response.body).to include(task.title)
expect(response.body).to include(new_task.title)
expect(response.body).to_not include(in_progress_task.title)
end
end
context 'when project does not exist' do
it 'returns a 404 status code with an error message' do
get project_tasks_path(project_id: 'nonexistent_id'), as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.project_not_found'))
end
end
end
describe 'GET /projects/:project_id/tasks/:id' do
context 'when task and project exist' do
it 'shows task' do
get project_task_path(project_id: project.id, id: task.id), as: :json
expect(response).to have_http_status(200)
expect(response.body).to include(task.title)
end
end
context 'when project does not exist' do
it 'returns a 404 status code with an error message' do
get project_task_path(project_id: 'nonexistent_id', id: task.id), as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.project_not_found'))
end
end
context 'when task does not exist in the project' do
let!(:another_task) { create(:task, title: 'Another task title') }
it 'returns a 404 status code with an error message' do
get project_task_path(project_id: project.id, id: another_task.id), as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.task_not_found'))
end
end
context 'when task does not exist' do
it 'returns a 404 status code with an error message' do
get project_task_path(project_id: project.id, id: 'nonexistent_id'), as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.task_not_found'))
end
end
end
describe 'POST /projects/:project_id/tasks' do
context 'with valid params' do
let(:task_params) { { title: 'Task', description: 'The description of task.' } }
it 'creates task' do
expect do
post "/projects/#{project.id}/tasks", params: { task: task_params }, as: :json
end.to change(Task, :count).by(1)
end
it 'returns status code 201' do
post "/projects/#{project.id}/tasks", params: { task: task_params }, as: :json
expect(response).to have_http_status(201)
end
end
context 'with invalid params' do
let(:task_params) { { title: '', description: 'The description of task.' } }
it 'does not create task' do
expect do
post "/projects/#{project.id}/tasks", params: { task: task_params }, as: :json
end.to_not change(Task, :count)
end
it 'returns status code 422' do
post "/projects/#{project.id}/tasks", params: { task: task_params }, as: :json
expect(response).to have_http_status(422)
end
end
context 'when project does not exist' do
let(:task_params) { { title: 'Task', description: 'The description of task.' } }
it 'returns a 404 status code with an error message' do
post '/projects/nonexistent_id/tasks', params: { task: task_params }, as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.project_not_found'))
end
end
end
describe 'PUT /projects/:project_id/tasks/:id' do
context 'with valid params' do
let(:task_params) { { title: 'other task title' } }
it 'updates the task' do
put "/projects/#{project.id}/tasks/#{task.id}", params: { task: task_params }, as: :json
task.reload
expect(task.title).to eq(task_params[:title])
end
it 'returns status code 200' do
put "/projects/#{project.id}/tasks/#{task.id}", params: { task: task_params }, as: :json
expect(response).to have_http_status(200)
end
end
context 'with invalid params' do
let(:task_params) { { title: '' } }
it 'does not update the task' do
original_title = task.title
put "/projects/#{project.id}/tasks/#{task.id}", params: { task: task_params }, as: :json
task.reload
expect(task.title).to eq(original_title)
end
it 'returns status code 422' do
put "/projects/#{project.id}/tasks/#{task.id}", params: { task: task_params }, as: :json
expect(response).to have_http_status(422)
end
end
context 'when project does not exist' do
let(:task_params) { { title: 'other task title' } }
it 'returns a 404 status code with an error message' do
put "/projects/nonexistent_id/tasks/#{task.id}", params: { task: task_params }, as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.project_not_found'))
end
end
context 'when task does not exist in the project' do
let(:task_params) { { title: 'other task title' } }
let!(:another_task) { create(:task, title: 'Another task title') }
it 'returns a 404 status code with an error message' do
put "/projects/#{project.id}/tasks/#{another_task.id}", params: { task: task_params }, as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.task_not_found'))
end
end
context 'when task does not exist' do
let(:task_params) { { title: 'other task title' } }
it 'returns a 404 status code with an error message' do
put "/projects/#{project.id}/tasks/nonexistent_id", params: { task: task_params }, as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.task_not_found'))
end
end
end
describe 'DELETE /projects/:project_id/tasks/:id' do
context 'when task exists' do
it 'deletes the task' do
expect { delete "/projects/#{project.id}/tasks/#{task.id}", as: :json }.to change(Task, :count).by(-1)
end
end
context 'when project does not exist' do
it 'returns a 404 status code with an error message' do
delete "/projects/nonexistent_id/tasks/#{task.id}", as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.project_not_found'))
end
end
context 'when task does not exist in the project' do
let!(:another_task) { create(:task, title: 'Another task title') }
it 'returns a 404 status code with an error message' do
delete "/projects/#{project.id}/tasks/#{another_task.id}", as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.task_not_found'))
end
end
context 'when task does not exist' do
it 'returns a 404 status code with an error message' do
delete "/projects/#{project.id}/tasks/nonexistent_id", as: :json
expect(response).to have_http_status(404)
expect(response.body).to include(I18n.t('errors.task_not_found'))
end
end
end
end |
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_web_ptb/constants/dimens.dart';
import 'package:flutter_web_ptb/master_layout_config.dart';
import 'package:flutter_web_ptb/providers/userdata.provider.dart';
import 'package:flutter_web_ptb/theme/theme_extensions/app_sidebar_theme.dart';
import 'package:go_router/go_router.dart';
class SidebarMenuConfig {
final String uri;
final IconData icon;
final String Function(BuildContext context) title;
final List<SidebarChildMenuConfig> children;
const SidebarMenuConfig({
required this.uri,
required this.icon,
required this.title,
List<SidebarChildMenuConfig>? children,
}) : children = children ?? const [];
}
class SidebarChildMenuConfig {
final String uri;
final IconData icon;
final String Function(BuildContext context) title;
const SidebarChildMenuConfig({
required this.uri,
required this.icon,
required this.title,
});
}
class Sidebar extends ConsumerStatefulWidget {
final bool autoSelectMenu;
final String? selectedMenuUri;
final void Function() onAccountButtonPressed;
final void Function() onLogoutButtonPressed;
final List<SidebarMenuConfig> sidebarConfigs;
final String? role;
const Sidebar({
Key? key,
this.autoSelectMenu = true,
this.selectedMenuUri,
required this.onAccountButtonPressed,
required this.onLogoutButtonPressed,
required this.sidebarConfigs,
required this.role,
}) : super(key: key);
@override
ConsumerState<Sidebar> createState() => _SidebarState();
}
class _SidebarState extends ConsumerState<Sidebar> {
final _scrollController = ScrollController();
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// final lang = Lang.of(context);
final mediaQueryData = MediaQuery.of(context);
final themeData = Theme.of(context);
final sidebarTheme = themeData.extension<AppSidebarTheme>()!;
return Drawer(
child: Column(
children: [
Visibility(
visible: (mediaQueryData.size.width <= kScreenWidthLg),
child: Container(
alignment: Alignment.centerLeft,
height: kToolbarHeight,
padding: const EdgeInsets.only(left: 8.0),
child: IconButton(
onPressed: () {
if (Scaffold.of(context).isDrawerOpen) {
Scaffold.of(context).closeDrawer();
}
},
icon: const Icon(Icons.close_rounded),
color: sidebarTheme.foregroundColor,
tooltip: 'Close Navigation Menu',
),
),
),
Expanded(
child: Theme(
data: themeData.copyWith(
scrollbarTheme: themeData.scrollbarTheme.copyWith(
thumbColor: MaterialStateProperty.all(
sidebarTheme.foregroundColor.withOpacity(0.2)),
),
),
child: Scrollbar(
controller: _scrollController,
child: ListView(
controller: _scrollController,
padding: EdgeInsets.fromLTRB(
sidebarTheme.sidebarLeftPadding,
sidebarTheme.sidebarTopPadding,
sidebarTheme.sidebarRightPadding,
sidebarTheme.sidebarBottomPadding,
),
children: [
SidebarHeader(
onAccountButtonPressed: widget.onAccountButtonPressed,
onLogoutButtonPressed: widget.onLogoutButtonPressed,
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Divider(
height: 2.0,
thickness: 1.0,
color: sidebarTheme.foregroundColor.withOpacity(0.5),
),
),
_sidebarMenuList(context),
],
),
),
),
),
],
),
);
}
Widget _sidebarMenuList(BuildContext context) {
final sidebarTheme = Theme.of(context).extension<AppSidebarTheme>()!;
var currentLocation = widget.selectedMenuUri ?? '';
if (currentLocation.isEmpty && widget.autoSelectMenu) {
currentLocation = GoRouter.of(context).location;
}
var sideBar = [];
if (widget.role == "SuperAdmin") {
sideBar = sidebarMenuConfigs;
} else if (widget.role == "Admin") {
sideBar = sideBarMenuConfigs_Admin;
} else if (widget.role == "Verify") {
sideBar = sideBarMenuConfigs_Verifikator;
}
return Column(
children: sideBar.map<Widget>((menu) {
if (menu.children.isEmpty) {
return _sidebarMenu(
context,
EdgeInsets.fromLTRB(
sidebarTheme.menuLeftPadding,
sidebarTheme.menuTopPadding,
sidebarTheme.menuRightPadding,
sidebarTheme.menuBottomPadding,
),
menu.uri,
menu.icon,
menu.title(context),
(currentLocation.startsWith(menu.uri)),
);
} else {
return _expandableSidebarMenu(
context,
EdgeInsets.fromLTRB(
sidebarTheme.menuLeftPadding,
sidebarTheme.menuTopPadding,
sidebarTheme.menuRightPadding,
sidebarTheme.menuBottomPadding,
),
menu.uri,
menu.icon,
menu.title(context),
menu.children,
currentLocation,
);
}
}).toList(growable: false),
);
}
Widget _sidebarMenu(
BuildContext context,
EdgeInsets padding,
String uri,
IconData icon,
String title,
bool isSelected,
) {
final sidebarTheme = Theme.of(context).extension<AppSidebarTheme>()!;
final textColor = (isSelected
? sidebarTheme.menuSelectedFontColor
: sidebarTheme.foregroundColor);
return Padding(
padding: padding,
child: Card(
color: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(sidebarTheme.menuBorderRadius)),
elevation: 0.0,
margin: EdgeInsets.zero,
clipBehavior: Clip.antiAlias,
child: ListTile(
title: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: (sidebarTheme.menuFontSize + 4.0),
color: textColor,
),
const SizedBox(width: kDefaultPadding * 0.5),
Text(
title,
style: TextStyle(
fontSize: sidebarTheme.menuFontSize,
color: textColor,
),
),
],
),
onTap: () {
GoRouter.of(context).go(uri);
},
selected: isSelected,
selectedTileColor: sidebarTheme.menuSelectedBackgroundColor,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(sidebarTheme.menuBorderRadius)),
textColor: textColor,
hoverColor: sidebarTheme.menuHoverColor,
),
),
);
}
Widget _expandableSidebarMenu(
BuildContext context,
EdgeInsets padding,
String uri,
IconData icon,
String title,
List<SidebarChildMenuConfig> children,
String currentLocation,
) {
final themeData = Theme.of(context);
final sidebarTheme = Theme.of(context).extension<AppSidebarTheme>()!;
final hasSelectedChild =
children.any((e) => currentLocation.startsWith(e.uri));
final parentTextColor = (hasSelectedChild
? sidebarTheme.menuSelectedFontColor
: sidebarTheme.foregroundColor);
return Padding(
padding: padding,
child: Card(
color: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(sidebarTheme.menuBorderRadius)),
elevation: 0.0,
margin: EdgeInsets.zero,
clipBehavior: Clip.antiAlias,
child: Theme(
data: themeData.copyWith(
hoverColor: sidebarTheme.menuExpandedHoverColor,
),
child: ExpansionTile(
key: UniqueKey(),
textColor: parentTextColor,
collapsedTextColor: parentTextColor,
iconColor: parentTextColor,
collapsedIconColor: parentTextColor,
backgroundColor: sidebarTheme.menuExpandedBackgroundColor,
collapsedBackgroundColor: (hasSelectedChild
? sidebarTheme.menuExpandedBackgroundColor
: Colors.transparent),
initiallyExpanded: hasSelectedChild,
childrenPadding: EdgeInsets.only(
top: sidebarTheme.menuExpandedChildTopPadding,
bottom: sidebarTheme.menuExpandedChildBottomPadding,
),
title: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: (sidebarTheme.menuFontSize + 4.0),
),
const SizedBox(width: kDefaultPadding * 0.5),
Text(
title,
style: TextStyle(
fontSize: sidebarTheme.menuFontSize,
),
),
],
),
children: children.map<Widget>((childMenu) {
return _sidebarMenu(
context,
EdgeInsets.fromLTRB(
sidebarTheme.menuExpandedChildLeftPadding,
sidebarTheme.menuExpandedChildTopPadding,
sidebarTheme.menuExpandedChildRightPadding,
sidebarTheme.menuExpandedChildBottomPadding,
),
childMenu.uri,
childMenu.icon,
childMenu.title(context),
(currentLocation.startsWith(childMenu.uri)),
);
}).toList(growable: false),
),
),
),
);
}
}
class SidebarHeader extends ConsumerWidget {
final void Function() onAccountButtonPressed;
final void Function() onLogoutButtonPressed;
const SidebarHeader({
Key? key,
required this.onAccountButtonPressed,
required this.onLogoutButtonPressed,
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
// final lang = Lang.of(context);
final themeData = Theme.of(context);
final sidebarTheme = themeData.extension<AppSidebarTheme>()!;
var value = ref.watch(userDataProvider.select((value) => value.username));
return Column(
children: [
Row(
children: [
CircleAvatar(
backgroundColor: Colors.white,
radius: 20.0,
child: ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.asset("assets/hospital_ic.png"),
),
),
const SizedBox(width: kDefaultPadding * 0.5),
Text(
'Hi, $value',
style: TextStyle(
fontSize: sidebarTheme.headerUsernameFontSize,
color: sidebarTheme.foregroundColor,
),
),
],
),
const SizedBox(height: kDefaultPadding * 0.5),
Align(
alignment: Alignment.centerRight,
child: IntrinsicHeight(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_textButton(themeData, sidebarTheme, Icons.login_rounded,
'Logout', onLogoutButtonPressed),
],
),
),
),
],
);
}
Widget _textButton(ThemeData themeData, AppSidebarTheme sidebarTheme,
IconData icon, String text, void Function() onPressed) {
return TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
foregroundColor: sidebarTheme.foregroundColor,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: (sidebarTheme.headerUsernameFontSize + 4.0),
),
const SizedBox(width: kDefaultPadding * 0.5),
Text(
text,
style: TextStyle(
fontSize: sidebarTheme.headerUsernameFontSize,
),
),
],
),
);
}
} |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Adventure implements Commodity {
private final int id;
private final String name;
private int level = 1;
private int hp = 500;
private int maxBots = 1;
private long price;
private HashMap<Integer, Bottle> bottles = new HashMap<>();
private HashMap<String, TreeMap<Integer, Bottle>> takenBottles = new HashMap<>();
private HashMap<Integer, Equipment> equipments = new HashMap<>();
private HashMap<String, Equipment> takenEquipments = new HashMap<>();
private HashMap<Integer, Food> foods = new HashMap<>();
private HashMap<String, TreeMap<Integer, Food>> takenFoods = new HashMap<>();
private HashMap<Integer, Commodity> commodities = new HashMap<>();
public Adventure(int id, String name) {
this.id = id;
this.name = name;
}
public void addBottle(Bottle bottle) {
bottles.put(bottle.getId(), bottle);
commodities.put(bottle.getId(), bottle);
this.price += bottle.getPrice();
}
public void addEquipment(Equipment equipment) {
equipments.put(equipment.getId(), equipment);
commodities.put(equipment.getId(), equipment);
this.price += equipment.getPrice();
}
public void addFood(Food food) {
foods.put(food.getId(), food);
commodities.put(food.getId(), food);
this.price += food.getPrice();
}
public void takeBottle(int bottleId) {
Bottle bottle = bottles.get(bottleId);
if (takenBottles.containsKey(bottle.getName())) {
if (takenBottles.get(bottle.getName()).size() < maxBots) {
takenBottles.get(bottle.getName()).put(bottleId, bottle);
}
} else {
TreeMap<Integer, Bottle> treeMap = new TreeMap<>();
treeMap.put(bottleId, bottle);
takenBottles.put(bottle.getName(), treeMap);
}
}
public void takeEquipment(int equipmentId) {
Equipment equipment = equipments.get(equipmentId);
takenEquipments.put(equipment.getName(), equipment);
}
public void takeFood(int foodId) {
Food food = foods.get(foodId);
if (takenFoods.containsKey(food.getName())) {
takenFoods.get(food.getName()).put(foodId, food);
} else {
TreeMap<Integer, Food> treeMap = new TreeMap<>();
treeMap.put(foodId, food);
takenFoods.put(food.getName(), treeMap);
}
}
public boolean useBottle(boolean isFight, String bottleName) {
if (takenBottles.containsKey(bottleName) && !takenBottles.get(bottleName).isEmpty()) {
Map.Entry<Integer, Bottle> entry = takenBottles.get(bottleName).firstEntry();
int bottleId = entry.getKey();
Bottle bottle = entry.getValue();
if (bottle.getCapacity() > 0) {
int increasedHp = bottle.getIncreasedHp(this.hp);
this.hp += increasedHp;
bottle.setCapacity(0);
} else {
takenBottles.get(bottleName).pollFirstEntry();
this.price -= bottle.getPrice();
bottles.remove(bottleId);
commodities.remove(bottleId);
}
System.out.println(bottleId + " " + this.hp);
if (takenBottles.get(bottleName).isEmpty()) {
takenBottles.remove(bottleName);
}
return true;
} else {
if (isFight) {
System.out.println("Fight log error");
} else {
System.out.println("fail to use " + bottleName);
}
return false;
}
}
public void eatFood(String foodName) {
if (takenFoods.containsKey(foodName) && !takenFoods.get(foodName).isEmpty()) {
Map.Entry<Integer, Food> entry = takenFoods.get(foodName).pollFirstEntry();
int foodId = entry.getKey();
Food food = entry.getValue();
this.level += food.getEnergy();
this.maxBots = this.level / 5 + 1;
foods.remove(foodId);
this.price -= food.getPrice();
commodities.remove(foodId);
System.out.println(foodId + " " + this.level);
if (takenFoods.get(foodName).isEmpty()) {
takenFoods.remove(foodName);
}
} else {
System.out.println("fail to eat " + foodName);
}
}
public PrintInfo removeBottle(int bottleId) {
String name = bottles.get(bottleId).getName();
this.price -= bottles.get(bottleId).getPrice();
bottles.remove(bottleId); // 根据key删除元素
if (takenBottles.containsKey(name)) {
takenBottles.get(name).remove(bottleId);
}
commodities.remove(bottleId);
return new PrintInfo(bottles.size(), name);
}
public PrintInfo removeEquipment(int equipmentId) {
this.price -= equipments.get(equipmentId).getPrice();
String name = equipments.get(equipmentId).getName();
equipments.remove(equipmentId);
commodities.remove(equipmentId);
if (takenEquipments.containsKey(name)) {
int id = takenEquipments.get(name).getId();
if (id == equipmentId) {
takenEquipments.remove(name);
}
}
return new PrintInfo(equipments.size(), name);
}
public PrintInfo removeFood(int foodId) {
this.price -= foods.get(foodId).getPrice();
String name = foods.get(foodId).getName();
commodities.remove(foodId);
foods.remove(foodId);
if (takenFoods.containsKey(name)) {
takenFoods.get(name).remove(foodId);
}
return new PrintInfo(foods.size(), name);
}
public PrintInfo increaseStar(int equipmentId) {
Equipment equipment = equipments.get(equipmentId);
equipment.increaseStar();
return new PrintInfo(equipment.getStar(), equipment.getName());
}
public boolean attackAoe(ArrayList<String> fight,
HashMap<Integer, Adventure> advs,
HashMap<String, Integer> advNameToId,
String equName) {
if (fight.contains(name) && takenEquipments.containsKey(equName)) {
Equipment equipment = takenEquipments.get(equName);
for (String name : fight) {
if (!name.equals(this.name)) {
int attackedId = advNameToId.get(name);
Adventure attacked = advs.get(attackedId);
int loseHp = equipment.getLoseHp(level, attacked.getHp());
attacked.setHp(attacked.getHp() - loseHp);
System.out.print(attacked.getHp() + " ");
}
}
System.out.println();
return true;
} else {
System.out.println("Fight log error");
return false;
}
}
public boolean attack(ArrayList<String> fight,
HashMap<Integer, Adventure> advs,
HashMap<String, Integer> advNameToId,
String attackedName,
String equName) {
if (fight.contains(name) && fight.contains(attackedName) &&
takenEquipments.containsKey(equName)) {
Equipment equipment = takenEquipments.get(equName);
int attackedId = advNameToId.get(attackedName);
Adventure attacked = advs.get(attackedId);
int loseHp = equipment.getLoseHp(level, attacked.getHp());
attacked.setHp(attacked.getHp() - loseHp);
System.out.println(attacked.getId() + " " + attacked.getHp());
return true;
} else {
System.out.println("Fight log error");
return false;
}
}
public void hireAdventure(int adventureId, Adventure adventure) {
commodities.put(adventureId, adventure);
this.price += adventure.getPrice();
}
public void searchAllCommodities() {
int totalNum = commodities.size();
long totalPrice = 0;
for (Commodity commodity : commodities.values()) {
totalPrice += commodity.getPrice();
}
System.out.println(totalNum + " " + totalPrice);
}
public void searchMaxPrice() {
if (commodities.isEmpty()) {
System.out.println("0");
} else {
long maxPrice = 0;
for (Commodity commodity : commodities.values()) {
if (commodity.getPrice() > maxPrice) {
maxPrice = commodity.getPrice();
}
}
System.out.println(maxPrice);
}
}
public void searchCommodityClass(int commodityId) {
String name = commodities.get(commodityId).getClassName();
System.out.println("Commodity whose id is " +
commodityId + " belongs to " + name);
}
@Override
public long getPrice() {
long totalPrice = 0;
for (Commodity commodity : commodities.values()) {
totalPrice += commodity.getPrice();
}
this.price = totalPrice;
return this.price;
}
@Override
public String getClassName() {
return "Adventurer";
}
public HashMap<Integer, Bottle> getBottles() {
return bottles;
}
public HashMap<Integer, Equipment> getEquipments() {
return equipments;
}
public HashMap<String, TreeMap<Integer, Bottle>> getTakenBottles() {
return takenBottles;
}
public HashMap<String, Equipment> getTakenEquipments() {
return takenEquipments;
}
public HashMap<Integer, Food> getFoods() {
return foods;
}
public HashMap<String, TreeMap<Integer, Food>> getTakenFoods() {
return takenFoods;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getLevel() {
return level;
}
public int getMaxBots() {
return maxBots;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
} |
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!--project fonts-->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap"
rel="stylesheet"
/>
<!--normalize-->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css"
integrity="sha512-wpPYUAdjBVSE4KJnH1VR1HeZfpl1ub8YT/NKx4PuQ5NmX2tKuGu6U/JRp5y+Y8XG2tV+wKQpNHVUX03MfMFn9Q=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<!--Шапка-->
<header class="header">
<div class="container heder-container">
<a class="link logo-header" href="./index.html" lang="en"
>Web<span class="logo-black">Studio</span></a
>
<nav class="navigation">
<ul class="header-list">
<li class="header-navigation">
<a class="link header-link current" href="./index.html">Студия</a>
</li>
<li class="header-navigation">
<a class="link header-link" href="./portfolio.html"
>Портфолио</a
>
</li>
<li class="header-navigation">
<a class="link header-link" href="#">Контакты</a>
</li>
</ul>
</nav>
<ul class="header-contacts">
<li>
<a class="link header-mail" href="mailto:info@devstudio.com"
>info@devstudio.com</a
>
</li>
<li>
<a class="link header-phone" href="tel:+380961111111"
>+38 096 111 11 11</a
>
</li>
</ul>
</div>
</header>
<main class="main">
<!--Герой-->
<section class="hero">
<div class="container">
<h1 class="hero-title">
Эффективное решение<br />
для вашего бизнеса
</h1>
<button class="hero-btn" type="button">Заказать услугу</button>
</div>
</section>
<!--Особенности-->
<section class="section">
<div class="container features-container">
<h2 class="visually-hidden">Наши преимущества</h2>
<ul class="features-section">
<li class="features-item">
<h3 class="features-title">Внимание к деталям</h3>
<p class="features-text">
Идейные соображения, а также начало повседневной работы по
формированию позиции.
</p>
</li>
<li class="features-item">
<h3 class="features-title">Пунктуальность</h3>
<p class="features-text">
Задача организации, в особенности же рамки и место обучения
кадров влечет за собой.
</p>
</li>
<li class="features-item">
<h3 class="features-title">Планирование</h3>
<p class="features-text">
Равным образом консультация с широким активом в значительной
степени обуславливает.
</p>
</li>
<li class="features-item">
<h3 class="features-title">Современные технологии</h3>
<p class="features-text">
Значимость этих проблем настолько очевидна, что реализация
плановых заданий.
</p>
</li>
</ul>
</div>
</section>
<!--Чем мы занимаемся-->
<section class="section our-work-section">
<div class="container">
<h2 class="section-title our-work-title">Чем мы занимаемся</h2>
<ul class="our-work">
<li class="our-work-list">
<img
src="./images/about/box1.jpg"
alt="печатает на клавиатуре"
width="370"
/>
</li>
<li class="our-work-list">
<img
src="./images/about/box2.jpg"
alt="работает со смартфоном"
width="370"
/>
</li>
<li class="our-work-list">
<img
src="./images/about/box3.jpg"
alt="рисует абстракцию"
width="370"
/>
</li>
</ul>
</div>
</section>
<!--Наша команда-->
<section class="teem section">
<div class="container">
<h2 class="section-title teem-title">Наша команда</h2>
<ul class="teem-card">
<li class="teem-list">
<img
class="teem-photo"
src="./images/teem/photo1.jpg"
alt="Игорь Демьяненко"
width="270"
/>
<div class="teem-name"><h3 class="name">Игорь Демьяненко</h3>
<p class="speciality" lang="en">Product Designer</p></div>
</li>
<li class="teem-list">
<img
class="teem-photo"
src="./images/teem/photo2.jpg"
alt="Ольга Репина"
width="270"
/>
<div class="teem-name"><h3 class="name">Ольга Репина</h3>
<p class="speciality" lang="en">Frontend Developer</p></div>
</li>
<li class="teem-list">
<img
class="teem-photo"
src="./images/teem/photo3.jpg"
alt="Николай Тарасов"
width="270"
/>
<div class="teem-name"><h3 class="name">Николай Тарасов</h3>
<p class="speciality" lang="en">Marketing</p></div>
</li>
<li class="teem-list">
<img
class="teem-photo"
src="./images/teem/photo4.jpg"
alt="Михаил Ермаков"
width="270"
/>
<div class="teem-name"><h3 class="name">Михаил Ермаков</h3>
<p class="speciality" lang="en">UI Designer</p></div>
</li>
</ul>
</div>
</section>
</main>
<!--Подвал-->
<footer class="footer">
<div class="container">
<a class="link logo-footer" href="./index.html" lang="en"
>Web<span class="logo-white">Studio</span></a
>
<address>
<ul>
<li class="address-list">
<a
class="link address"
href="https://goo.gl/maps/5uR2JUp8dFeEwz9S6"
>г. Киев, пр-т Леси Украинки, 26</a
>
</li>
<li class="address-list">
<a class="link footer-contacts" href="mailto:info@example.com"
>info@example.com</a
>
</li>
<li class="address-list">
<a class="link footer-contacts" href="tel:+380991111111"
>+38 099 111 11 11</a
>
</li>
</ul>
</address>
</div>
</footer>
</body>
</html> |
import {
BadRequestException,
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
Request,
UnauthorizedException,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { promisify } from 'util';
import { UserDto } from 'src/chatdb/dto/user';
import { Public } from './roles.decorator';
import * as bcrypt from 'bcrypt';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Public()
@HttpCode(HttpStatus.OK)
@Get('pre-login')
async preLogin() {
const init = await this.authService.hasInitialized();
return { init };
}
@Public()
@HttpCode(HttpStatus.OK)
@Post('setup')
async setup(
@Body()
body: {
password: string;
openai: { token: string; baseUrl: string };
padLocal: {
token: string;
puppetType: string;
};
},
) {
const hasInitialized = await this.authService.hasInitialized();
if (hasInitialized) {
throw new BadRequestException('Already initialized');
}
const adminUser = await this.authService.setup(
body.password,
body.openai.baseUrl,
body.openai.token,
body.padLocal.token,
body.padLocal.puppetType,
);
return {
user: new UserDto(adminUser),
};
}
@Public()
@HttpCode(HttpStatus.OK)
@Post('login')
async login(
@Body() body: { username: string; password: string },
@Request() req: Express.Request,
) {
const { password, username } = body;
const user = await this.authService.validateUser(username, password);
if (user) {
await promisify(req.logIn.bind(req))(user);
return { user: new UserDto(user) };
}
throw new UnauthorizedException('Invalid username or password');
}
@Public()
@HttpCode(HttpStatus.OK)
@Post('register')
async register(@Body() body: { username: string; password: string }) {
const { password, username } = body;
const user = await this.authService.register(username, password);
if (user) return { user };
}
@HttpCode(HttpStatus.OK)
@Post('logout')
async logout(@Request() req: Express.Request) {
await promisify(req.logout.bind(req))(); // Passport method to log out
await promisify(req.session.destroy.bind(req.session))(); // Destroy the session
return { message: 'Logged out successfully' };
}
} |
/*
* "Commons Clause" License Condition v1.0
*
* The Software is provided to you by the Licensor under the
* License, as defined below, subject to the following condition.
*
* Without limiting other conditions in the License, the grant
* of rights under the License will not include, and the
* License does not grant to you, the right to Sell the Software.
*
* For purposes of the foregoing, "Sell" means practicing any
* or all of the rights granted to you under the License to
* provide to third parties, for a fee or other consideration
* (including without limitation fees for hosting or
* consulting/ support services related to the Software), a
* product or service whose value derives, entirely or substantially,
* from the functionality of the Software. Any
* license notice or attribution required by the License must
* also include this Commons Clause License Condition notice.
*
* License: LGPL 2.1 or later
* Licensor: metaphacts GmbH
*
* Copyright (C) 2015-2021, metaphacts GmbH
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, you can receive a copy
* of the GNU Lesser General Public License from http://www.gnu.org/
*/
import { find } from 'lodash';
import { createElement } from 'react';
import * as D from 'react-dom-factories';
import * as DateTimePicker from 'react-datetime';
import * as moment from 'moment';
import Moment = moment.Moment;
import { Rdf, vocabularies, XsdDataTypeValidation } from 'platform/api/rdf';
import { FieldDefinition, getPreferredLabel } from '../FieldDefinition';
import { FieldValue, AtomicValue, EmptyValue } from '../FieldValues';
import {
SingleValueInput, SingleValueInputConfig, AtomicValueInput, AtomicValueInputProps,
} from './SingleValueInput';
import { ValidationMessages } from './Decorations';
import './datetime.scss';
// input format patterns include timezone offset to be compatible with XSD specification
export const INPUT_XSD_DATE_FORMAT = 'YYYY-MM-DDZZ';
export const INPUT_XSD_TIME_FORMAT = 'HH:mm:ssZZ';
// output format patterns for UTC moments (without timezone offset), compatible with ISO and XSD
export const OUTPUT_UTC_DATE_FORMAT = 'YYYY-MM-DD';
export const OUTPUT_UTC_TIME_FORMAT = 'HH:mm:ss';
interface SemanticFormDatePickerInputConfig extends SingleValueInputConfig {
mode?: DatePickerMode;
placeholder?: string;
}
export type DatePickerMode = 'date' | 'time' | 'dateTime';
export interface DatePickerInputProps
extends SemanticFormDatePickerInputConfig, AtomicValueInputProps {}
export class DatePickerInput extends AtomicValueInput<DatePickerInputProps, {}> {
private get datatype() {
return this.props.definition.xsdDatatype || vocabularies.xsd.dateTime;
}
render() {
const rdfNode = FieldValue.asRdfNode(this.props.value);
const dateLiteral = dateLiteralFromRdfNode(rdfNode);
const utcMoment = utcMomentFromRdfLiteral(dateLiteral);
const mode = this.props.mode || getModeFromDatatype(this.datatype);
const displayedDate = (
utcMoment ? utcMoment :
dateLiteral ? dateLiteral.value :
(rdfNode && Rdf.isLiteral(rdfNode)) ? rdfNode.value :
undefined
);
const placeholder = typeof this.props.placeholder === 'undefined'
? defaultPlaceholder(this.props.definition, mode) : this.props.placeholder;
return D.div(
{className: 'date-picker-field'},
createElement(DateTimePicker, {
className: 'date-picker-field__date-picker',
onChange: this.onDateSelected, // for keyboard changes
closeOnSelect: true,
value: displayedDate as any, // TODO: fix typings (value could be Moment)
viewMode: mode === 'time' ? 'time' : 'days',
dateFormat: (mode === 'date' || mode === 'dateTime') ? OUTPUT_UTC_DATE_FORMAT : null,
timeFormat: (mode === 'time' || mode === 'dateTime') ? OUTPUT_UTC_TIME_FORMAT : null,
inputProps: {placeholder},
}),
createElement(ValidationMessages, {errors: FieldValue.getErrors(this.props.value)})
);
}
private onDateSelected = (value: string | Moment) => {
let parsed;
if (typeof value === 'string') {
// if user enter a string without using the date picker
// we pass direclty to validation
parsed = this.parse(value);
} else {
// otherwise we format to UTC
const mode = getModeFromDatatype(this.datatype);
const formattedDate = (
mode === 'date' ? value.format(OUTPUT_UTC_DATE_FORMAT) :
mode === 'time' ? value.format(OUTPUT_UTC_TIME_FORMAT) :
value.format()
);
parsed = this.parse(formattedDate);
}
this.setAndValidate(parsed);
}
private parse(isoDate: string): AtomicValue | EmptyValue {
if (isoDate.length === 0) { return FieldValue.empty; }
return AtomicValue.set(this.props.value, {
value: Rdf.literal(isoDate, this.datatype),
});
}
static makeHandler = AtomicValueInput.makeAtomicHandler;
}
export function getModeFromDatatype(datatype: Rdf.Iri): DatePickerMode {
const parsed = XsdDataTypeValidation.parseXsdDatatype(datatype);
if (parsed && parsed.prefix === 'xsd') {
switch (parsed.localName) {
case 'date': return 'date';
case 'time': return 'time';
}
}
return 'dateTime';
}
function dateLiteralFromRdfNode(node: Rdf.Node | undefined): Rdf.Literal | undefined {
if (!node || !Rdf.isLiteral(node)) { return undefined; }
const dateString = node.value;
const types = [vocabularies.xsd.date, vocabularies.xsd.time, vocabularies.xsd.dateTime];
return find(
types.map(type => Rdf.literal(dateString, type)),
literal => XsdDataTypeValidation.validate(literal).success);
}
export function utcMomentFromRdfLiteral(literal: Rdf.Literal | undefined): Moment | undefined {
if (!literal) { return undefined; }
const mode = getModeFromDatatype(literal.datatype);
const parsedMoment = (
mode === 'date' ? moment.utc(literal.value, INPUT_XSD_DATE_FORMAT) :
mode === 'time' ? moment.utc(literal.value, INPUT_XSD_TIME_FORMAT) :
moment.utc(literal.value)
);
return parsedMoment.isValid() ? parsedMoment : undefined;
}
function defaultPlaceholder(definition: FieldDefinition, mode: DatePickerMode) {
const valueType = mode === 'time' ? 'time' : 'date';
const fieldName = (getPreferredLabel(definition.label) || valueType).toLocaleLowerCase();
return `Select or enter ${fieldName} here...`;
}
SingleValueInput.assertStatic(DatePickerInput);
export default DatePickerInput; |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import '../styles/ProductCard.css';
export default class ProductCard extends Component {
render() {
const { searchData, addToCart } = this.props;
const { title,
price,
thumbnail,
id, available_quantity: availableQuantity,
shipping: { free_shipping: freeShiping } } = searchData;
return (
<section
data-testid="product"
className="product-card"
>
<Link
to={ { pathname: `/item/${id}`, data: { searchData } } }
data-testid="product-detail-link"
className="product-title"
>
<h1>{title}</h1>
</Link>
{freeShiping ? <p data-testid="free-shipping">Frete Gratis</p> : ''}
<img
src={ thumbnail }
alt={ `img from ${title}` }
className="product-img"
/>
<p className="product-price">{`R$ ${price}`}</p>
<button
data-testid="product-add-to-cart"
type="button"
className="product-btn"
onClick={ () => addToCart({
name: title,
price,
quantity: 1,
availableQuantity,
}) }
>
Adicionar ao carrinho
</button>
</section>
);
}
}
ProductCard.propTypes = {
searchData: PropTypes.objectOf(PropTypes.any).isRequired,
addToCart: PropTypes.func.isRequired,
}; |
let score = JSON.parse(localStorage.getItem('score')) || {
Wins: 0,
Losses: 0,
Ties: 0
}
updateScoreElement();
// if (!score){
// score = {
// Win: 0,
// Losses: 0,
// Tie : 0
// }
// }
//using regular function
// let isautoPlaying = false;
// let intervalId;
// function autoPlay(){
// if(!isautoPlaying){
// intervalId = setInterval(function(){
// const playerMove = pickComputerMove();
// playGame(playerMove);
// }, 2000);
// isautoPlaying = true;
// } else {
// clearInterval(intervalId);
// isautoPlaying = false;
// }
//using addEventListner
document.querySelector('.js-rock-button')
.addEventListener('click', ()=> {
playGame('rock');
})
//using arrow function
const autoPlay = () => {
if(!isautoPlaying){
intervalId = setInterval(()=>{
const playerMove = pickComputerMove();
playGame(playerMove);
}, 1000);
isautoPlaying = true;
} else {
clearInterval(intervalId);
isautoPlaying = false;
}
const buttonElement = document.querySelector('.js-autoPlay-button');
if (buttonElement.innerHTML === 'Auto Play'){
buttonElement.innerHTML = 'Stop';
buttonElement.classList.add('is-Stop')
} else {
buttonElement.innerHTML = 'Auto Play';
buttonElement.classList.remove('is-Stop')
}
}
function playGame(playerMove){
const computerMove = pickComputerMove();
let result = '';
if (playerMove === 'scissors'){
if (computerMove==='rock'){
result = 'You lose.';
} else if (computerMove === 'paper'){
result = 'You win.';
} else if (computerMove === 'scissors'){
result = 'Tie.'
}
}
else if (playerMove === 'paper'){
if (computerMove==='rock'){
result = 'You win.';
} else if (computerMove === 'paper'){
result = 'Tie.';
} else if (computerMove === 'scissors'){
result = 'You lose.'
}
}
if (playerMove === 'rock'){
if (computerMove==='rock'){
result = 'Tie.';
} else if (computerMove === 'paper'){
result = 'You lose.';
} else if (computerMove === 'scissors'){
result = 'You Win.'
}
}
if (result === 'You win.'){
score.Wins+=1;
} else if (result === 'You lose.'){
score.Losses+=1;
} else if (result === 'Tie.'){
score.Ties+=1;
}
localStorage.setItem('score', JSON.stringify(score));
updateScoreElement();
document.querySelector('.js-result').innerHTML = result;
document.querySelector('.js-moves').innerHTML =
`You<img src="${playerMove}-emoji.png" class="result-emoji">
<img src="${computerMove}-emoji.png" class="result-emoji">Computer`;
}
function updateScoreElement(){
document.querySelector('.js-score').innerHTML =
`Wins: ${score.Wins}, Losses: ${score.Losses}, Ties: ${score.Ties}`;
}
function pickComputerMove(){
const randomNumber = Math.random();
let computerMove = '';
if (randomNumber >=0 && randomNumber < 1/3 ){
computerMove = 'rock';
} else if (randomNumber >=1/3 && randomNumber < 2/3){
computerMove = 'paper';
} else if (randomNumber >=2/3 && randomNumber < 1){
computerMove = 'scissors';
}
return computerMove;
}; |
/*
* Copyright (C) 2008 Kristian Høgsberg <krh@redhat.com>
* Copyright (C) 2008 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <limits.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include "razor-internal.h"
int
razor_create_dir(const char *root, const char *path)
{
char buffer[PATH_MAX], *p;
const char *slash, *next;
struct stat buf;
/* Create all sub-directories in dir. We know root exists and
* is a dir, root does not end in a '/', and path has a
* leading '/'. */
strcpy(buffer, root);
p = buffer + strlen(buffer);
slash = path;
for (slash = path; *slash != '\0'; slash = next) {
next = strchr(slash + 1, '/');
if (next == NULL)
break;
memcpy(p, slash, next - slash);
p += next - slash;
*p = '\0';
if (stat(buffer, &buf) == 0) {
if (!S_ISDIR(buf.st_mode)) {
fprintf(stderr,
"%s exists but is not a directory\n",
buffer);
return -1;
}
} else if (mkdir(buffer, 0777) < 0) {
fprintf(stderr, "failed to make directory %s: %m\n",
buffer);
return -1;
}
/* FIXME: What to do about permissions for dirs we
* have to create but are not in the cpio archive? */
}
return 0;
}
int
razor_write(int fd, const void *data, size_t size)
{
size_t rest;
ssize_t written;
const unsigned char *p;
rest = size;
p = data;
while (rest > 0) {
written = write(fd, p, rest);
if (written < 0) {
fprintf(stderr, "write error: %m\n");
return -1;
}
rest -= written;
p += written;
}
return 0;
}
struct qsort_context {
size_t size;
razor_compare_with_data_func_t compare;
void *data;
};
static void
qsort_swap(void *p1, void *p2, size_t size)
{
char buffer[size];
memcpy(buffer, p1, size);
memcpy(p1, p2, size);
memcpy(p2, buffer, size);
}
static void
__qsort_with_data(void *base, size_t nelem, uint32_t *map,
struct qsort_context *ctx)
{
void *p, *start, *end, *pivot;
uint32_t *mp, *mstart, *mend, tmp;
int left, right, result;
size_t size = ctx->size;
p = base;
start = base;
end = base + nelem * size;
mp = map;
mstart = map;
mend = map + nelem;
pivot = base + (random() % nelem) * size;
while (p < end) {
result = ctx->compare(p, pivot, ctx->data);
if (result < 0) {
qsort_swap(p, start, size);
tmp = *mp;
*mp = *mstart;
*mstart = tmp;
if (start == pivot)
pivot = p;
start += size;
mstart++;
p += size;
mp++;
} else if (result == 0) {
p += size;
mp++;
} else {
end -= size;
mend--;
qsort_swap(p, end, size);
tmp = *mp;
*mp = *mend;
*mend = tmp;
if (end == pivot)
pivot = p;
}
}
left = (start - base) / size;
right = (base + nelem * size - end) / size;
if (left > 1)
__qsort_with_data(base, left, map, ctx);
if (right > 1)
__qsort_with_data(end, right, mend, ctx);
}
uint32_t *
razor_qsort_with_data(void *base, size_t nelem, size_t size,
razor_compare_with_data_func_t compare, void *data)
{
struct qsort_context ctx;
uint32_t *map;
int i;
if (nelem == 0)
return NULL;
ctx.size = size;
ctx.compare = compare;
ctx.data = data;
map = malloc(nelem * sizeof (uint32_t));
for (i = 0; i < nelem; i++)
map[i] = i;
__qsort_with_data(base, nelem, map, &ctx);
return map;
} |
# 🚀 Java 클래스 로더
> #### 📃 Java 컴파일 챕터 작은 목차
> - [자바 컴파일 과정](./java_compile_sequence.md)
> - [자바 클래스 로더](./java_class_loader.md) - 현재 포스트
> - [자바 실행 엔진](./java_execution_engine.md)
## 📍 0. 들어가기 전에
Java는 **컴파일 시점이 아닌 런타임 시점에 클래스를 로드하고 링크 하는 동적 로딩 방식**을 사용한다.
이 때 각 클래스를 동적으로 로드하는 역할을 `클래스 로더`가 담당한다.
**동적 로딩**은 `로딩` - `링크` - `초기화` 과정을 거쳐 명령을 실행한다.
- ### 로딩
- 바이트코드를 메서드 영역에 적재한다.
- JVM은 메서드 영역에 읽어온 바이트 코드들의 정보를 저장한다.
- 로드된 클래스와 그 부모 클래스 정보.
- 클래스 파일과 Class, Interface, Enum 관련 여부.
- 변수나 메서드 정보.
- ### 링크
- 검증
- 읽어온 클래스가 자바 및 JVM 명세에 명시된 대로 잘 구성됐는지 검사한다.
- 준비
- 클래스가 필요로 하는 메모리를 할당하고 정의된 클래스, 인터페이스, 필드, 메서드를 나타내는 데이터 구조를 준비한다.
- 분석
- 심볼릭 메모리 레퍼런스를 메서드 영역 내 실제 레퍼런스로 바꾼다.
- ### 초기화
- 클래스 변수들을 적절한 값으로 초기화 한다. -> 정적 필드를 설정된 값으로 초기화 한다.
## 🔍 1. 종류
### 1.1 부트스트랩 클래스 로더 Bootstrap Class Loader
클래스 로더 계층 구조 상 최상위 계층 클래스 로더.
자바 클래스를 로드 할 수 있는 자바 자체의 클래스 로더와 Object 클래스를 로드한다.
- #### ~ Java 8
- `/jre/lib/rt.jar` 와 기타 핵심 라이브러리 등 JDK 내부 클래스를 로드한다.
- #### Java 9 ~
- `/rt.jar` 가 `/lib` 내에 모듈화 되어 포함되어 자바 자체의 클래스 로더만 로드한다.
### 1.2 확장 클래스 로더 Extension Class Loader -> Java 9 부터 Platform Class Loader 로 변경
부트스트랩 클래스 로더의 자식 클래스 로더로 확장 자바 클래스를 로드한다.
> 기본적으로 `${JAVA_HOME}/jre/lib/ext` 내 클래스들을 로드하고, `java.ext.dirs`환경변수를 통해 로드 할 디렉토리를 설정 할 수 있다.
- #### ~ Java 8
- `URLClassLoader`를 상속받고 설정된(혹은 기본) 디렉토리 내 모든 클래스를 로드한다.
- #### Java 9 ~
- `PlatformClassLoader`로 변경되었고 `URLClassLoader`가 아닌 `BulletinClassLoader`를 상속받아 Inner Static 클래스로 구현되어있다.
### 1.3 시스템 클래스 로더 System Class Loader
사용자가 지정한 ${CLASSPATH}의 클래스를 로드한다.
### 1.4 사용자 정의 클래스 로더 User-Defined Class Loader
클래스 로더 중 최하위 계층으로, 애플리케이션 레벨에서 사용자가 직접 정의하고 생성한 클래스 로더.
## 💡 2. 동작 방식
새로운 클래스를 로드할 경우 다음과 같은 절차를 따른다.
- 메서드 영역에 클래스가 적재돼있는지 확인한다. 있다면 그대로 사용한다.
- 메서드 영역에서 찾을 수 없을 경우 `시스템 클래스 로더`에 요청하고 `시스템 클래스 로더`는 `확장 클래스 로더`에 요청을 넘긴다.
- `확장 클래스 로더`는 `부트스트랩 클래스 로더`에 요청을 넘기고 `부트스트랩 클래스 로더`는 `부트스트랩 경로(/jre/lib)`에 해당 클래스가 존재하는지 확인한다.
- 클래스가 없다면 다시 `확장 클래스 로더`로 요청을 넘기고 확장 클래스 로더는 확장 경로(/jre/lib/ext)에서 찾아본다.
- `확장 클래스 로더`에서도 찾을 수 없다면 `시스템 클래스 로더`에서 시스템 경로에서 찾는다. 이 때 찾을 수 없다면 `ClassNotFoundException`을 발생시킨다.
> ### 클래스 로더 동작 확인
> - #### 실행
> - 다음과 같이 어떤 클래스 로더가 로드했는지 알 수 있다.
> - `zulu-17`을 기준으로 작성했다.
> ```
> System.out.println(Object.class.getClassLoader() + " loads Object.class");
> System.out.println(SQLData.class.getClassLoader() + " loads SQLData.class");
> System.out.println(Main.class.getClassLoader() + " loads Main.class");
> ```
> - #### 결과
> - `null` 은 `부트스트랩 클래스 로더`.
> ```
> null loads Object.class
> jdk.internal.loader.ClassLoaders$PlatformClassLoader@5305068a loads SQLData.class
> jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7 loads Main.class
> ```
## 🚧 3. 클래스 로더 3원칙
### 3.1 위임 원칙
- 클래스 로더는 리소스를 찾을 때 상위 클래스 로더로 요청을 위임한다.
### 3.2 가시 범위 원칙
- 하위 클래스 로더는 상위 클래스 로더가 로드한 클래스를 알 수 있지만 상위 클래스 로더는 하위 클래스 로더가 로드한 클래스를 알 수 없다.
- 상위 클래스 로더에서 로드한 클래스를 하위 클래스 로더가 사용할 수 있다.
### 3.3 유일성 원칙
- 하위 클래스 로더는 상위 클래스 로더가 로드한 클래스를 다시 로드하면 안된다.
- 위임 원칙으로 고유한 클래스 로딩을 보장 할 수 있다.
## 📝 4. 동적 로딩
### 4.1 로드타임 동적 로딩
```
public Class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world!!!");
}
}
```
위처럼 `hello world!!!`를 출력 하는 코드를 컴파일 과정 이후 실행 했을 때 클래스 로더는 `Object` 클래스와 `HelloWorld` 클래스를 읽고 로딩하기 위해 필요한 `String`, `System` 클래스를 로딩한다. 여기서 모든 클래스는 `HelloWorld` 클래스가 실행 되기 전 **로드타임에 동적으로 로드** 된다.
### 4.2 런타임 동적 로딩
객체지향 다형성 원리를 이용해 런타임 동적 로딩을 알아보자. 우선 다음과 같이 `Main`, `Car`, `SportsCar` 클래스코드를 이용해 세개의 파일을 만들고 실행 해보자.
```
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Car car = new SportsCar();
car.move();
}
}
---
public interface Car {
void move();
}
---
public class SportsCar implements Car {
@Override
public void move() {
System.out.println("Sports car move!!!");
}
}
```
정상적으로 실행되었다면 프로젝트의 실행파일 경로에 바이트 코드 결과물이 생성되고 다음과 같이 실행된다.
```
Hello world!
Sports car move!!!
```
이 때 클래스 로딩 로그를 확인해보려면 터미널을 열고 다음 명령어를 입력해보면 된다.
```
java classpath ${바이트코드 경로} -verbose:class ${메인클래스 명}
// ex) java classpath ./out/production/hello-world verbose:class Main
```
로그를 출력해보면 다음과 같이 어마어마하게 많은 클래스들이 로드타임에 로드되고 나서야 프로그램이 실행되고 실행되는 런타임에 `SportsCar` 클래스가 로드되는것을 확인할 수 있다.
```
// 명령어 입력
neo@Neos-MacBook-Air hello-world % java -classpath ./out/production/hello-world -verbose:class Main
... 중략 ...
// Car 클래스 로드.
[0.029s][info][class,load] Car source: file:/Users/neo/workspace/java/hello-world/out/production/hello-world/
... 중략 ...
Hello world!
// 이 지점에서 SportsCar 클래스가 로드 됨.
[0.029s][info][class,load] SportsCar source: file:/Users/neo/workspace/java/hello-world/out/production/hello-world/
Sports car move!!!
[0.029s][info][class,load] java.lang.Shutdown source: shared objects file
[0.029s][info][class,load] java.lang.Shutdown$Lock source: shared objects file
neo@Neos-MacBook-Air hello-world %
```
> #### 🧐 Q. 왜 `SportsCar` 클래스는 런타임 중간에 로드되는걸까?
> **A.** 앞서 배웠던 객체지향 원리중 다형성 원리를 생각해보자. 상위 클래스(인터페이스)인 `Car`는 구체화된 클래스로 객체를 전달 받아야 한다. 그런데 프로그램이 실행되며 실행문이 해석되기 전까지 JVM은 `Car`에 `SportsCar`가 올지 `Sedan`이 올지 알 수 없다. 즉, **로드타임에 어떤 클래스를 로딩할지 결정 할 수 없다**. 따라서 이 때 `SportsCar` 클래스는 런타임 중에 로딩된다.
## 👀 5. 동적로딩의 장점과 단점
### 5.1 장점
- 런타임 전 까지 메모리 낭비를 막을 수 있다.
- 사실 런타임 전까지, 해당 클래스가 사용되는 시점까지 정보를 알 수 없다.
### 5.2 단점
- 런타임에러를 조기에 발견하기 어렵다.
- 실행문이 실행되는 시점까지 가서야 발견할 수 있다.
- 동적로딩에도 시간비용이 발생하기때문에 성능저하로 이어질 수 있다.
---
### 📚 References
- [[Java] JVM의 클래스 로더란?](https://steady-coding.tistory.com/593)
- [자바의 클래스로더 알아보기](https://leeyh0216.github.io/posts/java_class_loader)
- [[JAVA] ☕ 클래스는 언제 메모리에 로딩 & 초기화 되는가 ❓](https://inpa.tistory.com/entry/JAVA-%E2%98%95-%ED%81%B4%EB%9E%98%EC%8A%A4%EB%8A%94-%EC%96%B8%EC%A0%9C-%EB%A9%94%EB%AA%A8%EB%A6%AC%EC%97%90-%EB%A1%9C%EB%94%A9-%EC%B4%88%EA%B8%B0%ED%99%94-%EB%90%98%EB%8A%94%EA%B0%80-%E2%9D%93)
- [자바의 클래스로더 알아보기](https://leeyh0216.github.io/posts/java_class_loader/) |
import { useState } from "react";
function TodoRow1({ onNewItem }) {
let [toDoName, setToDoName] = useState();
let [toDoDate, setToDoDate] = useState();
function handleNameChange(event) {
let name = event.target.value;
setToDoName(name);
}
function handleDateChange(event) {
let date = event.target.value;
setToDoDate(date);
}
function handleAddButton() {
onNewItem(toDoName, toDoDate);
setToDoName("");
setToDoDate("");
}
return (
<div class="container">
<div class="row sp-row">
<div class="col-6">
<input
type="text"
placeholder="Enter Todo here"
value={toDoName}
onChange={handleNameChange}
/>
</div>
<div class="col-4">
<input type="date" value={toDoDate} onChange={handleDateChange} />
</div>
<div class="col-2">
<button
type="button"
class="btn btn-success sp-button"
onClick={handleAddButton}
>
Add
</button>
</div>
</div>
</div>
);
}
export default TodoRow1; |
/*
The Apache Software License, Version 1.1
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Batik" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
apache@apache.org.
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation. For more information on the
Apache Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.batik.i18n;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* This class provides a default implementation of the Localizable interface.
* You can use it as a base class or as a member field and delegates various
* work to it.<p>
* For example, to implement Localizable, the following code can be used:
* <pre>
* package mypackage;
* ...
* public class MyClass implements Localizable {
* // This code fragment requires a file named
* // 'mypackage/resources/Messages.properties', or a
* // 'mypackage.resources.Messages' class which extends
* // java.util.ResourceBundle, accessible using the current
* // classpath.
* LocalizableSupport localizableSupport =
* new LocalizableSupport("mypackage.resources.Messages");
*
* public void setLocale(Locale l) {
* localizableSupport.setLocale(l);
* }
* public Local getLocale() {
* return localizableSupport.getLocale();
* }
* public String formatMessage(String key, Object[] args) {
* return localizableSupport.formatMessage(key, args);
* }
* }
* </pre>
* The algorithm for the Locale lookup in a LocalizableSupport object is:
* <ul>
* <li>
* if a Locale has been set by a call to setLocale(), use this Locale,
* else,
* <li/>
* <li>
* if a Locale has been set by a call to the setDefaultLocale() method
* of a LocalizableSupport object in the current LocaleGroup, use this
* Locale, else,
* </li>
* <li>
* use the object returned by Locale.getDefault() (and set by
* Locale.setDefault()).
* <li/>
* </ul>
* This offers the possibility to have a different Locale for each object,
* a Locale for a group of object and/or a Locale for the JVM instance.
* <p>
* Note: if no group is specified a LocalizableSupport object belongs to a
* default group common to each instance of LocalizableSupport.
*
* @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
* @version $Id$
*/
public class LocalizableSupport implements Localizable {
/**
* The locale group to which this object belongs.
*/
protected LocaleGroup localeGroup = LocaleGroup.DEFAULT;
/**
* The resource bundle classname.
*/
protected String bundleName;
/**
* The classloader to use to create the resource bundle.
*/
protected ClassLoader classLoader;
/**
* The current locale.
*/
protected Locale locale;
/**
* The locale in use.
*/
protected Locale usedLocale;
/**
* The resources
*/
protected ResourceBundle resourceBundle;
/**
* Same as LocalizableSupport(s, null).
*/
public LocalizableSupport(String s) {
this(s, null);
}
/**
* Creates a new Localizable object.
* The resource bundle class name is required allows the use of custom
* classes of resource bundles.
* @param s must be the name of the class to use to get the appropriate
* resource bundle given the current locale.
* @param cl is the classloader used to create the resource bundle,
* or null.
* @see java.util.ResourceBundle
*/
public LocalizableSupport(String s, ClassLoader cl) {
bundleName = s;
classLoader = cl;
}
/**
* Implements {@link org.apache.batik.i18n.Localizable#setLocale(Locale)}.
*/
public void setLocale(Locale l) {
if (locale != l) {
locale = l;
resourceBundle = null;
}
}
/**
* Implements {@link org.apache.batik.i18n.Localizable#getLocale()}.
*/
public Locale getLocale() {
return locale;
}
/**
* Implements {@link
* org.apache.batik.i18n.ExtendedLocalizable#setLocaleGroup(LocaleGroup)}.
*/
public void setLocaleGroup(LocaleGroup lg) {
localeGroup = lg;
}
/**
* Implements {@link
* org.apache.batik.i18n.ExtendedLocalizable#getLocaleGroup()}.
*/
public LocaleGroup getLocaleGroup() {
return localeGroup;
}
/**
* Implements {@link
* org.apache.batik.i18n.ExtendedLocalizable#setDefaultLocale(Locale)}.
* Later invocations of the instance methods will lead to update the
* resource bundle used.
*/
public void setDefaultLocale(Locale l) {
localeGroup.setLocale(l);
}
/**
* Implements {@link
* org.apache.batik.i18n.ExtendedLocalizable#getDefaultLocale()}.
*/
public Locale getDefaultLocale() {
return localeGroup.getLocale();
}
/**
* Implements {@link
* org.apache.batik.i18n.Localizable#formatMessage(String,Object[])}.
*/
public String formatMessage(String key, Object[] args) {
getResourceBundle();
return MessageFormat.format(resourceBundle.getString(key), args);
}
/**
* Implements {@link
* org.apache.batik.i18n.ExtendedLocalizable#getResourceBundle()}.
*/
public ResourceBundle getResourceBundle() {
Locale l;
if (resourceBundle == null) {
if (locale == null) {
if ((l = localeGroup.getLocale()) == null) {
usedLocale = Locale.getDefault();
} else {
usedLocale = l;
}
} else {
usedLocale = locale;
}
if (classLoader == null) {
resourceBundle = ResourceBundle.getBundle(bundleName,
usedLocale);
} else {
resourceBundle = ResourceBundle.getBundle(bundleName,
usedLocale,
classLoader);
}
} else if (locale == null) {
// Check for group Locale and JVM default locale changes.
if ((l = localeGroup.getLocale()) == null) {
if (usedLocale != (l = Locale.getDefault())) {
usedLocale = l;
if (classLoader == null) {
resourceBundle = ResourceBundle.getBundle(bundleName,
usedLocale);
} else {
resourceBundle = ResourceBundle.getBundle(bundleName,
usedLocale,
classLoader);
}
}
} else if (usedLocale != l) {
usedLocale = l;
if (classLoader == null) {
resourceBundle = ResourceBundle.getBundle(bundleName,
usedLocale);
} else {
resourceBundle = ResourceBundle.getBundle(bundleName,
usedLocale,
classLoader);
}
}
}
return resourceBundle;
}
} |
require('dotenv').config();
const express = require('express');
const { Server } = require('ws');
const { Deepgram } = require('@deepgram/sdk');
const app = express();
const PORT = process.env.PORT || 3001;
const deepgramApiKey = '11dd3c7b32a0b1fa5e360742b8c3c73346c55ebc';
const deepgram = new Deepgram(deepgramApiKey);
const server = app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
const wss = new Server({ server });
wss.on('connection', (ws) => {
console.log('Client connected');
var deepgramLive = deepgram.transcription.live({
punctuate: true, interim_results: true, endpointing: 300
});
deepgramLive.addListener('transcriptReceived', (transcription) => {
if (ws.readyState === ws.OPEN) {
ws.send(transcription);
}
});
deepgramLive.addListener('error', (error) => {
console.error("Deepgram error:", error);
});
ws.on('message', (message) => {
if (typeof message !== 'string') {
// Handle binary audio data
if (deepgramLive) {
try {
deepgramLive.send(message);
} catch (error) {
console.error("Error sending message to Deepgram:", error);
// Consider restarting Deepgram live session here if needed
}
}
} else {
// Handle JSON messages
try {
const data = JSON.parse(message);
if (data.action && data.action === 'stop_transcription') {
console.log("Stopping transcription");
if (deepgramLive) {
deepgramLive.finish();
// Delay starting a new session
setTimeout(() => {
deepgramLive = startDeepgramLive();
}, 1000);
}
}
} catch (error) {
console.error("Error parsing JSON:", error);
}
}
});
ws.on('close', () => {
console.log("WebSocket connection closed");
if (deepgramLive) {
deepgramLive.finish();
deepgramLive = null;
}
});
}); |
import { gravite, marioImage, terrainSkyBoundary } from "../conf";
import { State } from "./state";
export class Character {
x: number;
y: number;
vx: number;
vy: number;
dx: number;
dy: number;
size: { height: number; width: number; };
img: HTMLImageElement;
constructor(x: number, y: number, vx: number, vy: number, size: { height: number; width: number; }, img: HTMLImageElement) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
//Permet de savoir dans quel direction il court
this.dx = 0;
this.dy = 0;
this.size = size;
this.img = img;
}
}
export class Mario extends Character {
jumpHeight: number;
speed: number;
traits = {
jumping: false, running: false, bending: false,
falling: false, climbing: false, dead: false,
collisionOnTop: false, collisionOnBottom: false,
hasDestroyed: false, lostALife: false, immortal: false
};
immunise: number = 0
life: number = 3
camera: { width: number, height: number }
//Ajouter height et width
constructor(position: { x: number, y: number }, vx: number, vy: number, size: { height: number, width: number },
speed: number, jumpHeight: number) {
super(position.x, position.y, vx, vy, size, new Image())
this.speed = speed;
this.jumpHeight = jumpHeight;
this.img.src = marioImage;
this.camera = { width: size.width * 10, height: size.height * 2 }
}
actionOnMario(state: State) {
if (this.life <= 0) this.traits.dead = true
//S'il appuie sur fleche haut + n'est pas deja en l'air
if (state.input.keyUp && !this.traits.jumping && !this.traits.bending) {
this.dy = 1
this.vy = -this.jumpHeight
this.traits.jumping = true
}
else if (!state.input.keyUp && !this.traits.jumping) {
this.dy = 0
this.vy = 0
this.traits.jumping = false
}
//S'il n'est pas baisé et appuie sur fleche bas
if (state.input.keyDown && !this.traits.bending) {
this.y = this.y + this.size.height / 2
this.size.height = this.size.height / 2
this.traits.bending = true
}
else if (!state.input.keyDown && this.traits.bending) {
this.y = this.y - this.size.height
this.size.height = this.size.height * 2
this.traits.bending = false
}
if (state.input.keyRight || state.input.keyLeft) {
state.input.keyRight ? this.dx = 1 : this.dx = -1
this.vx = this.speed * this.dx
this.traits.running = true
}
else {
this.vx = 0
this.traits.running = false
}
}
collisionDangerous() {
if (!this.traits.immortal) {
this.traits.lostALife = true
this.traits.immortal = true
this.life--;
setTimeout(() => {
this.traits.immortal = false
}, 2000)
}
}
graviteOnMario(state: State): void {
let hitObstacleOnTopOfMario = false
for (const obstacle of state.obstacle) {
if (obstacle.collisionOnTop(this)) {
this.traits.jumping = false
this.y = obstacle.y - this.size.height
this.dy = 0
hitObstacleOnTopOfMario = true
}
if (obstacle.collisionOnBottom(this)) {
this.traits.jumping = false
this.traits.collisionOnTop = true
this.vy = 0
this.dy = 0
}
}
if (hitObstacleOnTopOfMario) return
//Dans le cas où il n'est pas au sol
if (this.y + this.size.height + this.vy < terrainSkyBoundary(state)) {
this.traits.jumping = true
this.vy += gravite
}
//Dans le cas où il n'est pas au sol et qu'il est en train de se baisser
else if (this.traits.bending && this.y + this.vy > terrainSkyBoundary(state) - this.size.height) {
this.y = terrainSkyBoundary(state) - this.size.height
this.traits.jumping = false
this.vy = 0
}
else {
this.y = terrainSkyBoundary(state) - this.size.height
this.traits.jumping = false
this.vy = 0
}
this.y += this.vy
}
walkingMario(state: State): void {
for (const obstacle of state.obstacle) {
if (obstacle.collisionOnLeft(this) && this.vx > 0) {
this.vx = 0
state.mario.x = obstacle.x - state.mario.size.width
}
else if (obstacle.collisionOnRight(this) && this.vx < 0) {
this.vx = 0
}
}
if (!this.traits.bending) {
this.x += this.vx
}
if (this.x <= 0) {
this.x = 0
}
}
step(state: State): State {
this.actionOnMario(state)
this.graviteOnMario(state)
this.walkingMario(state)
return state
}
} |
import React, { useEffect } from 'react'
import { connect } from 'react-redux'
import { fetchUsers } from '../redux'
function UserContainer({ userData, fetchUsers }) {
useEffect(() => {
fetchUsers();
}, [])
return userData.loading ? (
<p>Loading...</p>) : userData.error ?
(
<h2>{userData.error}</h2>)
: (
<div>
<h2>Users List</h2>
{
// userData &&
// userData.users &&
userData.users.map(user => <p key={user.id}>{user.name}</p>)
}
</div>
)
}
const mapStateToProps = state => {
return {
userData: state.user
}
}
const mapDispatchToProps = dispatch => {
return {
fetchUsers: () => dispatch(fetchUsers())
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserContainer) |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Pricing Table</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="#">Company Name</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Enterprise</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Support</a>
</li>
<li class="nav-item">
<a class="btn btn-primary" href="#">Signup</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-12">
<h1 class="text-center">Pricing</h1>
<p class="text-center">Quickly build an effective pricing table for your potential cunstomers with this</p>
<p class="text-center">Bootstrap example. It's built with default Bootstrap components and utilities</p>
<p class="text-center">with little customization.</p><br/>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-4">
<div class="card text-center">
<div class="card-header bg-white">
<h3 class="card-title text-black">Free</h3>
</div>
<div class="card-body">
<ul class="list-group list-group-flush">
<h2>$0/mo</h2>
<li class="list-group-item">10 users included</li>
<li class="list-group-item">2 GB of storage</li>
<li class="list-group-item">Email support</li>
<li class="list-group-item">Help center access</li>
</ul>
<a href="#" class="btn btn-primary">Sign up for free</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card text-center">
<div class="card-header bg-white">
<h3 class="card-title text-black">Pro</h3>
</div>
<div class="card-body">
<ul class="list-group list-group-flush">
<h2>$15/mo</h2>
<li class="list-group-item">20 users included</li>
<li class="list-group-item">10 GB of storage</li>
<li class="list-group-item">Priority email support</li>
<li class="list-group-item">Help center access</li>
</ul>
<a href="#" class="btn btn-primary">Get started</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card text-center">
<div class="card-header bg-white">
<h3 class="card-title text-black">Enterprise</h3>
</div>
<div class="card-body">
<ul class="list-group list-group-flush">
<h2>$29/mo</h2>
<li class="list-group-item">30 users included</li>
<li class="list-group-item">15 GB of storage</li>
<li class="list-group-item">Phone and email support</li>
<li class="list-group-item">Help center access</li>
</ul>
<a href="#" class="btn btn-primary">Contact us</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html> |
import java.util.Hashtable;
class Solution {
public ListNode deleteDuplicatesUnsorted(ListNode head) {
Map<Integer, Integer> map = new HashMap<>();
ListNode curr = head;
while (curr != null) {
map.put(curr.val, map.getOrDefault(curr.val, 0) + 1);
curr = curr.next;
}
ListNode dummy = new ListNode(0);
curr = dummy;
while (head != null) {
if (map.get(head.val) == 1) {
curr.next = head;
curr = curr.next;
}
head = head.next;
}
curr.next = null;
return dummy.next;
}
}
TC: Because this is a two-pass algorithm, TC will be O(n) + O(n) where n is the length of the list. So, the final TC will be O(n)
SC: Because we are using a space for each node in the map, the SC will be O(n). As this Map increases in size depending on the list, this will be O(n) |
// This file manages everything related to the local storage data on the phone
import Foundation
let userInfoFileName: String = "userInfo"
var timeFormat: Int = 0 // Default: 24 Hour format
var currency: Int = 0 // Default: BHD
// [[ MANAGING APP'S SETTINGS ]]
// Get the time format
func getTimeFormatStr() -> String {
var format: String = ""
switch timeFormat {
case 0:
format = "HH:mm"
case 1:
format = "h:mm a"
default:
format = "HH:mm"
}
return format
}
// Get currency
func getCurrencyStr() -> String {
var format: String = ""
switch currency {
case 0:
format = "BHD"
case 1:
format = "USD"
default:
format = "BHD"
}
return format
}
// Get the currency
// [[ MANAGING USER'S CARS ]]
// Read the user's car data from local storage and returns it
func readCarsData() -> [Car] {
var tempCarList: [Car] = []
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListDecoder = PropertyListDecoder()
if let retrievedData = try? Data(contentsOf: archiveURL),
let decodedData = try? propertyListDecoder.decode(Array<Profile>.self, from: retrievedData) {
//var counter: Int = 1
//for data in decodedData {
// print("Car #\(counter)")
// print(data)
// print("")
//
// counter += 1
//}
for data in decodedData[selectedProfileIndex].carsList {
tempCarList.append(data)
}
}
return tempCarList
}
// Adds a car to the global [My Cars] variable and then saves it to the local storage (for the user)
func addCarToLocalStorage(carData: Car) {
profilesData[selectedProfileIndex].carsList.append(carData)
myCarsData = profilesData[selectedProfileIndex].carsList
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(profilesData)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
}
// Overwrites the carsList both on local storage and the global variable
func updateCarsListStored(carsList: [Car]) {
myCarsData = carsList
profilesData[selectedProfileIndex].carsList = myCarsData
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(profilesData)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
}
// Updates a single Car
func updateCar(newCar: Car) {
myCarsData[selectedCarIndex].manufacturer = newCar.manufacturer
myCarsData[selectedCarIndex].model = newCar.model
myCarsData[selectedCarIndex].yearManufactured = newCar.yearManufactured
myCarsData[selectedCarIndex].engine = newCar.engine
myCarsData[selectedCarIndex].licensePlate = newCar.licensePlate
myCarsData[selectedCarIndex].mileage = newCar.mileage
myCarsData[selectedCarIndex].cost = newCar.cost
profilesData[selectedProfileIndex].carsList[selectedCarIndex] = myCarsData[selectedCarIndex]
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(profilesData)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
}
// [[ MANAGING USER'S SERVICES ]]
// Adds a service to the globally selected car (using an index) and then overwrites the carsList that is stored locally
func addServiceToLocalStorage(serviceData: Service) {
myCarsData[selectedCarIndex].servicesList.append(serviceData)
profilesData[selectedProfileIndex].carsList[selectedCarIndex].servicesList = myCarsData[selectedCarIndex].servicesList
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(profilesData)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
}
// Overwrites the servicesList of the selected car both on local storage and the global variable
func updateSerivcesListStored(servicesList: [Service]) {
myCarsData[selectedCarIndex].servicesList = servicesList
profilesData[selectedProfileIndex].carsList[selectedCarIndex].servicesList = servicesList
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(profilesData)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
}
// Updates a single service
func updateService(newService: Service) {
myCarsData[selectedCarIndex].servicesList[selectedServiceIndex].title = newService.title
myCarsData[selectedCarIndex].servicesList[selectedServiceIndex].date = newService.date
myCarsData[selectedCarIndex].servicesList[selectedServiceIndex].serviceMileage = newService.serviceMileage
myCarsData[selectedCarIndex].servicesList[selectedServiceIndex].serviceCost = newService.serviceCost
myCarsData[selectedCarIndex].servicesList[selectedServiceIndex].isDone = newService.isDone
profilesData[selectedProfileIndex].carsList[selectedCarIndex].servicesList = myCarsData[selectedCarIndex].servicesList
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(profilesData)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
}
// [[ MANAGING PROFILE INFO ]]
// Reads user's info and then returns it
func readUsersListStored() -> [Profile] {
var tempProfilesList: [Profile] = []
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListDecoder = PropertyListDecoder()
if let retrievedUserInfo = try? Data(contentsOf: archiveURL),
let decodedUserInfo = try? propertyListDecoder.decode(Array<Profile>.self, from: retrievedUserInfo) {
for data in decodedUserInfo {
tempProfilesList.append(data)
}
}
return tempProfilesList
}
// Checks if a user already exists
func checkUserExistence(userInfo: Profile) -> Bool {
let userExists: Bool = false
let profilesStored: [Profile] = readUsersListStored()
for profile in profilesStored {
if userInfo.username == profile.username {
return true
}
}
return userExists
}
// Register a new user
func registerUserInfo(profileInfo: Profile) {
profilesData.append(profileInfo)
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(profilesData)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
}
// Updates the current user's information
func updateUserProfile(updatedProfile: Profile) {
profilesData[selectedProfileIndex].username = updatedProfile.username
profilesData[selectedProfileIndex].fullName = updatedProfile.fullName
profilesData[selectedProfileIndex].age = updatedProfile.age
profilesData[selectedProfileIndex].address = updatedProfile.address
let documentsDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first!
let archiveURL = documentsDirectory
.appendingPathComponent(userInfoFileName)
.appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(profilesData)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
} |
#define ENABLE
#define MINBUFFERS
using System;
#if !FEATURE_CORECLR
using System.Diagnostics.Tracing;
#endif
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Security.Permissions;
#if PINNABLEBUFFERCACHE_MSCORLIB
namespace System.Threading
#else
namespace System
#endif
{
internal sealed class PinnableBufferCache
{
/// <summary>
/// Create a new cache for pinned byte[] buffers
/// </summary>
/// <param name="cacheName">A name used in diagnostic messages</param>
/// <param name="numberOfElements">The size of byte[] buffers in the cache (they are all the same size)</param>
public PinnableBufferCache(string cacheName, int numberOfElements) : this(cacheName, () => new byte[numberOfElements]) { }
/// <summary>
/// Get a buffer from the buffer manager. If no buffers exist, allocate a new one.
/// </summary>
public byte[] AllocateBuffer() { return (byte[])Allocate(); }
/// <summary>
/// Return a buffer back to the buffer manager.
/// </summary>
public void FreeBuffer(byte[] buffer) { Free(buffer); }
/// <summary>
/// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData)
/// This is only used in mscorlib.
/// </summary>
#if (ENABLE || MINBUFFERS)
[EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
[System.Security.SecuritySafeCritical]
#endif
internal PinnableBufferCache(string cacheName, Func<object> factory)
{
m_NotGen2 = new List<object>(DefaultNumberOfBuffers);
m_factory = factory;
#if ENABLE
// Check to see if we should disable the cache.
string envVarName = "PinnableBufferCache_" + cacheName + "_Disabled";
try
{
string envVar = Environment.GetEnvironmentVariable(envVarName);
if (envVar != null)
{
PinnableBufferCacheEventSource.Log.DebugMessage("Creating " + cacheName + " PinnableBufferCacheDisabled=" + envVar);
int index = envVar.IndexOf(cacheName, StringComparison.OrdinalIgnoreCase);
if (0 <= index)
{
// The cache is disabled because we haven't set the cache name.
PinnableBufferCacheEventSource.Log.DebugMessage("Disabling " + cacheName);
return;
}
}
}
catch
{
// Ignore failures when reading the environment variable.
}
#endif
#if MINBUFFERS
// Allow the environment to specify a minimum buffer count.
string minEnvVarName = "PinnableBufferCache_" + cacheName + "_MinCount";
try
{
string minEnvVar = Environment.GetEnvironmentVariable(minEnvVarName);
if (minEnvVar != null)
{
if (int.TryParse(minEnvVar, out m_minBufferCount))
CreateNewBuffers();
}
}
catch
{
// Ignore failures when reading the environment variable.
}
#endif
PinnableBufferCacheEventSource.Log.Create(cacheName);
m_CacheName = cacheName;
}
/// <summary>
/// Get a object from the buffer manager. If no buffers exist, allocate a new one.
/// </summary>
[System.Security.SecuritySafeCritical]
internal object Allocate()
{
#if ENABLE
// Check to see whether or not the cache is disabled.
if (m_CacheName == null)
return m_factory();
#endif
// Fast path, get it from our Gen2 aged m_FreeList.
object returnBuffer;
if (!m_FreeList.TryPop(out returnBuffer))
Restock(out returnBuffer);
// Computing free count is expensive enough that we don't want to compute it unless logging is on.
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
int numAllocCalls = Interlocked.Increment(ref m_numAllocCalls);
if (numAllocCalls >= 1024)
{
lock (this)
{
int previousNumAllocCalls = Interlocked.Exchange(ref m_numAllocCalls, 0);
if (previousNumAllocCalls >= 1024)
{
int nonGen2Count = 0;
foreach (object o in m_FreeList)
{
if (GC.GetGeneration(o) < GC.MaxGeneration)
{
nonGen2Count++;
}
}
PinnableBufferCacheEventSource.Log.WalkFreeListResult(m_CacheName, m_FreeList.Count, nonGen2Count);
}
}
}
PinnableBufferCacheEventSource.Log.AllocateBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(returnBuffer), returnBuffer.GetHashCode(), GC.GetGeneration(returnBuffer), m_FreeList.Count);
}
return returnBuffer;
}
/// <summary>
/// Return a buffer back to the buffer manager.
/// </summary>
[System.Security.SecuritySafeCritical]
internal void Free(object buffer)
{
#if ENABLE
// Check to see whether or not the cache is disabled.
if (m_CacheName == null)
return;
#endif
if (PinnableBufferCacheEventSource.Log.IsEnabled())
PinnableBufferCacheEventSource.Log.FreeBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(buffer), buffer.GetHashCode(), m_FreeList.Count);
if(buffer == null)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
PinnableBufferCacheEventSource.Log.FreeBufferNull(m_CacheName, m_FreeList.Count);
return;
}
// After we've done 3 gen1 GCs, assume that all buffers have aged into gen2 on the free path.
if ((m_gen1CountAtLastRestock + 3) > GC.CollectionCount(GC.MaxGeneration - 1))
{
lock (this)
{
if (GC.GetGeneration(buffer) < GC.MaxGeneration)
{
// The buffer is not aged, so put it in the non-aged free list.
m_moreThanFreeListNeeded = true;
PinnableBufferCacheEventSource.Log.FreeBufferStillTooYoung(m_CacheName, m_NotGen2.Count);
m_NotGen2.Add(buffer);
m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1);
return;
}
}
}
// If we discovered that it is indeed Gen2, great, put it in the Gen2 list.
m_FreeList.Push(buffer);
}
#region Private
/// <summary>
/// Called when we don't have any buffers in our free list to give out.
/// </summary>
/// <returns></returns>
[System.Security.SecuritySafeCritical]
private void Restock(out object returnBuffer)
{
lock (this)
{
// Try again after getting the lock as another thread could have just filled the free list. If we don't check
// then we unnecessarily grab a new set of buffers because we think we are out.
if (m_FreeList.TryPop(out returnBuffer))
return;
// Lazy init, Ask that TrimFreeListIfNeeded be called on every Gen 2 GC.
if (m_restockSize == 0)
Gen2GcCallback.Register(Gen2GcCallbackFunc, this);
// Indicate to the trimming policy that the free list is insufficent.
m_moreThanFreeListNeeded = true;
PinnableBufferCacheEventSource.Log.AllocateBufferFreeListEmpty(m_CacheName, m_NotGen2.Count);
// Get more buffers if needed.
if (m_NotGen2.Count == 0)
CreateNewBuffers();
// We have no buffers in the aged freelist, so get one from the newer list. Try to pick the best one.
// Debug.Assert(m_NotGen2.Count != 0);
int idx = m_NotGen2.Count - 1;
if (GC.GetGeneration(m_NotGen2[idx]) < GC.MaxGeneration && GC.GetGeneration(m_NotGen2[0]) == GC.MaxGeneration)
idx = 0;
returnBuffer = m_NotGen2[idx];
m_NotGen2.RemoveAt(idx);
// Remember any sub-optimial buffer so we don't put it on the free list when it gets freed.
if (PinnableBufferCacheEventSource.Log.IsEnabled() && GC.GetGeneration(returnBuffer) < GC.MaxGeneration)
{
PinnableBufferCacheEventSource.Log.AllocateBufferFromNotGen2(m_CacheName, m_NotGen2.Count);
}
// If we have a Gen1 collection, then everything on m_NotGen2 should have aged. Move them to the m_Free list.
if (!AgePendingBuffers())
{
// Before we could age at set of buffers, we have handed out half of them.
// This implies we should be proactive about allocating more (since we will trim them if we over-allocate).
if (m_NotGen2.Count == m_restockSize / 2)
{
PinnableBufferCacheEventSource.Log.DebugMessage("Proactively adding more buffers to aging pool");
CreateNewBuffers();
}
}
}
}
/// <summary>
/// See if we can promote the buffers to the free list. Returns true if sucessful.
/// </summary>
[System.Security.SecuritySafeCritical]
private bool AgePendingBuffers()
{
if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1))
{
// Allocate a temp list of buffers that are not actually in gen2, and swap it in once
// we're done scanning all buffers.
int promotedCount = 0;
List<object> notInGen2 = new List<object>();
PinnableBufferCacheEventSource.Log.AllocateBufferAged(m_CacheName, m_NotGen2.Count);
for (int i = 0; i < m_NotGen2.Count; i++)
{
// We actually check every object to ensure that we aren't putting non-aged buffers into the free list.
object currentBuffer = m_NotGen2[i];
if (GC.GetGeneration(currentBuffer) >= GC.MaxGeneration)
{
m_FreeList.Push(currentBuffer);
promotedCount++;
}
else
{
notInGen2.Add(currentBuffer);
}
}
PinnableBufferCacheEventSource.Log.AgePendingBuffersResults(m_CacheName, promotedCount, notInGen2.Count);
m_NotGen2 = notInGen2;
return true;
}
return false;
}
/// <summary>
/// Generates some buffers to age into Gen2.
/// </summary>
private void CreateNewBuffers()
{
// We choose a very modest number of buffers initially because for the client case. This is often enough.
if (m_restockSize == 0)
m_restockSize = 4;
else if (m_restockSize < DefaultNumberOfBuffers)
m_restockSize = DefaultNumberOfBuffers;
else if (m_restockSize < 256)
m_restockSize = m_restockSize * 2; // Grow quickly at small sizes
else if (m_restockSize < 4096)
m_restockSize = m_restockSize * 3 / 2; // Less agressively at large ones
else
m_restockSize = 4096; // Cap how agressive we are
// Ensure we hit our minimums
if (m_minBufferCount > m_buffersUnderManagement)
m_restockSize = Math.Max(m_restockSize, m_minBufferCount - m_buffersUnderManagement);
PinnableBufferCacheEventSource.Log.AllocateBufferCreatingNewBuffers(m_CacheName, m_buffersUnderManagement, m_restockSize);
for (int i = 0; i < m_restockSize; i++)
{
// Make a new buffer.
object newBuffer = m_factory();
// Create space between the objects. We do this because otherwise it forms a single plug (group of objects)
// and the GC pins the entire plug making them NOT move to Gen1 and Gen2. by putting space between them
// we ensure that object get a chance to move independently (even if some are pinned).
var dummyObject = new object();
m_NotGen2.Add(newBuffer);
}
m_buffersUnderManagement += m_restockSize;
m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1);
}
/// <summary>
/// This is the static function that is called from the gen2 GC callback.
/// The input object is the cache itself.
/// NOTE: The reason that we make this functionstatic and take the cache as a parameter is that
/// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when
/// the application no longer needs it.
/// </summary>
[System.Security.SecuritySafeCritical]
private static bool Gen2GcCallbackFunc(object targetObj)
{
return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded();
}
/// <summary>
/// This is called on every gen2 GC to see if we need to trim the free list.
/// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK. INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE).
/// If you register a non-static function as a callback, then this object will be leaked.
/// </summary>
[System.Security.SecuritySafeCritical]
private bool TrimFreeListIfNeeded()
{
int curMSec = Environment.TickCount;
int deltaMSec = curMSec - m_msecNoUseBeyondFreeListSinceThisTime;
PinnableBufferCacheEventSource.Log.TrimCheck(m_CacheName, m_buffersUnderManagement, m_moreThanFreeListNeeded, deltaMSec);
// If we needed more than just the set of aged buffers since the last time we were called,
// we obviously should not be trimming any memory, so do nothing except reset the flag
if (m_moreThanFreeListNeeded)
{
m_moreThanFreeListNeeded = false;
m_trimmingExperimentInProgress = false;
m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
return true;
}
// We require a minimum amount of clock time to pass (10 seconds) before we trim. Ideally this time
// is larger than the typical buffer hold time.
if (0 <= deltaMSec && deltaMSec < 10000)
return true;
// If we got here we have spend the last few second without needing to lengthen the free list. Thus
// we have 'enough' buffers, but maybe we have too many.
// See if we can trim
lock (this)
{
// Hit a ----, try again later.
if (m_moreThanFreeListNeeded)
{
m_moreThanFreeListNeeded = false;
m_trimmingExperimentInProgress = false;
m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
return true;
}
var freeCount = m_FreeList.Count; // This is expensive to fetch, do it once.
// If there is something in m_NotGen2 it was not used for the last few seconds, it is trimable.
if (m_NotGen2.Count > 0)
{
// If we are not performing an experiment and we have stuff that is waiting to go into the
// free list but has not made it there, it could be becasue the 'slow path' of restocking
// has not happened, so force this (which should flush the list) and start over.
if (!m_trimmingExperimentInProgress)
{
PinnableBufferCacheEventSource.Log.TrimFlush(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count);
AgePendingBuffers();
m_trimmingExperimentInProgress = true;
return true;
}
PinnableBufferCacheEventSource.Log.TrimFree(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count);
m_buffersUnderManagement -= m_NotGen2.Count;
// Possibly revise the restocking down. We don't want to grow agressively if we are trimming.
var newRestockSize = m_buffersUnderManagement / 4;
if (newRestockSize < m_restockSize)
m_restockSize = Math.Max(newRestockSize, DefaultNumberOfBuffers);
m_NotGen2.Clear();
m_trimmingExperimentInProgress = false;
return true;
}
// Set up an experiment where we use 25% less buffers in our free list. We put them in
// m_NotGen2, and if they are needed they will be put back in the free list again.
var trimSize = freeCount / 4 + 1;
// We are OK with a 15% overhead, do nothing in that case.
if (freeCount * 15 <= m_buffersUnderManagement || m_buffersUnderManagement - trimSize <= m_minBufferCount)
{
PinnableBufferCacheEventSource.Log.TrimFreeSizeOK(m_CacheName, m_buffersUnderManagement, freeCount);
return true;
}
// Move buffers from teh free list back to the non-aged list. If we don't use them by next time, then we'll consider trimming them.
PinnableBufferCacheEventSource.Log.TrimExperiment(m_CacheName, m_buffersUnderManagement, freeCount, trimSize);
object buffer;
for (int i = 0; i < trimSize; i++)
{
if (m_FreeList.TryPop(out buffer))
m_NotGen2.Add(buffer);
}
m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
m_trimmingExperimentInProgress = true;
}
// Indicate that we want to be called back on the next Gen 2 GC.
return true;
}
private const int DefaultNumberOfBuffers = 16;
private string m_CacheName;
private Func<object> m_factory;
/// <summary>
/// Contains 'good' buffers to reuse. They are guarenteed to be Gen 2 ENFORCED!
/// </summary>
private ConcurrentStack<object> m_FreeList = new ConcurrentStack<object>();
/// <summary>
/// Contains buffers that are not gen 2 and thus we do not wish to give out unless we have to.
/// To implement trimming we sometimes put aged buffers in here as a place to 'park' them
/// before true deletion.
/// </summary>
private List<object> m_NotGen2;
/// <summary>
/// What whas the gen 1 count the last time re restocked? If it is now greater, then
/// we know that all objects are in Gen 2 so we don't have to check. Should be updated
/// every time something gets added to the m_NotGen2 list.
/// </summary>
private int m_gen1CountAtLastRestock;
/// <summary>
/// Used to ensure we have a minimum time between trimmings.
/// </summary>
private int m_msecNoUseBeyondFreeListSinceThisTime;
/// <summary>
/// To trim, we remove things from the free list (which is Gen 2) and see if we 'hit bottom'
/// This flag indicates that we hit bottom (we really needed a bigger free list).
/// </summary>
private bool m_moreThanFreeListNeeded;
/// <summary>
/// The total number of buffers that this cache has ever allocated.
/// Used in trimming heuristics.
/// </summary>
private int m_buffersUnderManagement;
/// <summary>
/// The number of buffers we added the last time we restocked.
/// </summary>
private int m_restockSize;
/// <summary>
/// Did we put some buffers into m_NotGen2 to see if we can trim?
/// </summary>
private bool m_trimmingExperimentInProgress;
/// <summary>
/// A forced minimum number of buffers.
/// </summary>
private int m_minBufferCount;
/// <summary>
/// The number of calls to Allocate.
/// </summary>
private int m_numAllocCalls;
#endregion
}
/// <summary>
/// Schedules a callback roughly every gen 2 GC (you may see a Gen 0 an Gen 1 but only once)
/// (We can fix this by capturing the Gen 2 count at startup and testing, but I mostly don't care)
/// </summary>
internal sealed class Gen2GcCallback : CriticalFinalizerObject
{
[System.Security.SecuritySafeCritical]
public Gen2GcCallback()
: base()
{
}
/// <summary>
/// Schedule 'callback' to be called in the next GC. If the callback returns true it is
/// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop.
///
/// NOTE: This callback will be kept alive until either the callback function returns false,
/// or the target object dies.
/// </summary>
public static void Register(Func<object, bool> callback, object targetObj)
{
// Create a unreachable object that remembers the callback function and target object.
Gen2GcCallback gcCallback = new Gen2GcCallback();
gcCallback.Setup(callback, targetObj);
}
#region Private
private Func<object, bool> m_callback;
private GCHandle m_weakTargetObj;
[System.Security.SecuritySafeCritical]
private void Setup(Func<object, bool> callback, object targetObj)
{
m_callback = callback;
m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak);
}
[System.Security.SecuritySafeCritical]
~Gen2GcCallback()
{
// Check to see if the target object is still alive.
if (!m_weakTargetObj.IsAllocated)
{
return;
}
object targetObj = m_weakTargetObj.Target;
if (targetObj == null)
{
// The target object is dead, so this callback object is no longer needed.
m_weakTargetObj.Free();
return;
}
// Execute the callback method.
try
{
if (!m_callback(targetObj))
{
// If the callback returns false, this callback object is no longer needed.
return;
}
}
catch
{
// Ensure that we still get a chance to resurrect this object, even if the callback throws an exception.
}
// Resurrect ourselves by re-registering for finalization.
if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
{
GC.ReRegisterForFinalize(this);
}
}
#endregion
}
#if FEATURE_CORECLR
internal sealed class PinnableBufferCacheEventSource
{
public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
public bool IsEnabled() { return false; }
public void DebugMessage(string message) {}
public void DebugMessage1(string message, long value) {}
public void DebugMessage2(string message, long value1, long value2) {}
public void DebugMessage3(string message, long value1, long value2, long value3) {}
public void Create(string cacheName) {}
public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) {}
public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) {}
public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) {}
public void AllocateBufferAged(string cacheName, int agedCount) {}
public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) {}
public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) {}
public void FreeBufferNull(string cacheName, int freeCountBefore) { }
public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) {}
public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) {}
public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) {}
public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) {}
public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) {}
public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) {}
public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) {}
public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) {}
static internal ulong AddressOf(object obj)
{
return 0;
}
[System.Security.SecuritySafeCritical]
static internal unsafe long AddressOfObject(byte[] array)
{
return 0;
}
}
#else
/// <summary>
/// PinnableBufferCacheEventSource is a private eventSource that we are using to
/// debug and monitor the effectiveness of PinnableBufferCache
/// </summary>
#if PINNABLEBUFFERCACHE_MSCORLIB
[EventSource(Name = "Microsoft-DotNETRuntime-PinnableBufferCache")]
#else
[EventSource(Name = "Microsoft-DotNETRuntime-PinnableBufferCache-System")]
#endif
internal sealed class PinnableBufferCacheEventSource : EventSource
{
public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
[Event(1, Level = EventLevel.Verbose)]
public void DebugMessage(string message) { if (IsEnabled()) WriteEvent(1, message); }
[Event(2, Level = EventLevel.Verbose)]
public void DebugMessage1(string message, long value) { if (IsEnabled()) WriteEvent(2, message, value); }
[Event(3, Level = EventLevel.Verbose)]
public void DebugMessage2(string message, long value1, long value2) { if (IsEnabled()) WriteEvent(3, message, value1, value2); }
[Event(18, Level = EventLevel.Verbose)]
public void DebugMessage3(string message, long value1, long value2, long value3) { if (IsEnabled()) WriteEvent(18, message, value1, value2, value3); }
[Event(4)]
public void Create(string cacheName) { if (IsEnabled()) WriteEvent(4, cacheName); }
[Event(5, Level = EventLevel.Verbose)]
public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { if (IsEnabled()) WriteEvent(5, cacheName, objectId, objectHash, objectGen, freeCountAfter); }
[Event(6)]
public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { if (IsEnabled()) WriteEvent(6, cacheName, notGen2CountAfter); }
[Event(7)]
public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { if (IsEnabled()) WriteEvent(7, cacheName, totalBuffsBefore, objectCount); }
[Event(8)]
public void AllocateBufferAged(string cacheName, int agedCount) { if (IsEnabled()) WriteEvent(8, cacheName, agedCount); }
[Event(9)]
public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(9, cacheName, notGen2CountBefore); }
[Event(10, Level = EventLevel.Verbose)]
public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { if (IsEnabled()) WriteEvent(10, cacheName, objectId, objectHash, freeCountBefore); }
[Event(11)]
public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(11, cacheName, notGen2CountBefore); }
[Event(13)]
public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { if (IsEnabled()) WriteEvent(13, cacheName, totalBuffs, neededMoreThanFreeList, deltaMSec); }
[Event(14)]
public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { if (IsEnabled()) WriteEvent(14, cacheName, totalBuffs, freeListCount, toBeFreed); }
[Event(15)]
public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { if (IsEnabled()) WriteEvent(15, cacheName, totalBuffs, freeListCount, numTrimTrial); }
[Event(16)]
public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { if (IsEnabled()) WriteEvent(16, cacheName, totalBuffs, freeListCount); }
[Event(17)]
public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(17, cacheName, totalBuffs, freeListCount, notGen2CountBefore); }
[Event(20)]
public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { if (IsEnabled()) WriteEvent(20, cacheName, promotedToFreeListCount, heldBackCount); }
[Event(21)]
public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { if (IsEnabled()) WriteEvent(21, cacheName, freeListCount, gen0BuffersInFreeList); }
[Event(22)]
public void FreeBufferNull(string cacheName, int freeCountBefore) { if(IsEnabled()) WriteEvent(22, cacheName, freeCountBefore); }
static internal ulong AddressOf(object obj)
{
var asByteArray = obj as byte[];
if (asByteArray != null)
return (ulong)AddressOfByteArray(asByteArray);
return 0;
}
[System.Security.SecuritySafeCritical]
static internal unsafe long AddressOfByteArray(byte[] array)
{
if (array == null)
return 0;
fixed (byte* ptr = array)
return (long)(ptr - 2 * sizeof(void*));
}
}
#endif
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.