text
stringlengths 184
4.48M
|
|---|
#!/usr/bin/python3
"""Review Api"""
from flask import jsonify, abort, make_response, request
from api.v1.views import app_views
from models.place import Place
from models.user import User
from models.review import Review
from models import storage
@app_views.route("/places/<place_id>/reviews", methods=['GET'],
strict_slashes=False)
def get_reviews(place_id):
"""retrieve list of all reviews of a place"""
if not storage.get(Place, place_id):
abort(404)
reviews = storage.all(Review).values()
all_reviews = []
for review in reviews:
if review.place_id == place_id:
all_reviews.append(review.to_dict())
return jsonify(all_reviews)
@app_views.route("/reviews/<review_id>", methods=['GET'],
strict_slashes=False)
def get_review(review_id):
"""Retrieve specific review"""
review = storage.get(Review, review_id)
if not review:
abort(404)
return jsonify(review.to_dict())
@app_views.route("/reviews/<review_id>", methods=['DELETE'],
strict_slashes=False)
def delete_review(review_id):
"""Deletes a review"""
review = storage.get(Review, review_id)
if not review:
abort(404)
storage.delete(review)
storage.save()
return make_response(jsonify({}), 200)
@app_views.route("/places/<place_id>/reviews", methods=['POST'],
strict_slashes=False)
def create_review(place_id):
"""Create a new Place"""
if not storage.get(Place, place_id):
abort(404)
content_type = request.headers.get('Content-Type')
if content_type != 'application/json' or not request.get_json():
abort(400, 'Not a JSON')
review_data = request.get_json()
if 'user_id' not in review_data:
abort(400, 'Missing user_id')
elif not storage.get(User, review_data['user_id']):
abort(404)
elif 'text' not in review_data:
abort(400, 'Missing text')
review_data['place_id'] = place_id
new_review = Review(**review_data)
new_review.save()
return make_response(jsonify(new_review.to_dict()), 201)
@app_views.route("/reviews/<review_id>", methods=['PUT'],
strict_slashes=False)
def update_review(review_id):
"""Update a Review"""
review = storage.get(Review, review_id)
if not review:
abort(404)
content_type = request.headers.get('Content-Type')
if content_type != 'application/json' or not request.get_json():
abort(400, 'Not a JSON')
review_data = request.get_json()
ignored_keys = ['id', 'created_at', 'updated_at', 'user_id', 'place_id']
for key, value in review_data.items():
if key not in ignored_keys:
setattr(review, key, value)
storage.save()
return make_response(jsonify(review.to_dict()), 200)
|
"use client";
import React, { useState, useEffect } from "react";
import { motion, AnimatePresence} from "framer-motion";
import { ComplexNavbar } from "./navbar1";
export default function Navbar() {
const [isScrolling, setIsScrolling] = useState(false);
const handleScroll = () => {
if (window.scrollY >= 72) {
setIsScrolling(true);
} else {
setIsScrolling(false);
}
};
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return (
<>
<AnimatePresence>
{isScrolling ? (
<NavbarScroll isScrolling={isScrolling} />
) : (
<NavbarFixed isScrolling={isScrolling} />
)}
</AnimatePresence>
</>
);
}
function NavbarFixed({ isScrolling }:{isScrolling:boolean}) {
return (
<nav className="sticky top-[72px] z-10 flex justify-between w-full bg-[#737373]">
<ComplexNavbar isScroll={isScrolling} />
</nav>
);
}
function NavbarScroll({ isScrolling }:{isScrolling:boolean}) {
return (
<motion.nav
key={1}
initial="initial"
animate={isScrolling ? "animate" : "initial"}
exit="exit"
variants={NavAnimations}
className="fixed z-10 flex justify-between w-full main_nav"
>
<ComplexNavbar isScroll={isScrolling} />
</motion.nav>
);
}
const NavAnimations = {
initial: {
y: -50,
// x: "-50%",
opacity: 0,
},
animate: {
y: 0,
opacity: 1,
transition: {
type: "ease-in-out",
damping: 10,
stiffness: 100,
},
},
exit: {
y: -50,
opacity: 0,
},
};
|
import cv2
import os
def extract_first_frame(video_path):
"""
Extract the first frame from a video file and save it as an image.
Parameters:
video_path (str): The path of the video file.
"""
directory, filename = os.path.split(video_path)
name, _ = os.path.splitext(filename)
capture = cv2.VideoCapture(video_path)
success, image = capture.read()
if success:
cv2.imwrite(os.path.join(directory, f"{name}.jpg"), image)
async def process_photo(photo, new_date):
"""
Process and download a photo from iCloud.
Parameters:
photo (obj): The photo object to download.
new_date (datetime): The date for naming the downloaded file.
"""
date_string = f"{new_date.year}-{new_date.month}-{new_date.day}"
if not os.path.exists(date_string):
os.makedirs(date_string)
extension = photo.versions['original']['filename'].split(".")[1]
filename = f"{date_string}/{new_date.month}-{new_date.day}-{new_date.year}-{new_date.hour}-{new_date.minute}-{new_date.second}-{new_date.microsecond}.{extension}"
if "heic" in photo.filename.lower():
download = photo.download('medium')
video_name = filename.replace('.HEIC', '.mov')
with open(video_name, 'wb') as file:
file.write(download.raw.read())
extract_first_frame(video_name)
else:
download = photo.download('original')
with open(filename, 'wb') as file:
file.write(download.raw.read())
|
# multiAgents.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from util import manhattanDistance
from game import Directions
import random, util
import math
from game import Agent
class ReflexAgent(Agent):
"""
A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers.
"""
def getAction(self, gameState):
"""
You do not need to change this method, but you're welcome to.
getAction chooses among the best options according to the evaluation function.
Just like in the previous project, getAction takes a GameState and returns
some Directions.X for some X in the set {NORTH, SOUTH, WEST, EAST, STOP}
"""
# Collect legal moves and successor states
legalMoves = gameState.getLegalActions()
# Choose one of the best actions
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestIndices) # Pick randomly among the best
"Add more of your code here if you want to"
return legalMoves[chosenIndex]
def evaluationFunction(self, currentGameState, action):
"""
Design a better evaluation function here.
The evaluation function takes in the current and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
The code below extracts some useful information from the state, like the
remaining food (newFood) and Pacman position after moving (newPos).
newScaredTimes holds the number of moves that each ghost will remain
scared because of Pacman having eaten a power pellet.
Print out these variables to see what you're getting, then combine them
to create a masterful evaluation function.
"""
# Useful information you can extract from a GameState (pacman.py)
successorGameState = currentGameState.generatePacmanSuccessor(action)
newPos = successorGameState.getPacmanPosition()
newFood = successorGameState.getFood()
newGhostStates = successorGameState.getGhostStates()
newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]
"*** YOUR CODE HERE ***"
return successorGameState.getScore()
def scoreEvaluationFunction(currentGameState):
"""
This default evaluation function just returns the score of the state.
The score is the same one displayed in the Pacman GUI.
This evaluation function is meant for use with adversarial search agents
(not reflex agents).
"""
return currentGameState.getScore()
class MultiAgentSearchAgent(Agent):
"""
This class provides some common elements to all of your
multi-agent searchers. Any methods defined here will be available
to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.
You *do not* need to make any changes here, but you can if you want to
add functionality to all your adversarial search agents. Please do not
remove anything, however.
Note: this is an abstract class: one that should not be instantiated. It's
only partially specified, and designed to be extended. Agent (game.py)
is another abstract class.
"""
def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):
self.index = 0 # Pacman is always agent index 0
self.evaluationFunction = util.lookup(evalFn, globals())
self.depth = int(depth)
class MinimaxAgent(MultiAgentSearchAgent):
"""
Your minimax agent (question 2)
"""
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.generateSuccessor(agentIndex, action):
Returns the successor game state after an agent takes an action
gameState.getNumAgents():
Returns the total number of agents in the game
gameState.isWin():
Returns whether or not the game state is a winning state
gameState.isLose():
Returns whether or not the game state is a losing state
"""
"*** YOUR CODE HERE ***"
#util.raiseNotDefined()
# Root-level action-selection
actions = gameState.getLegalActions(0)
best_action = ''
score = -10000000000
# Iterates all legal actions
for action in actions:
next_state = gameState.generateSuccessor(0, action)
# Iterates the actions of the ghosts
# Number of agents minus pacman minus index 0
for i in range(1, gameState.getNumAgents() - 1):
min_value = self.min_value(next_state, 0, i)
# If value generated is larger than current score, value and action is updated
if min_value > score:
score = min_value
best_action = next_state
return best_action
# Returns the maximum value
def max_value(self, gameState, depth):
# Defining variables for depth, the max-value and legal actions for max-agents
# For every function-call, depth is increased by 1
current_depth = depth + 1
agent_actions = gameState.getLegalActions(0)
max_v = -10000000000
# Checking if function is in a terminal state
if self.terminal_state(gameState, current_depth):
return self.evaluationFunction(gameState)
#For-loop for choosing best action for the max-agent (pacman)
for action in agent_actions:
for i in range(1, gameState.getNumAgents() - 1):
succ = gameState.generateSuccessor(0, action)
max_v = max(max_v, self.min_value(succ, current_depth, i))
return max_v
# Return the minimum-value
def min_value(self, gameState, depth, ghost_index):
# Defining variables for depth, the min-value, legal actions for min-agents
current_depth = depth + 1
ghost_actions = gameState.getLegalActions(ghost_index)
min_v = 10000000000
# Checking if function is in a terminal state
if self.terminal_state(gameState, current_depth):
return self.evaluationFunction(gameState)
# For-loop that goes through all actions of the ghosts
for action in ghost_actions:
succ = gameState.generateSuccessor(ghost_index, action)
min_v = min(min_v, self.max_value(succ, current_depth))
return min_v
#Terminal-state fuction, returns true if agent is in a terminal state
def terminal_state(self, gameState, depth):
if gameState.isWin() or gameState.isLose() or self.depth == depth:
return True
else:
return False
class AlphaBetaAgent(MultiAgentSearchAgent):
"""
Your minimax agent with alpha-beta pruning (question 3)
"""
def getAction(self, gameState):
"""
Returns the minimax action using self.depth and self.evaluationFunction
"""
"*** YOUR CODE HERE ***"
#util.raiseNotDefined()
actions = gameState.getLegalActions(0)
score = -10000000000
best_action = ''
alpha = -10000000000
beta = 10000000000
# Iterates all legal actions
for action in actions:
succ = gameState.generateSuccessor(0, action)
# Goes through actions of the ghosts
for i in range(1, gameState.getNumAgents()-1):
min_value = self.minValue(succ, 1, i, alpha, beta)
# Update action and score values if value of score is larger than value of the min_value
if min_value > score:
best_action = action
score = min_value
# Return the best action if min_value is larger than beta-value
if min_value > beta:
return best_action
#Set new alpha value
alpha = max(alpha, score)
return best_action
def maxValue(self, gameState, depth, alpha, beta):
# Defining variables for depth, alpha, beta, the max-value and legal actions for the max-agent
current_depth = depth + 1
current_alpha = alpha
agent_actions = gameState.getLegalActions(0)
max_v = -10000000000
# Checking if the max-agent is in a terminal state
if self.terminal_state(gameState, current_depth):
return self.evaluationFunction(gameState)
# For-loop for choosing best action for the max-agent (pacman)
for action in agent_actions:
succ = gameState.generateSuccessor(0, action)
for i in range(1, gameState.getNumAgents()-1):
max_v = max(max_v, self.minValue(succ, current_depth, i, current_alpha, beta))
# If max-value is larger than beta, we return the max value
if max_v >= beta:
return max_v
# Else, we update or alpha value to the larges of the current alpha and our max-value
else:
current_alpha = max(current_alpha, max_v)
return max_v
def minValue(self, gameState, depth, ghost_index, alpha, beta):
# Defining variables for depth, beta, the min-value and legal actions for min-agents
current_depth = depth + 1
current_beta = beta
min_v = 10000000000
ghost_actions = gameState.getLegalActions(ghost_index)
# Checking if the function is in a terminal state
if self.terminal_state(gameState, current_depth):
return self.evaluationFunction(gameState)
# For-loop for choosing best actions for the min-agents (ghosts)
for action in ghost_actions:
succ = gameState.generateSuccessor(ghost_index, action)
min_v = min(min_v, self.maxValue(succ, current_depth, alpha, current_beta))
# Checks if the min-value is smaller or equal than the alpha
if min_v <= alpha:
return min_v
# Else, update beta to min of current-beta and min-value
else:
current_beta = min(current_beta, min_v)
return min_v
# Terminal-state fuction, returns true if agent is in a terminal state
def terminal_state(self, gameState, depth):
if gameState.isWin() or gameState.isLose() or self.depth == depth:
return True
else:
return False
class ExpectimaxAgent(MultiAgentSearchAgent):
"""
Your expectimax agent (question 4)
"""
def getAction(self, gameState):
"""
Returns the expectimax action using self.depth and self.evaluationFunction
All ghosts should be modeled as choosing uniformly at random from their
legal moves.
"""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
def betterEvaluationFunction(currentGameState):
"""
Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
evaluation function (question 5).
DESCRIPTION: <write something here so we know what you did>
"""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
# Abbreviation
better = betterEvaluationFunction
|
import React, { useCallback, useState } from 'react';
import { Link } from 'react-router-dom';
import {
Avatar,
Box,
Divider,
IconButton,
Menu,
MenuItem,
Tooltip,
Typography
} from '@mui/material';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
const UserMenu = ({ avatar }) => {
const [anchorElUser, setAnchorElUser] = useState(null);
const handleCloseUserMenu = () => {
setAnchorElUser(null);
};
const handleOpenUserMenu = (event) => {
setAnchorElUser(event.currentTarget);
};
return (
<Box sx={{ flexGrow: 0 }}>
<Tooltip title='Open Settings'>
<IconButton onClick={handleOpenUserMenu}>
{avatar ? <Avatar alt='avatar' src={avatar} />
: <Avatar>
<AccountCircleIcon />
</Avatar>
}
</IconButton>
</Tooltip>
<Menu
sx={{ mt: '45px' }}
id="menu-appbar"
anchorEl={anchorElUser}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={Boolean(anchorElUser)}
onClose={handleCloseUserMenu}
>
<Link to='/user/profile'>
<MenuItem>
<Typography textAlign="center">Proflie</Typography>
</MenuItem>
</Link>
<Divider />
<MenuItem>
<Typography textAlign="center">Sign Out</Typography>
</MenuItem>
</Menu>
</Box>
);
};
export default UserMenu;
|
<!DOCTYPE HTML>
<!--
Title:
Мультимаршрут: getBounds карты при добавлении мультимаршрута
Description:
Проверка работы метода getBounds карты при добавлении мультимаршрута.
Памятка по терминам: https://wiki.yandex-team.ru/eva/testing/Projects/maps-api/
Components:
multiRouter
Estimated time:
120000
Precondition:
Открыть ссылку ${currentPagePath}
Step:
Action:
Осмотреть карту и элементы на ней.
Expectation:
Карта отобразилась корректно со слоем - спутниковый снимок.
Сверху в контейнере кнопки "Первый маршрут", "Второй маршрут", "Третий маршрут", "bounds".
Step:
Action:
Выполнить клик в кнопку "Первый маршрут".
Expectation:
Происходит смена спана, на спане появляется мультимаршрут ОТ из 3 точек.
Step:
Action:
Выполнить клик в кнопку "Второй маршрут".
Expectation:
Происходит смена спана, на спане появляется мультимаршрут авто из 2 точек.
Step:
Action:
Выполнить быстрый клик в "Первый маршрут" после появления маршрута клик во "Второй маршрут".
Expectation:
При клике спан карты корректно меняется, на спанах появляются маршруты из шагов 1 и 2, карта отображается корректно.
Step:
Action:
Выполнить клик в кнопку "Третий маршрут".
Expectation:
Со спана карты пропадает маршрут, спан карты не меняется.
Step:
Action:
Выполнить клик в кнопку "bounds".
Expectation:
Происходит смена спана на спан СПб, на карте мультимаршрут ОТ, имеются метик общественного транспорта, альтернативные нитки.
-->
<html>
<head>
<title>2.1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="../../helper.js"></script>
<script type=text/javascript>
Api('init');
function init(ymaps) {
ymaps = ym;
// если несколько раз переключиться с маршрута на маршрут,
// карта начинает выставлять неправильные координаты
__log__('если несколько раз переключиться с маршрута на маршрут,');
__log__('карта начинает выставлять неправильные координаты');
var map = myMap = new ymaps.Map('map', {
center: [55.739625, 37.54120],
zoom: 7,
type: "yandex#satellite",
controls: [],
behaviors: ['default']
}),
multiRoute1 = new ymaps.multiRouter.MultiRoute({
referencePoints: ["метро Киевская", "метро Охотный ряд", "метро Площадь Революции", "Москва, улица Льва Толстого"],
params: {
viaIndexes: [1],
routingMode: 'masstransit'
}
}, {
boundsAutoApply: true,
viaPointIconRadius: 10,
pinIconRadius: 5,
wayPointStartIconColor: "#80C257",
wayPointFinishIconColor: "#8470FF",
wayPointIconColor: "black",
routeStrokeWidth: 2,
routeActiveStrokeWidth: 6,
routeStrokeColor: "000088",
routeActiveStrokeColor: "#FF4500",
pinIconFillColor: "#BFEFFF",
viaPointIconFillColor: "#FFD39B",
transportMarkerIconColor: "#FFE4E1"
}),
multiRoute2 = new ymaps.multiRouter.MultiRoute({
referencePoints: ["Москва, улица Лобачевского", "Москва, метро Академическая"]
}, {
boundsAutoApply: true,
preset: "islands#multiRouterBig",
routeStrokeWidth: 2,
routeActiveStrokeWidth: 4,
routeStrokeColor: "000088",
routeActiveStrokeColor: "ff0011"
}),
multiRoute3 = new ymaps.multiRouter.MultiRoute({
referencePoints: ["комендантский 30к1", "пискареский пр 2к2"],
params: {
routingMode: 'masstransit'
}
}, {
boundsAutoApply: false,
preset: "islands#multiRouterBig",
routeStrokeWidth: 2,
routeActiveStrokeWidth: 4,
routeStrokeColor: "000088",
routeActiveStrokeColor: "ff0011"
}),
buttonRoute1 = new ymaps.control.Button({
data: {
content: "Первый маршрут"
},
options: {
maxWidth: 300
}
}),
buttonRoute2 = new ymaps.control.Button({
data: {
content: "Второй маршрут"
},
options: {
maxWidth: 300
}
}),
buttonRoute3 = new ymaps.control.Button({
data: {
content: "Третий маршрут"
},
options: {
maxWidth: 300
}
}),
buttonBounds = new ymaps.control.Button({
data: {
content: "bounds"
},
options: {
maxWidth: 300
}
});
myMap.controls
.add(buttonBounds)
.add(buttonRoute3)
.add(buttonRoute2)
.add(buttonRoute1);
buttonRoute1.events.add('select', function () {
if (multiRoute2.getMap() || multiRoute3.getMap()) {
buttonRoute2.deselect();
buttonRoute3.deselect();
}
myMap.geoObjects.add(multiRoute1);
});
buttonRoute2.events.add('select', function () {
if (multiRoute1.getMap() || multiRoute3.getMap()) {
buttonRoute1.deselect();
buttonRoute3.deselect();
}
myMap.geoObjects.add(multiRoute2);
});
buttonRoute3.events.add('select', function () {
if (multiRoute1.getMap() || multiRoute2.getMap()) {
buttonRoute1.deselect();
buttonRoute2.deselect();
}
myMap.geoObjects.add(multiRoute3);
});
buttonRoute1.events.add('deselect', function () {
myMap.geoObjects.remove(multiRoute1);
});
buttonRoute2.events.add('deselect', function () {
myMap.geoObjects.remove(multiRoute2);
});
buttonRoute3.events.add('deselect', function () {
myMap.geoObjects.remove(multiRoute3);
});
buttonBounds.events.add('click', function () {
map.setBounds(multiRoute3.getBounds());
});
addGrid(map);
var log = new Log();
}
</script>
</head>
<body style="position: relative; padding: 0; margin: 0;">
<div id="map" style="height: 512px; width: 512px;"></div>
</body>
</html>
|
# Copyright 2022 Bedford Freeman & Worth Pub Grp LLC DBA Macmillan Learning.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#' Serialize a Luz Model
#'
#' Parameters for luz models are held in pointers that become invalid if you
#' save and then load the model. To avoid issues with those pointers, we add a
#' `serialized_state_dict` parameter to the `luz_model` object, which holds safe
#' versions of the parameter values.
#'
#' @param luz_model A `luz_model` object to update.
#'
#' @return The `luz_model` with `serialized_state_dict` attached.
#' @keywords internal
.serialize_luz_model <- function(luz_model) {
# We serialize just the state_dict. That will allow us to "repair" a loaded
# model in place.
con <- rawConnection(raw(), open = "wr")
torch::torch_save(luz_model$model$state_dict(), con)
on.exit({close(con)}, add = TRUE)
luz_model$serialized_state_dict <- rawConnectionValue(con)
return(luz_model)
}
#' Check Pointers in a Luz Model
#'
#' The `.check$ptr` tensor in a `bert_linear` model allows us to check whether
#' the model contains invalid pointers. If it does, restore the
#' `serialized_state_dict` into the model (in-place).
#'
#' @param luz_model The model to check.
#'
#' @return The model, invisibly.
#' @keywords internal
.check_luz_model_serialization <- function(luz_model) {
if (.is_null_external_pointer(luz_model$model$.check$ptr)) {
.unserialize_luz_model(luz_model)
}
return(invisible(luz_model))
}
#' Check if a Pointer is NULL
#'
#' This comes from https://stackoverflow.com/a/27350487/3297472 via
#' https://github.com/mlverse/tabnet/blob/main/R/hardhat.R#L494
#'
#' @param pointer A pointer to check.
#'
#' @return A logical indicating whether that pointer is NULL (and thus invalid).
#' @keywords internal
.is_null_external_pointer <- function(pointer) {
a <- attributes(pointer)
attributes(pointer) <- NULL
out <- identical(pointer, methods::new("externalptr"))
attributes(pointer) <- a
return(out)
}
#' Restore a Serialized State Dictionary
#'
#' This function reloads the state dictionary in place.
#'
#' @param luz_model The model to fix.
#'
#' @return The model, invisibly.
#' @keywords internal
.unserialize_luz_model <- function(luz_model) {
# Do this in place.
con <- rawConnection(luz_model$serialized_state_dict)
on.exit({close(con)}, add = TRUE)
luz_model$model$load_state_dict(
torch::torch_load(con)
)
return(invisible(luz_model))
}
|
// let API_KEY = "1a88bad1187ec4b382d7cef114365e79"
// let city = "Jabalpur";
// async function apiWeatherCall() {
// let apidata = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`)
// let data = await apidata.json()
// console.log(data);
// let newPara = document.createElement('p')
// newPara.textContent = `${data?.main?.temp.toFixed(2)} degC`
// document.body.appendChild(newPara)
// }
const userTab = document.querySelector("[data-userWeather]")
const searchTab = document.querySelector("[data-searchWeather]")
const userContainer = document.querySelector(".weather-container")
const grantAccessContainer = document.querySelector(".grant-location-container")
const searchForm = document.querySelector("[data-searchForm]")
const loadingScreen = document.querySelector(".loading-container")
const userInfoContainer = document.querySelector(".user-info-container")
// by default current tab will be user tab when page is reloaded
let currentTab = userTab
currentTab.classList.add("current-tab")
const API_KEY = "7f87e635de64b0dd6904bcb35452a777"
getfromSessionStorage();
function switchTab(clickedTab) {
if(clickedTab != currentTab)
{
currentTab.classList.remove("current-tab")
currentTab = clickedTab;
currentTab.classList.add("current-tab")
if(!searchForm.classList.contains("active")) {
// if search form container is invisible if yes make it visible
userInfoContainer.classList.remove("active")
grantAccessContainer.classList.remove("active")
searchForm.classList.add("active")
}
else {
// it means we're on search tab close make it invisible and make weather tab visible to switch between tabs
searchForm.classList.remove("active")
userInfoContainer.classList.remove("active")
// we're now in weather tab, make weather visible check local storage first
// in local storage if we have stored coords we can display weather of user on tab switch
getfromSessionStorage()
}
}
}
userTab.addEventListener("click", () => {
switchTab(userTab);
})
searchTab.addEventListener("click", () => {
switchTab(searchTab)
})
// check if coordinates are already present in local storage
function getfromSessionStorage() {
let localCoordinates = sessionStorage.getItem("user-coordinates");
if(!localCoordinates) {
// if local coordinates not found, which means coordinates arent stored in system
grantAccessContainer.classList.add("active")
}
else {
// if they are
const coordinates = JSON.parse(localCoordinates)
fetchUserWeatherInfo(coordinates)
}
}
async function fetchUserWeatherInfo(coordinates) {
const {lat, lon} = coordinates;
// const part = {
// current
// ,minutely
// ,hourly
// ,daily
// ,alerts};
// make grant access container invisible
grantAccessContainer.classList.remove("active")
// make loading screeen visible
loadingScreen.classList.add("active")
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`
);
let data = await response.json()
loadingScreen.classList.remove("active")
userInfoContainer.classList.add("active")
renderWeatherData(data)
}
catch(err) {
loadingScreen.classList.remove("active")
}
}
function renderWeatherData(data) {
// fetch all dynamic elements
const cityName = document.querySelector("[data-cityName]")
const countryIcon = document.querySelector("[data-countryIcon]")
const desc = document.querySelector("[data-weatherDesc]")
const weatherIcon = document.querySelector("[data-weatherIcon]")
const temp =document.querySelector("[data-temp]")
const windspeed = document.querySelector("[data-windspeed]")
const humidity = document.querySelector("[data-humidity]")
const cloudiness = document.querySelector("[data-cloudiness]")
// chaining operator - used to target json property
cityName.innerText = data?.name;
countryIcon.src = `https://flagcdn.com/144x108/${data?.sys?.country.toLowerCase()}.png`;
desc.innerText = data?.weather?.[0]?.description;
weatherIcon.src = `http://openweathermap.org/img/w//${data?.weather?.[0]?.icon}.png`
temp.innerText = `${data?.main?.temp} °C`;
windspeed.innerText = `${data?.wind?.speed} m/s`;
humidity.innerText = `${data?.main?.humidity}%`;
cloudiness.innerText = `${data?.clouds?.all}%`;
}
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
//HW - show an alert for no gelolocation support available
}
}
function showPosition(position) {
const userCoordinates = {
lat: position.coords.latitude,
lon: position.coords.longitude,
}
sessionStorage.setItem("user-coordinates", JSON.stringify(userCoordinates));
fetchUserWeatherInfo(userCoordinates);
}
const grantAccessButton = document.querySelector("[data-grantAccess]");
grantAccessButton.addEventListener("click", getLocation);
const searchInput = document.querySelector("[data-searchInput]");
searchForm.addEventListener("submit", (e) => {
e.preventDefault();
let cityName = searchInput.value;
if(cityName === "")
return;
else
fetchSearchWeatherInfo(cityName);
})
async function fetchSearchWeatherInfo(cityName) {
let city = cityName;
// console.log(city);
loadingScreen.classList.add("active");
userInfoContainer.classList.remove("active");
grantAccessContainer.classList.remove("active");
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`
);
// console.log(response);
const data = await response.json();
// console.log(data);
loadingScreen.classList.remove("active");
userInfoContainer.classList.add("active");
renderWeatherData(data);
}
catch(err) {
//hW
}
}
|
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from './Button';
import { DiaryItem } from './DiaryItem';
interface optionType {
value: string
name: string
}
const sortList: optionType[] = [
{ value: 'lastest', name: '최신순' },
{ value: 'oldest', name: '오래된 순' }
]
const filterList: optionType[] = [
{ value: 'all', name: '전부' },
{ value: 'good', name: '좋은 감정만' },
{ value: 'bad', name: '안좋은 감정만' }
]
const Menu = React.memo(({ value, onChange, optionList }: any) => {
return (
<select value={value} onChange={(e) => onChange(e.target.value)} className='ControlMenu'>
{optionList.map((data: optionType, index: number) =>
<option key={`value_${index}`} value={data.value}>{data.name}</option>
)}
</select>
);
});
export const DiaryList = ({ list }: any) => {
const navi = useNavigate();
const [sortType, setSortType] = useState('lastest');
const [filterType, setFilterType] = useState('all');
const getDiaryList = () => {
const filterCallBack = (item: any) => {
if (filterType === 'good') {
return parseInt(item.emotion) <= 3;
} else {
return parseInt(item.emotion) > 3;
}
}
const compare = (a: any, b: any) => {
const a_date: any = new Date(a.date).getTime();
const b_date: any = new Date(b.date).getTime();
if (sortType === 'lastest') {
return b_date > a_date ? 1 : -1;
} else {
return a_date > b_date ? 1 : -1;
}
}
const diaryList = JSON.parse(JSON.stringify(list));
const fillteredList = (filterType === 'all') ? diaryList : diaryList.filter((el: any) => filterCallBack(el));
const sortedList = fillteredList.sort(compare);
return sortedList;
};
return (
<div className='DiaryList'>
<div className='menu_wrapper'>
<div className='left_col'>
<Menu
value={sortType}
onChange={setSortType}
optionList={sortList}
/>
<Menu
value={filterType}
onChange={setFilterType}
optionList={filterList}
/>
</div>
<div className='right_col'>
<Button
text='새 일기 쓰기'
type='positive'
onClick={() => navi('/new')}
/>
</div>
</div>
{
getDiaryList().map((data: any) => (
<DiaryItem key={`diaryItem_${data.id}`} {...data} />
))
}
</div>
);
}
DiaryList.defaultProps = {
list: []
};
|
import { FormikValues, useFormikContext } from 'formik';
import TextInput from '../TextInput';
import { FormErrorMessage } from '.';
interface FormFieldProps {
name: string;
label: string;
type: string;
width: string;
}
function FormField({ name, type, width, label, ...otherTextInputProps }: FormFieldProps) {
const { setFieldTouched, setFieldValue, values, errors, touched } =
useFormikContext<FormikValues>();
return (
<div className=''>
<TextInput
type={type}
width={width}
label={label}
onChange={(event: any) => setFieldValue(name, event.target.value)}
value={values[name]}
onBlur={() => setFieldTouched(name)}
{...otherTextInputProps}
/>
{errors[name] && touched[name] ? null : <h6> </h6>}
<FormErrorMessage error={errors[name]} visible={touched[name]} />
</div>
);
}
export default FormField;
|
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
public class ConferenceServiceImpl extends UnicastRemoteObject implements ConferenceService {
private List<Participant> participants;
protected ConferenceServiceImpl() throws RemoteException {
participants = new ArrayList<>();
}
@Override
public void registerParticipant(Participant participant) throws RemoteException {
participants.add(participant);
}
@Override
public List<Participant> getParticipants() throws RemoteException {
return participants;
}
@Override
public void exportParticipantsToXML(String fileName) throws RemoteException {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
Element rootElement = doc.createElement("participants");
doc.appendChild(rootElement);
for (Participant participant : participants) {
Element participantElement = doc.createElement("participant");
Element name = doc.createElement("name");
name.appendChild(doc.createTextNode(participant.getName()));
participantElement.appendChild(name);
Element email = doc.createElement("email");
email.appendChild(doc.createTextNode(participant.getEmail()));
participantElement.appendChild(email);
rootElement.appendChild(participantElement);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(fileName));
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void importParticipantsFromXML(String fileName) throws RemoteException {
try {
File inputFile = new File(fileName);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
participants.clear();
NodeList nList = doc.getElementsByTagName("participant");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String name = eElement.getElementsByTagName("name").item(0).getTextContent();
String email = eElement.getElementsByTagName("email").item(0).getTextContent();
Participant participant = new Participant();
participant.setName(name);
participant.setEmail(email);
participants.add(participant);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
def keep_ints(cond, n):
"""Print out all integers 1..i..n where cond(i) is true
>>> def is_even(x):
... # Even numbers have remainder 0 when divided by 2.
... return x % 2 == 0
>>> keep_ints(is_even, 5)
2
4
"""
k = 1
while k <= n:
if cond(k):
print(k)
k += 1
def make_keeper(n):
"""Returns a function which takes one parameter cond and prints out
all integers 1..i..n where calling cond(i) returns True.
>>> def is_even(x):
... # Even numbers have remainder 0 when divided by 2.
... return x % 2 == 0
>>> make_keeper(5)(is_even)
2
4
"""
def take_func(f):
k = 1
while k <= n:
if f(k):
print(k)
k += 1
return take_func
def print_delayed(x):
"""Return a new function. This new function, when called,
will print out x and return another function with the same
behavior.
>>> f = print_delayed(1)
>>> f = f(2)
1
>>> f = f(3)
2
>>> f = f(4)(5)
3
4
>>> f("hi")
5
<function print_delayed> # a function is returned
"""
def delay_print(y):
print(x)
return print_delayed(y)
return delay_print
|
<?php
namespace ChrisComposer\Tool\Cmd;
use App\Util\Cmd\CmdForLinux;
use App\Util\Cmd\CmdForWin;
/**
* 命令工具
*/
class CmdTool
{
protected $options = [];
/**
* @var static 单例模式
*/
protected static $instance;
public function __construct($options = [])
{
$this->envCheck();
$this->options = $options;
}
/**
* 单例模式
*/
public static function getInstance()
{
if (static::$instance instanceof static) {
return static::$instance;
}
static::$instance = new static();
return static::$instance;
}
/**
* 环境检查
* @author Chris Yu <chrisyu@crabapple.top> 2024/2/25
*/
protected function envCheck()
{
if (!function_exists('proc_open')) {
throw new \Exception('请开启 proc_open 函数');
}
}
/**
* 获取工具
* @return \app\Util\Cmd\CmdInterface
* @author Chris Yu <chrisyu@crabapple.top> 2024/1/15
*/
public function getTool()
{
if ($this->isWin()) {
return CmdForWin::getInstance();
}
else {
return CmdForLinux::getInstance($this->options);
}
}
/**
* 是否 windows 系统
* @return bool
* @author Chris Yu <chrisyu@crabapple.top> 2024/1/15
*/
public function isWin()
{
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
return true;
}
else {
return false;
}
}
}
|
import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { selectIsAdmin } from '../../store/slices/authSlice';
import { TariffsList } from '../../components/Tariff/List/List';
import { TariffAdminHeader } from '../../components/Tariff/AdminHeader/AdminHeader';
import {
useAddTariffMutation,
useDeleteTariffMutation,
useGetAllTariffsQuery,
useGetCurrentTariffQuery,
useSelectTariffMutation,
useUpdateTariffMutation,
useUpdateTariffsOrderMutation,
} from '../../api/tariffs';
import { Tariff, TariffOrder } from '../../@types/entities/Tariff';
import Modal from '../../shared/Global/Modal/Modal';
import { eventBus, EventTypes } from '../../services/EventBus';
import { NotificationType } from '../../components/GlobalNotifications/GlobalNotifications';
import './paymentForm.scss';
import { NotificationButtons } from './NotificationButtons';
import { useGetInvoiceByProductUuidQuery } from '../../api/invoice';
import {
errorAddTariffNotification,
errorChangeTariffOrderNotification,
errorDeleteTariffNotification,
errorUpdateTariffNotification,
successAddTariffNotification,
successChangeTariffOrderNotification,
successDeleteTariffNotification,
successUpdateTariffNotification,
} from './tariffNotifications';
import { CreateTariffDto } from '../../@types/dto/tariffs/create.dto';
import { DeleteTariffDto } from '../../@types/dto/tariffs/delete.dto';
import { UpdateTariffDto } from '../../@types/dto/tariffs/update.dto';
import { EditTariffModal } from '../../components/Tariff/EditModal/EditModal';
const Tariffs = () => {
// FIXME: refetch
const {
data: tariffs,
isLoading,
isError,
refetch: refetchTariffs,
} = useGetAllTariffsQuery();
const [selectTariff, { isLoading: isSelectTariffLoading }] =
useSelectTariffMutation();
const [isMobile, setIsMobile] = useState(false);
const isAdmin = useSelector(selectIsAdmin);
const [editedTariff, setEditedTariff] = useState<Tariff | null>(null);
const [isOrderEdit, setIsOrderEdit] = useState<boolean>(false);
const [tariffOrderList, setTariffOrderList] = useState<TariffOrder[]>([]);
const [isEditTariffModalOpen, setIsEditTariffModalOpen] =
useState<boolean>(false);
useEffect(() => {
if (document.documentElement.clientWidth <= 500) {
setIsMobile(true);
}
}, []);
const [paymentForm, setPaymentForm] = useState('');
const [addTariff] = useAddTariffMutation();
const [updateTariff] = useUpdateTariffMutation();
const [deleteTariff] = useDeleteTariffMutation();
const [updateTariffsOrders] = useUpdateTariffsOrderMutation();
const { data: currentTariff } = useGetCurrentTariffQuery();
const { data: invoice } = useGetInvoiceByProductUuidQuery(
currentTariff?.uuid || '',
{
skip: !currentTariff?.uuid,
},
);
const resetTariffOrder = () => {
const orders =
tariffs?.map((tariff, id) => ({
tariffId: tariff.id,
order: tariff.order || 1,
})) || [];
setTariffOrderList(orders);
};
const onSelectTariff = async (tariff: Tariff) => {
try {
if (
invoice?.paymentForm &&
!currentTariff?.expiredAt &&
currentTariff?.tariff.id === tariff.id
) {
return setPaymentForm(invoice.paymentForm);
}
const { tinkoffForm } = await selectTariff(tariff.id).unwrap();
setPaymentForm(tinkoffForm);
} catch (error) {
console.log(error);
eventBus.emit(EventTypes.notification, {
message: 'Произошла ошибка',
type: NotificationType.DANGER,
});
}
};
const onDiscardChangeTariff = () => {
//
};
const handleSelectTariff = async (tariff: Tariff) => {
if (currentTariff) {
const isTariffCurrent = currentTariff.tariffId === tariff.id;
const title = isTariffCurrent
? 'Оплатить тариф?'
: `У вас уже есть тариф "${currentTariff.tariff.title}". Вы хотите заменить его?`;
const type = isTariffCurrent ? 'extend' : 'replace';
eventBus.emit(EventTypes.notification, {
title,
message: (
<NotificationButtons
type={type}
onChange={() => onSelectTariff(tariff)}
onDiscard={onDiscardChangeTariff}
/>
),
type: NotificationType.INFO,
});
return;
}
onSelectTariff(tariff);
};
const onClickAddTariff = () => {
setIsEditTariffModalOpen(true);
setEditedTariff(null);
};
const onClickEditTariff = (tariff: Tariff) => {
setIsEditTariffModalOpen(true);
setEditedTariff(tariff);
};
const onCancelEditOrder = () => {
resetTariffOrder();
setIsOrderEdit(false);
};
const closeEditTariffModal = () => {
setIsEditTariffModalOpen(false);
setEditedTariff(null);
};
const handleAddTariff = async (data: CreateTariffDto) => {
try {
await addTariff(data).unwrap();
successAddTariffNotification();
closeEditTariffModal();
} catch (error) {
console.log(error);
errorAddTariffNotification();
}
};
const handleUpdateTariff = async (data: UpdateTariffDto) => {
try {
await updateTariff(data).unwrap();
successUpdateTariffNotification(data.title);
closeEditTariffModal();
} catch (error) {
console.log(error);
errorUpdateTariffNotification(data.title);
}
};
const handleDeleteTariff = async (data: DeleteTariffDto) => {
try {
await deleteTariff({ id: data.id }).unwrap();
successDeleteTariffNotification();
closeEditTariffModal();
} catch (error) {
console.log(error);
errorDeleteTariffNotification();
}
};
const handleSaveOrder = async () => {
const updateOrdersData = {
ordersList: tariffOrderList,
};
try {
await updateTariffsOrders(updateOrdersData).unwrap();
successChangeTariffOrderNotification();
setIsOrderEdit(false);
} catch (error) {
errorChangeTariffOrderNotification();
}
};
useEffect(() => {
resetTariffOrder();
}, [tariffs]);
return (
<>
{isAdmin && (
<TariffAdminHeader
isOrderEdit={isOrderEdit}
onCancelEditOrder={onCancelEditOrder}
onAddTariff={onClickAddTariff}
onEditOrder={() => setIsOrderEdit(true)}
onSaveOrder={handleSaveOrder}
/>
)}
<TariffsList
tariffs={tariffs}
isLoading={isLoading}
isSelectLoading={isSelectTariffLoading}
isError={isError}
isMobile={isMobile}
tariffOrderList={tariffOrderList}
isEditableOrder={isOrderEdit}
onEdit={onClickEditTariff}
onSelect={handleSelectTariff}
refetchTariffs={refetchTariffs}
setTariffOrderList={setTariffOrderList}
/>
<EditTariffModal
mode={editedTariff ? 'edit' : 'create'}
isOpened={isEditTariffModalOpen}
tariff={editedTariff}
onCreate={handleAddTariff}
onUpdate={handleUpdateTariff}
onDelete={() => handleDeleteTariff({ id: editedTariff?.id || -1 })}
onClose={closeEditTariffModal}
/>
<Modal
isOpened={!!paymentForm}
close={() => {
setPaymentForm('');
}}
>
<div>
<p style={{ marginBottom: '15px' }}>Выберите способ оплаты:</p>
<div dangerouslySetInnerHTML={{ __html: paymentForm }} />
</div>
</Modal>
</>
);
};
export default Tariffs;
|
import { fireEvent, render, screen, within } from "@testing-library/react"
import userEvent from "@testing-library/user-event";
import SearchForm from "../SearchForm"
const mockFunc = jest.fn();
describe('SearchFrom', () => {
it("renders", () => {
const { asFragment } = render(<SearchForm callback={mockFunc} />);
expect(asFragment).toMatchSnapshot();
});
it("calls the callback with correct coctail name parameters", () => {
render(<SearchForm callback={mockFunc} />);
const findBtn = screen.getByRole('button', { name: /find/i });
const nameInput = screen.getByTestId('coctailname');
const view = within(nameInput).getByRole("textbox");
userEvent.type(view, 'martini');
fireEvent.click(findBtn);
expect(mockFunc).toHaveBeenCalled();
expect(mockFunc.mock.calls[0][0]).toBe('martini');
expect(mockFunc.mock.calls[0][1]).toBe(true);
});
it('calls the callback with correct coctail ingredient parameters', () => {
render(<SearchForm callback={mockFunc} />);
const findBtn = screen.getByRole('button', { name: /find/i });
const nameInput = screen.getByTestId('coctailingredient');
const view = within(nameInput).getByRole("textbox");
userEvent.type(view, 'vermouth');
fireEvent.click(findBtn);
expect(mockFunc).toHaveBeenCalled();
expect(mockFunc.mock.calls[0][0]).toBe('vermouth');
expect(mockFunc.mock.calls[0][1]).toBe(false);
});
it('only calls with information from a single text field', () => {
render(<SearchForm callback={mockFunc} />);
const ingredient = screen.getByTestId('coctailingredient');
const ingredientView = within(ingredient).getByRole("textbox");
const nameInput = screen.getByTestId('coctailname');
const nameView = within(nameInput).getByRole("textbox");
// load data in the name field, this will be ignored
userEvent.type(nameView, 'martini');
// load data in ingredient field, this should delete the above
userEvent.type(ingredientView, 'tequila');
const findBtn = screen.getByRole('button', { name: /find/i });
fireEvent.click(findBtn);
expect(mockFunc).toHaveBeenCalled();
expect(mockFunc.mock.calls[0][0]).toBe('tequila');
});
it('will not call the callback without input values', () => {
render(<SearchForm callback={mockFunc} />);
const findBtn = screen.getByRole('button', { name: /find/i });
fireEvent.click(findBtn);
expect(mockFunc).not.toHaveBeenCalled();
});
})
|
class MyCircularDeque:
def __init__(self, k: int):
self.k = k
self.li = []
def insertFront(self, value: int) -> bool:
if self.isFull():
return False
self.li = [value]+self.li
return True
def insertLast(self, value: int) -> bool:
if self.isFull():
return False
self.li.append(value)
return True
def deleteFront(self) -> bool:
if self.isEmpty():
return False
self.li.pop(0)
return True
def deleteLast(self) -> bool:
if self.isEmpty():
return False
self.li.pop(-1)
return True
def getFront(self) -> int:
return self.li[0] if len(self.li) != 0 else -1
def getRear(self) -> int:
return self.li[-1] if len(self.li) != 0 else -1
def isEmpty(self) -> bool:
return len(self.li) == 0
def isFull(self) -> bool:
return len(self.li) == self.k
# Your MyCircularDeque object will be instantiated and called as such:
# obj = MyCircularDeque(k)
# param_1 = obj.insertFront(value)
# param_2 = obj.insertLast(value)
# param_3 = obj.deleteFront()
# param_4 = obj.deleteLast()
# param_5 = obj.getFront()
# param_6 = obj.getRear()
# param_7 = obj.isEmpty()
# param_8 = obj.isFull()
|
import { ListItemButton, ListItemIcon, ListItemText, Typography, useTheme } from '@mui/material';
import { Stack } from '@mui/system';
import { useAtom } from 'jotai';
import { atomPersistenceSidebarCategory, SidebarCategory } from '../atoms/atomUI';
import useNav from '../utils/useNav';
export interface Category {
path: SidebarCategory;
tasksLength: number;
name: string;
activeIcon: JSX.Element;
inactiveIcon: JSX.Element;
}
interface Props {
category?: Category;
}
const defaultProps: { category: Category } = {
category: {
path: '/queueAll',
tasksLength: 0,
name: 'All',
activeIcon: <div />,
inactiveIcon: <div />,
},
};
function StyledListItemButton({ category = defaultProps.category }: Props) {
const theme = useTheme();
const { navigate } = useNav();
const [sidebarCategory] = useAtom(atomPersistenceSidebarCategory);
return (
<ListItemButton disableRipple selected={sidebarCategory === category.path} onClick={() => navigate(category.path)}>
<ListItemIcon
sx={{
minWidth: theme.spacing(4),
color: sidebarCategory === category.path ? theme.palette.primary.main : theme.palette.text.primary,
}}
>
{sidebarCategory === category.path ? category.activeIcon : category.inactiveIcon}
</ListItemIcon>
<ListItemText
primary={
<Typography
noWrap
color={sidebarCategory === category.path ? theme.palette.primary.main : theme.palette.text.primary}
fontSize={13}
fontWeight={500}
sx={{ mr: theme.spacing(0.5) }}
>
{category.name}
</Typography>
}
/>
{category.tasksLength > 0 && (
<Stack
justifyContent="center"
alignItems="center"
height={theme.spacing(2)}
minWidth={theme.spacing(3)}
sx={{
backgroundColor: theme.palette.text.secondary,
borderRadius: theme.spacing(1),
px: category.tasksLength >= 100 ? theme.spacing(0.25) : 0,
}}
>
<Typography
fontSize={10}
fontWeight={500}
color={theme.palette.card.default}
sx={{ fontFamily: 'Noto Sans Mono' }}
>
{category.tasksLength >= 100 ? '99+' : category.tasksLength}
</Typography>
</Stack>
)}
</ListItemButton>
);
}
StyledListItemButton.defaultProps = defaultProps;
export default StyledListItemButton;
|
<div class="container">
<div class="finder">
<h1>Find GitHub User</h1>
</div>
</div>
<div class="container">
<form [formGroup]="searchGroup">
<div class="pseudo-search">
<input
placeholder="GitHub Username"
class="form-control"
id="username"
formControlName="username"
/>
<button (click)="getGitHubUserInformation()">
<i class="fa-brands fa-github"></i>
<i class="fa fa-search"></i>
</button>
</div>
</form>
</div>
<div class="container" *ngIf="userFound && gitHubUser">
<div class="content">
<div class="card">
<div class="additional">
<div class="user-card">
<div class="level center">{{ gitHubUser.login }}</div>
<img class="round" [src]="gitHubUser.avatar_url" />
<div class="points center">
{{ gitHubUser.created_at | date : "EEE MMM dd yyyy" }}
</div>
</div>
<div class="more-info">
<h1>{{ gitHubUser.name }}</h1>
<div style="display: flex">
<div class="coords" style="width: 50%">
<i class="fa-solid fa-location-dot"></i>
{{ gitHubUser.location }}
</div>
<div class="coords" style="width: 50%">
<span>
<i class="fa-brands fa-twitter"></i
><span>@{{ gitHubUser.twitter_username }}</span>
</span>
</div>
</div>
<div class="coords" style="width: 100%">
<div class="center-blog">
<i class="fa-solid fa-blog"></i>
<a [href]="gitHubUser.blog">{{ gitHubUser.blog }}</a>
</div>
</div>
<div class="stats">
<div>
<div class="title">REPOS</div>
<i class="fa-solid fa-code-branch"></i>
<div class="value">{{ gitHubUser.public_repos }}</div>
</div>
<div>
<div class="title">FOLLOWERS</div>
<i class="fa-solid fa-users"></i>
<div class="value">{{ gitHubUser.followers }}</div>
</div>
<div>
<div class="title">FOLLOWING</div>
<i class="fa-solid fa-user-group"></i>
<div class="value">{{ gitHubUser.following }}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container" *ngIf="!userFound && !firstUse">
<div class="card">
<div class="additional">
<div class="center-blog">
<span>No hay usuarios que cumplan con el criterio de búsqueda</span>
</div>
</div>
</div>
</div>
|
"""
Implementation of the Hankel-based Deep Learning Dynamic Mode Decomposition
in PyTorch
Author: Jay Lago, NIWC Pacific, 55280
Created: 11-May-2023
"""
import torch
import torch.nn as nn
from torch.autograd import Function
import numpy as np
from scipy.linalg import hankel
# Model Implementations
class Hankel_DLDMD(nn.Module):
def __init__(self, hyp):
super(Hankel_DLDMD, self).__init__()
# Hyperparameters
self.bs = hyp['batch_size']
self.p_dim = hyp['phys_dim']
self.l_dim = hyp['latent_dim']
self.n_ts = hyp['num_pred']
self.device = hyp['device']
self.dtype = hyp['dtype']
self.cdtype = hyp['cdtype']
self.enc_layers = hyp['enc_layers']
self.dec_layers = hyp['dec_layers']
self.act_fn = hyp['act_fn']
self.ysteps = hyp['ysteps']
self.tikhonov_param = hyp['tikhonov_param']
self.num_observables = hyp['num_observables']
self.window = self.n_ts - (self.num_observables - 1)
self.max_win_stp = hyp['max_win_stp']
self.operation_mode = hyp['operation_mode']
# Neural Networks
encoder = []
for ll in range(len(self.enc_layers)):
if ll < len(self.enc_layers)-1:
encoder.append(nn.Linear(self.enc_layers[ll][0], self.enc_layers[ll][1]))
encoder.append(self.act_fn)
else:
encoder.append(nn.Linear(self.enc_layers[ll][0], self.enc_layers[ll][1]))
self.encoder = nn.Sequential(*encoder)
decoder = []
for ll in range(len(self.dec_layers)):
if ll < len(self.dec_layers)-1:
decoder.append(nn.Linear(self.dec_layers[ll][0], self.dec_layers[ll][1]))
decoder.append(self.act_fn)
else:
decoder.append(nn.Linear(self.dec_layers[ll][0], self.dec_layers[ll][1]))
self.decoder = nn.Sequential(*decoder)
def forward(self, x):
y = self.encoder(x)
x_ae = self.decoder(y)
if self.operation_mode == 'DLHDMD':
initconds = torch.transpose(torch.squeeze(y[:, 0, :]), 0, 1)
curgm, curgp = self.hankel_maker(y)
kmat, phi_adv = self.hankel_dmd_real(initconds, curgm, curgp)
y_adv = torch.reshape(torch.transpose(kmat @ phi_adv, 0, 1),
[self.bs, self.window-1, self.l_dim])
elif self.operation_mode == 'DLDMD':
y_adv, _ = self.dmd_real(y)
x_adv = self.decoder(y_adv)
return y, x_ae, x_adv, y_adv
def dmd_real(self, y):
"""Computes the standard Dynamic Mode Decomposition of a multi-
dimensional time series.
Args:
y (tensor array): Batched time series of data (batch, dims, time)
Returns:
y_adv (tensor array): Batched time series of predicted data (batch, dims, time)
A (tensor array)
"""
y = torch.transpose(y, 1, 2)
y_m = y[:, :, :-1]
y_p = y[:, :, 1:]
U, S, Vh = torch.linalg.svd(y_m, full_matrices=False)
Si = torch.diag_embed(1.0 / S)
V = torch.adjoint(Vh)
Uh = torch.adjoint(U)
A = y_p @ V @ Si @ Uh
y_adv = torch.transpose(self.phi_adv(y_m, A), 1, 2)
return y_adv, A
def hankel_maker(self, yin):
ws = self.window
nobs = self.num_observables
gm = torch.zeros([nobs*self.l_dim, self.bs*(ws-1)],
dtype=self.dtype, device=self.device)
gp = torch.zeros([nobs*self.l_dim, self.bs*(ws-1)],
dtype=self.dtype, device=self.device)
for jj in range(self.l_dim):
Yobserved = torch.squeeze(yin[:, :, jj])
for ll in range(self.bs):
tseries = Yobserved[ll, :]
hankel_idx = np.array([np.arange(ii, ii+nobs) for ii in range(len(tseries) - nobs + 1)])
hmat = tseries[hankel_idx].T
gm[jj*nobs:(jj+1)*nobs, ll * (ws - 1):(ll + 1) * (ws - 1)] = hmat[:, :-1]
gp[jj*nobs:(jj+1)*nobs, ll * (ws - 1):(ll + 1) * (ws - 1)] = hmat[:, 1:]
return gm, gp
def hankel_dmd_real(self, initconds, curgm, curgp):
U, sig, Vh = torch.linalg.svd(curgm, full_matrices=False)
sigr_inv = torch.diag_embed(1.0 / sig)
V = torch.adjoint(Vh)
Uh = torch.adjoint(U)
A = curgp @ V @ sigr_inv @ Uh
phi_adv = self.phi_adv(curgm, A)
# Build reconstruction
gm0 = curgm[:, ::(self.window-1)]
Up, sigp, Vph = torch.linalg.svd(gm0, full_matrices=False)
Vp = torch.adjoint(Vph)
sigpr = sigp/(sigp**2.+self.tikhonov_param)
pinv = Vp @ torch.diag_embed(sigpr) @ torch.adjoint(Up)
kmat = initconds @ pinv
return kmat, phi_adv
def phi_adv(self, curgm, A):
phi_adv = A @ curgm
for jj in range(1, self.ysteps):
phi_adv = A @ phi_adv
return phi_adv
# Loss Function Implementations
class Hankel_DLDMD_Loss(nn.Module):
def __init__(self, hyp):
super(Hankel_DLDMD_Loss, self).__init__()
self.device = hyp['device']
self.cdtype = hyp['cdtype']
self.a1 = hyp['a1']
self.a2 = hyp['a2']
self.a3 = hyp['a3']
self.a4 = hyp['a4']
self.num_observables = hyp['num_observables']
self.n_ts = hyp['num_pred']
self.window = self.n_ts - (self.num_observables - 1)
self.ysteps = hyp['ysteps']
self.num_loss_comps = 4
def forward(self, x, model_results, model_params):
y, x_ae, x_adv, y_adv = model_results
loss_recon = self.a1 * torch.mean(torch.square(x - x_ae))
loss_dmd = self.a2 * torch.mean(
torch.square(y[:, self.ysteps:(self.window-1), :] -
y_adv[:, :-self.ysteps, :]))
loss_pred = self.a3 * torch.mean(
torch.square(x[:, self.ysteps:(self.window-1), :] -
x_adv[:, :-self.ysteps, :]))
loss_reg = self.a4 * sum([torch.norm(torch.flatten(w)) for w in model_params])
total_loss = loss_recon + loss_dmd + loss_pred + loss_reg
losses = [total_loss, loss_recon, loss_dmd, loss_pred]
return losses
def dmd_loss(self, y):
"""Computes the loss for the DMD component of the DLDMD loss function.
Args:
y (tensor array): Batched time series of latent data (batch, dims, time)
Returns:
loss (tensor array): DMD loss term (batch,)
"""
y_m = torch.transpose(y, 2, 1)[:, :, :-1]
y_p = torch.transpose(y, 2, 1)[:, :, 1:]
_, _, Vh = torch.linalg.svd(y_m, full_matrices=False)
VVh = torch.adjoint(Vh) @ Vh
eye_mat = torch.eye(VVh.shape[-1], device=self.device,
dtype=self.cdtype, requires_grad=True)
tmp = y_p.type(dtype=self.cdtype) @ (eye_mat - VVh)
return torch.mean(torch.linalg.norm(tmp, ord='fro', dim=(-2, -1)))
|
/*
* EasyPmd
* Copyright (C) 2009 - 2017 Gianluca Costa
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
*/
package info.gianlucacosta.easypmd.pmdscanner.messages.cache;
import info.gianlucacosta.easypmd.pmdscanner.ScanMessage;
import info.gianlucacosta.easypmd.util.Throwables;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
/**
* Cache backed by a lightweight db
*/
public class HsqlDbStorage implements CacheStorage {
private static final Logger logger = Logger.getLogger(HsqlDbStorage.class.getName());
private static final String DB_FILE_NAME = "ScanMessages.db";
private static final String TABLE_CREATION_DDL
= "CREATE TABLE IF NOT EXISTS CacheItems (path VARCHAR(4096) PRIMARY KEY, lastModificationMillis BIGINT NOT NULL, scanMessages OTHER NOT NULL)";
private static final String SELECT_QUERY
= "SELECT lastModificationMillis, scanMessages FROM CacheItems WHERE path = ?";
private static final String INSERT_DDL
= "INSERT INTO CacheItems (path, lastModificationMillis, scanMessages) VALUES (?, ?, ?)";
private static final String UPDATE_DDL
= "UPDATE CacheItems SET lastModificationMillis = ?, scanMessages = ? WHERE path = ?";
private static final String CLEAR_DDL
= "DELETE FROM CacheItems";
private Connection dbConnection;
private PreparedStatement selectStatement;
private PreparedStatement insertStatement;
private PreparedStatement updateStatement;
private PreparedStatement clearStatement;
public HsqlDbStorage(Path cacheRootPath) {
try {
Files.createDirectories(cacheRootPath);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
Path cacheDb = cacheRootPath.resolve(DB_FILE_NAME);
String connectionString = String.format(
"jdbc:hsqldb:file:%s; shutdown=true",
cacheDb
);
try {
dbConnection = DriverManager.getConnection(connectionString);
dbConnection.setAutoCommit(true);
try (Statement statement = dbConnection.createStatement()) {
statement.execute(TABLE_CREATION_DDL);
}
selectStatement = dbConnection.prepareStatement(SELECT_QUERY);
insertStatement = dbConnection.prepareStatement(INSERT_DDL);
updateStatement = dbConnection.prepareStatement(UPDATE_DDL);
clearStatement = dbConnection.prepareStatement(CLEAR_DDL);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
@Override
public Optional<CacheEntry> getEntry(String pathString) {
try {
selectStatement.setString(1, pathString);
try (ResultSet resultSet = selectStatement.executeQuery()) {
if (resultSet.next()) {
long lastModificationMillis = resultSet.getLong(1);
Set<ScanMessage> scanMessages = (Set<ScanMessage>) resultSet.getObject(2);
CacheEntry cacheEntry = new CacheEntry(lastModificationMillis, scanMessages);
return Optional.of(cacheEntry);
} else {
return Optional.empty();
}
}
} catch (Exception ex) {
logger.warning(
() -> String.format(
"Error while retrieving db-cached scan messages for path: %s.\nCause: %s",
pathString,
Throwables.toStringWithStackTrace(ex)
)
);
return Optional.empty();
}
}
@Override
public void putEntry(String pathString, CacheEntry cacheEntry) {
try {
updateStatement.setLong(1, cacheEntry.getLastModificationMillis());
updateStatement.setObject(2, cacheEntry.getScanMessages());
updateStatement.setString(3, pathString);
if (updateStatement.executeUpdate() == 0) {
insertStatement.setString(1, pathString);
insertStatement.setLong(2, cacheEntry.getLastModificationMillis());
insertStatement.setObject(3, cacheEntry.getScanMessages());
if (insertStatement.executeUpdate() == 0) {
throw new IllegalStateException(
String.format(
"Neither UPDATE nor INSERT could add messages to the cache for path: %s",
pathString
)
);
}
}
} catch (Exception ex) {
logger.warning(
() -> String.format(
"Could not write to db-cache messages for path: %s.\nCause: %s",
pathString,
Throwables.toStringWithStackTrace(ex)
)
);
}
}
@Override
public boolean clearEntries() {
try {
clearStatement.executeUpdate();
return true;
} catch (Exception ex) {
logger.warning(
() -> String.format(
"Error while clearing the db cache: %s.\nCause: %s",
ex,
Throwables.toStringWithStackTrace(ex)
)
);
return false;
}
}
@Override
public void close() throws Exception {
dbConnection.close();
}
}
|
plan("multisession",workers=8)
## Load data times for 2019
cluster_migration_timeSeries_one_year <- function(list_of_yearly_migration_rates, number_of_clusters){
discrete_colours <- RColorBrewer::brewer.pal(4, "Set1")
############################################################# 2019 #########################################
LAD_mig_A <- list_of_yearly_migration_rates[[1]]
LAD_mig_B <- list_of_yearly_migration_rates[[2]]
##### Data comes in 2 parts, which are combined (row-wise)
LAD_mig_A <- as.data.frame(LAD_mig_A)
colnames(LAD_mig_A) <- c("orig_CODE" , "dest_CODE" , "Age" , "Sex" , "Count")
LAD_mig_A <- LAD_mig_A%>%filter(Sex == "F")%>%dplyr::select(-Sex)
LAD_mig_B <- as.data.frame(LAD_mig_B)
colnames(LAD_mig_B) <- c("orig_CODE" , "dest_CODE" , "Age" , "Sex" , "Count")
LAD_mig_B <- LAD_mig_B%>%filter(Sex == "F")%>%dplyr::select(-Sex)
LAD_mig_2019 <- rbind(LAD_mig_A,LAD_mig_B)
#LAD_mig_2019 <- LAD_mig_2019 %>%
# filter(!substr(orig_CODE, 1, 1) == "S" , !substr(dest_CODE, 1, 1) == "S" )
LAD_mig_2019 <- LAD_mig_2019[order(LAD_mig_2019$Age, decreasing = FALSE),]
LAD_mig_2019$Age%>%unique()
LAD_mig_age_class_2019 <- data.frame()
foreach(age = seq(0, 90, by = 5))%do%{
df_temp <- LAD_mig_2019%>%filter(Age>= age & Age < age + 5)%>%
group_by(orig_CODE, dest_CODE)%>%
summarise(mean_count_over_age = sum(Count))
#df_temp$Age <- as.numeric(age)
df_temp$Age <- paste(age , age + 4, sep = "_")
LAD_mig_age_class_2019 <- rbind(LAD_mig_age_class_2019, df_temp)
}
########################################## Rbind to big data #####################
LAD_mig_age_class_2019$year <- 2019
time_LADS <- LAD_mig_age_class_2019
## Cluster based on emigration from LADS
k_means_df_ALL_YEARS <- time_LADS%>%group_by(Age, orig_CODE)%>%
summarise(mean_Dest = sum(mean_count_over_age))%>%ungroup()%>%
pivot_wider(names_from=c("Age"), values_from="mean_Dest")%>%
dplyr::select(-c(orig_CODE))
k_means_df_ALL_YEARS <- na.omit(k_means_df_ALL_YEARS)
res <- data.frame(ind=1:10)
for (i in 1:10) {
set.seed(1)
kmeansx <- kmeans(k_means_df_ALL_YEARS, centers=i, nstart=20)
res$wss[i] <- kmeansx$tot.withinss
if (i == 1) cen <- cbind(K=i,n=factor(1:i),kmeansx$centers)
if (i > 1) cen <- rbind(cen, cbind(K=i,n=factor(1:i),kmeansx$centers))
if (i == 1) clus <- kmeansx$cluster
if (i > 1) clus <- cbind(clus, kmeansx$cluster)
}
cen%>%nrow()
#Elbow plot
plot_of_elbows <- res %>% ggplot(aes(x=ind,y=wss/wss[1])) +
geom_point() + geom_line() +
scale_x_continuous(breaks=seq(5,20,5),minor_breaks=1:20) +
labs(x="K",y="Within-cluster sum of squares (scaled)") +
theme_bw()
plot_of_wss_diff <- res %>% mutate(wss=wss/wss[1]) %>%
mutate(First=c(NA,diff(wss)),
Second=c(NA,diff(First))) %>%
dplyr::select(-wss) %>%
pivot_longer(-ind,values_to="Difference",names_to="Order") %>%
ggplot(aes(x=ind,y=Difference,color=Order)) +
geom_hline(aes(yintercept=0),linetype=2) +
geom_line(aes(group=Order)) +
geom_point() +
geom_vline(aes(xintercept=6)) +
labs(x="K") +
scale_x_continuous(breaks=1:40,minor_breaks=NULL,expand=c(0.02,0.02)) +
coord_cartesian(ylim=c(-0.1,0.1)) +
theme_bw() +
theme(legend.position="bottom")
cp <- cen %>% as.data.frame() %>% filter(K==number_of_clusters)%>%
pivot_longer(-c("K","n"),values_to="cen",names_to="age")
plot_of_centers <- ggplot(cp, aes(x=age,y=cen,color=as.factor(n))) +
geom_line(aes(group = factor(n))) + scale_color_manual(values = discrete_colours[1:number_of_clusters])
codee <- time_LADS%>%group_by(Age, orig_CODE)%>%
summarise(mean_Dest = mean(mean_count_over_age))%>%
pivot_wider(names_from=c("Age"), values_from="mean_Dest")
codee <- codee%>%na.omit()
codee <- codee%>%dplyr::select(orig_CODE)%>%unique()%>%as.data.frame()%>%unname()
#colnames(codee) <- "code"
k_means_df_ALL_YEARS$code <- as.factor(codee[,1])
k_means_df_ALL_YEARS$clus <- as.factor(clus[, number_of_clusters])
colnames(k_means_df_ALL_YEARS)
k_means_df_ALL_YEARS <- k_means_df_ALL_YEARS[, c(1,10,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21)]
mig_cluster_df <- k_means_df_ALL_YEARS%>%melt(id = c("code","clus"))%>%
mutate(Age_class = variable,
no_out_moves = value,
cluster = clus,
LAD_code = code)%>%dplyr::select(Age_class,no_out_moves,cluster,LAD_code)
mig_cluster_df$num_age <- gsub('.{2}$' , "" , mig_cluster_df$Age_class)
mig_cluster_df$num_age <- as.numeric(gsub('_' , "" , mig_cluster_df$num_age))
mig_cluster_df$Age_class <- fct_reorder(mig_cluster_df$Age_class, mig_cluster_df$num_age)
plot_of_clusters <- mig_cluster_df%>%ggplot(aes( x = Age_class, y = no_out_moves, color = cluster)) +
geom_line(aes(group = factor(LAD_code)))+ scale_color_manual(values = discrete_colours[1:number_of_clusters]) +
theme_bw() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
text = element_text(size = 15),
legend.position = "top") + ylab("no. emigrations from LAD") + xlab("age class")
return(list(mig_cluster_df,
time_LADS,
plot_of_clusters,
plot_of_wss_diff,
plot_of_centers,
plot_of_elbows))
}
|
import client from "../DB";
import bcrypt from 'bcrypt';
import dotenv from 'dotenv';
dotenv.config();
const pepper : string | unknown = process.env.BCRYPT_PASSWORD?.toString();
const salt = process.env.SALT_ROUNDS;
export type user ={
id?: string | number;
fName: string;
lName: string;
userName:string;
password : string;
}
export type cartItem = {
id?: string | number,
userId : string | number,
productId : string | number,
qty : number
}
export class UserStore{
async index() : Promise<user[]> {
try {
const connection =await client.connect();
const sql = 'SELECT * FROM users';
const result = await connection.query(sql);
connection.release();
return result.rows;
}catch(err){
throw new Error(`can not connect to DB ${err}`);
}
}
async show(id : string | number):Promise<user> {
try{
const sql = `SELECT * FROM users WHERE id=($1)`;
const connection = await client.connect();
const result = await connection.query(sql,[id]);
connection.release();
return result.rows[0];
}catch(err){
throw new Error(`can not find user ${id}. error is ${err}`)
}
}
async create(u : user) : Promise<user>{
try{
const sql = `INSERT INTO users (fname , lname ,username, password) VALUES($1, $2, $3, $4) RETURNING *`;
const connection = await client.connect();
const hash = bcrypt.hashSync(
u.password + pepper,
parseInt(salt? salt : "10")
)
const result = await connection.query(sql,[u.fName,u.lName,u.userName,hash]);
connection.release();
return result.rows[0];
}catch(err){
throw new Error(`can not add user ${u.userName} , the error is ${err}`);
}
}
async delete(id : string | number) : Promise<user>{
try{
const sql = `DELETE FROM users WHERE id=($1)`;
const connection = await client.connect();
const result = await connection.query(sql,[id]);
connection.release();
return result.rows[0];
}catch(err){
throw new Error(`can not delete user ${id} , the error is ${err}`);
}
}
async update(id :string | number , u:user ) :Promise<user>{
try{
const sql = `UPDATE users SET fname=($1) , lname=($2) , username=($3), password=($4) WHERE id=($5) RETURNING *; `;
const connection = await client.connect();
const hash = bcrypt.hashSync(
u.password + pepper,
parseInt(salt? salt : "10")
);
const result = await connection.query(sql,[u.fName , u.lName , u.userName , hash , id]);
connection.release();
return result.rows[0];
}catch(err){
throw new Error(`can not update user ${id} , the error is ${err}`);
}
}
async authinticate(userName : string , password : string) : Promise <user | null>{
try{
const sql = 'SELECT * FROM users WHERE username=($1)';
const connection = await client.connect();
console.log("connecting");
const result = await connection.query(sql,[userName]);
console.log(result.rows);
connection.release();
if(result.rows.length){
const user = result.rows[0];
console.log(user);
if(bcrypt.compareSync(password + pepper , user.password)){
return user;
}
else{
throw new Error ("password is incorrect");
}
}
else{
return null;
}
}catch(err){
throw new Error(`can not authenticate ${err}`);
}
}
// for the cart items table (users is the prmary entity for it)
async addCartItem(qty : number , userId : string | number , productId :string | number) : Promise<cartItem>{
try{
const sql = 'INSERT INTO cart_items(quantity, user_id , product_id) VALUES($1, $2, $3) RETURNING *;';
const connection = await client.connect();
const result = await connection.query(sql,[qty,userId,productId]);
connection.release();
return result.rows[0];
}catch(err){
throw new Error(`can't add cart items ,${err}`);
}
}
async getCartItem(userId : string | number ) : Promise<cartItem[]>{
try{
const sql = 'SELECT * FROM cart_items WHERE user_id=($1);';
const connection = await client.connect();
const result = await connection.query(sql,[userId]);
connection.release();
return result.rows;
}catch(err){
throw new Error (`can not get cart items for user ${userId} , ${err}`);
}
}
}
|
import BarChart from '@cloudscape-design/components/bar-chart';
import Box from '@cloudscape-design/components/box';
import {
colorChartsPaletteCategorical25,
colorChartsStatusCritical,
colorChartsStatusNeutral,
colorChartsStatusPositive,
} from '@cloudscape-design/design-tokens';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { RaceTypeEnum } from '../admin/events/support-functions/raceConfig';
import { convertMsToString } from '../support-functions/time';
const RaceGraph = ({
laps,
fastestEventLapTime,
fastestEventAvgLap,
raceFormat,
fastestRaceAvgLap,
}) => {
const { t } = useTranslation(['translation', 'help-race-stats']);
const [yDomain, setYDomain] = useState([0, 15000]);
const [xDomain, SetXDomain] = useState([]);
const [redLaps, setRedLaps] = useState([]);
const [greenLaps, setGreenLaps] = useState([]);
const [neutralLaps, setNeutralLaps] = useState([]);
const [threshold, setThreshold] = useState(0);
const [thresholdLabel, setThresholdLabel] = useState(t('commentator.race.graph.fastestLap'));
const [fastestLabel, setFastestLabel] = useState(t('commentator.race.graph.fastestRaceLap'));
const prepareGraphForAvgFormat = (slowestTime, fastestTime, allLaps) => {
setFastestLabel(t('commentator.race.graph.fastestAvgWindow'));
setThresholdLabel(t('commentator.race.graph.fastestAvgLap'));
if (fastestEventAvgLap?.avgTime) {
const fastestAvg = fastestEventAvgLap?.avgTime;
setThreshold(fastestEventAvgLap.avgTime);
setYDomain([
Math.min(slowestTime, fastestAvg) - 500,
Math.max(fastestTime, fastestAvg) + 500,
]);
}
const lapsCopy = [...allLaps];
if (fastestRaceAvgLap?.avgTime) {
var avgWindowLaps = [];
if (fastestRaceAvgLap) {
const count = fastestRaceAvgLap.endLapId - fastestRaceAvgLap.startLapId + 1;
avgWindowLaps = lapsCopy.splice(fastestRaceAvgLap.startLapId, count);
}
setNeutralLaps(avgWindowLaps);
setGreenLaps(lapsCopy.filter((lap) => lap.isValid));
setRedLaps(lapsCopy.filter((lap) => !lap.isValid));
} else {
setGreenLaps(lapsCopy.filter((lap) => lap.isValid));
setRedLaps(lapsCopy.filter((lap) => !lap.isValid));
setNeutralLaps([]);
}
};
const prepareGraph = (fastestTime, slowestTime, allLaps) => {
setFastestLabel(t('commentator.race.graph.fastestRaceLap'));
if (fastestEventLapTime) {
setYDomain([
Math.min(fastestTime, fastestEventLapTime) - 500,
Math.max(slowestTime, fastestEventLapTime) + 500,
]);
setThreshold(fastestEventLapTime);
} else {
setYDomain([fastestTime - 500, slowestTime + 500]);
}
allLaps.sort((a, b) => a.time - b.time);
console.log(allLaps);
const fastest = allLaps.findIndex((lap) => lap.isValid);
console.log(fastest);
setGreenLaps(allLaps.filter((lap, index) => lap.isValid && index !== fastest));
setRedLaps(allLaps.filter((lap) => !lap.isValid));
setNeutralLaps(allLaps.filter((lap, index) => lap.isValid && index === fastest));
};
useEffect(() => {
if (laps && laps.length) {
var fastestTime = laps[0].time;
var slowestTime = laps[0].time;
const allLaps = laps.map((lap) => {
if (lap.time < fastestTime) {
fastestTime = lap.time;
}
if (lap.time > slowestTime) slowestTime = lap.time;
return {
x: Number(lap.lapId) + 1,
y: lap.time,
time: lap.time,
isValid: lap.isValid,
};
});
const xDomain = allLaps.map((lap) => lap.x);
SetXDomain(xDomain);
if (raceFormat === RaceTypeEnum.BEST_AVERAGE_LAP_TIME_X_LAP) {
prepareGraphForAvgFormat(fastestTime, slowestTime, allLaps);
} else {
prepareGraph(fastestTime, slowestTime, allLaps);
}
} else {
setYDomain([0, 15000]);
SetXDomain([]);
setRedLaps([]);
setGreenLaps([]);
setNeutralLaps([]);
}
}, [laps, fastestEventLapTime, fastestRaceAvgLap, raceFormat]);
return (
<>
<BarChart
series={[
{
type: 'bar',
color: colorChartsStatusCritical,
title: t('commentator.race.graph.invalidLaps'),
data: redLaps,
valueFormatter: (e) => convertMsToString(e, true),
},
{
type: 'bar',
color: colorChartsStatusPositive,
title: t('commentator.race.graph.validLaps'),
data: greenLaps,
valueFormatter: (e) => convertMsToString(e, true),
},
{
type: 'bar',
color: colorChartsStatusNeutral,
title: fastestLabel,
data: neutralLaps,
valueFormatter: (e) => convertMsToString(e, true),
},
{
title: thresholdLabel,
type: 'threshold',
color: colorChartsPaletteCategorical25,
y: Number(threshold),
valueFormatter: (e) => convertMsToString(e, true),
},
]}
yDomain={yDomain}
xDomain={xDomain}
i18nStrings={{
yTickFormatter: function numberFormatter(e) {
return convertMsToString(e, false);
},
xTickFormatter: function numberFormatter(e) {
return 'Lap ' + e;
},
}}
ariaLabel="Single data series line chart"
height={300}
yTitle="Time"
stackedBars
hideFilter
empty={
<Box textAlign="center" color="inherit">
{' '}
<b>No data available</b>{' '}
<Box variant="p" color="inherit">
{' '}
There is no data available{' '}
</Box>{' '}
</Box>
}
/>
</>
);
};
export { RaceGraph };
|
package com.app.composepractice.layouts
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun Elements() {
Column(modifier = Modifier.fillMaxSize()) {
SurfaceUsage()
Spacer(modifier = Modifier.padding(10.dp))
ShapeUsage()
}
}
@Composable
fun SurfaceUsage() {
// Surface is a basic building block for displaying content
// and can be used to wrap other composable to provide
// a background color, elevation, padding, and other layout properties.
Surface(
modifier = Modifier
.padding(15.dp)
.fillMaxWidth()
.height(150.dp),
shape = RoundedCornerShape(15),
contentColor = Color.Red,
border = BorderStroke(2.dp, Color.Red),
onClick = {
Log.d("Click Listener", "Clicked surface.")
}
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.Black),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Test Text", fontSize = 24.sp, fontWeight = FontWeight.Bold)
}
}
}
@Composable
fun ShapeUsage() {
// A Shape can be used to draw a Composable in specific shape.
// - RectangleShape, CircleShape, RoundedCornerShape, CutCornerShape
Row {
Box(modifier = Modifier
.size(100.dp)
.padding(15.dp)
.clip(CircleShape)
.background(Color.Blue)) {
}
Box(modifier = Modifier
.size(100.dp)
.padding(15.dp)
.clip(RectangleShape)
.background(Color.Blue)) {
}
Box(modifier = Modifier
.size(100.dp)
.padding(15.dp)
.clip(RoundedCornerShape(18.dp))
.background(Color.Blue)) {
}
Box(modifier = Modifier
.size(100.dp)
.padding(15.dp)
.clip(CutCornerShape(18.dp))
.background(Color.Blue)) {
}
}
}
@Composable
@Preview(showBackground = true, showSystemUi = true)
fun ElementsPreview() {
Elements()
}
|
using Sage.CA.SBS.ERP.Sage300.Common.Models;
using Sage.CA.SBS.ERP.Sage300.Common.Models.Attributes;
using Sage.CA.SBS.ERP.Sage300.Common.Models.Enums.DropShipment;
using Sage.CA.SBS.ERP.Sage300.Common.Models.PODropShipment;
using Sage.CA.SBS.ERP.Sage300.Common.Models.POVendorInformation;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Sage.CA.SBS.ERP.Sage300.Common.Interfaces.Service.Base.Statefull
{
/// <summary>
/// Interface ISequencedHeaderDetailFiveService
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TU">The type of the tu.</typeparam>
/// <typeparam name="TDetail2">The type of the TDetail2.</typeparam>
/// <typeparam name="TDetail3">The type of the TDetail3.</typeparam>
/// <typeparam name="TDetail4">The type of the TDetail4.</typeparam>
/// <typeparam name="TDetail5">The type of the TDetail5.</typeparam>
public interface ISequencedHeaderDetailFiveService<T, TU, TDetail2, TDetail3, TDetail4, TDetail5> : IEntityService<T>, ISecurityService
where T : ModelBase, new()
where TU : ModelBase, new()
where TDetail2 : ModelBase, new()
where TDetail3 : ModelBase, new()
where TDetail4 : ModelBase, new()
where TDetail5 : ModelBase, new()
{
/// <summary>
/// Creates a new Header.
/// </summary>
/// <returns>Header record</returns>
T NewHeader();
/// <summary>
/// Save for detail entry
/// </summary>
/// <param name="detail">Detail model</param>
/// <returns></returns>
T SaveDetail(TU detail);
/// <summary>
/// Save for detail 2 entry
/// </summary>
/// <param name="detail2">Detail 2 model</param>
/// <returns></returns>
T SaveDetail2(TDetail2 detail2);
/// <summary>
/// Save for detail 3 entry
/// </summary>
/// <param name="detail3">Detail 3 model</param>
/// <returns></returns>
T SaveDetail3(TDetail3 detail3);
/// <summary>
/// Save for detail 4 entry
/// </summary>
/// <param name="detail4">Detail 4 model</param>
/// <returns></returns>
T SaveDetail4(TDetail4 detail4);
/// <summary>
/// Save for detail 5 entry
/// </summary>
/// <param name="detail5">Detail 5 model</param>
/// <returns></returns>
T SaveDetail5(TDetail5 detail5);
/// <summary>
/// Sets pointer to the current Detail
/// </summary>
/// <param name="detail">The current detail.</param>
/// <returns>TDetail.</returns>
T SetDetail(TU detail);
/// <summary>
/// Sets pointer to the current Detail 2
/// </summary>
/// <param name="detail2">The current detail 2.</param>
/// <returns>TDetail2.</returns>
T SetDetail2(TDetail2 detail2);
/// <summary>
/// Sets pointer to the current Detail 3
/// </summary>
/// <param name="detail3">The current detail 3.</param>
/// <returns>TDetail3.</returns>
T SetDetail3(TDetail3 detail3);
/// <summary>
/// Sets pointer to the current Detail 4
/// </summary>
/// <param name="detail4">The current detail 4.</param>
/// <returns>TDetail4.</returns>
T SetDetail4(TDetail4 detail4);
/// <summary>
/// Sets pointer to the current Detail 5
/// </summary>
/// <param name="detail5">The current detail 5.</param>
/// <returns>TDetail5.</returns>
T SetDetail5(TDetail5 detail5);
/// <summary>
/// Save for detail entry
/// </summary>
/// <param name="details">Detail model</param>
/// <returns></returns>
bool SaveDetails(IEnumerable<TU> details);
/// <summary>
/// Save for detail 2 entry
/// </summary>
/// <param name="details2">Detail model</param>
/// <returns></returns>
bool SaveDetails2(IEnumerable<TDetail2> details2);
/// <summary>
/// Save for detail 3 entry
/// </summary>
/// <param name="details3">Detail model</param>
/// <returns></returns>
bool SaveDetails3(IEnumerable<TDetail3> details3);
/// <summary>
/// Save for detail 4 entry
/// </summary>
/// <param name="details4">Detail model</param>
/// <returns></returns>
bool SaveDetails4(IEnumerable<TDetail4> details4);
/// <summary>
/// Save for detail 5 entry
/// </summary>
/// <param name="details5">Detail model</param>
/// <returns></returns>
bool SaveDetails5(IEnumerable<TDetail5> details5);
/// <summary>
/// Get the list of editable and non editable attributes.
/// </summary>
/// <returns></returns>
List<EnablementAttribute> GetDynamicAttributesHeader();
/// <summary>
/// Get the list of editable and non editable attributes.
/// </summary>
/// <returns></returns>
List<EnablementAttribute> GetDynamicAttributesDetail();
/// <summary>
/// Get the list of editable and non editable attributes.
/// </summary>
/// <returns></returns>
List<EnablementAttribute> GetDynamicAttributesDetail2();
/// <summary>
/// Get the list of editable and non editable attributes.
/// </summary>
/// <returns></returns>
List<EnablementAttribute> GetDynamicAttributesDetail3();
/// <summary>
/// Get the list of editable and non editable attributes.
/// </summary>
/// <returns></returns>
List<EnablementAttribute> GetDynamicAttributesDetail4();
/// <summary>
/// Get the list of editable and non editable attributes.
/// </summary>
/// <returns></returns>
List<EnablementAttribute> GetDynamicAttributesDetail5();
/// <summary>
/// Creates a new detail
/// </summary>
/// <param name="pageNumber">The page number.</param>
/// <param name="pageSize">Size of the page.</param>
/// <param name="currentDetail">The current detail.</param>
/// <returns>Detail record</returns>
T NewDetail(int pageNumber, int pageSize, TU currentDetail);
/// <summary>
/// Creates a new detail 2
/// </summary>
/// <param name="pageNumber">The page number.</param>
/// <param name="pageSize">Size of the page.</param>
/// <param name="currentDetail2">The current detail 2.</param>
/// <returns>Detail record</returns>
T NewDetail2(int pageNumber, int pageSize, TDetail2 currentDetail2);
/// <summary>
/// Creates a new detail 3
/// </summary>
/// <param name="pageNumber">The page number.</param>
/// <param name="pageSize">Size of the page.</param>
/// <param name="currentDetail3">The current detail 3.</param>
/// <returns>Detail record</returns>
T NewDetail3(int pageNumber, int pageSize, TDetail3 currentDetail3);
/// <summary>
/// Creates a new detail 4
/// </summary>
/// <param name="pageNumber">The page number.</param>
/// <param name="pageSize">Size of the page.</param>
/// <param name="currentDetail4">The current detail 4.</param>
/// <returns>Detail record</returns>
T NewDetail4(int pageNumber, int pageSize, TDetail4 currentDetail4);
/// <summary>
/// Creates a new detail 5
/// </summary>
/// <param name="pageNumber">The page number.</param>
/// <param name="pageSize">Size of the page.</param>
/// <param name="currentDetail5">The current detail 5.</param>
/// <returns>Detail record</returns>
T NewDetail5(int pageNumber, int pageSize, TDetail5 currentDetail5);
/// <summary>
/// Refresh the details
/// </summary>
/// <param name="model">Ordered Header Model object</param>
/// <returns>Updated Ordered header detail object</returns>
T RefreshDetail(T model);
/// <summary>
/// To sync details 2 data based on field changes in details
/// </summary>
/// <param name="model">Header Detail 2 Model</param>
/// <returns>Header Detail 2 record</returns>
T RefreshDetail2(T model);
/// <summary>
/// To sync details 3 data based on field changes in details
/// </summary>
/// <param name="model">Header Detail 3 Model</param>
/// <returns>Header Detail 3 record</returns>
T RefreshDetail3(T model);
/// <summary>
/// To sync details 4 data based on field changes in details
/// </summary>
/// <param name="model">Header Detail 4 Model</param>
/// <returns>Header Detail 4 record</returns>
T RefreshDetail4(T model);
/// <summary>
/// To sync details 5 data based on field changes in details
/// </summary>
/// <param name="model">Header Detail 5 Model</param>
/// <returns>Header Detail 5 record</returns>
T RefreshDetail5(T model);
/// <summary>
/// Clear the detail records
/// </summary>
/// <param name="model">Header Detail model</param>
/// <returns>Header record</returns>
T ClearDetails(T model);
/// <summary>
/// Gets Paged Data for details
/// </summary>
/// <param name="currentPageNumber">Current Page Number</param>
/// <param name="pageSize">Page Size</param>
/// <param name="filter">Filter</param>
/// <param name="orderBy">Order By</param>
/// <returns>T.</returns>
EnumerableResponse<TU> GetDetail(int currentPageNumber, int pageSize, Expression<Func<TU, Boolean>> filter = null,
OrderBy orderBy = null);
/// <summary>
/// Gets Paged Data for details 2
/// </summary>
/// <param name="currentPageNumber">Current Page Number</param>
/// <param name="pageSize">Page Size</param>
/// <param name="filter">Filter</param>
/// <param name="orderBy">Order By</param>
/// <returns>T.</returns>
EnumerableResponse<TDetail2> GetDetail2(int currentPageNumber, int pageSize, Expression<Func<TDetail2, Boolean>> filter = null,
OrderBy orderBy = null);
/// <summary>
/// Gets Paged Data for details 3
/// </summary>
/// <param name="currentPageNumber">Current Page Number</param>
/// <param name="pageSize">Page Size</param>
/// <param name="filter">Filter</param>
/// <param name="orderBy">Order By</param>
/// <returns>T.</returns>
EnumerableResponse<TDetail3> GetDetail3(int currentPageNumber, int pageSize, Expression<Func<TDetail3, Boolean>> filter = null,
OrderBy orderBy = null);
/// <summary>
/// Gets Paged Data for details 4
/// </summary>
/// <param name="currentPageNumber">Current Page Number</param>
/// <param name="pageSize">Page Size</param>
/// <param name="filter">Filter</param>
/// <param name="orderBy">Order By</param>
/// <returns>T.</returns>
EnumerableResponse<TDetail4> GetDetail4(int currentPageNumber, int pageSize, Expression<Func<TDetail4, Boolean>> filter = null,
OrderBy orderBy = null);
/// <summary>
/// Gets Paged Data for details 5
/// </summary>
/// <param name="currentPageNumber">Current Page Number</param>
/// <param name="pageSize">Page Size</param>
/// <param name="filter">Filter</param>
/// <param name="orderBy">Order By</param>
/// <returns>T.</returns>
EnumerableResponse<TDetail5> GetDetail5(int currentPageNumber, int pageSize, Expression<Func<TDetail5, Boolean>> filter = null,
OrderBy orderBy = null);
/// <summary>
/// Process for detail entity
/// </summary>
/// <param name="detail">Detail model</param>
/// <returns>TU.</returns>
TU ProcessDetail(TU detail);
/// <summary>
/// Process for detail 2 entity
/// </summary>
/// <param name="detail2">Detail 2 model</param>
/// <returns>TDetail2.</returns>
TDetail2 ProcessDetail2(TDetail2 detail2);
/// <summary>
/// Process for detail 3 entity
/// </summary>
/// <param name="detail3">Detail 2 model</param>
/// <returns>TDetail2.</returns>
TDetail3 ProcessDetail3(TDetail3 detail3);
/// <summary>
/// Process for detail 4 entity
/// </summary>
/// <param name="detail4">Detail 4 model</param>
/// <returns>TDetail2.</returns>
TDetail4 ProcessDetail4(TDetail4 detail4);
/// <summary>
/// Process for detail 5 entity
/// </summary>
/// <param name="detail5">Detail 5 model</param>
/// <returns>TDetail2.</returns>
TDetail5 ProcessDetail5(TDetail5 detail5);
/// <summary>
/// Refreshes the specified header.
/// </summary>
/// <param name="header">header entity.</param>
T Refresh(T header);
/// <summary>
/// Gets the currency rate composite.
/// </summary>
/// <param name="rateType">Type of the rate.</param>
/// <param name="sourceCurrencyCode">The source currency code.</param>
/// <param name="date">The date.</param>
/// <param name="homeCurrency">The home currency.</param>
/// <returns></returns>
CompositeCurrencyRate GetCurrencyRateComposite(
string rateType,
string sourceCurrencyCode,
DateTime date,
string homeCurrency = null);
/// <summary>
/// Gets the Distribution Proration
/// </summary>
/// <param name="pageNumber">Current Page Number</param>
/// <param name="pageSize">Page Size</param>
/// <param name="filter">Filters, if any</param>
/// <param name="orderBy">Order By, if any</param>
/// <returns>List of DistributeProration</returns>
EnumerableResponse<Proration> GetDistributionProrations(int pageNumber, int pageSize,
Expression<Func<Proration, bool>> filter = null, OrderBy orderBy = null);
/// <summary>
/// Gets Manually Prorated Amount
/// </summary>
/// <returns>Amount</returns>
decimal GetManuallyProratedAmount();
/// <summary>
/// Sets the changed data when the user changes distribution proration value.
/// </summary>
/// <param name="lineRevision">Line number to set</param>
/// <param name="amount">Amount to set</param>
/// <returns>Amount Remaining or Manually prorated amount</returns>
void RefreshDistributionProration(int lineRevision, string amount);
/// <summary>
/// Sets the changed data when the user changes distribution proration value.
/// </summary>
/// <param name="getAmountRemaining">Return Amount Remaining or Manually prorated amount</param>
/// <returns>Amount Remaining or Manually prorated amount</returns>
decimal GetDistributionAmountRemaining(bool getAmountRemaining);
#region Comments & Instruction
/// <summary>
/// Gets the Comment Instruction
/// </summary>
/// <param name="pageNumber">Current Page Number</param>
/// <param name="pageSize">Page Size</param>
/// <param name="filter">Filters, if any</param>
/// <param name="orderBy">Order By, if any</param>
/// <returns>List of Comment Instruction</returns>
EnumerableResponse<TDetail2> GetCommentInstruction(int pageNumber, int pageSize,
Expression<Func<TDetail2, bool>> filter = null, OrderBy orderBy = null);
/// <summary>
/// Create New Comment/Instruction Line
/// </summary>
/// <param name="currentDetail">Current Line</param>
/// <returns>Comments/Instruction</returns>
TDetail2 NewCommentInstruction(TDetail2 currentDetail);
/// <summary>
/// Insert/Update Comments/Instruction
/// </summary>
/// <param name="model">Comments/Instruction model</param>
/// <param name="comment">Comment/Instruction to set</param>
/// <param name="lineType">Line Type</param>
/// <returns>Comments/Instruction</returns>
TDetail2 SaveCommentInstruction(TDetail2 model, string comment, string lineType);
/// <summary>
/// Get Result Count
/// </summary>
/// <param name="filter">Filter</param>
/// <returns>Total Count</returns>
int GetCommentInstructionCount(Expression<Func<TDetail2, bool>> filter = null);
#endregion Comments & Instruction
/// <summary>
/// GetDropShipAddressDetail
/// </summary>
/// <returns></returns>
DropShipAddress GetDropShipAddressDetail();
/// <summary>
/// UpdateDropShipAddressDetail
/// </summary>
/// <param name="model"></param>
void UpdateDropShipAddressDetail(DropShipAddress model);
/// <summary>
/// Gets Bill To Location
/// </summary>
/// <returns>Bill To Location Model</returns>
BillToLocation GetBillToLocation();
/// <summary>
/// Sets the Bill To Location Model Attributes.
/// </summary>
/// <param name="model">Bill To Location Model</param>
/// <returns>Bill To Location</returns>
BillToLocation SetBillToLocation(BillToLocation model);
/// <summary>
/// SetVendorInformation
/// </summary>
/// <param name="model"></param>
void SetVendorInformation(VendorBase model);
/// <summary>
/// GetVendorInformation
/// </summary>
/// <returns>VendorBase</returns>
VendorBase GetVendorInformation();
/// <summary>
/// CheckValidDropShipData
/// </summary>
/// <param name="model"></param>
/// <param name="type"></param>
void CheckValidDropShipData(DropShipAddress model, DropShipmentType type);
}
}
|
import { PropsWithChildren, useEffect, useRef, useState } from "react";
export default function AutoClicker(
props: PropsWithChildren<{
href: string;
preserveQueryParams?: boolean;
}>
) {
const clickRef = useRef<HTMLAnchorElement>(null);
let [url, setUrl] = useState(props.href);
useEffect(() => {
if (props.preserveQueryParams) {
setUrl(props.href + window.location.search);
} else {
setUrl(props.href);
}
}, [props.href, props.preserveQueryParams]);
useEffect(() => {
let timeout = setTimeout(() => {
if (clickRef.current) {
clickRef.current.click();
}
}, 200);
return () => {
clearTimeout(timeout);
};
}, [url]);
return (
<a ref={clickRef} href={url}>
{props.children}
</a>
);
}
|
# Endpoint: `GET /puestos/{id}`
Permite obtener todos los registro la tabla.
## Parámetros de URL
- `{nombre_tabla}` (obligatorio): Se requiere especificamente poner el nombre la tabla.
- `{id}` (obligatorio): Identificador único del registro que se desea recuperar.
## Ejemplo de Solicitud
```http
GET /puestos/1
```
## Respuesta Exitosa (Código 200 OK)
```json
{
"id_puesto": 1,
"nombre": "Desarrollador",
"descripcion": "Responsable de desarrollo de software"
}
```
## Respuestas de Errores Posibles
- Código 404 Not Found:
```json
{
"error": "Not found"
}
```
- Código 500 Internal Server Error:
```json
{
"errno": 500,
"error": "internal_error",
"error_description": "Ocurrió un problema para procesar la solicitud"
}
```
## Notas Adicionales
- Asegurate de incluir un ID válido en la solicitud para obtener la información solicitada.
|
import { Route, Routes, useLocation } from 'react-router-dom';
import './App.css';
import Home from '../Home/Home';
import Header from '../Header/Header';
import About from '../About/About';
import AboutNavButton from '../AboutNavButton/AboutNavButton';
import AdoptableCreatures from '../AdoptableCreatures/AdoptableCreatures';
import AdoptableCreaturesNavButton from '../AdoptableCreaturesNavButton/AdoptableCreaturesNavButton';
import CreatureDetail from '../CreatureDetail/CreatureDetail';
import NotFound from '../NotFound/NotFound';
const App = () => {
const location = useLocation();
const isAdoptPage = location.pathname === '/adoptable-creatures';
const isAboutPage = location.pathname === '/about';
return (
<main className='App'>
<Header isAdoptPage={isAdoptPage} isAboutPage={isAboutPage}>
{isAdoptPage ? null : (<AdoptableCreaturesNavButton />)}
{isAboutPage ? null : (<AboutNavButton />)}
</Header>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/adoptable-creatures' element={<AdoptableCreatures />} />
<Route path='/adoptable-creatures/:index' element={<CreatureDetail />} />
<Route path='/*' element={<NotFound />} />
</Routes>
</main>
);
};
export default App;
|
import {LOCALE_ID, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {provideAnimationsAsync} from '@angular/platform-browser/animations/async';
import {ReactiveFormsModule} from "@angular/forms";
import {DonationModule} from "./feature/donation/donation.module";
import {MatFormFieldModule} from "@angular/material/form-field";
import {registerLocaleData} from "@angular/common";
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';
import {NavigationModule} from "./feature/navigation/navigation.module";
registerLocaleData(localeDe, 'de-DE', localeDeExtra)
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
DonationModule,
NavigationModule,
MatFormFieldModule,
],
providers: [
{
provide: LOCALE_ID,
useValue: 'de-DE'
},
provideAnimationsAsync()
],
bootstrap: [AppComponent]
})
export class AppModule { }
|
@extends('layout.main')
@section('title', 'Ubah Karyawan')
@section('content')
<div class="card mb-3">
<div class="bg-holder d-none d-lg-block bg-card"
style="background-image:url({{ asset('falcon/public/assets/img/icons/spot-illustrations/corner-4.png') }});">
</div>
<!--/.bg-holder-->
<div class="card-body position-relative">
<div class="row">
<div class="col-lg-8">
<h3>Data Karyawan</h3>
<p class="mb-0">Perbarui</p>
</div>
</div>
</div>
</div>
@if (session('error'))
<div class="alert alert-danger border-2" role="alert">
<div class="clearfix">
<div class="d-flex align-items-center float-start">
<div class="bg-danger me-3 icon-item">
<span class="fas fa-times-circle text-white fs-3"></span>
</div>
<h5 class="mb-0 text-danger">Error!</h5>
</div>
<button class="btn-close float-end" type="button" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<div class="mt-3">
@foreach (session('error') as $error)
<p>
<span class="dot bg-danger"></span> {{ $error }}
</p>
@endforeach
</div>
</div>
@endif
<div class="card">
<div class="card-header">
<h5>Perbarui Karyawan</h5>
</div>
<form action="{{ url('admin/karyawan/' . $karyawan->id) }}" method="POST" enctype="multipart/form-data"
autocomplete="off">
@csrf
@method('put')
<div class="card-body">
<div class="form-group">
<label for="departemen_id">Departemen</label>
<select class="custom-select form-control" id="departemen_id" name="departemen_id">
<option value="">- Pilih Departemen -</option>
@foreach ($departemens as $departemen)
<option value="{{ $departemen->id }}"
{{ old('departemen_id', $karyawan->departemen_id) == $departemen->id ? 'selected' : '' }}>
{{ $departemen->nama }}</option>
@endforeach
</select>
</div>
{{-- <div class="form-group">
<label for="kode_karyawan">Kode Karyawan</label>
<input type="text" class="form-control" id="kode_karyawan" name="kode_karyawan"
placeholder="Masukan kode" value="{{ old('kode_karyawan') }}">
</div> --}}
<div class="form-group">
<label for="nama">Nama Lengkap</label>
<input type="text" class="form-control" id="nama_lengkap" name="nama_lengkap"
placeholder="Masukan nama lengkap" value="{{ old('nama_lengkap', $karyawan->nama_lengkap) }}">
</div>
<div class="form-group">
<label for="nama">Nama Kecil</label>
<input type="text" class="form-control" id="nama_kecil" name="nama_kecil"
placeholder="Masukan nama kecil" value="{{ old('nama_kecil', $karyawan->nama_kecil) }}">
</div>
<div class="form-group">
<label for="nama">No KTP</label>
<input type="text" class="form-control" id="no_ktp" name="no_ktp" placeholder="Masukan no KTP"
value="{{ old('no_ktp', $karyawan->no_ktp) }}">
</div>
<div class="form-group">
<label for="nama">No SIM</label>
<input type="text" class="form-control" id="no_sim" name="no_sim" placeholder="Masukan no SIM"
value="{{ old('no_sim', $karyawan->no_sim) }}">
</div>
<div class="mb-3">
<label class="form-label" for="gender">Pilih Gender</label>
<select class="form-control" id="gender" name="gender">
<option value="">- Pilih -</option>
<option value="L" {{ old('gender', $karyawan->gender) == 'L' ? 'selected' : null }}>
Laki-laki</option>
<option value="P" {{ old('gender', $karyawan->gender) == 'P' ? 'selected' : null }}>
Perempuan</option>
</select>
</div>
<div class="form-group">
<label>Tanggal Lahir:</label>
<div class="input-group date" id="reservationdatetime">
<input type="date" id="tanggal_lahir" name="tanggal_lahir" placeholder="d M Y sampai d M Y"
data-options='{"mode":"range","dateFormat":"d M Y","disableMobile":true}'
value="{{ old('tanggal_lahir', $karyawan->tanggal_lahir) }}"
class="form-control datetimepicker-input" data-target="#reservationdatetime">
</div>
</div>
<div class="form-group">
<label>Tanggal Gabung:</label>
<div class="input-group date" id="reservationdatetime">
<input type="date" id="tanggal_gabung" name="tanggal_gabung" placeholder="d M Y sampai d M Y"
data-options='{"mode":"range","dateFormat":"d M Y","disableMobile":true}'
value="{{ old('tanggal_gabung', $karyawan->tanggal_gabung) }}"
class="form-control datetimepicker-input" data-target="#reservationdatetime">
</div>
</div>
<div class="mb-3">
<label class="form-label" for="jabatan">Jabatan</label>
<select class="form-control" id="jabatan" name="jabatan">
<option value="">- Pilih Jabatan -</option>
<option value="STAFF" {{ old('jabatan', $karyawan->jabatan) == 'STAFF' ? 'selected' : null }}>
STAFF</option>
</select>
</div>
<div class="form-group">
<label for="telp">No. Telepon</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">+62</span>
</div>
<input type="text" id="telp" name="telp" class="form-control"
placeholder="Masukan nomor telepon" value="{{ old('telp', $karyawan->telp) }}">
</div>
</div>
<div class="form-group">
<label for="alamat">Alamat</label>
<textarea type="text" class="form-control" id="alamat" name="alamat" placeholder="Masukan alamat"
value="">{{ old('alamat', $karyawan->alamat) }}</textarea>
</div>
<div class="form-group">
<label for="gambar">Gambar <small>(Kosongkan saja jika tidak
ingin menambahkan)</small></label>
<input class="form-control @error('gambar') is-invalid @enderror" id="gambar" name="gambar"
type="file" accept="image/*" />
@error('gambar')
<span class="invalid-feedback" role="alert">{{ $message }}</span>
@enderror
</div>
</div>
<div class="card-footer text-end">
<button type="reset" class="btn btn-secondary">Reset</button>
<button type="submit" class="btn btn-primary">Simpan</button>
</div>
</form>
</div>
@endsection
|
import { sampleSize, sample } from 'lodash/fp';
import { corpsePlunderer as attribution } from 'rng/attributions';
import { formatAbilities, rollAbilities } from 'rng/shared/abilities';
import { formatBody } from 'rng/shared/bodies';
import { formatClass } from 'rng/shared/class';
import { formatHabit } from 'rng/shared/habits';
import { formatTrait } from 'rng/shared/traits';
import { blurb, titledEntry, formatTitledEntry } from 'rng/shared/entries';
import {
formatEquipmentList,
hasScroll,
rollArmor,
rollFoodAndWater,
rollSilver,
rollStandardEquipment,
rollWeapon,
} from '../../shared/equipment';
import { rollHp, formatHp } from 'rng/shared/hp';
import { formatName } from 'rng/shared/names';
import { rollOmens, formatOmens } from 'rng/shared/omens';
import tables from 'rng/tables';
import { Character } from 'types/character';
export const corpsePlunderer = (): Character => {
const abilities = rollAbilities(0, -2, 2, 0);
const hp = rollHp(1, 6, abilities.toughness.score);
const omens = rollOmens(1, 2);
const generalEquipment = rollStandardEquipment();
const weapon = rollWeapon(10);
const armor = rollArmor(4, hasScroll(generalEquipment));
const silver = rollSilver();
const silverRange = {min: 10, max: 100};
const foodAndWater = rollFoodAndWater();
const equipment = [foodAndWater, weapon, armor, ...generalEquipment, silver];
const graveSight = titledEntry(attribution, 'graveSight');
const pricePaid = titledEntry(attribution, 'pricePaid', 'plainBox');
const graveItems = [
'graveHonedShovel',
'agathasSkull',
'graveDust',
'graveCrow',
'witchesElixir',
'bonePickersBlade',
'wifesHand',
'cryptWornCrowbar',
].map((x) => titledEntry(attribution, x));
return {
tags: [attribution.id],
smalls: [
formatName(sample(tables.names)!),
formatClass('harkenstone.corpsePlunderer'),
formatHp(hp),
formatOmens(omens, 2),
],
bigs: [
{
component: { id: 'introduction' },
header: { id: 'character.stats.titles.introduction', values: {} },
content: [
blurb(attribution),
...sampleSize(2, tables.traits).map((trait) => formatTrait(trait)),
formatBody(sample(tables.bodies)!),
formatHabit(sample(tables.habits)!),
],
},
formatTitledEntry(pricePaid),
formatTitledEntry(sample(graveItems)!),
formatTitledEntry(graveSight),
formatAbilities(abilities),
formatEquipmentList(equipment, abilities.presence.score, silverRange),
],
};
};
|
import React, { useState } from 'react';
import { View, StyleSheet, Image, TouchableOpacity } from 'react-native';
import Text from './DefaultText';
import { ScreenProps } from '../types';
import { Color } from '../assets/GlobalStyles';
import { widthScale, heightScale, moderateScale } from '../utils/Scaling';
import ScoreReset from './modal/ScoreReset';
import PlayerSettings from './modal/PlayerSettings';
interface IGameHeader {
title: string;
isBack: boolean;
isPlaySetting: boolean;
isTeamSetting: boolean;
isRefreshSetting: boolean;
navigation: ScreenProps['navigation'];
}
export default function GameHeader({
navigation,
title,
isBack = false,
isPlaySetting = false,
isTeamSetting = false,
isRefreshSetting = false
}: IGameHeader) {
const [resetModalVisible, setResetModalVisible] = useState(false);
const [playerSettingModalVisible, setPlayerSettingModalVisible] = React.useState(false);
const handlerBack = () => {
navigation.goBack();
};
const handlerTeamSetting = () => {
setPlayerSettingModalVisible(true);
};
const handlerPlaySetting = () => {
navigation.navigate('PlaySettings');
};
const handlerScoreResetSetting = () => {
setResetModalVisible(true);
};
return (
<>
<View style={styles.headerContainer}>
{isBack && (
<TouchableOpacity onPress={handlerBack}>
<View style={styles.settingWrap}>
<View style={styles.iconWrap}>
<Image
style={styles.iconArrow}
resizeMode="cover"
source={require('../assets/icons/icon-left-arrow.png')}
/>
</View>
</View>
</TouchableOpacity>
)}
<Text style={styles.mainText}>{title}</Text>
{isPlaySetting && (
<TouchableOpacity onPress={handlerPlaySetting}>
<View style={styles.settingWrap}>
<View style={styles.iconWrap}>
<Image
style={styles.iconSetting}
resizeMode="cover"
source={require('../assets/icons/icon-setting.png')}
/>
</View>
<Text style={styles.settingText}>플레이 설정</Text>
</View>
</TouchableOpacity>
)}
{isTeamSetting && (
<TouchableOpacity onPress={handlerTeamSetting}>
<View style={styles.settingWrap}>
<View style={styles.iconWrap}>
<Image
style={styles.iconSetting}
resizeMode="cover"
source={require('../assets/icons/icon-team-setting.png')}
/>
</View>
<Text style={styles.settingText}>팀 설정</Text>
</View>
</TouchableOpacity>
)}
{isRefreshSetting && (
<TouchableOpacity onPress={handlerScoreResetSetting}>
<View style={styles.settingWrap}>
<View style={styles.iconWrap}>
<Image
style={styles.iconSetting}
resizeMode="cover"
source={require('../assets/icons/icon-refresh-setting.png')}
/>
</View>
<Text style={styles.settingText}>점수 초기화</Text>
</View>
</TouchableOpacity>
)}
</View>
<ScoreReset
modalVisible={resetModalVisible}
setModalVisible={setResetModalVisible}
/>
<PlayerSettings modalVisible={playerSettingModalVisible} setModalVisible={setPlayerSettingModalVisible} />
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: Color.background,
paddingHorizontal: widthScale(30)
},
headerContainer: {
flexDirection: 'row',
alignItems: 'center'
},
mainText: {
flex: 1,
color: Color.mainText,
textAlign: 'center',
fontSize: heightScale(50),
fontWeight: '600',
fontFamily: 'ONE Mobile POP'
},
settingWrap: {
alignItems: 'center',
justifyContent: 'center'
},
iconWrap: {
justifyContent: 'center',
alignItems: 'center'
},
iconArrow: {
width: heightScale(48),
height: heightScale(36)
},
iconSetting: {
width: heightScale(40),
height: heightScale(40)
},
settingText: {
color: '#B9BAB9',
fontWeight: '500',
fontSize: heightScale(20),
marginTop: heightScale(12)
}
});
|
package cucumber.runner;
import java.net.URL;
import java.util.ArrayList;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class ConfigurationArgsBuilder {
static Option urlOption =
Option.builder("u")
.longOpt("url")
.hasArg()
.required()
.desc("Url where the end to end test will be run against")
.type(URL.class)
.build();
static Options buildOptions() {
Options options = new Options();
options.addOption(urlOption);
options.addOption("h", "help", false, "Print help");
options.addOption("g", "glue", true, "Cucumber argument");
return options;
}
public static Configuration parse(String[] args) throws ParseException {
CommandLineParser parser = new DefaultParser(true);
Options options = buildOptions();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("run-test", options);
}
return parse(cmd);
}
public static String[] cucumberArgs(String[] args) throws ParseException {
CommandLineParser parser = new DefaultParser(true);
Options options = buildOptions();
CommandLine cmd = parser.parse(options, args);
ArrayList<String> cucumeberArgs = new ArrayList<>();
for (Option opt : cmd.getOptions()) {
if (opt.getDescription().indexOf("Cucumber") >= 0) {
cucumeberArgs.add("--" + opt.getLongOpt());
cucumeberArgs.addAll(opt.getValuesList());
}
}
cucumeberArgs.addAll(cmd.getArgList());
return cucumeberArgs.toArray(new String[0]);
}
static Configuration parse(CommandLine cmd) throws ParseException {
return new Configuration(cmd.getParsedOptionValue(urlOption));
}
}
|
"use client";
import { UserInfoSchema } from "@/schemas";
import { Control } from "react-hook-form";
import * as z from "zod";
import { Input } from "../ui/input";
import { resolveResultByField } from "@/lib/th-address-utls";
import { useReducer, useState } from "react";
import ThAutoCompleteBox from "./th-auto-complete-selection";
import {
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../ui/form";
export interface AddressObject {
subDistrict: string;
district: string;
province: string;
zipCode: string;
}
interface Action {
type: string;
payload: any;
}
const initialState = {
entities: [],
searchKey: "",
search: "",
form: {
subDistrict: "",
district: "",
province: "",
zipCode: "",
},
};
function reducer(state: any, action: Action) {
const { payload } = action;
switch (action.type) {
case SEARCH_ACTION:
return {
...state,
entities: resolveResultByField(payload.type, payload.search),
searchKey: payload.type,
search: payload.search,
};
case FORM_CHANGE_ACTION:
return {
...state,
form: {
...state.form,
[payload.name]: payload.value,
},
};
case SELECT_ADDRESS:
return {
...state,
form: {
...state.form,
...payload,
},
};
default:
throw new Error();
}
}
const SEARCH_ACTION = "SEARCH_ACTION";
const FORM_CHANGE_ACTION = "FORM_CHANGE_ACTION";
const SELECT_ADDRESS = "SELECT_ADDRESS";
interface Props {
control: Control<z.infer<typeof UserInfoSchema>>;
isPending: boolean;
isLoading: boolean;
onSetFormValue(name: string, value: unknown, config?: Object): void;
}
export default function ThAddressAutoComplete({
control,
isPending,
isLoading,
onSetFormValue,
}: Props) {
const [anchorEl, setAnchorEl] = useState<string>("");
const [state, dispatch] = useReducer(reducer, initialState);
const handlerClick = (obj: AddressObject) => {
setAnchorEl("");
dispatch({
type: SELECT_ADDRESS,
payload: { ...obj },
});
onSetFormValue("subDistrict", obj.subDistrict);
onSetFormValue("district", obj.district);
onSetFormValue("province", obj.province);
onSetFormValue("zipCode", obj.zipCode.toString());
};
const handlerFormChange = (event: any) => {
dispatch({
type: FORM_CHANGE_ACTION,
payload: {
name: event.target,
search: event.target.value,
},
});
dispatch({
type: SEARCH_ACTION,
payload: {
type: event.target.name,
search: event.target.value,
},
});
setAnchorEl(event.target.name);
};
return (
<div className="flex flex-col justify-center gap-4">
<div className="grid">
<FormField
control={control}
name="address"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel>ที่อยู่</FormLabel>
<FormControl>
<Input
disabled={isLoading || isPending}
{...field}
placeholder="ที่อยู่"
type="text"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex flex-row gap-2">
<FormField
control={control}
name="subDistrict"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel>ตำบล</FormLabel>
<FormControl>
<Input
disabled={isLoading || isPending}
autoComplete="none"
placeholder="ตำบล"
{...field}
onChange={(e) => {
field.onChange(e);
handlerFormChange(e);
}}
type="text"
/>
</FormControl>
<ThAutoCompleteBox
onSelect={handlerClick}
address={state.entities}
isActive={anchorEl == "subDistrict"}
/>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={control}
name="district"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel>อำเภอ</FormLabel>
<FormControl>
<Input
disabled={isLoading || isPending}
autoComplete="none"
placeholder="อำเภอ"
{...field}
onChange={(e) => {
field.onChange(e);
handlerFormChange(e);
}}
type="text"
/>
</FormControl>
<ThAutoCompleteBox
onSelect={handlerClick}
address={state.entities}
isActive={anchorEl == "district"}
/>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex flex-row gap-2">
<FormField
control={control}
name="province"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel>จังหวัด</FormLabel>
<FormControl>
<Input
disabled={isLoading || isPending}
autoComplete="none"
placeholder="จังหวัด"
{...field}
onChange={(e) => {
field.onChange(e);
handlerFormChange(e);
}}
type="text"
/>
</FormControl>
<ThAutoCompleteBox
onSelect={handlerClick}
address={state.entities}
isActive={anchorEl == "province"}
/>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={control}
name="zipCode"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel>รหัสไปรษณีย์</FormLabel>
<FormControl>
<Input
disabled={isLoading || isPending}
autoComplete="none"
placeholder="รหัสไปรษณีย์"
{...field}
onChange={(e) => {
field.onChange(e);
handlerFormChange(e);
}}
type="text"
/>
</FormControl>
<ThAutoCompleteBox
onSelect={handlerClick}
address={state.entities}
isActive={anchorEl == "zipCode"}
/>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
);
}
|
  一般说来,类的数据成员在声明时不能设置初值,都是在构造函数中设置。但被声明成static的数据成员后,在程序运行的过程中一定要设置初值,而且设置初值的操作只能有一次。另外,静态数据成员必须在类外部设置初值,语法如下:
<br/>
`

数据类型 类名称::静态数据成员=初值;
`
静态数据成员值的引用方式,语法如下:
<br/>
`

类名称::静态数据成员名称;
`
```
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std
class Dog{
private:
char* pName;
char* pColor;
static int counter; //声明为静态数据成员
public:
Dog(char* pN, char* pC)
{
pName = new char[strlen(pN) + 1];
strcpy(pName, pN); //设置字符串
pColor = new char[strlen(pC) + 1];
strcpy(pColor, pC); //设置字符串
counter++;
}

int getCounter(){ return counter; }
};
int Dog::counter = 0; //类外部设置静态数据成员初值

int main(int argc, const char * argv[])
{
Dog d1("小白", "白色"); //声明对象d1
Dog d2("小黄", "黄色"); //声明对象d2
Dog d3("小红", "红色"); //声明对象d3
cout<<d1.getCounter()<<endl; //计算产生对象的总数
system("pause");
return 0;
}
```
<br/>
***
<br/>
># 对象传址调用
  对象传址调用是指所传入的参数为对象的内存地址,即以“&”运算符将地址传给函数,在函数内则通过结构指针来存取对象数据,语法如下:
`

函数类型 函数名称(类名称1 *参数1, 类名称2 *参数2, ……)

{

//函数的程序代码

}
`
以两个对象参数为例,其调用方式为:
`

对象名称.函数名称(&对象参数1, &对象参数2);
`
12-3-3 对象传引用调用
  C++中的传引用调用方式比传址调用的应用容易理解,因为它本身只是别名(alias)的应用。在使用对象传引用调用时,只需要在函数原型和定义函数所要传递的参数前加上&运算符即可。另外,引用使用“.”来存取对象成员。函数原型声明如下:
```

函数类型 函数名称(类名称1 &参数1, 类名称2 &参数2, ……)

{
//函数的程序代码
}
```
以两个对象参数为例,其调用方式为:
```

对象名称.函数名称(对象参数1,对象参数2);
```
|
package com.justin.springboottest.designpatterns.behavioral.observer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
// maintain a list of interested parties and notify them whenever the events are available
public class EventManager {
Map<String, ArrayList<EventListener>> listeners = new HashMap<>();
// one operation correspond to a list of subscribers
public EventManager(String ... operations) {
for (String op : operations) {
listeners.put(op, new ArrayList<>());
}
}
// check the existing list, if not subscribed, add to the list
public void subscribe(String event, EventListener listener) {
ArrayList<EventListener> users = listeners.get(event);
if (!users.contains(listener)) {
users.add(listener);
}
}
// check the existing list, if subscribed, remove from the list
public void unsubscribe(String event, EventListener listener) {
ArrayList<EventListener> users = listeners.get(event);
if (users.contains(listener)) {
users.remove(listener);
}
}
// 一次通知一個群組(event)
public void notify(String event, String file) {
ArrayList<EventListener> users = listeners.get(event);
for (EventListener user : users) {
user.notify(event, file);
}
}
}
|
const std = @import("std");
const print = std.debug.print;
const assert = std.debug.assert;
const expectEqual = std.testing.expectEqual;
const absInt = std.math.absInt;
const indexOfScalar = std.mem.indexOfScalar;
const max = std.math.max;
const min = std.math.min;
const round = std.math.round;
const Parser = @import("lib/parse3.zig").Parser;
const REAL_INPUT = @embedFile("inputs/day08.txt");
pub fn main() !void {
print("Part 1: {}\n", .{try part1(&Parser.init(REAL_INPUT))});
print("Part 2: {}\n", .{try part2(&Parser.init(REAL_INPUT))});
// High: 1014835
}
fn part1(input: *Parser) !u64 {
var result: u64 = 0;
while (input.subparse("\n")) |*line| {
_ = try line.takeType([]const u8, "|");
_ = try line.takeDelimiter(" ");
while (try line.takeType([]const u8, " ")) |signals| {
if (signals.len == 2 or signals.len == 3 or signals.len == 4 or signals.len == 7) {
result += 1;
}
}
}
return result;
}
fn part2(input: *Parser) !u64 {
var sum: u64 = 0;
while (input.subparse("\n")) |*line| {
var digits: [10]u8 = undefined;
for (digits) |_, i| {
digits[i] = toU8((try line.takeType([]const u8, " ")).?);
}
var representations: [10]u8 = [_]u8 {1 << 7} ** 10;
representations[1] = try takeByLength(digits, 2);
representations[4] = try takeByLength(digits, 4);
representations[7] = try takeByLength(digits, 3);
representations[8] = try takeByLength(digits, 7);
representations[2] = try findTwo(digits);
representations[9] = try findNine(digits, representations[4], representations[8]);
representations[3] = try findThree(digits, representations[1]);
representations[5] = try findFive(digits, representations);
representations[0] = try findZero(digits, representations);
representations[6] = try findSix(digits, representations);
for (representations) |r| assert(r < 1 << 7);
assert(@popCount(u8, representations[0]) == 6);
assert(@popCount(u8, representations[1]) == 2);
assert(@popCount(u8, representations[2]) == 5);
assert(@popCount(u8, representations[3]) == 5);
assert(@popCount(u8, representations[4]) == 4);
assert(@popCount(u8, representations[5]) == 5);
assert(@popCount(u8, representations[6]) == 6);
assert(@popCount(u8, representations[7]) == 3);
assert(@popCount(u8, representations[8]) == 7);
assert(@popCount(u8, representations[9]) == 6);
for (representations) |r| assert(std.mem.count(u8, &representations, &[_]u8 {r}) == 1);
try line.skipSequence("| ");
var this_number: u64 = 0;
while (try line.takeType([]const u8, " ")) |digit| {
var decoded_digit = indexOfScalar(u8, &representations, toU8(digit)).?;
this_number *= 10;
this_number += decoded_digit;
}
assert(this_number < 10_000);
sum += this_number;
}
return sum;
}
fn findSix(digits: [10]u8, representations: [10]u8) !u8 {
for (digits) |digit| {
if (indexOfScalar(u8, &representations, digit) == null) return digit;
}
return error.NotFound;
}
fn findZero(digits: [10]u8, representations: [10]u8) !u8 {
var result: ?u8 = null;
for (digits) |digit| {
if (indexOfScalar(u8, &representations, digit) != null) continue;
if (@popCount(u8, digit) != 6) continue;
if (digit | representations[7] == digit) {
assert(result == null);
result = digit;
}
}
return result.?;
}
fn findFive(digits: [10]u8, representations: [10]u8) !u8 {
// From the three unknown digits only five is missing 2 segments
var result: ?u8 = null;
for (digits) |digit| {
if (indexOfScalar(u8, &representations, digit) != null) continue;
if (@popCount(u8, digit) == 5) {
assert(result == null);
result = digit;
}
}
return result.?;
}
fn findThree(digits: [10]u8, one: u8) !u8 {
// From digits missing 2 segments only three can be ored with one
var result: ?u8 = null;
for (digits) |digit| {
if (@popCount(u8, digit) != 5) continue;
if (one | digit == digit) {
assert(result == null);
result = digit;
}
}
return result.?;
}
fn findNine(digits: [10] u8, four: u8, eight: u8) !u8 {
// From (9,8,4) contains 4
var result: ?u8 = null;
for (digits) |digit| {
if (digit == eight) continue;
if (digit == four) continue;
if (four & digit == four) {
assert(result == null);
result = digit;
}
}
return result.?;
}
fn findTwo(digits: [10]u8) !u8 {
// 2 is the only one with F off
var bit: u8 = 1;
nextBit: while (bit < 1 << 8) : (bit <<= 1) {
var missingIndex: ?usize = null;
for (digits) |digit, i| {
if (digit & bit == 0) {
if (missingIndex == null) {
missingIndex = i;
} else {
continue :nextBit;
}
}
}
if (missingIndex) |i| return digits[i];
}
return error.NotFound;
}
fn toU8(segments: []const u8) u8 {
var result: u8 = 0;
for (segments) |s| {
result += @as(u8, 1) << @intCast(u3, s - 'a');
}
return result;
}
fn takeByLength(digits: [10]u8, length: usize) !u8 {
for (digits) |digit| {
if (@popCount(u8, digit) == length) return digit;
}
return error.NotFound;
}
test "Part 1" {
const test_input =
\\be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
\\edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
\\fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
\\fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
\\aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
\\fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
\\dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
\\bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
\\egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
\\gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce
;
try expectEqual(@as(u64, 26), try part1(&Parser.init(test_input)));
}
test "Part 2 a" {
const test_input =
\\acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf
;
try expectEqual(@as(u64, 5353), try part2(&Parser.init(test_input)));
}
test "Part 2 b" {
const test_input =
\\be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
\\edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
\\fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
\\fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
\\aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
\\fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
\\dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
\\bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
\\egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
\\gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce
;
try expectEqual(@as(u64, 61229), try part2(&Parser.init(test_input)));
}
|
#include "fileUtils.h"
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
char *logFilePath;
int logToFile(const char *logFilePath, const char *text) {
if (!logFilePath) {
return -1;
}
FILE *file = fopen(logFilePath, "a");
if (file == NULL) {
return 1;
}
fprintf(file, text);
fprintf(file, "\n");
fclose(file);
return 0;
}
int getBatteryLevel() {
int batteryLevel =
std::atoi(readFile("/sys/class/power_supply/BAT0/capacity"));
return batteryLevel;
}
int sendNotification(char *batteryLevel) {
char textStart[] = "notify-send 'battery level: ";
char *command = strcat(strcat(textStart, batteryLevel), "'");
FILE *pipe = popen(command, "r");
if (pipe == NULL) {
return 1;
}
return 0;
}
void daemonStart() {
while (true) {
sleep(60);
int batteryLevel = getBatteryLevel();
char sbatteryLevel[10];
sprintf(sbatteryLevel, "%d", batteryLevel);
logToFile(logFilePath, sbatteryLevel);
if (batteryLevel < 20) {
sendNotification(sbatteryLevel);
}
}
}
int main(int argc, char **argv) {
logFilePath = argv[1];
pid_t pid = fork();
if (pid < 0) {
std::cerr << "Failed to fork the process.\n";
return 1;
}
if (pid > 0) {
return 0;
}
pid_t sid = setsid();
if (sid < 0) {
std::cerr << "Failed to create a new session ID.\n";
return 1;
}
if ((chdir("/")) < 0) {
std::cerr << "Failed to change the working directory.\n";
return 1;
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
open("/dev/null", O_RDONLY);
open("/dev/null", O_RDWR);
open("/dev/null", O_RDWR);
daemonStart();
return 0;
}
|
// ignore_for_file: must_be_immutable, use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qr_quill/models/create_code.dart';
import 'package:qr_quill/screens/create/qr_code/create_qr_results.dart';
import 'package:qr_quill/services/isar_db.dart';
import 'package:qr_quill/shared/animations.dart';
import 'package:qr_quill/shared/button.dart';
import 'package:qr_quill/shared/constants.dart';
import 'package:qr_quill/shared/logger.dart';
import 'package:qr_quill/shared/navigator.dart';
import 'package:qr_quill/shared/snackbar.dart';
import 'package:qr_quill/shared/textfield.dart';
class EmailForm extends StatefulWidget {
EmailForm({super.key, required this.qrCodeName});
String qrCodeName;
@override
State<EmailForm> createState() => _EmailFormState();
}
class _EmailFormState extends State<EmailForm> with SingleTickerProviderStateMixin {
final _formKey = GlobalKey<FormState>();
bool obscureText = true;
bool isLoading = false;
String email = '';
String subject = '';
String message= '';
String data = '';
String qrData = '';
final isarDb = IsarDB();
final dateGenerated = DateTime.now().toString().substring(0, 16);
/// Function to handle emailng of message
String generateMail(String email, String subject, String message) {
final uri = Uri(
scheme: 'mailto',
path: email,
queryParameters: {
'subject': subject,
'body': message,
},
);
return uri.toString();
}
validateForm() async {
if (_formKey.currentState!.validate()) {
logger(email);
// Collect all data
data = 'Email: $email\nSubject: $subject\n\nMessage:\n$message';
qrData = generateMail(email, subject, message);
showSnackbar(context, 'Generating QR Code...');
setState(() {
isLoading = true;
});
await Future.delayed(kAnimationDuration2);
navigatorPushReplacement(context, ShowQRCode(
qrData: qrData,
stringData: data,
qrCodeName: widget.qrCodeName,
selectedCategory: QRCodeCategory.Email.name,
dateGenerated: dateGenerated,
)
);
await isarDb.addCreatedCode(
context,
CreateCode(
type: 'QR Code',
codeName: widget.qrCodeName,
category: QRCodeCategory.Email.name,
codeData: qrData,
stringData: data,
datetime: dateGenerated,
),
);
} else {
showSnackbar(context, 'Field validation failed. Ensure all fields are valid.');
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
EmailTextField(
onChanged: (value) {
setState(() {
email = value!;
});
},
hintText: 'Receiver Email',
enabledBorderColor: kFontTheme(context),
focusedBorderColor: kSecondaryColor,
errorBorderColor: kRedColor,
focusedErrorBorderColor: kRedColor,
errorTextStyleColor: kRedColor,
cursorColor: kSecondaryColor,
iconColor: kSecondaryColor,
),
NormalTextField(
hintText: 'Subject',
textColor: kSecondaryColor,
onChanged: (value) {
setState(() {
subject = value!;
});
},
enabledBorderColor: kFontTheme(context),
focusedBorderColor: kSecondaryColor,
errorBorderColor: kRedColor,
focusedErrorBorderColor: kRedColor,
errorTextStyleColor: kRedColor,
iconColor: kSecondaryColor,
cursorColor: kSecondaryColor,
prefixIcon: Icons.subject,
),
TextareaTextField(
hintText: 'Enter message',
onChanged: (value) {
setState(() {
message = value!;
});
},
enabledBorderColor: kFontTheme(context),
focusedBorderColor: kSecondaryColor,
errorBorderColor: kRedColor,
focusedErrorBorderColor: kRedColor,
errorTextStyleColor: kRedColor,
cursorColor: kSecondaryColor,
),
Button(
buttonColor: kSecondaryColor,
buttonText: 'Generate QR Code',
onPressed: () {
validateForm();
},
inactive: false,
),
SizedBox(height:10.h),
].animate(
interval: kAnimationDurationMs(100),
effects: MyEffects.fadeSlide(offset: const Offset(-0.05, 0)),
),
),
);
}
}
|
//
// PlayerCollectionViewCell.swift
// HomePokerTable
//
// Created by Sanghun Park on 19.04.22.
//
import UIKit
class PlayerCollectionViewCell: UICollectionViewCell {
// MARK: - Properties
var player: Player?
// MARK: IBOutlets
@IBOutlet weak var playerCellView: UIView!
@IBOutlet weak var playerButton: UIButton!
@IBOutlet weak var betLabel: UILabel!
@IBOutlet weak var assetLabel: UILabel!
// MARK: - Methods
// MARK: ConfigureCell
func configureCell(player: Player) {
// Keep track of the player this cell represents
self.player = player
// Set the title and label to the view the represents the player
playerButton.setTitle(player.name, for: .normal)
betLabel.text = String(player.bet + player.raise)
assetLabel.text = String(player.asset)
// Apply Style to cell
self.applyStyleToComponents()
// Configure highlighting of player selection in CollectionView
self.playerSelectionControl()
// Switch on/off alpha of PlayerButton depend on Player Asset
self.switchPlayerButtonActivation()
}
// MARK: Methods to style UI components
func applyStyleToComponents() {
self.addRadiusToView(uiView: playerCellView, radius: 20)
self.addBorderToPlayerView()
self.addStyleToPlayerButton()
}
func addRadiusToView(uiView: UIView?, radius: Int) {
guard let view = uiView else { return }
view.layer.cornerRadius = CGFloat(radius)
}
func addBorderToPlayerView() {
guard let view = self.playerCellView else { return }
view.layer.borderWidth = 3
view.layer.borderColor = UIColor(red: 0.192, green: 0.294, blue: 0.169, alpha: 1).cgColor
}
func addStyleToPlayerButton() {
guard let button = self.playerButton else { return }
//button.layer.backgroundColor = UIColor(red: 0.439, green: 0.561, blue: 0.392, alpha: 1).cgColor
button.layer.cornerRadius = 20
button.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
// MARK: Methods to control Selection on/off of cell
func playerSelectionControl() {
// Reset the state of the cell by checking the selected status of the player and then show the selection On or Off accordingly
// implemented because system will reuse the cells in the collection view
// For more, check `collectionView(willDisplay)` in CollectionViewDataSource and `collectionView(willDisplay)` in CollectionViewDelegate from the `PlayerViewController.swift` file
guard let player = player else { return }
if player.isSelected {
selectOn()
}
else {
selectOff()
}
}
func selectOn() {
guard let button = self.playerButton else { return }
button.layer.backgroundColor = UIColor(red: 0.439, green: 0.561, blue: 0.392, alpha: 1).cgColor
}
func selectOff() {
guard let button = self.playerButton else { return }
button.layer.backgroundColor = .none
}
// MARK: A method to Activate and Deactivate playerButton
func switchPlayerButtonActivation() {
guard let player = self.player else { return }
guard let button = self.playerButton else { return }
if player.isActive {
button.alpha = 1
}
else {
button.alpha = 0.5
}
}
}
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../components/custom_appbar_component.dart';
import '../../../components/custom_button_component.dart';
import '../../../components/custom_text_component.dart';
import '../../../components/custom_textfield_component.dart';
import '../../../components/main_scaffold_component.dart';
import '../../../components/svg_icons_components.dart';
import '../../../routes/app_routes.dart';
import '../../../utils/styles.dart';
import 'controller/chatting_controller.dart';
class ChattingScreen extends GetView<ChattingController> {
const ChattingScreen({super.key});
@override
Widget build(BuildContext context) {
return MainScaffold(
backgroundColor: Styles.black,
appBar: CustomAppBar(
leading: true,
bgColor: Styles.black,
backButtonColor: Styles.white,
centerTitle: false,
leadingWidget: Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: Get.height * 50 / 812,
width: Get.width * 50 / 420,
child: Stack(
clipBehavior: Clip.none,
children: [
CircleAvatar(
backgroundColor: Colors.orange,
radius: 22,
backgroundImage: NetworkImage(Get.arguments['image']),
),
Align(
alignment: Alignment.bottomRight,
child: Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: true ? Styles.green : Styles.greySilver,
border:
Border.all(width: 1, color: Colors.white)),
child: const Text(''),
)),
],
),
),
const SizedBox(
width: 10,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
children: [
CustomTextWidget(
text: Get.arguments['name'],
fontWeight: FontWeight.w700,
color: Styles.black,
),
if (Get.arguments['isVerified'])
const SizedBox(
width: 10,
),
if (Get.arguments['isVerified'])
const SvgIconComponent(icon: 'verified_new.svg'),
],
),
const SizedBox(
height: 5,
),
CustomTextWidget(
text: Get.arguments['role'],
color: Styles.orangeBorder,
fontSize: 12,
),
],
),
],
),
),
trailing: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: SvgIconComponent(
icon: 'menu.svg',
onTap: () {
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius:
BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: Styles.screenPadding),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(
height: 40,
),
const Row(
children: [
SvgIconComponent(icon: 'mute.svg'),
SizedBox(
width: 10,
),
CustomTextWidget(
text: 'Mute',
fontWeight: FontWeight.w700,
),
],
),
const SizedBox(
height: 30,
),
GestureDetector(
onTap: () {
Get.back();
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(20)),
),
builder: (context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: Styles.screenPadding),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(
height: 33,
),
SizedBox(
width: 75,
height: 75,
child: Image.asset(
Styles.getCommonImage(
"angel_herwitz.png"))
// SvgImageComponent(
// icon: 'angel_herwitz.png',
// width: 75,
// height: 75,
// ),
),
const SizedBox(height: 24),
const CustomTextWidget(
textAlign: TextAlign.center,
text:
'Lorem ipsum dolor sit amet consectetur. Maecenas amet arcu et aenean bibendum odio tristique parturient. Nibh porttitor ornare purus etiam vulputate.',
fontWeight: FontWeight.w500,
fontSize: 12,
color: Styles.solidGrey,
),
const SizedBox(height: 26),
CustomButton(
onTap: () {
Get.back();
},
radius: 9,
height: 48,
bgColor: Styles.red,
fontSize: 14,
title: "Block",
fontWeight: FontWeight.w800,
fontColor: Styles.white,
),
const SizedBox(height: 20),
],
),
);
});
// Get.back();
},
child: const Row(
children: [
SvgIconComponent(icon: 'block.svg'),
SizedBox(
width: 10,
),
CustomTextWidget(
text: 'Block User',
fontWeight: FontWeight.w700,
),
],
),
),
const SizedBox(
height: 40,
),
],
),
);
});
},
),
),
),
body: GetBuilder<ChattingController>(builder: (context) {
return Stack(
children: [
SingleChildScrollView(
controller: controller.scrollController,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Styles.screenPadding),
child: Column(
children: [
SizedBox(
height: controller.isQuote ? 60 : 20,
),
Center(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14),
color: Styles.solidGrey.withOpacity(0.1),
),
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
child: const CustomTextWidget(
text: 'Today',
fontSize: 12,
color: Styles.white,
),
)),
ListView.separated(
itemCount: controller.chatList.length,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (
context,
index,
) {
return messageWidget(
time: controller.chatList[index]['time'],
msg: controller.chatList[index]['message'],
file: controller.chatList[index]['file'],
fileType: controller.chatList[index]['fileType'],
isMe: controller.chatList[index]['isMe']);
},
separatorBuilder: (
context,
index,
) {
return const SizedBox(
height: 15,
);
},
),
const SizedBox(
height: 100,
),
],
),
),
),
if (controller.isQuote)
GestureDetector(
onTap: () {
Get.toNamed(Routes.quoteDetail);
},
child: Align(
alignment: Alignment.topCenter,
child: Container(
height: 50,
alignment: Alignment.center,
decoration: const BoxDecoration(
color: Styles.mainScaffoldColor,
),
child: const Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SvgIconComponent(icon: 'qoute.svg'),
SizedBox(
width: 10,
),
CustomTextWidget(
text: 'View Quote Detail',
color: Styles.orangeYellow,
fontWeight: FontWeight.w700,
fontSize: 16,
)
],
),
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Styles.screenPadding),
child: Container(
padding: const EdgeInsets.only(bottom: 15, top: 10),
color: Colors.black,
child: CustomTextField(
maxLines: 1,
cursorColor: Styles.solidGrey,
fillColor: Styles.greyLight3,
hint: "Write a message",
// focusColor: Styles.solidGrey,
hintColor: Styles.black.withOpacity(0.4),
textInputType: TextInputType.name,
txtController: controller.msgTextController,
textInputAction: TextInputAction.next,
node: controller.focusSearch,
suffixWidget: const Row(
mainAxisSize: MainAxisSize.min,
children: [
SvgIconComponent(icon: 'attachment.svg'),
SizedBox(
width: 20,
),
SvgIconComponent(icon: 'send.svg'),
SizedBox(
width: 20,
),
],
),
onTap: () {},
borderRadius: 24,
),
),
),
),
],
);
}),
);
}
Widget messageWidget({
required bool isMe,
required String? msg,
required String? file,
required String? fileType,
required String? time,
}) {
return GestureDetector(
onTap: () {
if (file != null && fileType == 'pdf') {
controller.file = file;
controller.update();
Get.toNamed(Routes.viewFile);
}
},
child: Column(
crossAxisAlignment:
isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
file == null
? Container(
decoration: BoxDecoration(
color: isMe ? Styles.orangeYellow : Styles.orangeYellow,
borderRadius: BorderRadius.only(
bottomLeft: const Radius.circular(10),
bottomRight:
isMe ? const Radius.circular(10) : Radius.zero,
topRight: isMe ? Radius.zero : const Radius.circular(10),
topLeft: const Radius.circular(10),
),
),
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
child: CustomTextWidget(
text: msg ?? '',
fontSize: 13,
color: isMe ? Styles.black : Styles.black,
),
)
: fileType == 'image'
? Container(
height: 200,
width: 200,
decoration: BoxDecoration(
color: Styles.orangeYellow,
borderRadius: BorderRadius.circular(16),
image: DecorationImage(
image: NetworkImage(file), fit: BoxFit.cover)),
)
: Container(
decoration: BoxDecoration(
color: isMe ? Styles.orangeYellow : Styles.orangeYellow,
borderRadius: BorderRadius.only(
bottomLeft: const Radius.circular(10),
bottomRight:
isMe ? const Radius.circular(10) : Radius.zero,
topRight:
isMe ? Radius.zero : const Radius.circular(10),
topLeft: const Radius.circular(10),
),
),
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 12),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SvgIconComponent(
icon: 'pdf_2x.svg',
height: 35,
),
const SizedBox(
width: 10,
),
CustomTextWidget(
text: file.split('/').last,
fontSize: 13,
color: isMe ? Styles.black : Styles.black,
),
],
))
],
),
);
}
}
|
import { Component, OnInit } from '@angular/core';
/**
This component is responsible for displaying a list of files along with their metadata.
It provides pagination functionality to navigate between different pages of files.
---------------------------------------------------------------------
Input Properties
orders: An array of orders containing information about files.
itemsPerPage: The number of files to be displayed per page.
---------------------------------------------------------------------
Functionality
The component displays a table of files and their metadata.
The component provides pagination functionality to navigate between different pages of files.
The component displays the total number of files and the current page number.
*/
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
Math = Math;
orders = [
{
documentName: 'Documents 1',
dataModifica: '11 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/pdf.svg'
},
{
documentName: 'Documents 2',
dataModifica: '11 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/pictures.svg'
},
{
documentName: 'Documents 3',
dataModifica: '11 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/word.svg'
},
{
documentName: 'Documents 4',
dataModifica: '11 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/excel.svg'
},
{
documentName: 'Documents 5',
dataModifica: '06 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/pdf.svg'
},
{
documentName: 'Documents 6',
dataModifica: '06 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/pictures.svg'
},
{
documentName: 'Documents 7',
dataModifica: '06 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/word.svg'
},
{
documentName: 'Documents 8',
dataModifica: '06 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/excel.svg'
},
{
documentName: 'Documents 9',
dataModifica: '06 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/pdf.svg'
},
{
documentName: 'Documents 10',
dataModifica: '06 / 02 / 2023',
dataSize: '0.98 KB',
iconUrl: '/assets/icons/excel.svg'
}
];
currentPage = 1;
itemsPerPage = 4;
constructor() { }
ngOnInit(): void {
}
getTotalPages(): number {
return Math.ceil(this.orders.length / this.itemsPerPage);
}
onNextPage(): void {
const totalPages = this.getTotalPages();
if (this.currentPage < totalPages) {
this.currentPage++;
}
}
onPrevPage(): void {
if (this.currentPage > 1) {
this.currentPage--;
}
}
}
|
import AppBar from 'components/AppBar/AppBar'
import React, { Suspense } from 'react'
import { Box, Container, Flex, Spinner } from '@chakra-ui/react'
import { useSelector } from 'react-redux'
import { Outlet } from 'react-router-dom'
import { getLoadingUserStatus } from 'redux/auth/auth-selectors'
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
export default function Layout() {
const isUserLoading = useSelector(getLoadingUserStatus)
return (
<Box bg='gray.100' minH='100vh'>
{
isUserLoading ? <Flex justify='center' align='center' h='100vh'><Spinner w='100px' h='100px' /></Flex> : (
<>
<AppBar />
<ToastContainer />
<Container maxW='container.xl'>
<Suspense>
<Outlet />
</Suspense>
</Container>
</>
)
}
</Box>
)
}
|
import React from "react";
import "./Sidebar.css";
// Material-UI
import DonutLargeIcon from "@material-ui/icons/DonutLarge";
import SearchOutlinedIcon from "@material-ui/icons/SearchOutlined";
import ChatIcon from "@material-ui/icons/Chat";
import MoreVertIcon from "@material-ui/icons/MoreVert";
import { Avatar, IconButton } from "@material-ui/core";
import SidebarChat from "./SidebarChat";
function Sidebar() {
return (
<div className="sidebar">
<div className="sidebar_header">
<Avatar src="https://cdn.pixabay.com/photo/2016/11/18/19/07/happy-1836445__480.jpg" />
<div className="sidebar_headerRight">
<IconButton>
<DonutLargeIcon />
</IconButton>
<IconButton>
<ChatIcon />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</div>
</div>
<div className="sidebar_search">
<div className="search_container">
<SearchOutlinedIcon />
<input type="text" placeholder="Search or start new chat" />
</div>
</div>
<div className="chats">
<SidebarChat />
<SidebarChat />
<SidebarChat />
</div>
</div>
);
}
export default Sidebar;
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:mg="http://at.irian/mygourmet"
xmlns:mc="http://java.sun.com/jsf/composite/mygourmet">
<head>
<title>Provider Details</title>
</head>
<body>
<ui:composition template="/META-INF/templates/customerTemplate.xhtml">
<ui:param name="title" value="#{msgs.title_main} - #{msgs.title_provider_details}"/>
<ui:define name="content">
<h:messages/>
<h2><h:outputText value="#{msgs.title_provider_details}"/></h2>
<h:form id="form">
<h:panelGrid columns="2">
<h:outputText value="#{msgs.provider_name}:"/>
<h:outputText value="#{providerBean.provider.name}"/>
<h:outputText value="#{msgs.stars}:"/>
<h:outputText value="#{providerBean.provider.stars}"/>
<h:outputText value="#{msgs.city}:"/>
<h:outputText value="#{providerBean.provider.address.zipCode} #{providerBean.provider.address.city}"/>
<h:outputText value="#{msgs.street}:"/>
<h:outputText value="#{providerBean.provider.address.street}"/>
<h:outputText value="#{msgs.categories}:"/>
<h:outputText value="#{providerBean.provider.categories}">
<mg:convertList separator=", "/>
</h:outputText>
</h:panelGrid>
<h:commandLink value="#{msgs.edit}" action="/editProvider.xhtml"/>
<h3><h:outputText value="#{msgs.title_dishes}"/></h3>
<h:commandLink action="#{providerBean.createDish}" value="#{msgs.add_dish}"/>
<mc:dataTable id="dishes" var="dish" value="#{providerBean.provider.dishes}">
<h:column>
<f:facet name="header">
<h:outputText value="#{msgs.name}"/>
</f:facet>
<h:outputText value="#{dish.name}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{msgs.price}"/>
</f:facet>
<h:outputText value="#{dish.price}">
<f:convertNumber pattern="#0.00" />
</h:outputText>
</h:column>
<h:column>
<h:commandLink action="#{providerBean.editDish(dish)}" value="#{msgs.edit}"/>
 
<h:commandLink value="#{msgs.delete}"
action="#{providerBean.deleteDish(dish)}">
<f:ajax render=":form:dishes"/>
</h:commandLink>
</h:column>
</mc:dataTable>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
|
use std::fs::File;
use std::io::{self, BufRead};
pub(crate) struct FiniteAutomata {
states: Vec<String>,
alphabet: Vec<char>,
transitions: Vec<((String, char), String)>,
initial_state: String,
final_states: Vec<String>,
}
impl FiniteAutomata {
pub fn new() -> Self {
FiniteAutomata {
states: vec![],
alphabet: vec![],
transitions: Vec::new(),
initial_state: String::new(),
final_states: vec![],
}
}
pub fn read_from_file(&mut self, filename: &str) -> io::Result<()> {
let file = File::open(filename)?;
let lines = io::BufReader::new(file).lines();
for line in lines {
let line = line?;
let parts: Vec<&str> = line.split(':').collect();
if parts.len() != 2 {
continue;
}
match parts[0].trim() {
"states" => {
self.states = parts[1].split(',').map(|s| s.trim().to_string()).collect()
}
"alphabet" => {
self.alphabet = parts[1]
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.collect::<String>()
.chars()
.collect()
}
"initial state" => self.initial_state = parts[1].trim().to_string(),
"final state" => {
self.final_states = parts[1].split(',').map(|s| s.trim().to_string()).collect()
}
"transitions" => {
self.transitions = parts[1]
.split(';')
.filter(|&t| !t.trim().is_empty()) // Filter out empty transitions
.map(|transition| {
let elements: Vec<&str> = transition.trim().split(',').collect();
if elements.len() == 3 {
let from_state = elements[0]
.trim_matches(|p| p == '(' || p == ')')
.to_string();
let to_state = elements[1].trim().to_string();
let symbol = elements[2].trim().chars().next().unwrap();
((from_state, symbol), to_state)
} else {
(("".to_string(), ' '), "".to_string()) // Placeholder for invalid transition
}
})
.filter(|t| !t.0 .0.is_empty()) // Further filter out any invalid transitions
.collect();
}
_ => (),
}
}
Ok(())
}
pub fn is_sequence_accepted(&self, sequence: &str) -> bool {
let mut current_state = self.initial_state.clone();
for c in sequence.chars() {
if !self.alphabet.contains(&c) {
return false; // Invalid character in sequence
}
let mut transition_found = false;
for transition in &self.transitions {
if transition.0 == (current_state.clone(), c) {
current_state = transition.1.clone();
transition_found = true;
break;
}
}
if !transition_found {
return false; // No transition found for this character
}
}
self.final_states.contains(¤t_state)
}
}
|
# [Clearing out Orphaned Shadow Copies](https://christitus.com/orphaned-shadow-copies/ "See on original website")
[Windows Server on Chris Titus Tech | Tech Content Creator](http://192.168.255.25:10010/i/?get=f_11 "Filter")
October 25th 2018 at 11:34 am
In this article, I go over how to get rid of Orphaned Shadow Copies that do not get cleared out by issuing: `vssadmin shadows delete /all`
## Steps to clear out all orphaned shadow copies
- `vssadmin shadows delete /all`
- `vssadmin shadows list`
- _verify orphaned shadow copies still exist_
- Use the following command to resize shadow storage, consequently, clears out any shadow copies on that drive
- `vssadmin Resize ShadowStorage /For=C: /On=C: /MaxSize=300MB`
- _Note: Repeat this for each drive with orphaned shadow copies_
- Afterward, do a shadows list to verify the shadow copies have been cleared out
- _This process can take a very long time for large drives with a lot of shadow copies._
- With all that finished, reset your shadow copies to either unbounded or 50-100 GB if you have space.

In conclusion, this issue has become less of an issue with the newer versions of Windows Server, but can still rear its ugly head from time to time. It’s important that you keep these pruned and functional, due to the fact a large number of shadow copies will bloat your server. This also can cause massive performance issues that will lock up a server. It is very important that you keep these manageable and functional for each server instance. In the day and age where virtualization has become so prevalent, you shouldn’t need many shadow copies.
|
import 'package:flutter/material.dart';
import 'package:flutter_product_db_local/bloc/product_bloc.dart';
import 'package:flutter_product_db_local/models/product.dart';
import 'package:flutter_product_db_local/providers/db_product_provider.dart';
import 'package:flutter_product_db_local/screens/add_product_screen.dart';
import 'package:flutter_product_db_local/screens/peroduct_details_screen.dart';
class ProductListScreen extends StatelessWidget {
const ProductListScreen({super.key});
@override
Widget build(BuildContext context) {
final productBloc = ProductBloc();
return Scaffold(
appBar: AppBar(
title: const Text('Lista de productos'),
actions: [
IconButton(
onPressed: () {
// DBProductProvider.db.deleteAll();
productBloc.deleteAllProduct();
},
icon: const Icon(Icons.delete),
),
],
),
// body: FutureBuilder(
// future: DBProductProvider.db.getAll(),
body: StreamBuilder<List<Product>>(
stream: productBloc.productStream,
builder: (BuildContext context, AsyncSnapshot<List<Product>> snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
final products = snapshot.data;
if (products == null || products.isEmpty) {
return const Center(
child: Text('No tienes productos'),
);
}
return ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
final product = products[index];
return ListTile(
title: Text(product.name),
subtitle: Text('${product.price}'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ProductDetailsScreen(id: product.id!),
),
);
},
);
},
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddProductScreen(),
),
);
},
child: const Icon(Icons.add),
),
);
}
}
|
"""
Vector2 Class
"""
from typing import TYPE_CHECKING, Generic, TypeVar
from typing_extensions import Self
if TYPE_CHECKING:
from .interval import Interval
T1 = TypeVar("T1", int, float, "Interval[int]", "Interval[float]", "Vector2")
T2 = TypeVar("T2", int, float, "Interval[int]", "Interval[float]", "Vector2")
class Vector2(Generic[T1, T2]):
x_: T1 # Can be int, Interval, and Vector2
y_: T2 # Can be int and Interval
__slots__ = ("x_", "y_")
def __init__(self, x, y) -> None:
"""
The `__init__` function initializes a Vector2 object with x and y coordinates.
:param x: The x-coordinate of the vector. It represents the horizontal component of the vector in a
2D space
:param y: The parameter `y` represents the y-coordinate of the vector. It is used to specify the
vertical component of the vector
Examples:
>>> v = Vector2(3, 4)
>>> print(v)
<3, 4>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> print(v3d)
<<3, 4>, 5>
"""
self.x_ = x
self.y_ = y
def __str__(self) -> str:
"""
The `__str__` function returns a string representation of a Vector2 object in the format "<x, y>".
:return: The `__str__` method is returning a string representation of the vector object.
Examples:
>>> v = Vector2(3, 4)
>>> print(v)
<3, 4>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> print(v3d)
<<3, 4>, 5>
"""
return f"<{self.x}, {self.y}>"
@property
def x(self) -> T1:
"""
The function returns the x-coordinate of a vector.
:return: The method `x` is returning the value of the attribute `x_`.
Examples:
>>> v = Vector2(3, 4)
>>> v.x
3
>>> v3d = Vector2(v, 5) # vector in 3d
>>> print(v3d.x)
<3, 4>
"""
return self.x_
@property
def y(self) -> T2:
"""
The function returns the y-coordinate of a vector.
:return: The method `y` is returning the value of the `y_` attribute.
Examples:
>>> v = Vector2(3, 4)
>>> v.y
4
>>> v3d = Vector2(v, 5) # vector in 3d
>>> print(v3d.y)
5
"""
return self.y_
# def copy(self) -> Self:
# """
# The `copy` function returns a new instance of the same class with the same values as the original
# instance.
# :return: The `copy` method is returning a new instance of the same class (`Self`) with the same `x_`
# and `y_` attributes.
#
# Examples:
# >>> v = Vector2(3, 4)
# >>> w = v.copy()
# >>> print(w)
# <3, 4>
# >>> v3d = Vector2(v, 5) # vector in 3d
# >>> w3d = v3d.copy()
# >>> print(w3d)
# <<3, 4>, 5>
# """
# T = type(self)
# return T(self.x_, self.y_)
def cross(self, rhs):
"""
The `cross` function calculates the cross product of two vectors.
:param rhs: The parameter `rhs` stands for "right-hand side" and represents another vector that we
want to perform the cross product with
:return: The cross product of the two vectors.
Examples:
>>> v = Vector2(3, 4)
>>> w = Vector2(5, 6)
>>> v.cross(w)
-2
"""
return self.x_ * rhs.y_ - rhs.x_ * self.y_
def __eq__(self, rhs) -> bool:
"""
The `__eq__` function checks if two instances of the `Vector2` class are equal by comparing their
`x_` and `y_` attributes.
:param rhs: The parameter `rhs` stands for "right-hand side" and represents the object that is being
compared to the current object (`self`) in the `__eq__` method
:return: The `__eq__` method returns a boolean value indicating whether the current object is equal
to the `rhs` object.
Examples:
>>> v = Vector2(3, 4)
>>> w = Vector2(3, 4)
>>> v == w
True
>>> v3d = Vector2(v, 5) # vector in 3d
>>> w3d = Vector2(w, 6) # vector in 3d
>>> v3d == w3d
False
"""
return (self.x_, self.y_) == (rhs.x_, rhs.y_)
def __neg__(self) -> Self:
"""
The `__neg__` function returns a new instance of the same type with the negated x and y values.
:return: The `__neg__` method returns a new instance of the same type as `self`, with the negated
values of `self.x` and `self.y`.
Examples:
>>> v = Vector2(3, 4)
>>> print(-v)
<-3, -4>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> print(-v3d)
<<-3, -4>, -5>
"""
T = type(self)
return T(-self.x, -self.y)
def __iadd__(self, rhs) -> Self:
"""
The `__iadd__` method is used to implement the in-place addition operator for a Vector2 class.
:param rhs: The parameter `rhs` stands for "right-hand side" and represents the object that is being
added to the current object. In this case, it is a `Vector2` object
:return: The `__iadd__` method returns `self`, which is an instance of the class.
Examples:
>>> v = Vector2(3, 4)
>>> v += Vector2(5, 6)
>>> print(v)
<8, 10>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> v3d += Vector2(v, 1)
>>> print(v3d)
<<16, 20>, 6>
"""
self.x_ += rhs.x
self.y_ += rhs.y
return self
def __add__(self, rhs) -> Self:
"""
The `__add__` method overloads the `+` operator for the `Vector2` class, allowing two vectors to be
added together.
:param rhs: The parameter `rhs` stands for "right-hand side" and represents the object that is being
added to the current object. In this case, it is assumed that both `self` and `rhs` are instances of
the `Vector2` class
:return: The `__add__` method is returning a new instance of the same type as `self` with the x and
y components added together.
Examples:
>>> v = Vector2(3, 4)
>>> w = Vector2(5, 6)
>>> print(v + w)
<8, 10>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> w3d = Vector2(w, 1)
>>> print(v3d + w3d)
<<8, 10>, 6>
"""
T = type(self)
return T(self.x + rhs.x, self.y + rhs.y)
def __isub__(self, rhs) -> Self:
"""
The `__isub__` method subtracts the x and y components of the right-hand side vector from the x and
y components of the left-hand side vector and returns the modified left-hand side vector.
:param rhs: The parameter `rhs` stands for "right-hand side" and represents the vector that is being
subtracted from the current vector
:return: The method `__isub__` returns an instance of the class `Self`.
Examples:
>>> v = Vector2(3, 4)
>>> v -= Vector2(5, 6)
>>> print(v)
<-2, -2>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> v3d -= Vector2(v, 1)
>>> print(v3d)
<<0, 0>, 4>
"""
self.x_ -= rhs.x
self.y_ -= rhs.y
return self
def __sub__(self, rhs) -> Self:
"""
The `__sub__` method subtracts the coordinates of two vectors and returns a new vector with the
result.
:param rhs: The parameter `rhs` stands for "right-hand side" and represents the vector that is being
subtracted from the current vector
:return: The `__sub__` method is returning a new instance of the same type (`T`) with the x and y
components subtracted from the corresponding components of the `rhs` object.
Examples:
>>> v = Vector2(3, 4)
>>> w = Vector2(5, 6)
>>> print(v - w)
<-2, -2>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> w3d = Vector2(w, 1)
>>> print(v3d - w3d)
<<-2, -2>, 4>
"""
T = type(self)
return T(self.x - rhs.x, self.y - rhs.y)
def __imul__(self, alpha) -> Self:
"""
The `__imul__` method multiplies the x and y components of a Vector2 object by a scalar value and
returns the modified object.
:param alpha: The parameter `alpha` represents the scalar value by which the vector's components
(`x_` and `y_`) will be multiplied
:return: The method `__imul__` returns `self`, which is an instance of the class that the method
belongs to.
Examples:
>>> v = Vector2(3, 4)
>>> v *= 2
>>> print(v)
<6, 8>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> v3d *= 2
>>> print(v3d)
<<12, 16>, 10>
"""
self.x_ *= alpha
self.y_ *= alpha
return self
def __mul__(self, alpha) -> Self:
"""
The `__mul__` method multiplies a vector by a scalar and returns a new vector.
:param alpha: The parameter `alpha` represents a scalar value that will be multiplied with the `x`
and `y` components of the vector
:return: The method `__mul__` returns a new instance of the same type as `self` with the `x` and `y`
attributes multiplied by `alpha`.
Examples:
>>> v = Vector2(3, 4)
>>> print(v * 2)
<6, 8>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> print(v3d * 2)
<<6, 8>, 10>
"""
T = type(self)
return T(self.x * alpha, self.y * alpha)
def __itruediv__(self, alpha) -> Self:
"""
The `__itruediv__` method divides the x and y components of a Vector2 object by a given value and
returns the modified object.
:param alpha: The parameter `alpha` represents the value by which the `x_` and `y_` attributes of
the object are divided
:return: The method is returning the updated instance of the class `self` after performing the
division operation.
Examples:
>>> v = Vector2(6.0, 9.0)
>>> v /= 2.0
>>> print(v)
<3.0, 4.5>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> v3d /= 0.5
>>> print(v3d)
<<6.0, 9.0>, 10.0>
"""
self.x_ /= alpha
self.y_ /= alpha
return self
def __truediv__(self, alpha) -> Self:
"""
The `__truediv__` method divides a vector by a scalar and returns a new vector with the resulting values.
:param alpha: The parameter `alpha` represents the value by which the vector is divided
:return: The `__truediv__` method returns a new instance of the same type (`T`) with the `x` and `y`
attributes divided by `alpha`.
Examples:
>>> v = Vector2(6.0, 9.0)
>>> print(v / 2.0)
<3.0, 4.5>
>>> v3d = Vector2(v, 5) # vector in 3d
>>> print(v3d / 2.0)
<<3.0, 4.5>, 2.5>
"""
T = type(self)
return T(self.x / alpha, self.y / alpha)
if __name__ == "__main__":
# import doctest
# doctest.testmod()
v = Vector2(6.0, 9.0)
v /= 2.0
print(v)
v3d = Vector2(v, 5) # vector in 3d
v3d /= 0.5
print(v3d)
|
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
// Classe para controlar as operações relacionadas às tarefas em SharedPreferences
class ListaTarefaController {
final String
email; // E-mail do usuário para diferenciar as chaves SharedPreferences
late SharedPreferences
_prefs; // Objeto SharedPreferences para acessar os dados
// Construtor da classe
ListaTarefaController({required this.email});
// Método para carregar as tarefas do SharedPreferences
Future<List<Map<String, dynamic>>> loadTasks() async {
// Obter uma instância do SharedPreferences
_prefs = await SharedPreferences.getInstance();
// Obter a lista de tarefas e a lista de tarefas concluídas do SharedPreferences
List<String>? taskList = _prefs.getStringList('${email}tasks');
List<String>? taskCompletedList =
_prefs.getStringList('${email}tasks_completed');
// Verificar se as listas não são nulas e têm o mesmo tamanho
if (taskList != null &&
taskCompletedList != null &&
taskList.length == taskCompletedList.length) {
// Se forem válidas, criar uma lista de mapas contendo as tarefas e seus estados de conclusão
List<Map<String, dynamic>> tasks = [];
for (int i = 0; i < taskList.length; i++) {
tasks.add({
'titulo': taskList[i],
'concluida': taskCompletedList[i] == 'true'
});
}
return tasks; // Retornar a lista de tarefas
} else {
return []; // Caso contrário, retornar uma lista vazia
}
}
// Método para salvar as tarefas no SharedPreferences
Future<void> saveTasks(List<Map<String, dynamic>> tasks) async {
// Obter uma instância do SharedPreferences
_prefs = await SharedPreferences.getInstance();
// Criar listas separadas para os títulos das tarefas e seus estados de conclusão
List<String> taskList = [];
List<String> taskCompletedList = [];
// Preencher as listas com os dados das tarefas fornecidas
for (int i = 0; i < tasks.length; i++) {
taskList.add(tasks[i]['titulo']); // Adicionar o título da tarefa à lista
taskCompletedList.add(tasks[i]['concluida']
? 'true'
: 'false'); // Adicionar o estado de conclusão à lista
}
// Salvar as listas no SharedPreferences usando chaves específicas para o usuário
await _prefs.setStringList('${email}tasks', taskList);
await _prefs.setStringList('${email}tasks_completed', taskCompletedList);
}
// Método para adicionar uma nova tarefa
Future<void> addTask(String task) async {
// Carregar as tarefas existentes do SharedPreferences
List<Map<String, dynamic>> currentTasks = await loadTasks();
// Adicionar a nova tarefa à lista de tarefas existentes
currentTasks.add({'titulo': task, 'concluida': false});
// Salvar as tarefas atualizadas no SharedPreferences
await saveTasks(currentTasks);
}
// Método para atualizar uma tarefa existente
Future<void> updateTask(int index, String newTask) async {
// Carregar as tarefas existentes do SharedPreferences
List<Map<String, dynamic>> currentTasks = await loadTasks();
// Atualizar o título da tarefa no índice fornecido
currentTasks[index]['titulo'] = newTask;
// Salvar as tarefas atualizadas no SharedPreferences
await saveTasks(currentTasks);
}
// Método para excluir uma tarefa
Future<void> deleteTask(int index) async {
// Carregar as tarefas existentes do SharedPreferences
List<Map<String, dynamic>> currentTasks = await loadTasks();
// Remover a tarefa no índice fornecido
currentTasks.removeAt(index);
// Salvar as tarefas atualizadas no SharedPreferences
await saveTasks(currentTasks);
}
// Método para marcar uma tarefa como concluída
Future<void> markTaskCompleted(int index) async {
// Carregar as tarefas existentes do SharedPreferences
List<Map<String, dynamic>> currentTasks = await loadTasks();
// Marcar a tarefa no índice fornecido como concluída
currentTasks[index]['concluida'] = true;
// Salvar as tarefas atualizadas no SharedPreferences
await saveTasks(currentTasks);
}
}
|
package kapitel5_OOP1;
/* Static variables (Statische Variablen)
- Eine statische Variable, die mit dem Schlüsselwort 'static' deklariert wird,
gehört zur Klasse und nicht zu einer bestimmten Instanz der Klasse.
- Wenn wir Instanz sagen, dann meinen wir ein Objekt. Man kann also aus einer Klasse (Klasse ist ja wie ein template) Instanzen (also Ojekte) erstellen.
- Das bedeutet, dass alle Instanzen der Klasse dieselbe Kopie der statischen Variable teilen.
Wie man mit `static variables` umgeht und sie verwendet:
- Statische Variablen werden auf Klassenebene deklariert, indem das Schlüsselwort 'static' verwendet wird.
- Sie können von jeder Instanz der Klasse oder direkt von der Klasse selbst aufgerufen werden.
- Der Zugriff auf eine statische Variable erfolgt über den Klassennamen gefolgt von einem Punkt und dem Variablennamen
(z.B., MeineKlasse.meineVariable).
- Wenn der Wert einer statischen Variable in einer Instanz geändert wird, wird dieser Wert für alle Instanzen der Klasse geändert.
In diesem Skript wird eine Klasse "Besitzer" erstellt, die eine Instanzvariable "name" und eine statische Variable "planet" enthält.
Es werden drei Objekte der Klasse erstellt und jeweils mit Werten initialisiert.
Beachtet, dass, wenn der Wert der statischen Variable "planet" für eine Instanz geändert wird,
der Wert für alle Instanzen gleichzeitig geändert wird.
*/
class Besitzer {
String name; // Instanzvariable
int age; // Instanzvariable
char gender; // Instanzvariable
static String planet; // Statische Variable
}
public class KlassenStaticVariable_6 {
public static void main(String[] args) {
// Statische Variable 'planet' wird auf "erde" gesetzt, und es gilt für alle Instanzen der Klasse.
Besitzer.planet = "erde";
// Objekt besitzer1 wird erstellt und initialisiert
Besitzer besitzer1 = new Besitzer();
besitzer1.name = "Jasem";
besitzer1.age = 88;
besitzer1.gender = 'M';
// Ausgabe der Werte für besitzer1 und der statischen Variable 'planet'
System.out.println(besitzer1.name);
System.out.println(besitzer1.age);
System.out.println(besitzer1.gender);
System.out.println(besitzer1.planet);
System.out.println("---------------------\n");
// Objekt besitzer2 wird erstellt und initialisiert
Besitzer besitzer2 = new Besitzer();
besitzer2.name = "esraa";
besitzer2.age = 8;
besitzer2.gender = 'F';
// Änderung der statischen Variable 'planet' für besitzer2
besitzer2.planet = "erde";
// Ausgabe der Werte für besitzer2 und der statischen Variable 'planet'
System.out.println(besitzer2.name);
System.out.println(besitzer2.age);
System.out.println(besitzer2.gender);
System.out.println("---------------------\n");
// Objekt besitzer3 wird erstellt und initialisiert
Besitzer besitzer3 = new Besitzer();
besitzer3.name = "rita";
besitzer3.age = 20;
besitzer3.gender = 'F';
// Ausgabe der Werte für besitzer3 und der statischen Variable 'planet'
System.out.println(besitzer3.name);
System.out.println(besitzer3.age);
System.out.println(besitzer3.gender);
System.out.println(besitzer3.planet);
// Änderung der statischen Variable 'planet' für besitzer3
besitzer3.planet = "mars";
// Ausgabe der geänderten Werte für besitzer1, besitzer2, besitzer3
System.out.println("Ab jetzt Planeten von Jasem, Esraa und Rita:");
System.out.println(besitzer1.planet);
System.out.println(besitzer2.planet);
System.out.println(besitzer3.planet);
}
}
|
using BillMate.Data;
using BillMate.Helpers;
using BillMate.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BillMate.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ClientsController : ControllerBase
{
private readonly BillMateDBContext _context;
public ClientsController(BillMateDBContext context)
{
_context = context;
}
// GET: api/Clients
[HttpGet]
public async Task<ActionResult<IEnumerable<Client>>> GetClient([FromQuery(Name = "role")] string role, [FromQuery(Name = "firstName")] string firstName, [FromQuery(Name = "username")] string username)
{
try
{
var user = HttpContext.User;
string companyIdString = null;
int? companyId = null;
if(user != null)
{
if(user.HasClaim(x => x.Type == "CompanyId"))
{
companyIdString = user.Claims.FirstOrDefault(x => x.Type == "CompanyId")?.Value;
companyId = Convert.ToInt32(companyIdString);
}
} else
{
throw new Exception("User is not linked to a company");
}
if (role == "Manager")
{
Console.WriteLine("--------------Came in Client Manager-----------");
List<string> clients = await _context.Employee.Where(emp => emp.AssignedManager == firstName).Select(e => new string((!string.IsNullOrEmpty(e.AssignOffices) ? e.AssignOffices : ""))).ToListAsync();
Console.WriteLine("--------------clients list-----------" + string.Join(",", clients));
HashSet<int> set = new HashSet<int>();
foreach (string cli in clients)
{
string[] strings = cli.Split(",");
foreach (string s in strings)
{
if (!string.IsNullOrEmpty(s))
{
set.Add(Convert.ToInt32(s));
}
}
}
Console.WriteLine("--------------clients set-----------" + string.Join(",", set));
return await _context.Client.Where(x => set.Contains(x.Id) && x.CompanyId == companyId).Include(a => a.User).Include(a => a.AddressDetails).Include(b => b.BillingPreferences).Include(n => n.NotificationsPreferences).ToListAsync();
}
else if (role == "Employee")
{
Console.WriteLine("--------------Came in Client Employee-----------");
List<string> clients = await _context.Employee.Where(emp => emp.WorkEmailAddress == username).Select(e => new string((!string.IsNullOrEmpty(e.AssignOffices) ? e.AssignOffices : ""))).ToListAsync();
Console.WriteLine("--------------clients list-----------" + string.Join(",", clients));
HashSet<int> set = new HashSet<int>();
foreach (string cli in clients)
{
string[] strings = cli.Split(",");
foreach (string s in strings)
{
if (!string.IsNullOrEmpty(s))
{
set.Add(Convert.ToInt32(s));
}
}
}
Console.WriteLine("--------------clients set-----------" + string.Join(",", set));
return await _context.Client.Where(x => set.Contains(x.Id) && x.CompanyId == companyId).Include(a => a.User).Include(a => a.AddressDetails).Include(b => b.BillingPreferences).Include(n => n.NotificationsPreferences).ToListAsync();
}
var clientsData = await _context.Client
.Where(x => x.CompanyId == companyId)
.Include(a => a.AddressDetails)
.Include(a => a.User)
.Include(b => b.BillingPreferences)
.Include(n => n.NotificationsPreferences)
.ToListAsync();
foreach (var item in clientsData)
{
var employeeOffice = _context.EmployeeOffices.FirstOrDefault(x => x.ClientId == item.Id);
if (employeeOffice == null)
continue;
var employee = _context.Employee.FirstOrDefault(x => x.Id == employeeOffice.EmployeeId);
item.Employee = employee;
}
return clientsData;
} catch(Exception exc)
{
throw exc;
}
}
// GET: api/Clients/5
[HttpGet("{id}")]
public async Task<ActionResult<Client>> GetClient(int id)
{
try
{
var user = HttpContext.User;
string companyIdString = null;
int? companyId = null;
if (user != null)
{
if (user.HasClaim(x => x.Type == "CompanyId"))
{
companyIdString = user.Claims.FirstOrDefault(x => x.Type == "CompanyId")?.Value;
companyId = Convert.ToInt32(companyIdString);
}
}
else
{
throw new Exception("User is not linked to a company");
}
var client = await _context.Client.Include(a => a.AddressDetails).Include(a => a.User).Include(b => b.BillingPreferences).Include(n => n.NotificationsPreferences).AsNoTracking().FirstAsync(c => c.Id == id && c.CompanyId == companyId);
if (client == null)
{
return NotFound();
}
return client;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
return BadRequest(new { message = ex.InnerException.Message });
}
}
// GET: api/Clients/5
[HttpGet("byUserId/{userId}")]
public async Task<ActionResult<Client>> GetClientDetailsByUserId(int userId)
{
try
{
var user = HttpContext.User;
string companyIdString = null;
int? companyId = null;
if (user != null)
{
if (user.HasClaim(x => x.Type == "CompanyId"))
{
companyIdString = user.Claims.FirstOrDefault(x => x.Type == "CompanyId")?.Value;
companyId = Convert.ToInt32(companyIdString);
}
}
else
{
throw new Exception("User is not linked to a company");
}
var client = await _context
.Client
.Include(a => a.AddressDetails)
.Include(a => a.User)
.Include(b => b.BillingPreferences)
.Include(n => n.NotificationsPreferences)
.AsNoTracking()
.FirstAsync(c => c.UserId == userId && c.CompanyId == companyId);
if (client == null)
{
return NotFound();
}
return client;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
return BadRequest(new { message = ex.InnerException.Message });
}
}
// PUT: api/Clients/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPut("{id}")]
public async Task<IActionResult> PutClient(int id, Client client)
{
if (id != client.Id)
{
return BadRequest();
}
var requestUser = HttpContext.User;
string companyIdString = null;
int? companyId = null;
if (requestUser != null)
{
if (requestUser.HasClaim(x => x.Type == "CompanyId"))
{
companyIdString = requestUser.Claims.FirstOrDefault(x => x.Type == "CompanyId")?.Value;
companyId = Convert.ToInt32(companyIdString);
}
}
else
{
throw new Exception("User is not linked to a company");
}
client.CompanyId = companyId;
client.AddressDetails.CompanyId = companyId;
client.BillingPreferences.CompanyId = companyId;
client.NotificationsPreferences.CompanyId = companyId;
_context.Entry(client).State = EntityState.Modified;
_context.Entry(client.AddressDetails).State = EntityState.Modified;
_context.Entry(client.BillingPreferences).State = EntityState.Modified;
_context.Entry(client.NotificationsPreferences).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return BadRequest(new { message = ex.Message });
}
return NoContent();
}
// POST: api/Clients
// To protect from oveposting attacks, please enable the specific properties to bind to, for
// more details if you want see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPost]
public async Task<ActionResult<Client>> PostClient(Client client)
{
try
{
var currentUser = HttpContext.User;
string companyIdString = null;
int? companyId = null;
if (currentUser != null)
{
if (currentUser.HasClaim(x => x.Type == "CompanyId"))
{
companyIdString = currentUser.Claims.FirstOrDefault(x => x.Type == "CompanyId")?.Value;
companyId = Convert.ToInt32(companyIdString);
}
}
else
{
throw new Exception("User is not linked to a company");
}
var isUserExist = _context.User.Where(x => x.Username == client.Email).FirstOrDefault();
if (isUserExist != null)
return BadRequest(new { message = "Client email address is already exist" });
//user adding
User user = new User();
user.FirstName = client.PracticeName;
user.Username = client.Email;
user.Password = Encryption.CalculateMD5Hash("pass");
user.Role = "Client";
user.CompanyId = companyId.Value;
_context.User.Add(user);
await _context.SaveChangesAsync();
client.UserId = user.Id;
client.CompanyId = companyId.Value;
_context.Client.Add(client);
await _context.SaveChangesAsync();
Console.WriteLine("Success");
return Ok();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return BadRequest(new { message = ex });
}
}
// DELETE: api/Clients/5
[HttpDelete("{id}")]
public async Task<ActionResult<Client>> DeleteClient(int id)
{
var client = await _context.Client.FindAsync(id);
if (client == null)
{
return NotFound();
}
var address = await _context.AddressDetails.FindAsync(client.AddressId);
if (address == null)
{
return NotFound();
}
var billing = await _context.BillingPreferences.FindAsync(client.BillingId);
if (billing == null)
{
return NotFound();
}
var notification = await _context.NotificationsPreferences.FindAsync(client.NotificationId);
if (notification == null)
{
return NotFound();
}
_context.Client.Remove(client);
_context.AddressDetails.Remove(address);
_context.BillingPreferences.Remove(billing);
_context.NotificationsPreferences.Remove(notification);
if (client.UserId.HasValue)
{
var user = await _context.User.FindAsync(client.UserId);
if (user != null)
{
_context.User.Remove(user);
}
}
await _context.SaveChangesAsync();
return client;
}
private bool ClientExists(int id)
{
return _context.Client.Any(e => e.Id == id);
}
}
}
|
<?php
declare(strict_types=1);
namespace Tests\Feature\Services\Osiris;
use App\Dto\Osiris\Repository\CaseExportResult;
use App\Events\Osiris\CaseExportFailed;
use App\Events\Osiris\CaseExportRejected;
use App\Events\Osiris\CaseExportSucceeded;
use App\Events\Osiris\CaseNotExportable;
use App\Exceptions\Osiris\CaseExport\CaseExportException;
use App\Exceptions\Osiris\CaseExport\CaseExportRejectedException;
use App\Exceptions\Osiris\Client\ErrorResponseException;
use App\Jobs\ExportCaseToOsiris;
use App\Models\CovidCase\Index;
use App\Models\Enums\Osiris\CaseExportType;
use App\Repositories\Osiris\CaseExportRepository;
use App\Services\Osiris\OsirisCaseExporter;
use App\Services\Osiris\SoapMessage\QuestionnaireVersion;
use App\ValueObjects\OsirisNumber;
use Exception;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Queue;
use MinVWS\DBCO\Enum\Models\Gender;
use Mockery;
use PHPUnit\Framework\Attributes\Group;
use Tests\Feature\FeatureTestCase;
use Tests\Helpers\ConfigHelper;
#[Group('osiris')]
final class OsirisCaseExporterTest extends FeatureTestCase
{
private CaseExportRepository $osirisRepository;
private OsirisCaseExporter $caseExporter;
public function setUp(): void
{
parent::setUp();
$this->osirisRepository = Mockery::mock(CaseExportRepository::class);
$this->caseExporter = new OsirisCaseExporter($this->osirisRepository);
}
/**
* @throws CaseExportException
* @throws CaseExportRejectedException
*/
public function testDispatchCaseExportSucceededEventOnSuccess(): void
{
Event::fake();
$case = $this->createCaseExportableToOsiris();
$this->osirisRepository->expects('exportCase')
->andReturns(
new CaseExportResult(
new OsirisNumber($this->faker->randomNumber(6)),
QuestionnaireVersion::V10->value,
$this->faker->word(),
$case->uuid,
),
);
$this->caseExporter->export($case, $this->faker->randomElement(CaseExportType::cases()));
Event::assertDispatched(CaseExportSucceeded::class);
}
/**
* @throws CaseExportException
* @throws CaseExportRejectedException
*/
public function testDispatchOsirisExportBlockedEventIfCaseHasHPZoneNumber(): void
{
Event::fake();
$case = $this->createCase(['hpzone_number' => $this->faker->randomNumber(6)]);
$this->osirisRepository->expects('exportCase')
->never();
$this->caseExporter->export($case, $this->faker->randomElement(CaseExportType::cases()));
Event::assertDispatched(CaseNotExportable::class);
}
/**
* @throws CaseExportException
*/
public function testDispatchCaseExportFailedEventWithRejectedFlag(): void
{
Event::fake();
$case = $this->createCaseExportableToOsiris();
$this->osirisRepository->expects('exportCase')
->andThrow(
CaseExportRejectedException::fromErrorResponse(
$case,
new ErrorResponseException('test', ['test']),
),
);
$this->expectException(CaseExportRejectedException::class);
$this->caseExporter->export($case, $this->faker->randomElement(CaseExportType::cases()));
Event::assertDispatched(static function (CaseExportRejected $event) {
return $event->errors === ['test'];
});
}
/**
* @throws CaseExportRejectedException
*/
public function testDispatchCaseExportFailedEventForCaseExportException(): void
{
Event::fake();
$case = $this->createCaseExportableToOsiris();
$this->osirisRepository->expects('exportCase')
->andThrow(
CaseExportException::fromThrowable(new Exception('test')),
);
$this->expectException(CaseExportException::class);
$this->caseExporter->export($case, $this->faker->randomElement(CaseExportType::cases()));
Event::assertDispatched(CaseExportFailed::class);
}
public function testPushingToOsirisQueue(): void
{
ConfigHelper::enableFeatureFlag('osiris_send_case_enabled');
Queue::fake();
$case = $this->createCase([
'index' => Index::newInstanceWithVersion(1, function (Index $index): void {
$index->dateOfBirth = $this->faker->dateTime();
$index->gender = $this->faker->randomElement(Gender::all());
}),
]);
ExportCaseToOsiris::dispatchIfEnabled($case->uuid, CaseExportType::DEFINITIVE_ANSWERS);
Queue::assertPushed(ExportCaseToOsiris::class);
}
public function testFeatureFlagValuePreventsPushingToQueue(): void
{
ConfigHelper::disableFeatureFlag('osiris_send_case_enabled');
Queue::fake();
$case = $this->createCaseExportableToOsiris();
ExportCaseToOsiris::dispatchIfEnabled($case->uuid, CaseExportType::DEFINITIVE_ANSWERS);
Queue::assertNotPushed(ExportCaseToOsiris::class);
}
}
|
// SPDX-License-Identifier: None
// Specifies the version of Solidity, using semantic versioning.
// Learn more: https://solidity.readthedocs.io/en/v0.5.10/layout-of-source-files.html#pragma
pragma solidity >=0.7.3;
// Defines a contract named `HelloWorld`.
// A contract is a collection of functions and data (its state). Once deployed, a contract resides at a specific address on the Ethereum blockchain. Learn more: https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html
contract Dindr {
struct User {
string name;
bool isReal;
string addr;
}
struct Chat {
address user1;
address user2;
string[] messages;
}
mapping(address => User) public users;
mapping(string => string[]) public matches;
Chat[] chats;
event NewUser(address user, string name);
event Matched(User matched, User matchee);
function register(string memory name) external {
require(users[msg.sender].isReal != true, "You already have an account!");
users[msg.sender] = User({
name: name,
isReal: true,
addr: abi.encodePacked(msg.sender)
});
emit NewUser(msg.sender, name);
}
function findUserInArray(string memory target) private returns(User memory user) {
for(uint256 i = 0; i < matches[target].length; i++) {
if((keccak256(abi.encodePacked(matches[target][i].addr)) == keccak256(abi.encodePacked(target)))) {
return matches[target][i];
}
}
}
function like(string memory target) external {
User memory found = findUserInArray(matches[target], target);
if (found.isReal) {
emit Matched(users[msg.sender], found);
} else {
matches[msg.sender] = [target];
}
}
function dislike(address target) external {}
function sendMessage(address target) external {}
function getMessages(address target) external {}
}
|
import { Component } from '@angular/core';
import { NavController, ToastController } from '@ionic/angular';
// import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { Router } from '@angular/router';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
// import { FcmService } from './services/fcm.service';
import { Capacitor, Plugins } from '@capacitor/core';
const { Storage } = Plugins;
const { SplashScreen } = Plugins;
const { StatusBar } = Plugins;
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
showSpinner: boolean = true;
constructor(
private toastCtrl: ToastController,
private router: Router,
private screenOrientation: ScreenOrientation,
// private fcmService: FcmService
private navCtrl: NavController,
) {
this.initializeApp();
}
initializeApp() {
this.checkUser();
if (Capacitor.isNative) {
// Tint statusbarÎ color
StatusBar.setBackgroundColor({
color: '#111619'
});
// set to portrait
this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
// Show the splash for two seconds and then auto hide:
SplashScreen.show({
showDuration: 3000,
autoHide: true
});
}
}
async checkUser() {
const value = await Storage.get({ key: 'user' });
const data = JSON.parse(value.value);
if (data !== null) {
switch (data.loggedIn) {
case true: {
if(data.uid === 'MQ9SRkXflwWBQJgXXltGU7AGTki2' || data.user.usertype === 'shop') {
this.navCtrl.navigateRoot('/users');
}else {
this.navCtrl.navigateRoot('/shop');
}
break;
} case false: {
this.router.navigate(['/login']);
break;
}
}
}else this.router.navigate(['/login']);
}
//listen to incoming messages
// getMessages() {
// this.authService.listenNotifactions()
// .pipe(map(msg => {
// this.showToast(msg);
// })).subscribe();
// }
//show toast method
async showToast(msg) {
let toast = await this.toastCtrl.create({
message: msg,
duration: 4000
});
await toast.present();
}
}
|
package org.example.array;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ZigZagConversionTest {
@Test
public void testConvertWithExample1() {
String s = "PAYPALISHIRING";
int numRows = 3;
String expected = "PAHNAPLSIIGYIR";
assertEquals(expected, convert(s, numRows));
}
@Test
public void testConvertWithExample2() {
String s = "PAYPALISHIRING";
int numRows = 4;
String expected = "PINALSIGYAHRPI";
assertEquals(expected, convert(s, numRows));
}
@Test
public void testConvertWithExample3() {
String s = "A";
int numRows = 1;
String expected = "A";
assertEquals(expected, convert(s, numRows));
}
private String convert(String s, int numRows) {
if (numRows == 1 || numRows >= s.length()) {
return s;
}
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
rows[i] = new StringBuilder();
}
int index = 0;
int step = 1;
for (char ch : s.toCharArray()) {
rows[index].append(ch);
if (index == 0) {
step = 1;
} else if (index == numRows - 1) {
step = -1;
}
index += step;
}
StringBuilder result = new StringBuilder();
for (StringBuilder row : rows) {
result.append(row);
}
return result.toString();
}
}
|
## no critic (RequireUseStrict, RequireUseWarnings, RequireTidyCode)
package Crispr::OffTargetInfo;
## use critic
# ABSTRACT: OffTargetInfo object - representing all possible off-target positions for a crispr guide RNA
use namespace::autoclean;
use Moose;
use Moose::Util::TypeConstraints;
use Carp qw( cluck confess );
use Crispr::OffTarget;
use Number::Format;
my $num = new Number::Format( DECIMAL_DIGITS => 3, );
=method new
Usage : my $off_target_info = Crispr::OffTarget->new(
crRNA_name => 'crRNA:5:101-123:1',
);
Purpose : Constructor for creating crRNA objects
Returns : Crispr::OffTarget object
Parameters : crRNA_name => Str
Throws : If parameters are not the correct type
Comments : None
=cut
=method crRNA_name
Usage : $off_target_info->crRNA_name;
Purpose : Getter for crRNA_name
Returns : Str (CHR:START-END:STRAND)
Parameters : None
Throws :
Comments :
=cut
has 'crRNA_name' => (
is => 'ro',
isa => 'Str',
);
=method _off_targets
Usage : $off_target_info->_off_targets;
Purpose : Attribute to hold the off-targets objects
Returns : HashRef
Parameters : None
Throws :
Comments :
=cut
has '_off_targets' => (
is => 'rw',
isa => 'HashRef',
lazy => 1,
builder => '_build_off_targets',
init_arg => undef,
);
=method add_off_target
Usage : $off_target_info->add_off_target( $off_target );
Purpose : adds a single Crispr::OffTarget object
Returns :
Parameters : None
Throws : If argument is not a Crispr::OffTarget object
Comments :
=cut
sub add_off_target {
my ( $self, $off_target, ) = @_;
if( !ref $off_target || !$off_target->isa('Crispr::OffTarget') ){
confess "Argument must be a Crispr::OffTarget object!\n";
}
push @{ $self->_off_targets->{ $off_target->annotation } }, $off_target;
}
=method all_off_targets
Usage : $off_target_info->all_off_targets;
Purpose : Returns a List of Crispr::OffTarget objects
Returns : Array( Crispr::OffTarget objects )
Parameters : None
Throws :
Comments :
=cut
sub all_off_targets {
my ( $self, ) = @_;
return ( @{ $self->_off_targets->{exon} }, @{ $self->_off_targets->{intron} }, @{ $self->_off_targets->{nongenic} }, );
}
=method _make_and_add_off_target
Usage : $off_target_info->_make_and_add_off_target;
Purpose : Creates a new Crispr::OffTarget object from the arguments and
adds it to the _off_targets attribute
Returns : Crispr::OffTarget
Parameters : None
Throws :
Comments :
=cut
sub _make_and_add_off_target {
my ( $self, $args, ) = @_;
my $off_target_obj = Crispr::OffTarget->new(
crRNA_name => $args->{crRNA_name},
chr => $args->{chr},
start => $args->{start},
end => $args->{end},
strand => $args->{strand},
mismatches => $args->{mismatches},
annotation => $args->{annotation},
);
$self->add_off_target( $off_target_obj );
}
=method score
Usage : $off_target_info->score;
Purpose : Calculates an off target score from the OffTarget objects
Returns : Float
Parameters : None
Throws : If score is larger than 1
Comments :
=cut
sub score {
my ( $self ) = @_;
my $score = 1;
if( $self->number_exon_hits ){
$score -= 0.1*$self->number_exon_hits;
}
if( $self->number_intron_hits ){
$score -= 0.05*$self->number_intron_hits;
}
if( $self->number_nongenic_hits ){
$score -= 0.02*$self->number_nongenic_hits;
}
if( $score < 0 ){
$score = 0;
}
elsif( $score > 1 ){
confess "score is larger than 1!\n";
}
else{
return $score;
}
}
=method info
Usage : $off_target_info->info;
Purpose : Returns information about the Off Targets
Returns : Array( Str )
Parameters : None
Throws :
Comments :
=cut
sub info {
my ( $self, ) = @_;
my @info;
# off-target score
push @info, $num->format_number($self->score);
# scores and detail
push @info, $self->off_target_counts;
my @hits = $self->off_target_hits_by_annotation;
push @info, join('|',
join('/', @{$hits[0]} ),
join('/', @{$hits[1]} ),
join('/', @{$hits[2]} ),
);
return @info;
}
=method off_target_counts
Usage : $off_target_info->off_target_counts;
Purpose : Returns the number of exon/intron/nongenic hits
Returns : Str (Exon/Intron/Nongenic)
Parameters : None
Throws :
Comments :
=cut
sub off_target_counts {
my ( $self, ) = @_;
my @exo_hit_numbers = (
$self->number_exon_hits,
$self->number_intron_hits,
$self->number_nongenic_hits,
);
return join('|', @exo_hit_numbers );
}
=method off_target_hits_by_annotation
Usage : $off_target_info->off_target_hits_by_annotation;
Purpose : Returns the OffTarget positions split by annotation type
Returns : Array( [Exon Hits], [Intron Hits], [Nongenic Hits] )
Parameters : None
Throws :
Comments :
=cut
sub off_target_hits_by_annotation {
my ( $self, ) = @_;
my @exon_hits = map { $_->position } @{ $self->_off_targets->{ exon } };
my @intron_hits = map { $_->position } @{ $self->_off_targets->{ intron } };
my @nongenic_hits = map { $_->position } @{ $self->_off_targets->{ nongenic } };
return ( \@exon_hits, \@intron_hits, \@nongenic_hits, );
}
=method all_off_target_hits
Usage : $off_target_info->all_off_target_hits;
Purpose : Returns a list of all the Off Target Hits (positions)
Returns : ArrayRef[ Str ]
Parameters : None
Throws :
Comments :
=cut
sub all_off_target_hits {
my ( $self, ) = @_;
my @exon_hits = map { $_->position } @{ $self->_off_targets->{ exon } };
my @intron_hits = map { $_->position } @{ $self->_off_targets->{ intron } };
my @nongenic_hits = map { $_->position } @{ $self->_off_targets->{ nongenic } };
return ( [ @exon_hits, @intron_hits, @nongenic_hits ] );
}
=method number_exon_hits
Usage : $off_target_info->number_exon_hits;
Purpose : Returns the number of exon hits
Returns : Int
Parameters : None
Throws :
Comments :
=cut
sub number_exon_hits {
my ( $self, ) = @_;
return scalar @{$self->_off_targets->{exon}};
}
=method number_intron_hits
Usage : $off_target_info->number_intron_hits;
Purpose : Returns the number of intron hits
Returns : Int
Parameters : None
Throws :
Comments :
=cut
sub number_intron_hits {
my ( $self, ) = @_;
return scalar @{$self->_off_targets->{intron}};
}
=method number_nongenic_hits
Usage : $off_target_info->number_nongenic_hits;
Purpose : Returns the number of nongenic hits
Returns : Int
Parameters : None
Throws :
Comments :
=cut
sub number_nongenic_hits {
my ( $self, ) = @_;
return scalar @{$self->_off_targets->{nongenic}};
}
=method number_hits
Usage : $off_target_info->number_hits;
Purpose : Returns the total number of off-target hits
Returns : Int
Parameters : None
Throws :
Comments :
=cut
sub number_hits {
my ( $self, ) = @_;
return $self->number_exon_hits + $self->number_intron_hits + $self->number_nongenic_hits;
}
=method _build_off_targets
Usage : $off_target_info->_build_off_targets;
Purpose : Internal method to build the _off_targets attribute
Returns : HashRef[ exon => ArrayRef, intron => ArrayRef, Nongenic => ArrayRef ]
Parameters : None
Throws :
Comments :
=cut
sub _build_off_targets {
my ( $self, ) = @_;
my $off_targets = {
exon => [ ],
intron => [ ],
nongenic => [ ],
};
return $off_targets;
}
__PACKAGE__->meta->make_immutable;
1;
|
'''
This program is designed to scrape real estate data from a website
(in this case, from 'https://appbrewery.github.io/Zillow-Clone/')
and then automatically fill out a Google Form with that data using Selenium.
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import requests
from time import sleep
google_form = 'https://docs.google.com/forms/d/e/1FAIpQLSf5GGHxw4uFOaXXbaesJqjc17r_9qn4p_4BpA5GXxWW0csCEQ/viewform?usp=sf_link'
def fetch_all_data():
header = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36",
"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8"
}
result = requests.get('https://appbrewery.github.io/Zillow-Clone/', headers=header)
soup = BeautifulSoup(result.content, 'html.parser')
list_of_links = [
link.get('href')
for link in
soup.select(selector='ul[class="List-c11n-8-84-3-photo-cards"] li .StyledPropertyCardDataArea-anchor')
]
list_of_prices = [
price.text[:6]
for price in (soup.select(selector='span[data-test="property-card-price"]'))
]
# print(len(list_of_links))
# print(len(list_of_prices))
lst = [
address.text
for address in soup.find_all(name='address')
]
# Filtering process of all address string
list_of_addresses = []
c = 0
for i in lst:
address = [j.strip() for j in i.strip().replace('|', '').split(',')]
if len(address) >= 4:
list_of_addresses.append(', '.join(address[1:]))
else:
list_of_addresses.append(', '.join(address))
# print(list_of_addresses[c])
# c += 1
# print(len(list_of_addresses))
return list_of_addresses, list_of_prices, list_of_links
# Selenium part
options = webdriver.ChromeOptions()
options.add_experimental_option('detach', True)
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.get(google_form)
sleep(3)
datas = fetch_all_data()
for i in range(len(datas[0])):
input_fields = driver.find_elements(By.CSS_SELECTOR, 'input[type="text"]')
input_fields[0].send_keys(datas[0][i])
input_fields[1].send_keys(datas[1][i])
input_fields[2].send_keys(datas[2][i])
send = driver.find_element(By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[3]/div[1]/div[1]/div/span')
send.click()
sleep(1)
driver.find_element(By.LINK_TEXT, 'Отправить ещё один ответ').click()
sleep(1)
driver.quit()
|
import sys
import re
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets
import mysql.connector
sys.path.insert(2,'windows/Account')
import user_account
sys.path.insert(1,'windows/Registration')
import registration
class Login(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlag(Qt.FramelessWindowHint)
self.setWindowTitle("Login")
self.setWindowIcon(QIcon("Images/bintech logo.png"))
self.setStyleSheet("background-color : #FFFAF3")
layout = QHBoxLayout()
greeting= QLabel(self)
greeting.setText("Hello There!")
greeting.move(300,150)
greeting.resize(900,100)
greeting.setStyleSheet("QLabel { font-size: 90px; font-family: Roboto;font-weight: 900; font-style: normal; color: #699913; }" "QPushButton:pressed { background-color: #0ef5a0 ; }" )
layout.addWidget(greeting)
self.email = QLineEdit(self)
self.email.setPlaceholderText("Email")
self.email.move(300,300)
self.email.resize(600,100)
self.email.setStyleSheet("QLineEdit { line-height: 42px; background-color: #FFFFFF; font-weight: 400; font-size: 20px; font-family: Roboto; font-style: normal; color: #979797; border-radius: 20px; padding-left: 24px; }" )
self.password= QtWidgets.QLineEdit(self)
self.password.setEchoMode(QLineEdit.Password)
self.password.setPlaceholderText("Password")
self.password.move(300,425)
self.password.resize(600,100)
self.password.setStyleSheet(" QLineEdit { line-height: 42px; background-color: #FFFFFF; font-weight: 400; font-size: 20px; font-family: Roboto; font-style: normal; color: #979797; border-radius: 20px; position: absolute; padding-left: 24px;}" )
log_btn = QPushButton("Login",self)
log_btn.setStyleSheet("QPushButton { font-size: 40px; background-color: #699913; font-family: Roboto;font-weight: 900; font-style: normal; color: white; border-radius: 20px; }" "QPushButton:pressed { background-color: #0E7470; color: #FFFFFF; }" )
log_btn.setGeometry(300, 600, 600, 100)
log_btn.clicked.connect(self.clicked_Login)
reg_btn = QPushButton("Register",self)
reg_btn.setStyleSheet("QPushButton { font-size: 40px; background-color: #699913; font-family: Roboto;font-weight: 900; font-style: normal; color: white; border-radius: 20px; }" "QPushButton:pressed { background-color: #0E7470; color: #FFFFFF; }" )
reg_btn.setGeometry(300, 720, 600, 100)
reg_btn.clicked.connect(self.clicked_Registration)
logo = QLabel(self)
logo.pixmap = QPixmap('Images/BINTECH LOGO.png')
logo.setPixmap(logo.pixmap)
logo.resize(logo.pixmap.width(),logo.pixmap.height())
logo.move(1100,320)
self.showFullScreen()
#def add_window(self):
# self.Window2.showMaximized()
# self.close()
def clicked_Registration(self):
self._registration = registration.Register()
self.hide()
self._registration.show()
def clicked_Login(self):
user_email = self.email.text()
user_password = self.password.text()
if not user_email or not user_password:
QMessageBox.warning(self, 'Error', 'Please fill out all fields!')
self.email.clear()
self.password.clear()
return
if not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
QMessageBox.warning(self, 'Error', 'Please enter a valid email address!')
self.email.clear()
self.password.clear()
return
try:
# Connect to MySQL database
conn = mysql.connector.connect(
host='127.0.0.1',
user='qwerty',
password='password123',
database='plark'
)
# Create cursor
cursor = conn.cursor()
# Execute query to verify user credentials
cursor.execute("SELECT * FROM users WHERE email = %s AND password = %s", (user_email, user_password))
user = cursor.fetchone()
# Close cursor and connection
cursor.close()
conn.close()
if user:
self._user_account = user_account.User_Account()
self.hide()
self._user_account.show()
else:
QMessageBox.warning(self, 'Error', 'Incorrect email or password!')
self.email.clear()
self.password.clear()
except mysql.connector.Error as e:
QMessageBox.critical(self, 'Error', f'Failed to connect to database. Error: {str(e)}')
if __name__ == "__main__":
app = QApplication(sys.argv)
#app.setStyleSheet(stylesheet)
ex = Login()
sys.exit(app.exec_())
|
package org.danielegiulianini.puzzled.backend.gamelogicservice;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.file.FileSystemOptions;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.ServerWebSocket;
import org.danielegiulianini.puzzled.commons.constants.ServicesInfo;
import org.danielegiulianini.puzzled.commons.Puzzle;
import org.danielegiulianini.puzzled.commons.domain.PuzzleRoom;
import org.danielegiulianini.puzzled.commons.RestFetcherService;
import org.danielegiulianini.puzzled.commons.JsonMessageEncoderDecoder;
import org.danielegiulianini.puzzled.commons.domain.events.*;
/*
* This is the service that:
* 1. groups service-consumers into rooms, each of which is assigned a puzzle
* 2. handles puzzles events from service-consumers and
* 3. keeps the state for the puzzle associated to every room.
* */
public class GameLogicService extends RestFetcherService {
private Set<PuzzleRoom> rooms;
private Map<String, PuzzleRoom> roomsByUserId;
private JsonMessageEncoderDecoder encoder;
public GameLogicService(int localPort) {
super(localPort);
this.roomsByUserId = new HashMap<>();
this.rooms = new HashSet<>();
this.encoder = new JsonMessageEncoderDecoder();
}
protected void setup() {
super.setup(); //needed
HttpServerOptions options = new HttpServerOptions();
options.setMaxWebSocketFrameSize(100000);
getVertx()
.createHttpServer(options)
.webSocketHandler(this::webSocketHandler)
.listen(localPort);
fetchPuzzles(
puzzles -> {
rooms.addAll(puzzles.stream().map(PuzzleRoom::new).collect(Collectors.toList()));
log("puzzles fetched!, they are"+ puzzles);
log("rooms are" + rooms);
}
);
log("ready at port: " + localPort);
}
private void webSocketHandler(ServerWebSocket ws) {
log("client connection arrived.");
if (ws.path().startsWith("/api/events/room")) {
getAnAvailableRoom()
.onSuccess(room -> assignRoomToNewClient(room, ws))
.onFailure(e -> ws.reject());
}
}
private void fetchPuzzles(Handler<List<Puzzle>> fun) {
log("fetching puzzles...");
fetchFromRestService(
ServicesInfo.PUZZLES_MANAGEMENT_SERVICE_PORT,
ServicesInfo.PUZZLES_MANAGEMENT_SERVICE_HOST,
"/api/puzzles",
result -> {
Optional<List<Puzzle>> puzzles = encoder.decodePuzzles(result.bodyAsString());
if (puzzles.isPresent()) {
log("puzzle is present in response by service");
fun.handle(puzzles.get());
} else {
log("puzzles management service response malformed: "+puzzles);
}
});
}
private Future<PuzzleRoom> getAnAvailableRoom(){
Promise<PuzzleRoom> promise = Promise.promise();
Optional<PuzzleRoom> room = rooms.stream().filter(x -> !x.getPuzzle().isComplete()).findFirst();
if (room.isPresent()) {
promise.complete(room.get());
log("a room is present: assigning to user");
} else {
log("a room is not present: fetching from service");
fetchPuzzles(puzzles -> {
if (!puzzles.isEmpty()) {
log("a room is returned by service");
Collections.shuffle(puzzles);
Puzzle newPuzzle = puzzles.get(0); //get the first puzzle available
promise.complete(new PuzzleRoom(newPuzzle));
} else {
log("no rooms returned by service");
promise.fail("no rooms.");
}
});
}
return promise.future();
}
private void assignRoomToNewClient(PuzzleRoom room, ServerWebSocket ws) {
log("assigning room to client");
String newClientId = ws.textHandlerID(); //could have generated ID randomly
rooms.add(room);
room.addUser(newClientId, ws);
roomsByUserId.put(newClientId, room);
ws.closeHandler(msg -> handleClientDisconnection(ws));
ws.textMessageHandler(msg -> handleWebSocketTextMessageByClient(msg, ws));
ws.writeTextMessage(new GameInfo("service", newClientId, room).toJsonString());
}
private void handleWebSocketTextMessageByClient(String message, ServerWebSocket ws) {
encoder.decodePuzzleEvent(message).ifPresent(decoded -> {
String senderUserId = decoded.getSenderId();
PuzzleRoom senderRoom = roomsByUserId.get(senderUserId);
if (decoded instanceof UserJoined) {
log("received clientjoined event at service.");
senderRoom.broadcastExcept(senderUserId, message);
} else if (decoded instanceof TilesSwap) {
log("received tilesswap event at service.");
senderRoom.getPuzzle().swap(
((TilesSwap) decoded).getTile1Id(),
((TilesSwap) decoded).getTile2Id());
senderRoom.broadcast(message);
if (senderRoom.getPuzzle().isComplete()){
senderRoom.broadcast(encoder.jsonEncode(new PuzzleCompleted(decoded.getSenderId())));
}
} else if (decoded instanceof CursorMoved){
log("received CursorMoved event at service.");
senderRoom.broadcastExcept(senderUserId, message);
} else if (decoded instanceof UserExited){
log("received ClientExited event at service.");
senderRoom.disconnectUser(senderUserId);
senderRoom.broadcast(message);
} else {
log("errors on formatting json."); //send error message to client
}
});
}
private void handleClientDisconnection(ServerWebSocket ws) {
log("a user disconnected.");
String senderUserId = ws.textHandlerID();
PuzzleRoom senderRoom = roomsByUserId.get(senderUserId);
senderRoom.disconnectUser(senderUserId);
senderRoom.broadcast(new UserExited(senderUserId).toJsonString());
}
}
|
package org.example.englishforum.controller;
import org.example.englishforum.dto.UserDto;
import org.example.englishforum.service.AuthenticationService;
import org.example.englishforum.service.JwtService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class AuthenticationControllerTest {
@Mock
AuthenticationService authService;
@Mock
JwtService jwtService;
@InjectMocks
AuthenticationController authenticationController;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
@DisplayName("Should login user and return ok status")
void loginUser() {
// Create a userDto
UserDto userDto = new UserDto();
// Mock the behavior of the signIn method in the authService
when(authService.signIn(userDto)).then(invocation -> {
UserDto argument = invocation.getArgument(0);
// Modify the userDto as per your service's behavior
argument.setUsername("John");
argument.setPassword("Doe");
return argument; // Return the modified userDto
});
// Call the login method in the authenticationController
ResponseEntity<?> response = authenticationController.login(userDto);
// Assert the expected result
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(userDto, response.getBody()); // This might need to be adjusted based on your service's behavior
}
@Test
@DisplayName("Should register user and return created status")
void registerUser() {
UserDto userDto = new UserDto();
when(authService.signUp(userDto)).then(invocation -> {
UserDto argument = invocation.getArgument(0);
// Modify the userDto as per your service's behavior
argument.setEmail("Jane");
argument.setPassword("Doe");
return null;
});
ResponseEntity<?> response = authenticationController.register(userDto);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
assertEquals(userDto, response.getBody());
}
@Test
@DisplayName("Should get user by token and return ok status")
void getUserByToken() {
UserDto userDto = new UserDto();
String token = "token";
when(jwtService.findUserByToken(token)).thenReturn(userDto);
ResponseEntity<?> response = authenticationController.getUser(token);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(userDto, response.getBody());
}
}
|
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
#define RANGE 255
// } Driver Code Ends
//User function Template for C++
class Solution{
public:
//Function to arrange all letters of a string in lexicographical
//order using Counting Sort.
string countSort(string arr){
// code here
vector<int> count(26, 0);
for(char c : arr) {
count[c - 'a']++;
}
for(int i = 1; i < 26; ++i) {
count[i] += count[i - 1];
}
string sorted(arr.length(), ' ');
for(int i = arr.size() - 1; i >= 0; --i) {
int pos = --count[arr[i] - 'a'];
sorted[pos] = arr[i];
}
return sorted;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
string arr;
cin>>arr;
Solution obj;
cout<<obj.countSort(arr)<<endl;
}
return 0;
}
// } Driver Code Ends
|
import fs from "node:fs";
import { SharedEventBus as eventBus } from "../Components/SharedEventBus";
import { ScheduledTask, SchedulerTime, TempTriggerArray } from "../Types/Scheduler";
import { Thermometer } from "../Types/DeviceSensors";
import { createNotification } from "../Components/NotificationSender";
import { NotificationType } from "../Types/NotificationType";
import { getToggleTypeFromOutputName, findToggle } from "../PersistedOutput";
import { ToggleType } from "../Types/DeviceBaseToggle";
import { ToggleResult } from "../Types/ToggleResult";
import { SchedulerTimeToTime } from "../Components/SchedulerTimeToTime";
import { ToggleEvent } from "../Types/ToggleEvent";
let scheduler: Array<ScheduledTask> = [];
export function getScheduledTasks(): Array<ScheduledTask> {
return scheduler;
}
/**
* @todo: There is a bug where if the device is not in the same
* timezone as the user's browser, the scheduler will not work correctly.
* Find a solution for this, but its a low priority issue.
* Could be worked around by having the client send in their timezone.
*/
function getSecondsUntilTargetTime(timeArr) {
const now = new Date(); // get current date and time
const targetTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), timeArr[0], timeArr[1]); // create a new date object with the target time today
const secondsUntilTargetTime = (targetTime.getTime() - now.getTime()) / 1000; // calculate the number of seconds until the target time
console.log("Time debug", secondsUntilTargetTime, now.toLocaleString(), targetTime.toLocaleString(), timeArr);
if (secondsUntilTargetTime < 0) {
// if the target time has already passed today
return false; // return false
}
return secondsUntilTargetTime; // return the number of seconds until the target time
}
// timeoutArray and intervalArray is an array of all the timeouts that are currently running.
// We will use this to clear all pending tasks when the user changes the schedules.
let timeoutArray: Array<NodeJS.Timeout> = [];
let intervalArray: Array<NodeJS.Timer> = [];
let tempTriggerArrays: Array<TempTriggerArray> = [];
// Override array means the user has manually turned on/off the output.
// Applicable for "TempRange" and "TimeRange" triggers.
// Right now only TempRange is implemented, and realistiaclly it is the only one that needs to be implemented.
let overrideArray: Array<boolean> = [];
function checkOverride(scheduledTaskName: string) {
return overrideArray[scheduledTaskName];
}
export function setOverride(scheduledTaskName: string, value: boolean) {
overrideArray[scheduledTaskName] = value;
}
const format = {
scheduledTaskName: {
outputName: "",
every: [
{
time: [10, 30],
lastExecuted: -1,
},
{
time: [17, 30],
lastExecuted: -1,
},
],
tempRange: [28, 31],
timeRange: {
from: {
time: [20, 0],
lastExecuted: -1,
},
to: {
time: [5, 0],
lastExecuted: -1,
},
},
},
};
// Copied from BingGPT. This is a function that will throttle the execution of a function.
//
function throttle(callback: { apply: (arg0: any, arg1: IArguments) => void }, interval: number) {
// Initialize a timer variable
let timer: NodeJS.Timer | null = null;
// Return a function that will be called when the event occurs
return function () {
// If the timer is null, it means we can run the callback function
if (timer === null) {
// Run the callback function
callback.apply(this, arguments);
// Set the timer to wait for the interval before setting it back to null
timer = setTimeout(function () {
timer = null;
}, interval);
}
};
}
function tempReceiver(data: Thermometer) {
for (let i = 0; i < tempTriggerArrays.length; i++) {
// Sanity Check first.
// If the temp sensor is messed up (data.temperature) is below -50 or above 100, it means something is wrong within the sensor.
// BESIDES, raspberry pi is not meant to be used in extreme temperatures.
if (data.Temperature < -50 || data.Temperature > 100) {
console.error("[Scheduler] Temperature sensor seems to be malfunctioning. Skipping temperature triggers.");
} else {
const trigger = tempTriggerArrays[i];
// If current temperature is within the range, turn on the output.
// If current tempearture is lower than the lower bound, turn off the output.
// If current temperature is higher than the upper bound, the output should remain on.
if (checkOverride(trigger.scheduledTaskName)) {
// currentToggleState allows us to check if the output is already on or off, so we don't send duplicate commands.
const localToggle = findToggle(trigger.scheduledTaskName);
if (!localToggle) console.warn("Can not find toggle for some reason. Trigger object" + trigger)
const currentToggleState = localToggle?.toggleValue || false; // If the toggle is not found, assume it is off.
if (data.Temperature >= trigger.triggerOnTemp && data.Temperature <= trigger.triggerOnTemp && !currentToggleState ) {
executeTemp(trigger.scheduledTaskName, trigger, "temp", true);
} else if (data.Temperature < trigger.triggerOffTemp && !currentToggleState) {
executeTemp(trigger.scheduledTaskName, trigger, "temp", false);
} else if (data.Temperature > trigger.triggerOnTemp && !currentToggleState) {
// The current temperature is higher than the upper bound, but the output should remain on.
executeTemp(trigger.scheduledTaskName, trigger, "temp", true);
}
} else {
console.log("Skipping temp trigger because of override.");
}
}
}
}
export function initScheduler() {
console.log("[Scheduler] Starting scheduler...");
if (fs.existsSync("/home/captainhandsome/project-tiara-persistent/scheduler.json")) {
console.log("[Scheduler] Schedules loaded...");
scheduler = JSON.parse(fs.readFileSync("/home/captainhandsome/project-tiara-persistent/scheduler.json", "utf8"));
} else {
// Schedules default layout
// Temperature unit is in Celsius.
// Time unit is in 24 hour format.
// Time is in array format [hour, minute]
// Does not account for Daylight Savings Time. (Researchers do not use DST, and therefore we do not know how to deal with it.)
scheduler = [];
fs.writeFileSync("/home/captainhandsome/project-tiara-persistent/scheduler.json", JSON.stringify(scheduler));
console.log("[Scheduler] No schedules - generating default...");
}
eventBus.emit("scheduler.ready", null, scheduler);
// Our tempearture sensor sends data every 2 seconds.
// We should have a mechanism to reduce the rate to about every 3/4 of a minute.
// This is to prevent the scheduler from being overwhelmed with data.
// TODO: Implement a mechanism to reduce the rate of data.
eventBus.on("sensors.temp.inside", throttle(tempReceiver, 45000));
ParseSchedulesAndTriggers();
}
// utilities
function execute(key: string, eventHandle: SchedulerTime, triggerType: string, toggleValue: boolean) {
console.log(`Executing ${key}'s ${triggerType}-type schedulable...`);
/**
* TODO: A POST request to the server to update the toggle value, so the web server will also know our Local State.
*
*/
let callbackNoter;
createNotification(
key + " automation started",
`Automation for "${key}" has started.`,
NotificationType.AUTOMATION_STARTED,
Date.now()
)
const emit: ToggleEvent = {
toggleName: key,
toggleValue: toggleValue,
toggleType: ToggleType.ONEOFF, // We don't care about this when triggering.
callback: (data: ToggleResult) => {
// Update lastExecuted
if (!data.success) {
console.warn(`[Scheduler] Executed scheduled task ${key} but the callback returned an error: ${data.message}`);
createNotification(
key + " automation execution failure",
`Automation for "${key}" failed with error: ${data.message}`,
NotificationType.AUTOMATION_ERROR,
Date.now()
)
return;
}
createNotification(
key + " automation finished" ,
`Automation for "${key}" succeeded!`,
NotificationType.AUTOMATION_FINISHED,
Date.now()
)
eventHandle.lastExecuted = Date.now();
fs.writeFileSync("/home/captainhandsome/project-tiara-persistent/scheduler.json", JSON.stringify(scheduler));
clearTimeout(callbackNoter);
},
}
eventBus.emit("ToggleEventSystemTriggered", null, emit);
callbackNoter = setTimeout(() => {
console.warn(`[Scheduler] Executed scheduled task ${key} but the callback was not called within 2 minutes.`);
}, 120000);
}
function executeTemp(key: string, eventHandle: TempTriggerArray, triggerType: string, toggleValue: boolean) {
console.log(`Executing ${key}'s ${triggerType}-type schedulable...`);
/**
* TODO: A POST request to the server to update the toggle value, so the web server will also know our Local State.
*
*/
let callbackNoter;
eventBus.emit("ToggleEventSystemTriggered", null, {
toggleName: key,
toggleValue: toggleValue,
callback: (data) => {
// Update lastExecuted
if (data.hasError) {
console.warn(`[Scheduler] Executed scheduled task ${key} but the callback returned an error: ${data.error}`);
}
fs.writeFileSync("/home/captainhandsome/project-tiara-persistent/scheduler.json", JSON.stringify(scheduler));
clearTimeout(callbackNoter);
},
});
callbackNoter = setTimeout(() => {
console.warn(`[Scheduler] Executed scheduled task ${key} but the callback was not called within 2 minutes.`);
}, 120000);
}
/*
Thesis side notes (Scopes and Limitations)
What if the end user manually triggered the function before the target time?
Well, the end user can manually trigger the function before the target time,
but when the target time is reached, the function will be executed again.
There are two approaches to this problem:
1: We can tell the frontend to actively warn if the end user manually triggers the function 30 minutes before
the trigger time, similar warning when they manually trigger a function within 30 minutes of the past trigger time.
2: Let them be. The function will be executed again when the target time is reached. This is the Unix way.
3: A blend of both. We can tell the frontend to warn the end user if they manually trigger the function within 30 minutes of the past trigger time
and let them either continue or cancel the manual trigger. If they continue, the function will be executed again when the target time is reached.
*/
function ParseSchedulesAndTriggers() {
// Since this function is called every time the schedules are reloaded, or the system is started, we will clear all pending timeouts and intervals.
timeoutArray = [];
intervalArray = [];
tempTriggerArrays = [];
for (let i = 0; i < scheduler.length; i++) {
const localScheduler: ScheduledTask = scheduler[i];
if (localScheduler.every) {
console.log("[Scheduler] Output %s has EVERY", localScheduler.outputName, localScheduler.every);
let everyArray = localScheduler.every;
for (let i = 0; i < everyArray.length; i++) {
if (everyArray[i].time === null) {
console.warn("[Scheduler] Output %s has an unset time. Skipping...", localScheduler.outputName);
} else {
/*
How do we determine that a Every-type of Schedulable has been executed?
1: We will compute the seconds until the target time. If it is false, we know that the target time has already passed today
2: If the target time has not passed today, we will set a timeout to execute the function at the target time, then we will set a daily setInterval to execute the function every day at the target time.
3: If the target time has passed today, we will set a timeout to execute the function at the target time tomorrow, then we will set a daily setInterval to execute the function every day at the target time.
*/
const secondsUntilTargetTime = getSecondsUntilTargetTime(everyArray[i].time);
if (secondsUntilTargetTime) {
// The target time has not passed yet today. We will set a timeout to execute the function at the target time.
console.log(
"[Scheduler] Target time is still good for today (%ss away). Scheduling execution for %s's every-type schedulable...",
secondsUntilTargetTime,
localScheduler.outputName
);
// Lets make a timeout to execute the function at the target time.
const timeout = setTimeout(() => {
// Two things in the timeout when the target time is reached.
// 1: Execute the function.
// 2: Set a daily setInterval to execute the function every day at the target time.
execute(localScheduler.outputName, everyArray[i], "every", true);
const interval = setInterval(() => {
// Execute function
// Note that in Every-triggers, toggleValue is always true.
console.log("[Scheduler] Executing %s's every-type schedulable...", localScheduler.outputName);
execute(localScheduler.outputName, everyArray[i], "every", true);
}, 86400 * 1000);
intervalArray.push(interval);
}, secondsUntilTargetTime * 1000);
timeoutArray.push(timeout);
} else {
// The target time has already passed today. We will set a timeout to execute the function at the target time tomorrow.
// Additionally, TODO, we will send a message to the server to let the user know that the function is not executed today.
const now = new Date();
const tomorrowTimeout =
new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, everyArray[i][0], everyArray[i][1]).getTime() -
now.getTime();
console.log("Target time has already passed today. Scheduling execution for tomorrow...");
createNotification(
localScheduler.outputName + " automation skipped",
`Automation for "${localScheduler.outputName}" every skipped because the target time (${SchedulerTimeToTime(everyArray[i].time)}) has already passed today. It will be executed tomorrow, or you may manually execute it now.`,
NotificationType.AUTOMATION_ERROR,
Date.now()
)
const timeout = setTimeout(() => {
// Once we got our timeout executed for tomorrow, we will now set
// a daily setInterval to execute the function every day at the target time.
const interval = setInterval(() => {
// Execute function
// Note that in Every-triggers, toggleValue is always true.
execute(localScheduler.outputName, everyArray[i], "every", true);
}, 86400 * 1000);
intervalArray.push(interval);
}, tomorrowTimeout);
timeoutArray.push(timeout);
}
}
}
}
const tempRange = localScheduler.tempRange;
if (tempRange && tempRange !== null) {
console.log(
"Output %s has TEMPRANGE. Trigger off temp: %s. Trigger on temp: %s",
localScheduler.outputName,
tempRange[0],
tempRange[1]
);
// TempRange Trigger is simple. We just need to check if the current temperature is within the range.
tempTriggerArrays.push({
scheduledTaskName: localScheduler.outputName,
triggerOffTemp: tempRange[0],
triggerOnTemp: tempRange[1],
});
}
const timeRange = localScheduler.timeRange;
if (timeRange) {
console.log("Output %s has TIMERANGE", localScheduler.outputName);
const from = timeRange.from.time;
const to = timeRange.to.time;
console.log("times:", from, to)
if (from && to) {
// TimeRange trigger is a bit more and less complicated than Every trigger, somehow.
// 1: Determine seconds until trigger start | end
const secondsUntilTriggerStart = getSecondsUntilTargetTime(timeRange.from.time);
const secondsUntilTriggerEnd = getSecondsUntilTargetTime(timeRange.to.time);
// 2: Check if the trigger start time has passed today.
// If it has passed, let's check if the trigger end is also passed today.
// If the trigger end is passed today, it means that we should not execute the function today.
// If the trigger end is not passed today, it means that we are still within the trigger time range.
// It means that we should turn on the output.
// If the trigger start has not passed today, it means that we are still outside the trigger time range.
// It means that we should schedule a timeout to execute the function at the trigger start time.
if (secondsUntilTriggerStart && secondsUntilTriggerEnd) {
// Trigger start has not passed today. We will set a timeout to execute the function at the trigger start time.
console.log(
"[Scheduler] Trigger start time has not passed today. Scheduling execution for %s's timeRange-type schedulable...",
localScheduler.outputName
);
const timeout = setTimeout(() => {
// Once we got our timeout executed for later, we will now set
// a daily setInterval to execute the function every day at the target time.
execute(localScheduler.outputName, timeRange.from, "timeRange", true);
const interval = setInterval(() => {
// Execute function.
// Note that in triggerStart timeRange type schedulable, toggleValue is always true.
execute(localScheduler.outputName, timeRange.from, "timeRange", true);
}, 86400 * 1000);
intervalArray.push(interval);
}, secondsUntilTriggerStart * 1000);
timeoutArray.push(timeout);
const endTimeTimeout = setTimeout(() => {
// Create a timeout to execute the function at the trigger end time.
// This timeout will be used to turn off the output.
const endTimeInterval = setInterval(() => {
// Execute function.
// Note that in triggerEnd timeRange type schedulable, toggleValue is always false.
execute(localScheduler.outputName, timeRange.to, "timeRange", false);
}, 86400 * 1000);
intervalArray.push(endTimeInterval);
}, secondsUntilTriggerEnd * 1000);
timeoutArray.push(endTimeTimeout);
} else {
// Trigger start has passed today. We will check if the trigger end has passed today
if (secondsUntilTriggerEnd) {
// Trigger end has not passed today.
// It means that we are still within the trigger time range.
// It means that we should turn on the output.
execute(localScheduler.outputName, timeRange.from, "timeRange", true);
// Here we schedule a triggerEnd timeout and interval because we are still within the trigger time range..
const endTimeTimeout = setTimeout(() => {
// Create a timeout to execute the function at the trigger end time.
// This timeout will be used to turn off the output.
execute(localScheduler.outputName, timeRange.to, "timeRange", false);
const endTimeInterval = setInterval(() => {
// Execute function.
// Note that in triggerEnd timeRange type schedulable, toggleValue is always false.
execute(localScheduler.outputName, timeRange.to, "timeRange", false);
}, 86400 * 1000);
intervalArray.push(endTimeInterval);
}, secondsUntilTriggerEnd * 1000);
timeoutArray.push(endTimeTimeout);
} else {
// Trigger end has passed today.
// It means we are past the trigger time range.
// Schedule both start and end timeouts and intervals for tomorrow.
const now = new Date();
const tomorrowFrom =
new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, from[0], from[1]).getTime() - now.getTime();
const tomorrowTo = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, to[0], to[1]).getTime() - now.getTime();
console.log(
"[Scheduler] Time-range target time has already passed today. Scheduling %s's execution for tomorrow...",
localScheduler.outputName
);
createNotification(
localScheduler.outputName + " Automation skipped",
`Automation for "${localScheduler.outputName}" Time-Range skipped because the target time (${SchedulerTimeToTime(timeRange?.from.time)} - ${SchedulerTimeToTime(timeRange?.to.time)}) has already passed today. It will be executed tomorrow, or you may manually execute it now.`,
NotificationType.AUTOMATION_ERROR,
Date.now()
)
const fromTimeout = setTimeout(() => {
// Once we got our timeout executed for tomorrow, we will now set
// a daily setInterval to execute the function every day at the target time.
execute(localScheduler.outputName, timeRange.from, "timeRange", true);
const interval = setInterval(() => {
// Execute function.
// Note that in triggerStart timeRange type schedulable, toggleValue is always true.
execute(localScheduler.outputName, timeRange.from, "timeRange", true);
}, 86400 * 1000);
intervalArray.push(interval);
}, tomorrowFrom);
timeoutArray.push(fromTimeout);
const toTimeout = setTimeout(() => {
// Once we got our timeout executed for tomorrow, we will now set
// a daily setInterval to execute the function every day at the target time.
execute(localScheduler.outputName, timeRange.to, "timeRange", false);
const interval = setInterval(() => {
// Execute function.
// Note that in triggerEnd timeRange type schedulable, toggleValue is always false.
execute(localScheduler.outputName, timeRange.to, "timeRange", false);
}, 86400 * 1000);
intervalArray.push(interval);
}, tomorrowTo);
timeoutArray.push(toTimeout);
}
}
} else {
console.log("Output %s has TIMERANGE but no from or to", localScheduler.outputName);
}
}
}
}
export function reloadSchedules() {
// Clear all pending timeouts and intervals
for (let i = 0; i < timeoutArray.length; i++) {
clearTimeout(timeoutArray[i]);
}
for (let i = 0; i < intervalArray.length; i++) {
clearInterval(intervalArray[i]);
}
// Reload schedules
scheduler = JSON.parse(fs.readFileSync("/home/captainhandsome/project-tiara-persistent/scheduler.json", "utf-8"));
ParseSchedulesAndTriggers();
}
export function applyNewSchedules(schedules: Array<ScheduledTask>) {
// Clear all pending timeouts and intervals
for (let i = 0; i < timeoutArray.length; i++) {
clearTimeout(timeoutArray[i]);
}
for (let i = 0; i < intervalArray.length; i++) {
clearInterval(intervalArray[i]);
}
// Apply new schedules, and save our received schedules to the file
scheduler = schedules;
fs.writeFileSync("/home/captainhandsome/project-tiara-persistent/scheduler.json", JSON.stringify(scheduler));
ParseSchedulesAndTriggers();
}
export function insertScheduledTask(scheduledTask: ScheduledTask): boolean {
// Insert a new scheduled task to our scheduler.
// This will also save the new schedule to the file.
// Clear all pending timeouts and intervals
// Duplicate checking
let hasAnyDuplicate = false;
for (let i = 0; i < scheduler.length; i++) {
if (scheduler[i].outputName === scheduledTask.outputName) {
console.log("[Scheduler] Output already registered. Replacing existing schedule...");
scheduler[i] = scheduledTask;
hasAnyDuplicate = true;
}
}
// Data cleanup in accordance to selected toggles toggletype.
const type = getToggleTypeFromOutputName(scheduledTask.outputName);
if (type) {
console.log("Running data cleanup for %s", scheduledTask.outputName);
if (type === ToggleType.ONEOFF) {
if (scheduledTask.timeRange) {
console.log("Removing timeRange from %s", scheduledTask.outputName);
scheduledTask.timeRange = null;
}
if (scheduledTask.tempRange) {
console.log("Removing tempRange from %s", scheduledTask.outputName);
scheduledTask.tempRange = null;
}
} else if (type === ToggleType.SWITCH) {
if (scheduledTask.every) {
console.log("Removing every from %s", scheduledTask.outputName);
scheduledTask.every = null;
}
}
} else {
console.log("No toggle type found for %s", scheduledTask.outputName);
}
for (let i = 0; i < timeoutArray.length; i++) {
clearTimeout(timeoutArray[i]);
}
for (let i = 0; i < intervalArray.length; i++) {
clearInterval(intervalArray[i]);
}
// Prevent duplicate schedules
if (!hasAnyDuplicate) scheduler.push(scheduledTask);
fs.writeFileSync("/home/captainhandsome/project-tiara-persistent/scheduler.json", JSON.stringify(scheduler));
ParseSchedulesAndTriggers();
return true;
}
/**
* @deprecated We dont need to register outputs anymore. The user should manually add any trigger to the scheduler.
*/
export function addOutput(outputName) {
console.trace("DEPRECATED CALL: addOutput", outputName)
// Creates an output.
// We will also register this to our DeviceState.
/*
for (let i = 0; i < scheduler.length; i++) {
if (scheduler[i].outputName === outputName) {
console.log("[Scheduler] Output %s already registered.", outputName);
return;
}
}
console.log("[Scheduler] Created empty schedule for %s.", outputName);
// Create an empty schedule for the output.
// This is to prevent the scheduler from crashing when the user tries to add a schedule for an output that does not exist.
// Also: 0, 0 is a valid time, so we can't use that as a placeholder.
scheduler.push({
...ScheduledTaskBase,
outputName: outputName
});
// Clear all pending timeouts and intervals
for (let i = 0; i < timeoutArray.length; i++) {
clearTimeout(timeoutArray[i]);
}
for (let i = 0; i < intervalArray.length; i++) {
clearInterval(intervalArray[i]);
}
fs.writeFileSync("/home/captainhandsome/project-tiara-persistent/scheduler.json", JSON.stringify(scheduler));
ParseSchedulesAndTriggers(); */
}
|
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Filament\Panel;
use App\Models\Company;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Filament\Models\Contracts\FilamentUser;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
// class User extends Authenticatable
// class User extends Authenticatable
class User extends Authenticatable implements FilamentUser
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'phone',
'profile',
'award',
'role',
'interest',
'social', //This could be github, linkedin or fb
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'password_confirmation',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
public function Companies(): HasMany
{
return $this->hasMany(Company::class);
}
public function canAccessPanel(Panel $panel): bool
{
// return str_ends_with($this->email, '@devsinfo.com') && $this->hasVerifiedEmail();
if ($this->hasRole(['super admin','company','developer'])){
return true;
}
return false;
}
}
|
import React, { useState, useEffect } from 'react';
import { HeartTwoTone, SmileTwoTone } from '@ant-design/icons';
import {
Card,
Typography,
Alert,
Table,
Radio,
Divider,
Button,
Row,
Col,
Modal,
Form,
Input,
Select,
InputNumber,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { useIntl } from 'umi';
import { EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import {
getProducts,
getProductById,
updateProductById,
addProduct,
deleteProduct,
} from '@/services/backend/api';
import { text } from 'express';
type LayoutType = Parameters<typeof Form>[0]['layout'];
const { Option } = Select;
export default (): React.ReactNode => {
const [form] = Form.useForm();
const intl = useIntl();
const [dataProducts, setDataProducts] = useState<API.ProductsItem[]>([]);
const [isModalVisible1, setIsModalVisible1] = useState(false);
const [isModalVisible2, setIsModalVisible2] = useState(false);
const [disbledButton, setDisbledButton] = useState(true);
const [productId, setProductId] = useState('');
const [productName, setProductName] = useState('');
const [productPrice, setProductPrice] = useState('');
const [productStatus, setProductStatus] = useState('');
const [deleteId, setDeleteId] = useState([]);
const [formLayout, setFormLayout] = useState<LayoutType>('horizontal');
const onFormLayoutChange = ({ layout }: { layout: LayoutType }) => {
setFormLayout(layout);
};
const formItemLayout =
formLayout === 'horizontal'
? {
labelCol: { span: 4 },
wrapperCol: { span: 14 },
}
: null;
const buttonItemLayout =
formLayout === 'horizontal'
? {
wrapperCol: { span: 14, offset: 4 },
}
: null;
const showEditModal = async (id: string) => {
const result = await getProductById(id);
if (result) {
setProductId(result[0].id);
setProductName(result[0].product_name);
setProductPrice(result[0].product_price);
setProductStatus(result[0].product_status);
setIsModalVisible1(true);
}
};
const showAddModal = async () => {
setIsModalVisible2(true);
};
const handleUpdateProduct = async () => {
const data = {
id: productId,
product_name: productName,
product_price: productPrice,
product_status: productStatus,
};
const update = await updateProductById(data);
if (update) {
refeshTable();
setIsModalVisible1(false);
}
};
const deleteProductClick = async () => {
const data = {
data: deleteId,
};
const statusDelete = await deleteProduct(data);
if (statusDelete) {
refeshTable();
setDisbledButton(true);
}
};
const handleAddProduct = async () => {
const data = {
product_name: productName,
product_price: productPrice,
product_status: productStatus,
};
const status = await addProduct(data);
if (status) {
refeshTable();
setIsModalVisible2(false);
}
};
const clearState = () => {
setProductId('');
setProductName('');
setProductPrice('');
setProductStatus('');
// console.log(productId)
// console.log(productName)
// console.log(productId)
// console.log(productId)
};
const refeshTable = async () => {
const result = await getProducts();
const data = result.map(
(x: {
id: any;
product_code: any;
product_name: any;
product_status: any;
product_price: any;
updatedAt: any;
}) => {
const mapData = {
id: x.id,
product_code: x.product_code,
product_name: x.product_name,
product_status: x.product_status,
product_price: x.product_price,
updatedAt: x.updatedAt,
};
return mapData;
},
);
setDataProducts(data);
clearState();
};
const handleCancelUpdate = () => {
setIsModalVisible1(false);
clearState();
};
const handleCancelAdd = () => {
clearState();
setIsModalVisible2(false);
};
const columns = [
{
title: 'Product Code',
dataIndex: 'product_code',
},
{
title: 'Product Name',
dataIndex: 'product_name',
},
{
title: 'Product Status',
dataIndex: 'product_status',
},
{
title: 'Price',
dataIndex: 'product_price',
},
{
title: 'Last Update',
dataIndex: 'updatedAt',
},
{
title: 'Action',
dataIndex: 'id',
render: (text: string) => (
<a href="#" onClick={() => showEditModal(text)}>
Edit
</a>
),
},
];
const rowSelection = {
onChange: (selectedRowKeys: React.Key[], selectedRows: API.ProductsItem[]) => {
if (selectedRowKeys.length == 0) {
setDisbledButton(true);
} else {
setDisbledButton(false);
setDeleteId(selectedRowKeys);
}
},
getCheckboxProps: (record: API.ProductsItem) => ({
// disabled: record.name === 'Disabled User', // Column configuration not to be checked
name: record.product_name,
}),
};
useEffect(() => {
(async function fetchdata() {
const result = await getProducts();
const data = result.map(
(x: {
id: any;
product_code: any;
product_name: any;
product_status: any;
product_price: any;
updatedAt: any;
}) => {
const mapData = {
id: x.id,
product_code: x.product_code,
product_name: x.product_name,
product_status: x.product_status,
product_price: x.product_price,
updatedAt: x.updatedAt,
};
return mapData;
},
);
setDataProducts(data);
})();
}, []);
function confirmDelete() {
Modal.confirm({
title: 'Are you sure delete this product?',
icon: <ExclamationCircleOutlined />,
okText: 'Yes',
okType: 'danger',
cancelText: 'No',
onOk() {
deleteProductClick();
},
});
}
return (
<>
<PageHeaderWrapper>
<Card>
<Typography.Title level={2} style={{ textAlign: 'center' }}>
<div>
<Divider />
<Row justify="end" style={{ marginBottom: '0.5rem' }}>
<Col span={4}>
<Button type="default">Import</Button>{' '}
<Button type="primary" onClick={showAddModal}>
Add
</Button>{' '}
<Button danger disabled={disbledButton} onClick={confirmDelete}>
Delete
</Button>
</Col>
</Row>
<Table
rowSelection={{
type: 'checkbox',
...rowSelection,
}}
rowKey="id"
columns={columns}
dataSource={dataProducts}
/>
</div>
</Typography.Title>
</Card>
</PageHeaderWrapper>
<Modal
title="Edit Product"
visible={isModalVisible1}
onOk={handleUpdateProduct}
onCancel={handleCancelUpdate}
>
<h5>{productName}</h5>
<Form
{...formItemLayout}
layout={formLayout}
form={form}
initialValues={{ layout: formLayout }}
onValuesChange={onFormLayoutChange}
>
<Form.Item label="Name">
<Input
placeholder="Product Name"
value={productName}
onChange={(e) => setProductName(e.target.value)}
/>
</Form.Item>
<Form.Item label="Price">
<InputNumber min={0} value={productPrice} onChange={(e) => setProductPrice(e)} />
</Form.Item>
<Form.Item label="Status">
<Select value={productStatus} onChange={(e) => setProductStatus(e)}>
<Option value="Active" selected>
Active
</Option>
<Option value="Not Active">Not Active</Option>
</Select>
</Form.Item>
</Form>
</Modal>
<Modal
title="Add Product"
visible={isModalVisible2}
onOk={handleAddProduct}
onCancel={handleCancelAdd}
>
<Form
{...formItemLayout}
layout={formLayout}
form={form}
initialValues={{ layout: formLayout }}
onValuesChange={onFormLayoutChange}
id="addForm"
>
<Form.Item label="Name">
<Input onChange={(e) => setProductName(e.target.value)} />
</Form.Item>
<Form.Item label="Price">
<InputNumber min={0} onChange={(e) => setProductPrice(e)} />
</Form.Item>
<Form.Item label="Status">
<Select onChange={(e) => setProductStatus(e)}>
<Option value="Active" selected>
Active
</Option>
<Option value="Not Active">Not Active</Option>
</Select>
</Form.Item>
</Form>
</Modal>
</>
);
};
|
package com.example.practico4.ui.activities
import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.practico4.R
import com.example.practico4.databinding.ActivityGeneroBinding
import com.example.practico4.models.Genero
import com.example.practico4.ui.adapters.GeneroAdapter
import com.example.practico4.ui.adapters.LibroAdapter
import com.example.practico4.ui.viewmodels.GeneroViewModel
class GeneroActivity : AppCompatActivity(), GeneroAdapter.OnGeneroClickListener {
lateinit var binding : ActivityGeneroBinding
private val model: GeneroViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityGeneroBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
setupRecyclerView()
setupViewModelListeners()
setupEventListeners()
}
private fun setupViewModelListeners() {
model.generosList.observe(this) {
val adapter = (binding.lstGeneros.adapter as GeneroAdapter)
adapter.updateData(it)
}
}
override fun onResume() {
super.onResume()
model.fetchListaGeneros()
}
private fun setupEventListeners() {
binding.btnAnadirGenero.setOnClickListener {
val intent = Intent(this, GeneroSaveActivity::class.java)
startActivity(intent)
}
}
private fun setupRecyclerView() {
binding.lstGeneros.apply {
this.adapter = GeneroAdapter(ArrayList(), this@GeneroActivity)
layoutManager = LinearLayoutManager(this@GeneroActivity)
}
}
override fun onGeneroEdit(genero: Genero) {
val intent = Intent(this, GeneroSaveActivity::class.java)
intent.putExtra("generoId", genero.id)
startActivity(intent)
}
override fun onGeneroDelete(genero: Genero) {
model.deleteGenero(genero.id!!)
}
override fun onGeneroClick(genero: Genero) {
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("generoId", genero.id)
startActivity(intent)
}
}
|
/*
! tailwindcss v3.3.3 | MIT License | https://tailwindcss.com
*/
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/
*,
::before,
::after {
box-sizing: border-box;
/* 1 */
border-width: 0;
/* 2 */
border-style: solid;
/* 2 */
border-color: #e5e7eb;
/* 2 */
}
::before,
::after {
--tw-content: '';
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
6. Use the user's configured `sans` font-variation-settings by default.
*/
html {
line-height: 1.5;
/* 1 */
-webkit-text-size-adjust: 100%;
/* 2 */
-moz-tab-size: 4;
/* 3 */
-o-tab-size: 4;
tab-size: 4;
/* 3 */
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
/* 4 */
font-feature-settings: normal;
/* 5 */
font-variation-settings: normal;
/* 6 */
}
/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/
body {
margin: 0;
/* 1 */
line-height: inherit;
/* 2 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/
hr {
height: 0;
/* 1 */
color: inherit;
/* 2 */
border-top-width: 1px;
/* 3 */
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font family by default.
2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0;
/* 1 */
border-color: inherit;
/* 2 */
border-collapse: collapse;
/* 3 */
}
/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
/* 1 */
font-feature-settings: inherit;
/* 1 */
font-variation-settings: inherit;
/* 1 */
font-size: 100%;
/* 1 */
font-weight: inherit;
/* 1 */
line-height: inherit;
/* 1 */
color: inherit;
/* 1 */
margin: 0;
/* 2 */
padding: 0;
/* 3 */
}
/*
Remove the inheritance of text transform in Edge and Firefox.
*/
button,
select {
text-transform: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/
button,
[type='button'],
[type='reset'],
[type='submit'] {
-webkit-appearance: button;
/* 1 */
background-color: transparent;
/* 2 */
background-image: none;
/* 2 */
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type='search'] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Removes the default spacing and border for appropriate elements.
*/
blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
margin: 0;
}
fieldset {
margin: 0;
padding: 0;
}
legend {
padding: 0;
}
ol,
ul,
menu {
list-style: none;
margin: 0;
padding: 0;
}
/*
Reset default styling for dialogs.
*/
dialog {
padding: 0;
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/
input::-moz-placeholder, textarea::-moz-placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
input::placeholder,
textarea::placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
/*
Set the default cursor for buttons.
*/
button,
[role="button"] {
cursor: pointer;
}
/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
cursor: default;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block;
/* 1 */
vertical-align: middle;
/* 2 */
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/* Make elements with the HTML hidden attribute stay hidden by default */
[hidden] {
display: none;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
.container {
width: 100%;
}
@media (min-width: 640px) {
.container {
max-width: 640px;
}
}
@media (min-width: 768px) {
.container {
max-width: 768px;
}
}
@media (min-width: 1024px) {
.container {
max-width: 1024px;
}
}
@media (min-width: 1280px) {
.container {
max-width: 1280px;
}
}
@media (min-width: 1536px) {
.container {
max-width: 1536px;
}
}
.line_border {
width: 100%;
height: 50px;
background: #2b3d73;
/* clip-path: polygon(50.37% 7px, 98.81% -32%, 50.23% 8%, 8px -37.00%); */
-webkit-clip-path: polygon(50.52% 44px, 99.85% 23%, 50.6% 93%, 5px 21%);
clip-path: polygon(50.52% 44px, 99.85% 23%, 50.6% 93%, 5px 21%);
}
.curve_border {
width: 100%;
height: 50px;
background: #2b3d73;
-webkit-clip-path: polygon(50.37% 7px, 98.81% -32%, 50.23% 8%, 8px -37.00%);
clip-path: polygon(50.37% 7px, 98.81% -32%, 50.23% 8%, 8px -37.00%);
}
.absolute {
position: absolute;
}
.relative {
position: relative;
}
.left-2 {
left: 0.5rem;
}
.left-40 {
left: 10rem;
}
.left-\[13\%\] {
left: 13%;
}
.left-\[26\.5\%\] {
left: 26.5%;
}
.left-\[31\.5\%\] {
left: 31.5%;
}
.left-\[45\%\] {
left: 45%;
}
.left-\[5\%\] {
left: 5%;
}
.left-\[50\%\] {
left: 50%;
}
.left-\[55\.5\%\] {
left: 55.5%;
}
.left-\[57\%\] {
left: 57%;
}
.left-\[58\%\] {
left: 58%;
}
.left-\[60\%\] {
left: 60%;
}
.left-\[65\%\] {
left: 65%;
}
.left-\[78\%\] {
left: 78%;
}
.left-\[79\%\] {
left: 79%;
}
.left-\[80\%\] {
left: 80%;
}
.left-\[85\%\] {
left: 85%;
}
.left-\[90\%\] {
left: 90%;
}
.top-10 {
top: 2.5rem;
}
.top-6 {
top: 1.5rem;
}
.top-\[10\%\] {
top: 10%;
}
.top-\[100px\] {
top: 100px;
}
.top-\[15\%\] {
top: 15%;
}
.top-\[17\%\] {
top: 17%;
}
.top-\[27\%\] {
top: 27%;
}
.top-\[3\%\] {
top: 3%;
}
.top-\[40\%\] {
top: 40%;
}
.top-\[55\%\] {
top: 55%;
}
.top-\[58\%\] {
top: 58%;
}
.top-\[59\%\] {
top: 59%;
}
.top-\[60\%\] {
top: 60%;
}
.top-\[65\%\] {
top: 65%;
}
.top-\[75\%\] {
top: 75%;
}
.z-20 {
z-index: 20;
}
.z-40 {
z-index: 40;
}
.z-50 {
z-index: 50;
}
.mx-12 {
margin-left: 3rem;
margin-right: 3rem;
}
.mx-16 {
margin-left: 4rem;
margin-right: 4rem;
}
.mx-2 {
margin-left: 0.5rem;
margin-right: 0.5rem;
}
.mx-20 {
margin-left: 5rem;
margin-right: 5rem;
}
.mx-4 {
margin-left: 1rem;
margin-right: 1rem;
}
.mx-6 {
margin-left: 1.5rem;
margin-right: 1.5rem;
}
.mx-\[88px\] {
margin-left: 88px;
margin-right: 88px;
}
.mx-auto {
margin-left: auto;
margin-right: auto;
}
.my-4 {
margin-top: 1rem;
margin-bottom: 1rem;
}
.my-8 {
margin-top: 2rem;
margin-bottom: 2rem;
}
.-ml-10 {
margin-left: -2.5rem;
}
.-ml-7 {
margin-left: -1.75rem;
}
.-ml-8 {
margin-left: -2rem;
}
.-mt-10 {
margin-top: -2.5rem;
}
.-mt-12 {
margin-top: -3rem;
}
.-mt-16 {
margin-top: -4rem;
}
.-mt-6 {
margin-top: -1.5rem;
}
.mb-12 {
margin-bottom: 3rem;
}
.mb-4 {
margin-bottom: 1rem;
}
.mb-48 {
margin-bottom: 12rem;
}
.mb-8 {
margin-bottom: 2rem;
}
.ml-12 {
margin-left: 3rem;
}
.mt-12 {
margin-top: 3rem;
}
.mt-16 {
margin-top: 4rem;
}
.mt-2 {
margin-top: 0.5rem;
}
.mt-20 {
margin-top: 5rem;
}
.mt-24 {
margin-top: 6rem;
}
.mt-28 {
margin-top: 7rem;
}
.mt-4 {
margin-top: 1rem;
}
.mt-6 {
margin-top: 1.5rem;
}
.mt-8 {
margin-top: 2rem;
}
.inline-block {
display: inline-block;
}
.flex {
display: flex;
}
.h-12 {
height: 3rem;
}
.h-16 {
height: 4rem;
}
.h-20 {
height: 5rem;
}
.h-36 {
height: 9rem;
}
.h-40 {
height: 10rem;
}
.h-44 {
height: 11rem;
}
.h-48 {
height: 12rem;
}
.h-9 {
height: 2.25rem;
}
.h-\[100vh\] {
height: 100vh;
}
.h-\[35px\] {
height: 35px;
}
.h-auto {
height: auto;
}
.h-screen {
height: 100vh;
}
.w-1\/2 {
width: 50%;
}
.w-12 {
width: 3rem;
}
.w-16 {
width: 4rem;
}
.w-20 {
width: 5rem;
}
.w-24 {
width: 6rem;
}
.w-36 {
width: 9rem;
}
.w-48 {
width: 12rem;
}
.w-56 {
width: 14rem;
}
.w-60 {
width: 15rem;
}
.w-9 {
width: 2.25rem;
}
.w-\[140px\] {
width: 140px;
}
.w-\[500px\] {
width: 500px;
}
.w-\[90\%\] {
width: 90%;
}
.w-full {
width: 100%;
}
.cursor-pointer {
cursor: pointer;
}
.flex-col {
flex-direction: column;
}
.flex-wrap {
flex-wrap: wrap;
}
.items-center {
align-items: center;
}
.justify-end {
justify-content: flex-end;
}
.justify-center {
justify-content: center;
}
.justify-between {
justify-content: space-between;
}
.justify-around {
justify-content: space-around;
}
.gap-16 {
gap: 4rem;
}
.gap-2 {
gap: 0.5rem;
}
.gap-4 {
gap: 1rem;
}
.overflow-hidden {
overflow: hidden;
}
.rounded {
border-radius: 0.25rem;
}
.rounded-full {
border-radius: 9999px;
}
.rounded-md {
border-radius: 0.375rem;
}
.rounded-xl {
border-radius: 0.75rem;
}
.rounded-r-full {
border-top-right-radius: 9999px;
border-bottom-right-radius: 9999px;
}
.border {
border-width: 1px;
}
.border-b {
border-bottom-width: 1px;
}
.border-b-2 {
border-bottom-width: 2px;
}
.border-t-2 {
border-top-width: 2px;
}
.border-none {
border-style: none;
}
.border-blue-800 {
--tw-border-opacity: 1;
border-color: rgb(30 64 175 / var(--tw-border-opacity));
}
.border-violet-900 {
--tw-border-opacity: 1;
border-color: rgb(76 29 149 / var(--tw-border-opacity));
}
.bg-\[\#0d0819\] {
--tw-bg-opacity: 1;
background-color: rgb(13 8 25 / var(--tw-bg-opacity));
}
.bg-\[\#180e2c\] {
--tw-bg-opacity: 1;
background-color: rgb(24 14 44 / var(--tw-bg-opacity));
}
.bg-\[\#1a1626\] {
--tw-bg-opacity: 1;
background-color: rgb(26 22 38 / var(--tw-bg-opacity));
}
.bg-blue-400 {
--tw-bg-opacity: 1;
background-color: rgb(96 165 250 / var(--tw-bg-opacity));
}
.bg-emerald-400 {
--tw-bg-opacity: 1;
background-color: rgb(52 211 153 / var(--tw-bg-opacity));
}
.bg-gray-700 {
--tw-bg-opacity: 1;
background-color: rgb(55 65 81 / var(--tw-bg-opacity));
}
.bg-orange-600 {
--tw-bg-opacity: 1;
background-color: rgb(234 88 12 / var(--tw-bg-opacity));
}
.bg-white\/10 {
background-color: rgb(255 255 255 / 0.1);
}
.bg-yellow-600 {
--tw-bg-opacity: 1;
background-color: rgb(202 138 4 / var(--tw-bg-opacity));
}
.bg-\[radial-gradient\(ellipse_at_top_left\2c _var\(--tw-gradient-stops\)\)\] {
background-image: radial-gradient(ellipse at top left, var(--tw-gradient-stops));
}
.bg-gradient-to-b {
background-image: linear-gradient(to bottom, var(--tw-gradient-stops));
}
.bg-gradient-to-br {
background-image: linear-gradient(to bottom right, var(--tw-gradient-stops));
}
.bg-gradient-to-r {
background-image: linear-gradient(to right, var(--tw-gradient-stops));
}
.from-\[\#d4adff\] {
--tw-gradient-from: #d4adff var(--tw-gradient-from-position);
--tw-gradient-to: rgb(212 173 255 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
}
.from-blue-500 {
--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);
--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
}
.from-blue-700 {
--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);
--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
}
.from-fuchsia-500 {
--tw-gradient-from: #d946ef var(--tw-gradient-from-position);
--tw-gradient-to: rgb(217 70 239 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
}
.from-violet-500 {
--tw-gradient-from: #8b5cf6 var(--tw-gradient-from-position);
--tw-gradient-to: rgb(139 92 246 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
}
.from-violet-700 {
--tw-gradient-from: #6d28d9 var(--tw-gradient-from-position);
--tw-gradient-to: rgb(109 40 217 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
}
.via-\[\#8254d6\] {
--tw-gradient-to: rgb(130 84 214 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), #8254d6 var(--tw-gradient-via-position), var(--tw-gradient-to);
}
.via-blue-800 {
--tw-gradient-to: rgb(30 64 175 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), #1e40af var(--tw-gradient-via-position), var(--tw-gradient-to);
}
.via-red-500 {
--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), #ef4444 var(--tw-gradient-via-position), var(--tw-gradient-to);
}
.via-sky-300 {
--tw-gradient-to: rgb(125 211 252 / 0) var(--tw-gradient-to-position);
--tw-gradient-stops: var(--tw-gradient-from), #7dd3fc var(--tw-gradient-via-position), var(--tw-gradient-to);
}
.via-10\% {
--tw-gradient-via-position: 10%;
}
.to-\[\#070113\] {
--tw-gradient-to: #070113 var(--tw-gradient-to-position);
}
.to-\[\#d4adff\] {
--tw-gradient-to: #d4adff var(--tw-gradient-to-position);
}
.to-fuchsia-400 {
--tw-gradient-to: #e879f9 var(--tw-gradient-to-position);
}
.to-pink-400 {
--tw-gradient-to: #f472b6 var(--tw-gradient-to-position);
}
.to-rose-700 {
--tw-gradient-to: #be123c var(--tw-gradient-to-position);
}
.to-yellow-500 {
--tw-gradient-to: #eab308 var(--tw-gradient-to-position);
}
.to-70\% {
--tw-gradient-to-position: 70%;
}
.bg-clip-text {
-webkit-background-clip: text;
background-clip: text;
}
.bg-center {
background-position: center;
}
.bg-no-repeat {
background-repeat: no-repeat;
}
.object-cover {
-o-object-fit: cover;
object-fit: cover;
}
.object-left {
-o-object-position: left;
object-position: left;
}
.p-0 {
padding: 0px;
}
.p-0\.5 {
padding: 0.125rem;
}
.px-1 {
padding-left: 0.25rem;
padding-right: 0.25rem;
}
.px-12 {
padding-left: 3rem;
padding-right: 3rem;
}
.px-16 {
padding-left: 4rem;
padding-right: 4rem;
}
.px-2 {
padding-left: 0.5rem;
padding-right: 0.5rem;
}
.px-20 {
padding-left: 5rem;
padding-right: 5rem;
}
.px-4 {
padding-left: 1rem;
padding-right: 1rem;
}
.px-6 {
padding-left: 1.5rem;
padding-right: 1.5rem;
}
.px-8 {
padding-left: 2rem;
padding-right: 2rem;
}
.px-\[60px\] {
padding-left: 60px;
padding-right: 60px;
}
.py-1 {
padding-top: 0.25rem;
padding-bottom: 0.25rem;
}
.py-12 {
padding-top: 3rem;
padding-bottom: 3rem;
}
.py-2 {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
}
.py-3 {
padding-top: 0.75rem;
padding-bottom: 0.75rem;
}
.py-4 {
padding-top: 1rem;
padding-bottom: 1rem;
}
.pb-36 {
padding-bottom: 9rem;
}
.pb-6 {
padding-bottom: 1.5rem;
}
.pl-24 {
padding-left: 6rem;
}
.pt-16 {
padding-top: 4rem;
}
.pt-8 {
padding-top: 2rem;
}
.text-center {
text-align: center;
}
.text-2xl {
font-size: 1.5rem;
line-height: 2rem;
}
.text-3xl {
font-size: 1.875rem;
line-height: 2.25rem;
}
.text-4xl {
font-size: 2.25rem;
line-height: 2.5rem;
}
.text-lg {
font-size: 1.125rem;
line-height: 1.75rem;
}
.text-sm {
font-size: 0.875rem;
line-height: 1.25rem;
}
.text-xl {
font-size: 1.25rem;
line-height: 1.75rem;
}
.text-xs {
font-size: 0.75rem;
line-height: 1rem;
}
.font-semibold {
font-weight: 600;
}
.tracking-wider {
letter-spacing: 0.05em;
}
.text-slate-400 {
--tw-text-opacity: 1;
color: rgb(148 163 184 / var(--tw-text-opacity));
}
.text-slate-500 {
--tw-text-opacity: 1;
color: rgb(100 116 139 / var(--tw-text-opacity));
}
.text-transparent {
color: transparent;
}
.text-violet-300 {
--tw-text-opacity: 1;
color: rgb(196 181 253 / var(--tw-text-opacity));
}
.text-white {
--tw-text-opacity: 1;
color: rgb(255 255 255 / var(--tw-text-opacity));
}
.placeholder-white::-moz-placeholder {
--tw-placeholder-opacity: 1;
color: rgb(255 255 255 / var(--tw-placeholder-opacity));
}
.placeholder-white::placeholder {
--tw-placeholder-opacity: 1;
color: rgb(255 255 255 / var(--tw-placeholder-opacity));
}
.opacity-100 {
opacity: 1;
}
.opacity-40 {
opacity: 0.4;
}
.opacity-80 {
opacity: 0.8;
}
.mix-blend-color-dodge {
mix-blend-mode: color-dodge;
}
.shadow-lg {
--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
.shadow-xl {
--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
.outline-none {
outline: 2px solid transparent;
outline-offset: 2px;
}
.blur-2xl {
--tw-blur: blur(40px);
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
}
.blur-xl {
--tw-blur: blur(24px);
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
}
.transition-all {
transition-property: all;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.hover\:bg-blue-700:hover {
--tw-bg-opacity: 1;
background-color: rgb(29 78 216 / var(--tw-bg-opacity));
}
.hover\:bg-green-900:hover {
--tw-bg-opacity: 1;
background-color: rgb(20 83 45 / var(--tw-bg-opacity));
}
.hover\:bg-pink-500:hover {
--tw-bg-opacity: 1;
background-color: rgb(236 72 153 / var(--tw-bg-opacity));
}
.hover\:bg-red-700:hover {
--tw-bg-opacity: 1;
background-color: rgb(185 28 28 / var(--tw-bg-opacity));
}
.hover\:text-pink-700:hover {
--tw-text-opacity: 1;
color: rgb(190 24 93 / var(--tw-text-opacity));
}
.hover\:outline-pink-400:hover {
outline-color: #f472b6;
}
@media (min-width: 768px) {
.md\:mx-16 {
margin-left: 4rem;
margin-right: 4rem;
}
.md\:mt-12 {
margin-top: 3rem;
}
.md\:h-16 {
height: 4rem;
}
.md\:h-\[105vh\] {
height: 105vh;
}
.md\:h-\[100vh\] {
height: 100vh;
}
.md\:w-16 {
width: 4rem;
}
.md\:w-\[100\%\] {
width: 100%;
}
.md\:w-\[12\%\] {
width: 12%;
}
.md\:flex-row {
flex-direction: row;
}
.md\:flex-col {
flex-direction: column;
}
.md\:justify-around {
justify-content: space-around;
}
.md\:text-3xl {
font-size: 1.875rem;
line-height: 2.25rem;
}
.md\:text-5xl {
font-size: 3rem;
line-height: 1;
}
.md\:text-xl {
font-size: 1.25rem;
line-height: 1.75rem;
}
}
@media (min-width: 1024px) {
.lg\:text-7xl {
font-size: 4.5rem;
line-height: 1;
}
}
|
在LR字符串中交换相邻字符
在一个由 'L' , 'R' 和 'X' 三个字符组成的字符串(例如"RXXLRXRXL")中进行移动操作。一次移动操作指用一个"LX"替换一个"XL",或者用一个"XR"替换一个"RX"。现给定起始字符串start和结束字符串end,请编写代码,当且仅当存在一系列移动操作使得start可以转换成end时, 返回True。
示例 :
输入: start = "RXXLRXRXL", end = "XRLXXRRLX"
输出: True
解释:
我们可以通过以下几步将start转换成end:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
class Solution(object):
def canTransform(self, start, end):
"""
:type start: str
:type end: str
:rtype: bool
"""
'''
思路:题目说了可以把初始字符串中的XL换成LX,可以把初始字符串中的RX换成XR,那么也就是说初始字符串中的L只能向左移动,初始字符串中R只能向右移动。并且L和R是不可能交换顺序的,两个字符串的L和R对应次数应该相等。
'''
i, j = 0, 0
N = len(start)
while i < N and j < N:
while i < N - 1 and start[i] == 'X':
i += 1
while j < N - 1 and end[j] == 'X':
j += 1
if start[i] != end[j]:
return False
if start[i] == 'L' and i < j:
return False
if start[i] == 'R' and i > j:
return False
i += 1
j += 1
return True
|
package org.creditcard.parsingwritingfiles.writing;
import org.creditcard.models.OutPutCard;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
public class XMLWritingStrategy implements WritingStrategy{
@Override
public void writeCards(OutputStream output, List<OutPutCard> cards) throws IOException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(OutPutCardsWrapper.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
OutPutCardsWrapper wrapper = new OutPutCardsWrapper();
wrapper.setCards(cards);
marshaller.marshal(wrapper, output);
} catch (Exception e) {
throw new IOException("Error writing XML", e);
}
}
@XmlRootElement(name = "cards")
@XmlAccessorType(XmlAccessType.FIELD)
public static class OutPutCardsWrapper {
private List<OutPutCard> cards;
// Getter
public List<OutPutCard> getCards() {
return cards;
}
// Setter
public void setCards(List<OutPutCard> cards) {
this.cards = cards;
}
}
}
|
<refentry id="ziw">
<indexterm id="IndexZiw"><primary>ziw</primary></indexterm>
<refentryinfo><title>Zak Patch System</title></refentryinfo>
<refmeta>
<refentrytitle>ziw</refentrytitle>
</refmeta>
<refnamediv>
<refname>ziw</refname>
<refpurpose>
Writes to a zk variable at i-rate without mixing.
</refpurpose>
</refnamediv>
<refsect1>
<title>Description</title>
<para>
Writes to a zk variable at i-rate without mixing.
</para>
</refsect1>
<refsect1>
<title>Syntax</title>
<synopsis><command>ziw</command> isig, indx</synopsis>
</refsect1>
<refsect1>
<title>Initialization</title>
<para>
<emphasis>isig</emphasis> -- initializes the value of the zk location.
</para>
<para>
<emphasis>indx</emphasis> -- points to the zk location to which to write.
</para>
</refsect1>
<refsect1>
<title>Performance</title>
<para>
<emphasis>ziw</emphasis> writes <emphasis>isig</emphasis> into the zk variable specified by <emphasis>indx</emphasis>.
</para>
<para>
These opcodes are fast, and always check that the index is within the range of zk or za space. If not, an error is reported, 0 is returned, and no writing takes place.
</para>
</refsect1>
<refsect1>
<title>Examples</title>
<para>
Here is an example of the ziw opcode. It uses the file <ulink url="examples/ziw.csd"><citetitle>ziw.csd</citetitle></ulink>.
<example>
<title>Example of the ziw opcode.</title>
<para>See the sections <link linkend="UsingRealTime"><citetitle>Real-time Audio</citetitle></link> and <link linkend="CommandFlags"><citetitle>Command Line Flags</citetitle></link> for more information on using command line flags.</para>
<xi:include href="examples-xml/ziw.csd.xml" xmlns:xi="http://www.w3.org/2001/XInclude"/>
</example>
</para>
</refsect1>
<refsect1>
<title>See Also</title>
<para>
<link linkend="zaw"><citetitle>zaw</citetitle></link>,
<link linkend="zawm"><citetitle>zawm</citetitle></link>,
<link linkend="ziwm"><citetitle>ziwm</citetitle></link>,
<link linkend="zkw"><citetitle>zkw</citetitle></link>,
<link linkend="zkwm"><citetitle>zkwm</citetitle></link>
</para>
</refsect1>
<refsect1>
<title>Credits</title>
<para>
<simplelist>
<member>Author: Robin Whittle</member>
<member>Australia</member>
<member>May 1997</member>
</simplelist>
</para>
<para>New in version 3.45</para>
<para>Example written by &namekevin;.</para>
</refsect1>
</refentry>
|
import mimetypes
import numpy as np
import moviepy.editor as mp
import os
import speech_recognition as sr
import pickle
from keras.models import load_model
from keras.utils import pad_sequences
from .clear_text_data import prepare_data
def determine_media_type(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if mime_type.startswith('audio'):
return "audio"
elif mime_type.startswith('video'):
return "video"
else:
return "unknown"
def convert_sound_to_text(file_path):
try:
with mp.AudioFileClip(file_path) as audio_clip:
audio_duration = audio_clip.duration
if audio_duration > 60:
return False, ("Sound length longer than 1 minute will not be converted. You can use a maximum of 1 "
"minute of sound for text classification from sound.")
recognizer = sr.Recognizer()
with sr.AudioFile(file_path) as source:
audio = recognizer.record(source)
try:
text = recognizer.recognize_google(audio, language="tr-TR")
return True, text
except sr.UnknownValueError:
return False, "Failed to detect sound"
except sr.RequestError as e:
return False, f"Error: {e}"
except Exception as e:
return False, e
def convert_video_to_text(file_path):
try:
with mp.VideoFileClip(file_path) as video_clip:
if video_clip.duration > 60:
return False, ("Video length longer than 1 minute will not be converted. You can use a maximum of 1 "
"minute of video for text classification from video.")
audio_file_path = "temp_audio.wav"
audio_clip = video_clip.audio
audio_clip.write_audiofile(audio_file_path)
converted_text = convert_sound_to_text(audio_file_path)
os.remove(audio_file_path)
return converted_text
except Exception as e:
return False, e
def convert_media_to_text(file_path):
try:
media_type = determine_media_type(file_path)
if media_type in "audio":
return convert_sound_to_text(file_path)
elif media_type in "video":
return convert_video_to_text(file_path)
except Exception as e:
print(e)
def predict_text_class(text, model_name):
try:
classes = list(map(lambda x: x.strip(), open('text_classification/networks/label_dict.txt')))
model_path = "text_classification/networks/" + model_name + "/text_net_" + model_name + ".h5"
tokenizer_path = "text_classification/networks/" + model_name + "/tokenizer_" + model_name + ".pickle"
model = load_model(model_path)
with open(tokenizer_path, 'rb') as handle:
tokenizer = pickle.load(handle)
clean_text = prepare_data(text)
sequences = tokenizer.texts_to_sequences([clean_text])
padded = pad_sequences(sequences, maxlen=164)
predicted = model.predict(padded)
index = np.argmax(predicted, axis=1)
predicted_class = classes[index[0]]
return True, predicted_class
except Exception as e:
print(e)
return False, "An error occurred during the text classification process."
|
/*
* File: CPInfo.h
* Author: Benjamin J. Land
*
* Created on November 25, 2008, 7:37 PM
*/
#ifndef _CPINFO_H
#define _CPINFO_H
#include <string>
class FieldInfo;
class MethodInfo;
class ClassFile;
class CPInfo {
public:
const static char CONSTANT_Class = 7;
const static char CONSTANT_Fieldref = 9;
const static char CONSTANT_Methodref = 10;
const static char CONSTANT_InterfaceMethodref = 11;
const static char CONSTANT_String = 8;
const static char CONSTANT_Integer = 3;
const static char CONSTANT_Float = 4;
const static char CONSTANT_Long = 5;
const static char CONSTANT_Double = 6;
const static char CONSTANT_NameAndType = 12;
const static char CONSTANT_Utf8 = 1;
char type;
static CPInfo* read(unsigned char *data, int &index);
virtual ~CPInfo() { };
protected:
CPInfo(char type);
};
class UTF8Info : public CPInfo {
public:
short int size;
char *bytes;
UTF8Info(unsigned char *data, int &index);
virtual ~UTF8Info();
};
class StringInfo : public CPInfo {
public:
short int stringIndex;
StringInfo(unsigned char *data, int &index);
};
class NameAndTypeInfo : public CPInfo {
public:
short int nameIndex;
short int descriptorIndex;
NameAndTypeInfo(unsigned char *data, int &index);
};
class LongDoubleInfo : public CPInfo {
public:
char data[8];
LongDoubleInfo(unsigned char *data, int &index);
};
class IntegerFloatInfo : public CPInfo {
public:
char data[4];
IntegerFloatInfo(unsigned char *data, int &index);
};
class FieldMethodInfo : public CPInfo {
public:
short int classIndex;
short int nameAndTypeIndex;
FieldInfo* fieldRef;
MethodInfo* methodRef;
std::string name;
FieldMethodInfo(unsigned char *data, int &index);
};
class ClassInfo : public CPInfo {
public:
short int nameIndex;
ClassFile *classRef;
std::string name;
ClassInfo(unsigned char *data, int &index);
};
#endif /* _CPINFO_H */
|
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { AiOutlineSearch, AiOutlineMenu } from 'react-icons/ai';
import { BiVideoPlus } from 'react-icons/bi';
import { FaRegBell } from 'react-icons/fa';
import { toggleMenu } from '../utils/navSlice';
import { cacheResults } from '../utils/searchSlice';
import logo from '../assets/yt-logo.png';
import SearchBar from './SearchBar';
import './Header.css';
import { YOUTUBE_SEARCH_API } from '../utils/constants';
const Header = () => {
const [showSearchBar, setShowSearchBar] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [searchSuggestions, setSearchSuggestions] = useState([]);
const searchCacheResults = useSelector((store) => store.search);
const dispatch = useDispatch();
useEffect(() => {
const timer = setTimeout(() => {
if (searchCacheResults[searchQuery]) {
setSearchSuggestions(searchCacheResults[searchQuery]);
} else {
getSearchSuggestions();
}
}, 200);
return () => {
clearTimeout(timer);
};
}, [searchQuery]);
const toggleMenuHandler = () => {
dispatch(toggleMenu());
};
const getSearchSuggestions = async () => {
fetch(YOUTUBE_SEARCH_API + searchQuery)
.then((res) => res.json())
.then((res) => {
setSearchSuggestions(res[1]);
if (searchQuery) dispatch(cacheResults({ [searchQuery]: res[1] }));
})
.catch((error) => console.log(error));
};
return (
<>
{!showSearchBar && (
<div className="flex md:grid-flow-col md:grid justify-between items-center border-b-2 shadow-sm md:shadow-none md:border-none">
<div className="flex items-center md:col-span-3">
<button onClick={toggleMenuHandler}>
<AiOutlineMenu className="hidden md:block mx-4 text-xl cursor-pointer" />
</button>
<Link to={'/'} className="flex items-center">
<img
className=" w-32 cursor-pointer"
src={logo}
alt="Youtube Logo"
/>
</Link>
</div>
<div className="hidden md:block col-span-8">
<SearchBar
showSearchBar={showSearchBar}
setShowSearchBar={setShowSearchBar}
setSearchQuery={setSearchQuery}
searchSuggestions={searchSuggestions}
/>
</div>
<Link to="/login" style={{ textDecoration: 'none' }}>
<div className="nav__item">
<span className="nav__itemLineOne">Hello Guest</span>
<span className="nav__itemLineTwo">Sign In</span>
</div>
</Link>
<div className="mr-2 p-2 w-10 hover:bg-yt-light-black rounded-full cursor-pointer">
<BiVideoPlus size={25} className="text-yt-white text-center" />
</div>
<div className="mx-3 p-2 w-10 hover:bg-yt-light-black rounded-full cursor-pointer">
<FaRegBell size={20} className="text-center text-yt-white" />
</div>
<div className="flex space-x-2 mr-2 md:mr-4 text-xl md:col-span-1">
<AiOutlineSearch
className="md:hidden"
onClick={() => setShowSearchBar(!showSearchBar)}
/>
</div>
</div>
)}
{showSearchBar && (
<SearchBar
showSearchBar={showSearchBar}
setShowSearchBar={setShowSearchBar}
setSearchQuery={setSearchQuery}
searchSuggestions={searchSuggestions}
/>
)}
</>
);
};
export default Header;
|
tags: words-pets5
title: indifferent
type: application/x-tiddler
!!释义
:<div>
indifferent
英[ɪn'dɪf(ə)r(ə)nt]美[ɪn'dɪfrənt]
adj. 漠不关心的;无关紧要的;中性的,中立的
</div>
!!【柯林斯英汉双解大词典】
:<div>
indifferent /ɪnˈdɪfrənt/
1. ADJ If you accuse someone of being indifferent to something, you mean that they have a complete lack of interest in it. 漠不关心的
例: People have become indifferent to the suffering of others. 人们已经变得对别人的痛苦漠不关心。
2. indifferently ADV 漠不关心地 [ADV after v]
例: 'Not that it matters,' said Trujillo indifferently. “它倒不是那么重要”,特鲁希略漠然地说。
3. ADJ If you describe something or someone as indifferent , you mean that their standard or quality is not very good, and often quite bad. 平庸的
例: She had starred in several very indifferent movies. 她领衔主演过好几部非常平庸的电影。
4. indifferently ADV 平庸地 [ADV with v]
例: ...a shoddy piece of work, poorly written, indifferently performed. …一部粗制滥造的作品,写得差劲,演得也蹩脚。
</div>
!!【同近义词】
:<div>
adj. 漠不关心的;无关紧要的;中性的,中立的
neutral,insignificant
</div>
!!【词语辨析】
:<div>
----------------------------------------
↓ different, indifferent 的辨析 ↓
----------------------------------------
different >> 跟……不一样,同from搭配。如:This book is different from that one.(这本书跟那本不一样。)
indifferent >> 冷漠的,不关心的,同to搭配。如:He was indifferent to his personal appearance.(他从前不注意自己的外表。)
</div>
!!【双语例句】
:<div>
Is he actually so utterly indifferent for my life ?他对我的生命真的是这样完全漠不关心吗?
putclub.com If you are bright , then China is not in the dark ; but if you are indifferent , then China will be .如果你聪明 ,那么中国就不会陷入黑暗 ,但如果你漠不关心 ,那么中国就会变成那样”。
Although thoughts which flit through the mind may be good , bad, or indifferent -- mostly the latter -- the mind does not usually hold on to any one of them sufficiently long to learn its nature .虽然 ,在脑海中掠过的想法是好的或者是无关紧要的——大多数是后者 ——大脑往往不能对它们中的任何一个坚持足够长的时间去认识它的本质。
</div>
|
class PostsController < ApplicationController
before_action :find_post, only: [:show,:edit,:update,:destroy, :upvote, :downvote]
before_action :authenticate_user!, except: [:index, :show]
def index
@posts =Post.all.order('created_at DESC')
end
def show
@comments =Comment.where(post_id: @post)
@random_post = Post.where.not(id: @post).order("RANDOM()").first
end
def new
@post= current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def edit
end
def update
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to root_path
end
def upvote
@post.upvote_by current_user
redirect_to :back
end
def downvote
@post.downvote_by current_user
redirect_to :back
end
private
def find_post
@post =Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title,:link,:description,:image)
end
end
|
<section>
<div class="container card-container">
<div class="row justify-content-center">
<div class="col-lg-6 col-md-8 col-xl-4">
<div class="card">
<div class="card-header d-flex">
<h5>'Project Name' Chatbot</h5>
</div>
<div class="card-body">
<div *ngFor="let message of messageData">
<ng-template [ngIf]="message.isChatbot" [ngIfElse]="botUser">
<div class="d-flex justify-content-between">
<p class="chat-details">{{chatbotName}}</p>
<p class="chat-details">{{message.dateTime | date:"dd MMM yy HH:mm:ss"}}</p>
</div>
<div class="d-flex flex-row justify-content-start">
<img src="../../../assets/bot.jpg" [alt]="chatbotName"
style="width: 45px; height: 100%;">
<div>
<p class="bot-message">{{message.message}}</p>
</div>
</div>
<div class="user-message-option">
<div *ngFor="let userMsg of message.options">
<button (click)="userOptionButtonClick(message,userMsg)" type="button"
class="btn btn-outline-primary">{{userMsg.message}}</button>
</div>
</div>
</ng-template>
<ng-template #botUser>
<div class="d-flex justify-content-between">
<p class="chat-details">{{message.dateTime| date:"dd MMM yy HH:mm:ss"}}</p>
<p class="chat-details">You</p>
</div>
<div class="d-flex flex-row justify-content-end">
<div>
<p class="user-message">{{message.message}}</p>
</div>
<img src="../../../assets/user.png" [alt]="chatbotName"
style="width: 45px; height: 100%;">
</div>
</ng-template>
</div>
</div>
<div class="card-footer d-flex justify-content-start align-items-center">
<div class="input-control" *ngIf="showTextBox">
<input name="emailId" type="text" class="form-control" placeholder="Enter email Id" [(ngModel)]="emailId"/>
<button class="btn btn-outline-primary" type="button" (click)="emailClick()">
<img src="../../../assets/sendIcon.png" style="height: 25px">
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
|
import { readBlockHead, asyncIterableReader } from '@ipld/car/decoder'
import { base58btc } from 'multiformats/bases/base58'
import { GetObjectCommand } from '@aws-sdk/client-s3'
import defer from 'p-defer'
import retry from 'p-retry'
import { DynamoIndex } from './block-index.js'
import { OrderedCarBlockBatcher } from './block-batch.js'
/**
* A blockstore that is backed by a DynamoDB index and S3 buckets.
*/
export class DynamoBlockstore {
/**
* @param {import('@aws-sdk/client-dynamodb').DynamoDBClient} dynamoClient
* @param {string} dynamoTable
* @param {import('../bindings').RegionalS3Clients} s3Clients
* @param {object} [options]
* @param {string} [options.preferRegion] Preferred region to fetch data
* from, typically the same region as where the service is running.
*/
constructor (dynamoClient, dynamoTable, s3Clients, options) {
this._buckets = s3Clients
/** @type {import('./block-index').BlockIndex} */
this._idx = new DynamoIndex(dynamoClient, dynamoTable, options)
}
/** @param {import('multiformats').UnknownLink} cid */
async get (cid) {
// console.log(`get ${cid}`)
const idxEntries = await this._idx.get(cid)
if (!idxEntries.length) return
const { region, bucket, key, offset, length } = idxEntries[0]
const s3Client = this._buckets[region]
if (!s3Client) return
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
Range: `bytes=${offset}-${offset + length - 1}`
})
const res = await s3Client.send(command)
if (!res.Body) return
const bytes = await res.Body.transformToByteArray()
return { cid, bytes }
}
}
export class BatchingDynamoBlockstore extends DynamoBlockstore {
/** @type {Map<string, Array<import('p-defer').DeferredPromise<import('dagula').Block|undefined>>>} */
#pendingBlocks = new Map()
/** @type {import('./block-batch').BlockBatcher} */
#batcher = new OrderedCarBlockBatcher()
#scheduled = false
/** @type {Promise<void>|null} */
#processing = null
#scheduleBatchProcessing () {
if (this.#scheduled) return
this.#scheduled = true
const startProcessing = async () => {
this.#scheduled = false
const { promise, resolve } = defer()
this.#processing = promise
try {
await this.#processBatch()
} finally {
this.#processing = null
resolve()
}
}
// If already running, then start when finished
if (this.#processing) {
return this.#processing.then(startProcessing)
}
// If not running, then start on the next tick
setTimeout(startProcessing)
}
async #processBatch () {
console.log('processing batch')
const batcher = this.#batcher
this.#batcher = new OrderedCarBlockBatcher()
const pendingBlocks = this.#pendingBlocks
this.#pendingBlocks = new Map()
/**
* @param {import('multiformats').UnknownLink} cid
* @param {Uint8Array} bytes
*/
const resolvePendingBlock = (cid, bytes) => {
const key = mhToKey(cid.multihash.bytes)
const blocks = pendingBlocks.get(key)
if (!blocks) return
console.log(`got wanted block ${cid} (${pendingBlocks.size} remaining)`)
const block = { cid, bytes }
blocks.forEach(b => b.resolve(block))
pendingBlocks.delete(key)
}
while (true) {
const batch = batcher.next()
if (!batch.length) break
batch.sort((a, b) => a.offset - b.offset)
const { region, bucket, key } = batch[0]
const range = `bytes=${batch[0].offset}-${batch[batch.length - 1].offset + batch[batch.length - 1].length - 1}`
console.log(`fetching ${batch.length} blocks from s3://${region}/${bucket}/${key} (${range})`)
const s3Client = this._buckets[region]
if (!s3Client) {
console.warn(`missing S3 client for region: ${region}`)
break
}
const res = await retry(async () => {
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
Range: range
})
return await s3Client.send(command)
}, { minTimeout: 100, onFailedAttempt: err => console.warn(`failed S3 query for: s3://${region}/${bucket}/${key} (${range})`, err) })
if (!res.Body) break
const reader = res.Body.transformToWebStream().getReader()
const bytesReader = asyncIterableReader((async function * () {
while (true) {
const { done, value } = await reader.read()
if (done) return
yield value
}
})())
const bytes = await bytesReader.exactly(batch[0].length)
bytesReader.seek(batch[0].length)
resolvePendingBlock(batch[0].cid, bytes)
while (true) {
try {
const blockHeader = await readBlockHead(bytesReader)
const bytes = await bytesReader.exactly(blockHeader.blockLength)
bytesReader.seek(blockHeader.blockLength)
resolvePendingBlock(blockHeader.cid, bytes)
// remove from batcher if queued to be read
batcher.remove(blockHeader.cid)
} catch {
break
}
}
// we should have read all the bytes from the reader by now but if the
// bytesReader throws for bad data _before_ the end then we need to
// cancel the reader - we don't need the rest.
reader.cancel()
}
// resolve `undefined` for any remaining blocks
for (const blocks of pendingBlocks.values()) {
blocks.forEach(b => b.resolve())
}
}
/** @param {import('multiformats').UnknownLink} cid */
async get (cid) {
// console.log(`get ${cid}`)
const idxEntries = await this._idx.get(cid)
if (!idxEntries.length) return
this.#batcher.add(cid, idxEntries)
const key = mhToKey(cid.multihash.bytes)
let blocks = this.#pendingBlocks.get(key)
if (!blocks) {
blocks = []
this.#pendingBlocks.set(key, blocks)
}
const deferred = defer()
blocks.push(deferred)
this.#scheduleBatchProcessing()
return deferred.promise
}
}
const mhToKey = (/** @type {Uint8Array} */ mh) => base58btc.encode(mh)
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:insert="fragments.html :: headerfiles"></head>
<body>
<header class="header dark-bg" th:insert="fragments.html :: header-part"></header>
<!--header end-->
<!--sidebar start-->
<aside th:insert="fragments.html :: aside-part"></aside>
<!--sidebar end-->
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-table"></i> Location</h3>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i><a href="/">Home</a></li>
<li><i class="fa fa-table"></i>Table</li>
<li><i class="fa fa-th-list"></i>Basic Table</li>
</ol>
</div>
</div>
<!-- page start-->
<h2 align="center"><strong>List of Locations</strong></h2>
<div class="container">
<div>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addModal">Add New
</button>
</div>
<table class="table table-striped">
<thead>
<tr>
<th><i class="icon_table"></i>Id</th>
<th><i class="icon_table"></i>Description</th>
<th><i class="icon_table"></i>Details</th>
<th><i class="icon_table"></i>City</th>
<th><i class="icon_table"></i>Address</th>
<th><i class="icon_cogs"></i>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="location : ${listOfLocations}">
<td th:text="${location.id}"></td>
<td th:text="${location.description}"></td>
<td th:text="${location.details}"></td>
<td th:text="${location.city}"></td>
<td th:text="${location.address}"></td>
<td>
<div class="btn-group">
<a class="btn btn-warning editButton" th:href="@{/oneLocation/(id=${location.id})}"><i
class="icon_pencil-edit"></i></a>
<a class="btn btn-danger deleteButton" th:href="@{/deleteLocation/(id=${location.id})}"><i
class="icon_close_alt2"></i></a>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel"
aria-hidden="true">
<form th:action="@{/addNewLocation}" method="post">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="addModalLabel"><strong>Add New Location</strong></h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><strong>× </strong></span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="descriptionAdd" class="col-form-label">Description:</label>
<input type="text" class="form-control" id="descriptionAdd" name="description" required>
</div>
<div class="form-group">
<label for="detailsAdd" class="col-form-label">Details:</label>
<input type="text" class="form-control" id="detailsAdd" name="details" required>
</div>
<div class="form-group">
<label for="cityAdd" class="col-form-label">City:</label>
<input type="text" class="form-control" id="cityAdd" name="city" required>
</div>
<div class="form-group">
<label for="ddlCountryAdd" class="col-form-label">Country: </label>
<select class="form-control" id="ddlCountryAdd" name="countryid" required>
<option>-SELECT-</option>
<option th:each="country : ${listOfCountries}"
th:value="${country.id}"
th:text="${country.description}">
</option>
</select>
</div>
<div class="form-group">
<label for="addressAdd" class="col-form-label">Address:</label>
<input type="text" class="form-control" id="addressAdd" name="address" required>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</form>
</div>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel"
aria-hidden="true">
<form th:action="@{/editLocation}" method="post">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="editModalLabel"><strong>Update Location</strong></h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><strong>×</strong></span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="idEdit" class="col-form-label">Id:</label>
<input type="text" class="form-control" id="idEdit" name="id" readonly>
</div>
<div class="form-group">
<label for="descriptionEdit" class="col-form-label">Description:</label>
<input type="text" class="form-control" id="descriptionEdit" name="description"
required>
</div>
<div class="form-group">
<label for="detailsEdit" class="col-form-label">Details:</label>
<input type="text" class="form-control" id="detailsEdit" name="details" required>
</div>
<div class="form-group">
<label for="cityEdit" class="col-form-label">City:</label>
<input type="text" class="form-control" id="cityEdit" name="city" required>
</div>
<div class="form-group">
<label for="ddlCountryEdit" class="col-form-label">Country: </label>
<select class="form-control" id="ddlCountryEdit" name="countryid" required>
<option>-SELECT-</option>
<option th:each="country : ${listOfCountries}"
th:value="${country.id}"
th:text="${country.description}">
</option>
</select>
</div>
<div class="form-group">
<label for="addressEdit" class="col-form-label">Address:</label>
<input type="text" class="form-control" id="addressEdit" name="address" required>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</form>
</div>
<div class="modal fade" tabindex="-1" role="dialog" id="deleteModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title"><strong>Confirm delete</strong></h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><strong>× </strong></span>
</button>
</div>
<div class="modal-body">
<p><strong>Are you sure you want to delete this record?</strong></p>
</div>
<div class="modal-footer">
<a href="" class="btn btn-danger" id="deleteId">Yes, delete</a>
<button type="submit" class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<div class="text-right">
<div class="credits">
<!--
All the links in the footer should remain intact.
You can delete the links only if you purchased the pro version.
Licensing information: https://bootstrapmade.com/license/
Purchase the pro version form: https://bootstrapmade.com/buy/?theme=NiceAdmin
-->
<p align="center">© 2020 <a href="">FleetMS.com</a></p>
</div>
</div>
</section>
<!-- container section end -->
<!-- javascripts -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="js/jquery.scrollTo.min.js"></script>
<script src="js/jquery.nicescroll.js" type="text/javascript"></script>
<!--custome script for all page-->
<script src="js/scripts.js"></script>
<script src="js/location.js"></script>
</body>
</html>
|
from collections import OrderedDict, namedtuple
import cv2
from pathlib import Path
import re
import torch
import numpy as np
import pickle
from scipy.io import loadmat
from ai_util.dataset import batch_iter
from tqdm import tqdm
from torch.nn import functional as F
from ai_util.vision.image_gallery_reader import ImageGalleryReader
def euclidean_squared_distance(input1, input2):
"""Computes euclidean squared distance.
Args:
input1 (torch.Tensor): 2-D feature matrix.
input2 (torch.Tensor): 2-D feature matrix.
Returns:
torch.Tensor: distance matrix.
"""
input1 = torch.from_numpy(input1)
input2 = torch.from_numpy(input2)
m, n = input1.size(0), input2.size(0)
mat1 = torch.pow(input1, 2).sum(dim=1, keepdim=True).expand(m, n)
mat2 = torch.pow(input2, 2).sum(dim=1, keepdim=True).expand(n, m).t()
distmat = mat1 + mat2
distmat.addmm_(input1, input2.t(), beta=1, alpha=-2)
distmat = distmat.numpy()
return distmat
def cosine_distance(input1, input2):
# input1 = input1 / np.linalg.norm(input1, axis=1, keepdims=True)
# input2 = input2 / np.linalg.norm(input2, axis=1, keepdims=True)
prod = np.dot(input1, input2.T)
return 1 - prod
QueryResult = namedtuple("QueryResult", ("entry_idx", "data_key", "dist"))
class ImageGallery:
def __init__(self, data, data_extr=None, feat_extr=None, name=None, dist_metric=None, gallery_dir="galleries") -> None:
self.name = name
self.data = data
self.key_idx_map = None # one key has idx per box
self.keys = []
self.feats = None
self.boxes = [] # need to store boxes too, and asign a crop it to it
self.feat_extr = feat_extr
self.min_box_size = 5
self.dist_metric = dist_metric if dist_metric is not None else (feat_extr.dist_metric if feat_extr is not None else None)
self.is_loaded = False
self.key_freq = np.inf
self.gallery_dir = Path(gallery_dir)
self.gallery_dir.mkdir(parents=True, exist_ok=True)
if name is None or not self.load(nonexist_ok=True):
if data_extr is not None:
self._extract_data(data_extr)
if name is not None:
self.save()
def _build_key_idx_map(self):
self.key_idx_map = OrderedDict()
for idx, key in enumerate(self.keys):
if key not in self.key_idx_map:
self.key_idx_map[key] = []
self.key_idx_map[key].append(idx)
last_key = -np.inf
for key in self.key_idx_map:
self.key_freq = min(self.key_freq, key - last_key)
last_key = key
def save(self):
path = self.gallery_dir / f"{self.name}.npz"
out = {
"keys": np.array(self.keys),
"feats": self.feats,
"boxes": np.array(self.boxes)
}
np.savez(path, **out)
def load(self, nonexist_ok=False):
path = self.gallery_dir / f"{self.name}.npz"
if not path.is_file():
if nonexist_ok:
self.is_loaded = False
else:
raise FileNotFoundError
else:
data = np.load(path)
self.keys = [*data["keys"]]
self.feats = data["feats"]
self.boxes = [*data["boxes"]]
self.is_loaded = True
self._build_key_idx_map()
return self.is_loaded
def process_data_sample(self, sample):
raise NotImplementedError
def _iter_seq(self, seq):
for sample in seq:
for key, crop, box in self.process_data_sample(sample):
yield key, crop, box
def compute_distance_matrix(self, feats1, feats2):
if self.dist_metric == 'euclidean':
distmat = euclidean_squared_distance(feats1, feats2)
elif self.dist_metric == 'cosine':
distmat = cosine_distance(feats1, feats2)
return distmat
def __getitem__(self, idx):
return {
"key": self.keys[idx],
"box": self.boxes[idx],
"feat": self.feats[idx]
}
def retrieve_data(self, idx, **kwargs):
d = self.__getitem__(idx)
img = self.data.load_image_by_key(d["key"])
return {
**d,
"image": img
}
def query(self, query_feats, topk=5, return_distmat=False):
"""
data = batch_iter(query_data, self.feat_extr.batch_size)
query_feats = []
for batch in data:
out = self.feat_extr(batch)
query_feats += [*out]
"""
query_feats = np.stack(query_feats)
distmat = self.compute_distance_matrix(query_feats, self.feats)
indices = np.argsort(distmat, axis=1)
indices_topk = indices[:, :topk]
"""
keys = [[self.keys[i] for i in row] for row in indices_topk]
boxes = [[self.boxes[i] for i in row] for row in indices_topk]
dists = [distmat[i, idx] for i, idx in enumerate(indices_topk)]
"""
"""
out = [[{
**self.__getitem__(i),
"dist": distmat[row_idx, i],
}
for i in row] for row_idx, row in enumerate(indices_topk)]
"""
out = [[QueryResult(
entry_idx=i,
data_key=self.keys[i],
dist=distmat[row_idx, i],
)
for i in row] for row_idx, row in enumerate(indices_topk)]
if return_distmat:
return out, distmat
else:
return out
def add_data_from_galleries(self, gals):
for gal in gals:
self.keys += gal.key
self.boxes += gal.boxes
self.feats = np.concatenate(
[self.feats, gal.feats] if self.feats is not None else gal.feats,
0
)
self._build_key_idx_map()
def _extract_data(self, data_iterator):
seq = data_iterator(self.data)
data = batch_iter(self._iter_seq(seq), self.feat_extr.batch_size)
new_keys = []
new_boxes = []
new_feats = []
"""
for batch in data:
keys, crops, boxes = zip(*batch)
feats = self.feat_extr(crops)
new_keys += keys
new_boxes += boxes
new_feats += [f[None] for f in feats] # unwrap batch
"""
def _feat_input_iter():
for batch in data:
keys, crops, boxes = zip(*batch)
yield crops, (keys, boxes)
for feats, (keys, boxes) in tqdm(self.feat_extr.predict_all(_feat_input_iter()), desc="Creating gallery"):
new_keys += keys
new_boxes += boxes
new_feats += [f[None] for f in feats] # unwrap batch
self.keys += new_keys
self.boxes += new_boxes
self.feats = np.concatenate(
[self.feats, *new_feats] if self.feats is not None else new_feats,
0
)
self._build_key_idx_map()
return self
def create_reader(self, *args, **kwargs):
return ImageGalleryReader(self, *args, **kwargs)
class PRWDataset:
def __init__(self, root_dir) -> None:
self.root_dir = Path(root_dir)
img_dir = self.root_dir / "frames"
self.label_cache_file = self.root_dir / "label_cache.pkl"
img_files = sorted(img_dir.glob("*.jpg"))
self.cam_seq_img_files = [[]]
reg = re.compile("c(\d+)s(\d+)_(\d+)")
for img_file in img_files:
res = reg.match(img_file.stem)
cam_idx, seq_idx, frame_id = int(res.group(1)) - 1, int(res.group(2)) - 1, int(res.group(3))
while len(self.cam_seq_img_files) <= cam_idx:
self.cam_seq_img_files.append([])
while len(self.cam_seq_img_files[cam_idx]) <= seq_idx:
self.cam_seq_img_files[cam_idx].append([])
self.cam_seq_img_files[cam_idx][seq_idx].append({
"frame_id": frame_id,
"img_file": img_file
})
if not self.label_cache_file.exists():
cam_seq_annot = [[[
self.read_annot(img_file["img_file"]) for img_file in img_files]
for img_files in seq_img_files]
for seq_img_files in self.cam_seq_img_files]
with open(self.label_cache_file, "wb") as f:
pickle.dump(cam_seq_annot, f)
with open(self.label_cache_file, "rb") as f:
self.cam_seq_annot = pickle.load(f)
self.query_imgs = self._load_query_imgs()
def _load_query_imgs(self):
query_imgs = []
reg = re.compile("(\d+)_c(\d+)s(\d+)_(\d+)")
query_img_files = sorted((self.root_dir / "query_box").glob("*.jpg"))
for img_file in query_img_files:
res = reg.match(img_file.stem)
track_id, cam_idx, seq_idx, frame_id = int(res.group(1)), int(res.group(2)) - 1, int(res.group(3)) - 1, int(res.group(4))
query_imgs.append({
"img_file": img_file,
"track_id": track_id,
"cam_idx": cam_idx,
"seq_idx": seq_idx,
"frame_id": frame_id,
})
return query_imgs
def read_annot(self, img_path):
annot_file = str(img_path.with_suffix(".jpg.mat"))
annot_file = annot_file.replace("/frames/", "/annotations/")
data = loadmat(annot_file)
box_annot = None
for key in ("box_new", "anno_file", "anno_previous"):
if key in data:
box_annot = data[key]
break
assert box_annot is not None and box_annot.ndim == 2 and box_annot.shape[1] == 5
boxes_ids = box_annot[:, [1, 2, 3, 4, 0]].astype(np.float32) # push id back
# boxes_ids[:, 0:2] = boxes_ids[:, 0:2]
boxes_ids[:, 2:4] = boxes_ids[:, 0:2] + boxes_ids[:, 2:4]
return boxes_ids
def _load_img(self, path):
return cv2.cvtColor(cv2.imread(str(path)), cv2.COLOR_BGR2RGB)
def get_frame_by_key(self, key):
return self.get_frame(*key)
def get_frame(self, cam_idx, seq_idx, frame_idx):
d = self.cam_seq_img_files[cam_idx][seq_idx][frame_idx]
img_file = d["img_file"]
frame_id = d["frame_id"]
img = self._load_img(img_file)
box = self.cam_seq_annot[cam_idx][seq_idx][frame_idx]
return {
"key": (cam_idx, seq_idx, frame_idx),
"image": img,
"box": box
}
def get_query_image(self, idx):
d = self.query_imgs[idx]
img = self._load_img(d["img_file"])
info_keys = ["track_id", "cam_idx", "seq_idx", "frame_id"]
return {
"image": img,
**{k: d[k] for k in info_keys}
}
def get_cam_seq_indices(self):
return [(c, s) for c in range(len(self.cam_seq_img_files)) for s in range(len(self.cam_seq_img_files[c]))]
def iter_frames(self, cam_idx, seq_idx):
for i in range(len(self.cam_seq_img_files[cam_idx][seq_idx])):
yield self.get_frame(cam_idx, seq_idx, i)
def draw_boxes(img, boxes):
color = (255, 0, 0)
for x1, y1, x2, y2 in boxes[:, :4].astype(int):
cv2.rectangle(img, (x1, y1), (x2, y2), color=color, thickness=1)
def draw_box(img, box, label):
tl = 3
tf = 1
color = (255, 0, 0)
x1, y1, x2, y2 = box[:4].astype(int)
cv2.rectangle(img, (x1, y1), (x2, y2), color=color, thickness=1)
cv2.putText(img,
label, (10, 30),
0,
tl / 3, [225, 0, 0],
thickness=tf,
lineType=cv2.LINE_AA)
return img
|
{% extends "base.html" %}
{% load i18n %}
{% load mezzanine_tags keyword_tags %}
{% block meta_title %}{{ page.meta_title }}{% endblock %}
{% block meta_keywords %}{% metablock %}
{% keywords_for page as keywords %}
{% for keyword in keywords %}
{% if not forloop.first %}, {% endif %}
{{ keyword }}
{% endfor %}
{% endmetablock %}{% endblock %}
{% block meta_description %}{% metablock %}
{{ page.description }}
{% endmetablock %}{% endblock %}
{% block title %}
{% trans "tracker"|title %} {{ horsetracker }}
{% endblock %}
{% block extra_js %}
<script>
var map, heatmap;
var coldColor = [25,159,105,1]
var midColor = [255,193,107,1]
var hotColor = [233, 95, 37,0.8]
diffColor2 = [hotColor[0]-midColor[0],
hotColor[1]-midColor[1],
hotColor[2]-midColor[2],
hotColor[3]-midColor[3]];
diffColor1 = [midColor[0]-coldColor[0],
midColor[1]-coldColor[1],
midColor[2]-coldColor[2],
midColor[3]-coldColor[3]];
var gradient1HM = [];
var gradient1MC = [];
var step = 28;
for(i=0;i<step;i++){
red1 = parseInt(coldColor[0]+diffColor1[0]/step/step*i*i);
green1 = parseInt(coldColor[1]+diffColor1[1]/step/step*i*i);
blue1 = parseInt(coldColor[2]+diffColor1[2]/step/step*i*i);
if( i==9 || i==10 )
alpha1 = 1;//coldColor[3]+diffColor1[3]/step/step/step*i*i*i;
else if( i<9)
alpha1 = 0;
else
alpha1 = 0.3;
gradient1HM.push( "rgba("+red1+","+green1+","+blue1+","+alpha1+")" );
red2 = parseInt(midColor[0]+diffColor2[0]/step/step*i*i);
green2 = parseInt(midColor[1]+diffColor2[1]/step/step*i*i);
blue2 = parseInt(midColor[2]+diffColor2[2]/step/step*i*i);
if(
i==24 || i==25 || i==26 || i==27 )
alpha2 = midColor[3]+diffColor2[3]/step/step/step*i*i*i;
else
alpha2 = 0.3;
gradient1MC.push( "rgba("+red2+","+green2+","+blue2+","+alpha2+")" );
}
var gradient1 = gradient1HM.concat(gradient1MC);
var gradient3 = [
'rgba(0, 168, 255, 0)',
'rgba(10, 160, 240, 0.2)',
'rgba(30, 150, 230, 0.5)',
'rgba(50, 138, 220, 0.7)',
'rgba(70, 125, 210, 0.8)',
'rgba(90, 110, 203, 0.9)',
'rgba(110, 90, 194, 0.95)',
'rgba(130, 74, 187, 1)',
'rgba(150, 65, 178, 1)',
'rgba(170, 50, 172, 1)',
'rgba(190, 40, 165, 1)',
'rgba(210, 20, 157, 1)',
'rgba(230, 10, 150, 1)',
'rgba(255, 0 ,144, 1)'];
var gradient2 = [
'rgba(0, 255, 255, 0)',
'rgba(0, 255, 255, 1)',
'rgba(0, 191, 255, 1)',
'rgba(0, 127, 255, 1)',
'rgba(0, 63, 255, 1)',
'rgba(0, 0, 255, 1)',
'rgba(0, 0, 223, 1)',
'rgba(0, 0, 191, 1)',
'rgba(0, 0, 159, 1)',
'rgba(0, 0, 127, 1)',
'rgba(63, 0, 91, 1)',
'rgba(127, 0, 63, 1)',
'rgba(191, 0, 31, 1)',
'rgba(255, 0, 0, 1)'
];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: {lat: {{points.0.latitude}}, lng: {{points.0.longitude}}},
mapTypeId: google.maps.MapTypeId.SATELLITE,
zoomControl:true,
//zoomControlOptions: {
// style:google.maps.ZoomControlStyle.DEFAULT
//},
mapTypeControl:true,
//mapTypeControlOptions: {
//style:google.maps.MapTypeControlStyle.HORIZONTAL_BAR
//},
scaleControl:true,
//streetViewControl:false,
//rotateControl:false,
disableDefaultUI: true
});
heatmap = new google.maps.visualization.HeatmapLayer({
data: getPoints(),
map: map
});
heatmap.set('radius', {{mapConfigure.mapRadius}});
heatmap.set('opacity', 0.95);
heatmap.set('maxIntensity', 30);
heatmap.set('dissipating',false);
heatmap.set('gradient', gradient1);
}
function toggleHeatmap() {
heatmap.setMap(heatmap.getMap() ? null : map);
}
var gradientMode=false;
var radiusMode=false;
var opacityMode=false;
function changeGradient() {
if(gradientMode){
gradientMode = false;
heatmap.set('gradient', gradient1);
}
else{
gradientMode = true;
heatmap.set('gradient', gradient2);
}
}
function changeRadius() {
if(radiusMode){
radiusMode=false;
heatmap.set('radius', {{mapConfigure.mapRadius}});
}
else{
radiusMode=true;
heatmap.set('radius', 5e-5);
}
}
function changeOpacity() {
//heatmap.set('opacity', heatmap.get('opacity') ? null : 0.6);
if(opacityMode){
opacityMode=false;
heatmap.set('opacity', 0.85);
}
else{
opacityMode=true;
heatmap.set('opacity', 0.60);
}
}
// Heatmap
function getPoints() {
return [
{% for point in points|slice:"1:" %}
{location: new google.maps.LatLng({{point.latitude}}, {{point.longitude}}), weight:{{point.value2}}},{% endfor %}
];
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2zwNbTK2o6KpwKSp0aTsGpNNoGm4s3HI&libraries=visualization&callback=initMap">
</script>
{% endblock %}
{% block main %}
<div class="row">
<div class="col-md-9 left">
<div class="panel panel-default">
<div class="panel-body">
<H2>{% trans "temperature map"|title %}</H2>
<div class="google-map">
<div id="panel" class="btn-group btn-group-justified">
<a onclick="toggleHeatmap()" class="btn btn-default btn-xs">{% trans "heatmap"|title %}</a>
<a onclick="changeGradient()" class="btn btn-default btn-xs">{% trans "gradient"|title %}</a>
<a onclick="changeRadius()" class="btn btn-default btn-xs">{% trans "radius"|title %}</a>
<a onclick="changeOpacity()" class="btn btn-default btn-xs">{% trans "opacity"|title %}</a>
</div>
<div id="map"></div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
|
import 'dart:convert';
import 'package:chat_app_with_myysql/model/group_chat_users_model.dart';
import 'package:chat_app_with_myysql/service/network.dart';
import 'package:chat_app_with_myysql/util/config.dart';
import 'package:http/http.dart' as http;
class GroupChatRepository {
Future<List<GroupChatUsersModel>> getApiGroups(
String token,
) async {
List<GroupChatUsersModel> groupsList=[];
const String url = AppConfig.DIRECTORY + "user/fetchGroupChat/";
print("getApiContacts url: $url");
await Network().get(url, headers: {
"Authorization": "Bearer ${token}",
'Content-type': 'application/json'
}, onSuccess: (val) {
print("getApiGroupUsers response: ${val}");
var map = jsonDecode(val);
for(int i =0;i<map.length;i++){
groupsList.add(GroupChatUsersModel.fromJson(map[i]));
}
},
onError: (e){
print('Failed to load data: ${e}');
}
);
return groupsList ??[];
}
Future<dynamic> createGroupApi(String groupName, List<String> usersList,String? imagePath, String token) async {
print(groupName);
print(usersList);
print(imagePath);
print("-----uploadFiles-------------");
var headers = {
'Authorization': 'Bearer $token',
//'Authorization': 'Bearer $header',
'Content-Type': 'multipart/form-data',
//'Cookie': 'connect.sid=s%3AUzoS90auAKH3VbpprDYfj-BBRlL2j8D7.dVGHiwnEzlku21Y0u5rWI7ocb1UcdekdSxaQ2w04Lpk'
};
var request = http.MultipartRequest(
'POST', Uri.parse('https://xwavetechnologies.com/user/groupchat'));
request.fields.addAll(
{
'name': groupName ,
'users':json.encode(usersList)// usersList.join(','),
});
request.files.add(await http.MultipartFile.fromPath('media',
imagePath??"",
));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print("--------Group created Successfully-------1----");
dynamic data = jsonDecode(await response.stream.bytesToString());
// String responseBody = await utf8.decode(response.bodyBytes);
print("---------Group created Successfully-------2-----$data");
return GroupChatUsersModel.fromJson(data) ;
}
else {
print(response.reasonPhrase);
print(response.statusCode);
print(await response.stream.bytesToString());
}
}
}
|
require 'executable'
require 'open-uri'
require 'icalendar'
require 'date'
class EventsAggregator
include Executable
# Set the output file name
def out=(name)
@outputFile = name
end
# Set the input file to read for URLs (one per line)
def file=(name)
file = File.open(name)
@urls = []
file.each do |line|
url = line.strip
if url.match /^http/
@urls << url
else
$stderr.puts "Warning: Ignoring invalid (non HTTP) URL: #{url}"
end
end
end
# Default the file to config/calendars.txt
def get_urls
self.file = 'config/calendars.txt' unless @urls
@urls
end
# Show this message
def help!
cli.show_help
exit
end
alias :h! :help!
#Write output
def write_calendar(cal)
unless @outputFile && !@outputFile.empty?
$stderr.puts "Warning: You should specify output file (see --help). Defaulting to ./out.ical"
@outputFile = './out.ical'
end
cal.x_wr_calname = 'SF Startup Events (by Amoeba Labs)'
cal.x_wr_caldesc = 'Startup Events in and around San Francisco, curated by Amoeba Labs http://amoe.ba'
File.open(@outputFile, 'w') {|f| f.write(cal.to_ical) }
end
# Aggregate the calendar URLs specified into one
def call
urls = get_urls
calendars = []
# Load calendars from all the URLs
urls.each do |url|
begin
data = URI.parse(url).read
rescue Exception => ex
$stderr.puts "Warning: Exception: #{ex.message}"
$stderr.puts "Warning: Skipping URL: #{url} (probably not found)"
end
next unless data
# Icalendar::parse(data) can return an array of calendars, so union them in to our existing set
begin
calendars = calendars | Icalendar::parse(data)
rescue Exception => ex
$stderr.puts "Warning: Exception: #{ex.message}"
$stderr.puts "Warning: Skipping calendars for URL: #{url} (usually contain invalid data)"
end
end
# Now iterate over the calendars and combine all their events in one new one
newCal = Icalendar::Calendar.new
calendars.each do |cal|
cal.events.each do |event|
newCal.add_component event
end
end
puts "Done! Merged in #{newCal.events.count} events."
write_calendar newCal
end
end
|
# The Commit Stage
The commit stage begins with a **change** to the state of the project.
It ends with either a report of **faiure** or, if successful, a collection of binary **artifacts** and deployable assemblies to be used in subsequent test and release stages, as well as **reports**.

<br>
## Commit Stage Principles and Practices
### _Provide Fast, Useful Feedback_
Errors are easiest to **fix** if detected **early**.
Modern CI servers also provide the function called **pretested commit**, that runs the commit stage before check-in.
A common **mistake** is to take the doctrine of **"fail fast"** a little too literally and fail the build immediately when an error is found. This is optimized **too far**. We only stop the commit stage if an error prevents the rest of the stage from running. Otherwise, we run the commit stage to the end and report all the **errors** so they can all be **fixed at once**.
<br>
### _What Should Break the Commit Stage_
- compilation fails, tests breaks, environmental problem
- proide threshold (example: fail if unit test coverage drops below 60%)
_"Failing the Build for Warnings and Code Style Breaches"_ (previous chapters)
<br>
### _Tend the Commit Stage Carefully_
A **poor** build script **draws** vluable and expensive development effort and **slows** the project down.
Ensure that your scripts are **modular**. (Chapter 6 - Build and Deployment Scripting)
Keep tasks that are changing **often** from those that are changing **rarely**.
**Avoid environment-specific scripts!**
<br>
### _Give Developers Ownership_
Adding new libraries, configuration files, and so on, should be performed by **developers** and **operations** people working together.
The **goal** of specialists is to establish good **structures, patterns, and use of technology**, and to **transfer their knowledge** to the delivery team.
<br>
### _Use a Build Master for Very Large Teams_
Their job is to **oversee** the **maintenance** of the build, but also **encourage** and **enforce** build **discipline**.
Team members should **rotate** through it.
<br>
## The Results of the Commit Stage
The **inputs** are the source code.
The **outputs** are the binaries and reports.
The binaries generated by the commit stage are **precisely** the **same** ones that will be reused throughout the **pipeline**.
<br>
### _The Artifact Repository_
This is where you **store** artifacts.
- it ony keeps **successful versions**
- we must be able to **trace back** from the released software to the revisions in VC that were used to create it
- the binary **creation** process must be **repeatable**

RC = _release candidate_
Depending on the project, it might make sense to run some of the **post-acceptance-stage** steps **in parallel**.
For example, **manual** testing and **capacity** testing can both be triggered by the successful completion of the acceptance tests.
<br>
## Commit Test Suite Principles and Practices

**Unit tests must be fast!**
**Unit tests shouldn't touch** the filesystem, databases, libraries, framework, or external systems.
Any calls to these parts should be replaced with **test doubles**, such as **mocks** and **stubs**.
<br>
### _Avoid the User Interface_
Avoid these [patterns](https://bryanwilhite.github.io/the-funky-knowledge-base/entry/kb2076072213/) !
**UI testing** if often **problematic** and usually better handled at the **acceptance** test stage.
<br>
### _Use Dependency Injection_

<br>
### _Avoid the Database_
<br>
### _Avoid Asynchrony in Unit Tests_
Tests which rely on **infrastructure** count as **component** tests, not unit tests.
<br>
### _Using Test Doubles_
```
class Car {
private Engine engine;
public Car(Engine engine) {
this.Engine = engine;
}
public void drive() {
engine.start();
engine.accelerate();
}
}
Interface Engine() {
public start();
public accelerate();
}
```
We want to test whether the 2 methods (start() and accelerate(), from the Engine) work (sequentially) when the drive() method from Car is called.
1. **Stubbing** is the replacement of a part of a system with a simulated version that provides canned responses.
```
class TestEngine implements Engine {
boolean startWasCalled = false;
boolean acceleratedWasCalled = false;
boolean sequenceWasCorrect = false;
public start() {
startWasCalled = true;
}
public accelerate() {
accelerateWasCalled = true;
if(startWasCalled == true) {
sequenceWasCorrect = true;
}
}
public boolean wasDriven() {
return startWasCalled && accelerateWasCalled && sequenceWasCorrect;
}
}
class CarTestCase extends TestCase {
public void testShouldStartThenAccelerate() {
TestEngine engine = new TestEngine();
Car car = new Car(engine);
car.drive();
assertTrue(engine.wasDriven());
}
}
```
<br>
2. **Mocking** is a newer technique, which doesn't require writing lots of stub code.
```
import jmock;
class CarTestCase extends MockObjectTestCase {
public void testShouldStartThenAccelerate() {
Mock mockEngine = mock(Engine);
Car car = new Car((Engine)mockEngine.proxy());
mockEngine.expects(once()).method("start");
mockEngine.expects(once()).method("accelerate");
car.drive();
}
}
```
**Mocking** can save a lot of effort.
<br>
### _Minimizing State in Tests_
The **ideal** test is **quick** and **easy** to set up and even quicker and easier to tear down.
<br>
### _Faking Time_
Perhaps your system needs to trigger an end-of-day process, or it needs to wait 500ms before processing the next step.
We need to **abstract** our need for time information into a separate class that is under our control.
<br>
### _Brute Force_
The commit stage **duration** must be **balanced** with the ability to **identify** the most common **errors** that you are likely to introduce.
The commit stage should not last more than 10 minutes! (ideally under 5 minutes)
If it lasts long:
- the developers with check-in **less frequently** (BAD)
- people **stop caring** about whether or not the commit test suite passes (BAD)
<br>
## Summary
The commit stage is focused on 1 thing: **detecting, as fast as possible, the most common failures** and **notifying the developers**.
The commit stage should run every time someone introduces a **change** to the applcation's **code** or **configuration**.
|
WGiBeat - v1.0 Readme
http://code.google.com/p/wgibeat/
wgibeat{at}gmail{period}com
By thomeval
Setup
--------------------------------------------
Before running this game, ensure that your system has the .NET Framework 3.5 SP 1, and XNA Framework Redistributable 3.1 installed. If either of them are not present, the game will fail to load. Note that the WGiBeat installer should detect whether these are installed for you. Due to size concerns, the .NET Framework is not included in the installer (a link will be provided instead).
Alternatively, the prerequisites can be downloaded from the links below:
XNA Framework Redistributable 3.1:
http://www.microsoft.com/downloads/details.aspx?FamilyID=53867a2a-e249-4560-8011-98eb3e799ef2&displaylang=en
.NET Framework 3.5 SP1
http://www.microsoft.com/downloads/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7&DisplayLang=en
Starting WGiBeat
---------------------------------------------
When WGiBeat is started for the first time, a tutorial will be displayed explaining the basic gameplay. This can be skipped by
pressing the Escape key. The tutorial can be viewed at any time by selecting "How To Play" from the main menu.
Note that WGiBeat requires songs to be playable. If no songs are installed, WGiBeat will display an error message when attempting to
start a new game. Songs can be created from the song editor, and sample songs are also available from the official website (listed
at the top of the readme). An exaplanation of the song format (.sng) is given in the readme inside the Songs folder. All songs should be
contained inside this folder.
Another important consideration for users running Windows Vista or 7: It is *strongly* recommended that WGiBeat be run with administrative privileages, particularly if WGiBeat is installed into the Program Files folder. This is because WGiBeat routinely reads and writes to files contained in the folder. If WGiBeat is not run in this way, expect unusual issues (such as reading successfully from files that don't seem to exist).
Usage and default keys
---------------------------------------------
Start the game by running WGiBeat.exe. A shortcut should be created automatically on the start menu if the installer is used.
The game is controlled entirely with either a keyboard or an Xbox 360 controller. The following keys are used by default:
Player 1:
W = Up
A = Left
S = Down
D = Right
Space = Beatline
Q = Start
E = Select
Player 2:
Arrow keys for up, left, down and right
Numpad 0 = Beatline
Numpad 1 = Start
Numpad 2 = Select
Player 3:
Numpad 8 = Up
Numpad 4 = Left
Numpad 5 = Down
Numpad 6 = Right
Insert = Beatline
Page Down = Start
Page Up = Select
Player 4 (Xbox 360 controller 1):
Y = Up
X = Left
A = Down
S = Right
RB or LB = Beatline
LT or RT = Select
Back = Back
Start = Start
All keys can be changed from by Keys option in the main menu. To reset the assigned keys to default, delete the keys.conf file created by the game in the same folder.
To start a game, first press select Start Game from the main menu, then press Start. On the next screen, every player that wishes to play must press start to join in. Once joined in, select your difficulty. Once ready, select the Decision option, and press Start.
When all players are ready, the select mode screen is displayed. Choose which mode to play, and press start again.
When the mode is chosen, a list of available songs is displayed. Select the song to be played, and press start again.
Gameplay Explanation
----------------------------------------------
For a tutorial on the basic gameplay of WGiBeat, please see the the How To Play screen, accessible from the main menu.
For more help, please see the official website, or contact the developers at the address given at the top of the readme.
Compiling the source code
----------------------------------------------
To compile your own version of WGiBeat from source, the same prerequisites are necessary as mentioned above, in addition to Visual Studio 2008, and XNA Game Studio 3.1. With these installed, the project can be loaded and compiled normally by opening the .sln file.
For more information, or to join the development team, please contact the developers using the address given at the top of the readme.
|
<div class="largo">
<div *ngIf="this.perfilVisitadoBool === false">
<mat-card *ngFor="let cardContact of obsContact | async">
<mat-card-header>
<img mat-card-avatar [src]="cardContact.usuarioFoto || 'assets/imgApp/no-imagen.jpg'" alt="sin imagen">
<mat-card-title>{{cardContact.usuario.nombreUsu}}</mat-card-title>
<mat-card-subtitle>{{cardContact.usuario.nombreUsu}}</mat-card-subtitle>
</mat-card-header>
<mat-card-actions *ngIf="cardContact.boolAmigo === true">
<!-- acciones en caso de ser amigos, visitar, quitar de amigos -->
<button mat-raised-button color="primary" (click)="visitarPerfil(cardContact.usuario)">Visitar</button>
<button mat-raised-button color="warn" (click)="cancelarAmistad(cardContact.usuario)">Cancelar amistad</button>
</mat-card-actions>
<mat-card-actions *ngIf="cardContact.boolAmigo === false">
<!-- acciones en caso de no ser amigos, visitar si es publico, enviar peticion amistad -->
<button mat-raised-button color="primary" *ngIf="cardContact.usuarioLog.esAdministrador > 0 || cardContact.usuario.perfilPrivado < 1" (click)="visitarPerfil(cardContact.usuario)">Visitar</button>
<button mat-raised-button color="primary" *ngIf="cardContact.boolAmigo === false" (click)="enviarPeticionAmistad(cardContact.usuario)">Enviar peticion</button>
</mat-card-actions>
</mat-card>
<mat-paginator
[length] = "numUsuarios"
[pageSize] = "5"
[pageSizeOptions] = "[1, 5, 10, 20, 30, 40, 50, 100, 150, 200]">
</mat-paginator>
</div>
<div *ngIf="this.perfilVisitadoBool === true">
<!-- boton de volver atras -->
<button mat-raised-button color="primary" (click)="visitarPerfil()" class="btnVolverAtras">Atras</button>
<app-perfil [usuarioPerfil]="perfilVisita" [usuarioVisita]="usuarioLogged"></app-perfil>
</div>
</div>
|
import 'package:e_commerce_app_getx/controllers/order_controller.dart';
import 'package:e_commerce_app_getx/data/models/order_model.dart';
import 'package:e_commerce_app_getx/ui/pages/widgets/custom_loader.dart';
import 'package:e_commerce_app_getx/ui/utils/colors.dart';
import 'package:e_commerce_app_getx/ui/utils/dimension.dart';
import 'package:e_commerce_app_getx/ui/utils/styles.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/state_manager.dart';
class ViewOrder extends StatelessWidget {
final bool isCurrent;
const ViewOrder({super.key, required this.isCurrent});
@override
Widget build(BuildContext context) {
return Scaffold(
body: GetBuilder<OrderController>(
builder: (orderController) {
if (orderController.isLoading == false) {
late List<Order> orderList;
if (orderController.historyOrderList.isNotEmpty) {
orderList = isCurrent
? orderController.currentOrderList.reversed.toList()
: orderController.historyOrderList.reversed.toList();
}
return SizedBox(
width: Dimensions.screenWidth,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: Dimensions.width10 / 2,
vertical: Dimensions.height10 / 2),
child: ListView.builder(
itemCount: orderList.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () => null,
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Text(
'order ID',
style: robotoRegular.copyWith(
fontSize: Dimensions.font12,
),
),
SizedBox(width: Dimensions.width10 / 2),
Text('#${orderList[index].id.toString()}'),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Container(
decoration: BoxDecoration(
color: AppColors.mainColor,
borderRadius: BorderRadius.circular(
Dimensions.radius20 / 4),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: Dimensions.width10,
vertical: Dimensions.width10 / 2),
child: !isCurrent
? Text(
"Confirmed",
style: robotoMedium.copyWith(
fontSize: Dimensions.font12,
color: Theme.of(context)
.cardColor,
),
)
: Text(
"Pending",
style: robotoMedium.copyWith(
fontSize: Dimensions.font12,
color: Theme.of(context)
.cardColor,
),
),
)),
SizedBox(height: Dimensions.height10 / 2),
InkWell(
onTap: () => null,
child: Container(
padding: EdgeInsets.symmetric(
horizontal: Dimensions.width10,
vertical: Dimensions.width10 / 2),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(
Dimensions.radius20 / 4),
border: Border.all(
width: 1,
color: Theme.of(context)
.primaryColor),
),
child: Row(
children: [
Image.asset(
"assets/image/tracking.png",
height: 15,
width: 15,
color: Theme.of(context)
.primaryColor),
SizedBox(
width: Dimensions.width10 / 2),
Text(
"Track order",
style: robotoMedium.copyWith(
fontSize: Dimensions.font12,
color: Theme.of(context)
.primaryColor,
),
),
],
)),
),
SizedBox(height: Dimensions.height10),
],
),
],
),
),
);
}),
),
);
} else {
return CustomLoader();
}
},
),
);
}
}
|
import { useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
const captchaSiteKey = process.env.REACT_APP_RECAPTCHA_SITE_KEY;
const LoginForm = () => {
const [username, setUsername] = useState('');
const [reCAPTCHA, setReCAPTCHA] = useState('');
const [isVerified, setIsVerified] = useState(undefined);
const isUserNameValid = (username) => username && username.length > 5 && username.length < 20;
const handleChange = (e) => {
setUsername(e.target.value);
}
const submit = async (value, recaptchaToken, loginEndpoint = 'login') => {
if (!isUserNameValid(value)) {
alert('Username is not valid');
return;
}
try {
const res = await fetch(`/${loginEndpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: value, recaptcha: recaptchaToken })
})
if (res.status === 200) {
setIsVerified(data?.success);
} else if (res.status === 403) {
alert('something went wrong - unauthorized');
}
const data = await res.json();
} catch (e) {
console.log(e);
}
}
const handleSubmit = async (e) => {
e.preventDefault();
return submit(username, reCAPTCHA)
}
function handleCaptcha(value) {
setReCAPTCHA(value);
}
return (
<div>
<form onSubmit={handleSubmit}>
<div style={{margin: "10px"}}>
<label>
Name:
<input type="text" value={username} onChange={handleChange} />
</label>
</div>
<div style={{display: "flex", "align-items": "center", "justify-content": "center"}}>
{isUserNameValid(username) && <ReCAPTCHA
sitekey={captchaSiteKey}
onChange={handleCaptcha}
/>
}
</div>
<div style={{margin: "20px"}}>
<input type="submit" value="Submit" />
</div>
</form>
{isVerified !== undefined && (<h1>{isVerified ? 'Human :)' : 'Machine :('}</h1>)}
</div>
);
}
export default LoginForm;
|
import java.awt.Color;
import java.util.HashMap;
/**
* This class collects and provides some statistical data on the state
* of a field. It is flexible: it will create and maintain a counter
* for any class of object that is found within the field.
*
* @author David J. Barnes and Michael Kölling
* @edited by Stanislas Jacquet and Henri Chevreux
* @version 2021.02.28
*/
public class FieldStats
{
// Counters for each type of entity (lion, jaguar, etc.) in the simulation.
private HashMap<Class, Counter> counters;
//counter for infected species in the simulation.
private int infectedCounter = 0;
// Whether the counters are currently up to date.
private boolean countsValid;
private int viableParameter;
/**
* Construct a FieldStats object.
*/
public FieldStats()
{
// Set up a collection for counters for each type of animal that
// we might find
counters = new HashMap<>();
countsValid = true;
viableParameter = 1;
}
/**
* Get details of what is in the field.
* @return A string describing what is in the field.
*/
public String getPopulationDetails(Field field)
{
StringBuffer buffer = new StringBuffer();
if(!countsValid) {
generateCounts(field);
}
for(Class key : counters.keySet()) {
Counter info = counters.get(key);
buffer.append(info.getName());
buffer.append(": ");
buffer.append(info.getCount());
buffer.append(' ');
}
return buffer.toString();
}
/**
* Invalidate the current set of statistics; reset all
* counts to zero.
*/
public void reset()
{
countsValid = false;
for(Class key : counters.keySet()) {
Counter count = counters.get(key);
count.reset();
}
infectedCounter = 0;
}
/**
* Increment the count for one class of animal.
* @param animalClass The class of animal to increment.
*/
public void incrementCount(Class animalClass)
{
Counter count = counters.get(animalClass);
if(count == null) {
// We do not have a counter for this species yet.
// Create one.
count = new Counter(animalClass.getName());
counters.put(animalClass, count);
}
count.increment();
}
/**
* Indicate that an animal count has been completed.
*/
public void countFinished()
{
countsValid = true;
}
/**
* Determine whether the simulation is still viable.
* I.e., should it continue to run.
* @return true If all species are alive.
*/
public boolean isViable(Field field)
{
// How many counts are non-zero.
int nonZero = 0;
if(!countsValid) {
generateCounts(field);
}
for(Class key : counters.keySet()) {
Counter info = counters.get(key);
if(info.getCount() > 0) {
nonZero++;
}
}
return nonZero > viableParameter;
}
/**
* Generate counts of the number of entities in the field.
* These are not kept up to date as animals and plants
* are placed in the field, but only when a request
* is made for the information.
* @param field The field to generate the stats for.
*/
private void generateCounts(Field field)
{
reset();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object entity = field.getObjectAt(row, col);
if(entity != null) {
incrementCount(entity.getClass());
}
}
}
countsValid = true;
}
/**
* Gets the total number of infected animals.
* @return value of infectedCounter as integer.
*/
public int getInfectedCounter()
{
return infectedCounter;
}
/**
* Increments counter of infected animals by one.
*/
public void incrementInfectedCounter(){infectedCounter++;}
public void setViableParameter(int newParameter){viableParameter=newParameter;}
}
|
package com.zetkno.dynamicProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
/**
* 生成代理类
* @return
*/
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
/**
* @param proxy 代理类
* @param method 代理类的调用处理程序的方法对象
* @param args
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target, args);
return result;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>How I Designed & Built This Minimalistic Blog</title>
<link href="/css/reset.css" rel="stylesheet">
<link href="/css/style.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
</head>
<body data-spy="scroll" data-target=".subnav" data-offset="50">
<div id="navsuperwrap">
<div id="navwrap">
<a href="/" class="logo"></a>
<nav style="display: inline-block;">
<ul>
<li style="display: inline-block; "><a href="/" class="">Blog</a></li>
<li style="display: inline-block; margin-left: 30px;"><a href="https://github.com/manmal" class="">Github</a></li>
<li style="display: inline-block; margin-left: 30px;"><a href="/hireme.html" class="">Hire me</a></li>
</ul>
</nav>
</div>
<div class="round-thing"></div>
</div>
<div id="pagewrap">
<aside>
<div class="photo"></div>
<a href="http://twitter.com/manuelmaly" target="_blank" class="button" style="margin-left:14px; width:130px;">@manuelmaly</a>
<a href="/atom.xml" target="_blank" class="button" style="margin-left:14px; width:130px; margin-top: 5px;">Atom Feed</a>
</aside>
<article>
<header>
<h1><a href="">How I Designed & Built This Minimalistic Blog</a></h1>
<span class="postdate" style="margin-right: 7px;">2012 08 25</span>
<a href="/tag/jekyll" class="tag" title="View posts tagged with "jekyll"">jekyll</a>
<a href="/tag/design" class="tag" title="View posts tagged with "design"">design</a>
<a href="/tag/css" class="tag" title="View posts tagged with "css"">css</a>
<div style="height: 10px;"></div>
</header>
<p>
I'm a native Android & iOS developer, and not exactly doing web development every day - I'm surely ignorant of some fancy twists (tricking IE6 into doing things). However, I have spent upwards of 1000 hours with HTML 4 and CSS 1/2 in my teens, building a PHP CMS for a local shop and other stuff. To refresh my web development abilities, I decided to <b>design my blog from scratch</b> - CSS and HTML-wise.
<br>
This post is about how I did it.
</p>
<h2>Requirements</h2>
<p>What I want for my blog:</p>
<ul>
<li>Minimalistic but beautiful design</li>
<li>Low loading times (few requests, lean resources)</li>
<li>Inexpensive hosting</li>
</ul>
<h2>Technical Setup</h2>
<p>
After considering my requirements, I came up with this setup:
</p>
<ul>
<li>Jekyll</li>
<li>HTML 5, CSS 3</li>
<li>No self-written JS (for the time being)</li>
<li>Widgets for added functionality</li>
</ul>
<p>
I chose <a href="https://github.com/mojombo/jekyll" target="_blank"><b>Jekyll</b></a>, a semi-static site framework for Rails, for reasons of <b>performance and flexibility</b>. Pages reportedly load very fast, and you can host them at your own Github subdomain - neat! While your pages are mostly served statically, you can add "dynamic" functionality by using external services, like in-site Google search, all the web's widgets, and even comments (e.g., via Disqus). Eric Jones went to the absolute max with widget integration in his <a href="http://erjjones.github.com/blog/How-I-built-my-blog-in-one-day/" target="_blank">blog</a> - a great resource for reference!
</p>
<p>
As I thought it would not be necessary, I did not employ SASS. If CSS code becomes any more complicated, I will probably make the <a href="http://mikeferrier.com/2011/04/29/blogging-with-jekyll-haml-sass-and-jammit/" target="_blank">switch</a>.
</p>
<h2>Choosing Layout and Colors</h2>
<p>
I then surfed the web for blog layouts I wanted to borrow from - and found <a href="http://www.philterdesign.com/?p=541" target="_blank">this one</a> by Phil Chung. Then kicked up Photoshop, loaded a screenshot of Phil's blog, and created a <b>color palette</b> by overlaying all relevant elements. It's advisable to use an actual layout to find a palette, because a color's effect depends on the amount of screen space it is given.
</p>
<p>
Over time I have grown addicted to this shade of purplish red: <span style="color: #ff002a;"><b>#ff002a</b></span> - call it my favourite color - and now I can finally put it to use in my own blog.
Also, I like <b>high contrasts and warm colors</b> (that means, red or orange tint), as they are easy on the eye and comforting.
</p>
<p><figure>
<img src="/img/2012-05-23/layout_and_palette.png" style="margin: 20px auto; display: block;" title="Talent borrows...">
</figure></p>
<h2>Selecting Typefaces</h2>
<p>
The <a href="http://www.myfonts.com/fonts/exljbris/museo/" target="_blank">Museo family</a> is really great, I'm definitely a Museo fan (gotta watch out that I don't use it too often). Also, some of them are free, and can be downloaded at MyFonts as drop-in web fonts, readily shipped with <a href="http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax" target="_blank">bulletproof</a> CSS code. Therefore, I'm using <b>Museo 300</b> and <b>Museo 500</b> for headings and the navigation menu.
</p>
<p>
For the sake of readability of the body copy, I opted for <b>Helvetica Neue</b>, and as a fallback for Windows users, <b><span style="font-family: Arial">Arial</span></b> (yeah, I know :/).
</p>
<p>
<b>Font size</b> is not so easy to get right, but is VERY important for readability. There are people claiming that going below 16 points would be stupid. I am going with 1.1em which amounts to 19px on my 15" Macbook Pro at standard browser settings. It amounts to <b>11-15 words per line</b>, which will (hopefully) average in the oft-praised <a href="http://www.maxdesign.com.au/articles/em/" target="_blank">12 words per line</a>.
</p>
<h2>Adding Eye Candy</h2>
<p>
As a Photoshop addict, I HAD to take the chance to play around with <b>subtle effects and textures</b>. After all, the little details make all the difference.
</p>
<p>
After layout, colors, and typefaces had been set, I headed over to <a href="http://subtlepatterns.com" target="_blank">Subtle Patterns</a> to find nice textures. With some brightness modifications to <a href="http://subtlepatterns.com/?p=203" target="_blank">one of those</a>, a <b>pattern for the header area</b> was born, looking somewhat like denim cloth:
</p>
<p><figure>
<img src="/img/2012-05-23/stripes_pattern.png" title="Dark Stripes" style="margin: 20px auto; display: block;">
</figure></p>
<p>
The <b>main area</b> (on which you are currently reading) also needed some <b>texture</b>, so I went the good ol' noise route: Added <a href="/img/2012-05-23/transparent_noise.png" target="_blank">this pattern</a> as pattern overlay, with blend mode Luminosity and Opacity set to 10% - voilá.
</p>
<p>To add a fancy touch to the banner, I decided to go with a <b>pattern of cut circles</b> at its bottom, softening the transition from dark to bright. Adding a white inner shadow (angle: 90°, distance: 1px, size: 0px, blend mode: Normal) gives it a slight 3D effect:
</p>
<p><figure>
<img src="/img/2012-05-23/round_thing_enlarged.png" style="margin: 20px auto; display: block;" title="Pseudo 3D effect pattern">
</figure></p>
<p>The <b>photo of me</b> at the top left of every page makes the blog more personal (at least I hope so :^) ), and I wanted it to look like a physical print of a photograph, stuck into a fold of the "blog paper" (curious people, look into the <a href="/img/2012-05-23/photo.psd" target="_blank">PSD file</a>):
</p>
<p><figure>
<img src="/img/2012-05-23/photo.png" title="Dark Stripes" style="margin: 20px auto; display: block;">
</figure></p>
<h2>Slicing It Up</h2>
<p>
Having finished the Photoshop mockup, I proceeded to extract images from it and created a layout in CSS.
The first thing I did was load a <a href="http://meyerweb.com/eric/tools/css/reset/">CSS Reset</a> to minimize strange cross-browser surprises. After that, the layout elements were placed in their own HTML containers and assigned CSS layout properties. Curious people, look at the details in the site's <a href="/css/style.css" target="_blank">main CSS file</a>, or better, use your browser's element inspector. The box layout looks like this (click to enlarge):
</p>
<p><figure>
<a href="/img/2012-05-23/layout_detailed.png" target="_blank"><img src="/img/2012-05-23/layout_detailed_small.png" title="Dark Stripes" style="margin: 20px auto; display: block;"></a>
</figure></p>
<p>
As every resource (JS, CSS, Image,...) is served in its own request, a page's loading time can be lowered by putting as many images as possible in <b>sprites</b>. I used <a href="TODO" target="_blank">SpriteRight</a> to wrap all reoccurring, non-repeated images into one single file, which currently looks like this:
</p>
<p><figure>
<img src="/img/2012-05-23/sprite.png" style="margin: 20px auto; display: block;" title="Sprite">
</figure></p>
<h2>More CSS Eye Candy</h2>
<p>
Holding the finished HTML & essential CSS code in my hands, I went on to add some more details to make the page look more refined.
</p>
<p><b>Shadowed text</b> looks very nice on most backgrounds, as subtle as the effect may be (under some lighting conditions, it's not visible on this blog). A white shadow added to a dark font increases the contrast, making it look crisper by seemingly sharpening the edges.
</p>
<p>
Fancy <b>link color hover transitions</b> can be had by adding some CSS:
</p>
<p>One more subtlety is the manipulation of <b>text selection</b> background and color. In my case, I also had to disable text shadows:</p>
<h2>Code Highlighting</h2>
<p>
Jekyll comes with support for <b>Pygments</b>, a python syntax highlighter which also generates CSS code based on predefined styles. Installing and configuring Pygments is straightforward on OSX (Python is preinstalled on OSX >= 10.4):
</p>
<p>
You may have noticed that the generated highlighting is not perfect, and I might therefore switch to another technology - e.g. <a href="http://daniel-salazar.com/jekyll/code-highlighting-with-coderay-in-jekyll.html" target="_blank">CodeRay</a>.
</p>
<h2>JS or No</h2>
<p>
Fully blown JS frameworks like jQuery have found their way into most blog templates, be it sensible or not. Since low loading time is one of my main priorities for this blog, I meditated if I needed any client-side code - turns out: <b>No</b>.
I have been able to achieve everything I wanted for this blog, without JS.</p>
<p>
I might add Disqus and Google Analytics support later on, but for the time being, I'm fine with plain HTML & CSS plus the following HTML5 JS hack for older browsers.
</p>
<h2>HTML5 for Older Browsers</h2>
<p>
<b><a href="http://code.google.com/p/html5shiv/" target="_blank">html5shiv</a></b> provides a drop-in JS snippet to force browsers like IE6 to eat your HTML5, and you need not host it yourself:
</p>
<p>
I have not tested it though. :)
</p>
<h2>Cross-Browser Testing</h2>
<p>
To make sure my blog looks the same for most of the users (I developed it with Safari), I started some other browsers (FF, Chrome, Opera) and only minor problems showed: FF sets font-weight to bold for headings (which I disabled then), and Opera made Pygment's syntax highlighting appear super-huge (which I don't care about).
</p>
<p>Currently, I haven't found time to test Internet Explorer support (no Windows VM installed currently) - I will fix it if someone tells me there is a problem.</p>
<h2>Atom Feed</h2>
<p>
To provide an Atom feed for my blog, I copied one of the many templates floating around the interwebs and made some modifications like filling in my name, and saved it as <b><a href="https://github.com/manmal/manmal.github.com/blob/master/atom.xml" target="_blank">atom.xml</a></b>. Currently, the posts are sent in whole on every Atom request (making for a lot of traffic) - I might shorten the posts later on, but for the time being I have not found a way to do this in Liquid.
</p>
<h2>Deploying to Github</h2>
<p>
Pushing a Jekyll site to Github was straightforward - after setting up a public repo called <b>manmal.github.com</b>, I just pushed it up there, and, after a few minutes, received the first build notification per email. That was easy!
</p>
<h2>Remaining Issues</h2>
<p>
When validating my blog's markup via <a href="http://html5.validator.nu/" target="_blank">html5.validator.nu</a>, I got errors because all figure tags were wrapped in paragraph (p) tags - it seems Jekyll generates those without asking. I will look into this soon.
</p>
</article>
</div>
</body>
</html>
|
package com.devsuperior.dscatalog.tests.web;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import com.devsuperior.dscatalog.dto.ProductDTO;
import com.devsuperior.dscatalog.services.ProductService;
import com.devsuperior.dscatalog.services.exceptions.MyDatabaseIntegrityException;
import com.devsuperior.dscatalog.services.exceptions.ResourceNotFoundException;
import com.devsuperior.dscatalog.tests.factory.ProductFactory;
@SpringBootTest
@AutoConfigureMockMvc
public class ProductResourceTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private ProductService service;
// Allows Java objects conversion to JSON
@Autowired
private ObjectMapper objectMapper;
@Value("${security.oauth2.client.client-id}")
private String clientId;
@Value("${security.oauth2.client.client-secret}")
private String clientSecret;
private long existingId;
private long nonExistentId;
private long dependentId;
private ProductDTO newProductDTO;
private ProductDTO existingProductDTO;
private PageImpl<ProductDTO> page;
private String operatorUsername;
private String operatorPassword;
@BeforeEach
void setUp() throws Exception {
operatorUsername = "alex@gmail.com";
operatorPassword = "123456";
existingId = 1L;
nonExistentId = 2L;
dependentId = 3L;
newProductDTO = ProductFactory.createProductDTO(null);
existingProductDTO = ProductFactory.createProductDTO(existingId);
page = new PageImpl<>(List.of(existingProductDTO));
// CREATE
// mock service to insert a new ProductDTO
// insert an object was too complex. So any() was used instead.
when(service.insert(any())).thenReturn(existingProductDTO);
// RETRIEVE
// mock service to return a productDTO
when(service.findById(existingId)).thenReturn(existingProductDTO);
when(service.findById(nonExistentId)).thenThrow(ResourceNotFoundException.class);
// mock service to return a page of ProductsDTO
when(service.findAllPaged(any(), anyString(), any())).thenReturn(page);
//UPDATE
// mock service to UPDATE a ProductDTO
// eq() method replaces the actual existingId. It won't work on the other hand.
when(service.update(eq(existingId), any())).thenReturn(existingProductDTO);
// mock service when trying to update nonexistent ProductDTO
when(service.update(eq(nonExistentId), any())).thenThrow(ResourceNotFoundException.class);
// DELETE
// mock service to DELETE an existing ProductDTO
// .delete() returns void, hence we start with doNothing()
doNothing().when(service).delete(existingId);
// mock service to DELETE an nonexistent ProductDTO
doThrow(ResourceNotFoundException.class).when(service).delete(nonExistentId);
// mock service to DELETE a ProductDTO associated with another dependant object
/**
* NOTE: the way system entities associations are configured, there won't be
* unwanted effects due deletion of dependent objects, but since these are unit
* tests, we are covering this possibility.
**/
doThrow(MyDatabaseIntegrityException.class).when(service).delete(dependentId);
}
// CREATE
@Test
public void insertShouldReturnHttpStatusCreatedAndProductWhenDataIsValid() throws Exception{
// given
// To insert a product, one must be logged
String accessToken = obtainAccessToken(operatorUsername, operatorPassword);
// includes a valid Product into request body
String jsonBody = objectMapper.writeValueAsString(newProductDTO);
// when
// mock a request
ResultActions result = mockMvc.perform(post("/products")// url
.header("Authorization", "Bearer " + accessToken)// token
.content(jsonBody)// body
.contentType(MediaType.APPLICATION_JSON)// body type
.accept(MediaType.APPLICATION_JSON));// returned body type accepted
// then
// asserts that we expect a http response status 201 - created
result.andExpect(status().isCreated());
// check on returned object
result.andExpect(jsonPath("$.id").exists());// ID shall not be null
}
@Test
public void insertShouldReturnUnprocessableEntityWhenNegativePrice() throws Exception{
// given
// To insert a product, one must be logged
String accessToken = obtainAccessToken(operatorUsername, operatorPassword);
// provide a negative price
newProductDTO.setPrice(-10.00);
// includes a valid Product into request body
String jsonBody = objectMapper.writeValueAsString(newProductDTO);
// when
// mock a request
ResultActions result = mockMvc.perform(post("/products")// url
.header("Authorization", "Bearer " + accessToken)// token
.content(jsonBody)// body
.contentType(MediaType.APPLICATION_JSON)// body type
.accept(MediaType.APPLICATION_JSON));// returned body type accepted
// then
// asserts that we expect a http response status 201 - created
result.andExpect(status().isUnprocessableEntity());
}
// RETRIEVE
@Test
public void findAllShouldReturnPage() throws Exception {
ResultActions result = mockMvc.perform(get("/products")
.accept(MediaType.APPLICATION_JSON));
result.andExpect(status().isOk());
// Test JSON values within the response's body
result.andExpect(jsonPath("$.content").exists());
}
@Test
public void findByIdShouldReturnProductWhenIdExists() throws Exception {
ResultActions result = mockMvc.perform(get("/products/{id}", existingId)
.accept(MediaType.APPLICATION_JSON));
result.andExpect(status().isOk());
// Test JSON values within the response's body
result.andExpect(jsonPath("$.id").exists());// if returned id exists
result.andExpect(jsonPath("$.id").value(existingId));// if returned id matches w/ passed id
}
@Test
public void findByIdShouldReturnNotFoundWhenIdDoesNotExist() throws Exception {
ResultActions result = mockMvc.perform(get("/products/{id}", nonExistentId)
.accept(MediaType.APPLICATION_JSON));
result.andExpect(status().isNotFound());
}
// UPDATE
// Method shall return 404, when ID is nonexistent
@Test
public void updateShouldReturnNotFindWhenIdDoesNotExist () throws Exception{
// /products/{id} is a protected route. We need an access token.
String accessToken = obtainAccessToken(operatorUsername, operatorPassword);
// Put requests demands for a request body. Http protocol use JSON to send data.
// This line converts java object to json
String jsonBody = objectMapper.writeValueAsString(newProductDTO);
ResultActions result = mockMvc.perform(put("/products/{id}", nonExistentId)
.header("Authorization", "Bearer " + accessToken)// Adds access token to header
.content(jsonBody)// Adds json object to body request
.contentType(MediaType.APPLICATION_JSON)// Configure MediaType
.accept(MediaType.APPLICATION_JSON));
// asserts that we expect a http response status 404 - Not Found
result.andExpect(status().isNotFound());
}
// Method shall return a ProductDTO object when id exists
@Test
public void updateShouldReturnProductDTOWhenIdExists () throws Exception{
String accessToken = obtainAccessToken(operatorUsername, operatorPassword);
String jsonBody = objectMapper.writeValueAsString(newProductDTO);
// helps checking if returned ProductDTO is correct
String expectedName = newProductDTO.getName();
Double expectedPrice = newProductDTO.getPrice();
ResultActions result = mockMvc.perform(put("/products/{id}", existingId)
.header("Authorization", "Bearer " + accessToken)
.content(jsonBody)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON));
// asserts that we expect a http response status 200 - Ok
result.andExpect(status().isOk());
// check on returned object
result.andExpect(jsonPath("$.id").exists());// ID shall not be null
result.andExpect(jsonPath("$.id").value(existingId));// Object id matches the informed one
result.andExpect(jsonPath("$.name").value(expectedName));// Object name matches the informed one
result.andExpect(jsonPath("$.price").value(expectedPrice));// Object Price equals the informed one
}
// DELETE
@Test
public void deleteShouldReturnNoContentWhenIdExists() throws Exception{
// given
// /products/{id} is a protected route. We need an access token.
String accessToken = obtainAccessToken(operatorUsername, operatorPassword);
// when
// mock a delete request
ResultActions result = mockMvc.perform(delete("/products/{id}", existingId)
.header("Authorization", "Bearer " + accessToken)// Adds access token to header
.accept(MediaType.APPLICATION_JSON));
// asserts that we expect a http response status 204 - No Content
result.andExpect(status().isNoContent());
}
@Test
public void deleteShouldReturnNotFoundWhenIdDoesNotExist() throws Exception{
// given
// /products/{id} is a protected route. We need an access token.
String accessToken = obtainAccessToken(operatorUsername, operatorPassword);
// when
// mock a delete request
ResultActions result = mockMvc.perform(delete("/products/{id}", nonExistentId)
.header("Authorization", "Bearer " + accessToken)// Adds access token to header
.accept(MediaType.APPLICATION_JSON));
// asserts that we expect a http response status 404 - No Content
result.andExpect(status().isNotFound());
}
// AUTENTICATION
private String obtainAccessToken(String username, String password) throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "password");
params.add("client_id", clientId);
params.add("username", username);
params.add("password", password);
ResultActions result
= mockMvc.perform(post("/oauth/token")
.params(params)
.with(httpBasic(clientId, clientSecret))
.accept("application/json;charset=UTF-8"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"));
String resultString = result.andReturn().getResponse().getContentAsString();
// A different way to access the response message attributes
JacksonJsonParser jsonParser = new JacksonJsonParser();
return jsonParser.parseMap(resultString).get("access_token").toString();
}
}
|
// PSDX-Licence-Identifier: MIT
pragma solidity ^0.8.0;
contract Automotive {
// variables
address public owner;
string public vehicleMake;
string public vehicleModel;
uint public price;
// constructor
constructor() {
owner = msg.sender;
}
// mapping
mapping (address=>bool) public buyers;
// events
event Purchase(address buyer, string make, string model, uint price);
// modifier
modifier onlyOwner {
require(msg.sender == owner, "Only the owner can do this");
_;
}
// functions
function buyVehicle (string memory _make, string memory _model) public payable{
require(msg.value >= price);
require(buyers[msg.sender] == false);
vehicleMake = _make;
vehicleModel = _model;
buyers[msg.sender] = true;
emit Purchase(msg.sender, _make, _model, price);
}
function setPrice(uint _price) public onlyOwner {
price = _price;
}
}
|
# El isp o principio de segregación de interfaces, es un principio que
# nos dice que una clase no debe depender de métodos que no utiliza.
# Es decir, que una clase no debe depender de interfaces que no utiliza.
from abc import ABC, abstractmethod
class trabajar(ABC):
@abstractmethod
def trabajar(self):
pass
class comer(ABC):
@abstractmethod
def comer(self):
pass
class dormir(ABC):
@abstractmethod
def dormir(self):
pass
class Persona(trabajar, comer, dormir):
def trabajar(self):
return "El humano esta trabajando"
def comer(self):
return "El humano esta comiendo"
def dormir(self):
return "El humano esta durmiendo"
class Robot(trabajar):
def trabajar(self):
return "El robot esta trabajando"
arturito = Robot()
print(arturito.trabajar())
# print(arturito.comer())
# En este caso, la clase Robot no puede comer ni dormir, por lo que no
# debería heredar de las clases comer y dormir, ya que no utiliza sus
Pedro = Persona()
print(Pedro.trabajar())
print(Pedro.comer())
print(Pedro.dormir())
|
namespace chroma {
export interface Controller extends Disposable {
setValue(value: number): void;
getValue(): number;
observe(observer: (controller: Controller) => void): void;
element(): Element;
}
export class Led {
constructor(private readonly root: Element) {
}
turnOn() {
this.root.classList.add("active")
}
turnOff() {
this.root.classList.remove("active")
}
}
export class NumberInput {
private readonly observable: Observable<NumberInput> = new Observable<NumberInput>(this)
private validValue: number = 0.0
private currentValue: number = 0.0
constructor(private readonly root: HTMLInputElement) {
root.onmousedown = event => event.stopPropagation()
root.onfocus = () => this.validValue = this.value
root.onblur = () => this.value = this.validValue
root.onkeydown = (event: KeyboardEvent) => {
if (event.code === "Enter") root.blur()
}
root.oninput = () => {
const value = parseFloat(this.root.value)
if (!isNaN(value)) {
this.currentValue = this.validValue = value
this.observable.notify()
}
}
}
set value(value: number) {
this.currentValue = this.validValue = value
this.root.value = value.toString(10)
this.observable.notify()
}
get value(): number {
return this.currentValue
}
observe(observer: (input: NumberInput) => void): void {
this.observable.observe(observer)
}
}
export class Toggle {
private readonly observable: Observable<Toggle> = new Observable<Toggle>(this)
private _active: boolean
constructor(private readonly root: Element) {
this._active = root.classList.contains("active")
root.addEventListener("mousedown", event => event.stopPropagation())
root.addEventListener("click", (event) => {
event.stopPropagation()
this.toggle()
})
}
observe(observer: (toggle: Toggle) => void): void {
this.observable.observe(observer)
}
turnOn() {
this.root.classList.add("active")
this._active = true
this.notify()
}
turnOff() {
this.root.classList.remove("active")
this._active = false
this.notify()
}
set active(value: boolean) {
if (value) {
this.turnOn()
} else {
this.turnOff()
}
}
get active(): boolean {
return this._active
}
toggle() {
if (this._active) {
this.turnOff()
} else {
this.turnOn()
}
}
private notify() {
this.observable.notify()
}
}
export class Dial implements Controller {
private readonly angleRange: number
private readonly steps: number
private readonly observable: Observable<Dial> = new Observable<Dial>(this)
private _value: number = 0.0
constructor(private readonly root: HTMLElement, private readonly gear: number = 0.008) {
this.angleRange = parseFloat(root.getAttribute("angle-range"))
this.steps = parseInt(root.getAttribute("steps"))
this.update()
root.addEventListener("mousedown", (event: MouseEvent) => {
event.stopPropagation()
let beginY = event.clientY
let beginValue = this.getValue()
const mouseMove = (event: MouseEvent) => {
this.setValue(beginValue + (beginY - event.clientY) * this.gear)
}
const mouseUp = () => {
window.removeEventListener("mousemove", mouseMove)
window.removeEventListener("mouseup", mouseUp)
}
window.addEventListener("mousemove", mouseMove)
window.addEventListener("mouseup", mouseUp)
})
}
setValue(value: number) {
if (this.stepValue === this.toStepValue(value)) {
return
}
this._value = this.quantise(value)
this.update()
this.observable.notify()
}
getValue(): number {
return this._value
}
set stepValue(value: number) {
if (0 === this.steps) {
this.setValue(value)
} else {
this.setValue(value / (this.steps - 1))
}
}
get stepValue(): number {
return this.toStepValue(this._value)
}
toStepValue(value: number): number {
if (0 === this.steps) {
return value
}
return Math.round(value * (this.steps - 1))
}
observe(observer: (dial: Dial) => void): void {
this.observable.observe(observer)
}
element(): Element {
return this.root
}
private update(): void {
const angle = (-1.0 + this._value * 2.0) * this.angleRange * 0.5
this.root.style.setProperty("--angle", angle + "deg")
}
private quantise(value: number): number {
if (value < 0.0) return 0.0
if (value > 1.0) return 1.0
if (0 === this.steps) {
return value
}
const scale = this.steps - 1
return Math.round(value * scale) / scale
}
dispose(): void {
this.observable.dispose()
}
}
}
|
from pydantic import BaseModel
class Object(BaseModel):
id: int = 0
name: str
effect: str
req: list[str] = []
# def __init__(self, _name: str, _effect: str, _req=[]):
# self.name = str(_name).lower()
# self.effect = str(_effect)
# self.req = _req
def return_data(self):
info = self.easy_data()
self.update_info(info)
return info
def update_info(self, info):
# this is a way to easily update other stuff
pass
def easy_data(self):
return ({"id": self.id, "name": self.name, "effect": self.effect, "req": self.req})
class Trait(Object):
dice: int
is_passive: bool = False
# def __init__(self, _name: str, _effect: str, _req, _dice: int, _is_passive=False):
# self.name = str(_name).lower()
# self.effect = str(_effect)
# self.dice = int(_dice)
# self.is_passive = bool(_is_passive)
# if self.dice == 0:
# self.is_passive = True
# self.req = _req
def update_info(self, info):
info["dice"] = self.dice
info["is_passive"] = self.is_passive
class Item(Object):
cost: int = 0
craft: int = 0
tags: list[str]
# def __init__(self, _name: str, _effect: str, _cost: int, _craft: int, _tags, _req=[]):
# self.name = str(_name).lower()
# self.effect = str(_effect)
# self.cost = int(_cost)
# self.craft = int(_craft)
# self.tags = _tags
# self.req = _req
def update_info(self, info):
info["cost"] = self.cost
info["craft"] = self.craft
info["tags"] = self.tags
class Spell(BaseModel):
id: int = 0
name: str
effect: str
dice: int = 0
level: int = 0
tags: list[str]
# def __init__(self, _name: str, _effect: str, _dice: int, _level: int, _tags):
# self.name = str(_name).lower()
# self.effect = str(_effect)
# self.dice = int(_dice)
# self.level = int(_level)
# self.tags = _tags
def return_data(self):
return {"id": self.id, "name": self.name, "effect": self.effect, "dice": self.dice, "level": self.level, "tags": self.tags}
class DBUser(BaseModel):
id: int = 0
discord_id: int
username: str
email: str
is_admin: bool = False
avatar_url: str = ""
def compare(self,other_user: dict):
"""
This is used souly for the use of checking to see if we need to update users
"""
# You shouldent be able to change your discord id
# if self.discord_id != other_user["discord_id"]:
# return False
if self.username != other_user["username"]:
return False
if self.email != other_user["email"]:
return False
return True
class Creature(BaseModel):
id: int = 0
name: str
types: list[str] = []
level: int = 0
body: int = 0
mind: int = 0
soul: int = 0
arcana: int = 0
crafting: int = 0
charm: int = 0
thieving: int = 0
nature: int = 0
medicine: int = 0
traits: list[str] = []
spells: list[str] = []
items: list[str] = []
notes: str = ""
def output_json(self):
return {"name": self.name}
def create_textlist_from_Obj(lst):
txt = ""
for line in lst:
txt += f", {line.name}"
return txt[2:] # lop off the first "", ""
def create_textlist_from_strlist(lst):
print(lst)
print(', '.join(lst))
return ', '.join(lst)
|
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { signupThunk } from "../redux-toolkit/authSlice";
import { loginThunk } from "../redux-toolkit/authSlice";
import { useNavigate } from "react-router-dom";
import "../sass/AuthForm.scss";
export default function AuthForm(props) {
const isAuthenticated = useSelector((store) => store.auth.isAuthenticated);
const [credential, setCredential] = useState({
username: "",
password: "",
});
const dispatch = useDispatch();
const navigate = useNavigate();
useEffect(() => {
isAuthenticated && navigate("/todo");
}, [isAuthenticated, navigate]);
const handleChange = (event) => {
const { name, value } = event.target;
setCredential((prevValue) => ({
...prevValue,
[name]: value,
}));
};
return (
<div className="auth__container">
<h1 className="auth__title">{props.login}</h1>
<input
type="text"
placeholder="Username"
name="username"
onChange={handleChange}
/>
<input
type="password"
placeholder="Password"
name="password"
onChange={handleChange}
/>
<br />
<br />
<button
className="auth__btn"
onClick={() =>
dispatch(
props.login === "Register"
? signupThunk(credential)
: loginThunk(credential)
).then(() => navigate(props.login === "Signup" ? "/login" : "/todo"))
}
>
{props.login}
</button>
</div>
);
}
|
var ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur pulvinar pellentesque aliquet. Ut ullamcorper euismod dolor. Sed leo dolor, condimentum vel tortor ut, convallis semper erat. Mauris malesuada mauris id purus laoreet luctus sed non sem. Cras nunc quam, efficitur sit amet vestibulum euismod, cursus sit amet dui.";
var bio = {
name: "Robert Naccache",
role: "Front-End Designer",
contacts:
{
mobile: "+9999999",
email: "Rnaccache@ccc.gr",
github: "http://www.github.com",
twitter: "http://twitter.com",
location: "Porto Rafti"
},
welcomeMessage: "Welcome to my Resume",
skills: ["HTML", "CSS", "Javascript", "C#"],
biopic: "images/profile.png",
//Display Header
display: function()
{
//Header Name/Role
var formattedHeader = HTMLheaderName.replace("%data%", bio.name);
var formattedRole = HTMLheaderRole.replace("%data%", bio.role);
var nameDescription = formattedHeader + formattedRole;
//Contact Info
var formattedEmail = HTMLemail.replace("%data%", bio.contacts.email);
var formattedMobile = HTMLmobile.replace("%data%", bio.contacts.mobile);
var formattedGithub = HTMLgithub.replace("%data%", bio.contacts.github);
var formattedTwitter = HTMLtwitter.replace("%data%", bio.contacts.twitter);
var formattedLocation = HTMLlocation.replace("%data%", bio.contacts.location);
var contact = formattedEmail + formattedMobile + formattedGithub + formattedTwitter + formattedLocation;
//Bio picture
var formattedBioPic = HTMLbioPic.replace("%data%", bio.biopic);
var welcomeMessage = HTMLwelcomeMsg.replace("%data%", bio.welcomeMessage);
//Display above details
$("#topContacts").append(contact);
$("#header").prepend(nameDescription);
$("#header").append(formattedBioPic + welcomeMessage);
bio.displayFooter(contact);
//Iterate/display each skill if array not empty
if (bio.skills.length > 0)
{
$("#header").append(HTMLskillsStart);
bio.skills.forEach(function(skill)
{
var formattedSkill = HTMLskills.replace("%data%", skill);
$("#skills:last").append(formattedSkill);
});
}
},
//Display footer
displayFooter: function(contact)
{
console.log(contact);
$("#footerContacts").append(contact);
}
};
var work = {
jobs: [
{
employer: "CCC",
title: "RND Software Developer",
location: "Leofors kifisias 62b marrousi CCC",
dates: "01/01/2017",
description: ipsum,
url: "http://www.ccc.me"
},
{
employer: "CCC",
title: "IT Support Engineer",
location: "Leofors kifisias 62b marrousi CCC",
dates: "05/01/2012",
description: ipsum,
url: "http://www.ccc.gr"
}],
display: function()
{
work.jobs.forEach(function(job)
{
$("#workExperience").append(HTMLworkStart);
var formattedEmployer = HTMLworkEmployer.replace("%data%", job.employer);
var formattedTitle = HTMLworkTitle.replace("%data%", job.title);
var formattedLocation = HTMLworkLocation.replace("%data%", job.location);
var formattedDates = HTMLworkDates.replace("%data%", job.dates);
var formattedDescription = HTMLworkDescription.replace("%data%", job.description);
var formattedEmployerTitle = formattedEmployer + formattedTitle + formattedDates + formattedLocation + formattedDescription;
$(".work-entry:last").append(formattedEmployerTitle);
$(".work-entry:last").children("a").attr("href", job.url);
});
}
};
var projects = {
projects: [
{
title: "Portfolio 1",
dates: "15/04/2017",
description: ipsum,
images: ["https://placeimg.com/300/150/any", "https://placeimg.com/350/150/any"],
url: "http://www.yahoo.com"
},
{
title: "Portfolio 2",
dates: "24/04/2017",
description: ipsum,
images: ["https://placeimg.com/250/150/any"],
url: "http://www.google.com"
}],
display: function()
{
projects.projects.forEach(function(project)
{
$("#projects").append(HTMLprojectStart);
var formattedProjectTitle = HTMLprojectTitle.replace("%data%", project.title);
var formattedProjectDates = HTMLprojectDates.replace("%data%", project.dates);
var formattedProjectDescription = HTMLprojectDescription.replace("%data%", project.description);
var display = formattedProjectTitle + formattedProjectDates + formattedProjectDescription;
$(".project-entry:last").append(display);
$(".project-entry:last").children("a").attr("href", project.url);
project.images.forEach(function(image)
{
var formattedProjectImage = HTMLprojectImage.replace("%data%", image);
$(".project-entry:last").append(formattedProjectImage);
});
});
}
};
var education = {
schools: [
{
name: "Electrical Engineering and Electronics",
location: "Liverpool University UK",
degree: "BEng",
majors: ["Electrical Engineering", "Electronics"],
dates: "2005-2009",
url: "http://liverpool.co.uk"
},
{
name: "Microelectronic Systems & Telecommunications",
location: "Liverpool University UK",
degree: "MSc",
majors: ["Telecommunications", "Microelectronic Systems"],
dates: "2009-2010",
url: "http://liverpool.co.uk"
}],
onlineCourses: [
{
title: "Front-end Web Developer Nanodegree",
school: "Udacity",
dates: "2017 -2017",
url: "http://www.udacity.com"
}],
display: function()
{
//Format Schools
education.schools.forEach(function(school)
{
$("#education").append(HTMLschoolStart);
var formattedSchoolName = HTMLschoolName.replace("%data%", school.name);
var formattedSchoolDegree = HTMLschoolDegree.replace("%data%", school.degree);
var formattedSchoolDates = HTMLschoolDates.replace("%data%", school.dates);
var formattedLocation = HTMLschoolLocation.replace("%data%", school.location);
var formattedMajor = HTMLschoolMajor.replace("%data%", school.majors);
var formattedSchool = formattedSchoolName + formattedSchoolDegree + formattedSchoolDates + formattedLocation + formattedMajor;
$(".education-entry:last").append(formattedSchool);
$(".education-entry:last").children("a").attr("href", school.url);
});
$("#education").append(HTMLonlineClasses);
//Format Courses
education.onlineCourses.forEach(function(course)
{
$("#education").append(HTMLschoolStart);
var formattedOnlineTitle = HTMLonlineTitle.replace("%data%", course.title);
var formattedOnlineSchool = HTMLonlineSchool.replace("%data%", course.school);
var formattedOnlineDates = HTMLonlineDates.replace("%data%", course.dates);
var formattedOnlineURL = HTMLonlineURL.replace("%data%", course.url);
var formattedOnlineCourse = formattedOnlineTitle + formattedOnlineSchool + formattedOnlineDates + formattedOnlineURL;
$(".education-entry:last").append(formattedOnlineCourse);
$(".education-entry:last").children("a").attr("href", course.url);
});
}
};
function displayMap()
{
$("#mapDiv").append(googleMap);
}
//Display sections
bio.display();
work.display();
projects.display();
education.display();
displayMap();
|
import {AfterViewInit, Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {QuizItemModule} from "../../../../models/quiz-item/quiz-item.module";
import {ResultItemService} from "../../../../services/result-item.service";
import {ResultItemModule} from "../../../../models/result-item/result-item.module";
import {ResultModule} from "../../../../models/result/result.module";
import {ResultService} from "../../../../services/result.service";
import {ResponseObjectModule} from "../../../../models/response-object/response-object.module";
import {Subscription} from "rxjs";
@Component({
selector: 'app-do-quiz-item',
templateUrl: './do-quiz-item.component.html',
styleUrls: ['./do-quiz-item.component.css']
})
export class DoQuizItemComponent implements OnInit, OnDestroy, AfterViewInit {
@Input() roomId!: number;
@Input() quizItem!: QuizItemModule;
@Input() index!: number;
@Input() total!: number;
@Output() itemEvent = new EventEmitter<ResultItemModule>();
resultItem!: ResultItemModule;
observer!: Subscription;
result!: ResultModule;
isDisabled: boolean = false;
originalArray: number[] = [0, 1, 2, 3];
originalAnswers: string[] = [];
userAnswer!: string;
constructor(private resultItemService: ResultItemService,
private resultService: ResultService) {
}
ngAfterViewInit(): void {
if (this.userAnswer != null) {
this.checkAnswerAgain(parseInt(this.userAnswer));
}
}
ngOnDestroy(): void {
this.observer.unsubscribe;
console.log('destroy')
}
shuffledArray: number[] = [];
ngOnInit() {
this.userAnswer = localStorage.getItem("ans" + this.roomId + this.index);
//localStorage.setItem('isDisable', this.isDisabled);
this.resultItem = new ResultItemModule();
this.resultItem.quizItem = this.quizItem;
this.randomizeArray();
this.originalAnswers = [
this.quizItem.question.answerA,
this.quizItem.question.answerB,
this.quizItem.question.answerC,
this.quizItem.question.correctAnswer
];
this.resultService.getResultByRoomId(this.roomId);
this.observer = this.resultService.result$.subscribe(response => {
this.result = response as ResultModule;
})
console.log(this.result);
}
private randomizeArray() {
this.shuffledArray = this.shuffleArray([...this.originalArray]);
}
private shuffleArray(array: number[]): number[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
checkAnswer(ans: number) {
if (ans == 3) {
this.resultItem.userAns = "correctAnswer";
this.setCorrectAnswer(ans.toString())
localStorage.setItem("ans" + this.roomId + this.index, ans.toString());
} else if (ans == 2) {
this.resultItem.userAns = "answerC";
this.setWrongAnswer(ans.toString());
localStorage.setItem("ans" + this.roomId + this.index, ans.toString());
} else if (ans == 1) {
this.resultItem.userAns = "answerB";
this.setWrongAnswer(ans.toString());
localStorage.setItem("ans" + this.roomId + this.index, ans.toString());
} else if (ans == 0) {
this.resultItem.userAns = "answerA";
this.setWrongAnswer(ans.toString());
localStorage.setItem("ans" + this.roomId + this.index, ans.toString());
}
this.isDisabled = true;
console.log("Detail of result item: " + this.resultItem.userAns + ", " + this.quizItem.id + ", " + this.result.id);
this.observer = this.resultItemService.create(this.resultItem.userAns, this.quizItem.id, this.result.id).subscribe(
(response: any) => {
console.log(response.data);
}
)
}
private checkAnswerAgain(ans: number) {
if (ans == 3) {
this.resultItem.userAns = "correctAnswer";
this.setCorrectAnswer(ans.toString())
} else if (ans == 2) {
this.resultItem.userAns = "answerC";
this.setWrongAnswer(ans.toString());
} else if (ans == 1) {
this.resultItem.userAns = "answerB";
this.setWrongAnswer(ans.toString());
} else if (ans == 0) {
this.resultItem.userAns = "answerA";
this.setWrongAnswer(ans.toString());
}
this.isDisabled = true;
}
private setWrongAnswer(answer: string) {
const correctElement = document.getElementsByName("3").item(this.index);
correctElement.classList.add("correct");
const wrongElement = document.getElementsByName(answer.toString()).item(this.index)
wrongElement.classList.add("incorrect");
// send resultItem to parent
// this.itemEvent.emit(this.resultItem);
}
private setCorrectAnswer(answer: string) {
const correctElement = document.getElementsByName(answer).item(this.index);
correctElement.classList.add("correct");
// send resultItem to parent
// this.itemEvent.emit(this.resultItem);
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>盒子模型 —— 页面布局核心之一</title>
<style>
* {
margin: 0;
padding: 0;
}
div.box1,
div.box3,
div.shadow {
width: 100px;
height: 100px;
background-color: #ccc;
/* 给父级元素 .box3 设置margin */
margin: 30px 0px;
}
div>.box2 {
/* 不设置宽度,则不会撑大盒子 */
/* width: 100px; */
height: 50px;
/* 边框:border-width border-style border-color */
border: 5px solid pink;
/* 圆角边框: */
/* border-radius: 30%; */
border-radius: 20px;
/* 内边距:上、左右、下;上、有、下、左 */
padding: 5px;
}
.box3>div {
width: 50px;
height: 50px;
background-color: skyblue;
/* 由于和父盒子设置了同样的margin,则采用较大值 */
margin-top: 40px;
}
div.shadow {
background-color: pink;
}
div.shadow:hover {
/* 盒子阴影:垂直水平坐标 模糊距离 尺寸 颜色 inset内部阴影*/
box-shadow: 5px 5px 10px -4px rgba(0,0,0,0.3);
}
table {
width: 100px;
height: 100px;
/* 内边距 */
padding: 5px;
/* 外边距:块级盒子居中显示(必须设置宽度) */
margin: 30px auto;
/* 默认W3C盒模型 */
box-sizing: content-box;
}
/* 扩展:
行内、行内块元素水平居中只需要给父元素添加 text-align: center 即可
*/
.table,
td {
border: 1px solid skyblue;
/* 边框合并 */
border-collapse: collapse;
text-align: center;
}
</style>
</head>
<!--
盒子的组成部分:
margin + border + padding + content
盒子模型:
W3C盒模型 box-sizing: content-box 默认,宽度 = content宽度,盒子会膨胀
IE盒模型 box-sizing: border-box 宽度 = content + padding + border,盒子不膨胀
padding内边距:
不设置宽度,则padding不会撑开盒子
margin外边距:
常用于实现盒子对齐:
块级盒子 margin: 0 auto; 前提要设置宽度
行内、行内块盒子 给父元素添加 text-align: center;
注意:
嵌套块级盒子的塌陷问题:父子盒子都设置了相同的margin,则采取较大的margin显示
解决方案:
给父盒子添加 border: 1px solid transparent
给父盒子添加 padding: 1px
给父盒子添加 overflow: hidden
拓展:
浮动、固定、绝对定位 的盒子没有塌陷问题
盒子阴影:
box-shadow: h-shadow v-shadow blur spread color inset
-->
<body>
<main>
<div class="box1">
<div class="box2"></div>
</div>
<div class="box3">
<div></div>
</div>
<div class="shadow"></div>
<table class="table" cellspacing="0">
<thead>
<tr>
<td>th1</td>
<td>th2</td>
<td>th3</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
</main>
</body>
</html>
|
import { PropertyModel } from "../PropertyModel";
import { MetadataError } from "../MetadataError";
import { BinaryPropertyTable } from "./BinaryPropertyTable";
import { StringPropertyModel } from "./StringPropertyModel";
import { BooleanPropertyModel } from "./BooleanPropertyModel";
import { NumericPropertyModel } from "./NumericPropertyModel";
import { NumericArrayPropertyModel } from "./NumericArrayPropertyModel";
import { StringArrayPropertyModel } from "./StringArrayPropertyModel";
import { BooleanArrayPropertyModel } from "./BooleanArrayPropertyModel";
import { NumericBuffers } from "./NumericBuffers";
/**
* Methods related to `PropertyModel` instances that are created
* from binary data.
*
* @internal
*/
export class BinaryPropertyModels {
/**
* Creates a `PropertyModel` for the specified property in the
* given property table, based on the given binary metadata.
*
* This assumes that the input is structurally valid.
*
* This will determine the type of the property and access its
* associated data (i.e. the required buffer views data) from
* the given `BinaryMetadata`. For each type of property,
* this will return a matching implementation of the
* `PropertyModel` interface.
*
* @param propertyTable - The `PropertyTable`
* @param binaryMetadata - The `BinaryMetadata`
* @param propertyId - The property ID
* @returns The `PropertyModel`
* @throws MetadataError If the input data is not structurally
* valid
*/
static createPropertyModel(
binaryPropertyTable: BinaryPropertyTable,
propertyId: string
): PropertyModel {
// Implementation note:
// It would be nice to do some of the sanity checks upfront (e.g.
// checking that the string offsets have been defined properly
// when the type is 'STRING'). But in order to exploit the
// TypeScript definedness checks, and avoid the use of the
// non-null-assertion '!', some checks have to be done right
// before a certain value is used. It might be possible to
// find a more "elegant" solution here, but it's unlikely
// that the final, nested `if(isArray) { if (type===X) {}}`
// check could be avoided.
// Obtain the `ClassProperty`
const binaryMetadata = binaryPropertyTable.binaryMetadata;
const metadataClass = binaryMetadata.metadataClass;
const classProperties = metadataClass.properties;
if (!classProperties) {
throw new MetadataError(`The class does not define any properties`);
}
const classProperty = classProperties[propertyId];
if (!classProperty) {
throw new MetadataError(
`The class does not define property ${propertyId}`
);
}
// Obtain the `PropertyTableProperty`
const propertyTable = binaryPropertyTable.propertyTable;
const propertyTableProperties = propertyTable.properties;
if (!propertyTableProperties) {
throw new MetadataError(
`The property table does not define any properties`
);
}
const propertyTableProperty = propertyTableProperties[propertyId];
if (!propertyTableProperty) {
throw new MetadataError(
`The property table does not define property ${propertyId}`
);
}
// Obtain the required buffers from the binary data:
const binaryBufferData = binaryMetadata.binaryBufferData;
const bufferViewsData = binaryBufferData.bufferViewsData;
// Obtain the `values` buffer view data
const valuesBufferViewIndex = propertyTableProperty.values;
const valuesBufferViewData = bufferViewsData[valuesBufferViewIndex];
// Obtain the `arrayOffsets` buffer view data
const arrayOffsetsBufferViewIndex = propertyTableProperty.arrayOffsets;
let arrayOffsetsBufferViewData = undefined;
if (arrayOffsetsBufferViewIndex !== undefined) {
arrayOffsetsBufferViewData = bufferViewsData[arrayOffsetsBufferViewIndex];
}
const arrayOffsetType = propertyTableProperty.arrayOffsetType ?? "UINT32";
// Obtain the `stringOffsets` buffer view data
const stringOffsetsBufferViewIndex = propertyTableProperty.stringOffsets;
let stringOffsetsBufferViewData = undefined;
if (stringOffsetsBufferViewIndex !== undefined) {
stringOffsetsBufferViewData =
bufferViewsData[stringOffsetsBufferViewIndex];
}
const stringOffsetType = propertyTableProperty.stringOffsetType ?? "UINT32";
// Determine the `enumValueType` of the property
const enumType = classProperty.enumType;
let enumValueType = undefined;
if (enumType !== undefined) {
const binaryEnumInfo = binaryMetadata.binaryEnumInfo;
const enumValueTypes = binaryEnumInfo.enumValueTypes;
enumValueType = enumValueTypes[enumType] ?? "UINT16";
}
// Create the `PropertyModel` implementation that matches
// the type of the property
const type = classProperty.type;
const componentType = classProperty.componentType;
const count = classProperty.count;
const isArray = classProperty.array === true;
const propertyModel = BinaryPropertyModels.createPropertyModelInternal(
propertyId,
type,
componentType,
isArray,
count,
valuesBufferViewData,
arrayOffsetsBufferViewData,
arrayOffsetType,
stringOffsetsBufferViewData,
stringOffsetType,
enumValueType
);
return propertyModel;
}
/**
* Internal method to create a `PropertyModel` based on all
* the raw data elements that have been obtained from the
* `BinaryPropertyTable` for a specific property.
*
* @param propertyId - The property ID
* @param type - The type
* @param componentType - The component type
* @param isArray - Whether the property is an array
* @param count - The count (array length)
* @param valuesBufferViewData - The values data
* @param arrayOffsetsBufferViewData - The array offsets data
* @param arrayOffsetType - The array offsets type
* @param stringOffsetsBufferViewData - The string offsets data
* @param stringOffsetType - The string offsets type
* @param enumValueType - The enum value type
* @returns The `PropertyModel`
* @throws MetadataError if the given data is inconsistent
*/
static createPropertyModelInternal(
propertyId: string,
type: string,
componentType: string | undefined,
isArray: boolean,
count: number | undefined,
valuesBufferViewData: Buffer,
arrayOffsetsBufferViewData: Buffer | undefined,
arrayOffsetType: string,
stringOffsetsBufferViewData: Buffer | undefined,
stringOffsetType: string,
enumValueType: string | undefined
): PropertyModel {
if (isArray) {
if (type === "STRING") {
if (!stringOffsetsBufferViewData) {
throw new MetadataError(
`The property ${propertyId} is an array of strings, ` +
`but no string offsets have been defined`
);
}
const propertyModel = new StringArrayPropertyModel(
valuesBufferViewData,
arrayOffsetsBufferViewData,
arrayOffsetType,
stringOffsetsBufferViewData,
stringOffsetType,
count
);
return propertyModel;
}
if (type === "BOOLEAN") {
const propertyModel = new BooleanArrayPropertyModel(
valuesBufferViewData,
arrayOffsetsBufferViewData,
arrayOffsetType,
count
);
return propertyModel;
}
if (type === "ENUM") {
if (!enumValueType) {
throw new MetadataError(
`The property ${propertyId} is an enum, ` +
`but no enum value type has been defined`
);
}
const propertyModel = new NumericArrayPropertyModel(
type,
valuesBufferViewData,
enumValueType,
arrayOffsetsBufferViewData,
arrayOffsetType,
count
);
return propertyModel;
}
// The 'type' must be a numeric (array) type here
if (componentType === undefined) {
throw new MetadataError(
`The property ${propertyId} is a numeric array, ` +
`but no component type has been defined`
);
}
const propertyModel = new NumericArrayPropertyModel(
type,
valuesBufferViewData,
componentType,
arrayOffsetsBufferViewData,
arrayOffsetType,
count
);
return propertyModel;
}
// The property must be a non-array property here:
if (type === "STRING") {
if (!stringOffsetsBufferViewData) {
throw new MetadataError(
`The property ${propertyId} has the type 'STRING', ` +
`but no string offsets have been defined`
);
}
const propertyModel = new StringPropertyModel(
valuesBufferViewData,
stringOffsetsBufferViewData,
stringOffsetType
);
return propertyModel;
}
if (type === "BOOLEAN") {
const propertyModel = new BooleanPropertyModel(valuesBufferViewData);
return propertyModel;
}
if (type === "ENUM") {
if (!enumValueType) {
throw new MetadataError(
`The property ${propertyId} is an enum, ` +
`but no enum value type has been defined`
);
}
const propertyModel = new NumericPropertyModel(
type,
valuesBufferViewData,
enumValueType
);
return propertyModel;
}
// The property must be a (non-array) numeric property here
if (componentType === undefined) {
throw new MetadataError(
`The property ${propertyId} is numeric, ` +
`but no component type has been defined`
);
}
const propertyModel = new NumericPropertyModel(
type,
valuesBufferViewData,
componentType
);
return propertyModel;
}
/**
* Returns the 'slice' information that is given by an offsets
* buffer or a fixed number.
*
* This returns `{ offset, length }` for the `arrayOffsets` or
* `stringOffsets` of a property, for a given index.
*
* When the given `count` is defined, then the result will
* just be `{ index * count, count }`.
*
* Otherwise, the result will be `{ offset, length }`, where `offset`
* is the offset that is read from the given buffer at index `index`,
* and `length` is `offset[index+1] - offset[index]`.
*
* @param index - The index
* @param offsetsBuffer - The offsets
* @param offsetType - The `componentType` for the offsets
* @param count - The count
* @returns The slice information
* @throws MetadataError If both the `count` and the `offsetsBuffer`
* are `undefined`.
*/
static computeSlice(
index: number,
offsetsBuffer: Buffer | undefined,
offsetType: string,
count: number | undefined
): { offset: number; length: number } {
if (count !== undefined) {
return {
offset: index * count,
length: count,
};
}
if (!offsetsBuffer) {
throw new MetadataError(
`Neither the 'count' nor the offsets buffer have been defined`
);
}
const offset = NumericBuffers.getNumericFromBuffer(
offsetsBuffer,
index,
offsetType
);
const nextOffset = NumericBuffers.getNumericFromBuffer(
offsetsBuffer,
index + 1,
offsetType
);
const length = Number(nextOffset) - Number(offset);
return {
offset: Number(offset),
length: length,
};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.