text
stringlengths 184
4.48M
|
---|
<!--yml
category: codewars
date: 2022-08-13 11:48:20
-->
# Codewars第九天–Can you get the loop ?_soufal的博客-CSDN博客
> 来源:[https://blog.csdn.net/u011562123/article/details/81946003?ops_request_misc=&request_id=&biz_id=102&utm_term=codewars&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-9-81946003.nonecase](https://blog.csdn.net/u011562123/article/details/81946003?ops_request_misc=&request_id=&biz_id=102&utm_term=codewars&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-9-81946003.nonecase)
## Codewars第九天–Can you get the loop ?
题目描述:
您将获得一个节点,该节点是链接列表的开头。 此列表始终包含尾部和循环。
您的目标是确定循环的长度。
例如,在下图中,尾部的大小为3,循环大小为11。

在这里,可以使用`node.next` 来获得下一个节点。
思想:在这里只需要找到某一个节点有着两个前驱即可。这个节点就可以当做循环列表的开头和结尾。他的大小为原列表中的长度减去他在列表中的位置,并加1。
这里的输入node为一个节点对象,指向一个列表的开头。为了判断循环的大小,在这里设置一个循环判断值:`temp` 。以及一个顺序存储当前节点的列表`result`。循环的条件为:当前节点的下一个节点不在`result` 中时,将其添加到列表中,直到发现某一个节点的后继已经存在于`result` 中了。停止循环。这意味着我们找到了有着两个前驱的节点。
**这里开始出现了一个问题,当循环列表中有两个节点时,测试用例判断其长度为1,因此在最后的结果返回时条件了判断条件。**
通过了全部测试用例。
代码如下:
```
def loop_size(node):
temp = True
new_node = node
result = []
while temp:
result.append(new_node)
new_node = new_node.next
if new_node in result:
temp = False
loop_size = len(result) - result.index(new_node.next) + 1
if loop_size == 2:
return loop_size - 1
else:
return loop_size
``` |
import { SWAllItemsResponse } from '@core/models/intefaces/common-response.interface';
import { gameReducer, initialState } from '../game.reducer';
import { GameApiActions } from '../actions';
describe('Game reducer', () => {
it('should update isLoading state', () => {
const state = gameReducer(
initialState,
GameApiActions.fetchRandomCharacters,
);
const expectedState = { ...initialState, isLoading: true };
expect(state).toEqual(expectedState);
});
it('should update characters list', () => {
const fakeResult = { uid: '1', name: 'Luke', url: '' };
const fakeActionPayload = { results: [fakeResult] } as SWAllItemsResponse;
const state = gameReducer(
initialState,
GameApiActions.fetchAllCharactersSuccess({
charactersResponse: fakeActionPayload as SWAllItemsResponse,
}),
);
const expectedState = {
...initialState,
charactersList: { '1': fakeResult },
isLoading: false,
};
expect(state).toEqual(expectedState);
});
}); |
package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;
import com.test.Member.MemberDto;
import java.util.ArrayList;
class Member {
private String userid;
private String username;
private int age;
Member(String userid, String username, int age) {
this.userid = userid;
this.username = username;
this.age = age;
}
static class Builder {
private String userid;
private String username;
private int age;
public Builder userid(String userid) {
this.userid = userid;
return this;
}
public Builder username(String username) {
this.username = username;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Member build() {
if(userid == null || username == null || age == 0)
throw new IllegalStateException("멤버클래스가 생성이 안된다");
return new Member(userid, username, age);
}
} // class Builder_finish
public String getUserid() { return userid; }
public String getUsername() { return username; }
public int getAge() { return age; }
class MemberDto {
private String userid;
private String username;
private int age;
public String getUserid() { return userid; }
public String getUsername() { return username; }
public int getAge() { return age; }
MemberDto(Member member) {
this.userid = member.getUserid();
this.username = member.getUsername();
this.age = member.getAge();
} //MemberDto 매서드 끝
} //class MemberDto_finish
} //class Member_finish
public class JDBCTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:mariadb://127.0.0.1:3306/webdev";
String userid = "webmaster";
String userpw = "201410606";
String query = "select userid, username, age from tbl_test";
Connection con;
Statement stmt;
ResultSet rs;
Class.forName("org.mariadb.jdbc.Driver");
con = DriverManager.getConnection(url, userid, userpw);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
List<Member> list = new ArrayList<>();
List<MemberDto> listDTO = new ArrayList<>();
while(rs.next()) {
//list.add(new Member(rs.getString("userid"), rs.getString("username"), rs.getInt("age"));
list.add(new Member.Builder()
.userid(rs.getString("userid"))
.username(rs.getString("username"))
.age(rs.getInt("age"))
.build()
);
}
// for(Member member: list) {
// System.out.println("아이디 = " + member.getUserid() + ", 이름 = " + member.getUsername() + ", 나이" + member.getAge());
// }
listDTO = list.stream().map(MemberDto::new).collect(Collectors.toList());
for(MemberDto member: listDTO) {
System.out.println("아이디 = " + member.getUserid() + ", 이름 = " + member.getUsername() + ", 나이" + member.getAge());
}
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
} //public static void_end
} // public class jdbc_finshhhhh |
// Write a function that takes in an array of numbers and returns an array with all numbers multiplied by 3.
const testArr1 = [3, 9, 15, 4, 10]
// // output: [9, 27, 45, 12, 30]
const mult3 = (array) => {
let newArray = []
for (let i = 0; i < array.length; i++){
newArray.push(array[i] * 3)
}
return newArray
}
console.log(mult3(testArr1))
// output: [ 9, 27, 45, 12, 30 ]
// Write a function that takes in an array of numbers and returns a new array with only odd numbers.
const testArr2 = [0, 2, -7, 3, 5, 8, 10, 13]
// // output: [-7, 3, 5, 13]
const oddNumber = (array) => {
let newArray = []
for (let i = 0; i < array.length; i++){
if (array[i] % 2 !== 0){
newArray.push(array[i])
}
}
return newArray
}
console.log(oddNumber(testArr2));
// output: [ -7, 3, 5, 13 ]
// Write a function that takes in an array of numbers and letters and returns a string with only the letters. HINT: use the typeof method.
const comboArr = [ 7, "n", true, "i", "c", 10, "e", -388, "w", 3, "o", 0, "r", false, "k" ]
// // output: "nicework"
const letterSort = (array) => {
let newArray = []
for (let i = 0; i < array.length; i++){
if (typeof array[i] === "string"){
newArray.push(array[i])
}
}
return newArray.join("")
}
console.log(letterSort(comboArr));
// output: "nicework"
// Create a function that takes in an array of numbers and returns the sum.
const addThese1 = [1, 2, 3, 4]
// // output: 10
const adder = (array) => {
let sum = 0
for (let i = 0; i < array.length; i++){
sum += array[i]
}
return sum
}
console.log(adder(addThese1));
// output: 10
const addThese2 = []
// // output: 0
console.log(adder(addThese2));
// output: 0
// Create a function that takes in an array of numbers and returns the index of the largest number.
const indexHighestNumber = [1, 4, 2, 3]
// // output: 1
const largestNum = (array) => {
let highest = 0
for (let i = 0; i < array.length; i++){
if (array[i] > highest){
console.log(array[i]);
let highest = array[i]
}
}
return highest
}
console.log(largestNum(indexHighestNumber));
// 🏔 Stretch Goals
// Create a function that takes in two arrays and returns one array with no duplicate values.
// const arr1 = [3, 7, 10, 5, 4, 3, 3]
// const arr2 = [7, 8, 2, 3, 1, 5, 4]
// // output: [3, 7, 10, 5, 4, 8, 2, 1]
// Create a function that takes in two numbers as arguments and returns an array the length of the first number filled with the second number.
// const arrayLength = 6
// const arrayValue = 0
// // output: [0, 0, 0, 0, 0, 0]
// const arrayLength = 4
// const arrayValue = 11
// // output: [11, 11, 11, 11]
// Create a function that takes a number as an argument. Add up all the numbers from 1 to the number you passed to the function.
// const addUp1 = 4
// // 1 + 2 + 3 + 4 = 10
// // output: 10
// const addUp2 = 10
// // 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
// // output: 55
// const addUp3 = 600
// // output: 180300
// 🏔 Epic Goals
// Create a function called highLow that takes in a number and returns whether the number is higher or lower than the "answer".
// Create an HTML page and link your JavaScript file. More info here.
// As a user, I see a prompt or input where I can guess a number between 1 and 100 (both inclusive).
// As a user, I can see if my guess is too high or too low.
// As a user, if I guess the "answer" correctly I am notified that I won.
// As a user, I can continue to guess the "answer" until I am correct.
// STRETCH: As a user, if I have not guessed the correct number in seven tries I see a losing message. |
import torch
def make_dataset():
"""Return train and test dataloaders for MNIST."""
train_data, train_labels = (
[],
[],
)
for i in range(5):
train_data.append(torch.load(f"data/raw/corruptmnist/train_images_{i}.pt"))
train_labels.append(torch.load(f"data/raw/corruptmnist/train_target_{i}.pt"))
train_data = torch.cat(train_data, dim=0)
train_labels = torch.cat(train_labels, dim=0)
test_data = torch.load("data/raw/corruptmnist/test_images.pt")
test_labels = torch.load("data/raw/corruptmnist/test_target.pt")
print(train_data.shape)
print(train_labels.shape)
print(test_data.shape)
print(test_labels.shape)
train_data = train_data.unsqueeze(1)
test_data = test_data.unsqueeze(1)
train_data = (train_data - train_data.mean()) / train_data.std()
test_data = (test_data - test_data.mean()) / test_data.std()
train = torch.utils.data.TensorDataset(train_data, train_labels)
test = torch.utils.data.TensorDataset(test_data, test_labels)
torch.save(train, "data/processed/train_dataset.pt")
torch.save(test, "data/processed/test_dataset.pt")
if __name__ == "__main__":
make_dataset() |
// copied from 1-usertojson.dart, adding id prop, new instance fromJson, and method toString
class User {
// Propteries
String name;
int age;
double height;
int id;
// Constructor w/ named parameters
User({required this.name, required this.age, required this.height, required this.id});
// Method
String showName() {
return 'Hello $name';
}
// Converts the User instance to a Map
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'age': age,
'height': height,
};
}
// Factory constructor to create a User instance from a map
static User fromJson(Map<dynamic, dynamic> userJson) {
return User(
id: userJson['id'],
name: userJson['name'],
age: userJson['age'],
height: userJson['height'],
);
}
// Overrides Object.toString method to return a string representation of the User instance
@override
String toString() {
return 'User(id : $id ,name: $name, age: $age, height: $height)';
}
} |
async function rangosSalarialesDropdown() {
try {
const respuestaRangosSalariales = await fetch("http://localhost:3000/rangosSalariales");
const rangosSalariales = await respuestaRangosSalariales.json();
console.log(rangosSalariales);
const rangosSalarialesHTML = document.getElementById("rango-salarial");
rangosSalariales.forEach(function (rangoSalarial) {
const option = `<option value="${rangoSalarial.id}">${rangoSalarial.rangoSalarial}</option>`;
rangosSalarialesHTML.innerHTML += option;
});
} catch (error) {
console.log("Error:", error);
alert("Error al cargar los rangos salariales");
}
};
async function crearPuestoTrabajo(evento) {
evento.preventDefault();
const userName = localStorage.getItem("userName");
const userEmail = localStorage.getItem("userEmail");
const empresa = userName;
const titulo = document.getElementById("nombre").value;
const visibilidad = document.getElementById("visibilidad").value;
const rangoSalarialID = document.getElementById("rango-salarial").value;
const rangoSalarial = document.getElementById("rango-salarial").options[document.getElementById("rango-salarial").selectedIndex].text;
const requisitosMinimos = document.getElementById("requisitosMinimos").value;
const requisitosDeseados = document.getElementById("requisitosDeseados").value;
const correoGerente = userEmail;
const puestoTrabajo = {
empresa,
titulo,
visibilidad,
rangoSalarialID,
rangoSalarial,
requisitosMinimos,
requisitosDeseados,
correoGerente,
};
const confirmacion = confirm("¿Estás seguro de que deseas crear el puesto de trabajo?");
if (confirmacion) {
try {
const respuestaCrearPuestoTrabajo = await fetch("http://localhost:3000/empleos", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(puestoTrabajo),
});
const puestoTrabajoCreado = await respuestaCrearPuestoTrabajo.json();
console.log(puestoTrabajoCreado);
if (puestoTrabajoCreado) {
alert("Puesto de trabajo creado exitosamente");
const notificacionData = {
correoRecipiente: puestoTrabajo.correoGerente,
titulo: "Nuevo puesto de trabajo",
mensaje: "Se ha creado el puesto de trabajo '" + puestoTrabajo.titulo +"'.",
};
await fetch("http://localhost:3000/notificaciones", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(notificacionData),
});
window.location.href = "administrarPuestosAdmin.html";
} else {
alert("Error al crear el puesto de trabajo");
}
} catch (error) {
console.log("Error:", error);
alert("Error al crear el puesto de trabajo");
}
} else {
alert("Se canceló la creación del puesto de trabajo");
}
};
window.onload = function () {
rangosSalarialesDropdown();
let form = document.getElementById("crearPuestoForm");
form.addEventListener("submit", crearPuestoTrabajo)
}; |
<?php
namespace App\Models;
use App\Enum\ShippingOptionTypeEnum;
use App\Models\Traits\Activatable;
use App\Models\Traits\HasFeUsage;
class ShippingOption extends BaseModel
{
use Activatable;
use HasFeUsage;
protected $fillable = [
'name',
'type',
'logo',
'params',
'status',
'shipping_provider_id',
'expanded_content',
'supported_countries',
'supported_provinces',
'display_on_frontend',
'order'
];
protected $casts = [
'params' => 'json',
'supported_countries' => 'json',
'supported_provinces' => 'json',
];
public function getTypeNameAttribute()
{
return ShippingOptionTypeEnum::findConstantLabel($this->type);
}
public function shippingProvider()
{
return $this->belongsTo(ShippingProvider::class);
}
public function isNoneAmount()
{
return $this->type == ShippingOptionTypeEnum::NONE_AMOUNT;
}
public function isThirdParty()
{
return $this->type == ShippingOptionTypeEnum::SHIPPING_PROVIDER;
}
public function isShippingZone()
{
return $this->type == ShippingOptionTypeEnum::SHIPPING_ZONE;
}
} |
import { db } from './config/firebase';
import { setDoc, doc, getDoc, updateDoc, Timestamp } from 'firebase/firestore';
import { UserInfo } from 'firebase/auth/cordova';
export interface FirestoreUserProfile {
uid: string;
displayName: string;
email: string;
phoneNumber: string | null;
photoURL: string;
providerId: string;
freeRequest: number;
walletBalance: number;
allIndexCalculation: number;
lastLogIn: Timestamp;
whenFreebies: Timestamp;
}
export interface UserProfile extends Omit<FirestoreUserProfile, 'lastLogIn' | 'whenFreebies'> {
lastLogIn: number;
whenFreebies: number;
}
interface ModifyUserProps {
freeRequest?: number;
walletBalance?: number;
allIndexCalculation?: number;
lastLogIn?: Timestamp;
whenFreebies?: Timestamp;
}
interface ModifyUserBalanceProps {
requestCount: number;
userProfile: UserProfile;
}
async function isUserExist(uid: string) {
const userRef = doc(db, 'users', uid);
const userSnap = await getDoc(userRef);
return userSnap.exists();
}
async function createUser(user: UserInfo) {
const userRef = doc(db, 'users', user.uid);
await setDoc(userRef, {
...user,
freeRequest: 20,
walletBalance: 0,
allIndexCalculation: 0,
lastLogIn: Timestamp.now(),
whenFreebies: Timestamp.now(),
});
}
async function getUserProfl(uid: string) {
const userRef = doc(db, 'users', uid);
const userProfl = await getDoc(userRef);
const data = userProfl.data();
if (!data) {
console.error('Can`t get userProfl');
return undefined;
}
return data as FirestoreUserProfile;
}
async function modifyUser(userID: string, modifyObj: ModifyUserProps) {
const userProflRef = doc(db, 'users', userID);
try {
await updateDoc(userProflRef, { ...modifyObj });
return true;
} catch (error) {
return false;
}
}
async function modifyUserBalance({
userProfile,
requestCount,
}: ModifyUserBalanceProps): Promise<boolean> {
const pricePerRequest = 0.012;
const paidRequest = requestCount - userProfile.freeRequest;
const indexCalculation = userProfile.allIndexCalculation + requestCount;
if (requestCount > 5000) {
alert(
'Sorry but Thematicity index has limit 5000 request per day. If you want do more request, please contact with us. We solve this problem!'
);
return false;
}
if (paidRequest <= 0) {
const newFreeRequest = userProfile.freeRequest - requestCount;
const modufyResult = await modifyUser(userProfile.uid, {
freeRequest: newFreeRequest,
allIndexCalculation: indexCalculation,
});
return modufyResult;
}
const costOfRequests = paidRequest * pricePerRequest;
if (userProfile.walletBalance - costOfRequests < 0) {
alert(
`You can do ${
Math.trunc(userProfile.walletBalance / pricePerRequest) + userProfile.freeRequest
} index calculations, but tool got ${requestCount} urls`
);
return false;
}
const newWalletBalance =
Math.trunc((userProfile.walletBalance - costOfRequests) * 10000000) / 10000000;
await modifyUser(userProfile.uid, {
freeRequest: 0,
walletBalance: newWalletBalance,
allIndexCalculation: indexCalculation,
});
return true;
}
export const serializeUserProfile = (userProfile: FirestoreUserProfile): UserProfile => {
const logInTimestamp = userProfile.lastLogIn.toMillis();
const freebiesTimestamp = userProfile.whenFreebies.toMillis();
const serializedUserProfile = {
...userProfile,
lastLogIn: logInTimestamp,
whenFreebies: freebiesTimestamp,
};
return serializedUserProfile;
};
const fireStore = {
isUserExist,
createUser,
getUserProfl,
modifyUser,
modifyUserBalance,
};
export default fireStore; |
# python imports
from argparse import Namespace
from struct import pack
from typing import Iterator
from ebp.common.algorithm.mersenne_twister import MtSequenceEncoders
### Encoders to take the MT sequence and present the value in a defined manner.
class MtSequenceCliEncoders(dict):
## Creates a new instanec of this class.
# @param self the instance of the object that is invoking this method.
# @returns the new instance of this object type.
def __init__(self) -> dict:
super().__init__()
self['one-per-line-dec'] = self.one_per_line_dec
self['one-per-line-hex'] = self.one_per_line_hex
self['c-char-array-le'] = self.c_char_array_le
self['c-char-array-be'] = self.c_char_array_be
self['c-uint-array'] = self.c_uint_array
## Prints the given sequence, one value at a time as a decimal value.
# @param self the instance of the object that is invoking this method.
# @param arguments the arguments the arguments provided by the user on the CLI.
# @param generator the generator that will yield the sequence values.
def one_per_line_dec(self, arguments:Namespace, generator:Iterator[int]) -> None:
print( MtSequenceEncoders.one_per_line_dec(generator) )
## Prints the given sequence, one value at a time as a hexadecimal value.
# @param self the instance of the object that is invoking this method.
# @param arguments the arguments the arguments provided by the user on the CLI.
# @param generator the generator that will yield the sequence values.
def one_per_line_hex(self, arguments:Namespace, generator:Iterator[int]) -> None:
print( MtSequenceEncoders.one_per_line_hex(generator) )
## Prints the given sequence as a C `unsigned int` array.
# @param self the instance of the object that is invoking this method.
# @param arguments the arguments the arguments provided by the user on the CLI.
# @param generator the generator that will yield the sequence values.
def c_uint_array(self, arguments:Namespace, generator:Iterator[int]) -> None:
print(f"/// mersenne-twister sequence for seed {arguments.seed}")
if(arguments.skip): print(f"// @note: {arguments.skip} initial values skipped/discarded.")
print(MtSequenceEncoders.c_uint_array( f"mt_seed_{arguments.seed:08x}_values", generator ))
## Prints the given sequence as a C `unsigned char` array with each MT uint32 being interpretted as a little endian value.
# @param self the instance of the object that is invoking this method.
# @param arguments the arguments the arguments provided by the user on the CLI.
# @param generator the generator that will yield the sequence values.
def c_char_array_le(self, arguments:Namespace, generator:Iterator[int]) -> None:
print(f"/// mersenne-twister sequence for seed {arguments.seed} (uint32, little-endian encoded)")
if(arguments.skip): print(f"// @note: {arguments.skip} initial values skipped/discarded.")
print(MtSequenceEncoders.c_char_array_le( f"mt_seed_{arguments.seed:08x}_values", generator ))
## Prints the given sequence as a C `unsigned char` array with each MT uint32 being interpretted as a big endian value.
# @param self the instance of the object that is invoking this method.
# @param arguments the arguments the arguments provided by the user on the CLI.
# @param generator the generator that will yield the sequence values.
def c_char_array_be(self, arguments:Namespace, generator:Iterator[int]) -> None:
print(f"/// mersenne-twister sequence for seed {arguments.seed} (uint32, big-endian encoded)")
if(arguments.skip): print(f"// @note: {arguments.skip} initial values skipped/discarded.")
print(MtSequenceEncoders.c_char_array_be( f"mt_seed_{arguments.seed:08x}_values", generator )) |
#include <stdio.h>
#include <string.h>
#include "encode.h"
#include "types.h"
#include "common.h"
/* Function Definitions */
//step 1.1 step validation check (used for both encoding and decoding)
Status validation_check(int argc)
{
if( argc > 2 && argc <= 5 )
{
printf("validation successfull\n");
return e_success;
}
else if(argc > 5)
{
printf("Too many argument\n");
return e_failure;
}
else
{
return e_failure;
}
}
//step 2.1 check operation type (used for both encoding and decoding )
OperationType check_operation_type(char *argv[])
{
if(strcmp(argv[1],"-e") == 0 )
{
return e_encode;
}
else if(strcmp(argv[1],"-d") == 0 )
{
return e_decode;
}
else
{
return e_unsupported;
}
}
//step 3.1 read and validation for encoding
Status read_and_validate_encode_args(char *argv[], EncodeInfo *encInfo)
{
if(strstr(argv[2],".")!=NULL)
{
if(strcmp(strstr(argv[2],"."),".txt") == 0)
{
encInfo->secret_fname=argv[2];
}
else
{
return e_failure;
}
}
else
{
return e_failure;
}
if(strstr(argv[3],".") != NULL)
{
if(strcmp(strstr(argv[3],"."),".bmp") == 0)
{
encInfo->src_image_fname=argv[3];
}
else
{
return e_failure;
}
}
else
{
return e_failure;
}
if(argv[4] != NULL)
{
if(strstr(argv[4],".") != NULL)
{
if(strcmp(strstr(argv[4],"."),".bmp") == 0)
{
encInfo->stego_image_fname=argv[4];
}
else
{
return e_failure;
}
}
else
{
return e_failure;
}
}
else
encInfo->stego_image_fname="stego.bmp";
return e_success;
}
/* Get image size
* Input: Image file ptr
* Output: width * height * bytes per pixel (3 in our case)
* Description: In BMP Image, width is stored in offset 18,
* and height after that. size is 4 bytes
*/
// step 6.3 finding size of src bmp
uint get_image_size_for_bmp(FILE *fptr_image)
{
uint width, height;
// Seek to 18th byte
fseek(fptr_image, 18, SEEK_SET);
// Read the width (an int)
fread(&width, sizeof(int), 1, fptr_image);
printf("width = %u\n", width);
// Read the height (an int)
fread(&height, sizeof(int), 1, fptr_image);
printf("height = %u\n", height);
// Return image capacity
return width * height * 3;
}
/*
* Get File pointers for i/p and o/p files
* Inputs: Src Image file, Secret file and
* Stego Image file
* Output: FILE pointer for above files
* Return Value: e_success or e_failure, on file errors
*/
//step 5.1 open files
Status open_files(EncodeInfo *encInfo)
{
// Src Image file
encInfo->fptr_src_image = fopen(encInfo->src_image_fname, "r");
// Do Error handling
if (encInfo->fptr_src_image == NULL)
{
perror("fopen");
fprintf(stderr, "ERROR: Unable to open file %s\n", encInfo->src_image_fname);
return e_failure;
}
// Secret file
encInfo->fptr_secret = fopen(encInfo->secret_fname, "r");
// Do Error handling
if (encInfo->fptr_secret == NULL)
{
perror("fopen");
fprintf(stderr, "ERROR: Unable to open file %s\n", encInfo->secret_fname);
return e_failure;
}
// Stego Image file
encInfo->fptr_stego_image = fopen(encInfo->stego_image_fname, "w");
// Do Error handling
if (encInfo->fptr_stego_image == NULL)
{
perror("fopen");
fprintf(stderr, "ERROR: Unable to open file %s\n", encInfo->stego_image_fname);
return e_failure;
}
// No failure return e_success
return e_success;
}
//step 6.1 checking capacity
Status check_capacity(EncodeInfo *encInfo)
{
//step 6.2 get the beautiful.bmp file size
encInfo->image_capacity=get_image_size_for_bmp(encInfo->fptr_src_image);
//get the secret.txt file size
encInfo->size_secret_file = get_file_size(encInfo->fptr_secret);
//check image capacity is capable of storing secret file
if(encInfo->image_capacity > ( 54 + (2+4+4+encInfo->size_secret_file) * 8 ) )
{
return e_success;
}
else
{
return e_failure;
}
}
uint get_file_size(FILE *fptr)
{
fseek(fptr,0,SEEK_END);
return ftell(fptr);
}
//step 7.1 copying bmp header
Status copy_bmp_header(FILE *fptr_src_image, FILE *fptr_dest_image)
{
char str[54];
fseek(fptr_src_image,0,SEEK_SET);
fread(str,54,1,fptr_src_image);
fwrite(str,54,1,fptr_dest_image);
return e_success;
}
//step 8.1 encoding magic string
Status encode_magic_string(const char *magic_string, EncodeInfo *encInfo)
{
//step 8.2 encoding data to stego image
encode_data_to_image(magic_string,strlen(magic_string),encInfo->fptr_src_image,encInfo->fptr_stego_image,encInfo);
return e_success;
}
// encoding data to stego image(common function)
Status encode_data_to_image(const char *data, int size, FILE *fptr_src_image, FILE *fptr_stego_image,EncodeInfo *encInfo)
{
for(int i=0 ; i < size ; i++)
{
fread(encInfo->image_data,8,1,fptr_src_image);
//encoding 1 byte data into lsb of 8 bytes of stego imgae
encode_byte_to_lsb(data[i],encInfo->image_data);
fwrite(encInfo->image_data,8,1,fptr_stego_image);
}
}
//encoding 1 byte of data into lsb of 8 bytes of stego image(common function)
Status encode_byte_to_lsb(char data, char *image_buffer)
{
int i;
unsigned int mask=1<<7;
for( i = 0 ; i < 8 ; i++ )
{
image_buffer[i]=( image_buffer[i] & 0xfe ) | ( (data & mask) >> (7-i) );
mask = mask >> 1;
}
}
//step 9.2 encoding size to stego image
Status encode_size(int size,FILE *fptr_src_image,FILE *fptr_stego_image)
{
char str[32];
fread(str,32,1,fptr_src_image);
//step 9.3 encoding size in lsb of stego image
encode_size_to_lsb(str,size);
fwrite(str,32,1,fptr_stego_image);
return e_success;
}
//encoding size in lsb of stego image(common function)
Status encode_size_to_lsb(char *buffer,int size)
{
int i;
unsigned int mask=1<<31;
for( i = 0 ; i < 32 ; i++ )
{
buffer[i]=( buffer[i] & 0xfe ) | ( ( size & mask) >> (31-i) );
mask = mask >> 1;
}
return e_success;
}
//step 10.1 encoding scret file extension
Status encode_secret_file_extn(const char *file_extn, EncodeInfo *encInfo)
{
//step 10.2 encode data to image
encode_data_to_image(file_extn,strlen(file_extn),encInfo->fptr_src_image,encInfo->fptr_stego_image,encInfo);
return e_success;
}
//step 11.1 encoding secret file size
Status encode_secret_file_size(unsigned int file_size, EncodeInfo *encInfo)
{
char str[32];
fread(str,32,1,encInfo->fptr_src_image);
//step 11.2 encoding size to lsb
encode_size_to_lsb(str,file_size);
fwrite(str,32,1,encInfo->fptr_stego_image);
return e_success;
}
//step 12.1 encoding secret file data
Status encode_secret_file_data(EncodeInfo *encInfo)
{
fseek(encInfo->fptr_secret,0,SEEK_SET);
char str[encInfo->size_secret_file];
fread(str,encInfo->size_secret_file,1,encInfo->fptr_secret);
//step 12.2 encoding data into stego image
encode_data_to_image(str,encInfo->size_secret_file,encInfo->fptr_src_image,encInfo->fptr_stego_image,encInfo);
return e_success;
}
//step 13.1 copying remaining data to stego image
Status copy_remaining_img_data(FILE *fptr_src, FILE *fptr_dest)
{
char ch;
while(fread(&ch,1,1,fptr_src) > 0 )
{
fwrite(&ch,1,1,fptr_dest);
}
return e_success;
}
//step 4.1 encoding started
Status do_encoding(EncodeInfo *encInfo)
{
printf("Started Encoding\n");
//step 5.0 Open the file
if(open_files(encInfo) == e_success)
{
printf("Open file is successfull\n");
//step 6.0 check capacity
if(check_capacity(encInfo) == e_success)
{
printf("check capacity is a successfull\n");
//step 7.0 copy header file
if(copy_bmp_header(encInfo->fptr_src_image,encInfo->fptr_stego_image) == e_success)
{
printf("Copied bmp header successfully\n");
//step 8.0 encode magic string
if(encode_magic_string(MAGIC_STRING,encInfo) == e_success)
{
printf("Magic string encoded successfully\n");
//step 9.0 Encode the file extension size
if(encode_size(strlen( strstr(encInfo->secret_fname,".")),encInfo->fptr_src_image,encInfo->fptr_stego_image) == e_success)
{
printf("Encoded secret file extension size\n");
//step 10.0 Encode the secret file extension
if( encode_secret_file_extn(strstr(encInfo->secret_fname,"."),encInfo) == e_success)
{
printf("Encode secret file extension successfully\n");
//step 11.0 encode the secret file size
if(encode_secret_file_size(encInfo->size_secret_file,encInfo) == e_success)
{
printf("Encoded secret file size successfully\n");
//step 12.0 Encode secret file data
if( encode_secret_file_data(encInfo)== e_success )
{
printf("Encoded secret file data successfully\n");
//step 13.0 copy remaining data
if(copy_remaining_img_data(encInfo->fptr_src_image,encInfo->fptr_stego_image) == e_success)
{
printf("Copied remaining bytes successfully\n");
}
else
{
printf("Copying failed\n");
return e_failure;
}
}
else
{
printf("Couldn't encode the file data\n");
return e_failure;
}
}
else
{
printf("Falied to encode the file size\n");
return e_failure;
}
}
else
{
printf("Falied to encode the file extension\n");
return e_failure;
}
}
else
{
printf("Failed to encode the file extension size\n");
return e_failure;
}
}
else
{
printf("Couldn't encode Magic string\n");
return e_failure;
}
}
else
{
printf("Couldn't copy the header\n");
return e_failure;
}
}
else
{
printf("Check capcity falied\n");
return e_failure;
}
}
else
{
printf("Open file falied\n");
return e_failure;
}
return e_success;
} |
<!-- Improved compatibility of back to top link: See: https://github.com/jamesfrienkins3452/FEP-13-website-project/pull/73 -->
<a name="readme-top"></a>
<!--
*** Thanks for checking out the Best-README-Template. If you have a suggestion
*** that would make this better, please fork the repo and create a pull request
*** or simply open an issue with the tag "enhancement".
*** Don't forget to give the project a star!
*** Thanks again! Now go create something AMAZING! :D
-->
<!-- PROJECT SHIELDS -->
<!--
*** I'm using markdown "reference style" links for readability.
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
*** See the bottom of this document for the declaration of the reference variables
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
-->
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![MIT License][license-shield]][license-url]
<!-- PROJECT LOGO -->
<br />
<div align="center">
<a href="https://github.com/jamesfrienkins3452/FEP-13-website-project">
<img src="images/logo.jpg" alt="Logo" width="80" height="80">
</a>
<h3 align="center">FEP-13 - Lviv places to visit</h3>
<p align="center">
FEP-13 website project
<br />
<a href="https://github.com/jamesfrienkins3452/FEP-13-website-project"><strong>Explore the docs »</strong></a>
<br />
<br />
<a href="https://github.com/jamesfrienkins3452/FEP-13-website-project">View Demo</a>
·
<a href="https://github.com/jamesfrienkins3452/FEP-13-website-project/issues">Report Bug</a>
·
<a href="https://github.com/jamesfrienkins3452/FEP-13-website-project/issues">Request Feature</a>
</p>
</div>
<!-- TABLE OF CONTENTS -->
<details>
<summary>Table of Contents</summary>
<ol>
<li>
<a href="#about-the-project">About The Project</a>
<ul>
<li><a href="#built-with">Built With</a></li>
</ul>
</li>
<li><a href="#roadmap">Roadmap</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#license">License</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#acknowledgments">Acknowledgments</a></li>
</ol>
</details>
<!-- ABOUT THE PROJECT -->
## About The Project
This project is build as web server deployment practice task
<p align="right">(<a href="#readme-top">back to top</a>)</p>
### Built With
- AWS EC2 and VPC
- Jenkins (with Github Webhooks)
- Nginx
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- ROADMAP -->
## Roadmap
- [x] CI/CD using Jenkins and AWS EC2
- [x] Production branch on port 80 and development on port 90
See the [open issues](https://github.com/jamesfrienkins3452/FEP-13-website-project/issues) for a full list of proposed features (and known issues).
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- CONTRIBUTING -->
## Contributing
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
Don't forget to give the project a star! Thanks again!
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- LICENSE -->
## License
Distributed under the MIT License. See `LICENSE.txt` for more information.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- CONTACTS -->
## Contacts
Volodymyr Safiyanyk - [email protected]
Project Link: [https://github.com/jamesfrienkins3452/FEP-13-website-project](https://github.com/jamesfrienkins3452/FEP-13-website-project)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- ACKNOWLEDGMENTS -->
## Acknowledgments
AWS examples - [https://github.com/open-guides/og-aws](https://github.com/open-guides/og-aws)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[contributors-shield]: https://img.shields.io/github/contributors/jamesfrienkins3452/FEP-13-website-project.svg?style=for-the-badge
[contributors-url]: https://github.com/jamesfrienkins3452/FEP-13-website-project/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/jamesfrienkins3452/FEP-13-website-project.svg?style=for-the-badge
[forks-url]: https://github.com/jamesfrienkins3452/FEP-13-website-project/network/members
[stars-shield]: https://img.shields.io/github/stars/jamesfrienkins3452/FEP-13-website-project.svg?style=for-the-badge
[stars-url]: https://github.com/jamesfrienkins3452/FEP-13-website-project/stargazers
[issues-shield]: https://img.shields.io/github/issues/jamesfrienkins3452/FEP-13-website-project.svg?style=for-the-badge
[issues-url]: https://github.com/jamesfrienkins3452/FEP-13-website-project/issues
[license-shield]: https://img.shields.io/github/license/jamesfrienkins3452/FEP-13-website-project.svg?style=for-the-badge
[license-url]: https://github.com/jamesfrienkins3452/FEP-13-website-project/blob/production/LICENSE.txt
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555
[product-screenshot]: images/screenshot.png |
<template>
<view class="content">
<view class="opreate">
<view>在下面的画布中随意创作吧</view>
<view class="btnGroup">
<button type="default" style="margin-right: 20rpx;" @tap="clearEvent">
<image src="../../static/icon/del.png"></image>
</button>
<button type="default">
<image src="../../static/icon/reset.png"></image>
</button>
</view>
</view>
<canvas canvas-id="canvas" class="canvas"
@touchstart="touchstartEvent" @touchmove="touchmoveEvent" @touchend="touchendEvent"></canvas>
<div class="search">
<input placeholder="描述一下你想要创作的图片" :value="desc" type="text"/>
<view class="tag">5</view>
<button type="default" @click="toPage">生成</button>
</div>
</view>
</template>
<script>
export default {
data() {
return {
pain: false,
lastPoint:{
x:0,
y:0
},
desc:"我是一只小猫咪",
ctx:null,
canvasWH:{}
}
},
onLoad() {
},
onReady() {
this.ctx = uni.createCanvasContext('canvas', this);
// 获取canvas画布的宽高
uni.createSelectorQuery().select('.canvas').boundingClientRect().exec(res => {
const { width, height } = res[0]
this.canvasWH = {width, height}
})
console.log(document.getElementsByClassName('.canvas'))
},
methods: {
touchstartEvent(e) {
this.pain = true;
const {x , y} = e.touches[0];
this.lastPoint = {x, y}
},
touchmoveEvent(e) {
if(this.pain) {
const {x, y} = e.touches[0];
const newPoint = {x, y};
this.drawLine(this.lastPoint.x, this.lastPoint.y, newPoint.x, newPoint.y);
this.lastPoint = newPoint;
}
},
touchendEvent() {
this.pain = false;
},
drawLine(x1, y1, x2, y2) {
this.ctx.beginPath()
this.ctx.setLineWidth(10);
this.ctx.setLineCap('round')
this.ctx.setLineJoin('round')
this.ctx.moveTo(x1, y1)
this.ctx.lineTo(x2, y2);
this.ctx.setStrokeStyle('red')
this.ctx.closePath();
this.ctx.stroke();
this.ctx.draw(true);
},
clearEvent() {
uni.showModal({
title:'提示',
content:'确定要清空画布当中的内容吗?',
confirmText:'确定',
success:(res) => {
if(res.confirm) {
this.ctx.draw();
}
},
})
},
toPage() {
const {width, height} = this.canvasWH;
uni.canvasToTempFilePath({
canvasId:"canvas",
x:0,
y:0,
width,
height,
success:({tempFilePath}) => {
if(tempFilePath) {
uni.navigateTo({
url:`/pages/index/imageCreate?tempFilePath=${tempFilePath}&desc=${this.desc}`
})
}
}
})
},
}
}
</script>
<style lang="scss" scoped>
page{
overflow: hidden;
}
.opreate{
display: flex;
align-items: center;
justify-content: space-between;
padding: 40rpx 20px;
font-size: 32rpx;
color: #939393;
.btnGroup{
display: flex;
align-items: center;
button{
width: 106rpx;
height: 68rpx;
background-color: #22A3FF;
border-radius: 34rpx;
display: flex;
align-items: center;
image{
width: 42rpx;
height: 42rpx;
}
}
}
}
.canvas{
background-color: #fff;
border: 1px solid #22A3FF;
width: 730rpx;
height: 730rpx;
margin: 0 auto;
}
.search{
width:710rpx;
height: 96rpx;
margin: 0 auto;
font-size: 32rpx;
display: flex;
align-items: center;
margin-top: 65rpx;
position: relative;
input{
width: 570rpx;
height: 92rpx;
border: 1px solid #eee;
border-right: 0;
padding-left: 38rpx;
border-radius: 48rpx 0 0 48rpx;
&::placeholder{
color: #A7A7A7;
}
}
button{
width: 140rpx;
height: 100%;
background-color: #22A3FF;
color: #fff;
border-radius: 0 48rpx 48rpx 0;
display: flex;
align-items: center;
font-size: 32rpx;
}
.tag{
width: 60rpx;
height: 35rpx;
line-height: 35rpx;
background-color: #FF8122;
color: #fff;
border-radius: 35rpx;
font-size: 28rpx;
text-align: center;
position: absolute;
top: -46rpx;
right: 50rpx;
}
}
</style> |
const { DataTypes } = require("sequelize");
module.exports = (sequelize) => {
sequelize.define(
"Country",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
imgFlag: {
type: DataTypes.STRING,
allowNull: false,
},
continent: {
type: DataTypes.STRING,
allowNull: false,
},
capital: {
type: DataTypes.STRING,
allowNull: false,
},
subregion: {
type: DataTypes.STRING,
allowNull: false,
},
area: {
type: DataTypes.FLOAT,
allowNull: false,
},
population: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{
timestamps: true,
updatedAt: false, // Para desactivar la actualización automática del campo updatedAt
}
);
}; |
package nuber.students;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.Date;
public class Booking {
private static final AtomicInteger nextId = new AtomicInteger(1); // For unique, sequential job IDs
private final int jobId;
private final NuberDispatch dispatch;
private final Passenger passenger;
private Driver driver;
private final Date createTime;
public Booking(NuberDispatch dispatch, Passenger passenger) {
this.jobId = nextId.getAndIncrement();
this.dispatch = dispatch;
this.passenger = passenger;
this.createTime = new Date();
}
public BookingResult call() throws InterruptedException {
driver = dispatch.getDriver(); // This method should be implemented in NuberDispatch
while(driver == null) {
// Wait and retry to get an available driver
Thread.sleep(100);
driver = dispatch.getDriver();
}
driver.pickUpPassenger(passenger);
driver.driveToDestination();
Date endTime = new Date();
long tripDuration = endTime.getTime() - createTime.getTime();
dispatch.addDriver(driver); // This method should be implemented in NuberDispatch
return new BookingResult(jobId, passenger, driver, tripDuration);
}
@Override
public String toString() {
String driverName = (driver == null) ? "null" : driver.name;
String passengerName = (passenger == null) ? "null" : passenger.name;
return jobId + ":" + driverName + ":" + passengerName;
}
} |
import { Request } from "express";
import { uuid } from "uuidv4";
import Slug from "../utils/Slug";
//model
import User from "../models/user";
interface paginateObject {
next: {},
previous: {},
data: []
}
class UserRepository {
body: Request['body'];
params: Request['params'];
query: Request['query'];
constructor(req: Request) {
this.body = req.body;
this.params = req.params;
this.query = req.query;
}
all = async () => {
const { page, limit }: any = this.query;
const startIndex = (parseInt(page) - 1) * parseInt(limit);
const endIndex = parseInt(page) * parseInt(limit);
// let resultPaginate: paginateObject;
var resultPaginate = <paginateObject>{};
const countData = await User.query().count().first();
if (endIndex < countData.count) {
resultPaginate.next = {
page: parseInt(page) + 1,
limit: parseInt(limit)
}
}
if (startIndex > 0) {
resultPaginate.previous = {
page: parseInt(page) - 1,
limit: parseInt(limit)
}
}
resultPaginate.data = await User.query().page(startIndex, limit);
return resultPaginate;
}
insert = async () => {
const { name, description } = this.body
const data = await User.query().insert({
id: uuid(),
name,
description,
slug: Slug.generate(name)
});
return data;
}
update = async () => {
const { name, description } = this.body;
const { id } = this.params;
const data = await User.query()
.patchAndFetchById(id, {
name, description, slug: Slug.generate(name)
})
return data;
}
findByUsername = async () => {
const { username } = this.body;
const data = await User.query()
.where('username', '=', username)
.first()
return data;
}
}
export default UserRepository; |
package ian.Behavioral.Iterator.level2;
import java.util.*;
class DFSIterator implements Iterator {// 深度優先搜索
private Set<User> visited = new HashSet<>();
private Stack<User> check = new Stack<>();
public DFSIterator(User startUser) {
check.push(startUser);
}
@Override
public boolean hasNext() {
while (!check.isEmpty() && visited.contains(check.peek())) {
// 重複對象就用pop拿掉
check.pop();
}
return !check.isEmpty();
}
@Override
public User next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
User current = check.pop();
visited.add(current);
// 檢查朋友的名單,是否有自己沒有追蹤的
current.getFriends().forEach(friend -> {
if (!visited.contains(friend)) {
check.push(friend);
}
});
return current;
}
} |
package com.cq.seckill.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@Data
@NoArgsConstructor
/**
* 公用返回响应对象
*/
public class RespBean {
private long code;
private String message;
private Object obj;
/**
* 成功返回结果
* @return
*/
public static RespBean success(){
return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(),null);
}
public static RespBean success(Object obj){
return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(),obj);
}
/**
* 失败返回结果
* @param respBeanEnum
* @return
*/
public static RespBean error(RespBeanEnum respBeanEnum){
return new RespBean(respBeanEnum.getCode(), respBeanEnum.getMessage(),null);
}
public static RespBean error(RespBeanEnum respBeanEnum, Object obj){
return new RespBean(respBeanEnum.getCode(), respBeanEnum.getMessage(),obj);
}
} |
import { Body, Controller, Get, Param, ParseUUIDPipe, Patch, Query } from '@nestjs/common';
import { ApiTags, ApiQuery, ApiOperation, ApiOkResponse, ApiParam, ApiBody } from '@nestjs/swagger';
import joi2swagger from 'src/common/utils/joi2swagger';
import { UserId } from 'src/common/decorators/user.decorator';
import { NotificationService } from './notification.service';
import { NotificationsListDto } from './dto/notifications_list.dto';
import { ListItemsDto } from 'src/common/dto/list_items.dto';
import { NotificationDto } from './dto/notification.dto';
@ApiTags('Notification')
@Controller('notification')
export class NotificationController {
constructor(private notificationService: NotificationService) {}
@Get()
@ApiOperation({ summary: 'Get list notifications' })
@ApiQuery({ name: 'fromId', schema: { type: 'string', format: 'uuid' }, required: false })
@ApiQuery({ name: 'page', schema: { type: 'number' }, required: false })
@ApiQuery({ name: 'status', schema: { enum: ['read', 'unread'] }, required: false })
@ApiOkResponse(joi2swagger(ListItemsDto, 'LIST', NotificationDto))
async listNotifications(
@UserId() userId: string,
@Query('fromId') fromId: string | undefined,
@Query('page') page: number | undefined,
@Query('status') status: 'read' | 'unread'
): Promise<ListItemsDto<NotificationDto>> {
return await this.notificationService.listNotifications(userId, fromId, page, status);
}
@Patch('mark-read/:id')
@ApiOperation({ summary: 'Mark read notification by id' })
@ApiParam({ name: 'id', schema: { type: 'string', format: 'uuid' } })
@ApiOkResponse({ status: 200 })
async markRead(@UserId() userId: string, @Param('id', ParseUUIDPipe) id: string): Promise<void> {
await this.notificationService.markRead(userId, id);
}
@Patch('mark-read-list')
@ApiOperation({ summary: 'Mark read notifications' })
@ApiBody(joi2swagger(NotificationsListDto))
@ApiOkResponse({ status: 200 })
async markReadList(@UserId() userId: string, @Body() notificationsListDto: NotificationsListDto): Promise<void> {
await this.notificationService.markReadList(userId, notificationsListDto.notifications);
}
@Patch('mark-read-all')
@ApiOperation({ summary: 'Mark read notifications' })
@ApiOkResponse({ status: 200 })
async markReadAll(@UserId() userId: string): Promise<void> {
await this.notificationService.markReadAll(userId);
}
} |
import React, { useEffect, useState } from 'react';
import { ScrollView, View } from 'react-native';
import { Input, useTheme } from 'react-native-elements';
import { SwitchInput } from '../../../components/SwitchInput';
import { ENUM_AUTOMATION_TYPE } from '../../../enums';
import { ScheduleInput } from './ScheduleInput';
import { GeneralAreaStyles as styles } from './styles';
/**
* props:
* - automation
* - type
* - onChange
*/
function GeneralArea({ ...props }) {
const { theme } = useTheme();
const [automation, setAutomation] = useState({});
useEffect(() => {
setAutomation(props.automation);
}, [props.automation]);
function onChange(newProp) {
const newData = { ...automation, [newProp.name]: newProp.value };
setAutomation(newData);
props.onChange(newProp);
}
return (
<View style={{ ...theme.container }}>
<View style={{ ...theme.inputContainer }}>
<ScrollView>
<Input
label="Name"
placeholder="Automation name"
keyboardType="default"
autoCapitalize="words"
value={automation.name}
onChangeText={(event) => onChange({ name: 'name', value: event })}
/>
{props.type === ENUM_AUTOMATION_TYPE.SCHEDULE ||
automation.schedule ? (
<ScheduleInput
schedule={automation.schedule}
onChange={(event) => onChange({ name: 'schedule', value: event })}
/>
) : (
<></>
)}
<View style={styles.row}>
<SwitchInput
text="Is Active?"
onChange={(event) => onChange({ name: 'isActive', value: event })}
isChecked={automation.isActive}
/>
<SwitchInput
text="Enable logs?"
onChange={(event) => onChange({ name: 'logs', value: event })}
isChecked={automation.logs}
/>
</View>
</ScrollView>
</View>
</View>
);
}
export { GeneralArea }; |
/**
* @name CommandLineParser/tests/TestVerifyData.cpp
* @copyright (c) 2022 Sam Caldwell. All Rights Reserved.
* @author Sam Caldwell <[email protected]>
*/
#include "projects/application/CommandLineParser/src/CommandLineParser.h"
class TestBasic : public TestBase {
private:
ConfigStateMap *map;
Configuration *cfg;
CommandLineParser *parser;
public:
/**
* @name class constructor
* @brief initialize the test
*
* @param n string
*/
TestBasic(string n) {
debug(n + "::TestParse()");
name = n;
map = new ConfigStateMap;
cfg = new Configuration;
map->add("--help", "option.help", Bool, false, true);
map->add("-h", "option.help", Bool, false, true);
map->add("--option1", "option.a", String, false, false);
map->add("--option2", "option.b", String, false, false);
map->add("--option3", "option.c", Int, false, false);
}
/**
* @name class destructor
* @brief clean up the test
*/
~TestBasic() {
debug(name + "::~TestParse()");
if (parser) delete parser;
if (map) delete map;
if (cfg) delete cfg;
}
/**
* @name test_instantiation
* @brief can we instantiate the commandline parser object?
*
* @return bool
*/
bool test_instantiation() {
int argc = 3;
char *argv[9] = {
(char *) "TestParse",
(char *) "--help",
(char *) "--option1", (char *) "OptionValue1",
(char *) "--option2", (char *) "OptionValue2",
(char *) "--option3", (char *) "1337",
};
parser = new CommandLineParser(cfg, map, argc, argv);
return expect(parser, "expect parser not null");
}
/**
* @name main
* @brief coordinate tests.
*
* @return bool
*/
bool main() {
return expect(test_instantiation(), "test_instantiation()");
}
}; |
import {
Body,
Controller,
Post,
HttpStatus,
HttpException,
UseGuards,
Put,
Param,
Get,
Query,
Delete,
} from "@nestjs/common";
import { z } from "zod";
import { ZodValidationsPipe } from "../../../pipes/zod-validations-pipe";
import { CreateBrandUseCase } from "@/domain/catalog/application/use-cases/create-brand";
import { JwtAuthGuard } from "@/auth/jwt-auth.guard";
import { RolesGuard } from "@/auth/roles.guard";
import { Roles } from "@/auth/roles.decorator";
import { ResourceNotFoundError } from "@/domain/catalog/application/use-cases/errors/resource-not-found-error";
import { EditBrandUseCase } from "@/domain/catalog/application/use-cases/edit-brand";
import { FindBrandByNameUseCase } from "@/domain/catalog/application/use-cases/find-brand-by-name";
import { GetAllBrandsUseCase } from "@/domain/catalog/application/use-cases/get-all-brands";
import { left } from "@/core/either";
import { FindBrandByIdUseCase } from "@/domain/catalog/application/use-cases/find-brand-by-id";
import { DeleteBrandUseCase } from "@/domain/catalog/application/use-cases/delete-brand";
const createBrandSchema = z.object({
name: z
.string()
.min(1, "Name must not be empty")
.max(50, "Name must not exceed 50 characters"),
imageUrl: z
.string()
.nonempty("Image URL must not be empty"),
erpId: z.string().optional()
});
const bodyValidationPipe = new ZodValidationsPipe(createBrandSchema);
type CreateBrandBodySchema = z.infer<typeof createBrandSchema>;
const editBrandSchema = z.object({
name: z
.string()
.min(1, "Name must not be empty")
.max(50, "Name must not exceed 50 characters"),
imageUrl: z
.string()
.nonempty("Image URL must not be empty"),
});
const editBodyValidationPipe = new ZodValidationsPipe(editBrandSchema);
type EditBrandBodySchema = z.infer<typeof editBrandSchema>;
const paginationParamsSchema = z.object({
page: z.preprocess((val) => Number(val), z.number().min(1).default(1)),
pageSize: z.preprocess(
(val) => Number(val),
z.number().min(1).max(100).default(10)
),
});
const paginationPipe = new ZodValidationsPipe(paginationParamsSchema);
type PaginationParams = z.infer<typeof paginationParamsSchema>;
@Controller("brands")
export class BrandController {
constructor(
private readonly createBrandUseCase: CreateBrandUseCase,
private readonly editBrandUseCase: EditBrandUseCase,
private readonly findBrandByNameUseCase: FindBrandByNameUseCase,
private readonly getAllBrandsUseCase: GetAllBrandsUseCase,
private readonly findBrandByIdUseCase: FindBrandByIdUseCase,
private readonly deleteBrandUseCase: DeleteBrandUseCase
) {}
@Post()
async createBrand(@Body(bodyValidationPipe) body: CreateBrandBodySchema) {
try {
const result = await this.createBrandUseCase.execute({
name: body.name,
imageUrl: body.imageUrl,
erpId: body.erpId || 'undefined'
});
if (result.isLeft()) {
const error = result.value;
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
}
} else {
return { brand: result.value.brand };
}
} catch (error) {
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
}
throw new HttpException(
"Failed to create brand",
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
@Put(":brandId")
async editBrand(
@Param("brandId") brandId: string,
@Body(editBodyValidationPipe) body: EditBrandBodySchema
) {
try {
const result = await this.editBrandUseCase.execute({
brandId,
name: body.name,
imageUrl: body.imageUrl,
});
if (result.isLeft()) {
const error = result.value;
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
}
} else {
return { brand: result.value.brand };
}
} catch (error) {
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
}
throw new HttpException(
"Failed to update brand",
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
@Get()
async findBrandByName(@Query("name") name: string) {
try {
const result = await this.findBrandByNameUseCase.execute({ name });
if (result.isLeft()) {
const error = result.value;
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.NOT_FOUND);
}
} else {
return { brand: result.value.brand };
}
} catch (error) {
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.NOT_FOUND);
}
throw new HttpException(
"Failed to find brand",
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
@Get("all")
async getAllBrands(@Query(paginationPipe) params: PaginationParams) {
try {
const result = await this.getAllBrandsUseCase.execute(params);
if (result.isLeft()) {
throw new HttpException(
"Failed to find brands",
HttpStatus.INTERNAL_SERVER_ERROR
);
} else {
return { brands: result.value };
}
} catch (error) {
return left(new Error("Repository error"));
}
}
@Get(":id")
async findBrandById(@Param("id") id: string) {
try {
const result = await this.findBrandByIdUseCase.execute({ id });
if (result.isLeft()) {
const error = result.value;
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.NOT_FOUND);
}
} else {
return { brand: result.value.brand };
}
} catch (error) {
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.NOT_FOUND);
}
throw new HttpException(
"Failed to find brand",
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
@Delete(":id")
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("admin")
async deleteBrand(@Param("id") id: string) {
try {
const result = await this.deleteBrandUseCase.execute({ brandId: id });
if (result.isLeft()) {
const error = result.value;
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.NOT_FOUND);
}
} else {
return { message: "Brand deleted successfully" };
}
} catch (error) {
if (error instanceof ResourceNotFoundError) {
throw new HttpException(error.message, HttpStatus.NOT_FOUND);
}
throw new HttpException(
"Failed to delete brand",
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
} |
# This program is the pipeline for testing expressiveness.
# It includes 4 stages:
# 1. pre-calculation;
# 2. dataset construction;
# 3. model construction;
# 4. evaluation
from data_utils.preprocess import drfwl2_transform, drfwl3_transform
import numpy as np
import torch
import torch_geometric
from pygmmpp.data import DataLoader
from loguru import logger
import time
from data_utils.batch import collate
from BREC.BRECDataset_v3 import BRECDataset
from tqdm import tqdm
import os
import argparse
from torch.nn import CosineEmbeddingLoss
from json import dumps
from BREC.core.config import cfg
NUM_RELABEL = 32
P_NORM = 2
OUTPUT_DIM = 16
EPSILON_MATRIX = 1e-7
EPSILON_CMP = 1e-6
SAMPLE_NUM = 400
EPOCH = 10
MARGIN = 0.0
LEARNING_RATE = 1e-4
THRESHOLD = 72.34
BATCH_SIZE = 32
WEIGHT_DECAY = 1e-5
LOSS_THRESHOLD = 0.1
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.gnn_count import DR2FWL2Kernel
from models.pool import GraphLevelPooling
class BRECModel2(nn.Module):
def __init__(self,
hidden_channels: int,
num_layers: int,
add_0: bool = True,
add_112: bool = True,
add_212: bool = True,
add_222: bool = True,
eps: float = 0.,
train_eps: bool = False,
norm_type: str = "batch_norm",
norm_between_layers: str = "batch_norm",
residual: str = "none",
drop_prob: float = 0.0,
output_dim: int = 16):
super().__init__()
self.hidden_channels = hidden_channels
self.num_layers = num_layers
self.add_0 = add_0
self.add_112 = add_112
self.add_212 = add_212
self.add_222 = add_222
self.initial_eps = eps
self.train_eps = train_eps
self.norm_type = norm_type
self.residual = residual
self.drop_prob = drop_prob
self.OUTPUT_DIM = output_dim
self.node_transform = nn.Linear(1, self.hidden_channels)
self.ker = DR2FWL2Kernel(self.hidden_channels,
self.num_layers,
self.initial_eps,
self.train_eps,
self.norm_type,
norm_between_layers,
self.residual,
self.drop_prob)
self.pool = GraphLevelPooling(hidden_channels)
self.post_mlp = nn.Sequential(nn.Linear(hidden_channels, hidden_channels // 2),
nn.ELU(),
nn.Linear(hidden_channels // 2, self.OUTPUT_DIM))
self.ker.add_aggr(1, 1, 1)
if self.add_0:
self.ker.add_aggr(0, 1, 1)
self.ker.add_aggr(0, 2, 2)
if self.add_112:
self.ker.add_aggr(1, 1, 2)
if self.add_212:
self.ker.add_aggr(2, 2, 1)
if self.add_222:
self.ker.add_aggr(2, 2, 2)
self.reset_parameters()
def reset_parameters(self):
self.node_transform.reset_parameters()
self.ker.reset_parameters()
for m in self.post_mlp:
if hasattr(m, 'reset_parameters'):
m.reset_parameters()
def forward(self, batch) -> torch.Tensor:
edge_indices = [batch.edge_index, batch.edge_index2]
batch.x = batch.x.to(torch.float32)
edge_attrs = [self.node_transform(batch.x),
self.node_transform(batch.x[batch.edge_index[0]]) +
self.node_transform(batch.x[batch.edge_index[1]]),
self.node_transform(batch.x[batch.edge_index2[0]]) +
self.node_transform(batch.x[batch.edge_index2[1]])
]
triangles = {
(1, 1, 1): batch.triangle_1_1_1,
(1, 1, 2): batch.triangle_1_1_2,
(2, 2, 1): batch.triangle_2_2_1,
(2, 2, 2): batch.triangle_2_2_2,
}
inverse_edges = [batch.inverse_edge_1, batch.inverse_edge_2]
edge_attrs = self.ker(edge_attrs,
edge_indices,
triangles,
inverse_edges)
x = self.pool(edge_attrs, edge_indices, batch.num_nodes, batch.batch0)
x = self.post_mlp(x)
# x = F.log_softmax(x, dim=1)
return x
class BRECModel3(nn.Module):
def __init__(self,
hidden_channels: int,
num_layers: int,
add_0: bool = True,
add_112: bool = True,
add_212: bool = True,
add_222: bool = True,
eps: float = 0.,
train_eps: bool = False,
norm_type: str = "batch_norm",
norm_between_layers: str = "batch_norm",
residual: str = "none",
drop_prob: float = 0.0,
output_dim: int = 16):
super().__init__()
self.hidden_channels = hidden_channels
self.num_layers = num_layers
self.add_0 = add_0
self.add_112 = add_112
self.add_212 = add_212
self.add_222 = add_222
self.initial_eps = eps
self.train_eps = train_eps
self.norm_type = norm_type
self.residual = residual
self.drop_prob = drop_prob
self.OUTPUT_DIM = output_dim
self.node_transform = nn.Linear(1, self.hidden_channels)
self.ker = DR2FWL2Kernel(self.hidden_channels,
self.num_layers,
self.initial_eps,
self.train_eps,
self.norm_type,
norm_between_layers,
self.residual,
self.drop_prob)
self.pool = GraphLevelPooling(hidden_channels)
self.post_mlp = nn.Sequential(nn.Linear(hidden_channels, hidden_channels // 2),
nn.ELU(),
nn.Linear(hidden_channels // 2, self.OUTPUT_DIM))
self.ker.add_aggr(1, 1, 1)
if self.add_0:
self.ker.add_aggr(0, 1, 1)
self.ker.add_aggr(0, 2, 2)
if self.add_112:
self.ker.add_aggr(1, 1, 2)
if self.add_212:
self.ker.add_aggr(2, 2, 1)
if self.add_222:
self.ker.add_aggr(2, 2, 2)
self.ker.add_aggr(1, 2, 3)
self.ker.add_aggr(3, 3, 1)
self.ker.add_aggr(2, 2, 3)
self.ker.add_aggr(3, 3, 2)
self.ker.add_aggr(3, 3, 3)
self.ker.add_aggr(0, 3, 3)
self.reset_parameters()
def reset_parameters(self):
self.node_transform.reset_parameters()
self.ker.reset_parameters()
for m in self.post_mlp:
if hasattr(m, 'reset_parameters'):
m.reset_parameters()
def forward(self, batch) -> torch.Tensor:
edge_indices = [batch.edge_index, batch.edge_index2, batch.edge_index3]
batch.x = batch.x.to(torch.float32)
edge_attrs = [self.node_transform(batch.x),
self.node_transform(batch.x[batch.edge_index[0]]) +
self.node_transform(batch.x[batch.edge_index[1]]),
self.node_transform(batch.x[batch.edge_index2[0]]) +
self.node_transform(batch.x[batch.edge_index2[1]]),
self.node_transform(batch.x[batch.edge_index3[0]]) +
self.node_transform(batch.x[batch.edge_index3[1]])
]
triangles = {
(1, 1, 1): batch.triangle_1_1_1,
(1, 1, 2): batch.triangle_1_1_2,
(2, 2, 1): batch.triangle_2_2_1,
(2, 2, 2): batch.triangle_2_2_2,
(1, 2, 3): batch.triangle_1_2_3,
(3, 3, 1): batch.triangle_3_3_1,
(2, 2, 3): batch.triangle_2_2_3,
(3, 3, 2): batch.triangle_3_3_2,
(3, 3, 3): batch.triangle_3_3_3,
}
inverse_edges = [batch.inverse_edge_1, batch.inverse_edge_2, batch.inverse_edge_3]
edge_attrs = self.ker(edge_attrs,
edge_indices,
triangles,
inverse_edges)
x = self.pool(edge_attrs, edge_indices, batch.num_nodes, batch.batch0)
x = self.post_mlp(x)
# x = F.log_softmax(x, dim=1)
return x
parser = argparse.ArgumentParser("arguments for training and testing")
parser.add_argument("--P_NORM", type=str, default="2")
parser.add_argument("--EPOCH", type=int, default=EPOCH)
parser.add_argument("--LEARNING_RATE", type=float, default=LEARNING_RATE)
parser.add_argument("--BATCH_SIZE", type=int, default=BATCH_SIZE)
parser.add_argument("--WEIGHT_DECAY", type=float, default=WEIGHT_DECAY)
parser.add_argument("--OUTPUT_DIM", type=int, default=16)
parser.add_argument("--SEED", type=int, default=2022)
parser.add_argument("--THRESHOLD", type=float, default=THRESHOLD)
parser.add_argument("--MARGIN", type=float, default=MARGIN)
parser.add_argument("--LOSS_THRESHOLD", type=float, default=LOSS_THRESHOLD)
parser.add_argument("--D", type=int, default=2)
parser.add_argument("--DEVICE", type=str, default="1")
# parser.add_argument("--CONFIG", type=str, default="4_1_32")
args = parser.parse_args()
P_NORM = 2 if args.P_NORM == "2" else torch.inf
EPOCH = args.EPOCH
LEARNING_RATE = args.LEARNING_RATE
BATCH_SIZE = args.BATCH_SIZE
WEIGHT_DECAY = args.WEIGHT_DECAY
OUTPUT_DIM = args.OUTPUT_DIM
SEED = args.SEED
THRESHOLD = args.THRESHOLD
MARGIN = args.MARGIN
LOSS_THRESHOLD = args.LOSS_THRESHOLD
D = args.D
DEVICE = args.DEVICE
torch_geometric.seed_everything(SEED)
torch.backends.cudnn.deterministic = True
# torch.use_deterministic_algorithms(True)
# part_dict: {graph generation type, range}
part_dict = {
"Basic": (0, 60),
"Regular": (60, 110),
"Extension": (160, 260),
"CFI": (260, 320),
}
# Stage 1: pre calculation
# Here is for some calculation without data. e.g. generating all the k-substructures
def pre_calculation(*args, **kwargs):
time_start = time.process_time()
# Do something
time_end = time.process_time()
time_cost = round(time_end - time_start, 2)
logger.info(f"pre-calculation time cost: {time_cost}")
# Stage 2: dataset construction
# Here is for dataset construction, including data processing
def get_dataset(cfg, dataset_name):
time_start = time.process_time()
# dataset = BRECDataset(transform=transform_eval)
dataset = BRECDataset(name=dataset_name, pre_transform=eval(f"drfwl{D}_transform")())
time_end = time.process_time()
time_cost = round(time_end - time_start, 2)
logger.info(f"dataset construction time cost: {time_cost}")
return dataset
# Stage 3: model construction
# Here is for model construction.
def get_model(cfg):
time_start = time.process_time()
# Do something
model = (eval(f"BRECModel{D}"))(cfg.model.hidden_size,
cfg.model.num_layers,
norm_type='none',
norm_between_layers='none',
residual='last',
output_dim=OUTPUT_DIM).to('cuda:'+DEVICE)
time_end = time.process_time()
time_cost = round(time_end - time_start, 2)
logger.info(f"model construction time cost: {time_cost}")
return model
# Stage 4: evaluation
# Here is for evaluation.
def evaluation(dataset, model, path, device):
def T2_calculation(dataset, log_flag=False):
with torch.no_grad():
loader = DataLoader(dataset, collator=collate, batch_size=BATCH_SIZE)
pred_0_list = []
pred_1_list = []
for data in loader:
pred = model(data.to(device)).detach()
pred_0_list.extend(pred[0::2])
pred_1_list.extend(pred[1::2])
X = torch.cat([x.reshape(1, -1) for x in pred_0_list], dim=0).T
Y = torch.cat([x.reshape(1, -1) for x in pred_1_list], dim=0).T
if log_flag:
logger.info(f"X_mean = {torch.mean(X, dim=1)}")
logger.info(f"Y_mean = {torch.mean(Y, dim=1)}")
D = X - Y
D_mean = torch.mean(D, dim=1).reshape(-1, 1)
# S = torch.nan_to_num(torch.cov(D))
S = torch.cov(D)
inv_S = torch.linalg.pinv(S)
# inv_S = torch.inverse(S + S_epsilon)
return torch.mm(torch.mm(D_mean.T, inv_S), D_mean)
time_start = time.process_time()
# Do something
cnt = 0
correct_list = []
fail_in_reliability = 0
loss_func = CosineEmbeddingLoss(margin=MARGIN)
for part_name, part_range in part_dict.items():
logger.info(f"{part_name} part starting ---")
cnt_part = 0
fail_in_reliability_part = 0
start = time.process_time()
for id in tqdm(range(part_range[0], part_range[1])):
logger.info(f"ID: {id - part_range[0]}")
optimizer = torch.optim.Adam(
model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer)
dataset_traintest = dataset[
id * NUM_RELABEL * 2 : (id + 1) * NUM_RELABEL * 2
]
dataset_reliability = dataset[
(id + SAMPLE_NUM)
* NUM_RELABEL
* 2 : (id + SAMPLE_NUM + 1)
* NUM_RELABEL
* 2
]
model.reset_parameters()
model.train()
for _ in range(EPOCH):
traintest_loader = DataLoader(dataset_traintest, collator=collate, batch_size=BATCH_SIZE)
loss_all = 0
for data in traintest_loader:
optimizer.zero_grad()
pred = model(data.to(device))
loss = loss_func(
pred[0::2],
pred[1::2],
torch.tensor([-1] * (len(pred) // 2)).to(device),
)
loss.backward()
optimizer.step()
loss_all += len(pred) / 2 * loss.item()
loss_all /= NUM_RELABEL
logger.info(f"Loss: {loss_all}")
if loss_all < LOSS_THRESHOLD:
logger.info("Early Stop Here")
break
scheduler.step(loss_all)
model.eval()
T_square_traintest = T2_calculation(dataset_traintest, True)
T_square_reliability = T2_calculation(dataset_reliability, True)
isomorphic_flag = False
reliability_flag = False
if T_square_traintest > THRESHOLD and not torch.isclose(
T_square_traintest, T_square_reliability, atol=EPSILON_CMP
):
isomorphic_flag = True
if T_square_reliability < THRESHOLD:
reliability_flag = True
if isomorphic_flag:
cnt += 1
cnt_part += 1
correct_list.append(id - part_range[0])
logger.info(f"Correct num in current part: {cnt_part}")
if not reliability_flag:
fail_in_reliability += 1
fail_in_reliability_part += 1
logger.info(f"isomorphic: {isomorphic_flag} {T_square_traintest}")
logger.info(f"reliability: {reliability_flag} {T_square_reliability}")
end = time.process_time()
time_cost_part = round(end - start, 2)
logger.info(
f"{part_name} part costs time {time_cost_part}; Correct in {cnt_part} / {part_range[1] - part_range[0]}"
)
logger.info(
f"Fail in reliability: {fail_in_reliability_part} / {part_range[1] - part_range[0]}"
)
time_end = time.process_time()
time_cost = round(time_end - time_start, 2)
logger.info(f"evaluation time cost: {time_cost}")
Acc = round(cnt / SAMPLE_NUM, 2)
logger.info(f"Correct in {cnt} / {SAMPLE_NUM}, Acc = {Acc}")
logger.info(f"Fail in reliability: {fail_in_reliability} / {SAMPLE_NUM}")
logger.info(correct_list)
logger.add(f"{path}/result_show.txt", format="{message}", encoding="utf-8")
logger.info(
"Real_correct\tCorrect\tFail\thops\tlayers\tmini_layers\thidden\tOUTPUT_DIM\tBATCH_SIZE\tLEARNING_RATE\tWEIGHT_DECAY\tTHRESHOLD\tMARGIN\tLOSS_THRESHOLD\tEPOCH\tSEED"
)
logger.info(
f"{cnt-fail_in_reliability}\t{cnt}\t{fail_in_reliability}\t{cfg.model.num_layers}\t{D}\t{cfg.model.hidden_size}"
f"\t{OUTPUT_DIM}\t{BATCH_SIZE}\t{LEARNING_RATE}\t{WEIGHT_DECAY}\t{THRESHOLD}\t{MARGIN}\t{LOSS_THRESHOLD}\t{EPOCH}\t{SEED}"
)
if __name__ == "__main__":
file_name = "BREC/train/configs/BREC.yaml"
cfg.merge_from_file(file_name)
# cfg = update_cfg(cfg)
# Command Line Arguments
device = torch.device("cuda:"+DEVICE if torch.cuda.is_available() else "cpu")
NAME = f"d={D}_layer={cfg.model.num_layers}_hidden={cfg.model.hidden_size}"
DATASET_NAME = f"d={D}"
OUT_PATH = "result_BREC"
PATH = os.path.join(OUT_PATH, NAME)
os.makedirs(PATH, exist_ok=True)
LOG_NAME = os.path.join(PATH, "log.txt")
logger.remove(handler_id=None)
logger.add(LOG_NAME, rotation="5MB")
logger.info(f"Args: {dumps(vars(args), indent=4, sort_keys=True)}")
logger.info(cfg)
pre_calculation()
dataset = get_dataset(cfg, DATASET_NAME)
model = get_model(cfg)
evaluation(dataset, model, OUT_PATH, device) |
import React, { FC } from 'react';
import Layout from 'src/components/layout/Layout';
import TicTacToePlayer from 'src/components/tictactoe/player/TictactoePlayer';
import { useAuth } from 'src/firebase';
import useTranslate from 'src/hooks/useTranslate';
import useIsLocalStorageReady from 'src/hooks/useIsLocalStorageReady';
import TictactoeLayout from 'src/components/tictactoe/TictactoeLayout';
import TictactoeBoardCell from 'src/components/tictactoe/board/TictactoeBoardCell';
import { useDispatch, useSelector } from 'src/redux';
import { startNewGame, setSize } from 'src/redux/tictactoe-singleplayer';
import { moveThunk } from 'src/redux/tictactoe-singleplayer/actions';
import TictactoeSingleplayerMenu from './menu/TictactoeSingleplayerMenu';
import localization from './TictactoeSingleplayer.localization';
const TicTacToeSingleplayer: FC = () => {
const [auth, isAuthLoading] = useAuth();
const translate = useTranslate(localization);
const dispatch = useDispatch();
const isLocalStorageReady = useIsLocalStorageReady();
const cells = useSelector(
(state) => state.tictactoeSingleplayer.cells,
(prev, next) => JSON.stringify(prev) === JSON.stringify(next),
);
const isPlaying = useSelector((state) => state.tictactoeSingleplayer.isPlaying);
const isDraw = useSelector((state) => state.tictactoeSingleplayer.isDraw);
const isWinner = useSelector((state) => state.tictactoeSingleplayer.isWinner);
const cellsIndexesWinner = useSelector((state) => state.tictactoeSingleplayer.cellsIndexesWinner);
const size = useSelector((state) => state.tictactoeSingleplayer.size);
const isOver = isDraw || isWinner !== undefined;
return (
<Layout gameName="tictactoeSingleplayer">
<TictactoeLayout
playerLeft={
<TicTacToePlayer
edge="left"
isLoading={isAuthLoading}
isPlaying={!isOver ? isPlaying : undefined}
isWinner={isWinner === undefined ? undefined : isWinner}
nickname={translate('player')}
photo={auth ? auth.photoURL : null}
side="cross"
/>
}
playerRight={
<TicTacToePlayer
edge="right"
isPlaying={!isOver ? !isPlaying : undefined}
isRobot
isWinner={isWinner === undefined ? undefined : !isWinner}
nickname={translate('robot')}
side="circle"
/>
}
BoardCell={({ index }) => {
const side = cells[index];
return (
<TictactoeBoardCell
disabled={Boolean(!isPlaying || isOver || side)}
isWinnerCell={Boolean(cellsIndexesWinner && cellsIndexesWinner.includes(index))}
onClick={() => dispatch(moveThunk(index))}
side={side}
sidePlayer="cross"
/>
);
}}
isLoading={!isLocalStorageReady}
onChangeSize={(newSize) => dispatch(setSize(newSize))}
Overlay={
isOver
? () => (
<TictactoeSingleplayerMenu
isWinner={isWinner}
startNewGame={() => dispatch(startNewGame())}
translate={translate}
/>
)
: undefined
}
size={size}
/>
</Layout>
);
};
export default TicTacToeSingleplayer; |
# The robot should use the orders file (.csv ) and complete all the orders in the file. orders.csv
# Only the robot is allowed to get the orders file. You may not save the file manually on your computer.
# The robot should save each order HTML receipt as a PDF file.
# The robot should save a screenshot of each of the ordered robots.
# The robot should embed the screenshot of the robot to the PDF receipt
# The robot should create a ZIP archive of the PDF receipts (one zip archive that contains all the PDF files). Store the archive in the output directory.
# The robot should complete all the orders even when there are technical failures with the robot order website.
# The robot should be available in public GitHub repository.
# It should be possible to get the robot from the public GitHub repository and run it without manual setup.
from RPA.PDF import PDF
from robocorp.tasks import task
from robocorp import browser
from RPA.HTTP import HTTP
from RPA.Excel.Files import Files
from RPA.Tables import Tables
from RPA.Outlook.Application import Application
from robot.api import logger
from RPA.Archive import Archive
import csv
import os
@task
def order_robots_from_RobotSpareBin():
"""
Orders robots from RobotSpareBin Industries Inc.
Saves the order HTML receipt as a PDF file.
Saves the screenshot of the ordered robot.
Embeds the screenshot of the robot to the PDF receipt.
Creates ZIP archive of the receipts and the images.
"""
init()
open_robot_order_website()
download_excel_file()
fill_the_form()
archive_receipts()
cleanup()
def open_robot_order_website():
# TODO: Implement your function here
page = browser.page()
browser.goto("https://robotsparebinindustries.com/#/robot-order")
close_annoying_modal()
def fill_the_form():
"""Fills in the sales data and click the 'Submit' button"""
page = browser.page()
worksheet = get_order()
for row in worksheet:
fill_and_submit(row)
archive_receipts()
def fill_and_submit(row):
page = browser.page()
page.select_option("#head", str(row["Head"]))
rad = "#id-body-"+str(row["Body"])
page.set_checked(rad, True)
page.get_attribute
page.keyboard.press('Tab')
page.keyboard.press(str(row["Legs"]))
page.fill("#address", row["Address"])
page.click("#preview")
is_alert_visible = True
while is_alert_visible:
page.click("#order")
is_alert_visible = page.locator("//div[@class='alert alert-danger']").is_visible()
if not is_alert_visible:
break
store_receipt_as_pdf(row["Order number"])
page.click("#order-another")
close_annoying_modal()
def get_order():
library = Tables()
data = library.read_table_from_csv("orders.csv")
return data
def read_csv_file(filename):
data = []
with open(filename, 'rt', encoding="utf8") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
data.append(row)
return data
def close_annoying_modal():
page = browser.page()
page.click("button:text('Yep')")
def download_excel_file():
"""Downloads excel file from the given URL"""
http = HTTP()
http.download(url="https://robotsparebinindustries.com/orders.csv", overwrite=True)
def store_receipt_as_pdf(order_number):
"""Saves file to a location in output folder"""
page = browser.page()
pdf = PDF()
pdf_path = "output/receipts/order_"+order_number+".pdf"
order_receipt_html = page.locator("#receipt").inner_html()
pdf.html_to_pdf(order_receipt_html, pdf_path)
#take screenshot
screenshot_robot(order_number)
#embed screenshot in pdf
embed_screenshot_to_receipt("output/receipts/order_"+order_number+".png", pdf_path)
def screenshot_robot(order_number):
page = browser.page()
page.locator(selector="#robot-preview-image").screenshot(path="output/receipts/order_"+order_number+".png")
def embed_screenshot_to_receipt(screenshot, pdf_file):
pdf = PDF()
pdf.add_files_to_pdf(
files=[screenshot],
target_document=pdf_file,
append=True
)
def archive_receipts():
"""Downloads excel file from the given URL"""
lib = Archive()
lib.archive_folder_with_zip("output/receipts",'receipts.zip',recursive=True)
def init():
"All functions that need to be done to initialize robot"
create_folders()
def create_folders():
"All functions that need to be done to initialize robot"
os.makedirs("output/receipts", exist_ok=True)
def cleanup():
"All functions that need to be done to cleanup robot robot run"
# TODO: delete folders that are more than X days old
# TODO: delete downloaded orders.csv |
import { NextResponse, NextRequest } from "next/server";
import { NextApiRequest, NextApiResponse } from 'next';
import OpenAI from "openai";
require('dotenv').config({ path: ['.env.local', '.env'] });
export async function POST(req: NextRequest, res: NextResponse) {
if (req.method === 'POST')
{
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const body = await req.json();
const userInput = body.userInput;
console.log(userInput);
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{
role: "system",
content: "You are a cooking/baking assistant. You give helpful cooking tips and tricks, and create recipes for the user"
},
{
role: "user",
content: userInput
}
];
try {
//Request a response from GPT-3.5 Turbo
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: messages,
temperature: 0.7,
max_tokens: 800,
top_p: 1,
});
console.log(response.choices[0].message.content);
// Correctly use NextResponse
return NextResponse.json({ message: "Success", response: response.choices[0].message.content});
} catch (error) {
console.log("Error:", error);
return NextResponse.json({error: 'Internal Server Error'}, {status: 500});
}
} else {
return NextResponse.json({ error: 'Method Not Allowed' });
}
} |
from __future__ import annotations
from typing import List
from discord import Interaction, InputTextStyle
from discord.ui import InputText
from UI.Common import FroggeModal
################################################################################
__all__ = ("BGCheckVenueModal",)
################################################################################
class BGCheckVenueModal(FroggeModal):
def __init__(self):
super().__init__(title="Add Venue Experience")
self.add_item(
InputText(
style=InputTextStyle.multiline,
label="Instructions",
placeholder="Enter your character's venue experience.",
value=(
"Please enter the name of a venue which you'd like "
"to list as a reference, as well as the position(s) in which "
"you were employed."
),
required=False
)
)
self.add_item(
InputText(
style=InputTextStyle.singleline,
label="Venue Name",
placeholder="eg. 'Lilypad Lounge'",
max_length=50,
required=True
)
)
self.add_item(
InputText(
style=InputTextStyle.multiline,
label="Jobs Worked",
placeholder="eg. 'Bartender, Bouncer'",
max_length=200,
required=True
)
)
async def callback(self, interaction: Interaction):
self.value = (
self.children[1].value,
[j.strip() for j in self.children[2].value.split(",")]
)
self.complete = True
await interaction.edit()
self.stop()
################################################################################ |
/**
* Copyright (C) 2006 NetMind Consulting Bt.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package hu.netmind.beankeeper.lock;
import hu.netmind.beankeeper.common.StoreException;
/**
* Exception is thrown, if an object is about to be saved in a transaction,
* but the same object (or another representation of the same data) is under
* modification in another thread. This exception is also thrown if one
* of the objects is already locked.
* @author Brautigam Robert
* @version Revision: $Revision$
*/
public class ConcurrentModificationException extends StoreException
{
private SessionInfo sessionInfo;
private Object[] objs;
public ConcurrentModificationException(SessionInfo sessionInfo, Object[] objs, String message)
{
super(message);
this.sessionInfo=sessionInfo;
this.objs=objs;
}
public ConcurrentModificationException(SessionInfo sessionInfo, Object[] objs, String message, Throwable cause)
{
super(message,cause);
this.sessionInfo=sessionInfo;
this.objs=objs;
}
/**
* Returns the object which could not be modified.
*/
public Object[] getObjects()
{
return objs;
}
/**
* Returns the transaction which currently locks the object that could
* not be modified.
*/
public SessionInfo getSessionInfo()
{
return sessionInfo;
}
} |
import type { PostSummary, PostType } from '@/server/data_types/post'
import Image from 'next/image'
import Link from 'next/link'
import { format } from 'date-fns'
import { classnames } from '@/lib/classnames'
import { Card } from '@/ui/card/card'
import { PostTypesDisplayMapping } from '@/server/data_types/post'
// TODO: implement correct scaling of images https://hdoro.dev/performant-sanity-io-images and separate it into a component
function PostCard({ post }: { post: PostSummary }) {
return (
<Link className="flex w-full justify-center" href={`/posts/${post.slug}`}>
<Card>
<div className="flex w-full flex-wrap items-center justify-center gap-6 md:flex-nowrap md:gap-4">
<div className="hidden min-w-[128px] items-center justify-center md:flex">
<Image
loading="lazy"
className="bg-grey aspect-auto rounded"
src={`${post.mainImage}?auto=format&h=72&w=128&dpr=3`}
alt={post.title}
height={72}
width={128}
/>
</div>
<div className="flex min-w-[128px] items-center justify-center md:hidden">
<Image
loading="lazy"
className="bg-grey aspect-auto rounded"
src={`${post.mainImage}?auto=format&h=144&w=256&dpr=3`}
alt={post.title}
height={144}
width={256}
/>
</div>
<div className="flex flex-1 flex-col justify-between gap-4">
<div className="flex flex-row items-start justify-between gap-2">
<span className="text-xl font-medium text-text line-clamp-2 group-hover:text-primary md:line-clamp-1">
{post.title}
</span>
<PostTypeBadge postType={post.type} />
</div>
<span className="flex-shrink text-sm font-thin text-text line-clamp-1 group-hover:text-primary">
{post.description}
</span>
<div>
<span className="text-sm font-thin text-text group-hover:text-primary">
{format(new Date(post.publishedAt), 'MMMM do, yyyy')} |{' '}
{post.estimatedDuration} min
</span>
</div>
</div>
</div>
</Card>
</Link>
)
}
function PostTypeBadge({ postType }: { postType: PostType }) {
const badgeClassname = classnames(
'rounded px-2 py-1 text-xs font-light group-hover:bg-primary bg-secondary text-background'
)
return (
<span className={badgeClassname}>{PostTypesDisplayMapping[postType]}</span>
)
}
export { PostCard } |
import gym
import random
from tensorflow.keras import Sequential
from collections import deque
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.optimizers import RMSprop
from keras import optimizers
import matplotlib.pyplot as plt
from tensorflow.keras.activations import relu, linear
import tensorflow as tf
import numpy as np
import time
adam= Adam(lr=0.0001, decay=1e-6)
EPISODES = 1000
class DQN:
""" Implementation of deep q learning algorithm """
def __init__(self, action_space, state_space):
self.state_size = state_size
self.action_size = action_size
self.memory = deque(maxlen=2000)
self.gamma = 0.95 # discount rate
self.epsilon = 1.0 # exploration rate
self.epsilon_min = 0.01
self.epsilon_decay = 0.995
self.learning_rate = 0.001
self.model = self._build_model()
# Set Optimizer
def _build_model(self):
# Neural Net for Deep-Q learning Model
model = Sequential()
model.add(Dense(24, input_dim=self.state_size, activation='relu'))
model.add(Dense(24, activation='relu'))
model.add(Dense(self.action_size, activation='linear'))
model.compile(loss='mse',
optimizer=tf.keras.optimizers.Adam(lr=self.learning_rate))
return model
def memorize(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
if np.random.rand() <= self.epsilon:
return random.randrange(self.action_size)
act_values,loss = self.model.predict(state)
return np.argmax(act_values[0]),loss
def replay(self, batch_size):
minibatch = random.sample(self.memory, batch_size)
for state, action, reward, next_state, done in minibatch:
target = reward
if not done:
Q_next=self.model.predict(next_state)[0]
target = (reward + self.gamma *np.amax(Q_next))
target_f = self.model.predict(state)
target_f[0][action] = target
#train network
self.model.fit(state, target_f, epochs=1, verbose=1)
def get_reward(state):
if state[0] >= 0.5:
print("Car has reached the goal")
return 10
if state[0] > -0.4:
return (1+state[0])**2
return 0
def test_dqn(episode):
loss = []
agent = DQN(env.action_space.n, env.observation_space.shape[0])
for e in range(episode):
state = env.reset()
state = np.reshape(state, (1, 2))
score = 0
max_steps = 1000
for i in range(max_steps):
action = agent.act(state)
env.render()
next_state, reward, done, _ = env.step(action)
reward = get_reward(next_state)
score += reward
next_state = np.reshape(next_state, (1, 2))
agent.remember(state, action, reward, next_state, done)
state = next_state
agent.replay()
if done:
print("episode: {}/{}, score: {}".format(e, episode, score))
break
loss.append(score)
return loss
def random_policy(episode, step):
for i_episode in range(episode):
env.reset()
for t in range(step):
env.render()
action = env.action_space.sample()
state, reward, done, info = env.step(action)
if done:
print("Episode finished after {} timesteps".format(t+1))
break
print("Starting next episode")
import os
os.environ.setdefault('PATH', '')
from collections import deque
from gym import spaces
import cv2
cv2.ocl.setUseOpenCL(False)
class ProcessFrame84(gym.ObservationWrapper):
def __init__(self, env=None):
super(ProcessFrame84, self).__init__(env)
self.observation_space = spaces.Box(low=0, high=255, shape=(84, 84, 1), dtype=np.uint8)
def observation(self, obs):
return ProcessFrame84.process(obs)
@staticmethod
def process(frame):
if frame.size == 210 * 160 * 3:
img = np.reshape(frame, [210, 160, 3]).astype(np.float32)
elif frame.size == 250 * 160 * 3:
img = np.reshape(frame, [250, 160, 3]).astype(np.float32)
else:
assert False, "Unknown resolution."
img = img[:, :, 0] * 0.299 + img[:, :, 1] * 0.587 + img[:, :, 2] * 0.114
resized_screen = cv2.resize(img, (84, 110), interpolation=cv2.INTER_AREA)
x_t = resized_screen[18:102, :]
x_t = np.reshape(x_t, [84, 84, 1])
return x_t.astype(np.uint8)
class ClippedRewardsWrapper(gym.RewardWrapper):
def reward(self, reward):
"""Change all the positive rewards to 1, negative to -1 and keep zero."""
return np.sign(reward)
class NoopResetEnv(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset.
No-op is assumed to be action 0.
"""
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.override_num_noops = None
self.noop_action = 0
assert env.unwrapped.get_action_meanings()[0] == 'NOOP'
def reset(self, **kwargs):
""" Do no-op action for a number of steps in [1, noop_max]."""
self.env.reset(**kwargs)
if self.override_num_noops is not None:
noops = self.override_num_noops
else:
noops = self.unwrapped.np_random.integers(1, self.noop_max + 1) #pylint: disable=E1101
assert noops > 0
obs = None
for _ in range(noops):
obs, _, done, _ = self.env.step(self.noop_action)
if done:
obs = self.env.reset(**kwargs)
return obs
def step(self, ac):
return self.env.step(ac)
class FireResetEnv(gym.Wrapper):
def __init__(self, env):
"""Take action on reset for environments that are fixed until firing."""
gym.Wrapper.__init__(self, env)
assert env.unwrapped.get_action_meanings()[1] == 'FIRE'
assert len(env.unwrapped.get_action_meanings()) >= 3
def reset(self, **kwargs):
self.env.reset(**kwargs)
obs, _, done, _ = self.env.step(1)
if done:
self.env.reset(**kwargs)
obs, _, done, _ = self.env.step(2)
if done:
self.env.reset(**kwargs)
return obs
def step(self, ac):
return self.env.step(ac)
class EpisodicLifeEnv(gym.Wrapper):
def __init__(self, env):
"""Make end-of-life == end-of-episode, but only reset on true game over.
Done by DeepMind for the DQN and co. since it helps value estimation.
"""
gym.Wrapper.__init__(self, env)
self.lives = 0
self.was_real_done = True
def step(self, action):
obs, reward, done, info = self.env.step(action)
self.was_real_done = done
# check current lives, make loss of life terminal,
# then update lives to handle bonus lives
lives = self.env.unwrapped.ale.lives()
if lives < self.lives and lives > 0:
# for Qbert sometimes we stay in lives == 0 condtion for a few frames
# so its important to keep lives > 0, so that we only reset once
# the environment advertises done.
done = True
self.lives = lives
return obs, reward, done, info
def reset(self, **kwargs):
"""Reset only when lives are exhausted.
This way all states are still reachable even though lives are episodic,
and the learner need not know about any of this behind-the-scenes.
"""
if self.was_real_done:
obs = self.env.reset(**kwargs)
else:
# no-op step to advance from terminal/lost life state
obs, _, _, _ = self.env.step(0)
self.lives = self.env.unwrapped.ale.lives()
return obs
class MaxAndSkipEnv(gym.Wrapper):
def __init__(self, env, skip=4):
"""Return only every `skip`-th frame"""
gym.Wrapper.__init__(self, env)
# most recent raw observations (for max pooling across time steps)
self._obs_buffer = np.zeros((2,)+env.observation_space.shape, dtype=np.uint8)
self._skip = skip
def step(self, action):
"""Repeat action, sum reward, and max over last observations."""
total_reward = 0.0
done = None
for i in range(self._skip):
obs, reward, done, info = self.env.step(action)
if i == self._skip - 2: self._obs_buffer[0] = obs
if i == self._skip - 1: self._obs_buffer[1] = obs
total_reward += reward
if done:
break
# Note that the observation on the done=True frame
# doesn't matter
max_frame = self._obs_buffer.max(axis=0)
return max_frame, total_reward, done, info
def reset(self, **kwargs):
return self.env.reset(**kwargs)
class ClipRewardEnv(gym.RewardWrapper):
def __init__(self, env):
gym.RewardWrapper.__init__(self, env)
def reward(self, reward):
"""Bin reward to {+1, 0, -1} by its sign."""
return np.sign(reward)
class WarpFrame(gym.ObservationWrapper):
def __init__(self, env, width=84, height=84, grayscale=True):
"""Warp frames to 84x84 as done in the Nature paper and later work."""
gym.ObservationWrapper.__init__(self, env)
self.width = width
self.height = height
self.grayscale = grayscale
if self.grayscale:
self.observation_space = spaces.Box(low=0, high=255,
shape=(self.height, self.width, 1), dtype=np.uint8)
else:
self.observation_space = spaces.Box(low=0, high=255,
shape=(self.height, self.width, 3), dtype=np.uint8)
def observation(self, frame):
if self.grayscale:
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
frame = cv2.resize(frame, (self.width, self.height), interpolation=cv2.INTER_AREA)
if self.grayscale:
frame = np.expand_dims(frame, -1)
return frame
class FrameStack(gym.Wrapper):
def __init__(self, env, k):
"""Stack k last frames.
Returns lazy array, which is much more memory efficient.
See Also
--------
baselines.common.atari_wrappers.LazyFrames
"""
gym.Wrapper.__init__(self, env)
self.k = k
self.frames = deque([], maxlen=k)
shp = env.observation_space.shape
self.observation_space = spaces.Box(low=0, high=255, shape=(shp[:-1] + (shp[-1] * k,)), dtype=env.observation_space.dtype)
def reset(self):
ob = self.env.reset()
for _ in range(self.k):
self.frames.append(ob)
return self._get_ob()
def step(self, action):
ob, reward, done, info = self.env.step(action)
self.frames.append(ob)
return self._get_ob(), reward, done, info
def _get_ob(self):
assert len(self.frames) == self.k
return list(self.frames)
class ScaledFloatFrame(gym.ObservationWrapper):
def __init__(self, env):
gym.ObservationWrapper.__init__(self, env)
self.observation_space = gym.spaces.Box(low=0, high=1, shape=env.observation_space.shape, dtype=np.float32)
def observation(self, observation):
# careful! This undoes the memory optimization, use
# with smaller replay buffers only.
return np.array(observation).astype(np.float32) / 255.0
class LazyFrames(object):
def __init__(self, frames):
"""This object ensures that common frames between the observations are only stored once.
It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay
buffers.
This object should only be converted to numpy array before being passed to the model.
You'd not believe how complex the previous solution was."""
self._frames = frames
self._out = None
def _force(self):
if self._out is None:
self._out = np.concatenate(self._frames, axis=-1)
self._frames = None
return self._out
def __array__(self, dtype=None):
out = self._force()
if dtype is not None:
out = out.astype(dtype)
return out
def __len__(self):
return len(self._force())
def __getitem__(self, i):
return self._force()[i]
def make_atari(env_id, timelimit=True):
# XXX(john): remove timelimit argument after gym is upgraded to allow double wrapping
env = gym.make(env_id)
if not timelimit:
env = env.env
assert 'NoFrameskip' in env.spec.id
env = NoopResetEnv(env, noop_max=30)
env = MaxAndSkipEnv(env, skip=4)
return env
def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):
"""Configure environment for DeepMind-style Atari.
"""
if episode_life:
env = EpisodicLifeEnv(env)
if 'FIRE' in env.unwrapped.get_action_meanings():
env = FireResetEnv(env)
env = WarpFrame(env)
if scale:
env = ScaledFloatFrame(env)
if clip_rewards:
env = ClipRewardEnv(env)
if frame_stack:
env = FrameStack(env, 4)
return env
def wrap_dqn(env):
assert 'NoFrameskip' in env.spec.id
env = EpisodicLifeEnv(env)
env = NoopResetEnv(env, noop_max=30)
env = MaxAndSkipEnv(env, skip=4)
if 'FIRE' in env.unwrapped.get_action_meanings():
env = FireResetEnv(env)
env = ProcessFrame84(env)
env = FrameStack(env, 4)
env = ClippedRewardsWrapper(env)
return env
def calc_accuracy(score,scores):
acc=(score/scores)*100
return acc
if __name__ == '__main__':
env = wrap_dqn(gym.make('PongNoFrameskip-v4', render_mode='human'))
env.seed(110)
np.random.seed(10)
env.reset()
for i in range(3000):
time.sleep(0.1)
action = env.action_space.sample()
next_state, reward, done, info = env.step(action)
if done:
env.reset()
env.close()
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
agent = DQN(state_size, action_size)
done = False
batch_size = 32
loss = []
accuracy=[]
for e in range(EPISODES):
state = env.reset()
state = np.reshape(state, [1, state_size])
score = 0
done = False
for time in range(500):
if e > (EPISODES * 0.8):
env.render()
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
reward = reward if not done else -10
score += reward
scores.append(score)
accuracy.append(calc_accuracy(score,scores))
next_state = np.reshape(next_state, [1, state_size])
agent.memorize(state, action, reward, next_state, done)
state = next_state
if done:
print("episode: {}/{},score:{}, e: {:.2}"
.format(e, EPISODES, time, agent.epsilon))
break
if len(agent.memory) > batch_size:
agent.replay(batch_size)
loss.append(score)
print(accuracy)
print(env.observation_space)
print(env.action_space)
plt.plot([i + 1 for i in range(EPISODES)], loss)
plt.show() |
{% extends 'layout.html' %}
{% load i18n static djmoney custom_filters %}
{% block page_content %}
<div class="Middle Middle_top">
<div class="Section">
<div class="wrap">
<div class="Product">
<div class="ProductCard">
<div class="ProductCard-look">
<div class="ProductCard-photo">
<img src="{{ product.main_image.middle.url }}" alt="{{ product.main_image }}.png"/>
</div>
<div class="ProductCard-picts">
<a class="ProductCard-pict ProductCard-pict_ACTIVE" href="{{ product.main_image.middle.url }}">
<img src="{{ product.main_image.small.url }}" alt="{{ product.main_image }}"/>
</a>
{% for img in product.images.all %}
{% if img.id != product.main_image.id %}
<a class="ProductCard-pict" href="{{ img.middle.url }}">
<img src="{{ img.small.url }}" alt="{{ img }}">
</a>
{% endif %}
{% empty %}
{% endfor %}
</div>
</div>
<div class="ProductCard-desc">
<div class="ProductCard-header">
<h2 class="ProductCard-title">{{ product.name }}</h2>
<div class="ProductCard-info">
<div class="ProductCard-cost">
<div class="ProductCard-price">
{% if request.LANGUAGE_CODE == 'en' %}
{{ price|dollar_conversion }}
{% else %}
{% money_localize price 'RUB' %}
{% endif %}
</div>
</div>
</div>
</div>
<div class="ProductCard-text">
<p>{{ product.description_short }}</p>
</div>
<div class="ProductCard-cart">
<div class="ProductCard-cartElement ProductCard-cartElement_amount">
<div class="Amount Amount_product">
<button class="Amount-remove" type="button"></button>
<input class="Amount-input form-input" name="amount" type="text" value="1"/>
<button class="Amount-add" type="button"></button>
</div>
</div>
<div class="ProductCard-cartElement">
<a class="btn btn_primary" href="{% url 'cart_add' random_product_id %}?next={{ request.path|urlencode }}">
<img class="btn-icon" src="{% static 'img/icons/card/cart_white.svg' %}" alt="cart_white.svg"/>
<span class="btn-content">{% trans 'Buy' %}</span>
</a>
</div>
<div id="modal_open" class="my_modal">
<div class="my_modal-dialog">
<div class="my_modal-content">
<div class="my_modal-header">
<p class="my_modal-title">Поздравляем!</p>
<a href="#" title="Закрыть модальное окно" class="close">×</a>
</div>
<div class="my_modal-body">
<p>Товар успешно добавлен в корзину!</p>
</div>
</div>
</div>
</div>
</div>
<div class="ProductCard-footer">
<div class="ProductCard-tags">
<strong class="ProductCard-tagsTitle">{% trans 'Tags' %}:</strong>
{% for tag in product.tags.all %}
{% if forloop.last %}
<a href="#">{{ tag.name }}</a>
{% else %}
<a href="#">{{ tag.name }}, </a>
{% endif %}
{% empty %}
<p>No tags</p>
{% endfor %}
</div>
</div>
</div>
</div>
<div class="Tabs Tabs_default">
<div class="Tabs-links">
<a class="Tabs-link_ACTIVE Tabs-link" href="#description">
<span>{% trans 'Description' %}</span>
</a>
<a class="Tabs-link" href="#sellers">
<span>{% trans 'Sellers' %}</span>
</a>
<a class="Tabs-link" href="#addit">
<span>{% trans 'Features' %}</span>
</a>
<a class="Tabs-link" href="#reviews">
<span>{% trans 'Reviews' %} ({{ reviews_count }})</span>
</a>
</div>
<div class="Tabs-wrap">
<div class="Tabs-block" id="description">
<h2>{{ product.name }}</h2>
<p>
{{ product.description_long }}
</p>
<div class="clearfix">
</div>
<div class="table">
<table>
<tr>
<th>{% trans 'Feature' %}
</th>
<th>{% trans 'Value' %}
</th>
</tr>
<tr>
<td>{% trans 'Device type' %}
</td>
<td>{{ product.category }}
</td>
</tr>
</table>
</div>
</div>
<div class="Tabs-block" id="sellers">
<div class="Section-content">
<div class="Orders">
{% for shop, price in sellers.items %}
<div class="Order Order_anons">
<div class="Order-personal">
<div class="row">
<div class="row-block">
<a class="Order-title" href="oneorder.html">
{{ shop.name }}
</a>
<div class="ProductCard-cartElement" style="margin-top: 10px;">
<a class="btn btn_primary" href="{% url 'cart_add' shop.id %}?next={{ request.path|urlencode }}">
<img class="btn-icon" src="../../static/img/icons/card/cart_white.svg"
alt="cart_white.svg"/>
<span class="btn-content">{% trans 'Buy' %}</span>
</a>
</div>
</div>
<div class="row-block">
<div class="Order-info Order-info_delivery">
<div class="Order-infoType">
{% trans 'Delivery type' %}:
</div>
<div class="Order-infoContent">
Ordinary delivery
</div>
</div>
<div class="Order-info Order-info_pay">
<div class="Order-infoType">
{% trans 'Payment' %}:
</div>
<div class="Order-infoContent">
Card online
</div>
</div>
<div class="Order-info">
<div class="Order-infoType">
{% trans 'Price' %}:
</div>
<div class="Order-infoContent">
{% if request.LANGUAGE_CODE == 'ru' %}
{% if price.price_new %}
<span class="Card-priceOld" style="font-size: 18px">{% money_localize price.price_old 'RUB' %}</span>
<span class="Card-price" style="color: #000; font-weight: 400; font-size: 18px">{% money_localize price.price_new 'RUB' %}</span>
{% else %}
<span class="Order-price">{% money_localize price.price_old 'RUB' %}</span>
{% endif %}
{% else %}
{% if price.price_new %}
<span class="Card-priceOld" style="font-size: 18px">{{ price.price_old|dollar_conversion }}</span>
<span class="Card-price" style="color: #000; font-weight: 400; font-size: 18px">{{ price.price_new|dollar_conversion }}</span>
{% else %}
<span class="Order-price">{{ price.price_old|dollar_conversion }}</span>
{% endif %}
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<div class="Tabs-block" id="addit">
<div class="Product-props">
{% for feature in product.features.all %}
{% for value in feature.values.all %}
{% if forloop.first %}
<div class="Product-prop">
<strong>{{ feature.feature_name }}</strong>
<span>{{ value }}</span>
</div>
{% else %}
<div class="Product-prop">
<strong></strong>
<span>{{ value }}</span>
</div>
{% endif %}
{% endfor %}
{% empty %}
<p>No features</p>
{% endfor %}
</div>
</div>
<div class="Tabs-block" id="reviews">
<header class="Section-header">
{% if reviews_count == 1 %}
{% if request.LANGUAGE_CODE == 'ru' %}
<h3 class="Section-title">{{ reviews_count }} отзыв</h3>
{% else %}
<h3 class="Section-title">{{ reviews_count }} review</h3>
{% endif %}
{% elif reviews_count > 1 %}
{% if request.LANGUAGE_CODE == 'ru' %}
<h3 class="Section-title">{{ reviews_count }} отзыва</h3>
{% else %}
<h3 class="Section-title">{{ reviews_count }} reviews</h3>
{% endif %}
{% elif reviews_count > 4 or reviews_count == 0 %}
{% if request.LANGUAGE_CODE == 'ru' %}
<h3 class="Section-title">{{ reviews_count }} отзывов</h3>
{% else %}
<h3 class="Section-title">{{ reviews_count }} reviews</h3>
{% endif %}
{% endif %}
</header>
<div class="Comments">
{% for review in product.reviews.all|dictsortreversed:"created" %}
<div class="Comment">
<div class="Comment-column Comment-column_pict">
<div class="Comment-avatar">
</div>
</div>
<div class="Comment-column">
<header class="Comment-header">
<div>
<strong class="Comment-title">{{ review.user.name }} {{ review.user.surname }}</strong>
<span class="Comment-date">{{ review.created }}</span>
</div>
</header>
<div class="Comment-content">
{{ review.text }}
</div>
</div>
</div>
{% endfor %}
</div>
<header class="Section-header Section-header_product">
<h3 class="Section-title">{% trans 'Add review' %}
</h3>
</header>
<div class="Tabs-addComment">
<form class="form" method="post">
{% csrf_token %}
<div class="form-group">
{{ review_form }}
</div>
<div class="form-group">
<button class="btn btn_muted" type="submit">{% trans 'Submit review' %}
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %} |
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Object MOdel, DOM</title>
<link rel="favicon" href="./../favicon.ico" type="image/x-icon">
<!-- Bootstrap -->
<!-- <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
-->
<!-- GOOGLE FONTS -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Creepster&family=Montserrat:wght@400;900&family=Pacifico&family=Ubuntu:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./static/css/style.css">
</head>
<body onload="//function puttedn into script tag">
<section id="title">
<button type="button"><a href="../index.html">BACK TO HOME!</a></button>
<br>
<h1>Sesion 11
<br><span>The Document Object Model<br>-DOM-</span></h1>
<hr>
</section>
<section id="middle">
<div class="container-insade">
<button type="button"><a href="./DOM.html">DOM concepts</a></button>
<button type="button"><a href="./JSandCSS.html">Styling with JS!</a></button>
<h1>Adding JS to the web</h1>
<div class="container-insade">
<!---------------------------- JS FROM ONLOAD -->
<h2>Adding from the onload on the body tag</h2>
<p>We can add JavaScript in the body with <span>onload</span>, we'll write our code into the double quotes,
but the onload don't suport functions or advanced js, like the next example:</p>
<button type="button" onclick="hiBody()">Hello from body</button>
<code>
<body <span>onload="alert('Hello from the body onload!')"</span>> <br><br>
//On load means, wherever the js is, it's called
</code>
<!---------------------------- JS FROM SCRIPT TAG -->
<h2>Adding from the script tag</h2>
<p>You can add js, insade the html, just adding the tag "script", and inside him all your wantend code</p>
<button type="button" onclick="hiScript()">Hello from Script</button>
<script>
function hiBody(){
alert('Hello from the body onload!');
};
function hiScript() {
alert("Hello from the script tag!");
};
</script>
<!---------------------------- JS FROM AN EXTERNAL JS FILE -->
<code>
<b><scrip></b> <br><br>
<span class="comment">//Here you can add your code like this</span> <br><br>
function hiScript() {
alert("Hello from the script tag!");
};
<br><br>
<b></scrip></b>
</code>
<h2>Adding from an external js file</h2>
<p>You can add js, from an external js file, white the script tag, but, adding some atributes. <br> JUST ONE BEST PRACTICE, the js are adding at the bottom of the body, cause on that don't will be crashed with the inexisting html tags or css, on that place, the js will be played until all the html struture is loaded, and it will give an fast aparience</p>
<button type="button" onclick="hiExternalJS()">Hello from an external JS</button>
<script src="./static/js/index.js" charset="utf-8"></script>
<code>
<b><scrip</b> src="./static/js/index.js" charset="utf-8" <b>></b><b></scrip></b>
</code>
<br><br>
</div>
</div>
<!-- ------------------------- code of excercices ------------------------- -->
</section>
<footer>
<button type="button"><a href="../index.html">BACK TO HOME!</a></button>
<p> All rigths reserved, Ricardo Hernández <br>
<span>+502 4209 0991 | [email protected]</span>
</p>
</footer>
</body>
</html> |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ShrubberyCreationForm.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bbonaldi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/07/04 21:36:03 by bbonaldi #+# #+# */
/* Updated: 2023/07/08 23:17:46 by bbonaldi ### ########.fr */
/* */
/* ************************************************************************** */
#include "ShrubberyCreationForm.hpp"
ShrubberyCreationForm::ShrubberyCreationForm() : AForm("ShrubberyCreationForm", 145, 137)
{
std::cout << "ShrubberyCreationForm Default Constructor called!" << std::endl;
}
ShrubberyCreationForm::ShrubberyCreationForm(std::string target) : AForm("ShrubberyCreationForm", 145, 137)
{
std::cout << "ShrubberyCreationForm Named Constructor called!" << std::endl;
this->_target = target;
}
ShrubberyCreationForm::ShrubberyCreationForm(ShrubberyCreationForm const &src) : AForm(src.getName(), src.getGrade(), src.getExec())
{
std::cout << "ShrubberyCreationForm Copy Constructor called!" << std::endl;
*this = src;
}
ShrubberyCreationForm::~ShrubberyCreationForm()
{
std::cout << "ShrubberyCreationForm Destructor called!" << std::endl;
}
ShrubberyCreationForm & ShrubberyCreationForm::operator=(ShrubberyCreationForm const &rhs)
{
std::cout << "ShrubberyCreationForm Copy Assignment called!" << std::endl;
if (this != &rhs)
this->_target = this->_target;
return (*this);
}
void ShrubberyCreationForm::execute(Bureaucrat const &executor) const
{
AForm::execute(executor);
std::ofstream file(this->_target.c_str());
if (file.is_open())
{
file << " /\\ " << std::endl;
file << " /\\/\\ " << std::endl;
file << " /\\/\\/\\ " << std::endl;
file << " /\\/\\/\\/\\ " << std::endl;
file << " /\\/\\/\\/\\/\\ " << std::endl;
file << " /\\/\\/\\/\\/\\/\\ " << std::endl;
file << "/\\/\\/\\/\\/\\/\\/\\" << std::endl;
file << " || " << std::endl;
file << " || " << std::endl;
file << " || " << std::endl;
file.close();
}
} |
import { Request, Response, NextFunction } from "express";
import ErrorResponse from "../utils/errorResponse";
const errorHandler = (
err: any,
req: Request,
res: Response,
next: NextFunction
) => {
let error = { ...err };
error.message = err.message;
// Log to the console
console.error(err);
// If a response has already been sent, return early
if (res.headersSent) {
return next(err);
}
// Mongoose bad ObjectId
if (err.name === "CastError") {
const message = "Resource not found";
error = new ErrorResponse(message, 404);
}
// Mongoose duplicate key error
if (err.code === 11000) {
const message = "Duplicate field value entered";
error = new ErrorResponse(message, 400);
}
// Mongoose Validation Error
if (err.name === "ValidationError") {
const message = Object.values(err.errors).map((val: any) => val.message).join(', ');
error = new ErrorResponse(message, 400);
}
res.status(error.statusCode || 500).json({
success: false,
error: error.message || "Server Error",
});
};
export default errorHandler; |
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { combineLatest, Subject, Subscription } from 'rxjs';
import { Army, BoardLocation, UnitType } from 'src/app/models/game-models';
import { GameContext } from 'src/app/models/game-utility-models';
import { GameContextService } from 'src/app/services/rx-logic/shared/game-context.service';
import { MaxArmyService } from 'src/app/services/rx-logic/shared/max-army.service';
import {
getFrozenUnitsAtLocation,
getUnitImage,
subtractArmies,
} from 'src/app/utils/army-utils';
import { findByFieldLocation } from 'src/app/utils/location-utils';
type Quartile = 1 | 2 | 3 | 4;
type UnitOccurence = {
quartile: Quartile; // which quartile does the amount belong to? <0%; 25%), 25%-50%, 50%-75%, 75%-100%
relativeAmount: number; // from 0 to 90, where does the amount belong INSIDE IT'S QUARTILE?
unitType: UnitType;
};
@Component({
selector: 'app-unit-circles',
templateUrl: './unit-circles.component.html',
styleUrls: ['./unit-circles.component.scss'],
})
export class UnitCirclesComponent implements OnInit, OnDestroy {
fieldLocationSubject = new Subject<BoardLocation>();
maxArmy: Army = { droids: 100, tanks: 20, cannons: 30 };
ownershipClass = '';
// Quartile:
unitOccurences: Array<UnitOccurence> = [];
sub1: Subscription;
constructor(
private maxArmyService: MaxArmyService,
private gameContextService: GameContextService
) {
this.sub1 = combineLatest([
this.maxArmyService.getStateUpdates(),
this.fieldLocationSubject.asObservable(),
this.gameContextService.getStateUpdates(),
]).subscribe(([maxArmy, location, context]) => {
this.unitOccurences = this.convertToUnitOccurenceList(
maxArmy,
location,
context
);
this.ownershipClass = this.getOwnershipClass(location, context);
});
this.maxArmyService.requestState();
this.gameContextService.requestState();
}
ngOnInit(): void {
}
getImagePath(unitType: UnitType): string {
return getUnitImage(unitType);
}
private getOwnershipClass(fieldLocation: BoardLocation, gameContext: GameContext): string {
const field = findByFieldLocation(fieldLocation, gameContext.game.fields);
const owns = field.ownerId === gameContext.player.id;
return owns ? 'owned' : 'enemy';
}
private convertToUnitOccurenceList(
maxArmy: Army,
fieldLocation: BoardLocation,
context: GameContext
): Array<UnitOccurence> {
const baseArmy = findByFieldLocation(
fieldLocation,
context.game.fields
).army || { droids: 0, tanks: 0, cannons: 0 };
const frozenUnits = getFrozenUnitsAtLocation(
fieldLocation,
context.currentActions
);
const currentArmy = subtractArmies(baseArmy, frozenUnits);
return [
this.convertSingleToUnitOccurence(
maxArmy.droids,
currentArmy?.droids,
'DROID'
),
this.convertSingleToUnitOccurence(
maxArmy.tanks,
currentArmy?.tanks,
'TANK'
),
this.convertSingleToUnitOccurence(
maxArmy.cannons,
currentArmy?.cannons,
'CANNON'
),
].filter((o) => o !== null);
}
private convertSingleToUnitOccurence(
maxUnits: number,
currentUnits: number,
unitType: UnitType
): UnitOccurence | null {
if (
currentUnits === null ||
currentUnits < 1 ||
maxUnits === null ||
maxUnits < 1
) {
return null;
}
const ratio = currentUnits / maxUnits;
const quartile = this.getQuartile(ratio);
const quartileRangeLower = (quartile - 1) * 0.25;
const distanceBetweenLowerAndUpper = 0.25;
const distanceFromLower = ratio - quartileRangeLower;
const quartileRangeRatio = distanceFromLower / distanceBetweenLowerAndUpper;
const relativeAmount = quartileRangeRatio * 90;
return {
quartile,
relativeAmount,
unitType,
};
}
private getQuartile(ratio: number): Quartile {
if (ratio < 0.25) {
return 1;
}
if (ratio < 0.5) {
return 2;
}
if (ratio < 0.75) {
return 3;
}
return 4;
}
@Input()
set fieldLocation(location: BoardLocation) {
this.fieldLocationSubject.next(location);
}
ngOnDestroy(): void {
this.sub1.unsubscribe();
}
} |
import { FunctionComponent } from "react";
import { AbsoluteFill, Easing, interpolate, useCurrentFrame } from "remotion";
import Layout from "./Layout";
interface AboutProps {}
interface TextProps {
children: React.ReactNode;
index: number;
isLast?: boolean;
}
const Text: FunctionComponent<TextProps> = ({ children, index, isLast }) => {
const frame = useCurrentFrame();
const start = 5 + 40 * index;
const end = start + 40;
const appearingY = interpolate(frame, [start, end], [50, 0], {
extrapolateRight: "clamp",
easing: Easing.out(Easing.ease),
});
const disappearingY = interpolate(frame, [end + 10, end + 30], [0, -50], {
extrapolateRight: "clamp",
easing: Easing.out(Easing.ease),
});
return (
<span
style={{
transform: `translateY(${
frame > end && !isLast ? disappearingY : appearingY
}px)`,
}}
className="ml-4 uppercase font-bold absolute top-0 z-10 left-0"
>
{children}
</span>
);
};
const skills = [
"React",
"Svelte",
"Next js",
"Nodejs",
"Javascript",
"Frontend",
];
const About: FunctionComponent<AboutProps> = () => {
const frame = useCurrentFrame();
const welcomeOpacity = interpolate(
frame,
[5 + 40 * skills.length, 5 + 40 * skills.length + 30],
[0, 1]
);
return (
<AbsoluteFill className="bg-black flex-1 items-center justify-center">
<div className="text-white relative">
<div className="text-4xl">
Hello, This is <span className="text-lime-400">Duc Mai</span>
</div>
<div className="text-3xl flex overflow-hidden">
<span className="text-red-700 uppercase font-bold">
proficient in
</span>
<div className="relative">
<span className="opacity-0 w-64 inline-block">Long word</span>
{skills.map((sk, index) => (
<Text
key={index}
index={index}
isLast={index === skills.length - 1}
>
{sk}
</Text>
))}
</div>
</div>
<div
style={{ opacity: welcomeOpacity }}
className="absolute top-40 border p-4 rounded-md border-lime-500 text-lg"
>
Welcome to my world{" "}
<span className="underline text-lime-400">
https://hittaducmai.se
</span>
</div>
</div>
</AbsoluteFill>
);
};
export default About; |
const express = require("express");
const { check, validationResult } = require("express-validator");
const usersRepo = require("../../repositories/users");
const signupTemplate = require("../../views/admin/auth/signup");
const signinTemplate = require("../../views/admin/auth/signin");
const {
requireEmail,
requirePassword,
requirePasswordConfirmation,
} = require("./validators");
const router = express.Router();
router.get("/signup", (req, res) => {
res.send(signupTemplate({ req }));
});
router.post(
"/signup",
[requireEmail, requirePassword, requirePasswordConfirmation],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.send(signupTemplate({ req, errors }));
}
const { email, password, passwordConfirmation } = req.body;
// create a usre in our repo to represent this person
const user = await usersRepo.create({ email, password });
// Store the id that user inside the users cookie
req.session.userId = user.id;
res.send("Account created!");
}
);
router.get("/signout", (req, res) => {
req.session = null;
res.send("You are logged out");
});
router.get("/signin", (req, res) => {
res.send(signinTemplate());
});
router.post("/signin", async (req, res) => {
const { email, password } = req.body;
const user = await usersRepo.getOneBy({ email });
if (!user) {
return res.send("Email is not found!");
}
const validPassword = await usersRepo.comparePasswords(
user.password,
password
);
if (!validPassword) {
return res.send("Invalid password");
}
req.session.userId = user.id;
res.send("You are signd in");
});
module.exports = router; |
import torch
import torch.nn as nn
from functools import partial
import clip
from einops import rearrange, repeat
from transformers import CLIPTokenizer, CLIPTextModel
import kornia
from ldm.dream.devices import choose_torch_device
from ldm.modules.x_transformer import (
Encoder,
TransformerWrapper,
) # TODO: can we directly rely on lucidrains code and simply add this as a reuirement? --> test
def _expand_mask(mask, dtype, tgt_len=None):
"""
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"""
bsz, src_len = mask.size()
tgt_len = tgt_len if tgt_len is not None else src_len
expanded_mask = (
mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
)
inverted_mask = 1.0 - expanded_mask
return inverted_mask.masked_fill(
inverted_mask.to(torch.bool), torch.finfo(dtype).min
)
def _build_causal_attention_mask(bsz, seq_len, dtype):
# lazily create causal attention mask, with full attention between the vision tokens
# pytorch uses additive attention mask; fill with -inf
mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype)
mask.fill_(torch.tensor(torch.finfo(dtype).min))
mask.triu_(1) # zero out the lower diagonal
mask = mask.unsqueeze(1) # expand mask
return mask
class AbstractEncoder(nn.Module):
def __init__(self):
super().__init__()
def encode(self, *args, **kwargs):
raise NotImplementedError
class ClassEmbedder(nn.Module):
def __init__(self, embed_dim, n_classes=1000, key='class'):
super().__init__()
self.key = key
self.embedding = nn.Embedding(n_classes, embed_dim)
def forward(self, batch, key=None):
if key is None:
key = self.key
# this is for use in crossattn
c = batch[key][:, None]
c = self.embedding(c)
return c
class TransformerEmbedder(AbstractEncoder):
"""Some transformer encoder layers"""
def __init__(
self,
n_embed,
n_layer,
vocab_size,
max_seq_len=77,
device=choose_torch_device(),
):
super().__init__()
self.device = device
self.transformer = TransformerWrapper(
num_tokens=vocab_size,
max_seq_len=max_seq_len,
attn_layers=Encoder(dim=n_embed, depth=n_layer),
)
def forward(self, tokens):
tokens = tokens.to(self.device) # meh
z = self.transformer(tokens, return_embeddings=True)
return z
def encode(self, x):
return self(x)
class BERTTokenizer(AbstractEncoder):
"""Uses a pretrained BERT tokenizer by huggingface. Vocab size: 30522 (?)"""
def __init__(
self, device=choose_torch_device(), vq_interface=True, max_length=77
):
super().__init__()
from transformers import (
BertTokenizerFast,
) # TODO: add to reuquirements
# Modified to allow to run on non-internet connected compute nodes.
# Model needs to be loaded into cache from an internet-connected machine
# by running:
# from transformers import BertTokenizerFast
# BertTokenizerFast.from_pretrained("bert-base-uncased")
try:
self.tokenizer = BertTokenizerFast.from_pretrained(
'bert-base-uncased', local_files_only=False
)
except OSError:
raise SystemExit(
"* Couldn't load Bert tokenizer files. Try running scripts/preload_models.py from an internet-conected machine."
)
self.device = device
self.vq_interface = vq_interface
self.max_length = max_length
def forward(self, text):
batch_encoding = self.tokenizer(
text,
truncation=True,
max_length=self.max_length,
return_length=True,
return_overflowing_tokens=False,
padding='max_length',
return_tensors='pt',
)
tokens = batch_encoding['input_ids'].to(self.device)
return tokens
@torch.no_grad()
def encode(self, text):
tokens = self(text)
if not self.vq_interface:
return tokens
return None, None, [None, None, tokens]
def decode(self, text):
return text
class BERTEmbedder(AbstractEncoder):
"""Uses the BERT tokenizr model and add some transformer encoder layers"""
def __init__(
self,
n_embed,
n_layer,
vocab_size=30522,
max_seq_len=77,
device=choose_torch_device(),
use_tokenizer=True,
embedding_dropout=0.0,
):
super().__init__()
self.use_tknz_fn = use_tokenizer
if self.use_tknz_fn:
self.tknz_fn = BERTTokenizer(
vq_interface=False, max_length=max_seq_len
)
self.device = device
self.transformer = TransformerWrapper(
num_tokens=vocab_size,
max_seq_len=max_seq_len,
attn_layers=Encoder(dim=n_embed, depth=n_layer),
emb_dropout=embedding_dropout,
)
def forward(self, text, embedding_manager=None):
if self.use_tknz_fn:
tokens = self.tknz_fn(text) # .to(self.device)
else:
tokens = text
z = self.transformer(
tokens, return_embeddings=True, embedding_manager=embedding_manager
)
return z
def encode(self, text, **kwargs):
# output of length 77
return self(text, **kwargs)
class SpatialRescaler(nn.Module):
def __init__(
self,
n_stages=1,
method='bilinear',
multiplier=0.5,
in_channels=3,
out_channels=None,
bias=False,
):
super().__init__()
self.n_stages = n_stages
assert self.n_stages >= 0
assert method in [
'nearest',
'linear',
'bilinear',
'trilinear',
'bicubic',
'area',
]
self.multiplier = multiplier
self.interpolator = partial(
torch.nn.functional.interpolate, mode=method
)
self.remap_output = out_channels is not None
if self.remap_output:
print(
f'Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing.'
)
self.channel_mapper = nn.Conv2d(
in_channels, out_channels, 1, bias=bias
)
def forward(self, x):
for stage in range(self.n_stages):
x = self.interpolator(x, scale_factor=self.multiplier)
if self.remap_output:
x = self.channel_mapper(x)
return x
def encode(self, x):
return self(x)
class FrozenCLIPEmbedder(AbstractEncoder):
"""Uses the CLIP transformer encoder for text (from Hugging Face)"""
def __init__(
self,
version='openai/clip-vit-large-patch14',
device=choose_torch_device(),
max_length=77,
):
super().__init__()
self.tokenizer = CLIPTokenizer.from_pretrained(
version, local_files_only=False
)
self.transformer = CLIPTextModel.from_pretrained(
version, local_files_only=False
)
self.device = device
self.max_length = max_length
self.freeze()
def embedding_forward(
self,
input_ids=None,
position_ids=None,
inputs_embeds=None,
embedding_manager=None,
) -> torch.Tensor:
seq_length = (
input_ids.shape[-1]
if input_ids is not None
else inputs_embeds.shape[-2]
)
if position_ids is None:
position_ids = self.position_ids[:, :seq_length]
if inputs_embeds is None:
inputs_embeds = self.token_embedding(input_ids)
if embedding_manager is not None:
inputs_embeds = embedding_manager(input_ids, inputs_embeds)
position_embeddings = self.position_embedding(position_ids)
embeddings = inputs_embeds + position_embeddings
return embeddings
self.transformer.text_model.embeddings.forward = (
embedding_forward.__get__(self.transformer.text_model.embeddings)
)
def encoder_forward(
self,
inputs_embeds,
attention_mask=None,
causal_attention_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
output_attentions = (
output_attentions
if output_attentions is not None
else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
return_dict = (
return_dict
if return_dict is not None
else self.config.use_return_dict
)
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
hidden_states = inputs_embeds
for idx, encoder_layer in enumerate(self.layers):
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
layer_outputs = encoder_layer(
hidden_states,
attention_mask,
causal_attention_mask,
output_attentions=output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
return hidden_states
self.transformer.text_model.encoder.forward = encoder_forward.__get__(
self.transformer.text_model.encoder
)
def text_encoder_forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
embedding_manager=None,
):
output_attentions = (
output_attentions
if output_attentions is not None
else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
return_dict = (
return_dict
if return_dict is not None
else self.config.use_return_dict
)
if input_ids is None:
raise ValueError('You have to specify either input_ids')
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
hidden_states = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
embedding_manager=embedding_manager,
)
bsz, seq_len = input_shape
# CLIP's text model uses causal mask, prepare it here.
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
causal_attention_mask = _build_causal_attention_mask(
bsz, seq_len, hidden_states.dtype
).to(hidden_states.device)
# expand attention_mask
if attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
attention_mask = _expand_mask(
attention_mask, hidden_states.dtype
)
last_hidden_state = self.encoder(
inputs_embeds=hidden_states,
attention_mask=attention_mask,
causal_attention_mask=causal_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
last_hidden_state = self.final_layer_norm(last_hidden_state)
return last_hidden_state
self.transformer.text_model.forward = text_encoder_forward.__get__(
self.transformer.text_model
)
def transformer_forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
embedding_manager=None,
):
return self.text_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
embedding_manager=embedding_manager,
)
self.transformer.forward = transformer_forward.__get__(
self.transformer
)
def freeze(self):
self.transformer = self.transformer.eval()
for param in self.parameters():
param.requires_grad = False
def forward(self, text, **kwargs):
batch_encoding = self.tokenizer(
text,
truncation=True,
max_length=self.max_length,
return_length=True,
return_overflowing_tokens=False,
padding='max_length',
return_tensors='pt',
)
tokens = batch_encoding['input_ids'].to(self.device)
z = self.transformer(input_ids=tokens, **kwargs)
return z
def encode(self, text, **kwargs):
return self(text, **kwargs)
class FrozenCLIPTextEmbedder(nn.Module):
"""
Uses the CLIP transformer encoder for text.
"""
def __init__(
self,
version='ViT-L/14',
device=choose_torch_device(),
max_length=77,
n_repeat=1,
normalize=True,
):
super().__init__()
self.model, _ = clip.load(version, jit=False, device=device)
self.device = device
self.max_length = max_length
self.n_repeat = n_repeat
self.normalize = normalize
def freeze(self):
self.model = self.model.eval()
for param in self.parameters():
param.requires_grad = False
def forward(self, text):
tokens = clip.tokenize(text).to(self.device)
z = self.model.encode_text(tokens)
if self.normalize:
z = z / torch.linalg.norm(z, dim=1, keepdim=True)
return z
def encode(self, text):
z = self(text)
if z.ndim == 2:
z = z[:, None, :]
z = repeat(z, 'b 1 d -> b k d', k=self.n_repeat)
return z
class FrozenClipImageEmbedder(nn.Module):
"""
Uses the CLIP image encoder.
"""
def __init__(
self,
model,
jit=False,
device=choose_torch_device(),
antialias=False,
):
super().__init__()
self.model, _ = clip.load(name=model, device=device, jit=jit)
self.antialias = antialias
self.register_buffer(
'mean',
torch.Tensor([0.48145466, 0.4578275, 0.40821073]),
persistent=False,
)
self.register_buffer(
'std',
torch.Tensor([0.26862954, 0.26130258, 0.27577711]),
persistent=False,
)
def preprocess(self, x):
# normalize to [0,1]
x = kornia.geometry.resize(
x,
(224, 224),
interpolation='bicubic',
align_corners=True,
antialias=self.antialias,
)
x = (x + 1.0) / 2.0
# renormalize according to clip
x = kornia.enhance.normalize(x, self.mean, self.std)
return x
def forward(self, x):
# x is assumed to be in range [-1,1]
return self.model.encode_image(self.preprocess(x))
if __name__ == '__main__':
from ldm.util import count_params
model = FrozenCLIPEmbedder()
count_params(model, verbose=True) |
---
title: Diseño de Páginas Web para Agencias de Seguros en Elche
date: '2023-10-04'
tags: ['Diseño web', 'Agencias de Seguros', 'Elche']
draft: false
banner : diseño_paginas_web_agenciasdeseguros
fondoBanner : diseño_pagina_web_elche
summary: El diseño de páginas web se ha convertido en una herramienta fundamental para las agencias de seguros en la ciudad de Elche. Con el crecimiento constante de la industria, es crucial que las agencias aprovechen todas las oportunidades digitales para aumentar su visibilidad y generar ventas.
---
import Cta from "../../../components/Cta.astro";
import CtaBot from "../../../components/CtaBot.astro";
import GifSeo from "../../../components/GifSeo.astro";
import Gmaps from "../../../components/Gmaps.astro";
import Video from "../../../components/Video.astro";
## Diseño de Páginas Web para Agencias de Seguros en Elche
El diseño de páginas web se ha convertido en una herramienta fundamental para las agencias de seguros en la ciudad de Elche. Con el crecimiento constante de la industria, es crucial que las agencias aprovechen todas las oportunidades digitales para aumentar su visibilidad y generar ventas.
### Motivos por los que una Agencia de Seguros en Elche necesita una página web:
1. **Mayor alcance**: Una página web permite que las agencias de seguros en Elche sean accesibles las 24 horas del día, los 7 días de la semana, llegando a un público más amplio que busca información y servicios en línea.
2. **Exposición en buscadores**: El diseño web adecuado y optimizado para SEO coloca a las agencias de seguros en Elche en los primeros resultados de búsqueda, aumentando la visibilidad y la posibilidad de ser encontrados por clientes potenciales.
3. **Mejora la credibilidad**: Contar con una página web profesional transmite confianza en los servicios que ofrece la agencia de seguros en Elche. Los usuarios confían en las empresas con una presencia en línea sólida y actualizada.
4. **Facilidad de contacto**: Una página web bien estructurada y diseñada proporciona a los clientes potenciales una forma sencilla de ponerse en contacto con la agencia de seguros en Elche, aumentando las posibilidades de conversión en ventas.
### Beneficios del diseño web para una Agencia de Seguros en Elche:
1. **Diferenciación**: El diseño web personalizado y atractivo permite a las agencias de seguros en Elche destacarse de la competencia y mostrar su propuesta de valor única.
2. **Información clara**: Una página web bien diseñada y organizada proporciona a los clientes toda la información necesaria sobre los servicios y productos ofrecidos por la agencia de seguros en Elche, facilitando la toma de decisiones.
3. **Optimización para dispositivos móviles**: Con un diseño web responsivo, las agencias de seguros en Elche aseguran una experiencia de usuario óptima tanto en computadoras de escritorio como en dispositivos móviles, adaptándose a las preferencias y comportamientos de los usuarios.
4. **Aumento de conversiones**: Una página web profesionalmente diseñada y optimizada para la conversión convierte a los visitantes en clientes, generando ventas y ayudando al crecimiento del negocio de la agencia de seguros en Elche.
Elche, conocida como la ciudad de las palmeras, cuenta con una rica tradición agrícola y un creciente sector empresarial. El diseño de páginas web para agencias de seguros en Elche contribuye al desarrollo digital de la ciudad, combinando la industria de los seguros con las nuevas tecnologías.
No pierda la oportunidad de expandir su negocio de seguros en Elche a través de una página web atractiva y efectiva. Contacte con nosotros en 'Élite Webs' y le ayudaremos a alcanzar el éxito en el mundo digital.
<GifSeo />
<Cta />
## Elementos clave del diseño web exitoso
- Diseño atractivo y profesional.
- Navegación intuitiva y fácil de usar.
- Contenido relevante y bien estructurado.
- Velocidad de carga rápida.
- Adaptabilidad a diferentes dispositivos y pantallas.
- Optimización para motores de búsqueda.
- Integración de formularios de contacto y herramientas de seguimiento.
En Élite Webs somos expertos en el diseño y desarrollo de páginas web para agencias de seguros en Elche. Sabemos que estos elementos son fundamentales para convertir las visitas en ventas, y por eso nos especializamos en ofrecer soluciones que cumplan con todos ellos.
## Cómo nuestro servicio de diseño web puede ayudar
Nuestro equipo de diseñadores y desarrolladores se encargará de crear una página web única y personalizada para tu agencia de seguros en Elche. Nos aseguramos de que el diseño sea atractivo y profesional, captando la atención del visitante desde el primer momento.
Además, nos enfocamos en una navegación intuitiva y fácil de usar, para que los usuarios encuentren rápidamente la información que están buscando. Organizamos el contenido de manera clara y estructurada, resaltando los servicios y productos que tu agencia ofrece.
La velocidad de carga de la página web también es un factor crucial. Estudios han demostrado que los usuarios abandonan un sitio si tarda más de 3 segundos en cargar. Por eso, optimizamos el rendimiento de tu sitio para que cargue rápidamente, evitando que los visitantes se vayan sin convertir.
Además, nos aseguramos de que tu página web se adapte a distintos dispositivos y pantallas, ya que cada vez más personas utilizan sus móviles y tablets para navegar por internet. Esto garantiza una experiencia óptima tanto para los usuarios que buscan seguros desde su ordenador como para aquellos que lo hacen desde su móvil.
Por último, aplicamos técnicas de optimización SEO para mejorar el posicionamiento de tu página web en los motores de búsqueda. Esto te ayudará a aumentar la visibilidad y atraer más visitas de calidad, incrementando así las oportunidades de venta.
## Conclusión: la importancia de una página web de calidad y por qué contratarnos
En este competitivo mercado de agencias de seguros en Elche, tener una página web de calidad es esencial para destacar y atraer clientes potenciales. Una página web bien diseñada y optimizada no solo captará la atención de los visitantes, sino que también generará confianza y credibilidad en tu agencia.
En Élite Webs somos conscientes de la importancia de este factor y, por eso, nos esforzamos en crear páginas web que se destaquen por encima de la competencia. Nuestra experiencia y conocimientos nos permiten ofrecerte un servicio de diseño web que cumplirá con tus expectativas y te ayudará a convertir visitas en ventas.
No dejes que tu agencia de seguros en Elche se quede atrás. Contrata nuestros servicios de diseño web y destaca en este mercado tan competitivo. Contacta con nosotros hoy mismo y descubre cómo podemos ayudarte a alcanzar el éxito en línea.
<Video />
<CtaBot job='Agencias de Seguros' city='Elche'/>
<Gmaps query='Elche+españa+maps' /> |
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from "react";
import { Link } from "react-router-dom";
import { Form, Formik } from 'formik'
import * as yup from 'yup'
import { SelectField, TextInput } from "../components/CustomFormFields";
import YupPassword from "yup-password";
YupPassword(yup);
const Register = () => {
return (
<div className=" grid">
<div className="grid h-screen content-center gap-2 md:content-around">
<div className="hidden place-self-end p-5 font-mulish md:inline">
<p className="text-sm">
Already have an account?{" "}
<Link to="register" className="font-semibold text-blue-600">
Login
</Link>
</p>
</div>
<div className="mx-auto mt-20 w-11/12 px-4 xs:w-10/12 sm:mt-0 sm:px-6 md:w-7/12 md:pb-10 lg:w-5/12">
<div className="mx-auto">
<h1 className="font-poppins text-xl font-semibold md:text-2xl">
Get Your Smart Fuel Wallet.
</h1>
<h1 className="mt-2 font-mulish text-md font-semibold text-gray-600 md:text-lg">
It's Cashless & Cardless.
</h1>
</div>
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
phoneNumber: '',
password: '',
selectoption: ''
}}
validationSchema={
yup.object().shape({
firstName: yup
.string()
.required('Required'),
lastName: yup
.string()
.required('Required'),
email: yup
.string()
.email('Invalid email address')
.required('Required'),
phoneNumber: yup
.string()
.required('Required'),
password: yup.string()
.min(6, "Password must be 6 characters or more")
.minSymbols(0)
.minNumbers(1, 'Password requires at least 1 Number')
.minUppercase(1, 'Password requires at least 1 uppercase character')
.required('Required')
,
selectoption: yup
.string()
.required('Required')
.oneOf(
['option-1', 'option-2', 'option-3', 'option-3'],
'Invalid Option Type'
),
})
}
onSubmit={(values, { setSubmitting }) => {
setSubmitting(true)
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
<Form className="mx-auto mt-4 mb-0 space-y-4">
{/* Row 1 */}
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
{/* Firstname */}
<TextInput
label="First Name"
id="firstName"
name="firstName"
type="text"
/>
{/* Lastname */}
<TextInput
label="Last Name"
id="lastName"
name="lastName"
type="text"
/>
</div>
{/* Row 2 */}
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
{/* Email Address */}
<TextInput
label="Email address"
id="email"
name="email"
type="email"
/>
{/* Phone Number */}
<TextInput
label="Phone Number"
id="phoneNumber"
name="phoneNumber"
type="text"
/>
</div>
{/* Select */}
<SelectField name="selectoption">
<option value="">---select type----</option>
<option value="option-1">Option 1</option>
<option value="option-2">Option 2</option>
<option value="option-3">Option 3</option>
<option value="option-4">Option 4</option>
</SelectField>
{/* Password */}
<TextInput
label="Password"
id="password"
name="password"
type="password"
/>
<button
type="submit"
className="inline-block w-full rounded-lg bg-blue-500 px-5 py-3 font-poppins text-sm font-medium text-white shadow-md shadow-blue-200"
>
Register
</button>
<div className="px-4 text-center font-mulish">
<p className="text-xs font-medium md:text-sm">
By registering, I agree to Carviva{" "}
<a href="#" className="text-blue-600 underline">
Terms of Service{" "}
</a>
and{" "}
<a href="#" className="text-blue-600 underline">
PrivacyPolicy
</a>
.
</p>
</div>
<div className="mb-10 place-self-end pb-10 text-center font-mulish sm:pb-0 md:hidden">
<p className="text-xs md:text-sm">
Already have an account?{" "}
<Link to="register" className="font-semibold text-blue-600">
Login
</Link>
</p>
</div>
</Form>
</Formik>
</div>
</div>
</div>
);
};
export default Register; |
import { Component } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import {
ButtonModule,
CardModule,
FormModule,
TooltipModule,
} from '@coreui/angular-pro';
import { cilCommentBubble, cilLockLocked, cilUser } from '@coreui/icons';
import { IconModule } from '@coreui/icons-angular';
import { AuthServerProvider } from 'src/app/services/auth/auth-jwt.service';
import { StateStorageService } from 'src/app/services/auth/stateStorage.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
imports: [
CardModule,
FormModule,
ButtonModule,
IconModule,
TooltipModule,
ReactiveFormsModule,
RouterLink,
],
standalone: true,
})
export class LoginComponent {
icons = { cilUser, cilLockLocked, cilCommentBubble };
constructor(
private authServerProvider: AuthServerProvider,
private stateStorage: StateStorageService,
private route: Router
) {}
loginForm = new FormGroup({
username: new FormControl('', [
Validators.required,
Validators.minLength(4),
Validators.maxLength(20),
]),
password: new FormControl('', Validators.required),
rememberMe: new FormControl(true),
});
submitFormLogin() {
console.log(this.loginForm.value);
this.username?.markAsDirty();
this.password?.markAsDirty();
if (this.loginForm.valid) {
this.authServerProvider.login(this.loginForm.getRawValue()).subscribe({
next: (response) => {
this.route.navigate(['/'])
alert("Đăng nhạp thành công!!!")
},
error: (err) => {
alert(`Cannot Login my App: ${err}`);
},
});
}
}
get username() {
return this.loginForm.get('username');
}
get password() {
return this.loginForm.get('password');
}
get rememberMe() {
return this.loginForm.get('rememberMe');
}
} |
import React from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import { render, screen } from '@testing-library/react';
import FlyoutVideo from '../flyout-video';
describe('FlyoutVideo', () => {
const sampleURL = 'https://www.example.com/sample-video';
beforeEach(() => {
render(<FlyoutVideo url={sampleURL} />);
});
it('Renders the iframe container', async () => {
const iframeElementContainer = screen.getByTestId('dt_flyout_video_container');
expect(iframeElementContainer).toBeInTheDocument();
});
it('Renders the iframe with the provided URL', async () => {
const iframeElement = screen.getByTestId('dt_flyout_video');
expect(iframeElement).toHaveAttribute('src', sampleURL);
});
it('Renders the iframe with the correct attributes', () => {
const iframeElement = screen.getByTestId('dt_flyout_video');
expect(iframeElement).toHaveAttribute('frameBorder', '0');
expect(iframeElement).toHaveAttribute('allow', 'accelerometer; encrypted-media; gyroscope; picture-in-picture');
expect(iframeElement).toHaveAttribute('allowFullScreen', '');
expect(iframeElement).toHaveAttribute('width', '100%');
});
it('Renders the iframe with the correct class', () => {
const iframeElement = screen.getByTestId('dt_flyout_video');
expect(iframeElement).toHaveClass('flyout__video');
});
}); |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cart - Pharmacy manager</title>
<meta name="description" content="Pharmacy manager">
<!-- style -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/main.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<!-- scripts -->
<script src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">
<b>Pharmacy manager</b>
</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="divider-vertical"></li>
<li><a href="/pharmacies"><span class="glyphicon glyphicon-plus-sign"></span> Pharmacies</a></li>
<li class="divider-vertical"></li>
<li><a href="/products"><span class="glyphicon glyphicon-tint"></span> Products</a></li>
<li class="divider-vertical"></li>
<li><a href="/users"><span class="glyphicon glyphicon-user"></span> Users</a></li>
<li class="divider-vertical"></li>
<li><a href="/orders"><span class="glyphicon glyphicon-th-list"></span> Orders</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="divider-vertical"></li>
<li class="active"><a href="/cart"><span class="glyphicon glyphicon-shopping-cart"></span> Cart</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="col-md-12">
<br><br><br><br>
<h1>Cart</h1>
<hr>
<table class="table table-hover" id="table-cart">
<thead>
<th>Name</th>
<th>Description</th>
<th>Price (€)</th>
<th>Pharmacy</th>
<th>Quantity</th>
</thead>
<tbody>
<!--Products will be here-->
</tbody>
</table>
<p class="less-bigger" id="total-price"></p>
<hr>
<div class="row">
<div class="col-md-6">
<b>Email:</b><input name="email" id="email" type="email" class="form-control" placeholder="Enter a registered email for reserving or purchasing your cart" />
</div>
</div>
<div class="row">
<br>
<div class="col-md-6">
<div class="form-group">
<button type="submit" class="btn btn-danger delete-cart">
<span class="glyphicon glyphicon-trash"></span> Empty cart
</button>
<button type="submit" class="btn btn-primary reserve-cart">
<span class="glyphicon glyphicon-tag"></span> Reserve products
</button>
<button type="submit" class="btn btn-success buy-cart">
<span class="glyphicon glyphicon-euro"></span> Buy products
</button>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$( document ).ready(function()
{
GET_cart();
setTimeout(function(){
console.log(parse_cart());
}, 100);
});
var CART_REST_URL = "/rest/cart";
var ORDERS_REST_URL = "/rest/orders";
function GET_cart()
{
$.ajax({
url: CART_REST_URL,
type: 'GET',
dataType: 'json',
success: function (products)
{
// console.log( products );
var total_price = 0;
$.each(products, function (key, value)
{
var new_row = '<tr class="product_row">'+
'<td class="name">' + value.name + '</td>'+
'<td class="description">'+ value.description + '</td>'+
'<td class="price">'+ value.price + '</td>' +
'<td class="pharmacy">'+ value.pharmacy + '</td>'+
'<td class="quantity">'+ value.quantity + '</td>';
jQuery("#table-cart > tbody:last-child").append(new_row);
total_price += value.price * value.quantity;
});
$("#total-price").html("<b>Total price:</b> " + total_price + "€");
},
error: function (request, message, error)
{
console.log("Error performing GET on " + PRODUCT_REST_URL);
}
});
}
$(document).on('click', '.delete-cart', function ()
{
$.ajax({
url: CART_REST_URL,
type: 'DELETE',
success: function ()
{
location.reload();
},
error: function (request, message, error)
{
console.log("Error performing DELETE on " + CART_REST_URL);
}
});
});
$(document).on('click', '.reserve-cart', function ()
{
var email = $('input[name=email]').val();
var cart = parse_cart();
if (email)
{
$.ajax({
url: ORDERS_REST_URL,
type: 'POST',
data: {'email': email, 'type':'Reserve', 'cart': cart},
success: function (response)
{
if ( response.status == 404 ) // user not found
{
alert( "⚠️ " + response.message + " ⚠️");
}
else if ( response.status == 409 ) // cart empty
{
alert( "⚠️ " + response.message + " ⚠️\n");
}
else
{
alert("Products reserved correctly!")
location.reload();
}
},
error: function (request, message, error)
{
console.log("Error performing POST on " + ORDERS_REST_URL);
}
});
}
else
{
alert("Email cannot be empty")
}
});
$(document).on('click', '.buy-cart', function ()
{
var email = $('input[name=email]').val();
var cart = parse_cart();
if (email)
{
$.ajax({
url: ORDERS_REST_URL,
type: 'POST',
data: {'email': email, 'type':'Purchase', 'cart': cart},
success: function (response)
{
if ( response.status == 404 ) // user not found
{
alert( "⚠️ " + response.message + " ⚠️");
}
else if ( response.status == 409 ) // cart empty
{
alert( "⚠️ " + response.message + " ⚠️\n");
}
else
{
alert("Products purchased correctly!")
location.reload();
}
},
error: function (request, message, error)
{
console.log("Error performing POST on " + ORDERS_REST_URL);
}
});
}
else
{
alert("Email cannot be empty")
}
});
function parse_cart()
{
var products = "";
$("#table-cart tbody tr").each(function(i, tr)
{
$this = $(this);
var name = $this.find(".name").html();
var description = $this.find(".description").html();
var price = $this.find(".price").html();
var pharmacy = $this.find(".pharmacy").html();
var quantity = $this.find(".quantity").html();
var parsed_product = name +'. '+ description + '. '+ pharmacy +'. '+price +'EUR x '+ quantity + 'u;';
products += parsed_product;
});
return products;
}
</script>
</html> |
## --------------------------- \
# import best-performing first-stage SOM and extract codebook vectors
prototypes = readr::read_rds(here("data/som_files/som_files_full/som1_nrc_22_iter_40.rds"))
prototypes = prototypes$codes[[1]] |> as.data.frame()
# set range of second-stage SOM following range suggested by Eisenack et al. 2021
r_min = 2
r_max = 30
# convert prototypes to matrix to feed to som function
som_input = prototypes |> as.matrix()
## --------------------------- \
# Loop through second-stage SOM iterations
for (n_clust in seq(r_min, r_max, by = 1)) {
# n_clust = 4
message("starting SOM size ", n_clust)
# data frame to store SOM quality metrics for each lattice size
quality_df = data.frame(
iter = seq(1:120), # 20 iterations per SOM lattice
quant = rep(NA), # all other parts of this df as same as in first-stage SOM
varra = rep(NA),
k_l = rep(NA),
topo = rep(NA),
db_x = rep(NA),
nrc = rep(n_clust)
)
# loop through each SOM iteration per lattice size
for (i in 1:(quality_df$iter |> max())) {
# i = 1
# create the SOM
som_iter = supersom(som_input,
grid = somgrid(xdim = n_clust, ydim = 1, topo="hexagonal"),
rlen = 500,
alpha = c(0.05, 0.01),
keep.data = TRUE,
cores = 8)
## write out SOM data to recall in case the iteration is thebest performing SOM
write_rds(x = som_iter,
file = paste0(here("data/som_files/som2_files/som2_nclust_"), n_clust, "_iter_", i, ".rds"))
# calculate SOM quality metrics
som_quality = aweSOM::somQuality(som = som_iter, traindat = som_input)
cluster_quality = clusterSim::index.DB(x = som_input, cl = som_iter$unit.classif)
# assign SOM quality metrics to data frame
quality_df$quant[i] = som_quality$err.quant[1] |> as.numeric() |> round(5)
quality_df$varra[i] = som_quality$err.varratio[1] |> as.numeric() |> round(5)
quality_df$k_l[i] = som_quality$err.kaski[1] |> as.numeric() |> round(5)
quality_df$topo[i] = som_quality$err.topo[1] |> as.numeric() |> round(5)
quality_df$topo[i] = som_quality$err.topo[1] |> as.numeric() |> round(5)
quality_df$db_x[i] = cluster_quality$DB[1] |> as.numeric() |> round(5)
message("... ", i, "/", n_clust)
}
# write the full SOM quality data frame to file for the SOM lattice size
write_rds(x = quality_df,
file = paste0(here("data/som_files/som2_performance/som2_nclust_"), n_clust, ".rds"))
message("SOM iterations for nclust=", n_clust, " has completed")
} |
Linear Next Benchmark
Linear Next is a comprehensive benchmark designed to fairly compare various efficient transformer architectures. This project evaluates different approaches including linear attention, sparse attention, and other model structures under identical training conditions and datasets.
Overview
The benchmark aims to provide an unbiased comparison of efficient transformer variants by ensuring all models are trained with the same datasets, hyperparameters, and evaluation metrics. This allows for a clear understanding of the relative strengths and weaknesses of each approach.
Datasets
The benchmark utilizes a diverse collection of high-quality datasets:
General Text
- DCLM-pro: A large-scale dataset containing diverse text from various domains, designed for general language modeling tasks.
- Cosmopedia-v2: A curated corpus of high-quality web content covering a wide range of topics, with emphasis on educational and informative material.
- Fineweb-edu: A filtered collection of educational web content, focusing on instructional and academic text from reliable sources.
Code
- The Stack v2: A comprehensive collection of source code spanning multiple programming languages, designed to train models on code understanding and generation tasks.
Mathematics
- Finemath: A specialized dataset containing mathematical content, including equations, proofs, and mathematical explanations across various difficulty levels.
Reasoning
- Natural Reasoning: A dataset focused on logical reasoning, problem-solving, and inference tasks, designed to improve models' reasoning capabilities.
Methodology
All models in the Linear Next benchmark are evaluated using identical:
- Training datasets and data mixing ratios
- Optimization parameters
- Hardware configurations
- Evaluation metrics
This controlled environment ensures that performance differences can be attributed to the architectural differences rather than training conditions.
Results
Detailed benchmark results, including training curves, inference speed, memory usage, and performance metrics across different tasks, are available in the project repository.
- Downloads last month
- 1,046