text
stringlengths 184
4.48M
|
|---|
from app.db.repositories.base import BaseRepository
from app.models.product_details import ProductDetailsCreate, ProductDetailsInDB
GET_PRODUCT_DETAILS_BY_PRODUCT_ID_QUERY = """
SELECT id, calories, protein, carbs, fiber, sugars, fat, saturated_fat, product_id
FROM product_details
WHERE product_id = :product_id;
"""
CREATE_PRODUCT_DETAILS_QUERY = """
INSERT INTO product_details (
calories, protein, carbs, fiber, sugars, fat, saturated_fat, product_id
)
VALUES (
:calories, :protein, :carbs, :fiber, :sugars, :fat, :saturated_fat, :product_id
)
RETURNING
id, calories, protein, carbs, fiber, sugars, fat, saturated_fat, product_id;
"""
class ProductDetailsRepository(BaseRepository):
""""
All database actions associated with the ProductDetails resource
"""
async def get_product_details_by_product_id(
self, *, product_id: int
) -> ProductDetailsInDB:
product_details_record = await self.db.fetch_one(
query=GET_PRODUCT_DETAILS_BY_PRODUCT_ID_QUERY,
values={"product_id": product_id}
)
if not product_details_record:
return None
return ProductDetailsInDB(**product_details_record)
async def create_product_details(
self, *, new_product_details: ProductDetailsCreate
) -> ProductDetailsInDB:
product_details_record = await self.db.fetch_one(
query=CREATE_PRODUCT_DETAILS_QUERY,
values=new_product_details.model_dump()
)
return ProductDetailsInDB(**product_details_record)
|
-- CREO LA BASE DE DATO
CREATE DATABASE IF NOT EXISTS COMERCIO;
-- USO LA BASE DE DATOS COMERCIO
USE COMERCIO;
-- CREO LAS TABLAS
CREATE TABLE CLIENTE (
ID INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
NOMBRE VARCHAR(30) NOT NULL,
APELLIDO_1 varchar(30) NOT NULL,
APELLIDO_2 VARCHAR(30),
CIUDAD VARCHAR(100),
CATEGORIA INT
);
CREATE TABLE COMERCIAL (
ID INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
NOMBRE VARCHAR(30) NOT NULL,
APELLIDO_1 varchar(30) NOT NULL,
APELLIDO_2 VARCHAR(30),
COMISION FLOAT(8,2)
);
CREATE TABLE PEDIDO (
ID INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TOTAL DOUBLE NOT NULL,
FECHA DATE,
ID_CLIENTE INT UNSIGNED NOT NULL,
ID_COMERCIAL INT UNSIGNED NOT NULL,
FOREIGN KEY FK_ID_CLIENTE(ID_CLIENTE) REFERENCES CLIENTE(ID),
FOREIGN KEY FK_ID_COMERCIAL(ID_COMERCIAL) REFERENCES COMERCIAL(ID)
);
-- INSERTO LOS DATOS EN LAS TABLAS
INSERT INTO CLIENTE VALUES(1,'Aarón', 'Rivero', 'Gómez', 'Almería', 100);
INSERT INTO cliente VALUES(2, 'Adela', 'Salas', 'Díaz', 'Granada', 200);
INSERT INTO cliente VALUES(3, 'Adolfo', 'Rubio', 'Flores', 'Sevilla', NULL);
INSERT INTO cliente VALUES(4, 'Adrián', 'Suárez', NULL, 'Jaén', 300);
INSERT INTO cliente VALUES(5, 'Marcos', 'Loyola', 'Méndez', 'Almería', 200);
INSERT INTO cliente VALUES(6, 'María', 'Santana', 'Moreno', 'Cádiz', 100);
INSERT INTO cliente VALUES(7, 'Pilar', 'Ruiz', NULL, 'Sevilla', 300);
INSERT INTO cliente VALUES(8, 'Pepe', 'Ruiz', 'Santana', 'Huelva', 200);
INSERT INTO cliente VALUES(9, 'Guillermo', 'López', 'Gómez', 'Granada', 225);
INSERT INTO cliente VALUES(10, 'Daniel', 'Santana', 'Loyola', 'Sevilla', 125);
INSERT INTO comercial VALUES(1, 'Daniel', 'Sáez', 'Vega', 0.15);
INSERT INTO comercial VALUES(2, 'Juan', 'Gómez', 'López', 0.13);
INSERT INTO comercial VALUES(3, 'Diego','Flores', 'Salas', 0.11);
INSERT INTO comercial VALUES(4, 'Marta','Herrera', 'Gil', 0.14);
INSERT INTO comercial VALUES(5, 'Antonio','Carretero', 'Ortega', 0.12);
INSERT INTO comercial VALUES(6, 'Manuel','Domínguez', 'Hernández', 0.13);
INSERT INTO comercial VALUES(7, 'Antonio','Vega', 'Hernández', 0.11);
INSERT INTO comercial VALUES(8, 'Alfredo','Ruiz', 'Flores', 0.05);
INSERT INTO pedido VALUES(1, 150.5, '2017-10-05', 5, 2);
INSERT INTO pedido VALUES(2, 270.65, '2016-09-10', 1, 5);
INSERT INTO pedido VALUES(3, 65.26, '2017-10-05', 2, 1);
INSERT INTO pedido VALUES(4, 110.5, '2016-08-17', 8, 3);
INSERT INTO pedido VALUES(5, 948.5, '2017-09-10', 5, 2);
INSERT INTO pedido VALUES(6, 2400.6, '2016-07-27', 7, 1);
INSERT INTO pedido VALUES(7, 5760, '2015-09-10', 2, 1);
INSERT INTO pedido VALUES(8, 1983.43, '2017-10-10', 4, 6);
INSERT INTO pedido VALUES(9, 2480.4, '2016-10-10', 8, 3);
INSERT INTO pedido VALUES(10, 250.45, '2015-06-27', 8, 2);
INSERT INTO pedido VALUES(11, 75.29, '2016-08-17', 3, 7);
INSERT INTO pedido VALUES(12, 3045.6, '2017-04-25', 2, 1);
INSERT INTO pedido VALUES(13, 545.75, '2019-01-25', 6, 1);
INSERT INTO pedido VALUES(14, 145.82, '2017-02-02', 6, 1);
INSERT INTO pedido VALUES(15, 370.85, '2019-03-11', 1, 5);
INSERT INTO pedido VALUES(16, 2389.23, '2019-03-11', 1, 5);
/* 1 => CONSULTAS SOBRE UNA TABLA */
-- Devuelve todos los datos de los dos pedidos de mayor valor.
SELECT * FROM PEDIDO
ORDER BY TOTAL DESC
LIMIT 0,2;
-- Devuelve un listado con los identificadores de los clientes que han realizado algún pedido.
-- Tenga en cuenta que no debe mostrar identificadores que estén repetidos.
SELECT DISTINCT ID_CLIENTE FROM PEDIDO
WHERE TOTAL IS NOT NULL;
-- Devuelve un listado de todos los pedidos que se realizaron durante el año 2017,
-- cuya cantidad total sea superior a 500€.
SELECT * FROM PEDIDO
WHERE (TOTAL > 500) AND (FECHA BETWEEN '2017-01-01' AND '2017-12-31');
-- Devuelve un listado con el nombre y los apellidos de los comerciales que tienen una comisión
-- entre 0.05 y 0.11.
SELECT NOMBRE, APELLIDO_1, APELLIDO_2 FROM COMERCIAL
WHERE COMISION BETWEEN 0.05 AND 0.11;
-- Devuelve el valor de la comisión de mayor valor que existe en la tabla comercial.
SELECT MAX(COMISION) AS 'MAYOR COMISION' FROM COMERCIAL;
-- Devuelve un listado de los nombres de los clientes que empiezan por A y terminan por n
-- y también los nombres que empiezan por P.
-- El listado deberá estar ordenado alfabéticamente.
SELECT NOMBRE FROM CLIENTE
WHERE NOMBRE LIKE 'A%N' OR NOMBRE LIKE 'P%'
ORDER BY NOMBRE;
-- Devuelve un listado con los nombres de los comerciales que terminan por el o o. Tenga en cuenta que
-- se deberán eliminar los nombres repetidos.
SELECT DISTINCT NOMBRE FROM COMERCIAL
WHERE NOMBRE LIKE '%O' OR NOMBRE LIKE '%EL';
/* 2 => SUBCONSULTAS */
-- Devuelve un listado con todos los pedidos que ha realizado Adela Salas Díaz.
-- (Sin utilizar INNER JOIN).
SELECT * FROM PEDIDO
WHERE ID_CLIENTE = (SELECT ID FROM CLIENTE
WHERE NOMBRE = 'ADELA');
-- Devuelve el número de pedidos en los que ha participado el comercial Daniel Sáez Vega.
-- (Sin utilizar INNER JOIN)
SELECT * FROM PEDIDO
WHERE ID_COMERCIAL = (SELECT ID FROM COMERCIAL
WHERE NOMBRE = 'DANIEL' AND APELLIDO_1 = 'SAEZ');
-- Devuelve la fecha y la cantidad del pedido de menor valor realizado por el cliente Pepe Ruiz Santana.
SELECT FECHA, MIN(TOTAL) FROM PEDIDO
WHERE PEDIDO.ID_CLIENTE =
(SELECT ID FROM CLIENTE
WHERE NOMBRE = 'PEPE' AND APELLIDO_1 = 'RUIZ' AND APELLIDO_2 = 'SANTANA');
-- Devuelve un listado con los datos de los clientes y los pedidos, de todos los clientes que han
-- realizado un pedido durante el año 2017 con un valor mayor o igual al valor medio de los
-- pedidos realizados durante ese mismo año.
SELECT * FROM CLIENTE C
INNER JOIN PEDIDO P ON P.ID_CLIENTE = C.ID
WHERE P.FECHA LIKE ('2017-%-%') AND P.TOTAL > (SELECT AVG(TOTAL) FROM PEDIDO
WHERE FECHA LIKE ('2017-%-%'));
/* 3 => Subconsultas con ALL y ANY */
-- Devuelve un listado de los clientes que no han realizado ningún pedido. (Utilizando ANY o ALL).
SELECT * FROM CLIENTE
WHERE ID <ALL (SELECT ID_CLIENTE FROM PEDIDO
WHERE TOTAL = 1);
-- Devuelve un listado de los comerciales que no han realizado ningún pedido. (Utilizando ANY o ALL).
SELECT * FROM COMERCIAL
WHERE ID >=ANY (SELECT ID_COMERCIAL FROM PEDIDO
WHERE TOTAL IS NULL);
/* 4 => Subconsultas con IN y NOT IN */
-- Devuelve un listado de los clientes que no han realizado ningún pedido. (Utilizando IN o NOT IN).
SELECT * FROM CLIENTE C
INNER JOIN PEDIDO P ON P.ID_CLIENTE = C.ID
WHERE P.TOTAL IN(0);
-- BLOQUEO DE TABLA PARA LECTURA Y DESBLOQUEO
LOCK TABLES CLIENTE READ;
UNLOCK TABLES;
-- COMIENZO UNA TRANSACCION Y LA FINALIZO CON UN COMMIT PARA QUE LOS CAMBIOS SEAN PERMANENTES
START TRANSACTION;
INSERT INTO CLIENTE VALUE( 33, 'ANTONIO', 'RUIZ', 'LOBEZNO', 'MADRID', 3);
COMMIT;
SELECT * FROM CLIENTE WHERE NOMBRE = 'ANTONIO';
-- CREO UNA VISTA PARA LOS CLIENTES DE SEVILLA
CREATE VIEW CLI_SEVILLA AS
SELECT * FROM CLIENTE
WHERE CIUDAD = 'SEVILLA';
SELECT * FROM CLI_SEVILLA;
-- CREO UNA VISTA PARA EL COMERCIAL DIEGO FLORES SALAS
CREATE VIEW COM_SALAS AS
SELECT C.*
FROM COMERCIAL C
WHERE C.NOMBRE = 'DIEGO' AND C.APELLIDO_1 = 'FLORES' AND C.APELLIDO_2 = 'SALAS';
SELECT * FROM COM_SALAS;
-- BORRO LA VISTA COM_SALAS
DROP VIEW COM_SALAS;
-- CREO UNA TABLA CON LOS DATOS DE LA TABLA COMPONENTES DE LA BASE DE DATOS EQUIPOS
CREATE TABLE COMPONENTES_BACK
AS SELECT COMPONENTES.*
FROM EQUIPOS.COMPONENTES;
SELECT * FROM COMPONENTES_BACK;
DROP TABLE COMPONENTES_BACK;
-- AÑADO NUEVOS CAMPOS A LAS TABLAS
ALTER TABLE COMERCIAL ADD VACACIONES INT(2) AFTER APELLIDO_2;
SELECT * FROM COMERCIAL;
-- MODIFICO EL CAMPO VACACIONES
UPDATE COMERCIAL
SET VACACIONES = 33;
-- CREACION DE INDICE PARA BUSCAR NOMBRE Y COMISION DE COMERCIAL
CREATE INDEX COMI_COMERCIAL ON COMERCIAL(NOMBRE, COMISION);
|
# Licensed under the CC BY-NC 4.0 license (https://creativecommons.org/licenses/by-nc/4.0/)
import numpy as np
import cv2
from typing import Dict, List, Optional, Tuple
from .video_recorder import ImageEncoder
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (255, 255, 255)
COLOR_RED = (255, 0, 0)
COLOR_GREEN = (0, 255, 0)
COLOR_BLUE = (0, 0, 255)
COLOR_CYAN = (0, 255, 255)
COLOR_MAGENTA = (255, 0, 255)
COLOR_MAGENTA_2 = (255, 140, 255)
COLOR_YELLOW = (255, 255, 0)
COLOR_YELLOW_2 = (160, 160, 0)
COLOR_VIOLET = (170, 0, 255)
COLOR_BUTTER_0 = (252, 233, 79)
COLOR_BUTTER_1 = (237, 212, 0)
COLOR_BUTTER_2 = (196, 160, 0)
COLOR_ORANGE_0 = (252, 175, 62)
COLOR_ORANGE_1 = (245, 121, 0)
COLOR_ORANGE_2 = (209, 92, 0)
COLOR_CHOCOLATE_0 = (233, 185, 110)
COLOR_CHOCOLATE_1 = (193, 125, 17)
COLOR_CHOCOLATE_2 = (143, 89, 2)
COLOR_CHAMELEON_0 = (138, 226, 52)
COLOR_CHAMELEON_1 = (115, 210, 22)
COLOR_CHAMELEON_2 = (78, 154, 6)
COLOR_SKY_BLUE_0 = (114, 159, 207)
COLOR_SKY_BLUE_1 = (52, 101, 164)
COLOR_SKY_BLUE_2 = (32, 74, 135)
COLOR_PLUM_0 = (173, 127, 168)
COLOR_PLUM_1 = (117, 80, 123)
COLOR_PLUM_2 = (92, 53, 102)
COLOR_SCARLET_RED_0 = (239, 41, 41)
COLOR_SCARLET_RED_1 = (204, 0, 0)
COLOR_SCARLET_RED_2 = (164, 0, 0)
COLOR_ALUMINIUM_0 = (238, 238, 236)
COLOR_ALUMINIUM_1 = (211, 215, 207)
COLOR_ALUMINIUM_2 = (186, 189, 182)
COLOR_ALUMINIUM_3 = (136, 138, 133)
COLOR_ALUMINIUM_4 = (85, 87, 83)
COLOR_ALUMINIUM_4_5 = (66, 62, 64)
COLOR_ALUMINIUM_5 = (46, 52, 54)
class VisWaymo:
def __init__(
self,
map_valid: np.ndarray,
map_type: np.ndarray,
map_pos: np.ndarray,
map_boundary: np.ndarray,
px_per_m: float = 10.0,
video_size: int = 960,
) -> None:
# centered around ego vehicle first step, x=0, y=0, theta=0
self.px_per_m = px_per_m
self.video_size = video_size
self.px_agent2bottom = video_size // 2
# waymo
self.lane_style = [
(COLOR_WHITE, 6), # FREEWAY = 0
(COLOR_ALUMINIUM_4_5, 6), # SURFACE_STREET = 1
(COLOR_ORANGE_2, 6), # STOP_SIGN = 2
(COLOR_CHOCOLATE_2, 6), # BIKE_LANE = 3
(COLOR_SKY_BLUE_2, 4), # TYPE_ROAD_EDGE_BOUNDARY = 4
(COLOR_PLUM_2, 4), # TYPE_ROAD_EDGE_MEDIAN = 5
(COLOR_BUTTER_0, 2), # BROKEN = 6
(COLOR_MAGENTA, 2), # SOLID_SINGLE = 7
(COLOR_SCARLET_RED_2, 2), # DOUBLE = 8
(COLOR_CHAMELEON_2, 4), # SPEED_BUMP = 9
(COLOR_SKY_BLUE_0, 4), # CROSSWALK = 10
]
self.tl_style = [
COLOR_ALUMINIUM_1, # STATE_UNKNOWN = 0;
COLOR_RED, # STOP = 1;
COLOR_YELLOW, # CAUTION = 2;
COLOR_GREEN, # GO = 3;
COLOR_VIOLET, # FLASHING = 4;
]
# sdc=0, interest=1, predict=2
self.agent_role_style = [COLOR_CYAN, COLOR_CHAMELEON_2, COLOR_MAGENTA]
self.agent_cmd_txt = [
"STATIONARY", # STATIONARY = 0;
"STRAIGHT", # STRAIGHT = 1;
"STRAIGHT_LEFT", # STRAIGHT_LEFT = 2;
"STRAIGHT_RIGHT", # STRAIGHT_RIGHT = 3;
"LEFT_U_TURN", # LEFT_U_TURN = 4;
"LEFT_TURN", # LEFT_TURN = 5;
"RIGHT_U_TURN", # RIGHT_U_TURN = 6;
"RIGHT_TURN", # RIGHT_TURN = 7;
]
raster_map, self.top_left_px = self._register_map(map_boundary, self.px_per_m)
self.raster_map = self._draw_map(raster_map, map_valid, map_type, map_pos)
@staticmethod
def _register_map(map_boundary: np.ndarray, px_per_m: float, edge_px: int = 100) -> Tuple[np.ndarray, np.ndarray]:
"""
Args:
map_boundary: [4], xmin, xmax, ymin, ymax
px_per_m: float
Returns:
raster_map: empty image
top_left_px
"""
# y axis is inverted in pixel coordinate
xmin, xmax, ymax, ymin = (map_boundary * px_per_m).astype(np.int64)
ymax *= -1
ymin *= -1
xmin -= edge_px
ymin -= edge_px
xmax += edge_px
ymax += edge_px
raster_map = np.zeros([ymax - ymin, xmax - xmin, 3], dtype=np.uint8)
top_left_px = np.array([xmin, ymin], dtype=np.float32)
return raster_map, top_left_px
def _draw_map(
self,
raster_map: np.ndarray,
map_valid: np.ndarray,
map_type: np.ndarray,
map_pos: np.ndarray,
attn_weights_to_pl: Optional[np.ndarray] = None,
) -> np.ndarray:
"""
Args: numpy arrays
map_valid: [n_pl, 20], # bool
map_type: [n_pl, 11], # bool one_hot
map_pos: [n_pl, 20, 2], # float32
attn_weights_to_pl: [n_pl], sum up to 1
Returns:
raster_map
"""
mask_valid = map_valid.any(axis=1)
if attn_weights_to_pl is None:
attn_weights_to_pl = np.zeros(map_valid.shape[0]) - 1
for type_to_draw in range(len(self.lane_style)):
for i in np.where((map_type[:, type_to_draw]) & mask_valid)[0]:
color, thickness = self.lane_style[type_to_draw]
if attn_weights_to_pl[i] > 0:
color = tuple(np.array(color) * attn_weights_to_pl[i])
cv2.polylines(
raster_map,
[self._to_pixel(map_pos[i][map_valid[i]])],
isClosed=False,
color=color,
thickness=thickness,
lineType=cv2.LINE_AA,
)
# for i in range(mask_valid.shape[0]):
# if mask_valid[i]:
# cv2.arrowedLine(
# raster_map,
# self._to_pixel(map_pos[i, 0]),
# self._to_pixel(map_pos[i, 0] + (map_pos[i, 2] - map_pos[i, 0]) * 1),
# color=COLOR_CYAN,
# thickness=4,
# line_type=cv2.LINE_AA,
# tipLength=0.5,
# )
return raster_map
def save_prediction_videos(
self,
video_base_name: str,
episode: Dict[str, np.ndarray],
prediction: Optional[Dict[str, np.ndarray]],
save_agent_view: bool = True,
) -> List[str]:
"""prediction["step_current"] <= prediction["step_gt"] <= prediction["step_end"]
Args:
episode: Dict for ground truth, for t = {0, ..., prediction["step_gt"]}, 11 steps for test, 91 for train/val
"agent/valid": [n_ag, n_step/n_step_hist], bool
"agent/pos": [n_ag, n_step/n_step_hist, 2], (x,y)
"agent/yaw_bbox": [n_ag, n_step/n_step_hist, 1], [-pi, pi]
"agent/role": [n_ag, 3], one_hot [sdc=0, interest=1, predict=2]
"agent/size": [n_ag, 3], [length, width, height]
"map/valid": [n_mp, n_mp_pl_node]
"map/pos": [n_mp, n_mp_pl_node, 2], (x,y)
"tl_lane/valid": [n_tl_lane, n_step/n_step_hist], bool
"tl_lane/state": [n_tl_lane, n_step/n_step_hist, n_tl_state], bool one_hot
"tl_lane/idx": [n_tl_lane], int, -1 means not valid
"tl_stop/valid": [n_tl_stop, n_step/n_step_hist], bool
"tl_stop/state": [n_tl_stop, n_step/n_step_hist, n_tl_state], bool, one_hot
"tl_stop/pos": [n_tl_stop, 2], (x,y)
"tl_stop/dir": [n_tl_stop, 2], (x,y)
"agent/goal": not exist or [n_ag, 4], float32: (x,y,yaw,spd)
"agent/dest": not exist or [n_ag], int64: index to map [0, n_mp]
prediction: Dict, for t = {prediction["step_current"]+1, ..., prediction["step_end"]}, 80 steps
"agent/valid": [n_ag, n_step_future]
"agent/pos": [n_ag, n_step_future, 2]
"agent/yaw_bbox": [n_ag, n_step_future, 1]
"tl_lane/state": not exist or [n_tl_lane, n_step_future, n_tl_state], bool one_hot
"tl_stop/state": not exist or [n_tl_stop, n_step_future, n_tl_state], bool, one_hot
"agent/goal": not exist or [n_ag, n_step_future, 4], float32: (x,y,yaw,spd)
"agent/dest": not exist or [n_ag, n_step_future], int64: index to map [0, n_mp]
"ag_navi_valid": [n_ag, n_step_future]
"""
buffer_video = {f"{video_base_name}-gt.mp4": [[], None]} # [List[im], agent_id]
if prediction is None:
# step_current = step_end
step_end = episode["agent/valid"].shape[1] - 1
step_gt = step_end
else:
# step_current = prediction["step_current"]
step_end = prediction["step_end"]
step_gt = prediction["step_gt"]
buffer_video[f"{video_base_name}-pd.mp4"] = [[], None]
buffer_video[f"{video_base_name}-mix.mp4"] = [[], None]
if save_agent_view:
buffer_video[f"{video_base_name}-sdc.mp4"] = [[], np.where(episode["agent/role"][:, 0])[0][0]]
for i in np.where(episode["agent/role"][:, 1])[0]:
buffer_video[f"{video_base_name}-int_{i}.mp4"] = [[], i]
for i in np.where(episode["agent/role"][:, 2])[0]:
buffer_video[f"{video_base_name}-pre_{i}.mp4"] = [[], i]
n_others_to_vis = 5
idx_others = np.where(prediction["agent/valid"].any(1) & ~(episode["agent/role"].any(1)))[0]
for i in idx_others[:n_others_to_vis]:
buffer_video[f"{video_base_name}-other_{i}.mp4"] = [[], i]
for t in range(step_end + 1):
step_image = self.raster_map.copy()
t_pred = t - prediction["step_current"] - 1
# ! get the tl_lane and tl_stop to draw
if t_pred < 0 or prediction is None: # draw ground truth when prediction is not available
# [n_tl_lane], [n_tl_lane, n_tl_state]
tl_lane_valid, tl_lane_state = episode["tl_lane/valid"][:, t], episode["tl_lane/state"][:, t]
# [n_tl_stop], [n_tl_stop, n_tl_state]
tl_stop_valid, tl_stop_state = episode["tl_stop/valid"][:, t], episode["tl_stop/state"][:, t]
else: # ground truth traffic light not available
if "tl_lane/state" in prediction: # model predicted tl_lane_state
tl_lane_valid = episode["tl_lane/valid"].any(-1)
tl_lane_state = prediction["tl_lane/state"][:, t_pred]
else: # no gt, no pred -> no vis
tl_lane_valid = np.zeros_like(episode["tl_lane/valid"][:, 0])
if "tl_stop/state" in prediction: # model predicted tl_stop_state
tl_stop_valid = episode["tl_stop/valid"].any(-1)
tl_stop_state = prediction["tl_stop/state"][:, t_pred]
else: # no gt, no pred -> no vis
tl_stop_valid = np.zeros_like(episode["tl_stop/valid"][:, 0])
# ! draw loop for tl_lane
for i in range(tl_lane_valid.shape[0]):
if tl_lane_valid[i]:
lane_idx = episode["tl_lane/idx"][i]
tl_state = tl_lane_state[i].argmax()
pos = self._to_pixel(episode["map/pos"][lane_idx][episode["map/valid"][lane_idx]])
cv2.polylines(
step_image,
[pos],
isClosed=False,
color=self.tl_style[tl_state],
thickness=8,
lineType=cv2.LINE_AA,
)
if tl_state >= 1 and tl_state <= 3:
cv2.drawMarker(
step_image,
pos[-1],
color=self.tl_style[tl_state],
markerType=cv2.MARKER_TILTED_CROSS,
markerSize=10,
thickness=6,
)
# ! draw loop for tl_stop
for i in range(tl_stop_valid.shape[0]):
if tl_stop_valid[i]:
tl_state = tl_stop_state[i].argmax()
stop_point = self._to_pixel(episode["tl_stop/pos"][i])
stop_point_end = self._to_pixel(episode["tl_stop/pos"][i] + 5 * episode["tl_stop/dir"][i])
cv2.arrowedLine(
step_image,
stop_point,
stop_point_end,
color=self.tl_style[tl_state],
thickness=4,
line_type=cv2.LINE_AA,
tipLength=0.3,
)
# ! draw gt agents
step_image_gt, raster_blend_gt = step_image.copy(), np.zeros_like(step_image)
if t <= step_gt:
ag_valid = episode["agent/valid"][:, t] # [n_ag]
ag_pos = episode["agent/pos"][:, t] # [n_ag, 2]
ag_yaw_bbox = episode["agent/yaw_bbox"][:, t] # [n_ag, 1]
bbox_gt = self._to_pixel(self._get_agent_bbox(ag_valid, ag_pos, ag_yaw_bbox, episode["agent/size"]))
heading_start = self._to_pixel(ag_pos[ag_valid])
ag_yaw_bbox = ag_yaw_bbox[:, 0][ag_valid]
heading_end = self._to_pixel(
ag_pos[ag_valid] + 1.5 * np.stack([np.cos(ag_yaw_bbox), np.sin(ag_yaw_bbox)], axis=-1)
)
agent_role = episode["agent/role"][ag_valid]
for i in range(agent_role.shape[0]):
if not agent_role[i].any():
color = COLOR_ALUMINIUM_0
else:
color = self.agent_role_style[np.where(agent_role[i])[0].min()]
cv2.fillConvexPoly(step_image_gt, bbox_gt[i], color=color)
cv2.fillConvexPoly(raster_blend_gt, bbox_gt[i], color=color)
cv2.arrowedLine(
step_image_gt,
heading_start[i],
heading_end[i],
color=COLOR_BLACK,
thickness=4,
line_type=cv2.LINE_AA,
tipLength=0.6,
)
buffer_video[f"{video_base_name}-gt.mp4"][0].append(step_image_gt)
# ! draw prediction agents
if prediction is not None:
if t_pred >= 0:
step_image_pd = step_image.copy()
ag_valid = prediction["agent/valid"][:, t_pred] # # [n_ag]
ag_pos = prediction["agent/pos"][:, t_pred] # [n_ag, 2]
ag_yaw_bbox = prediction["agent/yaw_bbox"][:, t_pred] # [n_ag, 1]
bbox_pred = self._to_pixel(
self._get_agent_bbox(ag_valid, ag_pos, ag_yaw_bbox, episode["agent/size"])
)
heading_start = self._to_pixel(ag_pos[ag_valid])
ag_yaw_bbox = ag_yaw_bbox[:, 0][ag_valid]
heading_end = self._to_pixel(
ag_pos[ag_valid] + 1.5 * np.stack([np.cos(ag_yaw_bbox), np.sin(ag_yaw_bbox)], axis=-1)
)
agent_role = episode["agent/role"][ag_valid]
for i in range(agent_role.shape[0]):
if not agent_role[i].any():
color = COLOR_ALUMINIUM_0
else:
color = self.agent_role_style[np.where(agent_role[i])[0].min()]
cv2.fillConvexPoly(step_image_pd, bbox_pred[i], color=color)
cv2.arrowedLine(
step_image_pd,
heading_start[i],
heading_end[i],
color=COLOR_BLACK,
thickness=4,
line_type=cv2.LINE_AA,
tipLength=0.6,
)
step_image_mix = cv2.addWeighted(raster_blend_gt, 0.6, step_image_pd, 1, 0)
else:
step_image_pd = step_image_gt.copy()
step_image_mix = step_image_gt.copy()
buffer_video[f"{video_base_name}-pd.mp4"][0].append(step_image_pd)
buffer_video[f"{video_base_name}-mix.mp4"][0].append(step_image_mix)
# ! save agent-centric view
if save_agent_view:
for k, v in buffer_video.items():
ag_idx = v[1]
if ag_idx is not None:
text_valid = True
if t_pred < 0 or prediction is None: # draw ground truth when prediction is not available
pred_started, t_valid = False, t
if not episode["agent/valid"][ag_idx, t_valid]: # get the first valid step
text_valid = False
t_valid = np.where(episode["agent/valid"][ag_idx])[0][0]
ev_loc = self._to_pixel(episode["agent/pos"][ag_idx, t_valid])
ev_rot = episode["agent/yaw_bbox"][ag_idx, t_valid, 0]
else:
pred_started, t_valid = True, t_pred
if not prediction["agent/valid"][ag_idx, t_valid]: # get the closest valid step
text_valid = False
valid_steps = np.where(prediction["agent/valid"][ag_idx])[0]
t_valid_idx = np.abs(t_valid - valid_steps).argmin()
t_valid = valid_steps[t_valid_idx]
ev_loc = self._to_pixel(prediction["agent/pos"][ag_idx, t_valid])
ev_rot = prediction["agent/yaw_bbox"][ag_idx, t_valid, 0]
agent_view = step_image_mix.copy()
if not episode["agent/role"][ag_idx].any():
color = COLOR_ALUMINIUM_0
else:
color = self.agent_role_style[np.where(episode["agent/role"][ag_idx])[0].min()]
# draw ground-truth dest
if "agent/dest" in episode:
cv2.arrowedLine(
agent_view,
ev_loc,
self._to_pixel(episode["map/pos"][episode["agent/dest"][ag_idx], 0]),
color=COLOR_BUTTER_0,
thickness=4,
line_type=cv2.LINE_AA,
tipLength=0.05,
)
# draw ground-truth goal
if "agent/goal" in episode:
cv2.arrowedLine(
agent_view,
ev_loc,
self._to_pixel(episode["agent/goal"][ag_idx, :2]),
color=COLOR_MAGENTA,
thickness=4,
line_type=cv2.LINE_AA,
tipLength=0.05,
)
# draw predicted dest/goal
if "agent/dest" in prediction and prediction["ag_navi_valid"][ag_idx, t_valid]:
cv2.arrowedLine(
agent_view,
ev_loc,
self._to_pixel(episode["map/pos"][prediction["agent/dest"][ag_idx, t_valid], 0]),
color=COLOR_GREEN,
thickness=2,
line_type=cv2.LINE_AA,
tipLength=0.1,
)
elif "agent/goal" in prediction and prediction["ag_navi_valid"][ag_idx, t_valid]:
cv2.arrowedLine(
agent_view,
ev_loc,
self._to_pixel(prediction["agent/goal"][ag_idx, t_valid, :2]),
color=COLOR_GREEN,
thickness=2,
line_type=cv2.LINE_AA,
tipLength=0.1,
)
trans = self._get_warp_transform(ev_loc, ev_rot)
agent_view = cv2.warpAffine(agent_view, trans, (self.video_size, self.video_size))
agent_view = self._add_txt(
agent_view, episode, prediction, t_valid, ag_idx, pred_started, text_valid
)
v[0].append(agent_view)
for k, v in buffer_video.items():
encoder = ImageEncoder(k, v[0][0].shape, 20, 20)
for im in v[0]:
encoder.capture_frame(im)
encoder.close()
encoder = None
return list(buffer_video.keys())
@staticmethod
def _add_txt(
im: np.ndarray,
episode: Dict[str, np.ndarray],
prediction: Optional[Dict[str, np.ndarray]],
t: int,
idx: int,
pred_started: bool,
text_valid: bool,
line_width: int = 30,
) -> np.ndarray:
h, w, _ = im.shape
agent_view = np.zeros([h, w + 200, 3], dtype=im.dtype)
agent_view[:h, :w] = im
if (prediction is not None) and pred_started:
txt_list = [
f'id:{int(episode["episode_idx"])}',
f"valid:{int(text_valid)}",
f'nav_valid:{int(prediction["ag_navi_valid"][idx, t])}',
f'nav_reach:{int(prediction["navi_reached"][idx, t])}',
f'out:{int(prediction["outside_map_this_step"][idx, t])}/{int(prediction["outside_map"][idx, t])}',
f'col:{int(prediction["collided_this_step"][idx, t])}/{int(prediction["collided"][idx, t])}',
f'col_way:{int(prediction["collided_wosac_this_step"][idx, t])}/{int(prediction["collided_wosac"][idx, t])}',
f'red:{int(prediction["run_red_light_this_step"][idx, t])}/{int(prediction["run_red_light"][idx, t])}',
f'edge:{int(prediction["run_road_edge_this_step"][idx, t])}/{int(prediction["run_road_edge"][idx, t])}',
f'passive:{int(prediction["passive_this_step"][idx, t])}/{int(prediction["passive"][idx, t])}',
f'r_goal:{int(prediction["goal_reached_this_step"][idx, t])}/{int(prediction["goal_reached"][idx, t])}',
f'r_dest:{int(prediction["dest_reached_this_step"][idx, t])}/{int(prediction["dest_reached"][idx, t])}',
# f'x:{prediction["agent/pos"][idx, t, 0]:.2f}',
# f'y:{prediction["agent/pos"][idx, t, 1]:.2f}',
# f'yaw:{prediction["agent/yaw_bbox"][idx, t, 0]:.2f}',
# f'spd:{prediction["motion"][idx, t, 0]:.2f}',
# f'acc:{prediction["motion"][idx, t, 1]:.2f}',
# f'yaw_r:{prediction["motion"][idx, t, 2]:.2f}',
f'acc:{prediction["action"][idx, t, 0]:.2f}',
f'steer:{prediction["action"][idx, t, 1]:.2f}',
f'score:{prediction["score"][idx]:.2f}',
f'act_P:{prediction["act_P"][idx, t]:.2f}',
f"yellow:gt dest",
f"magent:gt goal",
f"green:pred",
]
# differentiable rewards
if "diffbar_reward_valid" in prediction:
txt_list.append(f'dr_valid:{int(prediction["diffbar_reward_valid"][idx, t])}')
txt_list.append(f'dr:{prediction["diffbar_reward"][idx, t]:.2f}')
txt_list.append(f'il_pos:{prediction["r_imitation_pos"][idx, t]:.2f}')
txt_list.append(f'il_rot:{prediction["r_imitation_rot"][idx, t]:.2f}')
txt_list.append(f'il_spd:{prediction["r_imitation_spd"][idx, t]:.2f}')
txt_list.append(f'rule_apx:{prediction["r_traffic_rule_approx"][idx, t]:.2f}')
else:
txt_list = [
f'id:{int(episode["episode_idx"])}',
f"valid:{int(text_valid)}",
f'x:{episode["agent/pos"][idx, t, 0]:.2f}',
f'y:{episode["agent/pos"][idx, t, 1]:.2f}',
f'yaw:{episode["agent/yaw_bbox"][idx, t, 0]:.2f}',
f'spd:{episode["agent/spd"][idx, t, 0]:.2f}',
f'role:{list(np.where(episode["agent/role"][idx])[0])}',
f'size_x:{episode["agent/size"][idx, 0]:.2f}',
f'size_y:{episode["agent/size"][idx, 1]:.2f}',
f'size_z:{episode["agent/size"][idx, 2]:.2f}',
]
for i, txt in enumerate(txt_list):
agent_view = cv2.putText(
agent_view, txt, (w, line_width * (i + 1)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 1
)
return agent_view
def _to_pixel(self, pos: np.ndarray) -> np.ndarray:
pos = pos * self.px_per_m
pos[..., 0] = pos[..., 0] - self.top_left_px[0]
pos[..., 1] = -pos[..., 1] - self.top_left_px[1]
return np.round(pos).astype(np.int32)
def _get_warp_transform(self, loc: np.ndarray, yaw: float) -> np.ndarray:
"""
loc: xy in pixel
yaw: in rad
"""
forward_vec = np.array([np.cos(yaw), -np.sin(yaw)])
right_vec = np.array([np.sin(yaw), np.cos(yaw)])
bottom_left = loc - self.px_agent2bottom * forward_vec - (0.5 * self.video_size) * right_vec
top_left = loc + (self.video_size - self.px_agent2bottom) * forward_vec - (0.5 * self.video_size) * right_vec
top_right = loc + (self.video_size - self.px_agent2bottom) * forward_vec + (0.5 * self.video_size) * right_vec
src_pts = np.stack((bottom_left, top_left, top_right), axis=0).astype(np.float32)
dst_pts = np.array([[0, self.video_size - 1], [0, 0], [self.video_size - 1, 0]], dtype=np.float32)
return cv2.getAffineTransform(src_pts, dst_pts)
@staticmethod
def _get_agent_bbox(
agent_valid: np.ndarray, agent_pos: np.ndarray, agent_yaw: np.ndarray, agent_size: np.ndarray
) -> np.ndarray:
yaw = agent_yaw[agent_valid] # n, 1
cos_yaw = np.cos(yaw)
sin_yaw = np.sin(yaw)
v_forward = np.concatenate([cos_yaw, sin_yaw], axis=-1) # n,2
v_right = np.concatenate([sin_yaw, -cos_yaw], axis=-1)
offset_forward = 0.5 * agent_size[agent_valid, 0:1] * v_forward # [n, 2]
offset_right = 0.5 * agent_size[agent_valid, 1:2] * v_right # [n, 2]
vertex_offset = np.stack(
[
-offset_forward + offset_right,
offset_forward + offset_right,
offset_forward - offset_right,
-offset_forward - offset_right,
],
axis=1,
) # n,4,2
agent_pos = agent_pos[agent_valid]
bbox = agent_pos[:, None, :].repeat(4, 1) + vertex_offset # n,4,2
return bbox
def get_dest_prob_image(
self, im_base_name: str, episode: Dict[str, np.ndarray], dest_prob: np.ndarray,
) -> Dict[str, np.ndarray]:
"""
Args:
episode: Dict for ground truth, for t = {0, ..., prediction["step_gt"]}, 11 steps for test, 91 for train/val
"agent/valid": [n_ag, n_step/n_step_hist], bool
"agent/pos": [n_ag, n_step/n_step_hist, 2], (x,y)
"agent/yaw_bbox": [n_ag, n_step/n_step_hist, 1], [-pi, pi]
"agent/role": [n_ag, 3], one_hot [sdc=0, interest=1, predict=2]
"agent/size": [n_ag, 3], [length, width, height]
"map/valid": [n_mp, n_mp_pl_node]
"map/pos": [n_mp, n_mp_pl_node, 2], (x,y)
"agent/dest": not exist or [n_ag], int64: index to map [0, n_mp]
dest_prob: [n_ag, n_mp] float prob
"""
list_im_idx = {}
list_im_idx[f"{im_base_name}-sdc.jpg"] = 0
for i in np.where(episode["agent/role"][:, 1])[0]:
list_im_idx[f"{im_base_name}-int_{i}.jpg"] = i
for i in np.where(episode["agent/role"][:, 2])[0]:
list_im_idx[f"{im_base_name}-pre_{i}.jpg"] = i
n_others_to_vis = 5
idx_others = np.where(episode["agent/valid"].any(1) & ~(episode["agent/role"].any(-1)))[0]
for i in idx_others[:n_others_to_vis]:
list_im_idx[f"{im_base_name}-other_{i}.jpg"] = i
for im_path, i in list_im_idx.items():
t = episode["agent/valid"][i].argmax()
dest_valid = dest_prob[i] > 1e-4
p_normalized = dest_prob[i, dest_valid].copy()
p_max = p_normalized.max()
p_min = p_normalized.min()
p_normalized = (p_normalized - p_min) / (p_max - p_min + 1e-4) * 3.0
m_type = np.zeros_like(episode["map/type"][dest_valid])
m_type[:, 1] = True
for k in p_normalized.argsort()[-6:]:
m_type[k, 1] = False
m_type[k, 3] = True
im = self._draw_map(
raster_map=np.zeros_like(self.raster_map),
map_valid=episode["map/valid"][dest_valid],
map_type=m_type,
map_pos=episode["map/pos"][dest_valid],
attn_weights_to_pl=p_normalized,
)
# ! draw gt_dest if available
if "agent/dest" in episode:
draw_gt_dest = self._to_pixel(episode["map/pos"][episode["agent/dest"][i]])
# [n_pl, 20]
draw_gt_dest_valid = episode["map/valid"][episode["agent/dest"][i]]
cv2.polylines(
im,
[draw_gt_dest[draw_gt_dest_valid]],
isClosed=False,
color=COLOR_MAGENTA,
thickness=2,
lineType=cv2.LINE_AA,
)
ag_pos = episode["agent/pos"][i, t]
ag_yaw_bbox = episode["agent/yaw_bbox"][i, t]
bbox_gt = self._get_agent_bbox(episode["agent/valid"][i, t], ag_pos, ag_yaw_bbox, episode["agent/size"][i])
bbox_gt = self._to_pixel(bbox_gt)
heading_start = self._to_pixel(ag_pos)
heading_end = self._to_pixel(
ag_pos + 1.5 * np.stack([np.cos(ag_yaw_bbox[0]), np.sin(ag_yaw_bbox[0])], axis=-1)
)
cv2.fillConvexPoly(im, bbox_gt, color=COLOR_RED)
cv2.arrowedLine(
im, heading_start, heading_end, color=COLOR_BLACK, thickness=4, line_type=cv2.LINE_AA, tipLength=0.6
)
cv2.imwrite(im_path, im[..., ::-1])
return list(list_im_idx.keys())
|
@model StoreProject.ViewModel.RegisterViewModel
@{
ViewData["Title"] = "Register";
var rolesValues = Enum.GetValues<CustomUserRole>();
var roles = rolesValues
.Where(c => c != CustomUserRole.Default && c != CustomUserRole.Administrator)
.Select(c => new
{
Id = (int)c,
Name = c.ToString()
})
.ToList();
var resultRoles = new SelectList(roles, nameof(Category.Id), nameof(Category.Name));
}
<h1>@ViewData["Title"]</h1>
<div class="row">
<div class="col-md-4">
<form method="post">
<h2>Create a new account.</h2>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-floating">
<input asp-for="@Model.Email" class="form-control" autocomplete="username" aria-required="true" />
<label asp-for="@Model.Email"></label>
<span asp-validation-for="@Model.Email" class="text-danger"></span>
</div>
<div class="form-floating">
<input type="password" asp-for="@Model.Password" class="form-control" aria-required="true" />
<label asp-for="@Model.Password"></label>
<span asp-validation-for="@Model.Password" class="text-danger"></span>
</div>
<div class="form-floating">
<input type="password" asp-for="@Model.ConfirmPassword" class="form-control" aria-required="true" />
<label asp-for="@Model.ConfirmPassword"></label>
<span asp-validation-for="@Model.ConfirmPassword" class="text-danger"></span>
</div>
<div class="form-floating">
<select asp-for="@Model.EnteredRole" class="form-control" asp-items="@resultRoles"></select>
<span asp-validation-for="@Model.EnteredRole" class="text-danger"></span>
</div>
<button type="submit" class="w-100 btn btn-lg btn-primary">Register</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
|
#region
using System;
#endregion
namespace DevAge.Patterns
{
/// <summary>
/// Interface to receive the callback for the activity events.
/// </summary>
public interface IActivityEvents
{
/// <summary>
/// Fired when the activity is started
/// </summary>
/// <param name="sender">Activity that have sended the event</param>
void ActivityStarted(IActivity sender);
/// <summary>
/// Fired when the activity is completed
/// </summary>
/// <param name="sender">Activity that have sended the event</param>
void ActivityCompleted(IActivity sender);
/// <summary>
/// Fired when the activity or one of its children throws an exception
/// </summary>
/// <param name="sender">Activity that have sended the event</param>
/// <param name="exception"></param>
void ActivityException(IActivity sender, Exception exception);
}
public class ActivityEventArgs : EventArgs
{
public ActivityEventArgs(IActivity activity)
{
Activity = activity;
}
public IActivity Activity { get; set; }
}
public delegate void ActivityEventHandler(object sender, ActivityEventArgs e);
public class ActivityExceptionEventArgs : ActivityEventArgs
{
public ActivityExceptionEventArgs(IActivity activity, Exception exception) : base(activity)
{
Exception = exception;
}
public Exception Exception { get; set; }
}
public delegate void ActivityExceptionEventHandler(object sender, ActivityExceptionEventArgs e);
}
|
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const axios = require('axios');
const port = process.env.PORT || 4001;
const index = require('./routes/index');
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIO(server);
let interval;
io.on('connection', socket => {
console.log('New client connected');
if(interval) {
clearInterval(interval);
}
interval = setInterval(() => getApiAndEmit(socket), 10000);
socket.on('disconnect', () => {console.log('Client disconnected')
});
});
const getApiAndEmit = async socket => {
try {
const res = await axios.get(
"https://api.darksky.net/forecast/94563199349ee746781bdf588dae0a36/43.7695,-11.2558"
);
socket.emit('FromAPI', res.data.currently.temperature)
} catch (err) {
console.log(`Error: $(err.code}`);
}
};
server.listen(port, () => console.log(`listening on port ${port}`));
|
import React from "react";
import { TextField, Box, Button, Typography, Modal } from "@mui/material";
import { useParams } from "react-router-dom";
import { useState } from "react";
import userApi from "../../requests/users";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
function TableEntry({ label, data, isEditable, onChange, name }) {
return (
<tr>
<td>{label}</td>
<td>
<TextField
hiddenLabel
name={name}
id="filled-hidden-label-small"
variant="filled"
size="small"
value={data}
disabled={!isEditable}
onChange={onChange}
sx={{ width: 500 }}
/>
</td>
</tr>
);
}
// Modified Modal from https://mui.com/material-ui/react-modal/
function ModalDelete({ open, close, fullName, mail, deleteUser }) {
const style = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "background.paper",
border: "2px solid #000",
boxShadow: 24,
p: 4,
};
return (
<div>
<Modal
open={open}
onClose={close}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<Typography id="modal-modal-title" variant="h6" component="h2">
DELETING USER!
</Typography>
<Typography id="modal-modal-description" sx={{ mt: 2 }}>
Are you sure you want to delete {fullName} with mail {mail}?
</Typography>
<Button onClick={deleteUser}>Delete</Button>
<Button onClick={close}>Cancel</Button>
</Box>
</Modal>
</div>
);
}
const emptyUser = {
email: "",
sex: "",
firstName: "",
lastName: "",
weight: "",
dob: "",
phoneNumber: "",
chronicDisease: "",
streetName: "",
doorNumber: "",
zipCode: "",
city: "",
region: "",
country: "",
};
function ViewUser() {
const mail = useParams();
const [isEditable, setIsEditable] = useState(false);
const [btnText, setBtnText] = useState("Edit");
const [user, setUser] = useState(emptyUser);
const [modalOpen, setModalOpen] = useState(false);
const navigate = useNavigate();
const fullName = user.firstName + " " + user.lastName;
const handleChange = (e) => {
setUser({
...user,
[e.target.name]: e.target.value,
});
};
useEffect(() => {
userApi.getUser(mail.id).then((user) => {
setUser(user);
});
}, [mail.id]);
const handleModalOpen = () => setModalOpen(true);
const handleModalClose = () => setModalOpen(false);
const deleteUser = () => {
userApi.deleteUser(user.email);
navigate("/admin-page/");
};
const btnDeleteClick = (e) => {
handleModalOpen();
};
const editBtnOnClick = (e) => {
if (isEditable) {
userApi.updateUser(user);
setIsEditable(false);
setBtnText("Edit");
} else {
setIsEditable(true);
setBtnText("Save");
}
};
return (
<div style={{ width: "100%" }}>
<ModalDelete
open={modalOpen}
close={handleModalClose}
fullName={fullName}
mail={user.email}
deleteUser={deleteUser}
/>
<Box
sx={{
display: "flex",
justifyContent: "space-evenly",
p: 10,
m: 1,
borderRadius: 1,
}}
>
<Box sx={{ justifyContent: "center" }}>
<table align="center">
<tbody>
<TableEntry
label="Email"
data={user.email}
isEditable={false} // Cannot be edited since it is primary key in db
/>
<TableEntry
label="Sex"
data={user.sex}
isEditable={false} // Cannot be edited since it is primary key in db
/>
<TableEntry
label="First Name"
name="firstName"
data={user.firstName}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Last Name"
name="lastName"
data={user.lastName}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Weight"
name="weight"
data={user.weight}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Date of Birth"
name="dob"
data={user.dob}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Phone Number"
name="phoneNumber"
data={user.phoneNumber}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Chronic Disease"
name="chronicDisease"
data={user.chronicDisease}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Street Name"
name="streetName"
data={user.streetName}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Door Number"
name="doorNumber"
data={user.doorNumber}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="City"
name="city"
data={user.city}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Zip Code"
name="zipCode"
data={user.zipCode}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Region"
name="region"
data={user.region}
isEditable={isEditable}
onChange={handleChange}
/>
<TableEntry
label="Country"
name="country"
data={user.country}
isEditable={isEditable}
onChange={handleChange}
/>
</tbody>
</table>
<br />
<Box
sx={{
justifyContent: "space-evenly",
display: "flex",
p: "50px 50px 10px 100px;",
}}
>
<Button
size="small"
color="primary"
variant="contained"
onClick={editBtnOnClick}
>
{btnText}
</Button>
<Button
size="small"
color="primary"
variant="contained"
onClick={btnDeleteClick}
>
Delete
</Button>
</Box>
</Box>
<Box>Insert list of trials </Box>
</Box>
</div>
);
}
export default ViewUser;
|
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.db.models import Q
from connect.storage_backends import PublicMediaStorage
# Create your models here.
GENDER = (
('Male', 'Male'),
('Female', 'Female'),
('Others', 'Others'),
('Perfer Not To Say', 'Perfer Not To Say')
)
class ProfileManager(models.Manager):
def get_all_profiles(self, me):
return Profile.objects.all().exclude(user=me)
def get_saved_posts(self, me, post_class):
saved_posts_ids = [post.object_id for post in me.saved_set.all()]
saved_posts = post_class.objects.filter(id__in=saved_posts_ids)
return saved_posts
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=255, blank=True)
last_name = models.CharField(max_length=255, blank=True)
bio = models.TextField(blank=True)
gender = models.CharField(choices=GENDER, blank=True, max_length=25)
country = models.CharField(max_length=255, blank=True)
avatar = models.ImageField(
upload_to='avatars/', null=True, blank=True)
slug = models.SlugField(unique=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
objects = ProfileManager()
def __str__(self):
return f"{self.user.username}"
@property
def get_username(self):
return self.user.username
def get_absolute_url(self):
return reverse("profiles:profile-detail-view", kwargs={"slug": self.slug})
def save(self, *args, **kwargs):
slug_text = f"{self.user.username}"
self.slug = slugify(slug_text)
return super(Profile, self).save(*args, **kwargs)
STATUS_CHOICES = (
('send', 'send'),
('accepted', 'accepted')
)
class RelationshipManager(models.Manager):
def get_all_request_by_me(self, me):
return Relationship.objects.filter(sender=me, status='send').only('receiver')
def get_all_followers(self, receiver):
return Relationship.objects.filter(receiver=receiver, status='accepted').only('sender')
def get_all_following(self, sender):
return Relationship.objects.filter(sender=sender, status='accepted').only('receiver')
def get_all_friends(self, me):
all_friends = Relationship.objects.filter(
(Q(sender=me) | Q(receiver=me)) & Q(status='accepted')).only('sender', 'receiver')
friends_profiles = []
for friend in all_friends:
if friend.sender == me:
friends_profiles.append(friend.receiver)
else:
friends_profiles.append(friend.sender)
return list(set(friends_profiles))
class Relationship(models.Model):
sender = models.ForeignKey(
Profile, on_delete=models.CASCADE, related_name='sender')
receiver = models.ForeignKey(
Profile, on_delete=models.CASCADE, related_name='receiver')
status = models.CharField(max_length=8, choices=STATUS_CHOICES)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
objects = RelationshipManager()
def __str__(self):
return f"{self.sender.user.username} - {self.receiver.user.username} - {self.status} - {self.created}"
|
import React, { useState } from 'react';
import { View, Text, StyleSheet, Button, Image, TextInput } from 'react-native';
import axios from 'axios';
export default function Principal() {
const [raçaDigitada, setRaçaDigitada] = useState('');
const [cachorro, setCachorro] = useState(null);
const [imagemCachorro, setImagemCachorro] = useState('');
const buscarDadosDaRaça = async () => {
try {
setCachorro(null);
setImagemCachorro('');
const response = await axios.get(`https://api.thedogapi.com/v1/breeds/search?q=${raçaDigitada}`);
if (response.data.length > 0) {
const breed = response.data[0];
buscarImagemDoCachorro(breed.id);
setCachorro(breed);
}
} catch (error) {
console.error('Erro ao buscar dados da raça de cachorro:', error);
}
};
const buscarImagemDoCachorro = async (breedId) => {
try {
const response = await axios.get(`https://api.thedogapi.com/v1/images/search?breed_ids=${breedId}`);
if (response.data.length > 0) {
const image = response.data[0];
setImagemCachorro(image.url);
} else {
setImagemCachorro('');
}
} catch (error) {
console.error('Erro ao buscar imagem do cachorro:', error);
}
};
return (
<View style={estilos.container}>
<TextInput
placeholder="Digite o nome da raça"
value={raçaDigitada}
onChangeText={(text) => setRaçaDigitada(text)}
style={estilos.textInput}
/>
<Button title="Buscar Raça" onPress={buscarDadosDaRaça} />
{cachorro && (
<View style={estilos.infoContainer}>
<Image style={estilos.imagem} source={{ uri: imagemCachorro || '' }} />
<Text style={estilos.texto}>Nome: {cachorro.name}</Text>
<Text style={estilos.texto}>Temperamento: {cachorro.temperament}</Text>
<Text style={estilos.texto}>Altura Média: {cachorro.height?.metric || 'Não disponível'} cm</Text>
<Text style={estilos.texto}>Estimativa de Vida: {cachorro.life_span.replace('years', 'anos')}</Text>
</View>
)}
</View>
);
}
const estilos = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'black',
alignItems: 'center',
justifyContent: 'center',
},
textInput: {
width: 200,
height: 40,
color: '#fff',
backgroundColor: '#333',
marginBottom: 10,
paddingHorizontal: 10,
},
texto: {
color: '#fff',
fontFamily: 'Times New Roman',
textAlign: 'center',
},
infoContainer: {
alignItems: 'center',
},
imagem: {
width: 210,
height: 210,
borderRadius: 10,
marginVertical: 10,
},
});
|
<?php
class podcrackController {
public function __construct() {
}
static function search_shows() {
$search_query = str_replace(' ', '+', $_GET['search-query']);
// Required values
$apiKey = $_ENV['PODCASTINDEX_API_KEY'];
$apiSecret = $_ENV['PODCASTINDEX_API_SECRET'];
$apiHeaderTime = time();
// Hash them to get the Authorization token
$hash = sha1($apiKey.$apiSecret.$apiHeaderTime);
// Set the required headers
$headers = [
"User-Agent: PodCRACK/1.0 (ZacBanas; zacbanas27@gmail.com)",
"X-Auth-Key: $apiKey",
"X-Auth-Date: $apiHeaderTime",
"Authorization: $hash"
];
// Make the request to an API endpoint
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.podcastindex.org/api/1.0/search/byterm?q=" . $search_query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Uncomment the line below to disable SSL verification (not recommended for production)
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Collect and show the results
$response = curl_exec($ch);
if ($response === false) {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
// Decode the JSON response into an associative array
$data = json_decode($response, true);
// Check if the 'feeds' key exists in the data
if (isset($data['feeds'])) {
echo json_encode($data);
} else {
echo $data;
}
}
static function search_episodes( $feed_id = false, $episode_max = false ) {
// $feed_id determines whether the method is being called via php or javascript
if (!isset($feed_id)) {
$search_query = str_replace(' ', '+', $_GET['search-query']);
}
else {
$search_query = $feed_id;
}
// Required values
$apiKey = $_ENV['PODCASTINDEX_API_KEY'];
$apiSecret = $_ENV['PODCASTINDEX_API_SECRET'];
$apiHeaderTime = time();
// Hash them to get the Authorization token
$hash = sha1($apiKey.$apiSecret.$apiHeaderTime);
// Set the required headers
$headers = [
"User-Agent: PodCRACK/1.0 (ZacBanas; zacbanas27@gmail.com)",
"X-Auth-Key: $apiKey",
"X-Auth-Date: $apiHeaderTime",
"Authorization: $hash"
];
// Make the request to an API endpoint
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.podcastindex.org/api/1.0/episodes/byfeedid?id=" . $search_query . "&pretty" . ($episode_max ? "&max=" . $episode_max : "&max=1000" . ""));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Uncomment the line below to disable SSL verification (not recommended for production)
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Collect and show the results
$response = curl_exec($ch);
if ($response === false) {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
// Decode the JSON response into an associative array
$data = json_decode($response, true);
// Check if the 'feeds' key exists in the data
if (isset($data['items'])) {
// if $feed_id then the method needs to return data to be assigned via php
// if not, then it needs to echo in order to be retrieved via js
if (!$feed_id) {
echo json_encode($data);
}
else {
return $data;
}
} else {
if (!$feed_id) {
echo $data;
}
else {
return false;
}
}
}
static function show_podcast() {
$podcast_string = urldecode($_GET['object']);
$podcast_object = json_decode($podcast_string);
$podcast_episodes = self::search_episodes( $podcast_object->id );
$_SESSION['single_podcast_object'] = $podcast_object;
$_SESSION['single_podcast_episodes'] = $podcast_episodes;
views('apps/podcrack/single-podcast.php');
}
static function index() {
// Define the file path
$filePath = '/var/www/html/apps-directory/podcrack-app/podcrack.xml';
// Check if the file exists
if (!file_exists($filePath)) {
die("File not found");
}
// Load the XML from the file
$xml = simplexml_load_file($filePath);
views('apps/podcrack/main.php', $xml);
}
static function subscribe() {
$podcast = urldecode($_GET['podcast']);
$podcast = json_decode($podcast);
// Define the file path
$filePath = '/var/www/html/apps-directory/podcrack-app/podcrack.xml';
// Check if the file exists
if (!file_exists($filePath)) {
die("File not found");
}
// Load the XML from the file
$xml = simplexml_load_file($filePath);
// Add a new podcast element (continue as in the previous example)
$newPodcast = $xml->library->addChild('podcast');
$newPodcast->addChild('id', $podcast->id);
$newPodcast->addChild('name', $podcast->title);
$newPodcast->addChild('description', $podcast->description);
$newPodcast->addChild('author', $podcast->author);
$newPodcast->addChild('artwork', $podcast->artwork);
$newPodcast->addChild('rss', $podcast->url);
$newPodcast->addChild('object', json_encode($podcast));
$newPodcast->addChild('metadata');
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
// Save the formatted XML back to the file
$dom->save($filePath);
header('Location: ' . '/apps/podcrack');
}
static function unsubscribe() {
$podcast_id = $_GET['podcast'];
$user = $_GET['user'];
// Define the file path
$filePath = '/var/www/html/apps-directory/podcrack-app/podcrack.xml';
// Check if the file exists
if (!file_exists($filePath)) {
die("File not found");
}
// Load the XML from the file using DOMDocument
$dom = new DOMDocument();
$dom->load($filePath);
$xpath = new DOMXPath($dom);
// XPath query to find the specific podcast node
$query = "/podcrack/library[@user_id='$user']/podcast[id='$podcast_id']";
$podcastNode = $xpath->query($query)->item(0);
if ($podcastNode) {
// Remove the podcast node
$podcastNode->parentNode->removeChild($podcastNode);
// Save the updated XML back to the file
$dom->save($filePath);
header('Location: ' . '/apps/podcrack');
} else {
die("Podcast not found");
}
}
}
|
require 'rails_helper'
RSpec.describe 'Dealerships Index' do
before :each do
@kendall = Dealership.create!(name: 'Kendall', offers_financing: true, offers_shuttle: false, rating: 3, created_at: Time.now - 2.days)
@lithia = Dealership.create!(name: 'Lithia', offers_financing: false, offers_shuttle: true, rating: 4, created_at: Time.now)
@power = Dealership.create!(name: 'Power', offers_financing: true, offers_shuttle: true, rating: 5, created_at: Time.now - 4.days)
end
it 'displays the name of every dealership' do
visit "/dealerships"
expect(page).to have_content(@kendall.name)
expect(page).to have_content(@lithia.name)
expect(page).to have_content(@power.name)
end
it 'sorts dealerships by most recent created_at date' do
visit "/dealerships"
expect(page).to have_content(@kendall.created_at)
expect(page).to have_content(@lithia.created_at)
expect(page).to have_content(@power.created_at)
expect(@lithia.name).to appear_before(@kendall.name)
expect(@kendall.name).to appear_before(@power.name)
end
it 'has a link to all vehicles belonging to a specific dealer ID' do
visit "/dealerships/#{@kendall.id}"
expect(page).to have_content("View Inventory")
click_on('View Inventory')
expect(current_path).to eq("/dealerships/#{@kendall.id}/vehicles")
end
it 'has a link to /dealerships' do
visit "/dealerships"
expect(page).to have_content('All Dealerships')
click_on('All Dealerships')
expect(current_path).to eq('/dealerships')
end
it 'has a link to /vehicles' do
visit "/dealerships"
expect(page).to have_content('All Vehicles')
click_on('All Vehicles')
expect(current_path).to eq('/vehicles')
end
it 'has a link to update each dealership' do
visit '/dealerships'
expect(page).to have_content("Update #{@kendall.name}")
expect(page).to have_content("Update #{@lithia.name}")
expect(page).to have_content("Update #{@power.name}")
click_on("Update #{@kendall.name}")
expect(current_path).to eq("/dealerships/#{@kendall.id}/edit")
end
end
|
#pragma once
#include <algorithm>
#include <fstream>
#include <functional>
#include <vector>
#include <iostream>
namespace s21 {
template <class T>
class BLAS;
template <class T>
class Matrix {
public:
using i_type = unsigned int;
using base = std::vector<T>;
inline static double fp_compare_precision = 1e-6;
Matrix() = default;
Matrix(i_type rows, i_type cols, T value = T());
Matrix(i_type rows);
Matrix(i_type rows, i_type cols, const base &data);
Matrix(i_type rows, i_type cols, base &&data);
Matrix(i_type rows, i_type cols, std::ifstream &is);
Matrix(std::ifstream &is);
Matrix(const std::initializer_list<std::initializer_list<T>> &data);
Matrix(i_type rows, i_type cols, const std::function<T(void)> &func);
Matrix(i_type rows, i_type cols,
const std::function<T(i_type, i_type)> &func);
Matrix(i_type rows, i_type cols, const std::function<void(T &)> &func);
Matrix(i_type rows, i_type cols,
const std::function<void(i_type, i_type, T &)> &func);
Matrix(const Matrix &other) = default;
Matrix(Matrix &&other) = default;
Matrix &operator=(const Matrix &other) = default;
Matrix &operator=(Matrix &&other) = default;
T &operator()(i_type row, i_type col);
const T &operator()(i_type row, i_type col) const;
i_type GetRows() const;
i_type GetCols() const;
i_type GetRows();
i_type GetCols();
void Fill(T value);
void Fill(const base &data);
void Fill(base &&data);
void Fill(const std::initializer_list<std::initializer_list<T>> &data);
void Fill(const std::function<T(void)> &func);
void Fill(const std::function<T(i_type, i_type)> &func);
void Fill(const std::function<void(T &)> &func);
void Fill(const std::function<void(i_type, i_type, T &)> &func);
void ForEach(const std::function<void(T &)> &f);
void ForEach(const std::function<void(i_type, i_type, T &)> &f);
void ForEach(const std::function<void(const T &)> &f) const;
void ForEach(const std::function<void(i_type, i_type, const T &)> &f) const;
struct Row;
Row operator[](i_type row);
const Row operator[](i_type row) const;
static void Sum(const Matrix &a, const Matrix &b, Matrix &c);
static void Sum(const Matrix &a, T value, Matrix &c);
static void Sub(const Matrix &a, const Matrix &b, Matrix &c);
static void Mul(const Matrix &a, const Matrix &b, Matrix &c);
static void MulABT(const Matrix &a, const Matrix &b, Matrix &c);
static void MulATB(const Matrix &a, const Matrix &b, Matrix &c);
static void Inverse(const Matrix &a, Matrix &c);
static void Mul(const Matrix &a, T value, Matrix &c);
static T Determinant(const Matrix &a);
static Matrix Minor(const Matrix &a, int row, int col);
static Matrix Transpose(const Matrix &a);
static void Divide(const Matrix &a, Matrix &b, T value);
void SetRows(i_type rows);
void Resize(i_type rows, i_type cols, T value = T());
void Resize(i_type rows, i_type cols, const std::function<T(void)> &func);
void Resize(i_type rows, i_type cols, const std::function<T(i_type, i_type)> &func);
void Resize(i_type rows, i_type cols, const std::function<void(T &)> &func);
void Resize(i_type rows, i_type cols, const std::function<void(i_type, i_type, T &)> &func);
Matrix &operator+=(const Matrix &other);
Matrix operator+(const Matrix &other) const;
Matrix &operator+=(T value);
Matrix operator+(T value) const;
Matrix &operator-=(const Matrix &other);
Matrix operator-(const Matrix &other) const;
Matrix &operator*=(const Matrix &other);
Matrix operator*(const Matrix &other) const;
Matrix &operator*=(const T &value);
Matrix operator*(const T &value) const;
bool operator==(const Matrix &other) const;
bool operator!=(const Matrix &other) const;
T *Data();
const T *Data() const;
base &DataVector();
const base &DataVector() const;
void Print(std::ostream &os = std::cout) const;
void PrintFull(std::ostream &os = std::cout) const;
void Read(std::istream &is = std::cin);
void ReadFull(std::istream &is = std::cin);
friend std::ostream &operator<<(std::ostream &os, const Matrix &matrix) {
matrix.Print(os);
return os;
}
friend std::istream &operator>>(std::istream &is, Matrix &matrix) {
matrix.Read(is);
return is;
}
private:
friend class BLAS<T>;
i_type rows_;
i_type cols_;
base data_;
};
template <class T>
Matrix<T>::Matrix(i_type rows, i_type cols, T value)
: rows_(rows), cols_(cols), data_(rows * cols, value) {}
template <class T>
Matrix<T>::Matrix(i_type rows)
: rows_(rows), cols_(rows), data_(rows * rows, T()) {}
template <class T>
Matrix<T>::Matrix(i_type rows, i_type cols, const base &data)
: rows_(rows), cols_(cols), data_(data) {}
template <class T>
Matrix<T>::Matrix(i_type rows, i_type cols, base &&data)
: rows_(rows), cols_(cols), data_(data) {}
template <class T>
Matrix<T>::Matrix(i_type rows, i_type cols, std::ifstream &is)
: rows_(rows), cols_(cols), data_(rows * cols) {
for (auto &value : data_) {
is >> value;
}
}
template <class T>
Matrix<T>::Matrix(std::ifstream &is) {
is >> rows_ >> cols_;
data_.resize(rows_ * cols_);
for (auto &value : data_) {
is >> value;
}
}
template <class T>
Matrix<T>::Matrix(const std::initializer_list<std::initializer_list<T>> &data)
: rows_(data.size()), cols_(data.begin()->size()), data_(rows_ * cols_) {
i_type i = 0;
for (const auto &row : data) {
for (const auto &value : row) {
data_[i++] = value;
}
}
}
template <class T>
Matrix<T>::Matrix(i_type rows, i_type cols, const std::function<T(void)> &func)
: rows_(rows), cols_(cols), data_(rows * cols) {
std::generate(data_.begin(), data_.end(), func);
}
template <class T>
Matrix<T>::Matrix(i_type rows, i_type cols,
const std::function<T(i_type, i_type)> &func)
: rows_(rows), cols_(cols), data_(rows * cols) {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
data_[i * cols_ + j] = func(i, j);
}
}
}
template <class T>
Matrix<T>::Matrix(i_type rows, i_type cols,
const std::function<void(T &)> &func)
: rows_(rows), cols_(cols), data_(rows * cols) {
for (auto &value : data_) {
func(value);
}
}
template <class T>
Matrix<T>::Matrix(i_type rows, i_type cols,
const std::function<void(i_type, i_type, T &)> &func)
: rows_(rows), cols_(cols), data_(rows * cols) {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
func(i, j, data_[i * cols_ + j]);
}
}
}
template <class T>
T &Matrix<T>::operator()(i_type row, i_type col) {
return data_[row * cols_ + col];
}
template <class T>
const T &Matrix<T>::operator()(i_type row, i_type col) const {
return data_[row * cols_ + col];
}
template <class T>
typename Matrix<T>::i_type Matrix<T>::GetRows() const {
return rows_;
}
template <class T>
typename Matrix<T>::i_type Matrix<T>::GetCols() const {
return cols_;
}
template <class T>
typename Matrix<T>::i_type Matrix<T>::GetRows() {
return rows_;
}
template <class T>
typename Matrix<T>::i_type Matrix<T>::GetCols() {
return cols_;
}
template <class T>
void Matrix<T>::Fill(T value) {
std::fill(data_.begin(), data_.end(), value);
}
template <class T>
void Matrix<T>::Fill(const base &data) {
data_ = data;
}
template <class T>
void Matrix<T>::Fill(base &&data) {
data_ = data;
}
template <class T>
void Matrix<T>::Fill(
const std::initializer_list<std::initializer_list<T>> &data) {
rows_ = data.size();
cols_ = data.begin()->size();
data_.resize(rows_ * cols_);
i_type i = 0;
for (const auto &row : data) {
for (const auto &value : row) {
data_[i++] = value;
}
}
}
template <class T>
void Matrix<T>::Fill(const std::function<T(void)> &func) {
std::generate(data_.begin(), data_.end(), func);
}
template <class T>
void Matrix<T>::Fill(const std::function<T(i_type, i_type)> &func) {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
data_[i * cols_ + j] = func(i, j);
}
}
}
template <class T>
void Matrix<T>::Fill(const std::function<void(T &)> &func) {
for (auto &value : data_) {
func(value);
}
}
template <class T>
void Matrix<T>::Fill(const std::function<void(i_type, i_type, T &)> &func) {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
func(i, j, data_[i * cols_ + j]);
}
}
}
template <class T>
void Matrix<T>::ForEach(const std::function<void(T &)> &f) {
for (auto &value : data_) {
f(value);
}
}
template <class T>
void Matrix<T>::ForEach(const std::function<void(i_type, i_type, T &)> &f) {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
f(i, j, data_[i * cols_ + j]);
}
}
}
template <class T>
void Matrix<T>::ForEach(const std::function<void(const T &)> &f) const {
for (const auto &value : data_) {
f(value);
}
}
template <class T>
void Matrix<T>::ForEach(
const std::function<void(i_type, i_type, const T &)> &f) const {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
f(i, j, data_[i * cols_ + j]);
}
}
}
template <class T>
struct Matrix<T>::Row {
Matrix &m;
i_type row;
Row(Matrix &matrix, i_type row) : m(matrix), row(row) {}
T &operator[](i_type col) { return m(row, col); }
};
template <class T>
typename Matrix<T>::Row Matrix<T>::operator[](i_type row) {
return Row(*this, row);
}
template <class T>
const typename Matrix<T>::Row Matrix<T>::operator[](i_type row) const {
return Row(*this, row);
}
template <class T>
void Matrix<T>::Sum(const Matrix &a, const Matrix &b, Matrix &c) {
if (a.rows_ != b.rows_ || a.cols_ != b.cols_ || a.rows_ != c.rows_ ||
a.cols_ != c.cols_) {
throw std::runtime_error("Matrix::Sum: different sizes");
}
const T *a_data = a.Data();
const T *b_data = b.Data();
T *c_data = c.Data();
for (i_type i = 0; i < a.rows_; ++i) {
for (i_type j = 0; j < a.cols_; ++j) {
c_data[i * a.cols_ + j] =
a_data[i * a.cols_ + j] + b_data[i * a.cols_ + j];
}
}
}
template <class T>
void Matrix<T>::Sum(const Matrix &a, T value, Matrix &c) {
if (a.rows_ != c.rows_ || a.cols_ != c.cols_) {
throw std::runtime_error("Matrix::Sum: different sizes");
}
const T *a_data = a.Data();
T *c_data = c.Data();
for (i_type i = 0; i < a.rows_; ++i) {
for (i_type j = 0; j < a.cols_; ++j) {
c_data[i * a.cols_ + j] = a_data[i * a.cols_ + j] + value;
}
}
}
template <class T>
void Matrix<T>::Sub(const Matrix &a, const Matrix &b, Matrix &c) {
if (a.rows_ != b.rows_ || a.cols_ != b.cols_ || a.rows_ != c.rows_ ||
a.cols_ != c.cols_) {
throw std::runtime_error("Matrix::Sub: different sizes");
}
const T *a_data = a.Data();
const T *b_data = b.Data();
T *c_data = c.Data();
for (i_type i = 0; i < a.rows_; ++i) {
for (i_type j = 0; j < a.cols_; ++j) {
c_data[i * a.cols_ + j] =
a_data[i * a.cols_ + j] - b_data[i * a.cols_ + j];
}
}
}
template <class T>
void Matrix<T>::Mul(const Matrix &a, const Matrix &b, Matrix &c) {
if (a.cols_ != b.rows_ || a.rows_ != c.rows_ || b.cols_ != c.cols_) {
throw std::runtime_error("Matrix::Mul: different sizes");
}
const T *a_data = a.Data();
const T *b_data = b.Data();
T *c_data = c.Data();
for (i_type i = 0; i < a.rows_; ++i) {
for (i_type j = 0; j < b.cols_; ++j) {
T sum = 0;
for (i_type k = 0; k < a.cols_; ++k) {
sum += a_data[i * a.cols_ + k] * b_data[k * b.cols_ + j];
}
c_data[i * b.cols_ + j] = sum;
}
}
}
template<class T>
void Matrix<T>::MulABT(const Matrix &a, const Matrix &b, Matrix &c) {
if (a.cols_ != b.cols_ || a.rows_ != c.rows_ || b.rows_ != c.cols_) {
throw std::runtime_error("Matrix::MulABT: different sizes");
}
const T *a_data = a.Data();
const T *b_data = b.Data();
T *c_data = c.Data();
for (i_type i = 0; i < a.rows_; ++i) {
for (i_type j = 0; j < b.rows_; ++j) {
T sum = 0;
for (i_type k = 0; k < a.cols_; ++k) {
sum += a_data[i * a.cols_ + k] * b_data[j * b.cols_ + k];
}
c_data[i * b.rows_ + j] = sum;
}
}
}
template<class T>
void Matrix<T>::MulATB(const Matrix &a, const Matrix &b, Matrix &c) {
if (a.rows_ != b.rows_ || a.cols_ != c.rows_ || b.cols_ != c.cols_) {
throw std::runtime_error("Matrix::MulATB: different sizes");
}
const T *a_data = a.Data();
const T *b_data = b.Data();
T *c_data = c.Data();
for (i_type i = 0; i < a.cols_; ++i) {
for (i_type j = 0; j < b.cols_; ++j) {
T sum = 0;
for (i_type k = 0; k < a.rows_; ++k) {
sum += a_data[k * a.cols_ + i] * b_data[k * b.cols_ + j];
}
c_data[i * b.cols_ + j] = sum;
}
}
}
template<class T>
void Matrix<T>::Divide(const Matrix &a, Matrix &b, T value) {
if (a.rows_ != b.rows_ || a.cols_ != b.cols_) {
throw std::runtime_error("Matrix::Divide: different sizes");
}
const T *a_data = a.Data();
T *b_data = b.Data();
for (i_type i = 0; i < a.rows_; ++i) {
for (i_type j = 0; j < a.cols_; ++j) {
b_data[i * a.cols_ + j] = a_data[i * a.cols_ + j] / value;
}
}
}
template<class T>
void Matrix<T>::Inverse(const Matrix &a, Matrix &c) {
if (a.rows_ != a.cols_ || a.rows_ != c.rows_ || a.cols_ != c.cols_) {
throw std::runtime_error("Matrix::Inverse: incorrect sizes");
}
T det = Determinant(a);
if (det == 0) {
throw std::runtime_error("Matrix::Inverse: matrix is singular (non-invertible)");
}
int n = a.rows_;
Matrix<T> minors(n, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Matrix<T> minor = Minor(a, i, j);
T minor_det = Determinant(minor);
minors(i, j) = (i + j) % 2 == 0 ? minor_det : -minor_det;
}
}
Matrix<T> adj = Transpose(minors);
Divide(adj, c, det);
}
template<class T>
T Matrix<T>::Determinant(const Matrix &a) {
if (a.rows_ != a.cols_) {
throw std::runtime_error("Matrix::Determinant: matrix is not square");
}
int n = a.rows_;
if (n == 1) {
return a(0, 0);
}
if (n == 2) {
return a(0, 0) * a(1, 1) - a(0, 1) * a(1, 0);
}
T det = 0;
for (int j = 0; j < n; j++) {
T cofactor = a(0, j) * Determinant(Minor(a, 0, j));
if (j % 2 == 0) {
det += cofactor;
} else {
det -= cofactor;
}
}
return det;
}
template<class T>
Matrix<T> Matrix<T>::Minor(const Matrix &a, int row, int col) {
Matrix minor(a.rows_ - 1, a.cols_ - 1);
int minor_row = 0;
for (int i = 0; i < a.rows_; i++) {
if (i == row) {
continue;
}
int minor_col = 0;
for (int j = 0; j < a.cols_; j++) {
if (j == col) {
continue;
}
minor(minor_row, minor_col) = a(i, j);
++minor_col;
}
++minor_row;
}
return minor;
}
template<class T>
Matrix<T> Matrix<T>::Transpose(const Matrix &a) {
Matrix<T> transpose(a.cols_, a.rows_);
for (int i = 0; i < a.rows_; i++) {
for (int j = 0; j < a.cols_; j++) {
transpose(j, i) = a(i, j);
}
}
return transpose;
}
template <class T>
void Matrix<T>::Mul(const Matrix &a, T value, Matrix &c) {
if (a.rows_ != c.rows_ || a.cols_ != c.cols_) {
throw std::runtime_error("Matrix::Mul: different sizes");
}
T *a_data = a.Data();
T *c_data = c.Data();
for (i_type i = 0; i < a.rows_; ++i) {
for (i_type j = 0; j < a.cols_; ++j) {
c_data[i * a.cols_ + j] = a_data[i * a.cols_ + j] * value;
}
}
}
template <class T>
Matrix<T> &Matrix<T>::operator+=(const Matrix &other) {
Sum(*this, other, *this);
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator+(const Matrix &other) const {
Matrix result(rows_, cols_);
Sum(*this, other, result);
return result;
}
template <class T>
Matrix<T> &Matrix<T>::operator+=(T value) {
Sum(*this, value, *this);
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator+(T value) const {
Matrix result(rows_, cols_);
Sum(*this, value, result);
return result;
}
template <class T>
Matrix<T> &Matrix<T>::operator-=(const Matrix &other) {
Sum(*this, other * -1, *this);
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator-(const Matrix &other) const {
Matrix result(rows_, cols_);
Sum(*this, other * -1, result);
return result;
}
template <class T>
Matrix<T> &Matrix<T>::operator*=(const Matrix &other) {
Mul(*this, other, *this);
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator*(const Matrix &other) const {
Matrix result(rows_, other.cols_);
Mul(*this, other, result);
return result;
}
template <class T>
Matrix<T> &Matrix<T>::operator*=(const T &value) {
Mul(*this, value, *this);
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator*(const T &value) const {
Matrix result(rows_, cols_);
Mul(*this, value, result);
return result;
}
template <class T>
bool Matrix<T>::operator==(const Matrix &other) const {
if (rows_ != other.rows_ || cols_ != other.cols_) {
return false;
}
if constexpr (std::is_floating_point_v<T>) {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
if (std::abs(data_[cols_ * i + j] - other.data_[cols_ * i + j]) >
fp_compare_precision) {
return false;
}
}
}
} else {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
if (data_[cols_ * i + j] != other.data_[cols_ * i + j]) {
return false;
}
}
}
}
return true;
}
template <class T>
bool Matrix<T>::operator!=(const Matrix &other) const {
return !(*this == other);
}
template <class T>
void Matrix<T>::Print(std::ostream &os) const {
for (i_type i = 0; i < rows_; ++i) {
for (i_type j = 0; j < cols_; ++j) {
os << data_[i * cols_ + j] << '\t';
}
os << '\n';
}
}
template <class T>
void Matrix<T>::PrintFull(std::ostream &os) const {
os << rows_ << '\t' << cols_ << '\n';
Print(os);
}
template <class T>
void Matrix<T>::Read(std::istream &is) {
for (auto &value : data_) {
is >> value;
}
}
template <class T>
void Matrix<T>::ReadFull(std::istream &is) {
is >> rows_ >> cols_;
data_.resize(rows_ * cols_);
Read(is);
}
template <class T>
T *Matrix<T>::Data() {
return data_.data();
}
template <class T>
const T *Matrix<T>::Data() const {
return data_.data();
}
template <class T>
typename Matrix<T>::base &Matrix<T>::DataVector() {
return data_;
}
template <class T>
const typename Matrix<T>::base &Matrix<T>::DataVector() const {
return data_;
}
} // namespace s21
|
import React from 'react';
import Image from 'next/image';
import useStore from '@/store';
import IconBack from '@/assets/icons/icon-back.svg';
import IconFlip from '@/assets/icons/icon-flip.svg';
import IconNext from '@/assets/icons/icon-next.svg';
import styles from './style.module.scss';
const ActionBar = () => {
const { flipped, setFlipped, undo, redo, history } = useStore((state) => ({
flipped: state.flipped,
setFlipped: state.setFlipped,
undo: state.undo,
redo: state.redo,
history: state.history,
}));
const canUndo = history.past.length > 0;
const canRedo = history.future.length > 0;
const handleActionClick = (actionType: string) => {
switch (actionType) {
case 'undo':
undo();
break;
case 'redo':
redo();
break;
case 'flip':
setFlipped(!flipped);
break;
default:
}
};
const actions = [
{
type: 'undo',
icon: IconBack,
tip: 'Undo',
disabled: !canUndo,
},
{
type: 'redo',
icon: IconNext,
tip: 'Redo',
disabled: !canRedo,
},
{
type: 'flip',
icon: IconFlip,
tip: 'Flip',
},
];
return (
<div className={styles.actionMenu}>
{actions.map((action) => (
<div
key={action.type}
className={`${styles.menuItem} ${action.disabled ? styles.disabled : ''}`}
title={action.tip}
onClick={() => handleActionClick(action.type)}
>
<Image src={action.icon} alt={action.tip} />
</div>
))}
</div>
);
}
export default ActionBar;
|
<template>
<div v-if="show" class="editEntryModal__shadow" @click.self="closeModal">
<div class="editEntryModal">
<div class="editEntryModal__close" @click="closeModal">
<svg width="2em" height="2em" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12L19 6.41Z"
></path>
</svg>
</div>
<slot name="title">
<h3 class="editEntryModal__title">Изменить запись</h3>
</slot>
<slot name="body">
<div class="editEntryModal__content">
<form @submit.prevent="handleSubmit">
<div class="newEntryModal__totalInp">
<label for="totalInp">Общее количество</label>
<input v-model="entry.total" type="number" id="totalInp" />
</div>
<div class="newEntryModal__actualInp newEntryModal__inputGroup">
<label for="totalInp">Общее количество</label>
<input v-model="entry.actual" type="number" id="actualInp" />
</div>
<button class="editEntryModal__submit" type="submit">
Отправить
</button>
</form>
</div>
</slot>
</div>
</div>
</template>
<script>
export default {
name: "EditEntryModal",
props: ["initialVals", "id"],
data: function () {
return {
show: false,
entry: {
total: 0,
actual: 0,
},
};
},
mounted() {
// console.log(this.initialVals);
this.entry = this.initialVals;
},
methods: {
closeModal() {
this.show = false;
},
handleSubmit() {
this.$store.commit("setKey", {
entry: this.entry,
level: this.id,
});
this.name = "";
this.show = false;
this.closeModal();
},
},
};
</script>
<style lang="scss">
@import "../assets/css/index.scss";
.editEntryModal {
background: #fff;
padding: 10px;
min-width: 400px;
max-width: 400px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-direction: column;
&__shadow {
position: absolute;
top: 0;
left: 0;
min-height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.4);
}
&__close {
color: #000;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 7px;
right: 7px;
width: 30px;
height: 30px;
cursor: pointer;
:hover {
background-color: #f1f1f1;
}
}
&__title {
color: $sec;
text-align: center;
margin-bottom: 10px;
}
&__inputGroup {
border-bottom: 1px solid;
margin-bottom: 20px;
}
&__nameInp {
color: $sec;
display: flex;
flex-direction: column;
> input {
margin-top: 5px;
padding: 5px;
font-size: 16px;
border: none;
background: #f1f1f1;
}
}
&__isEmpty {
color: $sec;
> input {
margin-left: 10px;
margin-bottom: 10px;
}
}
&__totalInp,
&__actualInp {
display: flex;
flex-direction: column;
border: none;
margin-bottom: 10px;
> input {
margin-top: 5px;
padding: 5px;
font-size: 16px;
border: none;
background: #f1f1f1;
}
}
&__level {
color: $sec;
margin-bottom: 10px;
display: flex;
flex-direction: column;
&-caption {
color: #666;
font-size: 14px;
}
> input {
margin-top: 5px;
padding: 5px;
font-size: 16px;
border: none;
background: #f1f1f1;
}
}
&__submit {
padding: 10px 30px;
color: $sec;
border: none;
border: 1px solid #f1f1f1;
cursor: pointer;
&:hover {
background: $sec;
color: #fff;
}
}
}
</style>
|
use http::Method;
use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
use tracing::instrument;
use types::{ClientResponse, ClientResult, PlacesResponse};
pub mod types;
pub struct ApiClient {
api_key: String,
client: ClientWithMiddleware,
}
const BASE_URL: &str = "https://maps.googleapis.com/maps/api/place";
impl ApiClient {
pub fn new(api_key: String, client: ClientWithMiddleware) -> Self {
Self { api_key, client }
}
fn get_default_request(&self, resource: &str, method: Method) -> RequestBuilder {
self.client
.request(method, format!("{BASE_URL}/{resource}"))
.query(&[("key", self.api_key.to_owned())])
}
// /findplacefromtext/json
#[instrument(skip(self))]
pub async fn get_place_by_text(
&self,
text: &str,
) -> ClientResult<ClientResponse<PlacesResponse>> {
let request = self
.get_default_request("findplacefromtext/json", Method::GET)
.query(&[
("inputtype", "textquery"),
("fields", "formatted_address,name,geometry"),
("input", text),
]);
let response = request.send().await?;
ClientResponse::from_response(response).await
}
}
|
//
// DouglasPeuckerTests.swift
//
//
// Created by Adam Wulf on 7/1/22.
//
import XCTest
@testable import Inkable
class DouglasPeuckerTests: XCTestCase {
func testDouglasPeucker() throws {
let touchId: UITouchIdentifier = UUID().uuidString
let completeEvents = [Event(id: touchId, loc: CGPoint(x: -6.19, y: -3.46), pred: false),
Event(id: touchId, loc: CGPoint(x: -4.99, y: 1.16), pred: false),
Event(id: touchId, loc: CGPoint(x: -2.79, y: -2.22), pred: false),
Event(id: touchId, loc: CGPoint(x: -1.87, y: 0.58), pred: false),
Event(id: touchId, loc: CGPoint(x: 0.77, y: 0.22), pred: false),
Event(id: touchId, loc: CGPoint(x: -1.15, y: 3.06), pred: false),
Event(id: touchId, loc: CGPoint(x: 5.33, y: -1.12), pred: false)]
let touchEvents = TouchEvent.newFrom(completeEvents)
let touchStream = TouchPathStream()
let polylineStream = PolylineStream()
let naive = NaiveDouglasPeucker(epsilon: 5.47722)
let iterative = IterativeDouglasPeucker(epsilon: 5.47722)
touchStream.nextStep(polylineStream)
polylineStream.nextStep(naive)
polylineStream.nextStep(iterative)
touchStream.produce(with: touchEvents)
let expected = Polyline(points: [polylineStream.lines[0].points.first!, polylineStream.lines[0].points.last!])
XCTAssert(naive.lines[0] == expected)
XCTAssert(iterative.lines[0] == expected)
}
func testDouglasPeucker2() throws {
let touchId: UITouchIdentifier = UUID().uuidString
let completeEvents = [Event(id: touchId, loc: CGPoint(x: 0, y: 0), pred: false),
Event(id: touchId, loc: CGPoint(x: 50, y: 1), pred: false),
Event(id: touchId, loc: CGPoint(x: 100, y: 0), pred: false)]
let touchEvents = TouchEvent.newFrom(completeEvents)
let touchStream = TouchPathStream()
let polylineStream = PolylineStream()
let naive = NaiveDouglasPeucker(epsilon: 2)
let iterative = IterativeDouglasPeucker(epsilon: 2)
touchStream.nextStep(polylineStream)
polylineStream.nextStep(naive)
polylineStream.nextStep(iterative)
touchStream.produce(with: touchEvents)
XCTAssertEqual(naive.lines[0].description, "[(0.0, 0.0),(100.0, 0.0)]")
XCTAssertEqual(iterative.lines[0].description, "[(0.0, 0.0),(100.0, 0.0)]")
}
func testNaiveDouglasPeucker3() throws {
let touchId: UITouchIdentifier = UUID().uuidString
let completeEvents = [Event(id: touchId, loc: CGPoint(x: 0, y: 0), pred: false),
Event(id: touchId, loc: CGPoint(x: 50, y: 1), pred: false),
Event(id: touchId, loc: CGPoint(x: 100, y: 0), pred: false),
Event(id: touchId, loc: CGPoint(x: 101, y: 50), pred: false),
Event(id: touchId, loc: CGPoint(x: 100, y: 100), pred: false)]
let touchEvents = TouchEvent.newFrom(completeEvents)
let touchStream = TouchPathStream()
let polylineStream = PolylineStream()
let naive = NaiveDouglasPeucker(epsilon: 2)
let iterative = IterativeDouglasPeucker(epsilon: 2)
touchStream.nextStep(polylineStream)
polylineStream.nextStep(naive)
polylineStream.nextStep(iterative)
touchStream.produce(with: touchEvents)
XCTAssertEqual(naive.lines[0].description, "[(0.0, 0.0),(100.0, 0.0),(100.0, 100.0)]")
XCTAssertEqual(iterative.lines[0].description, "[(0.0, 0.0),(100.0, 0.0),(100.0, 100.0)]")
}
func testSplitEventSmoothing() throws {
let touchId: UITouchIdentifier = UUID().uuidString
let completeEvents = [Event(id: touchId, loc: CGPoint(x: 0, y: 0), pred: false),
Event(id: touchId, loc: CGPoint(x: 50, y: 1), pred: false),
Event(id: touchId, loc: CGPoint(x: 100, y: 0), pred: false),
Event(id: touchId, loc: CGPoint(x: 101, y: 50), pred: false),
Event(id: touchId, loc: CGPoint(x: 100, y: 100), pred: false)]
let touchEvents = TouchEvent.newFrom(completeEvents)
let touchStream = TouchPathStream()
let polylineStream = PolylineStream()
let naive = NaiveDouglasPeucker()
let iterative = IterativeDouglasPeucker()
touchStream.nextStep(polylineStream)
polylineStream.nextStep(naive)
polylineStream.nextStep(iterative)
touchStream.produce(with: touchEvents)
XCTAssert(naive.lines[0] == iterative.lines[0])
for split in 0..<touchEvents.count {
let left = Array(touchEvents[0..<split])
let right = Array(touchEvents[split...])
let altTouchStream = TouchPathStream()
let altPolylineStream = PolylineStream()
let altNaive = NaiveDouglasPeucker()
let altIterative = IterativeDouglasPeucker()
altTouchStream.nextStep(altPolylineStream)
altPolylineStream.nextStep(altNaive)
altPolylineStream.nextStep(altIterative)
altTouchStream.produce(with: left)
altTouchStream.produce(with: right)
XCTAssert(naive.lines[0] == altNaive.lines[0], "failed in split \(split)")
XCTAssert(naive.lines[0] == altIterative.lines[0], "failed in split \(split)")
}
}
func testUnknownPolylineIndex() throws {
guard
let jsonFile = Bundle.module.url(forResource: "unknown-polyline-index", withExtension: "json")
else {
XCTFail("Could not load json")
return
}
for _ in 0..<10 {
try autoreleasepool {
let data = try Data(contentsOf: jsonFile)
let events = try JSONDecoder().decode([TouchEvent].self, from: data)
let touchStream = TouchPathStream()
let polylineStream = PolylineStream()
let naiveFilter = NaiveDouglasPeucker()
let iterativeFilter = NaiveDouglasPeucker()
touchStream.addConsumer(polylineStream)
polylineStream.addConsumer(naiveFilter)
polylineStream.addConsumer(iterativeFilter)
touchStream.produce(with: events)
XCTAssertEqual(naiveFilter.lines, iterativeFilter.lines)
for split in 1..<events.count {
let altStream = TouchPathStream()
let altPolylineStream = PolylineStream()
let altNaiveFilter = NaiveDouglasPeucker()
let altIterativeFilter = IterativeDouglasPeucker()
altStream.addConsumer(altPolylineStream)
altPolylineStream.addConsumer(altNaiveFilter)
altPolylineStream.addConsumer(altIterativeFilter)
altStream.produce(with: Array(events[0 ..< split]))
altStream.produce(with: Array(events[split ..< events.count]))
XCTAssertEqual(touchStream.paths, altStream.paths)
XCTAssertEqual(polylineStream.lines, altPolylineStream.lines)
XCTAssertEqual(naiveFilter.lines, altNaiveFilter.lines)
XCTAssertEqual(naiveFilter.lines, altIterativeFilter.lines)
}
}
}
}
func testCoeffs() {
let order = 3
let deriv = 0
// window = 2
var coeffs = Coeffs(index: 0, windowSize: 2)
XCTAssertEqual(coeffs.weight(-2, order, deriv), -0.08571428571428569)
XCTAssertEqual(coeffs.weight(-1, order, deriv), 0.34285714285714286)
XCTAssertEqual(coeffs.weight(0, order, deriv), 0.4857142857142857)
XCTAssertEqual(coeffs.weight(1, order, deriv), 0.34285714285714286)
XCTAssertEqual(coeffs.weight(2, order, deriv), -0.08571428571428569)
// window = 3
coeffs = Coeffs(index: 0, windowSize: 3)
XCTAssertEqual(coeffs.weight(-3, order, deriv), -0.0952380952380952)
XCTAssertEqual(coeffs.weight(-2, order, deriv), 0.14285714285714288)
XCTAssertEqual(coeffs.weight(-1, order, deriv), 0.2857142857142857)
XCTAssertEqual(coeffs.weight(0, order, deriv), 0.33333333333333337)
XCTAssertEqual(coeffs.weight(1, order, deriv), 0.2857142857142857)
XCTAssertEqual(coeffs.weight(2, order, deriv), 0.14285714285714288)
XCTAssertEqual(coeffs.weight(3, order, deriv), -0.0952380952380952)
// window = 4
coeffs = Coeffs(index: 0, windowSize: 4)
XCTAssertEqual(coeffs.weight(-4, order, deriv), -0.09090909090909091)
XCTAssertEqual(coeffs.weight(-3, order, deriv), 0.060606060606060615)
XCTAssertEqual(coeffs.weight(-2, order, deriv), 0.16883116883116883)
XCTAssertEqual(coeffs.weight(-1, order, deriv), 0.2337662337662338)
XCTAssertEqual(coeffs.weight(0, order, deriv), 0.2554112554112554)
XCTAssertEqual(coeffs.weight(1, order, deriv), 0.2337662337662338)
XCTAssertEqual(coeffs.weight(2, order, deriv), 0.16883116883116883)
XCTAssertEqual(coeffs.weight(3, order, deriv), 0.060606060606060615)
XCTAssertEqual(coeffs.weight(4, order, deriv), -0.09090909090909091)
// window = 12
coeffs = Coeffs(index: 0, windowSize: 12)
XCTAssertEqual(coeffs.weight(-12, order, deriv), -0.04888888888888888)
XCTAssertEqual(coeffs.weight(-11, order, deriv), -0.026666666666666665)
XCTAssertEqual(coeffs.weight(-10, order, deriv), -0.0063768115942028775)
XCTAssertEqual(coeffs.weight(-9, order, deriv), 0.011980676328502408)
XCTAssertEqual(coeffs.weight(-8, order, deriv), 0.028405797101449276)
XCTAssertEqual(coeffs.weight(-7, order, deriv), 0.042898550724637684)
XCTAssertEqual(coeffs.weight(-6, order, deriv), 0.05545893719806763)
XCTAssertEqual(coeffs.weight(-5, order, deriv), 0.06608695652173913)
XCTAssertEqual(coeffs.weight(-4, order, deriv), 0.07478260869565218)
XCTAssertEqual(coeffs.weight(-3, order, deriv), 0.08154589371980676)
XCTAssertEqual(coeffs.weight(-2, order, deriv), 0.0863768115942029)
XCTAssertEqual(coeffs.weight(-1, order, deriv), 0.08927536231884058)
XCTAssertEqual(coeffs.weight(0, order, deriv), 0.0902415458937198)
XCTAssertEqual(coeffs.weight(1, order, deriv), 0.08927536231884058)
XCTAssertEqual(coeffs.weight(2, order, deriv), 0.0863768115942029)
XCTAssertEqual(coeffs.weight(3, order, deriv), 0.08154589371980676)
XCTAssertEqual(coeffs.weight(4, order, deriv), 0.07478260869565218)
XCTAssertEqual(coeffs.weight(5, order, deriv), 0.06608695652173913)
XCTAssertEqual(coeffs.weight(6, order, deriv), 0.05545893719806763)
XCTAssertEqual(coeffs.weight(7, order, deriv), 0.042898550724637684)
XCTAssertEqual(coeffs.weight(8, order, deriv), 0.028405797101449276)
XCTAssertEqual(coeffs.weight(9, order, deriv), 0.011980676328502408)
XCTAssertEqual(coeffs.weight(10, order, deriv), -0.0063768115942028775)
XCTAssertEqual(coeffs.weight(11, order, deriv), -0.026666666666666665)
XCTAssertEqual(coeffs.weight(12, order, deriv), -0.04888888888888888)
}
}
|
// 1번
package d4Queue;
// 큐의 형태로 데이터를 관리하는 클래스
public class MyQueue {
private int[] arr = new int[16];
// 제일 앞의 데이터가 어딘지 확인하기 위한 front(데이터를 뺄 때 어디의 데이터를 뺄지를 결정하는)
private int front = -1;
// 제일 뒤의 데이터가 어딘지 나타내는 rear (데이터를 넣을 때 어디에 넣을지를 결정하는)
private int rear = -1;
// 데이터를 큐에 담기 위한 enQueue
public void enQueue(int x) {
// 넣어줄 공간을 설정하고
rear++;
// 해당 위치에 넣어준다.
arr[rear] = x;
}
// 데이터를 꺼내기 위한 deQueue
public int deQueue() {
// 데이터를 가져올 공간을 설정하고
front++;
// 해당 위치에서 가져온다.
return arr[front];
}
// Queue가 비어있는지 확인하기 위한 isEmpty
public boolean isEmpty() {
// front와 rear가 같은 index를 가리키면 비워있는 것이다.
return this.front == this.rear;
}
// 잘못된 포화 상태 인식
// 큐가 채워져있는지 확인하기 위한 isFull()
public boolean isFull() {
// front가 이동한 상황은 고려가 되지 않는다. (데이터를 deQueue한 것을 고려하지 않는다.)
// 배열의 길이만큼 데이터를 넣는다면 더이상 쓰지 못한다.
return this.rear == arr.length -1;
}
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.enQueue(10);
myQueue.enQueue(11);
myQueue.enQueue(12);
System.out.println(myQueue.isEmpty()); // false
System.out.println(myQueue.deQueue()); // 10
System.out.println(myQueue.deQueue()); // 11
System.out.println(myQueue.deQueue()); // 12
// 들어있는 데이터는 0개
System.out.println(myQueue.isEmpty()); // true
for (int i = 0; i < 13; i++) {
myQueue.enQueue(i);
}
// 들어있는 데이터는 12개
System.out.println(myQueue.deQueue());
// 남은 공간이 4칸이어도 가득찼다고 인식한다.
System.out.println(myQueue.isFull());
// myQueue.enQueue(10); // 오류
}
}
|
import { Box, Button, Paper } from "@mui/material";
import { useEffect, useReducer } from "react";
import CheckCircleOutlineSharpIcon from "@mui/icons-material/CheckCircleOutlineSharp";
import CheckCircleSharpIcon from "@mui/icons-material/CheckCircleSharp";
import CheckBoxOutlineBlankSharpIcon from "@mui/icons-material/CheckBoxOutlineBlankSharp";
import CheckBoxSharpIcon from "@mui/icons-material/CheckBoxSharp";
import '../styles/components/reviewList.css'
interface State {
showAll: boolean;
showFinished: boolean;
showDNF: boolean;
showStars: string | null;
}
type Action =
| { type: "SHOW_ALL" }
| { type: "SHOW_FINISHED" }
| { type: "SHOW_DNF" }
| { type: "SHOW_STARS"; payload: string }
| { type: "UNCHECK" };
interface SortProps {
onSortChange: (finished: string, stars: string) => void;
setFinished: (finished: string) => void;
setStars: (stars: string) => void;
}
export default function Sort({ onSortChange, setFinished, setStars }: SortProps) {
const sortingReducer = (state: State, action: Action) => {
switch (action.type) {
case "SHOW_ALL":
return { ...state, showAll: true, showFinished: false, showDNF: false, showStars: null };
case "SHOW_FINISHED":
return { ...state, showAll: false, showFinished: true, showDNF: false, showStars: null };
case "SHOW_DNF":
return { ...state, showAll: false, showFinished: false, showDNF: true, showStars: null };
case "SHOW_STARS":
return { ...state, showAll: false, showFinished: false, showDNF: false, showStars: action.payload };
case "UNCHECK":
return { ...state, showAll: true, showFinished: false, showDNF: false, showStars: null };
default:
return state;
}
};
const initialState: State = {
showAll: true,
showFinished: false,
showDNF: false,
showStars: null,
};
const [state, dispatch] = useReducer(sortingReducer, initialState);
useEffect(() => {
onSortChange(state.showFinished ? "Finished" : state.showDNF ? "DNF" : "", state.showStars || "");
}, [onSortChange, state.showAll, state.showDNF, state.showFinished, state.showStars]);
const handleButtonClick = (type: "SHOW_ALL" | "SHOW_FINISHED" | "SHOW_DNF" | "SHOW_STARS" | "UNCHECK", payload: string | null = null) => {
if (type === "SHOW_ALL") {
dispatch({ type: "SHOW_ALL" });
setFinished("");
setStars("");
} else if (type === "SHOW_FINISHED") {
if (state.showFinished) {
dispatch({ type: "UNCHECK" });
setFinished("");
} else {
dispatch({ type: "SHOW_FINISHED" });
setFinished("Finished");
}
setStars("");
} else if (type === "SHOW_DNF") {
if (state.showDNF) {
dispatch({ type: "UNCHECK" });
setFinished("");
} else {
dispatch({ type: "SHOW_DNF" });
setFinished("DNF");
}
setStars("");
} else if (type === "SHOW_STARS") {
if (state.showStars === payload) {
dispatch({ type: "UNCHECK" });
setStars("");
} else {
dispatch({ type: "SHOW_STARS", payload: payload! });
setStars(payload!);
}
setFinished(""); // Reset finished filter
} else if (type === "UNCHECK") {
dispatch({ type: "UNCHECK" });
setFinished("");
setStars("");
}
};
return (
<Paper className="sort-form">
<Box>
<Button onClick={() => handleButtonClick("SHOW_ALL")}>
{state.showAll ? <CheckCircleSharpIcon /> : <CheckCircleOutlineSharpIcon />} All
</Button>
<br />
<Button onClick={() => handleButtonClick("SHOW_FINISHED")}>
{state.showFinished ? <CheckBoxSharpIcon /> : <CheckBoxOutlineBlankSharpIcon />} Finished
</Button>
<Button onClick={() => handleButtonClick("SHOW_DNF")}>
{state.showDNF ? <CheckBoxSharpIcon /> : <CheckBoxOutlineBlankSharpIcon />} Did Not Finish
</Button>
</Box>
<br />
<Box>
{[1, 2, 3, 4, 5].map((stars) => (
<Button key={stars} onClick={() => handleButtonClick("SHOW_STARS", stars.toString())}>
{state.showStars === stars.toString() ? <CheckCircleSharpIcon /> : <CheckCircleOutlineSharpIcon />} {stars} Stars
</Button>
))}
</Box>
</Paper>
);
}
|
package org.bus.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import java.util.List;
@Entity
@Table(name="route")
public class Route {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer routeId;
@Column(name="routeFrom", nullable=false)
private String routeFrom;
@Column(name="routeTo", nullable=false)
private String routeTo;
@Column(name="distance", nullable=false)
private Integer distance;
@OneToMany
private List<Bus> busList;
public Route() {
}
public Route(Integer routeId, String routeFrom, String routeTo, Integer distance) {
this.routeId = routeId;
this.routeFrom = routeFrom;
this.routeTo = routeTo;
this.distance = distance;
}
public Integer getRouteId() {
return routeId;
}
public void setRouteId(Integer routeId) {
this.routeId = routeId;
}
public String getRouteFrom() {
return routeFrom;
}
public void setRouteFrom(String routeFrom) {
this.routeFrom = routeFrom;
}
public String getRouteTo() {
return routeTo;
}
public void setRouteTo(String routeTo) {
this.routeTo = routeTo;
}
public Integer getDistance() {
return distance;
}
public void setDistance(Integer distance) {
this.distance = distance;
}
@Override
public String toString() {
return "Route{" +
"routeId=" + routeId +
", routeFrom='" + routeFrom + '\'' +
", routeTo='" + routeTo + '\'' +
", distance=" + distance +
", busList=" + busList +
'}';
}
}
|
import { addDoc, collection, serverTimestamp } from "firebase/firestore";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { TagsInput } from "react-tag-input-component";
import { db, storage } from "../../firebase";
import "./CreateBlog.css";
const CreateBlog = ({ user }) => {
const navigate = useNavigate();
const [tags, setTags] = useState([]);
const [blogData, setBlogData] = useState({
title: "",
trending: "no",
category: "",
description: "",
imageUrl: "",
});
const [loading, setLoading] = useState(false);
const [progress, setProgress] = useState(0);
const [file, setFile] = useState(null);
const { title, trending, category, description } = blogData;
useEffect(() => {
const uploadFile = () => {
const blogImageRef = ref(storage, `blogImage/${file.name + Date.now()}`);
const uploadTask = uploadBytesResumable(blogImageRef, file);
uploadTask.on(
"state_changed",
() => {
setLoading(true);
},
(err) => console.log(err),
() => {
getDownloadURL(uploadTask.snapshot.ref)
.then((url) => {
setBlogData({ ...blogData, imageUrl: url });
setLoading(false);
})
.catch((error) => console.log(error));
}
);
};
file && uploadFile();
}, [file]);
const handleChange = (e) => {
setBlogData({ ...blogData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
//console.log({ ...blogData, tags });
const { title, category, description, trending } = blogData;
if (!title || !category || !description || !trending) {
return alert("Please, fill all the fields.");
}
try {
setLoading(true);
const docRef = await addDoc(collection(db, "blogs"), {
...blogData,
tags,
createdAt: serverTimestamp(),
author: user?.displayName,
authorId: user?.uid,
});
setLoading(false);
navigate("/");
} catch (error) {
alert(error.message);
setLoading(false);
}
};
return (
<>
<section className="createBlog">
<div className="container">
<h2>Write What You Want to Share</h2>
<form onSubmit={handleSubmit}>
<input
type="text"
name="title"
placeholder="Title"
value={title}
onChange={handleChange}
/>
<TagsInput
value={tags}
onChange={setTags}
name="tags"
placeHolder="Tags"
/>
<div className="trendingDiv">
<span>Is it trending?</span>
<input
type="radio"
name="trending"
value="yes"
onChange={handleChange}
required
/>{" "}
Yes
<input
type="radio"
name="trending"
value="no"
onChange={handleChange}
required
/>{" "}
No
</div>
<select name="category" value={category} onChange={handleChange}>
<option>Select a Category</option>
<option value="sports">Sports</option>
<option value="fashion">Fashion</option>
<option value="technology">Technology</option>
<option value="business">Business</option>
</select>
<textarea
name="description"
style={{ resize: "none" }}
cols="30"
rows="10"
placeholder="Description"
value={description}
onChange={handleChange}
></textarea>
<input type="file" onChange={(e) => setFile(e.target.files[0])} />
<input type="submit" value="Create" disabled={loading} />
</form>
</div>
</section>
</>
);
};
export default CreateBlog;
|
/*
Copyright 2017, 2018 Jeffrey Zhang
This file is part of ProjectFiasco.
ProjectFiasco 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.
ProjectFiasco 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 ProjectFiasco. If not, see <http://www.gnu.org/licenses/>.
The MIT License (MIT)
Copyright (c) 2018 Microsoft Corp
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <memory>
#include "SpriteFont.h"
#include "SimpleMath.h"
#include "Renderer.h"
#include "Timer.h"
#include <time.h>
#include <locale>
#include <codecvt>
#include <vector>
class TextHandler {
public:
TextHandler(Renderer& ren, int sw, int sh);
~TextHandler();
void drawMyText(const wchar_t* output, float x, float y, DirectX::XMVECTORF32 color);
void batchDraw(const wchar_t* output, float x, float y, float rotate, DirectX::XMVECTORF32 color);
void drawDialog(char name[256], char parameters[1000], DirectX::XMVECTORF32 color);
void deathRattle( float x, float y, DirectX::XMVECTORF32 color);
void tempMessage(int timeToLive, float x, float y, const wchar_t* output, DirectX::XMVECTORF32 color);
char * randomSchoolName();
void resetMyTime();
void setMCName(char * name);
void update();
double charPerSec;
char mcName[256] = "Anon ";
char schoolName[256] = "Dud High ";
private:
Timer timer;
int sizeofabuffer;
int screenWidth, screenHeight;
const wchar_t* randomTextGen();
DirectX::SimpleMath::Vector2 m_fontPos;
std::unique_ptr<DirectX::SpriteBatch> m_spriteBatch;
struct textObjs {
const wchar_t* string;
float x, y, rotation;
DirectX::XMVECTORF32 color;
int timeToLive;
};
std::vector<textObjs> timedText;
DirectX::XMVECTORF32 black = { 0, 0, 0, 1 };
DirectX::XMVECTORF32 red = { 1, 0, 0, 1 };
DirectX::XMVECTORF32 pansy = { 72 / 255.0f, 221 / 255.0f, 136 / 255.0f, 1 };
std::unique_ptr<DirectX::SpriteFont> cabri32;
std::unique_ptr<DirectX::SpriteFont> vinerHand16;
std::unique_ptr<DirectX::SpriteFont> bellmt16;
std::unique_ptr<DirectX::SpriteFont> bellmt18;
std::unique_ptr<DirectX::SpriteFont> bellmt20;
std::unique_ptr<DirectX::SpriteFont> bellmt22;
std::unique_ptr<DirectX::SpriteFont> bellmt24;
std::unique_ptr<DirectX::SpriteFont> vinerHand32;
std::unique_ptr<DirectX::SpriteFont> stencil30;
};
|
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class RegisterData extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $allData;
public function __construct($allData)
{
$this->allData = $allData;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: 'All Data',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'mail.registerData',
);
}
/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [];
}
}
|
// Copyright 2023 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package model
import (
"fmt"
"io"
"net/http"
"time"
"github.com/leverly/ChatGLM/client"
)
type ChatGLMModelProvider struct {
subType string
clientSecret string
}
func NewChatGLMModelProvider(subType string, clientSecret string) (*ChatGLMModelProvider, error) {
return &ChatGLMModelProvider{subType: subType, clientSecret: clientSecret}, nil
}
func (p *ChatGLMModelProvider) QueryText(question string, writer io.Writer, history []*RawMessage, prompt string, knowledgeMessages []*RawMessage) error {
proxy := client.NewChatGLMClient(p.clientSecret, 30*time.Second)
text := []client.Message{{Role: "user", Content: question}}
taskId, err := proxy.AsyncInvoke(p.subType, 0.2, text)
if err != nil {
return err
}
flusher, ok := writer.(http.Flusher)
if !ok {
return fmt.Errorf("writer does not implement http.Flusher")
}
flushData := func(data string) error {
if _, err := fmt.Fprintf(writer, "event: message\ndata: %s\n\n", data); err != nil {
return err
}
flusher.Flush()
return nil
}
response, err := proxy.AsyncInvokeTask(p.subType, taskId)
if err != nil {
return err
}
content := (*response.Choices)[0].Content
err = flushData(content)
if err != nil {
return err
}
return nil
}
|
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:karaz_shopping_organization/Themes/app_colors.dart';
class CustomSlider extends StatefulWidget {
const CustomSlider({super.key});
@override
State<CustomSlider> createState() => _CustomSliderState();
}
final imageList = [
'assets/images/flowerBouquet.jpg',
'assets/images/makeupBox.jpg',
'assets/images/gifts.jpg',
'assets/images/flower2.jpg',
'assets/images/chocolate.jpg',
'assets/images/watches.png',
];
final textList = [
'Flower bouquet',
'The best maekup',
'Gift box',
'Bouquet bride',
'Delicious chocolate',
'Brand watches',
];
class _CustomSliderState extends State<CustomSlider> {
@override
Widget build(BuildContext context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: 170,
child: Padding(
padding: const EdgeInsets.only(left: 20),
child: Swiper(
autoplay: true,
duration: 4,
scrollDirection: Axis.vertical,
controller: SwiperController(),
layout: SwiperLayout.TINDER,
itemWidth: MediaQuery.of(context).size.width,
itemHeight: 200.0,
itemBuilder: (context, index) {
return Stack(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
image: AssetImage(
imageList[index],
),
fit: BoxFit.fill,
colorFilter: ColorFilter.mode(
Colors.white.withOpacity(0.3),
BlendMode.colorDodge,
),
),
),
),
Positioned(
bottom: 10,
left: 10,
child: Container(
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(
topRight: Radius.circular(25),
bottomLeft: Radius.circular(25),
),
color: AppColors.somo2,
),
child: Text(
' ${textList[index]} ',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: AppColors.blueGrey4,
),
),
),
),
],
);
},
itemCount: imageList.length,
),
),
);
}
}
|
package main
import (
"ascii-art-web-export-file/Ascii"
"ascii-art-web-export-file/Export"
"fmt"
"html/template"
"log"
"net/http"
"ascii-art-web-export-file/Error"
)
type PageData struct {
Result string
}
var err error
func handleMainPage(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
Error.RenderErrorPage(w, http.StatusNotFound, "Page Not Found")
return
}
if r.Method == http.MethodGet {
tmpl, err := template.ParseFiles("template/web.html")
if err != nil {
Error.RenderErrorPage(w, http.StatusInternalServerError, "Internal Server Error")
return
}
err = tmpl.Execute(w, nil)
if err != nil {
Error.RenderErrorPage(w, http.StatusInternalServerError, "Internal Server Error")
}
} else {
Error.RenderErrorPage(w, http.StatusMethodNotAllowed, "Method Not Allowed")
return
}
}
func handleAsciiArt(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
err := r.ParseForm()
if err != nil {
Error.RenderErrorPage(w, http.StatusBadRequest, "Bad Request")
return
}
text := r.FormValue("Text")
banner := r.FormValue("Font")
result, err := Ascii.AsciiArt(text, banner)
if err != nil {
Error.RenderErrorPage(w, http.StatusInternalServerError, "Internal Server Error")
return
}
data := PageData{
Result: result,
}
renderMainPageWithData(w, data)
} else {
Error.RenderErrorPage(w, http.StatusMethodNotAllowed, "Method Not Allowed")
return
}
}
func renderMainPageWithData(w http.ResponseWriter, data PageData) {
tmpl, err := template.ParseFiles("template/web.html")
if err != nil {
Error.RenderErrorPage(w, http.StatusInternalServerError, "Internal Server Error")
return
}
err = tmpl.Execute(w, data)
if err != nil {
Error.RenderErrorPage(w, http.StatusInternalServerError, "Internal Server Error")
}
}
func handleExport(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
Error.RenderErrorPage(w, http.StatusBadRequest, "Bad Request")
return
}
text := r.FormValue("Text")
banner := r.FormValue("Font")
docType := r.FormValue("ExportedFile")
result, err := Ascii.AsciiArt(text, banner)
if err != nil {
Error.RenderErrorPage(w, http.StatusInternalServerError, "Internal Server Error")
return
}
data := PageData{
Result: result,
}
export.Export(w, r, docType, data.Result)
}
func main() {
http.HandleFunc("/", handleMainPage)
http.HandleFunc("/ascii-art", handleAsciiArt)
http.HandleFunc("/export", handleExport)
fs := http.FileServer(http.Dir("style"))
http.Handle("/style/", http.StripPrefix("/style/", fs))
fmt.Println("starting server at port 8125\n")
err = http.ListenAndServe(":8125", nil)
if err != nil {
log.Fatal(err)
}
}
|
"use client"
import { ReactNode, useState } from 'react';
import {
Box,
Stack,
HStack,
Heading,
Text,
VStack,
useColorModeValue,
List,
ListItem,
ListIcon,
Button,
} from '@chakra-ui/react';
import { FaCheckCircle } from 'react-icons/fa';
import { createCheckoutSession } from '@/stripe/createCheckoutSession';
import { createCheckoutSession2 } from '@/stripe/createCheckoutSession2';
import { createCheckoutSession3 } from '@/stripe/createCheckoutSession3';
import { auth } from '@/firebase/firebase';
import { useRouter } from 'next/navigation';
import { useAuthState } from 'react-firebase-hooks/auth';
function PriceWrapper({ children }: { children: ReactNode }) {
return (
<Box
mb={4}
shadow="base"
borderWidth="1px"
alignSelf={{ base: 'center', lg: 'flex-start' }}
borderColor={useColorModeValue('gray.200', 'gray.500')}
borderRadius={'xl'}>
{children}
</Box>
);
}
export default function ThreeTierPricing() {
const Router = useRouter();
const [user] = useAuthState(auth);
return (
<Box py={12}>
<VStack spacing={2} textAlign="center">
<Heading as="h1" fontSize="4xl">
We Have Options!
</Heading>
<Text fontSize="lg" color={'gray.500'}>
Begin your journey of success. It starts here
</Text>
</VStack>
<Stack
direction={{ base: 'column', md: 'row' }}
textAlign="center"
justify="center"
spacing={{ base: 4, lg: 10 }}
py={10}>
<PriceWrapper>
<Box py={4} px={12}>
<Text fontWeight="500" fontSize="2xl">
Signal Beater
</Text>
<HStack justifyContent="center">
<Text fontSize="3xl" fontWeight="600">
$
</Text>
<Text fontSize="5xl" fontWeight="900">
20
</Text>
<Text fontSize="3xl" color="gray.500">
/month
</Text>
</HStack>
</Box>
<VStack
bg={useColorModeValue('gray.50', 'gray.700')}
py={4}
borderBottomRadius={'xl'}>
<List spacing={3} textAlign="start" px={12}>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
Daily signals
</ListItem>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
Telegram chat room access
</ListItem>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
Networking connections
</ListItem>
</List>
<Box w="80%" pt={7}>
{user ? (
<Button w="full" colorScheme="green" variant="outline" onClick={() => {createCheckoutSession3(user.uid)}}>
Start Subscription
</Button> ) : (
<Button w="full" colorScheme="green" variant="outline" onClick={() => Router.push("/signup")}>
Sign in to start Subscription
</Button>)}
</Box>
</VStack>
</PriceWrapper>
<PriceWrapper>
<Box position="relative">
<Box
position="absolute"
top="-16px"
left="50%"
style={{ transform: 'translate(-50%)' }}>
<Text
textTransform="uppercase"
bg={useColorModeValue('green.300', 'green.700')}
px={3}
py={1}
color={useColorModeValue('gray.900', 'gray.300')}
fontSize="sm"
fontWeight="600"
rounded="xl">
Most Popular
</Text>
</Box>
<Box py={4} px={12}>
<Text fontWeight="500" fontSize="2xl">
Express Learner
</Text>
<HStack justifyContent="center">
<Text fontSize="3xl" fontWeight="600">
$
</Text>
<Text fontSize="5xl" fontWeight="900">
50
</Text>
<Text fontSize="3xl" color="gray.500">
/month
</Text>
</HStack>
</Box>
<VStack
bg={useColorModeValue('gray.50', 'gray.700')}
py={4}
borderBottomRadius={'xl'}>
<List spacing={3} textAlign="start" px={12}>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
Video coursework designed for success
</ListItem>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
Telegram chat room access
</ListItem>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
Weekly tips and tricks videos
</ListItem>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
5TB Lorem, ipsum dolor.
</ListItem>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
5TB Lorem, ipsum dolor.
</ListItem>
</List>
<Box w="80%" pt={7}>
{user ? (
<Button w="full" colorScheme="green" variant="outline" onClick={() => {createCheckoutSession2(user.uid)}}>
Start Subscription
</Button> ) : (
<Button w="full" colorScheme="green" variant="outline" onClick={() => Router.push("/signup")}>
Sign in to start Subscription
</Button>)}
</Box>
</VStack>
</Box>
</PriceWrapper>
<PriceWrapper>
<Box py={4} px={12}>
<Text fontWeight="500" fontSize="2xl">
VIP Member
</Text>
<HStack justifyContent="center">
<Text fontSize="3xl" fontWeight="600">
$
</Text>
<Text fontSize="5xl" fontWeight="900">
100
</Text>
<Text fontSize="3xl" color="gray.500">
/month
</Text>
</HStack>
</Box>
<VStack
bg={useColorModeValue('gray.50', 'gray.700')}
py={4}
borderBottomRadius={'xl'}>
<List spacing={3} textAlign="start" px={12}>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
Everything listed in previous plans
</ListItem>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
1 on 1 Mentor Sessions with top traders weekly
</ListItem>
<ListItem>
<ListIcon as={FaCheckCircle} color="green.500" />
Telegram *Exclusive* chatroom access
</ListItem>
</List>
<Box w="80%" pt={7}>
{user && (
<Button w="full" colorScheme="green" variant="outline" onClick={() => {
alert("Please wait a few seconds while you are redirected...")
createCheckoutSession(user.uid)}}>
Start Subscription
</Button> ) } {!user && (
<Button w="full" colorScheme="green" variant="outline" onClick={() => Router.push("/signup")}>
Sign in to start Subscription
</Button>)}
</Box>
</VStack>
</PriceWrapper>
</Stack>
</Box>
);
}
|
package tests
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"text/template"
)
type User struct {
Name string
}
func (user User) Introduce(strangerName string) string {
return "Hello " + strangerName + " my name is " + user.Name
}
func TemplateFuncHandler(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.New("FUNC").Parse(`{{.Introduce "Alexander"}}`))
t.ExecuteTemplate(w, "FUNC", User{
Name: "Jack Dorsey",
})
}
func TestTemplateFunc(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://localhost:8080", nil)
recorder := httptest.NewRecorder()
TemplateFuncHandler(recorder, request)
response := recorder.Result()
body, _ := io.ReadAll(response.Body)
bodyAsStr := string(body)
fmt.Println(bodyAsStr)
}
func TemplateFuncGlobalHandler(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.New("FUNC").Parse(`Name lenght is {{len .Name}}`))
t.ExecuteTemplate(w, "FUNC", User{
Name: "Jack Dorsey",
})
}
func TestTemplateFuncGlobal(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://localhost:8080", nil)
recorder := httptest.NewRecorder()
TemplateFuncGlobalHandler(recorder, request)
response := recorder.Result()
body, _ := io.ReadAll(response.Body)
bodyAsStr := string(body)
fmt.Println(bodyAsStr)
}
|
-- 14.0.0 Access Control and User Management
-- Expect this lab to take approximately 25 minutes.
-- Lab Purpose: Students will work with the Snowflake security model and
-- learn how to create roles, grant privileges, build, and implement
-- basic security models.
-- 14.1.0 Determine Privileges (GRANTs)
-- 14.1.1 Navigate to [Worksheets] and create a new worksheet named Managing
-- Security.
-- 14.2.0 14.1.2 If you haven’t created the class database or warehouse, do it
-- now
CREATE WAREHOUSE IF NOT EXISTS COBRA_WH;
CREATE DATABASE IF NOT EXISTS COBRA_DB;
-- 14.2.1 Run these commands to see what has been granted to you as a user, and
-- to your roles:
SHOW GRANTS TO USER COBRA;
SHOW GRANTS TO ROLE TRAINING_ROLE;
SHOW GRANTS TO ROLE SYSADMIN;
SHOW GRANTS TO ROLE SECURITYADMIN;
-- NOTE: The TRAINING_ROLE has some specific privileges granted - not
-- all roles in the system would be able to see these results.
-- 14.3.0 Work with Role Permissions
-- 14.3.1 Change your role to USERADMIN:
USE ROLE USERADMIN;
-- 14.3.2 Create two new custom roles, called COBRA_CLASSIFIED and
-- COBRA_GENERAL:
CREATE OR REPLACE ROLE COBRA_CLASSIFIED;
CREATE OR REPLACE ROLE COBRA_GENERAL;
-- 14.3.3 GRANT both roles to SYSADMIN, and to your user:
GRANT ROLE COBRA_CLASSIFIED, COBRA_GENERAL TO ROLE SYSADMIN;
GRANT ROLE COBRA_CLASSIFIED, COBRA_GENERAL TO USER COBRA;
-- 14.3.4 Change to the role SYSADMIN, so you can assign permissions to the
-- roles you created:
USE ROLE SYSADMIN;
-- 14.3.5 Create a warehouse named COBRA_SHARED_WH:
CREATE OR REPLACE WAREHOUSE COBRA_SHARED_WH;
USE WAREHOUSE COBRA_SHARED_WH;
-- 14.3.6 Grant both new roles privileges to use the shared warehouse:
GRANT USAGE ON WAREHOUSE COBRA_SHARED_WH
TO ROLE COBRA_CLASSIFIED;
GRANT USAGE ON WAREHOUSE COBRA_SHARED_WH
TO ROLE COBRA_GENERAL;
-- 14.3.7 Create a database called COBRA_CLASSIFIED_DB:
CREATE OR REPLACE DATABASE COBRA_CLASSIFIED_DB;
-- 14.3.8 Grant the role COBRA_CLASSIFIED all necessary privileges to create
-- tables on any schema in COBRA_CLASSIFIED_DB:
GRANT USAGE ON DATABASE COBRA_CLASSIFIED_DB
TO ROLE COBRA_CLASSIFIED;
GRANT USAGE ON ALL SCHEMAS IN DATABASE COBRA_CLASSIFIED_DB
TO ROLE COBRA_CLASSIFIED;
GRANT CREATE TABLE ON ALL SCHEMAS IN DATABASE COBRA_CLASSIFIED_DB
TO ROLE COBRA_CLASSIFIED;
-- 14.3.9 Use the role COBRA_CLASSIFIED, and create a table called
-- SUPER_SECRET_TBL inside the COBRA_CLASSIFIED_DB.PUBLIC schema:
USE ROLE COBRA_CLASSIFIED;
USE WAREHOUSE COBRA_SHARED_WH;
USE COBRA_CLASSIFIED_DB.PUBLIC;
CREATE OR REPLACE TABLE SUPER_SECRET_TBL (id INT);
-- 14.3.10 Insert some data into the table:
INSERT INTO SUPER_SECRET_TBL VALUES (1), (10), (30);
-- 14.3.11 Check if the login_CLASSIFIED role can access the table
SELECT * FROM COBRA_CLASSIFIED_DB.PUBLIC.SUPER_SECRET_TBL;
-- 14.3.12 Switch to the login_GENERAL role and try accessing the table
USE ROLE COBRA_GENERAL;
SELECT * FROM COBRA_CLASSIFIED_DB.PUBLIC.SUPER_SECRET_TBL;
-- 14.3.13 Because we haven’t given any permissions to the database, schema, or
-- the table, this doesn’t work.
-- 14.3.14 Before we give login_GENERAL permissions, try using SECONDARY_ROLES
-- to access the table
USE SECONDARY ROLES ALL;
SELECT * FROM COBRA_CLASSIFIED_DB.PUBLIC.SUPER_SECRET_TBL;
-- 14.3.15 Since SECONDARY ROLES ALL allows the user to use any permissions on
-- any role they’ve been granted, This will work.
-- 14.3.16 Now try using the SECONDARY ROLES to create a new table in the
-- database.
USE SCHEMA COBRA_CLASSIFIED_DB.PUBLIC;
CREATE TABLE NOT_SO_SECRET_TBL (id INT);
-- 14.3.17 This will fail since SECONDARY ROLES doesn’t support CREATE
-- 14.3.18 SECONDARY ROLES will support ALTER TABLE.
ALTER TABLE SUPER_SECRET_TBL ADD COLUMN name STRING(20);
-- 14.3.19 To continue this lab, turn off SECONDARY ROLES
USE SECONDARY ROLES NONE;
-- 14.3.20 Switch back to the login_CLASSIFIED
USE ROLE COBRA_CLASSIFIED;
-- 14.3.21 Assign GRANT SELECT privileges on SUPER_SECRET_TBL to the role
-- COBRA_GENERAL:
GRANT SELECT ON SUPER_SECRET_TBL TO ROLE COBRA_GENERAL;
-- 14.3.22 Use the role COBRA_GENERAL to SELECT * from the table
-- SUPER_SECRET_TBL:
USE ROLE COBRA_GENERAL;
SELECT * FROM COBRA_CLASSIFIED_DB.PUBLIC.SUPER_SECRET_TBL;
-- What happens? Why?
-- 14.3.23 Grant role COBRA_GENERAL usage on all schemas in
-- COBRA_CLASSIFIED_DB:
USE ROLE SYSADMIN;
GRANT USAGE ON DATABASE COBRA_CLASSIFIED_DB TO ROLE COBRA_GENERAL;
GRANT USAGE ON ALL SCHEMAs IN DATABASE COBRA_CLASSIFIED_DB TO ROLE COBRA_GENERAL;
-- 14.3.24 Now try again:
USE ROLE COBRA_GENERAL;
SELECT * FROM COBRA_CLASSIFIED_DB.PUBLIC.SUPER_SECRET_TBL;
-- 14.3.25 Drop the database COBRA_CLASSIFIED_DB:
USE ROLE SYSADMIN;
DROP DATABASE COBRA_CLASSIFIED_DB;
-- 14.3.26 Drop the roles COBRA_CLASSIFIED and COBRA_GENERAL:
USE ROLE USERADMIN;
DROP ROLE COBRA_CLASSIFIED;
DROP ROLE COBRA_GENERAL;
-- HINT: What role do you need to use to do this?
-- 14.4.0 Create Parent and Child Roles
-- 14.4.1 Change your role to USERADMIN:
USE ROLE USERADMIN;
-- 14.4.2 Create a parent and child role, and GRANT the roles to the role
-- SYSADMIN. At this point, the roles are peers (neither one is below
-- the other in the hierarchy):
CREATE OR REPLACE ROLE COBRA_CHILD;
CREATE OR REPLACE ROLE COBRA_PARENT;
GRANT ROLE COBRA_CHILD, COBRA_PARENT TO ROLE SYSADMIN;
-- 14.4.3 Give your user name privileges to use the roles:
GRANT ROLE COBRA_CHILD, COBRA_PARENT TO USER COBRA;
-- 14.4.4 Change your role to SYSADMIN:
USE ROLE SYSADMIN;
-- 14.4.5 Grant the following object permissions to the child role:
GRANT USAGE ON WAREHOUSE COBRA_WH TO ROLE COBRA_CHILD;
GRANT USAGE ON DATABASE COBRA_DB TO ROLE COBRA_CHILD;
GRANT USAGE ON SCHEMA COBRA_DB.PUBLIC TO ROLE COBRA_CHILD;
GRANT CREATE TABLE ON SCHEMA COBRA_DB.PUBLIC TO ROLE COBRA_CHILD;
-- 14.4.6 Use the child role to create a table:
USE ROLE COBRA_CHILD;
USE WAREHOUSE COBRA_WH;
USE SCHEMA COBRA_DB.PUBLIC;
CREATE TABLE genealogy (name STRING, age INTEGER, mother STRING, father STRING);
-- 14.4.7 Verify that you can see the table:
SHOW TABLES LIKE '%genealogy%';
-- 14.4.8 Use the parent role and view the table:
USE ROLE COBRA_PARENT;
SHOW TABLES LIKE '%genealogy%';
-- You will not see the table, because the parent role has not been
-- granted access.
-- 14.4.9 Change back to the USERADMIN role and change the hierarchy so the
-- child role is beneath the parent role:
USE ROLE USERADMIN;
GRANT ROLE COBRA_CHILD to ROLE COBRA_PARENT;
-- 14.4.10 Use the parent role, and verify the parent can now see the table
-- created by the child:
USE ROLE COBRA_PARENT;
SHOW TABLES LIKE '%genealogy%';
-- 14.4.11 Clean up by dropping the roles, warehouse and table created in this
-- lab
USE ROLE SYSADMIN;
DROP WAREHOUSE COBRA_SHARED_WH;
DROP TABLE COBRA_DB.public.genealogy;
-- 14.4.12 Drop the roles COBRA_CHILD and COBRA_PARENT:
USE ROLE USERADMIN;
DROP ROLE COBRA_CHILD;
DROP ROLE COBRA_PARENT;
-- 14.4.13 Suspend and resize the warehouse
USE ROLE TRAINING_ROLE;
ALTER WAREHOUSE COBRA_WH SET WAREHOUSE_SIZE=XSmall;
ALTER WAREHOUSE COBRA_WH SUSPEND;
|
import React, { useState } from "react";
import { Container, Nav, Navbar, NavDropdown, Offcanvas } from "react-bootstrap";
import { Link, useNavigate } from "react-router-dom";
import PurchasesSidebar from "./PurchasesSidebar"
const AppNavbar = () => {
const navigate = useNavigate();
const logout = () => {
localStorage.setItem("token", "")
navigate("/login")
};
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<>
<Navbar expand="lg" variant="dark" bg="primary">
<Container>
<Navbar.Brand as={Link} to="/" style={{ fontSize: 30 }}>E-commerce</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav>
<Nav.Link as={Link} to="/login" style={{ fontSize: 20 }}>Login<i className='bx bxs-user'></i></Nav.Link>
<Nav.Link as={Link} to="/product/id" style={{ fontSize: 20 }}>Product Detail</Nav.Link>
<Nav.Link as={Link} to="/purchases" style={{ fontSize: 20 }}>Purchases</Nav.Link>
<Nav.Link onClick={logout} style={{ fontSize: 20 }}>Log out<i class='bx bx-log-out'></i></Nav.Link>
<Nav.Link onClick={handleShow} style={{ fontSize: 20 }}>Cart<i className='bx bxs-cart'></i></Nav.Link>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
<PurchasesSidebar show={show} handleClose={handleClose} />
</>
);
};
export default AppNavbar;
|
package com.customerManager.controller;
import com.customerManager.dao.UserRepository;
import com.customerManager.helper.Message;
import com.customerManager.model.User;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/api")
public class HomeController {
@Autowired
BCryptPasswordEncoder passwordEncoder;
@Autowired
private UserRepository userRepository;
// Home page mapping
@GetMapping("/home")
public String Home(){
return "home";
}
// Signup page mapping
@GetMapping("/signup")
public String signup(Model model){
model.addAttribute("title" , "signup page");
model.addAttribute( "user",new User());
return "Signup";
}
// Register user mapping
@PostMapping("/do_register")
public String registerUser(@Valid @ModelAttribute("user") User user , BindingResult result1, @RequestParam(value="agreement",defaultValue = "false")boolean agreement, Model model, HttpSession session){
try {
// Check if the user has agreed to the terms and conditions
if(!agreement){
System.out.println("you have not agreed the term and conditions...");
throw new Exception("you have not agreed the term and conditions...");
}
// Check for validation errors
if(result1.hasErrors()){
System.out.print("ERROR" + result1.toString());
model.addAttribute("user", user);
return "Signup";
}
// Set default role for the user
user.setRole("USER");
// Encode user password before saving
user.setPassword(passwordEncoder.encode(user.getPassword()));
// Save the user to the repository
userRepository.save(user);
// user attribute and set success message
model.addAttribute("user", new User());
session.setAttribute("message" , new Message("successfully registered !! " , "alert-success"));
return"Signup";
}
catch (Exception e){
// Print stack trace for exception
e.printStackTrace();
model.addAttribute("user" , user);
session.setAttribute("message" , new Message("something went wrong!!" + e.getMessage(), "alert-danger"));
return"Signup";
}
}
}
|
package com.example.astraljourney.ui.main.horoscopodetail
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.navArgs
import com.example.astraljourney.R
import com.example.astraljourney.databinding.ActivityHoroscopoDetailBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
@AndroidEntryPoint
class HoroscopoDetailActivity : AppCompatActivity() {
private lateinit var binding: ActivityHoroscopoDetailBinding
private val horoscopoDetailViewModel by viewModels<HoroscopoDetailViewModel>()
private val navArgs by navArgs<HoroscopoDetailActivityArgs>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHoroscopoDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
initUI()
}
private fun initUI() {
initUiState()
initListeners()
}
private fun initListeners() {
binding.detailToolbar.setNavigationOnClickListener { onBackPressed() }
}
private fun initUiState() {
horoscopoDetailViewModel.onInitialize(navArgs.zodiacSelected)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
horoscopoDetailViewModel.detailUiState.collect { uiState ->
if (uiState.error == null && uiState.image != 0) {
binding.progressBar.visibility =
if (uiState.loading) View.VISIBLE else View.GONE
binding.tvDetailTitle.text = uiState.title
binding.tvDetailDescription.text = uiState.description
binding.ivToolbarBackground.setAnimation(uiState.image)
} else {
binding.tvDetailTitle.text = uiState.error
}
}
}
}
}
}
|
package com.nju.edu.erp.web.controller;
import com.nju.edu.erp.auth.Authorized;
import com.nju.edu.erp.enums.CustomerType;
import com.nju.edu.erp.enums.Role;
import com.nju.edu.erp.model.vo.CustomerVO;
import com.nju.edu.erp.service.CustomerService;
import com.nju.edu.erp.web.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "/customer")
public class CustomerController {
private final CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/findByType")
public Response findByType(@RequestParam CustomerType type) {
return Response.buildSuccess(customerService.getCustomersByType(type));
}
@GetMapping("/findAll")
public Response findAll() {
return Response.buildSuccess(customerService.getAllCustomers());
}
@PostMapping("/add")
@Authorized(roles = {Role.ADMIN, Role.GM, Role.SALE_MANAGER, Role.SALE_STAFF})
public Response addCustomer(@RequestBody CustomerVO customerVO){
return Response.buildSuccess(customerService.addCustomer(customerVO));
}
@GetMapping("/delete")
@Authorized(roles = {Role.ADMIN, Role.GM, Role.SALE_MANAGER, Role.SALE_STAFF})
public Response deleteCustomer(@RequestParam Integer id) {
customerService.deleteById(id);
return Response.buildSuccess();
}
}
|
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>Vinayak Plywood</title>
<meta content="" name="description">
<meta content="" name="keywords">
<!-- Favicons -->
<link href={% static "assets/img/fav.png" %} rel="icon">
<link href={% static "assets/img/fav.png" %} rel="apple-touch-icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<!-- Vendor CSS Files -->
<link href={% static "assets/vendor/animate.css/animate.min.css" %} rel="stylesheet">
<link href={% static "assets/vendor/aos/aos.css" %} rel="stylesheet">
<link href={% static "assets/vendor/bootstrap/css/bootstrap.min.css" %} rel="stylesheet">
<link href={% static "assets/vendor/bootstrap-icons/bootstrap-icons.css" %} rel="stylesheet">
<link href={% static "assets/vendor/boxicons/css/boxicons.min.css" %} rel="stylesheet">
<link href={% static "assets/vendor/glightbox/css/glightbox.min.css" %} rel="stylesheet">
<link href={% static "assets/vendor/remixicon/remixicon.css" %} rel="stylesheet">
<link href={% static "assets/vendor/swiper/swiper-bundle.min.css" %} rel="stylesheet">
<!-- Template Main CSS File -->
<link href={% static "assets/css/style.css" %} rel="stylesheet">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href={% static "assets\font\flaticon.css" %}>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
<!-- <link href="assets/css/style1.css" rel="stylesheet"> -->
</head>
<body>
<!-- ======= Header ======= -->
<header id="header" class="fixed-top d-flex align-items-center header-transparent ">
<div class="container d-flex align-items-center justify-content-between">
<div class="logo">
<h1><a href="index.html" class="animate_animated animatefadeInDown ">Vinayak Plywood</a></h1>
<!-- Uncomment below if you prefer to use an image logo -->
<!-- <a href="index.html"><img src="assets/img/logo.png" alt="" class="img-fluid"></a>-->
</div>
<nav id="navbar" class="navbar">
<ul>
<li><a class="nav-link scrollto active" href="#hero">Home</a></li>
<li><a class="nav-link scrollto" href="#about">About</a></li>
<li><a class="nav-link scrollto" href="#services">Services</a></li>
<li><a class="nav-link scrollto " href="#gallery">Products</a></li>
<li><a class="nav-link scrollto" href="#faq">F.A.Q</a></li>
<li><a class="nav-link scrollto" href="#contact">Contact</a></li>
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav><!-- .navbar -->
</div>
</header><!-- End Header -->
<!-- ======= Hero Section ======= -->
<section id="hero">
<div class="hero-container">
<div id="heroCarousel" class="carousel slide carousel-fade" data-bs-ride="carousel" data-bs-interval="5000">
<ol id="hero-carousel-indicators" class="carousel-indicators"></ol>
<div class="carousel-inner" role="listbox">
<div class="carousel-item active" style="background-image: url({% static "assets/img/bg11.jpg" %})">
<div class="carousel-container">
<div class="container">
<h2 class="animate__animated animate__fadeInDown">THE HOUSE OF PLYWOOD</h2>
<p class="animate__animated animate__fadeInUp">PLYWOOD | LAMINATE | FLUSH DOORS | LINER</p>
</div>
</div>
</div>
<div class="carousel-item" style="background-image: url({% static "assets/img/bg12.jpg" %})">
<div class="carousel-container">
<div class="container">
<h2 class="animate__animated animate__fadeInDown">DECORATIVE   FURNITURES</h2>
</div>
</div>
</div>
<div class="carousel-item" style="background-image: url({% static "assets/img/bg13.jpg" %})">
<div class="carousel-container">
<div class="container">
<h2 class="animate__animated animate__fadeInDown">DESIGNER   CUPBOARDS</h2>
</div>
</div>
</div>
<div class="carousel-item" style="background-image: url({% static "assets/img/bg15.jpg" %})">
<div class="carousel-container">
<div class="container">
<h2 class="animate__animated animate__fadeInDown">BEST QUALITY FLUSH DOORS</h2>
</div>
</div>
</div>
<div class="carousel-item" style="background-image: url({% static "assets/img/bg111.jpg" %})">
<div class="carousel-container">
<div class="container">
<h2 class="animate__animated animate__fadeInDown">LAMINATE   FLOURING</h2>
</div>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#heroCarousel" role="button" data-bs-slide="prev">
<span class="carousel-control-prev-icon bi bi-chevron-left" aria-hidden="true"></span>
</a>
<a class="carousel-control-next" href="#heroCarousel" role="button" data-bs-slide="next">
<span class="carousel-control-next-icon bi bi-chevron-right" aria-hidden="true"></span>
</a>
</div>
</div>
</section>
<!-- End Hero -->
<main id="main">
<!-- ======= About Section ======= -->
<!-- <section id="about" class="about">
<div class="container">
<div class="section-title" data-aos="zoom-out">
<h2>About</h2>
<p>Who we are</p>
</div> -->
<section id="about" class="services">
<div class="container">
<div class="section-title" data-aos="zoom-out">
<h2>About</h2>
<p style="color: #504037;">Who we are</p>
</div>
<div class="row">
<div class="col-lg-6 col-md-6" data-aos="fade-up" data-aos-delay="300">
<div class="icon-box">
<div class="icon"><i class="flaticon-flag"></i></div>
<h4 class="title"><a href="">Our Mission</a></h4>
<p class="description">Our Mission is to provide best quality products at a very reasonable price with utmost satisfaction to our business associates and end users.</p>
</div>
</div>
{% comment %} <div class="col-lg-4 col-md-6" data-aos="fade-up" data-aos-delay="400">
<div class="icon-box">
<div class="icon"><i class="flaticon-checklist"></i></div>
<h4 class="title"><a href="">Our Plan</a></h4>
<p class="description">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque</p>
</div>
</div> {% endcomment %}
<div class="col-lg-6 col-md-6" data-aos="fade-up" data-aos-delay="500">
<div class="icon-box">
<div class="icon"><i class="flaticon-spyglass"></i></div>
<h4 class="title"><a href="">Our Vision</a></h4>
<p class="description">To become a market leader in a very organised way in plywood industry by providing best services, values and satisfaction to our business associates.</p>
</div>
</div>
</div>
</div>
</section>
<!--
</div>
</section> -->
<!-- End About Section -->
<!-- ======= Welcome Section ======= -->
{% comment %} <section id="" class="">
<div class="container" class="red">
<img src="assets/img/vp_logo1.PNG" height="50px" width="100px">
<h1 class="red">WELCOME to vp</h1>
</div>
</section><!-- End Features Section --> {% endcomment %}
<!-- ======= slogan Section ======= -->
<section id="cta" class="cta">
<div class="container ">
</div>
</section>
<!-- End Cta Section -->
<!-- ======= Services Section ======= -->
<section id="services" class="services">
<div class="container">
<div class="section-title" data-aos="zoom-out">
<h2>Services</h2>
<p style="color: #504037;">What do we offer</p>
</div>
<div class="row">
<div class="col-lg-4 col-md-6" data-aos="fade-up">
<div class="icon-box">
<div class="icon"><i class="flaticon-shield"></i></div>
<h4 class="title"><a href="">Quality Assurance</a></h4>
<p class="description">Our products are the result of advance research which gurantees 100% quality assurance to our end users.</p>
</div>
</div>
<div class="col-lg-4 col-md-6" data-aos="fade-up" data-aos-delay="100">
<div class="icon-box">
<div class="icon"><i class="flaticon-delivery-truck"></i></div>
<h4 class="title"><a href="">Door-Step Dilevery</a></h4>
<p class="description">Our team ensures timely delivery of the orders in the safest way possible.</p>
</div>
</div>
<div class="col-lg-4 col-md-6" data-aos="fade-up" data-aos-delay="200">
<div class="icon-box">
<div class="icon"><i class="flaticon-price-tag"></i></div>
<h4 class="title"><a href="">Reasonable Price</a></h4>
<p class="description">We focus on providing the best quality products at a very reasonable cost.</p>
</div>
</div>
<div class="col-lg-4 col-md-6" data-aos="fade-up" data-aos-delay="300">
<div class="icon-box">
<div class="icon"><i class="flaticon-helmet"></i></div>
<h4 class="title"><a href="">Best Carpenters</a></h4>
<p class="description">We also provide carpenters and architects who are highly trained and expertise in their work field.</p>
</div>
</div>
<div class="col-lg-4 col-md-6" data-aos="fade-up" data-aos-delay="400">
<div class="icon-box">
<div class="icon"><i class="flaticon-customer-satisfaction"></i></div>
<h4 class="title"><a href="">Customer Satisfaction</a></h4>
<p class="description">Our company focuses on meeting customer needs and expectations, making sure 100% customer satisfaction.</p>
</div>
</div>
<div class="col-lg-4 col-md-6" data-aos="fade-up" data-aos-delay="500">
<div class="icon-box">
<div class="icon"><i class="flaticon-sprout"></i></div>
<h4 class="title"><a href="">Eco Freindly</a></h4>
<p class="description">We have actively undertaken plantation activities and believe in maintaining ecological harmony.</p>
</div>
</div>
</div>
</div>
</section><!-- End Services Section -->
<!-- ======= Product Section ======= -->
<!-- <section id="portfolio" class="portfolio">
<div class="container">
<div class="section-title" data-aos="zoom-out">
<h2>Products</h2>
<p>What we do</p>
</div>
<section id="gallery"> -->
<section id="gallery">
<div class="container" data-aos="fade-up">
<div class="section-title" >
<h2>Gallery</h2>
<p style="color: #504037;">Check our product gallery </p>
</div>
</div>
<div class="gallery-slider swiper-container">
<div class="swiper-wrapper align-items-center">
<div class="swiper-slide">
<div class="img"><a href="{% static "assets/img/p1.png" %}" class="gallery-lightbox"><img src="{% static "assets/img/p1.png" %}" class="img-fluid" alt=""></a></div>
<h3 class="product_details"> PLYWOOD</h3></div>
<div class="swiper-slide">
<div class="img"><a href="{% static "assets/img/l2.png" %}" class="gallery-lightbox"><img src="{% static "assets/img/l2.png" %}" class="img-fluid" alt=""></a></div>
<h3 class="product_details"> LINER</h3>
</div>
<div class="swiper-slide"><a href="assets/img/portfolio/portfolio-3.jpg" class="gallery-lightbox"><img src="assets/img/portfolio/portfolio-3.jpg" class="img-fluid" alt=""></a>
<div class="img"><a href="{% static "assets/img/d1.png" %}" class="gallery-lightbox"><img src="{% static "assets/img/d1.png" %}" class="img-fluid" alt=""></a></div>
<h3 class="product_details"> FLUSH DOORS</h3>
</div>
<div class="swiper-slide"><a href="assets/img/portfolio/portfolio-4.jpg" class="gallery-lightbox"><img src="assets/img/portfolio/portfolio-4.jpg" class="img-fluid" alt=""></a>
<div class="img"><a href="{% static "assets/img/l1.jpg" %}" class="gallery-lightbox"><img src="{% static "assets/img/l1.jpg" %}" class="img-fluid" alt=""></a></div>
<h3 class="product_details"> LAMINATES</h3>
</div>
{% comment %} <div class="swiper-slide"><a href="assets/img/portfolio/portfolio-5.jpg" class="gallery-lightbox"><img src="assets/img/portfolio/portfolio-5.jpg" class="img-fluid" alt=""></a>
<div class="img"><a href="{% static "assets/img/p2.png" %}" class="gallery-lightbox"><img src="{% static "assets/img/p2.png" %}" class="img-fluid" alt=""></a></div>
<h3 class="product_details"> p5</h3>
</div>
<div class="swiper-slide"><a href="assets/img/portfolio/portfolio-6.jpg" class="gallery-lightbox"><img src="assets/img/portfolio/portfolio-6.jpg" class="img-fluid" alt=""></a>
<div class="img"><a href="{% static "assets/img/p2.png" %}" class="gallery-lightbox"><img src="{% static "assets/img/p2.png" %}" class="img-fluid" alt=""></a></div>
<h3 class="product_details"> p6</h3>
</div>
<div class="swiper-slide"><a href="assets/img/portfolio/portfolio-7.jpg" class="gallery-lightbox"><img src="assets/img/portfolio/portfolio-7.jpg" class="img-fluid" alt=""></a>
<div class="img"><a href="{% static "assets/img/p2.png" %}" class="gallery-lightbox"><img src="{% static "assets/img/p2.png" %}" class="img-fluid" alt=""></a></div>
<h3 class="product_details"> p7</h3>
</div>
<div class="swiper-slide"><a href="assets/img/portfolio/portfolio-8.jpg" class="gallery-lightbox"><img src="assets/img/portfolio/portfolio-8.jpg" class="img-fluid" alt=""></a>
<div class="img"><a href="{% static "assets/img/p2.png" %}" class="gallery-lightbox"><img src="{% static "assets/img/p2.png" %}" class="img-fluid" alt=""></a></div>
<h3 class="product_details"> p8</h3>
</div> {% endcomment %}
</div>
<div class="swiper-pagination"></div>
</div>
</section>
<!-- </div>
</section>
-->
<!-- End product Section -->
<!-- ======= F.A.Q Section ======= -->
<section id="faq" class="faq">
<div class="container">
<div class="section-title" data-aos="zoom-out">
<h2>F.A.Q</h2>
<p style="color: #504037;">Frequently Asked Questions</p>
</div>
<ul class="faq-list">
<li>
<div data-bs-toggle="collapse" class="collapsed question" href="#faq1">How can a custormer judge the Quality of Plywood?<i class="bi bi-chevron-down icon-show"></i><i class="bi bi-chevron-up icon-close"></i></div>
<div id="faq1" class="collapse" data-bs-parent=".faq-list">
<p>
Firstly check plywood surface is smooth and doesn’t have ups or down, also check all four corner of plywood & make sure it has no thickness variation. Always prefer heavy weight plywood as it carries more density.
</p>
</div>
</li>
<li>
<div data-bs-toggle="collapse" href="#faq2" class="collapsed question">How can I waterproof Plywood? <i class="bi bi-chevron-down icon-show"></i><i class="bi bi-chevron-up icon-close"></i></div>
<div id="faq2" class="collapse" data-bs-parent=".faq-list">
<p>
Liqid Latex, Spray-on or Paint-on Latex is an effective plywood protector.It is available at hardware stores and forms a waterproof layer on the surface of the plywood to protect it from moisture.
</p>
</div>
</li>
<li>
<div data-bs-toggle="collapse" href="#faq3" class="collapsed question">What are the different types of Organisms which attack and destroy Plywood?<i class="bi bi-chevron-down icon-show"></i><i class="bi bi-chevron-up icon-close"></i></div>
<div id="faq3" class="collapse" data-bs-parent=".faq-list">
<p>
The most damaging organism that attack wood structures are the termites. The beetles are the next most important group of insect which attack wood.
</p>
</div>
</li>
<li>
<div data-bs-toggle="collapse" href="#faq4" class="collapsed question">How do we take care of Furnitures made of wood? <i class="bi bi-chevron-down icon-show"></i><i class="bi bi-chevron-up icon-close"></i></div>
<div id="faq4" class="collapse" data-bs-parent=".faq-list">
<p>
The furnitures made from wood must be kept Dry, be carefull about exposing wooden funitures to sunlight for prolonged time periods.Avoid using extremely hot and cold objects on wooden furnitures. For better mainteinance oiling and waxing wood is highly recommended and always use warm water and mild dish soap
to clean furniture.
</p>
</div>
</li>
{% comment %} <li>
<div data-bs-toggle="collapse" href="#faq5" class="collapsed question">Tempus quam pellentesque nec nam aliquam sem et tortor consequat? <i class="bi bi-chevron-down icon-show"></i><i class="bi bi-chevron-up icon-close"></i></div>
<div id="faq5" class="collapse" data-bs-parent=".faq-list">
<p>
Molestie a iaculis at erat pellentesque adipiscing commodo. Dignissim suspendisse in est ante in. Nunc vel risus commodo viverra maecenas accumsan. Sit amet nisl suscipit adipiscing bibendum est. Purus gravida quis blandit turpis cursus in
</p>
</div>
</li>
<li>
<div data-bs-toggle="collapse" href="#faq6" class="collapsed question">Tortor vitae purus faucibus ornare. Varius vel pharetra vel turpis nunc eget lorem dolor? <i class="bi bi-chevron-down icon-show"></i><i class="bi bi-chevron-up icon-close"></i></div>
<div id="faq6" class="collapse" data-bs-parent=".faq-list">
<p>
Laoreet sit amet cursus sit amet dictum sit amet justo. Mauris vitae ultricies leo integer malesuada nunc vel. Tincidunt eget nullam non nisi est sit amet. Turpis nunc eget lorem dolor sed. Ut venenatis tellus in metus vulputate eu scelerisque. Pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus faucibus. Nibh tellus molestie nunc non blandit massa enim nec.
</p>
</div>
</li> {% endcomment %}
</ul>
</div>
</section><!-- End F.A.Q Section -->
<!-- ======= Contact Section ======= -->
<section id="contact" class="contact">
<div class="container">
<div class="section-title" data-aos="zoom-out">
<h2>Contact</h2>
<p style="color: #504037;">Contact Us</p>
</div>
<div class="row mt-5">
<div class="col-lg-4" data-aos="fade-right">
<div class="info">
<div class="address">
<i class="bi bi-geo-alt"></i>
<h4>Location:</h4>
<p>Sector-H-101 Govindpura, Bhopal(M.P.)</p>
</div>
<div class="email">
<i class="bi bi-envelope"></i>
<h4>Email:</h4>
<p>vinayak.plywood@yahoo.com</p>
</div>
<div class="phone">
<i class="bi bi-phone"></i>
<h4>Call:</h4>
<p>+91 8140654321</p>
</div>
</div>
</div>
<div class="col-lg-8 mt-5 mt-lg-0" data-aos="fade-left">
<form action="" method="post" >
<div class="row">
<div class="col-md-6 form-group">
<!-- {% comment %} <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" required> {% endcomment %} -->
{{ forms.name }}
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<!-- {% comment %} <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" required> {% endcomment %} -->
{{ forms.email }}
</div>
</div>
<div class="form-group mt-3">
<!-- {% comment %} <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required> {% endcomment %} -->
{{ forms.subject}}
</div>
<div class="form-group mt-3">
<!-- {% comment %} <textarea class="form-control" name="message" rows="5" placeholder="Message" required></textarea> {% endcomment %} -->
{{ forms.message }}
</div>
{% csrf_token %}
<br>
<div class=" text-center"><button class="submit_button" type="submit">Send Message</button></div>
</form>
</div>
</div>
</div>
</section><!-- End Contact Section -->
</main><!-- End #main -->
<!-- ======= Footer ======= -->
<footer class="footer-distributed">
<div class="footer-left">
<img src="{% static "assets/img/vp_logo11.png" %}" width=100px height=100px>
<h3>Vinayak<span>Plywood</span></h3>
<p class="footer-links">
<a href="#hero">Home</a>
|
<a href="#services">Services</a>
|
<a href="#gallery">Gallery</a>
|
<a href="#faq">F.A.Q</a>
</p>
<p class="footer-company-name"> Vinayak Plywood © 2021 All Right Reserved</p>
</div>
<div class="footer-center">
<div>
<i class="fa fa-map-marker"></i>
<p><span>Sector - H - 101</span>
Govindpura, Bhopal (M.P.)</p>
</div>
<div>
<i class="fa fa-phone"></i>
<p>+91 8140654321</p>
</div>
<div>
<i class="fa fa-envelope"></i>
<p><a href="vinayak.plywood@yahoo.com">vinayak.plywood@yahoo.com</a></p>
</div>
</div>
<div class="footer-right">
<p class="footer-company-about">
<span>About the company</span>
We offer best quality Plywoods at a very resonable price with utmost Satisfaction to our End Users.</p>
<div class="footer-icons">
<a href="#"><i class="fa fa-facebook hh"></i></a>
<a href="#"><i class="fa fa-twitter hh"></i></a>
<a href="#"><i class="fa fa-instagram hh"></i></a>
{% comment %} <a href="#"><i class="fa fa-linkedin"></i></a>
<a href="#"><i class="fa fa-youtube"></i></a> {% endcomment %}
</div>
</div>
</footer>
<!-- End Footer -->
<div>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3665.2530397674514!2d77.4387261149724!3d23.270253584828218!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x0!2zMjPCsDE2JzEyLjkiTiA3N8KwMjYnMjcuMyJF!5e0!3m2!1sen!2sin!4v1619443714938!5m2!1sen!2sin" style="width: 100%; height: 270px;" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
</div>
<a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>
<!-- Vendor JS Files -->
<script src={% static "assets/vendor/aos/aos.js" %} ></script>
<script src={% static "assets/vendor/bootstrap/js/bootstrap.bundle.min.js" %} ></script>
<script src={% static "assets/vendor/glightbox/js/glightbox.min.js" %} ></script>
<script src={% static "assets/vendor/isotope-layout/isotope.pkgd.min.js" %} ></script>
<script src={% static "assets/vendor/php-email-form/validate.js" %} ></script>
<script src={% static "assets/vendor/swiper/swiper-bundle.min.js" %} ></script>
<!-- Template Main JS File -->
<script src={% static "assets/js/main.js" %} ></script>
<script src={% static "assets/js/jsproduct.js" %} ></script>
<script src={% static "assets/js/jscorosel.js" %} ></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">
{% if messages and i %}
{% for message in messages %}
// swal("{{message}}");
swal("{{message}}", "", "{{message.tags}}");
{% endfor %}
{% endif %}
</script>
<!-- Template Main JS File -->
<script src={% static "assets/js/main.js" %}></script>
</body>
</html>
|
package com.assignment.assignment2;
import com.assignment.assignment2.entity.Address;
import com.assignment.assignment2.entity.User;
import com.assignment.assignment2.repository.AddressRepository;
import com.assignment.assignment2.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Assignment2Application implements CommandLineRunner {
private final UserRepository userRepository;
private final AddressRepository addressRepository;
private final Logger LOG = LoggerFactory.getLogger(Assignment2Application.class);
@Autowired
public Assignment2Application(UserRepository userRepository, AddressRepository addressRepository) {
this.userRepository = userRepository;
this.addressRepository = addressRepository;
}
public static void main(String[] args) {
SpringApplication.run(Assignment2Application.class, args);
}
public void run(String... args) throws Exception{
// User user1 = new User();
// user1.setEmail("user2@gmail.com");
// user1.setName("User 2");
// user1.setPassword("333456");
// userRepository.save(user1);
// LOG.info("Berhasil menyimpan "+user1);
//
// Address address1 = new Address();
// address1.setCity("Jakarta");
// address1.setCountry("Indonesia");
// address1.setState("Indonesia");
// address1.setZip_code("40130");
// address1.setUserId(user1.getId());
//
// addressRepository.save(address1);
// LOG.info("Berhasil menyimpan "+address1);
userRepository.findAll().forEach(user -> LOG.info(user.getName() + " " + user.getId().toString()));
addressRepository.findAll().forEach(address -> LOG.info(address.getCity()));
}
}
|
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
public class Cat {
private int headDimension;
private int eyeY;
private int eyeX;
private int eyeSeparation;
private int eyeHeight;
private int eyeWidth;
private int mouthHeight;
private int mouthWidth;
private int mouthX;
private int mouthY;
private Color bodyColor = Color.BLACK; // Default body color
private Color eyeColor = Color.GREEN; // Default eye color
private Color mouthColor = Color.PINK; // Default mouth color
public Cat(int headDimension, int eyeY, int eyeX, int eyeSeparation,
int eyeHeight, int eyeWidth, int mouthHeight, int mouthWidth,
int mouthX, int mouthY) {
this.headDimension = headDimension;
this.eyeY = eyeY;
this.eyeX = eyeX;
this.eyeSeparation = eyeSeparation;
this.eyeHeight = eyeHeight;
this.eyeWidth = eyeWidth;
this.mouthHeight = mouthHeight;
this.mouthWidth = mouthWidth;
this.mouthX = mouthX;
this.mouthY = mouthY;
}
public void draw(Graphics g, int catX, int catY) {
Graphics2D g2 = (Graphics2D) g;
drawHead(g2, catX, catY);
drawEyes(g2, catX, catY);
drawMouth(g2, catX, catY);
// Meow text appears below cat head, +10 places below
// so it doesn't overlap the drawing
g2.setColor(Color.black);
g2.drawString("Meow", catX, catY + headDimension + 10);
}
// Method to draw the cat's head
private void drawHead(Graphics2D g2, int catX, int catY) {
g2.setColor(Color.black);
g2.fillOval(catX, catY, headDimension, headDimension);
// Calculate ear positions
int earWidth = headDimension / 3;
int earHeight = headDimension / 2;
int earY = catY - earHeight;
int earBase = headDimension / 4;
int leftEarX = catX + earBase;
int rightEarX = catX + headDimension - earBase - earWidth;
// Draw ears
Polygon leftEar = new Polygon();
leftEar.addPoint(leftEarX, catY);
leftEar.addPoint(catX + earBase / 2, earY);
leftEar.addPoint(catX + earBase, catY - earHeight);
Polygon rightEar = new Polygon();
rightEar.addPoint(rightEarX, catY);
rightEar.addPoint(catX + headDimension - earBase / 2, earY);
rightEar.addPoint(catX + headDimension - earBase, catY - earHeight);
// Fill ears
g2.setColor(Color.black);
g2.fillPolygon(leftEar);
g2.fillPolygon(rightEar);
}
// Method to draw the cat's eyes
private void drawEyes(Graphics2D g2, int catX, int catY) {
g2.setColor(Color.green);
int x = catX + eyeX;
int y = catY + eyeY;
g2.fillOval(x, y, eyeWidth, eyeHeight);
x += eyeSeparation;
g2.fillOval(x, y, eyeWidth, eyeHeight);
}
// Method to draw the cat's mouth
private void drawMouth(Graphics2D g2, int catX, int catY) {
g2.setColor(Color.pink);
int x = catX + mouthX;
int y = catY + mouthY;
g2.fillOval(x, y, mouthWidth, mouthHeight);
}
public static void main(String[] args) {
// Example usage:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Cat cat = new Cat(100, 25, 25, 33, 20, 10, 10, 25, 40, 60);
// Change properties using setters
cat.setHeadDimension(120); // Make the head larger
cat.setEyeY(30); // Adjust eye vertical position
cat.setEyeX(30); // Adjust eye horizontal position
cat.draw(g, 100, 100);
}
});
frame.setVisible(true);
}
// Setter for headDimension
public void setHeadDimension(int headDimension) {
this.headDimension = headDimension;
}
// Setter for eyeY
public void setEyeY(int eyeY) {
this.eyeY = eyeY;
}
// Setter for eyeX
public void setEyeX(int eyeX) {
this.eyeX = eyeX;
}
// Setter for body color
public void setBodyColor(Color color) {
this.bodyColor = color;
}
// Setter for eyecolor
public void setEyeColor(Color color) {
this.eyeColor = color;
}
// Setter for mouthcolor
public void setMouthColor(Color color) {
this.eyeColor = color;
}
}
|
import { useState } from "react";
const UseStateObject = () => {
const [person, setPerson] = useState({
name: "peter",
age: 24,
hobby: "Play cricket",
});
const { name, age, hobby } = person;
const updateDetails = () => {
setPerson({
name: "Nilesh",
age: 32,
hobby: "Play card",
});
};
return (
<>
<div>
<h3>{name}</h3>
<h3>{age}</h3>
<h3>{hobby}</h3>
</div>
<div>
<button onClick={updateDetails} type="button">
Update Details
</button>
</div>
</>
);
};
export default UseStateObject;
|
package it.uniroma3.diadia.attrezzi;
import it.uniroma3.diadia.ambienti.Stanza;
/**
* Una semplice classe che modella un attrezzo.
* Gli attrezzi possono trovarsi all'interno delle stanze
* del labirinto.
* Ogni attrezzo ha un nome ed un peso.
*
* @author docente di POO
* @see Stanza
* @version base
*/
public class Attrezzo implements Comparable<Attrezzo>{
private String nome;
private int peso;
public Attrezzo(String nome, int peso) {
this.peso = peso;
this.nome = nome;
}
@Override
public boolean equals(Object o) {
Attrezzo that = (Attrezzo)o;
return this.getPeso()==that.getPeso()&&this.getNome().equals(that.getNome());
}
@Override
public int hashCode() {
return this.getPeso()+this.getNome().hashCode();
}
public String toString() {
return this.getNome()+" ("+this.getPeso()+"kg)";
}
@Override
public int compareTo(Attrezzo that) {
if(this.getPeso()-that.getPeso()!=0)
return this.getPeso()-that.getPeso();
else
return this.getNome().compareTo(that.getNome());
}
public int getPeso() {
return this.peso;
}
public String getNome() {
return this.nome;
}
}
|
import type { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import Link from "next/link";
import { Menu, Transition } from "@headlessui/react";
import cx from "classnames";
const entries = [
{
name: "Home",
href: "/",
enabled: true,
},
{
name: "About",
href: "/about",
enabled: true,
},
{
name: "Contact",
href: "/contact",
enabled: false,
},
];
const { Button, Items, Item } = Menu;
type Props = {
name: string;
href: string;
enabled: boolean;
};
const MenuEntry = (props: Props): JSX.Element => (
<Item disabled={!props.enabled}>
{({ active }) => {
const classNames = cx("w-full", "p-2", "rounded-lg", "mt-2", "mb-2", {
"opacity-50": !props.enabled,
"bg-blue-600": active,
"text-white": active,
});
return (
<Link href={props.href} passHref>
<a className={classNames}>{props.name}</a>
</Link>
);
}}
</Item>
);
const Home: NextPage = () => {
return (
<div className="w-9/12 m-auto pt-16 pb-16">
<Menu>
<Button className="bg-purple-500 text-white p-2 pl-4 rounded-lg">
My Menu
</Button>
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform scale-95 opactiy-0"
enterTo="transform scale-100 opactiy-100"
leave="transition duration-75 ease-out"
leaveFrom="transform scale-100 opacity-100"
leaveTo="transform scale-95 opacity-0"
>
<Items className="flex flex-col w-52 mt-4 p-2 rounded-xl shadow-lg">
{entries.map((entry) => (
<MenuEntry key={entry.name} {...entry} />
))}
</Items>
</Transition>
</Menu>
</div>
);
};
export default Home;
|
package org.netxms.agent.android.main.activities;
import org.netxms.agent.android.NXApplication;
import org.netxms.agent.android.R;
import org.netxms.agent.android.service.AgentConnectorService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
/**
* Abstract base class for all activities in the client. Implements
* common functionality for connecting to service and handling common items
* in options menu.
*/
public abstract class AbstractClientActivity extends Activity implements ServiceConnection
{
private static final String TAG = "nxagent/AbstractClientActivity";
protected AgentConnectorService service;
/* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
onCreateStep2(savedInstanceState);
startService(new Intent(this, AgentConnectorService.class));
bindService(new Intent(this, AgentConnectorService.class), this, 0);
// the following is required if target API version is 14:
//getActionBar().setHomeButtonEnabled(true);
}
/**
* Called by AbstractClientActivity.onCreate before service binding
* to allow inherited classes to do initialization before onServiceConnected call
*
* @param savedInstanceState
*/
protected abstract void onCreateStep2(Bundle savedInstanceState);
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy()
{
unbindService(this);
super.onDestroy();
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume()
{
super.onResume();
NXApplication.activityResumed();
if (service != null)
service.reconnect(false);
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause()
{
super.onStop();
NXApplication.activityPaused();
}
/* (non-Javadoc)
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
/* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Log.d(TAG, "onOptionsItemSelected: id=" + android.R.id.home);
if (item.getItemId() == R.id.settings)
{
startActivity(new Intent(this, Preferences.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/* (non-Javadoc)
* @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName, android.os.IBinder)
*/
@Override
public void onServiceConnected(ComponentName name, IBinder binder)
{
service = ((AgentConnectorService.AgentConnectorBinder)binder).getService();
if (service != null)
service.reconnect(false);
}
/* (non-Javadoc)
* @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
*/
@Override
public void onServiceDisconnected(ComponentName name)
{
}
}
|
#include <iostream>
using namespace std;
template <class Type>
struct nodeType
{
Type value;
Type user;
Type id;
Type score;
Type grade;
nodeType<Type> *link;
};
template <class Type>
class linkedList {
private:
int count;
nodeType<Type> *head;
nodeType<Type> *tail;
public:
linkedList();
int length();
void loadInput(string input);
void loadCommand(string command);
void sortLoad();
void addAtLocation(string index, string cred);
void removeWithAttribute(string attribute);
void sortWithAttribute(string attribute);
void insertTail(const Type& newItem);
void insertHead(const Type& newItem);
void deleteNode(const Type& deleteItem);
void removeHead();
void removeTail();
void destroyList();
void print(ofstream &out) const;
void printInput() const;
void printCommand() const;
~linkedList();
};
template <class Type>
linkedList<Type>::linkedList()
{
head = NULL;
tail = NULL;
count = 0;
}
template <class Type>
int linkedList<Type>::length()
{
return count;
}
//this is the function help loading original info to the linked list
template <class Type>
void linkedList<Type>::loadInput(string str)
{
str.erase(remove(str.begin(), str.end(), '['), str.end());
str.erase(remove(str.begin(), str.end(), ']'), str.end());
string small="";//result as final product, small as elements contain by vector section
int n=str.length();// integer n to get string length
char arr[n];// turn string into an array of char
vector<string> section;//to contain and divide sections of the string
for(int i=0;i<n;i++){
arr[i]=str[i];
}
for(int i=0;i<n;i++){
if(i==(n-1)){//to ensure last id line is included due to the loop's nature
small+=arr[i];
section.push_back(small);
}
else if(arr[i]!=';'){
small+=arr[i];//add to string;
}
else if(arr[i]==';'){
section.push_back(small);
small="";//reset small to continue with the next section of vector;
}
}
if(section.size()<4){
return;
}
if(section[0][0]=='i' && section[1][0]=='u' && section[2][0]=='s' && section[3][0]=='g'){
nodeType<Type> *newNode = new nodeType<Type>();
newNode->id=section[0];
newNode->user=section[1];
newNode->score=section[2];
newNode->grade=section[3];
newNode->link=NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->link = newNode;
tail = newNode;
}
count++;
}else{
return;
}
}
//sortLoad function allows tha program to load input and compare id to make sure there is always updated with same id.
template<typename Type>
void linkedList<Type>::sortLoad(){
nodeType<Type> *temp3 = new nodeType<Type>();
temp3=head;
if(head == NULL){
return;
}
while(temp3->link != NULL){
nodeType<Type> *temp2 = new nodeType<Type>();
temp2=temp3;
while(temp2->link != NULL){// order is temp1 to temp2 to temp3
if(temp2->link->id == temp3->id){
temp3->user=temp2->link->user;
temp3->grade=temp2->link->grade;
temp3->score=temp2->link->score;
nodeType<Type> *dlt = temp2->link;
temp2->link=temp2->link->link;
free(dlt);
count--;
}
if(temp2->link->id !=temp3->id && temp2->link->user == temp3->user){
nodeType<Type> *dlt = temp2->link;
temp2->link=temp2->link->link;
free(dlt);
count--;
}
temp2=temp2->link;
}
temp3=temp3->link;
}
}
//loadCommand function allow loading command and distinguish between different commands
template<typename Type>
void linkedList<Type>::loadCommand(string cmd){
string small="";//result as final product, small as elements contain by vector section
int n=cmd.length();// integer n to get string length
char arr[n];// turn string into an array of char
vector<string> section;//to contain and divide sections of the string
string order="", index="", credential="";//to take parts of diseccting command order
for(int i=0;i<n;i++){
arr[i]=cmd[i];
}
for(int i=0;i<n;i++){
if(i==(n-1)){//to ensure last id line is included due to the loop's nature
small+=arr[i];
section.push_back(small);
}
else if(arr[i]!=' '){
small+=arr[i];//add to string;
}
else if(arr[i]==' '){
section.push_back(small);
small="";//reset small to continue with the next section of vector;
}
}
//assigning order, index and credential, with sorting index and credential
order=section[0];
index=section[1];
index.erase(remove(index.begin(), index.end(), '('), index.end());
index.erase(remove(index.begin(), index.end(), ')'), index.end());
if(section[0][0]=='A'){
credential=section[2];
credential.erase(remove(credential.begin(), credential.end(), '['), credential.end());
credential.erase(remove(credential.begin(), credential.end(), ']'), credential.end());
}
if(order[0]=='A'){
addAtLocation(index,credential);
}
if(order[0]=='R'){
removeWithAttribute(index);
}
if(order[0]=='S'){
sortWithAttribute(index);
}
}
template <class Type>
void linkedList<Type>::addAtLocation(string index, string credential)
{
int ind=stoi(index), pos=0;// turn index from string to integer, pos to count position
string small="";//result as final product, small as elements contain by vector section
int n=credential.length();// integer n to get string length
char arr[n];// turn string into an array of char
vector<string> section;//to contain and divide sections of the string
for(int i=0;i<n;i++){
arr[i]=credential[i];
}
for(int i=0;i<n;i++){
if(i==(n-1)){//to ensure last id line is included due to the loop's nature
small+=arr[i];
section.push_back(small);
}
else if(arr[i]!=';'){
small+=arr[i];//add to string;
}
else if(arr[i]==';'){
section.push_back(small);
small="";//reset small to continue with the next section of vector;
}
}
if(section.size()<4){
return;
}
if(section[0][0]=='i' && section[1][0]=='u' && section[2][0]=='s' && section[3][0]=='g'){
}else{
return;
}
nodeType<Type> *newNode = new nodeType<Type>();
newNode->id=section[0];
newNode->user=section[1];
newNode->score=section[2];
newNode->grade=section[3];
newNode->link=NULL;
//to detect same id but different user or same id to update the rest
int found = 0;
if(head!=NULL){
nodeType<Type> *detect;
detect = head;
while(detect!=NULL){
if(detect->id == newNode->id){
detect->score=newNode->score;
detect->grade=newNode->grade;
found = 1;
return;
}
if(detect->id!=newNode->id && detect->user==newNode->user){
return;
}
detect = detect->link;
}
}
if (found==0){
nodeType<Type> *temp= head;
nodeType<Type> *prev= NULL;
if(ind > count){
return;
}
else if( ind==0){
head=newNode;
newNode->link=temp;
}
else{
for(int i=0;i<ind;i++){
prev = temp;
temp=temp->link;
}
prev->link=newNode;
newNode->link=temp;
}
count++;
}
}
template <class Type>
void linkedList<Type>::removeWithAttribute(string index)
{
if(index[0]=='u'){//remove user
nodeType<Type> *temp = new nodeType<Type>();
temp=head;
while(temp->link!=NULL){
if(temp->link->user == index){
nodeType<Type> *dlt = temp->link;
temp->link=temp->link->link;
free(dlt);
count--;
}
temp=temp->link;
}
}
if(index[0]=='i'){//remove id
nodeType<Type> *temp = new nodeType<Type>();
temp=head;
while(temp->link!=NULL){
if(temp->link->id == index){
nodeType<Type> *dlt = temp->link;
temp->link=temp->link->link;
free(dlt);
count--;
}
temp=temp->link;
}
}
if(index[0]=='s'){//remove score
nodeType<Type> *temp = new nodeType<Type>();
temp=head;
while(temp->link!=NULL){
if(temp->link->score == index){
nodeType<Type> *dlt = temp->link;
temp->link=temp->link->link;
free(dlt);
count--;
}
temp=temp->link;
}
}
if(index[0]=='g'){//remove grade
nodeType<Type> *temp = new nodeType<Type>();
temp=head;
while(temp->link!=NULL){
if(temp->link->grade == index && temp->link->link==NULL){
nodeType<Type> *dlt = temp->link;
temp->link=temp->link->link;
free(dlt);
count--;
return;
}
if(temp->link->grade == index){
nodeType<Type> *dlt = temp->link;
temp->link=temp->link->link;
free(dlt);
count--;
}
temp=temp->link;
}
}
}
template <class Type>
void linkedList<Type>::sortWithAttribute(string index)
{
if(index[0]=='i'){//sort id
bool isSorted = false;
nodeType<Type> *cu;
nodeType<Type> *nxt;
while(!isSorted){ //while false, list is still unsorted
isSorted = true;
cu = head;
nxt = cu->link;
while(cu->link != nullptr){
if(cu->id > cu->link->id){
string tempData = cu->id;
cu->id = nxt->id;
nxt->id = tempData;
string tempDatachar = cu->grade;
cu->grade = nxt->grade;
nxt->grade = tempDatachar;
string tempDatauser = cu->user;
cu->user = nxt->user;
nxt->user = tempDatauser;
string tempDatascore = cu->score;
cu->score = nxt->score;
nxt->score = tempDatascore;
isSorted = false;
}
cu = cu->link;
nxt = cu->link;
}
}
}
if(index[0]=='u'){//sort user
bool isSorted = false;
nodeType<Type> *cu;
nodeType<Type> *nxt;
while(!isSorted){ //while false, list is still unsorted
isSorted = true;
cu = head;
nxt = cu->link;
while(cu->link != nullptr){
if(cu->user > cu->link->user){
string tempData = cu->id;
cu->id = nxt->id;
nxt->id = tempData;
string tempDatachar = cu->grade;
cu->grade = nxt->grade;
nxt->grade = tempDatachar;
string tempDatauser = cu->user;
cu->user = nxt->user;
nxt->user = tempDatauser;
string tempDatascore = cu->score;
cu->score = nxt->score;
nxt->score = tempDatascore;
isSorted = false;
}
cu = cu->link;
nxt = cu->link;
}
}
}
if(index[0]=='s'){//sort score
bool isSorted = false;
nodeType<Type> *cu;
nodeType<Type> *nxt;
while(!isSorted){ //while false, list is still unsorted
isSorted = true;
cu = head;
nxt = cu->link;
while(cu->link != nullptr){
if(cu->score < cu->link->score){
string tempData = cu->id;
cu->id = nxt->id;
nxt->id = tempData;
string tempDatachar = cu->grade;
cu->grade = nxt->grade;
nxt->grade = tempDatachar;
string tempDatauser = cu->user;
cu->user = nxt->user;
nxt->user = tempDatauser;
string tempDatascore = cu->score;
cu->score = nxt->score;
nxt->score = tempDatascore;
isSorted = false;
}
cu = cu->link;
nxt = cu->link;
}
}
}
if(index[0]=='g'){//sort grade
bool isSorted = false;
nodeType<Type> *cu;
nodeType<Type> *nxt;
while(!isSorted){ //while false, list is still unsorted
isSorted = true;
cu = head;
nxt = cu->link;
while(cu->link != nullptr){
if(cu->grade > cu->link->grade){
string tempData = cu->id;
cu->id = nxt->id;
nxt->id = tempData;
string tempDatachar = cu->grade;
cu->grade = nxt->grade;
nxt->grade = tempDatachar;
string tempDatauser = cu->user;
cu->user = nxt->user;
nxt->user = tempDatauser;
string tempDatascore = cu->score;
cu->score = nxt->score;
nxt->score = tempDatascore;
isSorted = false;
}
cu = cu->link;
nxt = cu->link;
}
}
}
}
template <class Type>
void linkedList<Type>::insertTail(const Type& newItem)
{
//complete
nodeType<Type> *newNode = new nodeType<Type>();
newNode->value = newItem;
newNode->link = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->link = newNode;
tail = newNode;
}
count++;
}
template <class Type>
void linkedList<Type>::insertHead(const Type& newItem)
{
//complete
nodeType<Type> *newNode = new nodeType<Type>();
newNode->value = newItem;
newNode->link = NULL;
if(head == NULL){
head = tail = newNode;
}
else {
newNode->link = head;
head=newNode;
}
count++;
}
template <class Type>
void linkedList<Type>::print(ofstream &out) const
{
nodeType<Type> *current; //pointer to traverse the list
current = head; //set current point to the head node
while (current != NULL ) //while more data to print
{
if(current->id!=""){
out <<"["<< current->id << ";" <<current->user << ";" << current->score << ";" << current->grade <<"]"<< endl;
current = current->link;
}
else{
current = current->link;
}
}
}
template <class Type>
void linkedList<Type>::printInput() const
{
nodeType<Type> *current; //pointer to traverse the list
current = head; //set current point to the head node
while (current != NULL) //while more data to print
{
cout << current->id << " " <<current->user << " " << current->score << " " << current->grade << endl;
current = current->link;
}
}
template <class Type>
void linkedList<Type>::printCommand() const
{
}
template <class Type>
void linkedList<Type>::destroyList()
{
nodeType<Type> *temp; //pointer to deallocate the memory occupied by the node
while (head != NULL) //while there are nodes in the list
{
temp = head; //set temp to the current node
head = head->link; //advance head to the next node
delete temp; //deallocate the memory occupied by temp
}
tail = NULL; //initialize tail to NULL; head has already been set to NULL by the while loop
count = 0;
}
template <class Type>
linkedList<Type>::~linkedList()
{
destroyList();
}
template <class Type>
void linkedList<Type>::removeHead() {
nodeType<Type> *temp;
temp = head;
if (head == NULL) {
head = NULL;
}
else if (head != NULL) {
temp = head->link;
delete head;
head = temp;
}
count--;
}
template <class Type>
void linkedList<Type>::removeTail() {
nodeType<Type> *temp;
nodeType<Type> *temp2;
temp = head;
if (temp == NULL) {
head = tail = NULL;
}
else if(temp->link==NULL) {
head=tail=NULL;
}
else{
while (temp->link!=NULL) {
temp2 = temp;
temp = temp->link;
}
temp2->link = NULL;
delete temp;
tail = temp2;
tail->link = NULL;
}
count--;
}
|
package nl.rug.aoop.networking.server;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import nl.rug.aoop.networking.client.MessageHandler;
import nl.rug.aoop.networking.client.MessageSendBack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* The ClientHandler class represents a handler for client connections in a server.
*/
@Slf4j
public class ClientHandler implements Runnable, MessageSendBack {
private final BufferedReader in;
private final PrintWriter out;
private Socket socket;
@Getter
private int id;
private MessageHandler messageHandler;
/**
* This is the constructor for a ClientHandler.
* @param socket is the client's socket.
* @param id is the unique ID assigned to this client handler.
* @param messageHandler is the message handler for processing incoming messages.
* @throws IOException if an I/O error occurs when creating the input or output streams.
*/
public ClientHandler(Socket socket, int id, MessageHandler messageHandler) throws IOException {
this.socket = socket;
this.id = id;
this.messageHandler = messageHandler;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}
@Override
public void run(){
try {
out.println(this.id);
String fromClient = in.readLine();
while(fromClient != null){
messageHandler.handleMessage(fromClient, this);
log.info("Client with id: " + id + " sent the following message: " + fromClient);
fromClient = in.readLine();
}
} catch (IOException e) {
log.error("Could not read from the client");
} finally {
terminate();
}
}
/**
* Terminates the client handler by closing the socket and stopping the thread.
*/
public void terminate(){
try {
this.in.close();
this.out.close();
this.socket.close();
} catch (IOException e) {
log.error("Could not close the socket!");
}
}
@Override
public void sendBack(String string) {
out.println(string);
}
}
|
import 'package:flutter/material.dart';
Widget DropdownWidget<T>({
T? currentValue,
required List<T> items,
required String Function(T) displayItem,
required void Function(T?) onSelected,
String hint = 'Choose one',
Color? underlineColor,
}) {
return DropdownButton<T>(
value: currentValue,
hint: Text(hint),
items: items.map((item) {
return DropdownMenuItem<T>(
value: item,
child: Text(displayItem(item)),
);
}).toList(),
onChanged: onSelected,
isExpanded: true,
underline: Container(
height: 1,
color: underlineColor ?? Colors.blue,
),
);
}
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SingleMovieResolver } from './services/resolvers/single-movie.resolver';
import { MovieSearchComponent } from './components/movie-search/movie-search.component';
import { MovieDetailsComponent } from './components/movie-details/movie-details.component';
import { MoviesComponent } from './components/movies/movies.component';
const routes: Routes = [
{path: '', pathMatch: 'full', redirectTo: 'movies'},
{path: 'movies', component: MoviesComponent},
{path: 'movies/search', component: MovieSearchComponent},
{path: 'movies/:id', component: MovieDetailsComponent, resolve: {singleMovie: SingleMovieResolver}}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import { Controller, Get, Query } from '@nestjs/common';
import { AppConfigFacade } from '@app/domains';
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AppConfigsGetRequestDto, AppConfigsGetResponseDto } from './dtos';
@ApiTags('configs')
@Controller('configs')
export class AppConfigsController {
constructor(
private readonly facade: AppConfigFacade
) {
}
@ApiOperation({ summary: 'Поиск/получение списка конфигов' })
@ApiOkResponse({ type: AppConfigsGetResponseDto })
@Get('')
find(
@Query() query: AppConfigsGetRequestDto
): Promise<AppConfigsGetResponseDto> {
return this.facade.find({
pagination: {
onPage: query.onPage,
page: query.page,
},
sorting: {
field: query.sortField,
direction: query.sortDirection,
},
});
}
}
|
# Write a Python function called max_num()to find the maximum of three numbers.
def max_num(a,b,c):
return max([a,b,c])
print(max_num(1,2,3))
print(max_num(3, 64, 1345))
print(max_num(867,5,309))
# Write a Python function called mult_list() to multiply all the numbers in a list.
def mult_list(my_list):
if len(my_list) == 0:
return 0
prod = my_list[0]
if len(my_list) > 1:
for i in my_list[1:]:
prod = prod * i
return prod
print(mult_list([1,2,3]))
print(mult_list([3,6,9]))
print(mult_list([69,420]))
# Write a Python function called rev_string() to reverse a string.
def rev_string(str):
return str[::-1]
print(rev_string("bort"))
print(rev_string("small amount of peas"))
print(rev_string("bob dylan"))
# Write a Python function called num_within() to check whether a number falls in a given range.
# The function accepts the number, beginning of range, and end of range (inclusive) as arguments.
# Examples: num_within(3,2,4) returns True, num_within(3,1,3) returns True, num_within(10,2,5) returns False.
def num_within(a,b,c):
return a in range(b,c+1)
print(num_within(3,2,4))
print(num_within(3,1,3))
print(num_within(10,2,5))
print(num_within(69,420,710))
# Write a Python function called pascal() that prints out the first n rows of Pascal's triangle.
# The function accepts the number n, the number of rows to print
# Note : Pascal's triangle is an arithmetic and geometric figure first imagined by Blaise Pascal. Each number is the two numbers above it added together.
triangle = [[1],[1,1]]
def pascal(n):
if n < 1:
print("invalid number of rows")
elif n == 1:
print(triangle[0])
else:
row_number = 2
while len(triangle) < n:
row = []
row_prev = triangle[row_number - 1]
length = len(row_prev)+1
for i in range(length):
if i == 0:
row.append(1)
elif i > 0 and i < length-1:
row.append(triangle[row_number-1][i-1]+triangle[row_number-1][i])
else:
row.append(1)
triangle.append(row)
row_number += 1
for row in triangle:
print(row)
pascal(2)
pascal(5)
|
package com.example.homefarmer.presentation
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.navigation.fragment.findNavController
import com.example.homefarmer.R
import com.example.homefarmer.databinding.FragmentPhotoCameraBinding
import java.io.File
class PhotoCameraFragment : Fragment() {
private var _binding: FragmentPhotoCameraBinding? = null
private val binding: FragmentPhotoCameraBinding
get() = _binding!!
private lateinit var imageCapture: ImageCapture
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentPhotoCameraBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
checkInternet()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun showCamera() = with(binding) {
photoScreen.isVisible = true
errorScreen.isVisible = false
launchCamera()
}
private fun showError() = with(binding) {
photoScreen.isVisible = false
errorScreen.isVisible = true
tvError.text = getString(R.string.error_internet)
btnRefreshInternet.setOnClickListener {
checkInternet()
}
}
private fun checkInternet() {
val isConnected = isInternetAvailable(requireContext())
checkCameraPermissions()
if (isConnected) {
showCamera()
} else {
showError()
}
}
@SuppressLint("ServiceCast")
fun isInternetAvailable(context: Context): Boolean {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = connectivityManager.activeNetwork ?: return false
val networkCapabilities =
connectivityManager.getNetworkCapabilities(network) ?: return false
return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
private fun launchCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder()
.build()
.also { mPreview ->
mPreview.setSurfaceProvider(
binding.cameraPreview.surfaceProvider
)
}
imageCapture = ImageCapture.Builder()
.build()
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
this@PhotoCameraFragment,
cameraSelector,
preview,
imageCapture
)
} catch (ex: Exception) {
throw RuntimeException(ex.message.toString())
}
}, ContextCompat.getMainExecutor(requireContext()))
binding.btnCapture.setOnClickListener {
takePhoto()
}
}
private fun takePhoto() {
val photoFile = File(requireContext().externalMediaDirs.first(), "photo.jpg")
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(
outputOptions,
ContextCompat.getMainExecutor(requireContext()),
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
// Путь к сохраненному изображению
val savedUri = Uri.fromFile(photoFile)
launchPlantReportFragment(savedUri.toString(), photoFile.toString())
}
override fun onError(exception: ImageCaptureException) {
Log.e("MyLog", "Photo capture failed: ${exception.message}", exception)
}
}
)
}
private fun checkCameraPermissions() {
if (!hasRequiredPermissions()) {
requestPermissions(CAMERAX_PERMISSIONS, CAMERA_PERMISSION_CODE)
}
}
private fun hasRequiredPermissions(): Boolean {
return CAMERAX_PERMISSIONS.all {
ContextCompat.checkSelfPermission(
requireContext(),
it
) == PackageManager.PERMISSION_GRANTED
}
}
private fun launchPlantReportFragment(imgPath: String, jpgPath: String) {
findNavController().navigate(
R.id.action_photoCameraFragment_to_reportFragment,
bundleOf(
REPORT_KEY to imgPath,
JPG to jpgPath,
"FROM" to "camera"
)
)
}
companion object {
private const val REPORT_KEY = "report_key"
const val JPG = "jpg"
private const val CAMERA_PERMISSION_CODE = 1
private val CAMERAX_PERMISSIONS = arrayOf(
Manifest.permission.CAMERA
)
}
}
|
//Author - Latha Davuluri
//Batch job to convert Contacts to Contact Roles on ONLY GSA and R&P Providers - LEAD-4721
global class EEC_Batch_ConvertContactToContactRole implements Database.Batchable<sObject>{
global List<Contact> dataListSize = null;
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator([SELECT c.Id, c.Role__c, c.Name, c.Contact_Processed__c, c.AccountId FROM Contact c WHERE c.AccountId != null AND c.AccountId in
(SELECT id FROM account WHERE is_GSA__c = true OR is_R_P__c = true OR RecordType.Name like '%umbrella%') AND c.Contact_Processed__c = false]);
}
global void execute(Database.BatchableContext BC,List<Contact> scope){
dataListSize = scope;
for(Contact c : scope){
EEC_ConvertContactToContactRole.convertContactToContactRole(c);
c.Contact_Processed__c = true;
}
update scope;
}
global void finish(Database.BatchableContext BC){
try{
if(dataListSize != null){
AsyncApexJob batchJob = [Select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
Integer jobs = [Select count() From AsyncApexJob Where JobType = 'BatchApex' and ( Status = 'Queued' or Status = 'Processing' or Status = 'Preparing' )];
if(jobs <= 1){
EEC_Util.batchEmailSuccess(bc, 'EEC_Batch_ConvertContactToContactRole');
}
//If NumberOfErrors is "0" - if the execute method processed all records without errors - then call next contact batch.
if (batchJob.NumberOfErrors == 0)
{
EEC_Batch_ConvertContactToContactRole batchCreateContactRole = new EEC_Batch_ConvertContactToContactRole();
Id batchProcessId = Database.executeBatch(batchCreateContactRole,1); //finish method logic here
}
else
{
//process other code
if ((batchJob.NumberOfErrors == 0) && (jobs < 5)){
EEC_Batch_ConvertContactToContactRole batchCreateContactRole = new EEC_Batch_ConvertContactToContactRole();
Id batchProcessId = Database.executeBatch(batchCreateContactRole,1); //finish method logic here
}
else{
//wait for 1 hour
}
}
}
else{
EEC_Util.batchEmailSuccess(bc, 'EEC_Batch_ConvertContactToContactRole');
}
}
catch(exception ex){
System.debug('----> Error Processing the EEC_Batch_ConvertContactToContactRole job: ' + ex.getMessage());
}
}
}
|
import { Product } from '@/types';
import Image from 'next/image';
import Link from 'next/link';
import React from 'react'
interface Props {
product: Product
}
function ProductCard({product}: Props) {
const {
_id,
title,
image,
category,
currency,
currentPrice
} = product;
return (
<Link href={`/products/${_id}`} className='product-card'>
<div className='product-card_img-container'>
<Image
src={image}
alt={title}
width={200}
height={200}
className='product-card_img'
/>
</div>
<div className='flex flex-col gap-3'>
<h3 className='product-title'>
{title}
</h3>
</div>
<div className='flex justify-between'>
<p className='text-back opacity-50 text-lg capitalize'>
{category}
</p>
<p className='text-back text-lg font-semibold'>
<span>
{currency}
</span>
<span>
{currentPrice}
</span>
</p>
</div>
</Link>
)
}
export default ProductCard
|
var stompClient = null;
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function connect() {
var socket = new SockJS('/gs-guide-websocket');
socket.onopen = function (event) {
alert("on open method invoked!!!!");
};
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
//stompClient.subscribe('/queue/greetings', function (greeting) {
// showGreeting(JSON.parse(greeting.body).content);
//});
//stompClient.subscribe('/user/' + 520 + '/queue/message', function (greeting) {
// alert(JSON.parse(greeting.body).content);
// //showGreeting(JSON.parse(greeting.body).content);
//});
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
//stompClient.subscribe('/queue/greetings', showGreeting);
})
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
alert($("#name").val());
stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));//
}
function showGreeting(message) {
//alert(JSON.parse(message.body).content);
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$("#connect").click(function () {
connect();
});
$("#disconnect").click(function () {
disconnect();
});
$("#send").click(function () {
sendName();
});
});
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
// Copyright (c) 2008 Roberto Raggi <roberto.raggi@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "CheckStatement.h"
#include "Semantic.h"
#include "AST.h"
#include "TranslationUnit.h"
#include "Scope.h"
#include "CoreTypes.h"
#include "Control.h"
#include "Symbols.h"
CPLUSPLUS_BEGIN_NAMESPACE
CheckStatement::CheckStatement(Semantic *semantic)
: SemanticCheck(semantic),
_statement(0),
_scope(0)
{ }
CheckStatement::~CheckStatement()
{ }
void CheckStatement::check(StatementAST *statement, Scope *scope)
{
Scope *previousScope = switchScope(scope);
StatementAST *previousStatement = switchStatement(statement);
accept(statement);
(void) switchStatement(previousStatement);
(void) switchScope(previousScope);
}
StatementAST *CheckStatement::switchStatement(StatementAST *statement)
{
StatementAST *previousStatement = _statement;
_statement = statement;
return previousStatement;
}
Scope *CheckStatement::switchScope(Scope *scope)
{
Scope *previousScope = _scope;
_scope = scope;
return previousScope;
}
bool CheckStatement::visit(CaseStatementAST *ast)
{
FullySpecifiedType exprTy = semantic()->check(ast->expression, _scope);
semantic()->check(ast->statement, _scope);
return false;
}
bool CheckStatement::visit(CompoundStatementAST *ast)
{
Block *block = control()->newBlock(ast->lbrace_token);
block->setStartOffset(tokenAt(ast->firstToken()).offset);
block->setEndOffset(tokenAt(ast->lastToken()).offset);
ast->symbol = block;
_scope->enterSymbol(block);
Scope *previousScope = switchScope(block->members());
for (StatementListAST *it = ast->statements; it; it = it->next) {
semantic()->check(it->statement, _scope);
}
(void) switchScope(previousScope);
return false;
}
bool CheckStatement::visit(DeclarationStatementAST *ast)
{
semantic()->check(ast->declaration, _scope);
return false;
}
bool CheckStatement::visit(DoStatementAST *ast)
{
semantic()->check(ast->statement, _scope);
FullySpecifiedType exprTy = semantic()->check(ast->expression, _scope);
return false;
}
bool CheckStatement::visit(ExpressionOrDeclarationStatementAST *ast)
{
// translationUnit()->warning(ast->firstToken(),
// "ambiguous expression or declaration statement");
if (ast->declaration)
semantic()->check(ast->declaration, _scope);
else
semantic()->check(ast->expression, _scope);
return false;
}
bool CheckStatement::visit(ExpressionStatementAST *ast)
{
FullySpecifiedType exprTy = semantic()->check(ast->expression, _scope);
return false;
}
bool CheckStatement::visit(ForeachStatementAST *ast)
{
Block *block = control()->newBlock(ast->foreach_token);
block->setStartOffset(tokenAt(ast->firstToken()).offset);
block->setEndOffset(tokenAt(ast->lastToken()).offset);
ast->symbol = block;
_scope->enterSymbol(block);
Scope *previousScope = switchScope(block->members());
if (ast->type_specifiers && ast->declarator) {
FullySpecifiedType ty = semantic()->check(ast->type_specifiers, _scope);
Name *name = 0;
ty = semantic()->check(ast->declarator, ty, _scope, &name);
unsigned location = ast->declarator->firstToken();
if (CoreDeclaratorAST *core_declarator = ast->declarator->core_declarator)
location = core_declarator->firstToken();
Declaration *decl = control()->newDeclaration(location, name);
decl->setType(ty);
_scope->enterSymbol(decl);
} else {
FullySpecifiedType exprTy = semantic()->check(ast->initializer, _scope);
(void) exprTy;
}
FullySpecifiedType exprTy = semantic()->check(ast->expression, _scope);
semantic()->check(ast->statement, _scope);
(void) switchScope(previousScope);
return false;
}
bool CheckStatement::visit(ObjCFastEnumerationAST *ast)
{
Block *block = control()->newBlock(ast->for_token);
block->setStartOffset(tokenAt(ast->firstToken()).offset);
block->setEndOffset(tokenAt(ast->lastToken()).offset);
ast->symbol = block;
_scope->enterSymbol(block);
Scope *previousScope = switchScope(block->members());
if (ast->type_specifiers && ast->declarator) {
FullySpecifiedType ty = semantic()->check(ast->type_specifiers, _scope);
Name *name = 0;
ty = semantic()->check(ast->declarator, ty, _scope, &name);
unsigned location = ast->declarator->firstToken();
if (CoreDeclaratorAST *core_declarator = ast->declarator->core_declarator)
location = core_declarator->firstToken();
Declaration *decl = control()->newDeclaration(location, name);
decl->setType(ty);
_scope->enterSymbol(decl);
} else {
FullySpecifiedType exprTy = semantic()->check(ast->initializer, _scope);
(void) exprTy;
}
semantic()->check(ast->body_statement, _scope);
(void) switchScope(previousScope);
return false;
}
bool CheckStatement::visit(ForStatementAST *ast)
{
Block *block = control()->newBlock(ast->for_token);
block->setStartOffset(tokenAt(ast->firstToken()).offset);
block->setEndOffset(tokenAt(ast->lastToken()).offset);
ast->symbol = block;
_scope->enterSymbol(block);
Scope *previousScope = switchScope(block->members());
semantic()->check(ast->initializer, _scope);
FullySpecifiedType condTy = semantic()->check(ast->condition, _scope);
FullySpecifiedType exprTy = semantic()->check(ast->expression, _scope);
semantic()->check(ast->statement, _scope);
(void) switchScope(previousScope);
return false;
}
bool CheckStatement::visit(IfStatementAST *ast)
{
Block *block = control()->newBlock(ast->if_token);
block->setStartOffset(tokenAt(ast->firstToken()).offset);
block->setEndOffset(tokenAt(ast->lastToken()).offset);
ast->symbol = block;
_scope->enterSymbol(block);
Scope *previousScope = switchScope(block->members());
FullySpecifiedType exprTy = semantic()->check(ast->condition, _scope);
semantic()->check(ast->statement, _scope);
semantic()->check(ast->else_statement, _scope);
(void) switchScope(previousScope);
return false;
}
bool CheckStatement::visit(LabeledStatementAST *ast)
{
semantic()->check(ast->statement, _scope);
return false;
}
bool CheckStatement::visit(BreakStatementAST *)
{
return false;
}
bool CheckStatement::visit(ContinueStatementAST *)
{
return false;
}
bool CheckStatement::visit(GotoStatementAST *)
{
return false;
}
bool CheckStatement::visit(ReturnStatementAST *ast)
{
FullySpecifiedType exprTy = semantic()->check(ast->expression, _scope);
return false;
}
bool CheckStatement::visit(SwitchStatementAST *ast)
{
Block *block = control()->newBlock(ast->switch_token);
block->setStartOffset(tokenAt(ast->firstToken()).offset);
block->setEndOffset(tokenAt(ast->lastToken()).offset);
ast->symbol = block;
_scope->enterSymbol(block);
Scope *previousScope = switchScope(block->members());
FullySpecifiedType condTy = semantic()->check(ast->condition, _scope);
semantic()->check(ast->statement, _scope);
(void) switchScope(previousScope);
return false;
}
bool CheckStatement::visit(TryBlockStatementAST *ast)
{
semantic()->check(ast->statement, _scope);
for (CatchClauseAST *c = ast->catch_clause_seq; c; c = c->next) {
semantic()->check(c, _scope);
}
return false;
}
bool CheckStatement::visit(CatchClauseAST *ast)
{
Block *block = control()->newBlock(ast->catch_token);
block->setStartOffset(tokenAt(ast->firstToken()).offset);
block->setEndOffset(tokenAt(ast->lastToken()).offset);
ast->symbol = block;
_scope->enterSymbol(block);
Scope *previousScope = switchScope(block->members());
semantic()->check(ast->exception_declaration, _scope);
semantic()->check(ast->statement, _scope);
(void) switchScope(previousScope);
return false;
}
bool CheckStatement::visit(WhileStatementAST *ast)
{
Block *block = control()->newBlock(ast->while_token);
block->setStartOffset(tokenAt(ast->firstToken()).offset);
block->setEndOffset(tokenAt(ast->lastToken()).offset);
ast->symbol = block;
_scope->enterSymbol(block);
Scope *previousScope = switchScope(block->members());
FullySpecifiedType condTy = semantic()->check(ast->condition, _scope);
semantic()->check(ast->statement, _scope);
(void) switchScope(previousScope);
return false;
}
CPLUSPLUS_END_NAMESPACE
|
#include "shell.h"
/**
* gettingMyEnviron - A function to make an array of strings
* from the enviorment varibales that are in linked list
* @myInfo: A pointer to myInfoObject that contains everything
* about the command
*
* Return: A pointer to a pointer
*/
char **gettingMyEnviron(myInfoObject *myInfo)
{
if ((*myInfo).environment_changed == 1 || (*myInfo).environ == NULL)
{
(*myInfo).environ = convertingNodeStringstoArray((*myInfo).environment);
(*myInfo).environment_changed = 0;
}
return ((*myInfo).environ);
}
/**
* unsetEnvVar - A function to unset a variable in the envirorment variables
* @myInfo: A variable that stores everything about the commmand
* @myVar: The name of the varibale to be deleted
*
* Return: It returns an integer that represents if we deleted a node or not
* (It means if we have updated the linked list of enviorment or not)
*/
int unsetEnvVar(myInfoObject *myInfo, char *myVar)
{
myList *myHead = (*myInfo).environment;
size_t i = 0;
char *myCP;
if (myHead == NULL || myVar == NULL)
return (0);
while (myHead != NULL)
{
myCP = startsWith((*myHead).myString, myVar);
if (myCP != NULL && *myCP == '=')
{
(*myInfo).environment_changed = delete_node_at_index(
&(*myInfo).environment, i);
i = 0;
myHead = (*myInfo).environment;
continue;
}
myHead = (*myHead).next;
i++;
}
return ((*myInfo).environment_changed);
}
/**
* settingEnvVar - A function to set an enviroment variable
* in myInfo variable
* @myInfo: A pointer to myInfo object
* @myVar: The name of the variable that we want to set
* @myValue: The value of the variable that we want to set
*
* Return: 1 on failure and 0 on success
*/
int settingEnvVar(myInfoObject *myInfo, char *myVar, char *myValue)
{
char *buf = NULL;
myList *node;
char *p;
if (!myVar|| !myValue)
return (0);
buf = malloc(_strlen(myVar) + _strlen(myValue) + 2);
if (!buf)
return (1);
_strcpy(buf, myVar);
_strcat(buf, "=");
_strcat(buf, myValue);
node = myInfo->environment;
while (node)
{
p = startsWith(node->myString, myVar);
if (p && *p == '=')
{
free(node->myString);
node->myString = buf;
myInfo->environment_changed = 1;
return (0);
}
node = node->next;
}
add_node_end(&(myInfo->environment), buf, 0);
free(buf);
myInfo->environment_changed = 1;
return (0);
}
|
class PayloadRequestRegister {
final String email;
final String password;
final String fullName;
final String rolesName;
PayloadRequestRegister(
{this.fullName = '',
this.email = '',
this.password = '',
this.rolesName = 'user'});
factory PayloadRequestRegister.fromJson(Map<String, dynamic> json) =>
PayloadRequestRegister(
fullName: json['fullName'] as String,
email: json['email'] as String,
password: json['password'] as String,
rolesName: json['rolesName'] as String);
Map<String, dynamic> toJson() => <String, dynamic>{
'fullName': this.fullName,
'email': this.email,
'password': this.password,
'rolesName': this.rolesName
};
}
|
<script lang="ts" setup>
import type { Conversation } from "~/types/chat"
const route = useRoute()
const { selectConversation } = useConversation()
const props = defineProps<{
conversations?: Conversation[] | null
}>()
onMounted(async () => {
if (props.conversations?.find((item) => item.id === route.params.id)) {
selectConversation(
props.conversations.find((item) => item.id === route.params.id),
)
} else if (route.params.id) {
await navigateTo("/c")
}
})
</script>
<template>
<div class="overflow-y-auto">
<UDivider />
<template v-if="conversations?.length">
<div v-for="item in conversations" :key="item.id" class="group">
<NuxtLink
:to="'/c/' + item.id"
class="hover:bg-gray-100 rounded flex flex-row items-center py-4 px-2 space-x-4"
exact-active-class="bg-gray-200 hover:bg-gray-200"
@click="selectConversation(item)"
>
<UAvatar
size="md"
src="https://avatars.githubusercontent.com/u/739984?v=4"
alt="Avatar"
/>
<div class="grow min-w-0">
<div class="text-lg font-semibold truncate">
{{ item.title }}
</div>
<div class="text-gray-500 truncate">
{{ item.lastMessage?.content }}
</div>
</div>
</NuxtLink>
<UDivider />
</div>
</template>
<div v-else class="p-4 text-center text-gray-500">No Conversations.</div>
</div>
</template>
|
import React, { Component } from 'react';
import InputMask from 'react-input-mask';
import sendRequest from '../SendRequest';
import './PolyAdd.css';
export class PolyAdd extends Component {
constructor(props) {
super(props);
this.state = {
clinicName: '',
addressCity: '',
addressStreet: '',
addressHouse: '',
registrationNumber: '',
schedule: '',
type: 'adult',
duplicateWarning: '',
successMessage: '',
};
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
duplicateWarning: '',
});
};
handleSubmit = (e) => {
e.preventDefault();
if (!this.isPhoneFullyEntered(this.state.registrationNumber)) {
this.setState({ duplicateWarning: 'Пожалуйста, введите полный номер телефона.' });
return;
}
sendRequest('api/Hospital/CheckDuplicate', 'POST', { clinicName: this.state.clinicName })
.then((result) => {
if (result.duplicate) {
this.setState({ duplicateWarning: 'Клиника с таким именем уже существует.' });
} else {
sendRequest('api/Hospital/CheckPhoneDuplicate', 'POST', { registrationNumber: this.state.registrationNumber })
.then((phoneResult) => {
if (phoneResult.duplicate) {
this.setState({ duplicateWarning: 'Клиника с таким номером телефона уже существует.' });
} else {
sendRequest('api/Hospital/AddHospital', 'POST', this.state)
.then((data) => {
this.setState({ successMessage: 'Поликлиника успешно добавлена.' });
setTimeout(() => {
this.setState({ successMessage: '' });
}, 2000);
console.log('Hospital added successfully:', data);
})
.catch((error) => {
console.error('Error adding hospital:', error);
});
}
})
.catch((phoneError) => {
console.error('Error checking phone duplicate:', phoneError);
});
}
})
.catch((error) => {
console.error('Error checking duplicate:', error);
});
};
isPhoneFullyEntered = (phone) => {
const phoneRegex = /\+375 \(\d{2}\) \d{3}-\d{2}-\d{2}/;
return phoneRegex.test(phone);
};
render() {
return (
<div className="form-container">
<h2>Форма для заполнения данных клиники</h2>
{this.state.successMessage && (
<div className="success-message-container">
<p className="success-message">{this.state.successMessage}</p>
</div>
)}
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="clinicName">Наименование клиники</label>
<input
type="text"
id="clinicName"
name="clinicName"
value={this.state.clinicName}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="addressCity">Город</label>
<input
type="text"
id="addressCity"
name="addressCity"
value={this.state.addressCity}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="addressStreet">Улица</label>
<input
type="text"
id="addressStreet"
name="addressStreet"
value={this.state.addressStreet}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="addressHouse">Дом</label>
<input
type="text"
id="addressHouse"
name="addressHouse"
value={this.state.addressHouse}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="registrationNumber">Номер регистратуры (телефонный номер)</label>
<InputMask
mask="+375 (99) 999-99-99"
maskChar="_"
id="registrationNumber"
name="registrationNumber"
value={this.state.registrationNumber}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="schedule">Время работы</label>
<input
type="text"
id="schedule"
name="schedule"
value={this.state.schedule}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="type">Тип клиники</label>
<select
id="type"
name="type"
value={this.state.type}
onChange={this.handleChange}
required
>
<option value="adult">Взрослая</option>
<option value="pediatric">Детская</option>
<option value="Specialized">Специализированная</option>
</select>
</div>
{this.state.duplicateWarning && (
<div className="duplicate-warning">
<p>{this.state.duplicateWarning}</p>
</div>
)}
<button type="submit">Добавить поликлинику</button>
</form>
<button className="admin-corner-button">↞</button>
</div>
);
}
}
export default PolyAdd;
|
package com.example.springjdbcmybatis3.vehicle.dao.repository;
import com.example.springjdbcmybatis3.vehicle.dao.entity.VehicleEntity;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
/**
* <code>VehicleRepository</code> interface is extension of the <code>CrudRepository</>
* interface. It is limited to demonstrating the field encryption capabilities. Do not
* use it as a reference application.
*/
@Repository
@Transactional(readOnly = true)
public class VehicleEntityXMLRepository {
@Autowired
SqlSessionFactory sqlSessionFactory;
// This query is added for compatibility with JPA version of the same application
// in the short period of time for developing of the field level encryption prototype.
// @Query("SELECT last_value FROM \"VEHICLE_id_seq\"")
public Long findNextId() {
try (SqlSession session = sqlSessionFactory.openSession()) {
Long id = session.selectOne(
"com.example.springjdbcmybatis3.vehicle.dao.VehicleEntityXMLMapper.findNextId");
return id;
}
}
@Transactional(readOnly = false)
public Optional<VehicleEntity> save(VehicleEntity entity) {
try (SqlSession session = sqlSessionFactory.openSession()) {
int res = session.insert(
"com.example.springjdbcmybatis3.vehicle.dao.VehicleEntityXMLMapper.save", entity);
return Optional.ofNullable(res > 0 ? entity : null);
}
}
public Optional<VehicleEntity> findById(Long id) {
try (SqlSession session = sqlSessionFactory.openSession()) {
VehicleEntity vehicleEntity = session.selectOne(
"com.example.springjdbcmybatis3.vehicle.dao.VehicleEntityXMLMapper.findById", id);
return Optional.ofNullable(vehicleEntity);
}
}
public Optional<VehicleEntity> findByVinNumber(String vin) {
try (SqlSession session = sqlSessionFactory.openSession()) {
VehicleEntity vehicleEntity = session.selectOne(
"com.example.springjdbcmybatis3.vehicle.dao.VehicleEntityXMLMapper.findByVinNumber", vin);
return Optional.ofNullable(vehicleEntity);
}
}
public List<VehicleEntity> findAll() {
try (SqlSession session = sqlSessionFactory.openSession()) {
List<VehicleEntity> vehicleEntities = session.selectList(
"com.example.springjdbcmybatis3.vehicle.dao.VehicleEntityXMLMapper.findAll");
return vehicleEntities;
}
}
public List<VehicleEntity> findAllByCreatedBy(String createdBy) {
try (SqlSession session = sqlSessionFactory.openSession()) {
List<VehicleEntity> vehicleEntities = session.selectList(
"com.example.springjdbcmybatis3.vehicle.dao.VehicleEntityXMLMapper.findAllCreatedBy", createdBy);
return vehicleEntities;
}
}
public List<VehicleEntity> findAllByYear(String year) {
try (SqlSession session = sqlSessionFactory.openSession()) {
List<VehicleEntity> vehicleEntities = session.selectList(
"com.example.springjdbcmybatis3.vehicle.dao.VehicleEntityXMLMapper.findAllByYear", year);
return vehicleEntities;
}
}
public boolean deleteById(Long id) {
try (SqlSession session = sqlSessionFactory.openSession()) {
int res = session.delete(
"com.example.springjdbcmybatis3.vehicle.dao.VehicleEntityXMLMapper.deleteById", id);
return res > 0;
}
}
}
|
<?php
include('../../../config.php');
$getdetails = $mysqli->query("select * from system_config LIMIT 1");
$resdetails = $getdetails->fetch_assoc();
$random = $resdetails['sysconid'];
$theid = $resdetails['sysid'];
?>
<form class="needs-validation" novalidate>
<div class="row">
<div class="col-md-6 col-12">
<div class="mb-1">
<label class="form-label" for="churchname">Church Name</label>
<input type="text" id="churchname" class="form-control" placeholder="Company Name" aria-label="Company Name" aria-describedby="churchname" required value="<?php echo $resdetails['churchname'] ?>" />
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter your church's name.</div>
</div>
</div>
<div class="col-md-6 col-12">
<div class="mb-1">
<label class="form-label" for="tagline">Tagline (Optional)</label>
<input type="text" id="tagline" class="form-control" placeholder="Tagline" aria-label="tagline" required value="<?php echo $resdetails['tagline'] ?>" />
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter tagline</div>
</div>
</div>
<div class="col-md-6 col-12">
<div class="mb-1">
<label class="form-label" for="tagline">Telephone</label>
<input type="text" id="telephone" class="form-control" placeholder="Telephone" aria-label="telephone" required value="<?php echo $resdetails['telephone'] ?>" />
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter telephone</div>
</div>
</div>
<div class="col-md-6 col-12">
<div class="mb-1">
<label class="form-label" for="logo">Logo</label>
<input id="file_upload" type="file" multiple="false" />
<div id="queue"></div>
<div class="profile-img mt-1">
<img src="../<?php echo $resdetails['logo']; ?>" style="width:100px;height:100px" class="rounded img-fluid" alt="User image">
</div>
<input type="hidden" id="selected" />
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter tagline</div>
</div>
</div>
</div>
<div class="mb-2"></div>
<button type="submit" id="configbtn" class="btn btn-primary">Update</button>
</form>
<script type="text/javascript">
$('#file_upload').uploadifive({
'auto': false,
'method': 'post',
'buttonText': 'Upload Picture',
'fileType': 'image/*',
'multi': false,
'width': 180,
"fileSizeLimit": "20MB",
'formData': {
'randno': '<?php echo $random ?>'
},
'dnd': false,
'uploadScript': 'ajaxscripts/queries/upload/configimg.php',
'onUploadComplete': function(file, data) {
console.log(data);
},
'onSelect': function(file) {
// Update selected so we know they have selected a file
$("#selected").val('yes');
},
'onCancel': function(file) {
// Update selected so we know they have no file selected
$("#selected").val('');
}
});
$("#configbtn").click(function() {
var churchname = $("#churchname").val();
var tagline = $("#tagline").val();
var telephone = $("#telephone").val();
var error = '';
if (churchname == "") {
error += "Please enter church's name \n";
$("#churchname").focus();
}
if (telephone == "") {
error += 'Please enter telephone \n';
$("#telephone").focus();
}
if (error == "") {
$.ajax({
type: "POST",
url: "ajaxscripts/queries/edit/systemconfig.php",
beforeSend: function() {
$.blockUI({
message: '<h3 style="margin-top:6px"><img src="https://jquery.malsup.com/block/busy.gif" /> Just a moment...</h3>'
});
},
data: {
churchname: churchname,
tagline: tagline,
telephone: telephone
},
success: function(text) {
$('#file_upload').uploadifive('upload');
//alert(text);
location.reload();
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
complete: function() {
$.unblockUI();
},
});
} else {
$("#error_loc").notify(error, {
position: "right"
});
}
return false;
});
</script>
|
---
permalink: expand/rebalancing-erasure-coded-data-after-adding-storage-nodes.html
sidebar: sidebar
keywords: erasure coding, EC, rebalancing, site rebalance procedure
summary: 'In some cases, you might need to rebalance erasure-coded data after you add new Storage Nodes.'
---
= Rebalance erasure-coded data after adding Storage Nodes
:icons: font
:imagesdir: ../media/
[.lead]
In some cases, you might need to rebalance erasure-coded data after you add new Storage Nodes.
.What you'll need
* You have completed the expansion steps to add the new Storage Nodes.
* You have reviewed the xref:considerations-for-rebalancing-erasure-coded-data.adoc[considerations for rebalancing erasure-coded data].
+
IMPORTANT: Only perform this procedure if the *Low Object Storage* alert has been triggered for one or more Storage Nodes at a site and you were unable to add the recommended number of new Storage Nodes.
* You understand that replicated object data will not be moved by this procedure and that the EC rebalance procedure does not consider the replicated data usage on each Storage Node when determining where to move erasure-coded data.
* You have the `Passwords.txt` file.
.About this task
When the EC rebalance procedure is running, the performance of ILM operations and S3 and Swift client operations are likely to be impacted. For this reason, you should only perform this procedure in limited cases.
NOTE: The EC rebalance procedure temporarily reserves a large amount of storage. Storage alerts might be triggered, but will resolve when the rebalance is complete. If there is not enough storage for the reservation, the EC rebalance procedure will fail. Storage reservations are released when the EC rebalance procedure completes, whether the procedure failed or succeeded.
[NOTE]
====
S3 and Swift API operations to upload objects (or object parts) might fail during the EC rebalancing procedure if they require more than 24 hours to complete. Long-duration PUT operations will fail if the applicable ILM rule uses Strict or Balanced placement on ingest. The following error will be reported:
`500 Internal Server Error`
====
.Steps
. [[review_object_storage]]Review the current object storage details for the site you plan to rebalance.
.. Select *NODES*.
.. Select the first Storage Node at the site.
.. Select the *Storage* tab.
.. Hover your cursor over the Storage Used - Object Data chart to see the current amount of replicated data and erasure-coded data on the Storage Node.
.. Repeat these steps to view the other Storage Nodes at the site.
. Log in to the primary Admin Node:
.. Enter the following command: `ssh admin@_primary_Admin_Node_IP_`
.. Enter the password listed in the `Passwords.txt` file.
.. Enter the following command to switch to root: `su -`
.. Enter the password listed in the `Passwords.txt` file.
+
When you are logged in as root, the prompt changes from `$` to `#`.
. Enter the following command:
+
`rebalance-data start --site "_site-name_"`
+
For `"_site-name_"`, specify the first site where you added new Storage Node or nodes. Enclose `site-name` in quotes.
+
The EC rebalance procedure starts, and a job ID is returned.
. Copy the job ID.
. Monitor the status of the EC rebalance procedure.
** To view the status of a single EC rebalance procedure:
+
`rebalance-data status --job-id _job-id_`
+
For `_job-id_`, specify the ID that was returned when you started the procedure.
** To view the status of the current EC rebalance procedure and any previously completed procedures:
+
`rebalance-data status`
+
[NOTE]
====
To get help on the rebalance-data command:
`rebalance-data --help`
====
+
** To view the estimated time to completion and the completion percentage for the current job, select *SUPPORT* > *Tools* > *Metrics*. Then, select *EC Overview* in the Grafana section. Look at the *Grid EC Job Estimated Time to Completion* and *Grid EC Job Percentage Completed* dashboards.
. Perform additional steps, based on the status returned:
** If the status is `In progress`, the EC rebalance operation is still running. You should periodically monitor the procedure until it completes.
** If the status is `Failure`, perform the <<rebalance_fail,failure steps>>.
** If the status is `Success`, perform the <<rebalance_succeed,success step>>.
. If the EC rebalance procedure is generating too much load (for example, ingest operations are affected), pause the procedure.
+
`rebalance-data pause --job-id _job-id_`
. If you need to terminate the EC rebalance procedure (for example, so you can perform a StorageGRID software upgrade), enter the following:
+
`rebalance-data terminate --job-id _job-id_`
+
NOTE: When you terminate an EC rebalance procedure, any data fragments that have already been moved remain in the new location. Data is not moved back to the original location.
. [[rebalance_fail]]If the status of the EC rebalance procedure is `Failure`, follow these steps:
.. Confirm that all Storage Nodes at the site are connected to the grid.
.. Check for and resolve any alerts that might be affecting these Storage Nodes.
+
For information about specific alerts, see the monitoring and troubleshooting instructions.
.. Restart the EC rebalance procedure:
+
`rebalance-data start –-job-id _job-id_`
.. If the status of the EC rebalance procedure is still `Failure`, contact technical support.
. [[rebalance_succeed]]If the status of the EC rebalance procedure is `Success`, optionally <<review_object_storage,review object storage>> to see the updated details for the site.
+
Erasure-coded data should now be more balanced among the Storage Nodes at the site.
. If you are using erasure coding at more than one site, run this procedure for all other affected sites.
|
import Videos from "./Videos";
import PlayButton from "./playButton";
import useYoutubeVideo from "../Hooks/YoutubeVideo";
// import axios from "axios";
// import { useState } from "react";
function VideoList({ updateVideo }) {
const youtubeVideos = useYoutubeVideo();
// this for fatching data
// const [youtubeVideos , setyoutubeVideos]= useState([])
// const url="https://my.api.mockaroo.com/data1.json?key=d050e840"
// async function handler(){
// const response= await axios.get(url)
// console.log("get videos" , response.data)
// setyoutubeVideos(response.data)
// }
return (
<>
<div className={`container`}>
{youtubeVideos.map((video) => (
<Videos
key={video.id}
name={video.name}
views={video.views}
time={video.time}
tick={video.tick}
image={video.image}
updateVideo={updateVideo}
id={video.id}
>
{" "}
<PlayButton
onPlay={() => console.log("play now")}
onPause={() => console.log("pause now")}
>
{video.name}
</PlayButton>
</Videos>
))}
</div>
{/* <button onClick={handler}>fatch data</button> */}
</>
);
}
export default VideoList;
|
<?php
namespace App\Http\Controllers;
use App\Subject;
use Hamcrest\Description;
use Illuminate\Support\Facades\Storage;
class SubjectController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('subject.list',[
'subject' => Subject::all()
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('subject.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store()
{
//dd(request()->all());
$data=$this->validator();
request('image')->store('public/admin/subject/');
$data['image']=request('image')->hashname();
Subject::create($data);
return redirect('subject')->with('succees','Record created successfully');
}
/**
* Display the specified resource.
*
* @param \App\Subject $subject
* @return \Illuminate\Http\Response
*/
public function show(Subject $subject)
{
return view('subject.show',compact('subject'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Subject $subject
* @return \Illuminate\Http\Response
*/
public function edit(Subject $subject)
{
return view('subject.edit',compact('subject'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Subject $subject
* @return \Illuminate\Http\Response
*/
public function update(Subject $subject)
{
$data =$this->validator();
if(request('image')):
Storage::delete('public/admin/subject/'.$subject->image);
request('image')->store('public/admin/subject/');
$image = request('image')->hashName();
else:
$image = $subject->image;
endif;
$subject->update($data);
return redirect('subject')->with('success','Record updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Subject $subject
* @return \Illuminate\Http\Response
*/
public function destroy(Subject $subject)
{
$subject->delete();
return redirect('subject')->with('success','Record deleted successfully');
}
public function validator()
{
return request()->validate([
'name'=>'required|string',
'description'=>'required|max:250',
'image'=>request()->route()->getName() == 'subject.update' ? 'nullable|image' :'required|image'
]);
}
}
|
# Percobaan 3 (penerapan multiple decorators to single function):
def title_decorator(function):
def wrapper():
func = function()
make_title = func.title()
print(make_title + " " + "-Data is convert to title case")
return make_title
return wrapper
def split_string(function):
def wrapper():
func = function()
splitted_string = func.split()
print(str(splitted_string) + " " + "- Then Data is splitted")
return splitted_string
return wrapper
# Tulis kembali fungsi decorator diatas dan tambahkan keduanya sebagai decorator
# pada fungsi say_hi berikut
@split_string
@title_decorator
def say_hi():
return 'hello there'
say_hi()
|
package com.maxijett.monetary.adapters.cashbox.rest.jpa.entity;
import com.maxijett.monetary.driver.model.DriverCash;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.math.BigDecimal;
@Getter
@Setter
@Table(name = "driver_cash")
@Entity(name = "DriverCashEntity")
public class DriverCashEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "driver_id")
private Long driverId;
@Column(name = "group_id")
private Long groupId;
@Column(name = "cash", nullable = false, columnDefinition = "Decimal(10,2) default '0.00'")
private BigDecimal cash;
@Column(name = "client_id")
private Long clientId;
@Column(name = "prepaid_collection_cash")
private BigDecimal prepaidCollectionCash;
public DriverCash toModel() {
return DriverCash.builder()
.id(getId())
.clientId(getClientId())
.groupId(getGroupId())
.cash(getCash())
.driverId(getDriverId())
.prepaidCollectionCash(getPrepaidCollectionCash()).build();
}
}
|
#' @import coda
#' @import HDInterval
#' @import grDevices
NULL
#' Add legend on crosscor.plot()
#'
#' This function use crosscor.plot() from coda, and add the
#' variables' names above the diagonal. Help understand
#' correlations problems in MCMC.
#'
#' @author Julien Bousquet (2022)
#' @param MCMC an MCMC sample from JAGS
#' @examples
#' # no example
#' @export
crosscorr <- function(MCMC) {
Ndis1 <- length(varnames(MCMC))
coda::crosscorr.plot(MCMC)
text(1:Ndis1-0.5, -0.5, 1:Ndis1,cex=0.5)
text(-0.5, Ndis1:1-0.5, 1:Ndis1,cex=0.5)
text(1:Ndis1-0.5, Ndis1:1-0.5, 1:Ndis1,cex=0.5)
text(1:Ndis1-0.5, Ndis1:1+0.5,
varnames(MCMC),srt=45 ,cex=0.5, adj=0)
}
#' Function for opening a graphic device.
#'
#' Function for opening graphics that operate the same for
#' Windows and Macintosh and Linux operating systems.
#' At least, that's the hope! writen by
#' John K. Kruschke in Doing Bayesian Data Analysis, 2nd edition, 2015
#'
#' @author John K. Kruschke (2015)
#' @param width width of the device in inches.
#' @param height height of the device in inches.
#' @param mag magnification coefficient.
#' @param ... more parameters for `dev.new()`
#' @examples
#' #openGraph()
#' hist(rnorm(2000))
#' @export
openGraph = function( width=7 , height=7 , mag=1.0 , ... ) {
if ( .Platform$OS.type != "windows" ) { # Mac OS, Linux
tryInfo = try( X11( width=width*mag , height=height*mag , type="cairo" ,
... ) ) # try dev.new if needed
if ( class(tryInfo)=="try-error" ) {
lineInput = readline("WARNING: Previous graphics windows will be closed because of too many open windows.\nTO CONTINUE, PRESS <ENTER> IN R CONSOLE.\n")
graphics.off()
X11( width=width*mag , height=height*mag , type="cairo" , ... )
}
} else { # Windows OS
tryInfo = try( dev.new( width=width*mag , height=height*mag , ... ) )
if ( class(tryInfo)=="try-error" ) {
lineInput = readline("WARNING: Previous graphics windows will be closed because of too many open windows.\nTO CONTINUE, PRESS <ENTER> IN R CONSOLE.\n")
graphics.off()
windows( width=width*mag , height=height*mag , ... )
}
}
}
#' Function for saving a graphic device.
#'
#' Function for saving graphics that operate the same for
#' Windows and Macintosh and Linux operating systems.
#' Writen by John K. Kruschke in Doing Bayesian Data Analysis, 2nd edition, 2015
#'
#' @author John K. Kruschke (2015)
#' @param file string of the name of file.
#' @param type string of the file type. 'pdf' by default, 'jpg', 'png' or 'eps' are possible.
#' @param ... more parameters for `savePlot()`
#' @examples
#' #openGraph()
#' hist(rnorm(2000))
#' #saveGraph(file='myfile', type='pdf')
#' @export
saveGraph = function( file="saveGraphOutput" , type="pdf" , ... ) {
if ( .Platform$OS.type != "windows" ) { # Mac OS, Linux
if ( any( type == c("png","jpeg","jpg","tiff","bmp")) ) {
sptype = type
if ( type == "jpg" ) { sptype = "jpeg" }
savePlot( filename=paste0(file,".",type) , type=sptype , ... )
}
if ( type == "pdf" ) {
dev.copy2pdf(file=paste0(file,".",type) , ... )
}
if ( type == "eps" ) {
dev.copy2eps(file=paste0(file,".",type) , ... )
}
} else { # Windows OS
file=paste0(file,".",type)
savePlot( filename=file , type=type , ... )
}
}
#' AutoCorrelation Plot.
#'
#' Function for plotting Auto-Correlation function graphic, usually for MCMC. Used in diagMCMC().
#' Writen by John K. Kruschke in Doing Bayesian Data Analysis, 2nd edition, 2015
#'
#' @author John K. Kruschke (2015)
#' @param codaObject coda object from an MCMC sampler.
#' @param parName string giving the name of the parameter to plot.
#' @param plColors vector of strings giving the colors of the different chains plot.
#' @export
DbdaAcfPlot = function( codaObject , parName=varnames(codaObject)[1] , plColors=NULL ) {
if ( all( parName != varnames(codaObject) ) ) {
stop("parName must be a column name of coda object")
}
nChain = length(codaObject)
if ( is.null(plColors) ) plColors=1:nChain
xMat = NULL
yMat = NULL
for ( cIdx in 1:nChain ) {
acfInfo = acf(codaObject[,c(parName)][[cIdx]],plot=FALSE)
xMat = cbind(xMat,acfInfo$lag)
yMat = cbind(yMat,acfInfo$acf)
}
matplot( xMat , yMat , type="o" , pch=20 , col=plColors , ylim=c(0,1) ,
main="" , xlab="Lag" , ylab="Autocorrelation" )
abline(h=0,lty="dashed")
EffChnLngth = effectiveSize(codaObject[,c(parName)])
text( x=max(xMat) , y=max(yMat) , adj=c(1.0,1.0) , cex=1.25 ,
labels=paste("ESS =",round(EffChnLngth,1)) )
}
#' Density Plot.
#'
#' Function for plotting Density graphics, usually for MCMC. Used in diagMCMC().
#' Writen by John K. Kruschke in Doing Bayesian Data Analysis, 2nd edition, 2015
#'
#' @author John K. Kruschke (2015)
#' @param codaObject coda object from an MCMC sampler.
#' @param parName string giving the name of the parameter to plot.
#' @param plColors vector of strings giving the colors of the different chains plot.
#' @export
DbdaDensPlot = function( codaObject , parName=varnames(codaObject)[1] , plColors=NULL ) {
if ( all( parName != varnames(codaObject) ) ) {
stop("parName must be a column name of coda object")
}
nChain = length(codaObject) # or nchain(codaObject)
if ( is.null(plColors) ) plColors=1:nChain
xMat = NULL
yMat = NULL
hdiLims = NULL
for ( cIdx in 1:nChain ) {
densInfo = density(codaObject[,c(parName)][[cIdx]])
xMat = cbind(xMat,densInfo$x)
yMat = cbind(yMat,densInfo$y)
hdiLims = cbind(hdiLims,hdi(codaObject[,c(parName)][[cIdx]]))
}
matplot( xMat , yMat , type="l" , col=plColors ,
main="" , xlab="Param. Value" , ylab="Density" )
abline(h=0)
points( hdiLims[1,] , rep(0,nChain) , col=plColors , pch="|" )
points( hdiLims[2,] , rep(0,nChain) , col=plColors , pch="|" )
text( mean(hdiLims) , 0 , "95% HDI" , adj=c(0.5,-0.2) )
EffChnLngth = effectiveSize(codaObject[,c(parName)])
MCSE = sd(as.matrix(codaObject[,c(parName)]))/sqrt(EffChnLngth)
text( max(xMat) , max(yMat) , adj=c(1.0,1.0) , cex=1.25 ,
paste("MCSE =\n",signif(MCSE,3)) )
}
#' Graphics for Diagnostic of MCMC chains' convergence, in coda format.
#'
#' Usual diagnostic statistics to assess convergence of one paramater of an MCMC chains : traceplot, Gelman shrinkage
#' coefficient, autocorrelation, and density plots.
#' Writen by John K. Kruschke in Doing Bayesian Data Analysis, 2nd edition, 2015
#'
#' @author John K. Kruschke (2015)
#' @param codaObject coda object from an MCMC sampler.
#' @param parName string giving the name of the parameter to plot.
#' @param saveName a string giving the name of the file to write the image.
#' @param saveType a string giving the saving format of the image. : 'jpg', 'png', 'eps'.
#' @export
diagMCMC = function( codaObject , parName=varnames(codaObject)[1] ,
saveName=NULL , saveType="jpg" ) {
DBDAplColors = c("skyblue","black","royalblue","steelblue")
openGraph(height=5,width=7)
par( mar=0.5+c(3,4,1,0) , oma=0.1+c(0,0,2,0) , mgp=c(2.25,0.7,0) ,
cex.lab=1.5 )
layout(matrix(1:4,nrow=2))
# traceplot and gelman.plot are from CODA package:
coda::traceplot( codaObject[,c(parName)] , main="" , ylab="Param. Value" ,
col=DBDAplColors )
tryVal = try(
coda::gelman.plot( codaObject[,c(parName)] , main="" , auto.layout=FALSE ,
col=DBDAplColors )
)
# if it runs, gelman.plot returns a list with finite shrink values:
if ( class(tryVal)=="try-error" ) {
plot.new()
print(paste0("Warning: coda::gelman.plot fails for ",parName))
} else {
if ( class(tryVal)=="list" & !is.finite(tryVal$shrink[1]) ) {
plot.new()
print(paste0("Warning: coda::gelman.plot fails for ",parName))
}
}
DbdaAcfPlot(codaObject,parName,plColors=DBDAplColors)
DbdaDensPlot(codaObject,parName,plColors=DBDAplColors)
mtext( text=parName , outer=TRUE , adj=c(0.5,0.5) , cex=2.0 )
if ( !is.null(saveName) ) {
saveGraph( file=paste0(saveName,"Diag",parName), type=saveType)
}
}
#' Summarize posterior MCMC
#'
#' Summarizing distribution of a large sample;
#' typically applied to MCMC posterior, writen by
#' John K. Kruschke in Doing Bayesian Data Analysis, 2nd edition
#'
#' @author John K. Kruschke (2015)
#' @param paramSampleVec the vector of the MCMC parameter's sample.
#' @param compVal numeric : value to compare.
#' @param ROPE vector of 2 limits defining the Range Of Practical Equivalence.
#' @param credMass the mass of credibility in the High Density Interval, 0.95 by default.
#' @return the vector of mcmc summary values.
#' @examples
#' summarizePost(rnorm(2000), ROPE=c(-1,1), compVal=0)
#' @export
summarizePost <- function( paramSampleVec ,
compVal=NULL , ROPE=NULL , credMass=0.95 ) {
meanParam = mean( paramSampleVec )
medianParam = median( paramSampleVec )
dres = density( paramSampleVec )
modeParam = dres$x[which.max(dres$y)]
mcmcEffSz = round( effectiveSize( paramSampleVec ) , 1 )
names(mcmcEffSz) = NULL
hdiLim = HDInterval::hdi( paramSampleVec , credMass=credMass )
if ( !is.null(compVal) ) {
pcgtCompVal = ( 100 * sum( paramSampleVec > compVal )
/ length( paramSampleVec ) )
} else {
compVal=NA
pcgtCompVal=NA
}
if ( !is.null(ROPE) ) {
pcltRope = ( 100 * sum( paramSampleVec < ROPE[1] )
/ length( paramSampleVec ) )
pcgtRope = ( 100 * sum( paramSampleVec > ROPE[2] )
/ length( paramSampleVec ) )
pcinRope = 100-(pcltRope+pcgtRope)
} else {
ROPE = c(NA,NA)
pcltRope=NA
pcgtRope=NA
pcinRope=NA
}
return( c( Mean=meanParam , Median=medianParam , Mode=modeParam ,
ESS=mcmcEffSz ,
HDImass=credMass , HDIlow=hdiLim[1] , HDIhigh=hdiLim[2] ,
CompVal=compVal , PcntGtCompVal=pcgtCompVal ,
ROPElow=ROPE[1] , ROPEhigh=ROPE[2] ,
PcntLtROPE=pcltRope , PcntInROPE=pcinRope , PcntGtROPE=pcgtRope ) )
}
#' Plot posterior MCMC
#' Plot the histogram of posterior MCMC, writen by
#' John K. Kruschke in Doing Bayesian Data Analysis, 2nd edition
#'
#' @author John K. Kruschke (2015)
#' @param paramSampleVec the vector of the MCMC parameter's sample
#' @param cenTend "mode" by default for Central Tendency. Possible other values are "median", or "mean".
#' @param compVal numeric : value to compare.
#' @param ROPE vector of 2 limits defining the Range Of Practical Equivalence
#' @param credMass the mass of credibility in the High Density Interval
#' @param HDItextPlace by default 0.7 : position of the text "HDI".
#' @param showCurve a boolean. FALSE by default. If TRUE, plot the curve of density instead off histogram.
#' @param ... other parameters given to hist() function, such xlab, xlim, yaxt, etc.
#' @return Plot the histogram of the mcmcm values. Return the vector of mcmc summary values.
#' @examples
#' plotPost(rnorm(2000), ROPE=c(-1,1), compVal=0)
#' @export
plotPost <- function( paramSampleVec ,
cenTend="mode" ,
compVal=NULL, ROPE=NULL, credMass=0.95, HDItextPlace=0.7,
xlab=NULL , xlim=NULL , yaxt=NULL , ylab=NULL ,
main=NULL , cex=NULL , cex.lab=NULL ,
col=NULL , border=NULL , showCurve=FALSE , breaks=NULL ,
... ) {
# Override defaults of hist function, if not specified by user:
# (additional arguments "..." are passed to the hist function)
if ( is.null(xlab) ) xlab="Param. Val."
if ( is.null(cex.lab) ) cex.lab=1.5
if ( is.null(cex) ) cex=1.4
if ( is.null(xlim) ) xlim=range( c( compVal , ROPE , paramSampleVec ) )
if ( is.null(main) ) main=""
if ( is.null(yaxt) ) yaxt="n"
if ( is.null(ylab) ) ylab=""
if ( is.null(col) ) col="skyblue"
if ( is.null(border) ) border="white"
# convert coda object to matrix:
if ( "mcmc.list" %in% class(paramSampleVec)) {
paramSampleVec = as.matrix(paramSampleVec)
}
summaryColNames = c("ESS","mean","median","mode",
"hdiMass","hdiLow","hdiHigh",
"compVal","pGtCompVal",
"ROPElow","ROPEhigh","pLtROPE","pInROPE","pGtROPE")
postSummary = matrix( NA , nrow=1 , ncol=length(summaryColNames) ,
dimnames=list( c( xlab ) , summaryColNames ) )
# require(coda) # for effectiveSize function
postSummary[,"ESS"] = coda::effectiveSize(paramSampleVec)
postSummary[,"mean"] = mean(paramSampleVec)
postSummary[,"median"] = median(paramSampleVec)
mcmcDensity = density(paramSampleVec)
postSummary[,"mode"] = mcmcDensity$x[which.max(mcmcDensity$y)]
HDI = HDInterval::hdi( paramSampleVec , credMass )
postSummary[,"hdiMass"]=credMass
postSummary[,"hdiLow"]=HDI[1]
postSummary[,"hdiHigh"]=HDI[2]
# Plot histogram.
cvCol = "darkgreen"
ropeCol = "darkred"
if ( is.null(breaks) ) {
if ( max(paramSampleVec) > min(paramSampleVec) ) {
breaks = c( seq( from=min(paramSampleVec) , to=max(paramSampleVec) ,
by=(HDI[2]-HDI[1])/18 ) , max(paramSampleVec) )
} else {
breaks=c(min(paramSampleVec)-1.0E-6,max(paramSampleVec)+1.0E-6)
border="skyblue"
}
}
if ( !showCurve ) {
par(xpd=NA)
histinfo = hist( paramSampleVec , xlab=xlab , yaxt=yaxt , ylab=ylab ,
freq=F , border=border , col=col ,
xlim=xlim , main=main , cex=cex , cex.lab=cex.lab ,
breaks=breaks , ... )
}
if ( showCurve ) {
par(xpd=NA)
histinfo = hist( paramSampleVec , plot=F )
densCurve = density( paramSampleVec , adjust=2 )
plot( densCurve$x , densCurve$y , type="l" , lwd=5 , col=col , bty="n" ,
xlim=xlim , xlab=xlab , yaxt=yaxt , ylab=ylab ,
main=main , cex=cex , cex.lab=cex.lab , ... )
}
cenTendHt = 0.9*max(histinfo$density)
cvHt = 0.7*max(histinfo$density)
ROPEtextHt = 0.55*max(histinfo$density)
# Display central tendency:
mn = mean(paramSampleVec)
med = median(paramSampleVec)
mcmcDensity = density(paramSampleVec)
mo = mcmcDensity$x[which.max(mcmcDensity$y)]
if ( cenTend=="mode" ){
text( mo , cenTendHt ,
bquote(mode==.(signif(mo,3))) , adj=c(.5,0) , cex=cex )
}
if ( cenTend=="median" ){
text( med , cenTendHt ,
bquote(median==.(signif(med,3))) , adj=c(.5,0) , cex=cex , col=cvCol )
}
if ( cenTend=="mean" ){
text( mn , cenTendHt ,
bquote(mean==.(signif(mn,3))) , adj=c(.5,0) , cex=cex )
}
# Display the comparison value.
if ( !is.null( compVal ) ) {
pGtCompVal = sum( paramSampleVec > compVal ) / length( paramSampleVec )
pLtCompVal = 1 - pGtCompVal
lines( c(compVal,compVal) , c(0.96*cvHt,0) ,
lty="dotted" , lwd=2 , col=cvCol )
text( compVal , cvHt ,
bquote( .(round(100*pLtCompVal,1)) * "% < " *
.(signif(compVal,3)) * " < " *
.(round(100*pGtCompVal,1)) * "%" ) ,
adj=c(pLtCompVal,0) , cex=0.8*cex , col=cvCol )
postSummary[,"compVal"] = compVal
postSummary[,"pGtCompVal"] = pGtCompVal
}
# Display the ROPE.
if ( !is.null( ROPE ) ) {
pInROPE = ( sum( paramSampleVec > ROPE[1] & paramSampleVec < ROPE[2] )
/ length( paramSampleVec ) )
pGtROPE = ( sum( paramSampleVec >= ROPE[2] ) / length( paramSampleVec ) )
pLtROPE = ( sum( paramSampleVec <= ROPE[1] ) / length( paramSampleVec ) )
lines( c(ROPE[1],ROPE[1]) , c(0.96*ROPEtextHt,0) , lty="dotted" , lwd=2 ,
col=ropeCol )
lines( c(ROPE[2],ROPE[2]) , c(0.96*ROPEtextHt,0) , lty="dotted" , lwd=2 ,
col=ropeCol)
text( mean(ROPE) , ROPEtextHt ,
bquote( .(round(100*pLtROPE,1)) * "% < " * .(ROPE[1]) * " < " *
.(round(100*pInROPE,1)) * "% < " * .(ROPE[2]) * " < " *
.(round(100*pGtROPE,1)) * "%" ) ,
adj=c(pLtROPE+.5*pInROPE,0) , cex=1 , col=ropeCol )
postSummary[,"ROPElow"]=ROPE[1]
postSummary[,"ROPEhigh"]=ROPE[2]
postSummary[,"pLtROPE"]=pLtROPE
postSummary[,"pInROPE"]=pInROPE
postSummary[,"pGtROPE"]=pGtROPE
}
# Display the HDI.
lines( HDI , c(0,0) , lwd=4 , lend=1 )
text( mean(HDI) , 0 , bquote(.(100*credMass) * "% HDI" ) ,
adj=c(.5,-1.7) , cex=cex )
text( HDI[1] , 0 , bquote(.(signif(HDI[1],3))) ,
adj=c(HDItextPlace,-0.5) , cex=cex )
text( HDI[2] , 0 , bquote(.(signif(HDI[2],3))) ,
adj=c(1.0-HDItextPlace,-0.5) , cex=cex )
par(xpd=F)
#
return( postSummary )
}
|
import { PayloadAction, createSlice } from '@reduxjs/toolkit'
export interface ThemeState {
dark:boolean
}
const initialState: ThemeState = {
dark: false,
}
export const uiSlice = createSlice({
name: 'ui-slice',
initialState,
reducers: {
dark: (state, action: PayloadAction<ThemeState>) => {
state.dark = action.payload.dark ;
}
},
})
// Action creators are generated for each case reducer function
export const themeStore = uiSlice.actions
|
import React, { useEffect } from "react";
import { ContactUsContainer } from "./contact.us.styles";
import Map from "../../components/map/Map";
import PageTitle from "../../components/page.title/PageTitle";
import { Link } from "react-router-dom";
import CallIcon from '@mui/icons-material/Call';
import EmailIcon from '@mui/icons-material/Email';
import FacebookIcon from '@mui/icons-material/Facebook';
// import TwitterIcon from '@mui/icons-material/Twitter';
import LinkedInIcon from '@mui/icons-material/LinkedIn';
import YouTubeIcon from '@mui/icons-material/YouTube';
import MessageBox from "../../components/message.box/MessageBox";
import localdb from "../../utils/localdb";
import observer from "../../utils/observer";
import { FaXTwitter } from "react-icons/fa6";
const ContactUs = () => {
useEffect(() => {
window.scrollTo(0, 0);
const anime = document.querySelectorAll(".anime");
observer(Object.values(anime));
}, []);
return (
<ContactUsContainer>
{/* CONTACT US SECTION */}
<section className="contact-us-section">
<PageTitle pageName="Contact Us"/>
</section>
{/* ADDRESS SECTION */}
<section className="address-section">
<div className="address-wrapper">
{/* ADDRESS HEADER TITLE */}
<h4 className="address-header-title anime" data-move="move-up">Contact Details</h4>
{/* ALL ADDRESS CONTAINER */}
<div className="all-address-container">
{/* TOP ADDRESS WRAPPER */}
<div className="top-address-wrapper">
{/* CONTACT NUMBER CONTAINER*/}
<div className="contact-number-container type-container">
{/* CONTACT NUMBER HEADER TITLE */}
<h4 className="contact-number-header-title type-header-title anime" data-move="move-up" data-delay={0.2}>Contact Number</h4>
{/* CONTACT NUMBER CONTENT */}
<Link to="tel:9644002222">
<div className="contaict-number-content type-content anime" data-move="move-right" data-delay={0.4}>
<CallIcon className="mui-icon" /> +91 96 44 00 22 22
</div>
</Link>
</div>
{/* EMAIL ADDRESS CONTAINER*/}
<div className="email-address-container type-container">
{/* EMAIL ADDRESS HEADER TITLE */}
<h4 className="email-address-header-title type-header-title anime" data-move="move-up" data-delay={0.2}>Email</h4>
{/* EMAIL ADDRESS CONTENT */}
<Link to="mailto:bishnusteel@gmail.com">
<div className="email-address-content type-content anime" data-move="move-right" data-delay={0.4}>
<EmailIcon className="mui-icon" /> bishnusteel@gmail.com
</div>
</Link>
</div>
{/* SOCIAL MEDIA CONTAINER */}
<div className="social-media-container type-container">
{/* SOCIAL MEDIA HEADER TITLE */}
<h4 className="social-media-header-title type-header-title anime" data-move="move-up" data-delay={0.2}>Social Media</h4>
{/* SOCIAL MEDIA CONTENT */}
<div className="social-media-content type-content">
<Link to="https://www.facebook.com" target="_blank"><FacebookIcon className="mui-icon anime" data-move="zoom-out" data-delay={0.3} /></Link>
<Link to="https://www.twitter.com" target="_blank"><FaXTwitter className="mui-icon anime" data-move="zoom-out" data-delay={0.5} /></Link>
<Link to="https://www.linkedin.com" target="_blank"><LinkedInIcon className="mui-icon anime" data-move="zoom-out" data-delay={0.7} /></Link>
<Link to="https://www.youtube.com" target="_blank"><YouTubeIcon className="mui-icon anime" data-move="zoom-out" data-delay={0.9} /></Link>
</div>
</div>
</div>
{/* BOTTOM ADDRESS WRAPPER */}
<div className="bottom-address-wrapper">
{/* OFFICE ADDRESS CONTAINER*/}
<div className="office-address-container type-container">
{/* OFFICE ADDRESS HEADER TITLE */}
<h4 className="office-address-header-title type-header-title anime" data-move="move-up" data-delay={0.2}>Office Address</h4>
{/* OFFICE ADDRESS CONTENT */}
<Link to={`https://www.google.com/maps/dir//${localdb.bsLocation.lat},%20${localdb.bsLocation.long}`} target="_blank">
<p className="office-address-content type-content anime" data-move="move-right" data-delay={0.4}>
Plot No-836/2476, Khta No-238/1577, Khordha Mouza, Maa Barunei Road, Garh khordha, Near Khordha Industrial Area, Khordha, Odisha, 752057
</p>
</Link>
</div>
</div>
</div>
</div>
</section>
{/* MAP SECTION */}
<section className="map-section">
{/* MAP WRAPPER */}
<div className="map-wrapper">
{/* MAP HEADER TEXT */}
<h4 className="locate-us-heading anime" data-move="move-up">Find Us On Earth.</h4>
{/* MAP CONTAINER */}
<div className="map-container anime" data-move="move-up" data-delay={0.4}>
<Map />
</div>
</div>
</section>
{/* NEED HELP SECTION */}
<section className="need-help">
<MessageBox />
</section>
</ContactUsContainer>
);
};
export default ContactUs;
|
import Image, { StaticImageData } from "next/image";
import { ReactElement } from "react";
import Button from "components/button/default/Button";
import commonStyles from "sections/common/section.module.css";
interface ContentProps {
image: {
src: StaticImageData;
alt: string;
};
isAlternate?: boolean;
id: string;
nextId?: string;
children: React.ReactNode;
isCenter?: boolean;
nextButtonLabel?: string;
titleContent: string;
hasBigContent?: boolean;
}
const Content: React.FC<ContentProps> = ({
image,
isAlternate,
id,
nextId,
children,
isCenter,
nextButtonLabel,
titleContent,
hasBigContent,
}: ContentProps): ReactElement => {
const { src, alt } = image || {};
const sectionClassName = [
commonStyles.section,
isAlternate ? commonStyles.sectionAlternate : commonStyles.sectionClassic,
hasBigContent && commonStyles.sectionBigContent,
]
.filter(Boolean)
.join(" ");
const imageWrapperClassName = [
commonStyles.textWithImageWrapper,
isAlternate && commonStyles.textWithImageWrapperAlternate,
isCenter && commonStyles.textWithImageWrapperCenter,
]
.filter(Boolean)
.join(" ");
return (
<section id={id} className={sectionClassName}>
<Button className={commonStyles.buttonContact} alternate href="/contact">
Contact
</Button>
<div className={commonStyles.content}>
<h3 className={commonStyles.titleContent}>{titleContent}</h3>
{src && (
<div className={imageWrapperClassName}>
<Image src={src} alt={alt} className={commonStyles.image} />
<div className={commonStyles.texts}>{children}</div>
</div>
)}
{nextId && nextButtonLabel && (
<Button href={nextId} className={commonStyles.sectionButton}>
{nextButtonLabel}
</Button>
)}
</div>
</section>
);
};
export default Content;
|
# محررات الأكواد
محرر الأكواد هو المكان الذي يقضي فيه المبرمجون معظم وقتهم.
يوجد نوعين من محررات الأكواد: IDEs (بيئة التطوير الكاملة) والمحررات البسيطة. العديد من الناس يستخدمون أداة واحدة لكل نوع.
## IDE
مصطلح [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) (Integrated Development Environment) يشير إلى محرر بإمكانات هائلة، مع العديد من المميزات التي تعمل عادة على "مشروع كامل". كما يوحي الاسم، فهو ليس مجرد محرر أكواد، ولكنه "بيئة تطوير" واسعة النطاق.
IDE تقوم بتحميل المشروع (الذي يمكن أن يتكون من العديد من الملفات)، ويسمح بالتنقل بين الملفات، ويوفر خاصة الإكمال التلقائي المعتمدة على المشروع ككل ( وليس الملف المفتوح فقط)، كما أنه يمكن أن يرتبط مع أنظمة إدارة الإصدار (مثل [git](https://git-scm.com/))، وبيئة الاختبار، وغيرها من الأشياء على مستوى المشروع.
إذا لم تقم باختيار IDE بعد، ففكر في الخيارات التالية:
- [فيجوال ستديو كود](https://code.visualstudio.com/) (يعمل على أكثر من نظام تشغيل، مجاني).
- [ويب ستورم](http://www.jetbrains.com/webstorm/) (يعمل على أكثر من نظام تشغيل، مدفوع).
بالنسبة للويندوز، يمكن استخدام برنامج فيجوال ستديو، لايجب الخلط بينه وبين الفيجوال ستديو كود، فيجوال ستديو هو محرر مدفوع يعمل على نظام ويندوز فقط، ومناسب تماماً لبيئة الـ.NET. أنه أيضاً جيد لجافا سكريبت. كما يوجد إصدار مجاني منه [Visual Studio Community](https://www.visualstudio.com/vs/community/).
عادة ما تكون تكلفتها ضئيلة للغاية مقارنة براتب المطور المؤهل، لذلك فقط اختر الأفضل بالنسبة لك. العديد من بيئات التطوير مدفوعة، لكن لها فترة سماحية.
## المحررات البسيطة
المحررات البسيطة ليست بقوة البيئات التطوير لكنها سريعة، وأنيقة وبسيطة، يتم استخدامها بشكل رئيس لفتح وتحرير ملف على الفور.
الفارق الرئيس بين المحررات البسيطة وبيئة التطوير هو أن بيئة التطوير تعمل على مستوى المشروع، لذلك فإنها تقوم بتحميل المزيد من البيانات عند البدء، وتحليل هيكل المشروع إذا لزم ذلك. أما المحررات البسيطة فإنها أسرع في حال نريد ملف واحد فقط.
من الناحية العملية، قد تحتوي المحررات البسيطة على الكثير من المكونات الإضافية بما في ذلك محللات بناء الجملة على مستوى الدليل وأجهزة الإكمال التلقائي، لذلك لا توجد حدود صارمة بين المحرر البسيط وبيئة التطوير.
الخيارات التالية تستحق انتباهك:
- [Atom](https://atom.io/) (يعمل على العديد من أنظمة التشغيل، مجاني).
- [Visual Studio Code](https://code.visualstudio.com/) (يعمل على العديد من أنظمة التشغيل، مجاني).
- [Sublime Text](http://www.sublimetext.com) (يعمل على العديد من أنظمة التشغيل، برنامج مشاركة).
- [Notepad++](https://notepad-plus-plus.org/) (الويندوز، مجاني).
- [Vim](http://www.vim.org/) و [Emacs](https://www.gnu.org/software/emacs/) رائعة إذا كنت تعرف كيفية استخدامها.
## دعونا لا نتشاجر
المحررات أعلاه هي التي نقوم باستخدامها أنا وأصدقائي، والذين أعتقد أنهم مطورون جيدون يستخدمونها منذ وقت طويل وتسعدهم.
يوجد أيضاً محررات رائعة في عالمنا الكبير، الرجاء اختيار المحرر الذي تفضله.
اختيار المحرر، مثل أي أداة أخرى، هو اختيار فردي ويعتمد على مشروعاتك، وعاداتك، وتفضيلاتك الشخصية.
|
library(tidyverse)
library(openxlsx)
library(gghighlight)
Mycol <- c("#08306B", "#238B45", "#FD8D3C", "#D4B9DA", "#FFEDA0")
# 記事:「北欧の出生率の急激な減少は社会経済的地位の低いグループがけん引か?」https://note.com/rmogimogi/n/n46dbd0507d1e
# データ読み込み
# data is from Human Fertility Database:https://www.humanfertility.org/Home/Index. Accessed on 25/05/2023
childless <- read.xlsx(".xlsx", sheet = "Cohort childlessness", startRow = 2)[-1, ]
# 図1
childless %>%
as.data.frame() %>%
rename(cohort = COUNTRY) %>%
gather(key = country, value = childless, -cohort) %>%
mutate(childless = as.numeric(as.character(childless)),
childless = ifelse(childless == 0, NA_real_, childless),
cohort = as.numeric(as.character(cohort))) %>%
filter(country %in% c("Denmark", "Finland", "Norway", "Sweden")) %>%
mutate(country = case_when(country == "Sweden" ~ "スウェーデン",
country == "Denmark" ~ "デンマーク",
country == "Finland" ~ "フィンランド",
country == "Norway" ~ "ノルウェー",
T ~ "日本")) %>%
ggplot(aes(x = cohort, y = childless)) +
facet_wrap(~ country) +
geom_line(aes(colour = country), size = 1.2) +
gghighlight(use_direct_label = F) +
xlim(1950, 1980) +
labs(x = "出生年", y = "44歳以上の女性における無子割合",
caption = "データソース:Human Fertility Database. 作成者:茂木良平") +
theme_minimal(base_family = "HiraKakuPro-W3") +
theme(legend.title = element_blank(),
legend.position = "none",
strip.text.x = element_text(size = 12),
axis.text = element_text(size = 12),
axis.title = element_text(size = 15))
ggsave("out/nordic-childless.png", width = 8, height = 6, bg = "white")
|
<mat-vertical-stepper [linear]="false" #stepper animationDuration="1000">
<mat-step [stepControl]="costObjectFormGroup">
<ng-template matStepLabel>Objeto de costo</ng-template>
<section class="stepper-section">
<form [formGroup]="costObjectFormGroup" class="stepper-form">
<mat-form-field class="mat-field">
<mat-label>Código</mat-label>
<input matInput formControlName="code">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Nombre</mat-label>
<input matInput formControlName="name">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Cantidad</mat-label>
<input matInput type="number" placeholder="0" formControlName="cant">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Descripción</mat-label>
<input matInput formControlName="description">
</mat-form-field>
<div>
<button mat-raised-button matStepperNext>Next</button>
<button mat-flat-button color="primary" (click)="onSaveCostObject()"
[disabled]="costObjectFormGroup.status == 'INVALID'">{{costObjectButtonText}}</button>
</div>
</form>
<section class="stepper-detail">
<h3>Detalles</h3>
<app-base-table [columns]="costObjectTableColumns" [data]="costObjectDataSource" [config]="tableConfig"
(action)="onTableActionCostObject($event)"></app-base-table>
</section>
</section>
</mat-step>
<mat-step [stepControl]="directCostElementFormGroup">
<ng-template matStepLabel>Elementos de costeo Directos</ng-template>
<mat-vertical-stepper [linear]="false" #stepper animationDuration="1000">
<mat-step [stepControl]="directLaborFormGroup">
<section class="stepper-section">
<form [formGroup]="directLaborFormGroup" class="stepper-form">
<ng-template matStepLabel>Mano de obra directa</ng-template>
<mat-form-field class="mat-field">
<mat-label>Personal</mat-label>
<input matInput formControlName="labor">
</mat-form-field>
<mat-form-field floatLabel="always" class="mat-field">
<mat-label>Costo Soles/mes</mat-label>
<input matInput type="number" placeholder="0" formControlName="cost">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Creiterio de Reparto</mat-label>
<input matInput formControlName="criterioReparto">
</mat-form-field>
<mat-form-field class="mat-field" *ngFor="let costObject of costObjectDataSource">
<mat-label>{{costObject.name}}</mat-label>
<input matInput type="number" [formControlName]="costObject.code">
</mat-form-field>
<div>
<button mat-flat-button matStepperPrevious>Back</button>
<button mat-flat-button matStepperNext>Next</button>
<button mat-flat-button color="accent" (click)="showTableDirectLabor()">Refrescar tabla</button>
<button mat-flat-button color="primary"
(click)="onSaveDirectLabor()">{{directLaborButtonText}}</button>
</div>
</form>
<section class="stepper-detail">
<h3>Detalles</h3>
<div *ngIf="showTableIndirectElements">
<app-base-table [columns]="directLaborTableColumns" [data]="directLaborDataSource"
[config]="tableConfig" (action)="onTableActionDirectLabor($event)"></app-base-table>
</div>
</section>
</section>
</mat-step>
<mat-step [stepControl]="directRawMaterialFormGroup">
<section class="stepper-section">
<form [formGroup]="directRawMaterialFormGroup" class="stepper-form">
<ng-template matStepLabel>Materia Prima Directa</ng-template>
<mat-form-field class="mat-field">
<mat-label>Material</mat-label>
<input matInput formControlName="material">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>UM</mat-label>
<input matInput >
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Cantidad</mat-label>
<input matInput type="number" placeholder="0">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Cto unit</mat-label>
<input matInput type="number" placeholder="0">
</mat-form-field>
<p>CMD : S/</p>
<div>
<button mat-flat-button matStepperPrevious>Back</button>
<button mat-flat-button matStepperNext>Next</button>
<button mat-flat-button color="accent" (click)="showTableDirectRawMaterial()">Refrescar tabla</button>
<button mat-flat-button color="primary"
(click)="onSaveDirectRawMaterial()">{{directRawMaterialButtonText}}</button>
</div>
</form>
<section class="stepper-detail">
<h3>Detalles</h3>
<div *ngIf="showTableDirectRawMaterials">
<app-base-table [columns]="directRawMaterialTableColumns" [data]="directRawMaterialDataSource"
[config]="tableConfig" (action)="onTableActionDirectRawMaterial($event)"></app-base-table>
</div>
</section>
</section>
</mat-step>
<mat-step>
<section class="stepper-section">
<form [formGroup]="directServiceFormGroup" class="stepper-form">
<ng-template matStepLabel>Servicios directos</ng-template>
<mat-form-field class="mat-field">
<mat-label>Servicio</mat-label>
<input matInput formControlName="service">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Cantidad</mat-label>
<input matInput type="number" placeholder="0">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Cto unit</mat-label>
<input matInput type="number" placeholder="0">
</mat-form-field>
<p>CSD : S/</p>
<div>
<button mat-flat-button matStepperPrevious>Back</button>
<button mat-flat-button matStepperNext>Next</button>
<button mat-flat-button color="accent" (click)="showTableDirectService()">Refrescar tabla</button>
<button mat-flat-button color="primary"
(click)="onSaveDirectService()">{{directServiceButtonText}}</button>
</div>
</form>
<section class="stepper-detail">
<h3>Detalles</h3>
<div *ngIf="showTableDirectServices">
<app-base-table [columns]="directServiceTableColumns" [data]="directServiceDataSource"
[config]="tableConfig" (action)="onTableActionDirectService($event)"></app-base-table>
</div>
</section>
</section>
</mat-step>
</mat-vertical-stepper>
<div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button matStepperNext>Next</button>
</div>
<!-- </form> -->
</mat-step>
<mat-step [stepControl]="indirectCostElementFormGroup">
<section class="stepper-section">
<form [formGroup]="indirectCostElementFormGroup" class="stepper-form">
<ng-template matStepLabel>Elementos de costeo Indirecto</ng-template>
<mat-form-field class="mat-field">
<mat-label>Actiidad</mat-label>
<input matInput formControlName="activity">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Costo</mat-label>
<input matInput type="number" placeholder="0" formControlName="cost">
</mat-form-field>
<mat-form-field class="mat-field">
<mat-label>Inductor</mat-label>
<mat-select disableRipple formControlName="inductor">
<mat-option> -- Ninguno --</mat-option>
<mat-option *ngFor="let inductor of inductors" [value]="inductor.code">{{inductor.name}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="mat-field" *ngFor="let costObject of costObjectDataSource">
<mat-label>{{costObject.name}}</mat-label>
<input matInput type="number" [formControlName]="costObject.code">
</mat-form-field>
<div>
<button mat-flat-button matStepperPrevious>Back</button>
<button mat-flat-button matStepperNext>Next</button>
<button mat-flat-button color="accent" (click)="showTable()">Refrescar tabla</button>
<button mat-flat-button color="primary"
(click)="onSaveIndirectCostElement()">{{indirectCostElementButtonText}}</button>
</div>
</form>
<section class="stepper-detail">
<h3>Detalles</h3>
<div *ngIf="showTableIndirectElements">
<app-base-table [columns]="indirectCostElementTableColumns" [data]="indirectCostElementDataSource"
[config]="tableConfig" (action)="onTableActionIndirectCostElement($event)"></app-base-table>
</div>
</section>
</section>
</mat-step>
<mat-step [stepControl]="fourthFormGroup">
<section class="stepper-section">
<form [formGroup]="fourthFormGroup">
<ng-template matStepLabel>Calcular costo</ng-template>
<!-- <mat-form-field>
<input matInput placeholder="Address" formControlName="secondCtrl" required>
</mat-form-field> -->
<div>
<button mat-button >Calcular costo</button>
<button mat-button color="primary">Guardar</button>
</div>
</form>
<section class="stepper-detail">
<h3>Resument de costo</h3>
<div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="Concepto">
<th mat-header-cell *matHeaderCellDef> Concepto </th>
<td mat-cell *matCellDef="let element"> {{element.Concepto}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="KA">
<th mat-header-cell *matHeaderCellDef> KA </th>
<td mat-cell *matCellDef="let element"> {{element.KA}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="KC">
<th mat-header-cell *matHeaderCellDef> KC </th>
<td mat-cell *matCellDef="let element"> {{element.KC}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="total">
<th mat-header-cell *matHeaderCellDef> total </th>
<td mat-cell *matCellDef="let element"><strong>{{element.total}} </strong> </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
</section>
</section>
</mat-step>
<!-- <mat-step>
<ng-template matStepLabel>Done</ng-template>
You are now done.
<div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button (click)="stepper.reset()">Reset</button>
</div>
</mat-step> -->
</mat-vertical-stepper>
<router-outlet></router-outlet>
|
import {
Body,
Controller,
Get,
Headers,
Param,
Post,
Query,
Req,
Res,
} from '@nestjs/common';
import { AppService } from './app.service';
import { Request, Response } from 'express';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHeaders(
@Req() req: Request,
@Headers('Cache-Control') cache: string,
): string {
return this.appService.getHeaders(req);
}
@Get('verbo')
getVerbo(@Req() req: Request): string {
return this.appService.getVerbo(req);
}
@Post('verbo')
postVerbo(@Req() req: Request): string {
return this.appService.getVerbo(req);
}
@Post('body')
postBody(@Req() req: Request, @Body('nome') nome: string): string {
return this.appService.postBody(req);
}
@Get('carro')
getCar(@Query('modelo') modelo: string, @Query('cor') cor: string) {
return this.appService.getCar(modelo, cor);
}
@Get('usuario/:id')
response(@Param('id') id: number, @Res() res: Response) {
return this.appService.response(id, res);
}
@Get('carro/:id')
responseHttp(@Param('id') id: number) {
return this.appService.responseHttp(id);
}
}
|
package com.Etech.Event.listner;
import com.Etech.Dto.CustomerRegistrationDTO;
import com.Etech.Dto.OrderPlacedDto;
import com.Etech.Model.Email;
import com.Etech.Service.EmailService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
@Service
public class OrderCancelationListener {
@Autowired
private EmailService emailService;
@KafkaListener(topics = {"order-canceled"})
public void listenWhenOrderCanceled(@Payload String memberDTO) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
try {
System.out.println("Received new Order cancellation details ....");
OrderPlacedDto messageUserDetails = objectMapper.readValue(memberDTO, OrderPlacedDto.class);
String body = "<p>Welcome to E-tech online Shopping System<p>\n" +
"</b> Your Order Cancellation Details are as Follows</p>\n" +
"<p>Canceled Order Number: <b>" + messageUserDetails.getOrderNumber() + "</b><br/>\n" +
"Total Amount of : <b>" + messageUserDetails.getOrderTotal() + "$"+ " Will be Refunded" +"</b></p>"+
"Order Date Was on: <b>" + messageUserDetails.getOrderDate() + "</b></p>"+
"<p>Thank you for choosing E-tech online Shopping System <p>\n" +
"<p>etechonlineshopping2023@gmail.com <p>\n";
Email email = new Email(messageUserDetails.getCustomer().getEmail(), "Welcome to E-tech online Shopping System", body);
emailService.sendWithHTMLBody(email);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/* eslint-disable react/no-unknown-property */
/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";
import {
Box,
Flex,
HStack,
Heading,
Highlight,
Skeleton,
Stack,
Text,
useColorMode,
} from "@chakra-ui/react";
import theme from "../../../theme";
import SearchBar from "../../../components/SearchBar";
import NavBar from "../../../components/NavBar/NavBar";
import * as styles from "./Home.styled.js";
import { useEffect, useState } from "react";
import axios from "axios";
import ListRooms from "../components/ListRooms/ListRooms";
const Home = () => {
const { colorMode } = useColorMode();
const [isLoaded, setIsLoaded] = useState(false);
const [location, setLocation] = useState("");
const [values, setValues] = useState({});
const [rooms, setRooms] = useState([]);
const handleSubmit = (values, onOpen) => {
console.log("loo", values);
if (values) {
if (!JSON.parse(localStorage.getItem("userData"))) {
onOpen();
} else {
setValues({
...values,
location,
});
}
}
};
useEffect(() => {
const getRooms = async () => {
try {
const { data } = await axios.get(
"https://hotelfinderserver.azurewebsites.net/hotel/room/getAllRooms",
{
params: {
location,
number_of_persons: values.number_of_persons,
},
}
);
setRooms(data);
} catch (error) {
console.error(error);
}
};
if (values) {
console.log(values);
getRooms();
}
}, [values]);
return (
<Box bg={theme.colors[colorMode].background} w="100%" h="100vh">
<Box bg={theme.colors[colorMode].primary} w="100%" h="400px">
<Flex css={styles.flexStyle}>
<NavBar />
<Heading
color={theme.colors.white}
mb={4}
css={css`
margin-top: auto;
`}
>
<Highlight
query={["hotel"]}
styles={{
px: "2",
py: "1",
rounded: "full",
bg: `${theme.colors[colorMode].secondary}`,
}}
>
Find your next hotel
</Highlight>
</Heading>
<Text color={theme.colors.white} fontSize="xl" mb={2}>
Search low prices on hotels, homes and much more...
</Text>
<SearchBar
location={location}
setLocation={setLocation}
handleSubmit={handleSubmit}
/>
</Flex>
</Box>
{rooms.length ? (
<HStack
spacing={4}
w="70%"
css={css`
margin-left: auto;
margin-right: auto;
margin-top: 20px;
`}
>
{rooms.map((room) => {
return (
<ListRooms
key={room._id}
room={room}
number_of_persons={values.number_of_persons}
startDate={values.start_date}
endDate={values.end_date}
/>
);
})}
</HStack>
) : (
<Stack css={styles.stackStyle} spacing={4}>
<Skeleton height="40px" isLoaded={isLoaded}></Skeleton>
<Skeleton
height="40px"
isLoaded={isLoaded}
bg="green.500"
color="white"
fadeDuration={1}
></Skeleton>
<Skeleton
height="40px"
isLoaded={isLoaded}
fadeDuration={4}
bg="blue.500"
color="white"
></Skeleton>
<Skeleton
height="40px"
isLoaded={isLoaded}
fadeDuration={4}
bg="blue.500"
color="white"
></Skeleton>
<Skeleton
height="40px"
isLoaded={isLoaded}
fadeDuration={4}
bg="blue.500"
color="white"
></Skeleton>
</Stack>
)}
</Box>
);
};
export default Home;
|
#ifndef RENDERING_STATUS_HH
# define RENDERING_STATUS_HH
# include <maths_utils/Size.hh>
# include <sdl_core/SdlWidget.hh>
# include <sdl_engine/Color.hh>
# include <sdl_graphic/Button.hh>
# include <sdl_graphic/LabelWidget.hh>
# include <sdl_graphic/ProgressBar.hh>
namespace fractsim {
class RenderingStatus: public sdl::core::SdlWidget {
public:
/**
* @brief - Used to create a rendering status widget allowing to display
* information about the current rendering being performed in
* the application or general information about the fractal being
* drawn.
* @param hint - the size hint for this widget.
* @param parent - the parent of this widget.
*/
RenderingStatus(const utils::Sizef& hint = utils::Sizef(),
sdl::core::SdlWidget* parent = nullptr);
~RenderingStatus() = default;
/**
* @brief - Used to retrive the render button associated to this status.
* This method is only meant as a way to connect elements to the
* `onClick` signal of this button, lacking of a better way.
* The method may raise an error in case the render button is
* not defined.
* @return - a reference to the render button associated to this status.
*/
sdl::graphic::Button&
getRenderButton();
/**
* @brief - Similar to the `getRenderButton` method but used to retrieve
* the reset button. Still not perfect in terms of design but it
* does the job.
* @return - a reference to the reset button associated to this status.
*/
sdl::graphic::Button&
getResetButton();
/**
* @brief - Used to connect external elements which can provide information
* about the current completion of the rendering task.
* @param perc - a value in the range `[0; 1]` indicating the completion
* percentage for the current rendering task.
*/
void
onCompletionChanged(float perc);
protected:
/**
* @brief - Retrieves the maximum height for this component. This is usually
* assigned at construction and considered enough to display all the
* info needed.
* @return - a value describing the maximum height of this component.
*/
static
float
getStatusMaxHeight() noexcept;
/**
* @brief - A suited value to use for the border size of the buttons used in
* this status.
* @return - a suited value for the size of the borders for buttons.
*/
static
float
getButtonBorderSize() noexcept;
/**
* @brief - Retrieves the maximum size for the render button. As we only want
* the button to be large enough so that the text is fully visible it
* is not needed to grow indefinitely.
* @return - a value describing the maximum size for the render button.
*/
static
utils::Sizef
getRenderButtonMaxSize() noexcept;
/**
* @brief - Retrieves the maximum size for the reset button. Very similar to
* the purpose achieved by the `getRenderButtonMaxSize`.
* @return - a value describing the maximum size of the reset button.
*/
static
utils::Sizef
getResetButtonMaxSize() noexcept;
/**
* @brief - Used to define the margins of the layout applied around the whole
* widget. Usually `0`.
* @return - a value representing the global margins for this widget.
*/
static
float
getGlobalMargins() noexcept;
/**
* @brief - Used to define the margins between the component of this status.
* @return - a value representing the margins between each component of the
* widget.
*/
static
float
getComponentMargins() noexcept;
/**
* @brief - Used to retrieve the default name for the render button.
* @return - a string that should be used to provide consistent naming for
* the render button.
*/
static
const char*
getRenderButtonName() noexcept;
/**
* @brief - Similar to the `getRenderButtonName` but retrieves the default
* name to use for the reset button.
* @return - a string that should be used to provide consistent naming for
* the reset button.
*/
static
const char*
getResetButtonName() noexcept;
/**
* @brief - Used to retrieve the default name for the progress bar.
* @return - a string that should be used to provide consistent naming for
* the progress bar.
*/
static
const char*
getProgressBarName() noexcept;
/**
* @brief - Retrieve a font name that can be used for buttons in this widget.
* @return - a string representing the font to use for labels of buttons in
* this widget.
*/
static
const char*
getButtonFontName() noexcept;
/**
* @brief - Used to build the content of this widget so that it can be
* readily displayed.
*/
void
build();
/**
* @brief - Used to retrieve the progress bar holding the current completion
* percentage of the rendering task monitored by this object.
* The return value is guaranteed to be not `null` if the method
* returns. Note that the locker is assumed to already be acquired
* upon calling this function.
* @return - the progress bar associated to this status.
*/
sdl::graphic::ProgressBar*
getProgressBar();
private:
/**
* @brief - A mutex to protect the internal properties of this widget.
*/
mutable std::mutex m_propsLocker;
};
}
# include "RenderingStatus.hxx"
#endif /* RENDERING_STATUS_HH */
|
from datetime import date, timedelta
from random import randint, choice
from fastapi import FastAPI, HTTPException
from spaceblocks_permissions_server import PermissionsClient, ClientAuthenticationOptions
SUMMARIES = ['Freezing', 'Bracing', 'Chilly', 'Cool', 'Mild', 'Warm', 'Balmy', 'Hot', 'Sweltering', 'Scorching']
app = FastAPI()
permissions_client = PermissionsClient(
'<YOUR_PERMISSIONS_URL>',
ClientAuthenticationOptions(
api_key='<YOUR_API_KEY>',
client_id='<YOUR_CLIENT_ID>',
client_secret='<YOUR_CLIENT_SECRET>',
scopes='permissions:management:read permissions:management:write'
)
)
@app.get('/get-weather-forecast/')
def get_weather_forecast(user: str, city: str):
permissions = permissions_client.permission_api.list_permissions(
'default',
'city',
city,
user
)
can_get_current_forecast = 'current-forecast-viewer' in permissions['city']
can_get_future_forecast = 'future-forecast-viewer' in permissions['city']
if not can_get_current_forecast and not can_get_future_forecast:
raise HTTPException(status_code=403, detail='No permission')
return [{
'date': date.today() + timedelta(days=i+1),
'temperature': randint(-5, 38),
'summary': choice(SUMMARIES)
} for i in range(5 if can_get_future_forecast else 1)]
|
import { Button, Flex, Heading, useDisclosure } from "@chakra-ui/react";
import Summary from "../summary";
import ExpenseView from "../expense-view";
export default function Main() {
const { isOpen, onOpen, onClose } = useDisclosure();
return (
<Flex textAlign={"center"} flexDirection={"column"} pr={"5"} pl={"5"}>
<Flex alignItems={"center"} justifyContent={"space-between"} mt={"12"}>
<Heading
color={"blue.400"}
display={["none", "block", "block", "block", "block"]}
>
Expense Tracker
</Heading>
<Flex alignItems={"center"}>
<Button onClick={onOpen} bg={"blue.300"} color={"black"} ml={"4"}>
Add New Transction
</Button>
</Flex>
</Flex>
<Summary isOpen={isOpen} onClose={onClose} />
<Flex
w={"full"}
alignItems={"flex-start"}
justifyContent={"space-evenly"}
flexDirection={["column", "column", "column", "row", "row"]}
>
<ExpenseView />
<ExpenseView />
</Flex>
</Flex>
);
}
|
import json
import time
import requests
from flask import Flask, request
from core.block import Block
from core.utils import norm_host
from core.blockchain import Blockchain
app = Flask(__name__)
blockchain = Blockchain()
PEERS = set()
def consensus_process():
global blockchain
longest_chain = None
current_len = len(blockchain.chain)
for node in PEERS:
response = requests.post('{}chain'.format(node))
length = response.json()['length']
chain = response.json()['chain']
if length > current_len and blockchain.check_chain_validity(chain):
current_len = length
longest_chain = chain
if longest_chain:
blockchain = longest_chain
return True
return False
def synchronized_chain(lasted_blockchain):
global blockchain
try:
for peer in PEERS:
requests.post("{}add_block".format(peer),
data=json.dumps({'latest_chain': lasted_blockchain.chain}),
headers = {'Content-Type': "application/json"})
except:
return "Cannot update blockchain\n", 401
return "Update successful\n", 200
def added_block_to_all_peer(block):
for peer in PEERS:
print(">>>>>>>>>>>>:\t", peer)
url = "{}add_block".format(peer)
requests.post(url,
data=json.dumps(block.__dict__, sort_keys=True),
headers = {'Content-Type': "application/json"})
@app.route('/update_chain', methods=['POST'])
def update_chain_in_network():
global blockchain
lasted_chain = request.get_json()['latest_chain']
blockchain.update_chain = lasted_chain
return True
@app.route('/chain', methods=['POST'])
def get_chain():
chain_data = []
for block in blockchain.chain:
chain_data.append(block.__dict__)
return json.dumps({"length": len(chain_data),
"chain": chain_data,
"peers": list(PEERS)})
@app.route('/get_pending_transactions', methods=['POST'])
def get_pending_transactions():
return json.dumps(blockchain.unconfirmed_transactions)
# route thêm một peer mới vào mạng
@app.route('/register_node', methods=['POST'])
def register_new_peers():
# Địa chỉ host đến các node ngang hàng
node_address = request.get_json()["node_address"]
if not node_address:
return "Node address is not valid\n", 400
PEERS.add(node_address)
PEERS.add(request.host_url)
return get_chain()
@app.route('/save_chain', methods=['POST'])
def save_chain():
chain_file_name = request.form["filename"]
if chain_file_name is not None:
with open(chain_file_name, 'w') as chain_file:
chain_file.write(get_chain())
@app.route('/register_with', methods=['POST'])
def register_with_existing_node():
"""
Trong nội bộ gọi đến route `register_node` để
đăng ký node hiện tại với node từ xa được chỉ định trong
request và cập nhật lại mạng blockchain
"""
node_address = request.form["node_address"]
if not node_address:
return "\nNode address is not valid", 400
data = {"node_address": request.host_url}
headers = {'Content-Type': "application/json"}
node_address = norm_host(node_address)
# Request đăng ký với node từ xa và lấy thông tin
response = requests.post(node_address + "register_node",
data=json.dumps(data), headers=headers)
if response.status_code == 200:
global blockchain
global PEERS
# update chain và các peers
chain_dump = response.json()['chain']
blockchain = create_chain_from_dump(chain_dump)
PEERS.update(set(response.json()['peers']))
PEERS.add(node_address)
return "Registration successful\n", 200
else:
return response.content, response.status_code
def create_chain_from_dump(chain_dump):
generated_blockchain = Blockchain()
for idx, block_data in enumerate(chain_dump):
if idx == 0:
continue # skip genesis block
block = Block(block_data["index"],
block_data["transactions"],
block_data["timestamp"],
block_data["previous_hash"],
block_data["nonce"])
proof = block_data['hash']
merkle_root = block_data['merkle_root']
generated_blockchain.add_block(block, proof, merkle_root)
return generated_blockchain
@app.route('/add_block', methods=['POST'])
def check_valid_and_add_block():
block_data = request.get_json()
block = Block(block_data["index"],
block_data["transactions"],
block_data["timestamp"],
block_data["previous_hash"],
block_data["nonce"])
added_flag = blockchain.add_block(block, block_data['hash'], block_data['merkle_root'])
if not added_flag:
return "The block cannot add in node\n", 400
return "Block added to the chain\n", 201
@app.route('/mine_transaction', methods=['POST'])
def mine_transactions():
# synchronized_chain(blockchain)
result = blockchain.mining_block()
if not result:
return "No transactions to mine\n", 400
else:
chain_length = len(blockchain.chain)
consensus_process()
if chain_length == len(blockchain.chain):
added_block_to_all_peer(blockchain.last_block)
blockchain.unconfirmed_transactions = []
return "Block {} is mined.\n".format(blockchain.last_block.index), 200
@app.route('/new_transaction', methods=['POST'])
def new_transaction():
data = request.get_json()['data']
if data is None:
return "Invlaid transaction data\n", 404
blockchain.add_transaction(data)
return "Sucessfully\n", 200
@app.route('/send_data', methods=['POST'])
def send_data():
data = request.form["data"]
target_node = request.form["target_node"]
target_node = norm_host(target_node)
if data is None:
return 'Data is not valid', 400
data_json = {
'data': data
}
if target_node != request.host_url:
PEERS.add(target_node)
transaction_address = "{}new_transaction".format(target_node)
response = requests.post(transaction_address,
json=data_json,
headers={'Content-type': 'application/json'})
return response.content, response.status_code
if __name__ == '__main__':
app.run(debug=True, port=5000)
|
package me.study.solvedac;
import me.study.CodingTest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
class Problem1182 implements CodingTest {
static int s;
static int n;
static int[] source;
private static int[] memory;
static int result = 0;
private static final int EMPTY_VALUE = Integer.MIN_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] source1 = reader.readLine().split(" ");
n = Integer.parseInt(source1[0]);
s = Integer.parseInt(source1[1]);
source = new int[n];
String[] source2 = reader.readLine().split(" ");
for (int i = 0; i < source2.length; i++) {
source[i] = Integer.parseInt(source2[i]);
}
writer.write(String.valueOf(solve()));
writer.close();
reader.close();
}
static int solve() {
memory = new int[n];
Arrays.fill(memory, EMPTY_VALUE);
recursive(-1);
return result;
}
private static void recursive(int currentIndex) {
if (currentIndex == n - 1) {
if (sum() == s) {
result++;
}
} else {
int nextIndex = currentIndex + 1;
memory[nextIndex] = source[nextIndex];
recursive(nextIndex);
memory[nextIndex] = EMPTY_VALUE;
recursive(nextIndex);
}
}
private static int sum() {
int result = EMPTY_VALUE;
for (int i : memory) {
if (i != EMPTY_VALUE) {
if (result == EMPTY_VALUE) {
result = 0;
}
result += i;
}
}
return result;
}
@Override
public String getTimeComplexity() {
// 완전 탐색이기 때문에 주어진 순열의 부분순열 개수와 같음
return "O(2^N)";
}
@Override
public String getSpaceComplexity() {
return "O(N)";
}
@Override
public String getPage() {
return "https://www.acmicpc.net/problem/1182";
}
}
|
import 'reflect-metadata';
import { textFile } from '../../test/stubs';
import { Field } from '../models';
import { serializeJson } from './serialize-json';
function field(name: string, value: unknown) {
const f = new Field();
f.name = name;
f.value = value;
return f;
}
describe('serializeJson', () => {
it('should return empty object when given no fields', () => {
const result = serializeJson([]);
expect(result).toBe('{}');
});
it('should return object from field names and values', () => {
const nameValues: [string, unknown][] = [
['foo', true],
['bar', 42],
['baz', 'foo'],
['qux', [1, 2, 3]],
['quz', { a: 1, b: 2 }]
];
const fields = nameValues.map(([name, value]) => field(name, value));
const result = serializeJson(fields);
expect(result).toBe(JSON.stringify(Object.fromEntries(nameValues)));
});
it("should use file's name when value is a File object", () => {
const field = new Field();
field.name = 'test-file';
field.value = textFile;
const result = serializeJson([field]);
expect(result).toBe(JSON.stringify({ [field.name]: textFile.name }));
});
});
|
// SPDX-License-Identifier: MIT
// Creator: LIBC (https://liblockchain.org)
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./ERC721A.sol";
/*
||//$\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\//$\\||
||\\$// ~ '------========--------' \\$//||
||<< / /$\ // ____ \\ \ >>||
||>>| 12 //L\\ // ///..) \\ L38036133B 12 |<<||
||<<| \\ // || <|| >\ || |>>||
||>>| \$/ || $$ --/ || One Hundred |<<||
||//$\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\//$\\||<||
||\\$// ~ '------========--------' \\$//||\||
||<< / /$\ // ____ \\ \ >>||)||
||>>| 12 //L\\ // ///..) \\ L38036133B 12 |<<||/||
||<<| \\ // || <|| >\ || |>>||=||
||>>| \$/ || $$ --/ || One Hundred |<<||
||<<| L38036133B *\\ |\_/ //* series |>>||
||>>| 12 *\\/___\_//* 1989 |<<||
||<<\ Treasurer ______/Hamilton\________ Secretary 12 />>||
||//$\ ~|UNITED STATES OF AMERICA|~ /$\\||
||\\$//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\$//||
*/
contract Eerieum is ERC721A, Ownable, ReentrancyGuard {
uint256 public immutable amountForDevs;
uint256 public immutable amountForSaleAndDev;
uint256 public immutable collectionSize;
uint256 public maxPerAddressDuringMint;
uint256 public price;
string private _baseTokenURI;
string private _contractMeta;
address private _royaltyAddr;
uint256 private _royaltyBps;
bool public hasSaleStarted;
bool public hasWhiteListStarted;
uint256 public whiteListStartTime;
bytes32 public merkleRoot = 0x3651a7fdd642f52f94bae279cdcbe1eae9627502de63b156b82fa88974f26499;
constructor(
uint256 maxBatchSize_,
uint256 collectionSize_,
uint256 amountForSaleAndDev_,
uint256 amountForDevs_,
uint256 price_,
string memory contractMeta_,
string memory baseURI_) ERC721A("eerieum_", "VALUE") {
_contractMeta = contractMeta_;
_baseTokenURI = baseURI_;
maxPerAddressDuringMint = maxBatchSize_;
amountForSaleAndDev = amountForSaleAndDev_;
amountForDevs = amountForDevs_;
collectionSize = collectionSize_;
price = price_;
hasSaleStarted = false;
hasWhiteListStarted = false;
whiteListStartTime = 0;
require(
amountForSaleAndDev_ <= collectionSize_,
"larger collection size needed"
);
}
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
function mint(uint256 quantity) external payable {
require(hasSaleStarted == true, "Sale has not started");
require(
totalSupply() + quantity <= amountForSaleAndDev,
"not enough remaining reserved for sale to support desired mint amount"
);
require(
quantity <= maxPerAddressDuringMint,
"can not mint this many"
);
uint256 totalCost = price * quantity;
// First 500 are free.
if(_currentIndex + quantity <= 500) {
totalCost = 0;
}
// Make sure the value sent is enough to cover the cost.
require(
msg.value >= totalCost,
"not enough ETH sent to mint"
);
// Get our mint on.
_safeMint(msg.sender, quantity);
// If we sent to much, lets return the remainder
if(totalCost > 0) {
refundIfOver(totalCost);
}
}
function _baseURI() internal view virtual override returns(string memory) {
return _baseTokenURI;
}
function _startTokenId() internal view virtual override returns (uint256) {
return 1;
}
function setMaxPerAddressDuringMint(uint256 maxPerAddressDuringMint_) external onlyOwner {
maxPerAddressDuringMint = maxPerAddressDuringMint_;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function contractURI() public view returns (string memory) {
return _contractMeta;
}
function setContractURI(string memory uri) public {
_contractMeta = uri;
}
function setPrice(uint256 price_) external onlyOwner {
price = price_;
}
function withdraw() external onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
function numberMinted(address owner) public view returns (uint256) {
return _numberMinted(owner);
}
function greenListMint(bytes32[] calldata _merkleProof) external payable callerIsUser nonReentrant {
require(hasWhiteListStarted == true, "greenlist sale has not begun yet");
require(totalSupply() + 1 <= collectionSize, "reached max supply");
require(_currentIndex <= 500, "greenlist tokens are all gone, check secondary markets.");
// Lets verify the address
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Address not on greenlist");
require(balanceOf(msg.sender) == 0, "Limited to one greenlist mint per address");
// Get our mint on!
_safeMint(msg.sender, 1);
}
function refundIfOver(uint256 price_) private {
require(msg.value >= price_, "No value to refund.");
if (msg.value > price_) {
payable(msg.sender).transfer(msg.value - price_);
}
}
function royaltyInfo(uint256 tokenId_, uint256 value_) public view returns (address _reciever, uint256 _royaltyAmount) {
return (_royaltyAddr, _royaltyBps);
}
function setRoyalty(uint256 bps, address distAddress) external onlyOwner {
_royaltyBps = bps;
_royaltyAddr = distAddress;
}
function startSale() external onlyOwner {
hasSaleStarted = true;
}
function pauseSale() external onlyOwner {
hasSaleStarted = false;
}
function startGreenListSale() external onlyOwner {
hasWhiteListStarted = true;
whiteListStartTime = block.timestamp;
}
function stopGreenListSale() external onlyOwner {
hasWhiteListStarted = false;
}
// Support the Royalties Interface ERC-2981
function supportsInterface(bytes4 interfaceId) public view override(ERC721A) returns (bool) {
return interfaceId == 0x2a55205a // ERC-2981
|| super.supportsInterface(interfaceId);
}
}
|
package Controller.ActionListionerController.Admin.Inventory.AddProductFrame.AddSupplierFrame;
import Controller.EntityControllers.Supplier;
import View.InputFrames.AddProductFrame;
import View.InputFrames.AddSupplierFrame;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// ActionListener to handle confirmation of adding a new supplier
public class ConfirmSupplierListener implements ActionListener {
private final AddSupplierFrame frame;
private final AddProductFrame frame1;
// Constructor to initialize the listener with the relevant frames
public ConfirmSupplierListener(AddSupplierFrame af, AddProductFrame apf) {
frame = af;
frame1 = apf;
}
// Method called when the "Confirm" button is clicked
@Override
public void actionPerformed(ActionEvent actionEvent) {
// Check if the supplier name is empty
if (frame.getSupplierNameField().getText().isEmpty()) {
JOptionPane.showMessageDialog(frame, "Please enter a supplier name");
return;
} else if (frame.getPhoneNoField().getText().isEmpty()) {
// Check if the phone number is empty
JOptionPane.showMessageDialog(frame, "Please enter a phone number");
return;
} else {
// Validate the phone number format
String phoneNumberRegex = "^03\\d{9}$";
Pattern pattern = Pattern.compile(phoneNumberRegex);
Matcher matcher = pattern.matcher(frame.getPhoneNoField().getText());
if (!matcher.matches()) {
JOptionPane.showMessageDialog(frame, "Please enter a valid phone number");
return;
}
}
// Check if the email is provided
Supplier s;
if (frame.getEmailField().getText().isEmpty()) {
// Create a new supplier without email
s = new Supplier(frame.getSupplierNameField().getText(), frame.getPhoneNoField().getText());
// Check if the supplier already exists
ArrayList<Supplier> list = s.getSuppliers();
for (Supplier supplier : list) {
if (supplier.getName().equals(frame.getSupplierNameField().getText())) {
JOptionPane.showMessageDialog(frame, "Supplier already exists");
return;
}
}
// Insert the supplier without email
s.insertWithoutEmail();
frame.dispose();
} else {
// Validate the email format
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
Pattern pattern = Pattern.compile(emailRegex);
Matcher matcher = pattern.matcher(frame.getEmailField().getText());
if (!matcher.matches()) {
JOptionPane.showMessageDialog(frame, "Please enter a valid email");
return;
}
// Create a new supplier with email
s = new Supplier(frame.getSupplierNameField().getText(), frame.getEmailField().getText(), frame.getPhoneNoField().getText());
// Check if the supplier already exists
ArrayList<Supplier> list = s.getSuppliers();
for (Supplier supplier : list) {
if (supplier.getName().equals(frame.getSupplierNameField().getText())) {
JOptionPane.showMessageDialog(frame, "Supplier already exists");
return;
}
}
// Insert the supplier with email
s.insert();
frame.dispose();
}
// Update the supplier combo box in the AddProductFrame
frame1.getSupplierComboBox().addItem(frame.getSupplierNameField().getText());
}
}
|
import enum
import io
from typing import Self
from .parser import Parser
from .utils import int_to_bytes, bytes_to_int
class EnumMeta(type):
def __new__(cls, name, bases, attrs, **kwargs):
cls_ = super().__new__(cls, name, bases, attrs, **kwargs)
if "EnumClass" in attrs:
for k, v in attrs["EnumClass"].__members__.items():
setattr(cls_, k, cls_(v))
return cls_
class Enum(Parser, metaclass=EnumMeta):
"""Base class for handling enums"""
EnumClass: type[enum.IntEnum]
size_in_bytes: int
def __init__(self, /, value: int) -> None:
self.value = self.EnumClass(value)
def to_bytes(self) -> bytes:
return int_to_bytes(self.value, self.size_in_bytes)
@classmethod
def parse(cls, stream: io.BufferedIOBase) -> Self:
n = bytes_to_int(stream.read(cls.size_in_bytes))
try:
obj = cls(n)
except ValueError:
raise cls.ParsingError(stream.tell() - cls.size_in_bytes, stream.tell(), f"Invalid value {n}")
return obj
@classmethod
def skip(cls, stream: io.BufferedIOBase) -> None:
stream.seek(cls.size_in_bytes,io.SEEK_CUR)
def print(self) -> str:
return f"{self.size_in_bytes} {self.__class__.__name__} {self.value.name}({self.value})"
__all__ = ["Enum"]
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos
// Manycore Performance-Portable Multidimensional Arrays
//
// Copyright (2012) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact H. Carter Edwards (hcedwar@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <Kokkos_Core.hpp>
#include <cstdio>
#include <cstdlib>
#include <cmath>
typedef Kokkos::View<int*> view_type;
typedef view_type::HostMirror host_view_type;
typedef Kokkos::View<int> count_type;
typedef count_type::HostMirror host_count_type;
struct findprimes {
view_type data;
view_type result;
count_type count;
findprimes(view_type data_, view_type result_, count_type count_):data(data_),result(result_),count(count_) {}
KOKKOS_INLINE_FUNCTION
void operator() (int i) const {
const int number = data(i);
const int upper_bound = sqrt(1.0*number)+1;
bool is_prime = !(number%2 == 0);
int k = 3;
while(k<upper_bound && is_prime) {
is_prime = !(number%k == 0);
k+=2;
}
if(is_prime) {
int idx = Kokkos::atomic_fetch_add(&count(),1);
result(idx) = number;
}
}
};
int main() {
Kokkos::initialize();
srand(61391);
int nnumbers = 100000;
view_type data("RND",nnumbers);
view_type result("Prime",nnumbers);
count_type count("Count");
host_view_type h_data = Kokkos::create_mirror_view(data);
host_view_type h_result = Kokkos::create_mirror_view(result);
host_count_type h_count = Kokkos::create_mirror_view(count);
typedef view_type::size_type size_type;
for (size_type i = 0; i < data.dimension_0(); ++i) {
h_data(i) = rand () % nnumbers;
}
Kokkos::deep_copy(data,h_data);
Kokkos::parallel_for(data.dimension_0(),findprimes(data,result,count));
Kokkos::deep_copy(h_count,count);
printf("Found %i prime numbers in %i random numbers\n",h_count(),nnumbers);
Kokkos::finalize();
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { QuizComponent } from './components/quiz/quiz.component';
import { RegisterComponent } from './components/register/register.component';
import { ResultComponent } from './components/result/result.component';
import { SignInComponent } from './components/sign-in/sign-in.component';
import { AuthGuard } from './services/auth/auth.guard';
import { MainComponent } from './components/main/main.component';
import { GamesComponent } from './components/games/games.component';
import { AccountPopupComponent } from './components/account-popup/account-popup.component';
const routes: Routes = [
{ path:'games',component:GamesComponent},
{ path:'account',component:AccountPopupComponent},
{ path:'register',component:RegisterComponent},
{ path:'quiz',component:QuizComponent, canActivate : [AuthGuard]},
{ path:'result',component:ResultComponent, canActivate : [AuthGuard]},
{ path:'login',component:SignInComponent},
{ path:'login?redirectTo=:redirect',component:SignInComponent, pathMatch: 'full'},
{ path:'dashboard',component:MainComponent, canActivate : [AuthGuard]},
{ path:'',redirectTo:'/login',pathMatch:'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import turtle
import random
import time
from enum import Enum
import logging
logging.basicConfig(level=logging.DEBUG)
# --------------------------
# global parameters
# --------------------------
length = 100
speed = 10
turn_angle = 23
repeat_num = 4
running_time = 120
pen_size = 2
turtle_size = 3
# GUI Setup
turtle.shape("turtle")
turtle.turtlesize(turtle_size, turtle_size, turtle_size)
turtle.pensize(pen_size)
def log(s):
''' logging string to command window '''
logging.debug(s)
# --------------------------
# Behaviour Tree Nodes
# --------------------------
class NodeStatus(Enum):
SUCCESS = "SUCCESS"
FAILURE = "FAILURE"
RUNNING = "RUNNING"
class ActionNode:
def __init__(self, name, action_func):
self.name = name
self.action_func = action_func
self.parent = None
def set_parent(self, name):
self.parent = name
def execute(self):
status = self.action_func()
log(f'\t action:\t {self.name} - {status}')
return status
class SequenceNode:
def __init__(self, name, nodes):
self.name = name
self.nodes = nodes
self.parent = None
[x.set_parent(name) for x in self.nodes]
def set_parent(self, name):
self.parent = name
def execute(self):
if not self.parent:
log(f'\t execute:\t {self.name}')
for node in self.nodes:
status = node.execute()
if status != NodeStatus.SUCCESS:
log(f'\t\t {status}')
return status
log('\t\t SUCCESS')
return NodeStatus.SUCCESS
class SelectorNode:
def __init__(self, name, nodes):
self.name = name
self.nodes = nodes
self.parent = None
[x.set_parent(name) for x in self.nodes]
def set_parent(self, name):
self.parent = name
def execute(self):
if not self.parent:
log(f'\t execute:\t {self.name}')
for node in self.nodes:
status = node.execute()
if status != NodeStatus.FAILURE:
log(f'\t\t {status}')
return status
log('\t\t FAILURE')
return NodeStatus.FAILURE
class WaitNode:
def __init__(self, name, wait_s, node) -> None:
self.name = name
self.parent = None
self.wait_s = wait_s
self.node = node
self.time_s = 0
node.set_parent(name)
def set_parent(self, name):
self.parent = name
def execute(self):
if not self.parent:
log(f'\t execute:\t {self.name}')
if self.time_s < 0:
log("\t\t FAILURE - timer disabled")
return NodeStatus.FAILURE
elif self.time_s == 0:
self.time_s = time.time()
log("\t\t RUNNING - starts timer")
self.node.execute()
return NodeStatus.RUNNING
elif time.time()-self.time_s < self.wait_s:
log("\t\t RUNNING - timer is counting")
self.node.execute()
return NodeStatus.RUNNING
else:
self.time_s = -1
log("\t\t SUCCESS - timer goes off")
return NodeStatus.SUCCESS
class RepeaterNode:
def __init__(self, name, number, node):
self.name = name
self.parent = None
self.number = number
self.node = node
node.set_parent(name)
def set_parent(self, name):
self.parent = name
def execute(self):
if not self.parent:
log('-'*76)
log(f'\t execute:\t {self.name}')
for i in range(self.number):
log(f'\t repeat:\t number {i+1}')
self.node.execute()
log("\t\t SUCCESS")
return NodeStatus.SUCCESS
# --------------------------
# Action functions
# --------------------------
def move_forward():
turtle.forward(length)
return random.choice([NodeStatus.SUCCESS, NodeStatus.FAILURE])
return NodeStatus.SUCCESS
def turn_left():
turtle.left(90)
return NodeStatus.SUCCESS
def turn_right():
turtle.right(90)
return NodeStatus.SUCCESS
def obstacle_in_front():
# Simulating an obstacle in front of the character
return random.choice([NodeStatus.SUCCESS, NodeStatus.FAILURE])
# --------------------------
# Helper Functions
# --------------------------
def get_new_colour():
R = random.random()
B = random.random()
G = random.random()
turtle.color(R, G, B)
return NodeStatus.SUCCESS
def get_new_dir():
turtle.left(turn_angle)
return NodeStatus.SUCCESS
def change_speed():
global speed
if random.random() < 0.5:
return NodeStatus.FAILURE
speed = random.choice(list(range(11)))
return NodeStatus.SUCCESS
# --------------------------
# Behaviour Tree Construction
# --------------------------
def main_loop():
draw_line = SelectorNode("Move, Turn, and Random Fail Sequence", [
SequenceNode("Draw Line and Turn Left Sequence", [
ActionNode("Draw Line Action", move_forward),
ActionNode("Turn Left Action", turn_left)
]),
SequenceNode("Alternate Move Sequence", [
ActionNode("Turn Left Action", turn_left),
SelectorNode("Turn Right or Move Forward Selector", [
ActionNode("Turn Right Action", turn_right),
ActionNode("Draw Line Action", move_forward)
]),
ActionNode("Turn Left Action", turn_left)
]),
ActionNode("Collide and Wait Action", obstacle_in_front)
])
draw_square = RepeaterNode("Draw Square Repeater", repeat_num, draw_line)
colour_act = ActionNode("Change Colour", get_new_colour)
new_dir = ActionNode("Change Direction", get_new_dir)
many_square = SequenceNode(
"Draw More Squares", [colour_act, new_dir, draw_square])
wait_root = WaitNode(
f"Wait {running_time} Seconds", running_time, many_square)
while wait_root.execute() != NodeStatus.FAILURE:
pass
# draw_line.execute()
# draw_square.execute()
# no BT version
# for _ in range(100):
# log('='*40)
# for _ in range(4):
# move_forward()
# turn_left()
# turtle.left(turn_angle)
# get_new_colour()
turtle.done()
# --------------------------
# Behaviour Tree Simulation
# --------------------------
if __name__ == '__main__':
main_loop()
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- <link rel="icon" type="image/svg+xml" href="/vite.svg" /> -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Graphs App</title>
<!-- ICONS -->
<script src="https://kit.fontawesome.com/31bac16aff.js" crossorigin="anonymous"></script>
<!-- STYLES -->
<link rel="stylesheet" href="/src/styles/ui.css" />
<link rel="stylesheet" href="/src/styles/graph.css" />
</head>
<body>
<main>
<header>
<h1>ezGraphs | Draw graphs and execute search algorithms</h1>
<div class="links">
<a href="https://github.com/Emanuel-Palestino/graphs-drawing-app-with-search-algorithm" target="_blank" title="Repository">
<i class="fa-brands fa-github"></i>
</a>
</div>
</header>
<!-- TOOLS MENU -->
<menu>
<!-- GRAPH -->
<section id="graph">
<span class="section-title">Graph</span>
<ul>
<li>
<button id="btn-new_graph" title="Create new graph">
<i class="fa-solid fa-circle-plus"></i>
</button>
</li>
<li>
<button id="btn-clear_graph" title="Clear canvas" disabled>
<i class="fa-solid fa-trash fa-sm"></i>
</button>
</li>
</ul>
</section>
<!-- DRAWING -->
<section id="drawing">
<span class="section-title">Drawing</span>
<ul>
<li>
<button id="btn-draw_node" title="Draw node" disabled>
<i class="fa-regular fa-circle"></i>
</button>
</li>
<li>
<button id="btn-draw_edge" title="Draw edge" disabled>
<i class="fa-solid fa-slash fa-sm"></i>
</button>
</li>
<li>
<button id="btn-delete_element" title="Delete element" disabled>
<i class="fa-regular fa-circle-xmark"></i>
</button>
</li>
</ul>
</section>
<!-- ALGORITHM EXECUTION -->
<section id="execution">
<span class="section-title">Algorithm Execution</span>
<ul>
<li>
<select id="algorithm_execution" title="Select search algorithm" disabled>
<option value="bfs">BFS</option>
<option value="dfs">DFS</option>
</select>
</li>
<li>
<button id="btn-play_execution" title="Play execution" disabled>
<i class="fa-solid fa-play"></i>
</button>
</li>
<li>
<button id="btn-pause_execution" title="Pause execution" disabled>
<i class="fa-solid fa-pause"></i>
</button>
</li>
<li>
<button id="btn-stop_execution" title="Stop execution" disabled>
<i class="fa-solid fa-stop"></i>
</button>
</li>
<li>
<button id="btn-clean_execution" title="Clean execution" disabled>
<i class="fa-solid fa-eraser"></i>
</button>
</li>
<li>
<button id="btn-show_results" title="Show/Hide result" disabled>
<i class="fa-solid fa-table"></i>
</button>
</li>
</ul>
</section>
</menu>
<div id="editor_body">
<!-- CANVAS -->
<svg id="canvas" width="100%" height="100%" viewBox="0 0 1200 700">
<defs>
<marker id="arrowhead" orient="auto" markerUnits="userSpaceOnUse" markerWidth="19" markerHeight="15" refX="39"
refY="7.5">
<path fill-rule="evenodd" clip-rule="evenodd"
d="M2.00686 14.4884H1.43619C1.09138 14.423 0.776803 14.24 0.569826 13.9598C0.201536 13.4613 0.272124 12.7994 0.741694 12.3757L6.14329 7.50152L0.741695 2.62733C0.272125 2.20361 0.198466 1.53895 0.569826 1.04322C0.941185 0.547492 1.64708 0.353632 2.26089 0.586263L17.4836 6.34666C17.9992 6.54052 18.3337 6.99748 18.3337 7.50152C18.3337 8.00555 17.9992 8.46251 17.4836 8.65637L2.26089 14.4168C2.1776 14.4483 2.09256 14.4721 2.00686 14.4884Z"
fill="#303952" />
</marker>
<marker id="arrowhead_temp" orient="auto" markerUnits="userSpaceOnUse" markerWidth="19" markerHeight="15"
refX="18" refY="7.5">
<path fill-rule="evenodd" clip-rule="evenodd"
d="M2.00686 14.4884H1.43619C1.09138 14.423 0.776803 14.24 0.569826 13.9598C0.201536 13.4613 0.272124 12.7994 0.741694 12.3757L6.14329 7.50152L0.741695 2.62733C0.272125 2.20361 0.198466 1.53895 0.569826 1.04322C0.941185 0.547492 1.64708 0.353632 2.26089 0.586263L17.4836 6.34666C17.9992 6.54052 18.3337 6.99748 18.3337 7.50152C18.3337 8.00555 17.9992 8.46251 17.4836 8.65637L2.26089 14.4168C2.1776 14.4483 2.09256 14.4721 2.00686 14.4884Z"
fill="#303952" />
</marker>
</defs>
<g id="edges"></g>
<g id="nodes"></g>
</svg>
<div id="algorithm_results">
<h2>Results</h2>
<table></table>
</div>
</div>
<!-- MODALS -->
<dialog id="new_graph_modal">
<div class="header">
<h3>Create New Graph</h3>
</div>
<div class="body">
<form id="new_graph_form">
<div class="form-input">
<label for="graph_type">Graph Type:</label>
<select id="graph_type" name="graph_type">
<option value="undirected">Undirected</option>
<option value="directed">Directed</option>
</select>
</div>
<div class="form-input">
<label for="weighted_graph">Weighted Graph:</label>
<input type="checkbox" name="weighted_graph" id="weighted_graph">
</div>
<div class="form-input">
<label for="autoname">Naming Nodes Automatically:</label>
<input type="checkbox" name="autoname" id="autoname" checked>
</div>
</form>
<div class="buttons">
<button class="secondary" modal-cancel>Cancel</button>
<button form="new_graph_form" class="primary" modal-accept>Create</button>
</div>
</div>
</dialog>
<dialog id="name_node_modal">
<div class="header">
<h3>Create a Node</h3>
</div>
<div class="body">
<form id="name_node_form">
<div class="form-input">
<label for="node_name">Node Name:</label>
<input type="text" name="node_name" id="node_name" autocomplete="off">
</div>
</form>
<div class="buttons">
<button class="secondary" modal-cancel>Cancel</button>
<button form="name_node_form" class="primary" modal-accept>Create Node</button>
</div>
</div>
</dialog>
<dialog id="edge_weight_modal">
<div class="header">
<h3>Create an Edge</h3>
</div>
<div class="body">
<form id="edge_weight_form">
<div class="form-input">
<label for="edge_weight">Edge Weight:</label>
<input type="number" name="edge_weight" id="edge_weight">
</div>
</form>
<div class="buttons">
<button class="secondary" modal-cancel>Cancel</button>
<button form="edge_weight_form" class="primary" modal-accept>Create Edge</button>
</div>
</div>
</dialog>
</main>
<script type="module" src="/src/editor.ts"></script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
|
import * as React from 'react'
import { Link, useStaticQuery, graphql } from 'gatsby'
const Layout = ({ pageTitle, children }) => {
// same as
// const Layout = (props) => {
// const pageTitle = props.pageTitle
// const children = props.children
// } - javascript destructuring
const data = useStaticQuery(graphql`
query {
site {
siteMetadata {
title
}
}
}
`)
return (
<div>
<title>{pageTitle}</title>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
<main>
<h1>{pageTitle} (this is a layout)</h1>
gql query data: {data.site.siteMetadata.title}
{children}
</main>
</div>
)
}
export default Layout
|
// import { NgModule } from '@angular/core';
// import { BrowserModule } from '@angular/platform-browser';
// import { AppComponent } from './app.component';
// @NgModule({
// declarations: [
// AppComponent
// ],
// imports: [
// BrowserModule
// ],
// providers: [],
// bootstrap: [AppComponent]
// })
// export class AppModule { }
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { ImageService } from './services/image.service';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
declarations: [
AppComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [ImageService],
bootstrap: [AppComponent]
})
export class AppModule { }
|
package dependent;
import dependency.Transport;
public class ATMImpl implements ATM {
private Transport myTransport;// = new HttpTransport();// creating dependency n linking it with the dep. obj
//implicit(auto wire) ctor based D.I
public ATMImpl(Transport t) {
this.myTransport = t;
System.out.println("in cnstr of " + getClass().getName() + " " + myTransport);// not null
}
@Override
public void deposit(double amt) {
System.out.println("depositing " + amt);
byte[] data = ("depositing " + amt).getBytes();
myTransport.informBank(data);// using dependency layer
}
@Override
public void withdraw(double amt) {
System.out.println("withdrawing " + amt);
byte[] data = ("withdrawing " + amt).getBytes();
myTransport.informBank(data);// using dependency layer
}
// custom init method
public void myInit() {
System.out.println("myInit " + myTransport);// not null!
}
// custom destroy method
public void myDestroy() {
System.out.println("in destroy " + myTransport);// not null!
}
}
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Error_1 = require("shared/Error");
const createResponseMessage_1 = __importDefault(require("shared/lib/createResponseMessage"));
const user_1 = __importDefault(require("@services/user"));
const _logger_1 = __importDefault(require("@logger"));
function getOrganizationMembers(req, res, next) {
return __awaiter(this, void 0, void 0, function* () {
try {
const orgId = req.params.org_id;
if (typeof orgId !== "string") {
throw new Error_1.BadRequestError("org_id empty");
}
const users = yield user_1.default.getMembersInOrg(orgId);
_logger_1.default.debug(`org : ${orgId}의 유저들 \n${JSON.stringify(users, null, 4)}`);
return res.status(200).json((0, createResponseMessage_1.default)("success", "success", { users: users }));
}
catch (error) {
next(error);
}
});
}
exports.default = getOrganizationMembers;
//# sourceMappingURL=getOrganizationMembers.js.map
|
package com.willfp.libreforge.triggers.impl
import com.willfp.libreforge.triggers.Trigger
import com.willfp.libreforge.triggers.TriggerData
import com.willfp.libreforge.triggers.TriggerParameter
import org.bukkit.entity.Arrow
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.entity.EntityDamageByEntityEvent
import org.bukkit.event.entity.ProjectileHitEvent
object TriggerProjectileHit : Trigger("projectile_hit") {
override val parameters = setOf(
TriggerParameter.PLAYER,
TriggerParameter.VICTIM,
TriggerParameter.PROJECTILE,
TriggerParameter.LOCATION,
TriggerParameter.BLOCK,
TriggerParameter.EVENT,
TriggerParameter.VELOCITY
)
@EventHandler(ignoreCancelled = true)
fun handle(event: ProjectileHitEvent) {
val projectile = event.entity
val shooter = projectile.shooter
if (shooter !is Player) {
return
}
this.dispatch(
shooter,
TriggerData(
player = shooter,
projectile = projectile,
location = projectile.location,
block = event.hitBlock,
event = event,
velocity = projectile.velocity
)
)
}
@EventHandler(ignoreCancelled = true)
fun handle(event: EntityDamageByEntityEvent) {
val arrow = event.damager as? Arrow ?: return
val victim = event.entity as? LivingEntity ?: return
val player = arrow.shooter as? Player ?: return
this.dispatch(
player,
TriggerData(
player = player,
victim = victim,
location = arrow.location,
event = event,
velocity = arrow.velocity,
projectile = arrow
)
)
}
}
|
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ToastrModule } from 'ngx-toastr';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from "@angular/common/http";
//Componentes
import { FooterComponent } from './footer/footer.component';
import { HeaderComponent } from './header/header.component';
import { HomeComponent } from './principal/home/home.component';
import { AboutusComponent } from './principal/aboutus/aboutus.component';
import { RegisterComponent } from './principal/register/register.component';
import { LoginComponent } from './principal/login/login.component';
import { ListProductComponent } from './productos/list-product/list-product.component';
import { CreateProductComponent } from './productos/create-product/create-product.component';
import { ScrollToTopComponent } from './scroll-to-top/scroll-to-top.component';
@NgModule({
declarations: [
AppComponent,
FooterComponent,
HeaderComponent,
HomeComponent,
AboutusComponent,
RegisterComponent,
LoginComponent,
ListProductComponent,
CreateProductComponent,
ScrollToTopComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
BrowserAnimationsModule,
ToastrModule.forRoot(),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
#!/usr/bin/python3
def safe_print_division(a, b):
"""Divides 2 integers and prints the result.
Args:
a: Numerator (integer)
b: The denominator
Returns: Value of the division else None.
"""
try:
result = a/b
except ZeroDivisionError:
result = None
finally:
print("Inside result: {}".format(result))
return result
|
import {AppService} from '../../../../services/app.service';
import {ConfirmComponent} from '../../../framework/confirmbox/confirm.component';
import {HeaderService} from '../../../common/header/header.service';
import {ActionIcons} from '../../../framework/smarttable/cellRenderer/ActionsIcons';
import {Component, OnInit} from '@angular/core';
import {OrganizationDocumentRepositoryService} from "./document-repository.service";
import {Http, Headers, RequestOptions, Response} from "@angular/http";
import * as FileSaver from 'file-saver';
import {BootstrapModalModule} from 'ng2-bootstrap-modal';
import {DialogService, DialogComponent} from "ng2-bootstrap-modal";
import {SortType} from "../../../framework/smarttable/types/query-parameters";
export interface ConfirmModel {
title: string;
message: string;
getData: boolean;
editFiles: boolean;
editFileObject: Object;
}
@Component({
selector: 'app-document-repository',
templateUrl: './document-repository.component.html',
styleUrls: ['./document-repository.component.sass']
})
export class OrganizationDocumentRepositoryComponent extends DialogComponent<ConfirmModel, boolean> implements OnInit {
warningMessage: boolean;
private message: string;
private accountId;
public settings;
public getFiles;
public getData: boolean = true;
public editFiles: boolean;
public editFileObject: any = {};
constructor(private organizationdocumentrepositoryService: OrganizationDocumentRepositoryService, private http: Http,
public appService: AppService, public dialogService: DialogService, private headerService: HeaderService) {
super(dialogService);
this.accountId = this.appService.user.accountId;
this.settings = {
'pagination': false,
'isDeleteEnable': false,
'isAddButtonEnable': false,
'rowHeight': 30,
'context': {
'componentParent': this
},
'sort' : [{
headingName: "updatedDate",
sort: SortType.DESC
}],
'columnsettings': [
{
headerName: "Actions",
cellRendererFramework: ActionIcons,
width: 80
},
{
headerName: "SL No",
field: "orderNo",
width: 50
},
{
headerName: "File Name",
field: "fileName",
},
{
headerName: "Uploaded Date",
field: "updatedDate",
width: 100
}
]
}
};
onDeleteClick(event) {
this.dialogService.addDialog(ConfirmComponent, {
title: 'Confirmation',
message: 'Are you sure you want to delete ' + event.data.fileName + ' ?'
})
.subscribe((isConfirmed) => {
//Get dialog result
if (isConfirmed) {
this.organizationdocumentrepositoryService.deleteFile(event.data.fileId).subscribe(res => {
this.getFilesList();
});
}
});
}
highlightSBLink(link) {
this.appService.currentSBLink = link;
}
fileUpload(event) {
let fileList: FileList = event.target.files;
let file: File = fileList[0];
let formData: FormData = new FormData();
var x = file.name;
let fileExists = this.isfileExists(file);
var y = x.split(".");
if (fileList.length > 0 && y[1] == "pdf" && fileExists != true) {
formData.append('file', file, file.name);
this.organizationdocumentrepositoryService.uploadFile(this.headerService.selectedOrg['orgId'], formData)
.subscribe(
res => {
this.getFilesList();
}
);
}
else {
if (fileExists == true) {
this.dialogService.addDialog(ConfirmComponent, {
title: 'Error..!',
message: 'File already exists'
});
}
else {
this.dialogService.addDialog(ConfirmComponent, {
title: 'Error..!',
message: 'Please upload only PDF file'
});
}
}
}
onReplaceClick(event) {
let fileList: FileList = event.event.target.files;
let file: File = fileList[0];
var x = file.name;
let fileExists = this.isfileExists(file);
this.dialogService.addDialog(ConfirmComponent, {
title: 'Information',
message: 'Do you want to replace '+x+' file ?'
}).subscribe((isConfirmed) => {
if (isConfirmed) {
let formData: FormData = new FormData();
var y = x.split(".");
if (fileList.length > 0 && y[1] == "pdf" && fileExists != true) {
formData.append('file', file, file.name);
this.organizationdocumentrepositoryService.replaceFile(event.data.fileId, formData)
.subscribe(
res => {
this.getFilesList();
}
);
}
if (fileExists) {
this.dialogService.addDialog(ConfirmComponent, {
title: 'Error..!',
message: 'File already exists.'
});
}
if (y[1] !== 'pdf') {
this.dialogService.addDialog(ConfirmComponent, {
title: 'Error..!',
message: 'Please upload only PDF file'
});
}
}
})
}
onDownloadClick(event) {
this.organizationdocumentrepositoryService.downloadFile(event.data.fileId).subscribe
(data => this.downloadFiles(data, event.data.fileName)),
error => console.log("Error Downloading....");
() => console.log("OK");
}
ngOnInit() {
this.getFilesList();
}
getFilesList() {
this.organizationdocumentrepositoryService.getFile(this.headerService.selectedOrg['orgId'])
.subscribe((res) => {
if (res != undefined) {
let data = res['files'];
for (var i = 0; i < data.length; i++) {
data[i]['orderNo'] = i + 1;
}
this.getFiles = data;
}
});
}
downloadFiles(data: any, fileName) {
var blob = new Blob([data], {
type: 'application/pdf'
});
FileSaver.saveAs(blob, fileName);
}
isfileExists(file) {
let fileExists : boolean = false;
this.getFiles.filter(item => {
if (file.name == item.fileName) {
fileExists = true;
}
});
return fileExists;
}
editFileName(event) {
if (event.colDef.headerName != 'Actions') {
this.editFileObject.fileName = event.data.fileName.split(".")[0];
this.dialogService.addDialog(OrganizationDocumentRepositoryComponent, {
editFiles: true,
getData: false,
title: 'Edit File Name',
editFileObject: this.editFileObject,
}).subscribe((isConfirmed) => {
if (isConfirmed) {
var FileId = event.data.fileId;
var fileName = this.editFileObject.fileName.concat(".pdf");
event.data.fileName = fileName;
var url = "/file/rename";
var data = {
"accountId": this.accountId,
"fileId": FileId,
"fileName": fileName
};
this.organizationdocumentrepositoryService.renameFile(url, data).subscribe(
res => {
if (res['statusCode'] == 'SUCCESS') {
this.getFilesList();
}
if (res['statusDescription'] == "File Name Exists, Use a different Name") {
this.dialogService.addDialog(ConfirmComponent, {
title: 'Error..!',
message: 'File with same name exists, please use a different name'
});
}
}
);
}
else {
this.editFileObject.fileName = event.data.fileName;
}
});
}
}
save() {
if (this.editFileObject['fileName'] == '' || this.editFileObject['fileName'] == null || this.editFileObject['fileName'] == undefined) {
this.warningMessage = true;
}
else {
this.warningMessage = false;
this.result = true;
this.close();
}
}
cancel() {
this.result = false;
this.close();
}
onFileUploadClick(file){
file.value=null;
}
}
|
#ifndef NBT_FILE_H_GUARD
#define NBT_FILE_H_GUARD
#include <cstdint>
#include <cstdio>
#include <string>
#include <cstring>
#include "NBT_Debug.h"
class NBT_File
{
public:
NBT_File();
NBT_File(const std::string &filename, bool readonly = true, bool append = false);
~NBT_File();
bool open();
bool open(const std::string &filename);
void close();
bool readCompressedMode(uint32_t length, bool gzip = false);
bool writeCompressedMode();
bool endCompressedMode();
bool clearCompressedMode();
bool seek(int64_t offset, int whence = SEEK_SET);
uint32_t tell()
{
if(compressedMode)
return buffer_pos;
return ftell(fh);
}
// maybe add a readBytes method and specialize read for the read* cases instead.
// so read(mydouble) would work properly, then we can get rid of the readDouble method and its friends.
bool read(uint8_t *out, uint32_t len = 1);
bool read(uint16_t *out);
bool read(uint32_t *out);
bool read(uint32_t *out, uint32_t len);
bool read(uint64_t *out);
bool read(int8_t *out, uint32_t len = 1) { return read((uint8_t*)out, len); }
bool read(int16_t *out) { return read((uint16_t*)out); }
bool read(int32_t *out) { return read((uint32_t*)out); }
bool read(int64_t *out) { return read((uint64_t*)out); }
bool read(float *out);
bool read(double *out);
bool read(std::string &out);
bool eof()
{
if(compressedMode)
return buffer_len >= buffer_size;
return feof(fh);
}
bool write(uint8_t *in, uint32_t len = 1);
bool write(uint8_t in);
bool write(uint16_t in);
bool write(uint32_t in);
bool write(uint32_t *in, uint32_t len);
bool write(uint64_t in);
bool write(int8_t *in, uint32_t len = 1) { return write((uint8_t*)in, len); }
bool write(int8_t in) { return write((uint8_t)in); }
bool write(int16_t in) { return write((uint16_t)in); }
bool write(int32_t in) { return write((uint32_t)in); }
bool write(int64_t in) { return write((uint64_t)in); }
bool write(float in);
bool write(double in);
bool write(const std::string &in);
uint32_t lastWriteBufferLen() { return last_write_buffer_len; }
private:
std::string filename;
bool readonly;
bool append;
enum {
COMP_MODE_NONE = 0,
COMP_MODE_READ,
COMP_MODE_WRITE
} compressedMode;
FILE *fh;
// buffer for handling compressed sections
uint8_t *buffer;
uint32_t buffer_size;
uint32_t buffer_len;
uint32_t buffer_pos;
uint32_t last_write_buffer_len;
static int32_t npot(int32_t in)
{
in |= (in >> 1);
in |= (in >> 2);
in |= (in >> 4);
in |= (in >> 8);
in |= (in >> 16);
in++;
return in;
}
bool ensureSize(int32_t len);
bool checkOffset(int32_t len)
{
/*NBT_Debug("%i - %i - %i = %i", length, offset, len, length - offset - len);*/
return (buffer_pos + len <= buffer_len);
}
bool writeCompressedData();
uint8_t *scratch_buffer;
size_t scratch_buffer_size;
bool ensure_scratch_buffer_size(size_t s);
};
inline bool NBT_File::read(uint8_t *out, uint32_t len)
{
if(compressedMode)
{
if(checkOffset(sizeof(uint8_t) * len))
{
memcpy(out, buffer + buffer_pos, sizeof(uint8_t) * len);
buffer_pos += sizeof(uint8_t) * len;
//for(uint32_t i = 0; i < len; i++)
//{
// printf("%02x ", out[i]);
//}
//printf("\n");
return true;
}
return false; // eof?
}
if(!fh)
return false;
uint16_t ret = std::fread(out, sizeof(uint8_t), len, fh);
if(ret != sizeof(uint8_t) * len)
return false;
return true;
}
inline bool NBT_File::read(uint16_t *out)
{
uint8_t tmp[sizeof(*out)];
if(!read(tmp, sizeof(*out)))
return false;
*out = tmp[0] << 8 | tmp[1];
return true;
}
inline bool NBT_File::read(uint32_t *out)
{
uint8_t tmp[sizeof(*out)];
if(!read(tmp, sizeof(*out)))
return false;
uint32_t swap = (tmp[0] << 24) |
(tmp[1] << 16) |
(tmp[2] << 8) |
tmp[3];
*out = swap;
//NBT_Debug("read: %08x -> %08x -> %u", *((uint32_t*)tmp), swap, swap);
return true;
}
inline bool NBT_File::read(uint32_t *out, uint32_t len)
{
bool ret = true;
for(uint32_t i = 0; i < len && ret != false; i++)
{
ret = read(out+i);
}
return ret;
}
inline bool NBT_File::read(uint64_t *out)
{
uint8_t tmp[sizeof(*out)];
if(!read(tmp, sizeof(*out)))
return false;
*out = (uint64_t)tmp[0] << 56 | (uint64_t)tmp[1] << 48 |
(uint64_t)tmp[2] << 40 | (uint64_t)tmp[3] << 32 |
(uint64_t)tmp[4] << 24 | (uint64_t)tmp[5] << 16 |
(uint64_t)tmp[6] << 8 | tmp[7];
return true;
}
inline bool NBT_File::read(float *out)
{
return read((uint32_t *)out);
}
inline bool NBT_File::read(double *out)
{
return read((uint64_t *)out);
}
inline bool NBT_File::read(std::string &out)
{
uint16_t len = 0;
if(!read(&len))
return false;
//NBT_Debug("read len: %i", len);
if(len == 0)
return true;
if(!ensure_scratch_buffer_size(len+1))
return false;
scratch_buffer[len] = 0;
if(!read(scratch_buffer, len))
{
NBT_Debug("failed to read string from nbt file :(");
return false;
}
out.assign((char*)scratch_buffer, len);
return true;
}
// write!
inline bool NBT_File::write(uint8_t *in, uint32_t len)
{
if(compressedMode)
{
//NBT_Debug("writing %i bytes", len);
if(ensureSize(len))
{
memcpy(buffer + buffer_pos, in, len);
buffer_pos += len;
if(buffer_pos > buffer_len)
buffer_len = buffer_pos;
return true;
}
return false;
}
uint32_t ret = fwrite(in, 1, len, fh);
if(ret != len)
return false;
return true;
}
inline bool NBT_File::write(uint8_t in)
{
//NBT_Debug("write char: %u", in);
return write(&in, 1);
}
inline bool NBT_File::write(uint16_t in)
{
uint8_t tmp[sizeof(in)], *ptr = (uint8_t *)∈
tmp[0] = ptr[1];
tmp[1] = ptr[0];
return write(tmp, sizeof(tmp));
}
inline bool NBT_File::write(uint32_t in)
{
uint8_t tmp[sizeof(in)], *ptr = (uint8_t *)∈
//NBT_Debug("write int: %u", in);
tmp[0] = ptr[3];
tmp[1] = ptr[2];
tmp[2] = ptr[1];
tmp[3] = ptr[0];
return write(tmp, sizeof(tmp));
}
inline bool NBT_File::write(uint32_t *in, uint32_t len)
{
bool ret = true;
//NBT_Debug("write %i integers", len);
for(uint32_t i = 0; i < len && ret != false; i++)
{
ret = write(in[i]);
}
return ret;
}
inline bool NBT_File::write(uint64_t in)
{
uint8_t tmp[sizeof(in)], *ptr = (uint8_t *)∈
//NBT_Debug("write 64bit int");
tmp[0] = ptr[7];
tmp[1] = ptr[6];
tmp[2] = ptr[5];
tmp[3] = ptr[4];
tmp[4] = ptr[3];
tmp[5] = ptr[2];
tmp[6] = ptr[1];
tmp[7] = ptr[0];
return write(tmp, sizeof(tmp));
}
inline bool NBT_File::write(float in)
{
//NBT_Debug("write float");
uint32_t *ptr = (uint32_t*)∈
return write(*ptr);
}
inline bool NBT_File::write(double in)
{
//NBT_Debug("write double");
uint64_t *ptr = (uint64_t*)∈
return write(*ptr);
}
inline bool NBT_File::write(const std::string &in)
{
uint16_t len = in.length();
//NBT_Debug("write %i byte string", len);
if(!ensureSize(sizeof(len) + sizeof(int8_t) * len))
return false;
if(!write(len))
return false;
if(!write((uint8_t*)in.c_str(), len))
return false;
return true;
}
#endif /* NBT_FILE_H_GUARD */
|
import { Component } from '@angular/core';
import { catchError, take } from 'rxjs';
import { MockRequestsService } from '@operators/services/mock-requests.service';
import { NotificationService } from '@operators/services/notification.service';
@Component({
selector: 'app-catch-error-operator',
templateUrl: './catch-error-operator.component.html',
styleUrls: ['./catch-error-operator.component.scss']
})
export class CatchErrorOperatorComponent {
constructor(private mockRequestService: MockRequestsService, private notification: NotificationService) {}
codeExample = `this.mockRequestService.getError().pipe(
catchError((err, caught) => {
this.createErrorNotification(err);
return caught;
}),
take(5)
).subscribe();`;
public sendRequestToGetError() {
this.mockRequestService.getError().pipe(
catchError((err, caught) => {
this.createErrorNotification(err);
return caught;
}),
take(5)
).subscribe();
}
public createErrorNotification(err: string): void {
this.notification.createErrorNotification(err);
}
}
|
//
// UserModel.swift
// th-ios
//
// Created by chengfj on 2018/2/15.
// Copyright © 2018年 wincode.com. All rights reserved.
//
import UIKit
extension UserModel {
static let current: UserModel = UserModel.loadCacheUser()
}
class UserModel: NSObject, NSCoding {
var isLogin: MutableProperty<Bool>!
var avatar: MutableProperty<URL?>!
var sid: MutableProperty<String>!
var userID: MutableProperty<String>!
var userName: MutableProperty<String>!
var currentCityName: MutableProperty<String> = MutableProperty("广州")
var currentCityId: MutableProperty<String> = MutableProperty("25")
override init() {
super.init()
self.isLogin = MutableProperty(false)
self.avatar = MutableProperty<URL?>(nil)
self.sid = MutableProperty<String>("")
self.userID = MutableProperty<String>("")
self.userName = MutableProperty<String>("")
self.bindKeyPath()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.isLogin.value, forKey: "isLogin")
aCoder.encode(self.avatar.value?.absoluteString, forKey: "avatar")
aCoder.encode(self.sid.value, forKey: "sid")
aCoder.encode(self.userID.value, forKey: "userID")
aCoder.encode(self.userName.value, forKey: "userName")
}
required init?(coder aDecoder: NSCoder) {
super.init()
self.isLogin = self.property(val: aDecoder.decodeBool(forKey: "isLogin"))
if let urlString = aDecoder.decodeObject(forKey: "avatar") as? String {
self.avatar = self.property(val: URL.init(string: urlString))
} else {
self.avatar = MutableProperty<URL?>(nil)
}
self.sid = self.property(val: aDecoder.decodeObject(forKey: "sid") as! String)
self.userID = self.property(val: aDecoder.decodeObject(forKey: "userID") as! String)
self.userName = self.property(val: aDecoder.decodeObject(forKey: "userName") as! String)
self.bindKeyPath()
}
private func property<T>(val: T) -> MutableProperty<T> {
return MutableProperty<T>(val)
}
func bindKeyPath() {
Signal.combineLatest(self.isLogin.signal,
self.avatar.signal,
self.sid.signal,
self.userID.signal,
self.userName.signal)
.observeValues { (tulp) in
UserModel.saveCurrentUser()
}
}
func clear() {
self.isLogin.value = false
self.avatar.value = nil
self.sid.value = ""
self.userID.value = ""
self.userName.value = ""
}
}
extension UserModel {
class func saveCurrentUser() {
let data: NSMutableData = NSMutableData.init()
let archiver = NSKeyedArchiver.init(forWritingWith: data)
archiver.encode(UserModel.current, forKey: "currentUser")
archiver.finishEncoding()
UserDefaults.standard.set(data, forKey: "currentUser")
UserDefaults.standard.synchronize()
}
class func loadCacheUser() -> UserModel {
if let data: Data = UserDefaults.standard.value(forKey: "currentUser") as? Data {
let unchiver = NSKeyedUnarchiver.init(forReadingWith: data)
let user = unchiver.decodeObject(forKey: "currentUser")
unchiver.finishDecoding()
if let user: UserModel = user as? UserModel {
return user
}
}
return UserModel()
}
}
|
import re
from collections import namedtuple
from flask import abort
from sqlalchemy import func
from ..extensions import db
from ..utils import json_output, propagate_satellite
from . import models
NO_TLE_FOUND = "Error: No TLE found"
def propagate_and_create_json_results(
location,
jd,
tle_line_1,
tle_line_2,
date_collected,
name,
min_altitude,
max_altitude,
catalog_id="",
data_source="",
):
# propagation and create output
result_list = []
for d in jd:
# Right ascension RA (deg), Declination Dec (deg), dRA/dt*cos(Dec) (deg/day),
# dDec/dt (deg/day), Altitude (deg), Azimuth (deg), dAlt/dt (deg/day),
# dAz/dt (deg/day), distance (km), range rate (km/s), phaseangle(deg),
# illuminated (T/F)
satellite_position = propagate_satellite(tle_line_1, tle_line_2, location, d)
if (
satellite_position.alt.degrees > min_altitude
and satellite_position.alt.degrees < max_altitude
):
result_list.append(
json_output(
name,
catalog_id,
d.jd,
satellite_position.ra,
satellite_position.dec,
date_collected,
satellite_position.dracosdec,
satellite_position.ddec,
satellite_position.alt,
satellite_position.az,
satellite_position.distance,
satellite_position.ddistance,
satellite_position.phase_angle,
satellite_position.illuminated,
data_source,
satellite_position.satellite_gcrs,
satellite_position.observer_gcrs,
)
)
if not result_list:
return {"info": "No position information found with this criteria"}
return result_list
def get_tle_by_catalog_number(target_number, data_source, date):
"""Query Two Line Element (orbital element) API and return TLE lines for propagation
Paremeters:
------------
target_number: 'str'
Catalog number of satellite as displayed in TLE file
data_source: 'str'
Original source of TLE data (celestrak or spacetrack)
date: 'datetime'
Date to query TLE data
Returns
-------
tle_sat: 'TLE, Satellite'
tuple with TLE and Satellite objects
"""
# use the tle closest to the date given (at the same time or before)
try:
tle_sat = (
db.session.query(models.TLE, models.Satellite)
.filter_by(data_source=data_source)
.join(models.Satellite, models.TLE.sat_id == models.Satellite.id)
.filter_by(sat_number=target_number)
.order_by(
func.abs(
func.extract("epoch", models.TLE.date_collected)
- func.extract("epoch", date)
)
)
.first()
)
except Exception:
# app.logger.error(e)
return None
return tle_sat
def get_tle_by_name(target_name, data_source, date):
"""Query Two Line Element (orbital element) API and return TLE lines for propagation
Paremeters:
------------
target_name: 'str'
Name of satellite as displayed in TLE file
data_source: 'str'
Original source of TLE data (celestrak or spacetrack)
date: 'datetime'
Date to query TLE data
Returns
-------
tle_sat: 'TLE, Satellite'
tuple with TLE and Satellite objects
"""
# use the tle closest to the date given (at the same time or before)
try:
tle_sat = (
db.session.query(models.TLE, models.Satellite)
.filter_by(data_source=data_source)
.join(models.Satellite, models.TLE.sat_id == models.Satellite.id)
.filter_by(sat_name=target_name)
.order_by(
func.abs(
func.extract("epoch", models.TLE.date_collected)
- func.extract("epoch", date)
)
)
.first()
)
except Exception:
# app.logger.error(e)
return None
return tle_sat
def get_tle(identifier, use_catalog_number, data_source, date):
tle_sat = (
get_tle_by_catalog_number(identifier, data_source, date)
if use_catalog_number
else get_tle_by_name(identifier, data_source, date)
)
if not tle_sat:
abort(500, NO_TLE_FOUND)
return tle_sat
def parse_tle(tle):
# parse url encoded parameter to string to remove space encoding
tle = tle.replace("%20", " ")
# split string into three lines based on url encoded space character
try:
pattern = re.compile(r"\\n|\n")
tle_data = pattern.split(tle)
except Exception:
abort(500, "Incorrect TLE format")
if len(tle_data) == 3:
name = tle_data[0].strip()
tle_line_1 = tle_data[1].strip()
tle_line_2 = tle_data[2].strip()
else:
name = None
tle_line_1 = tle_data[0].strip()
tle_line_2 = tle_data[1].strip()
# if any are null throw error
if (
[x for x in (tle_line_1, tle_line_2) if x is None]
or len(tle_line_1) != 69
or len(tle_line_2) != 69
):
abort(500, "Incorrect TLE format")
catalog = tle_line_1[2:6]
tle = namedtuple(
"tle", ["tle_line1", "tle_line2", "date_collected", "name", "catalog"]
)
return tle(tle_line_1, tle_line_2, None, name, catalog)
|
import { useEffect, useState } from "react";
import Actor from "../Actor/Actor";
const Actors = ({handleCart}) => {
const [allActors, setAllActors] = useState([]);
useEffect(() => {
fetch("/team.json")
.then((res) => res.json())
.then((data) => setAllActors(data));
}, []);
return (
<>
<div className="grid grid-cols-1 md:grid-cols-2 text-center">
{
allActors.map((actor) => (
<Actor key={actor.id} actor={actor} handleCart={handleCart}></Actor>
))}
</div>
</>
);
};
export default Actors;
|
import Link from "next/link";
import React from "react";
import MovieCard, { IMovieCard } from "./MovieCard";
const TopRatedMovies = ({ topRatedMovies }: { topRatedMovies: any }) => {
return (
<div className="flex flex-col mb-6">
<div className="flex flex-col sm:flex-row justify-between items-center mt-4">
<h1 className="text-2xl font-medium">Top Rated Movies</h1>
<Link
href="/movies/top-rated"
className="py-2 px-5 bg-slate-800 text-md font-normal text-white mt-4 sm:mt-0"
>
See all
</Link>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 mt-4 gap-4">
{topRatedMovies.results.slice(0, 4).map((movie: IMovieCard) => (
<MovieCard key={movie?.id} movie={movie} />
))}
</div>
</div>
);
};
export default TopRatedMovies;
|
import React from 'react';
import '../styles/ListaFuncionarios.css';
function ListaFuncionarios({ funcionarios, onEdit, onDelete }) {
return (
<div>
<ul className="funcionarios-list">
{funcionarios.map(funcionario => (
<li key={funcionario.cpf}>
<div className="funcionario-item">
<span>CNPJ: {funcionario.cnpj}</span>
<span>CPF: {funcionario.cpf}</span>
<span>Matrícula: {funcionario.matricula}</span>
<span>Nome: {funcionario.nome}</span>
<span>Departamento: {funcionario.codigodepartamento}</span>
<span>Endereço: {funcionario.endereco}</span>
<span>Salário: {funcionario.salario}</span>
<span>Cargo: {funcionario.cargo}</span>
<span>Data de Admissão: {funcionario.dataadmissao}</span>
<span>Data de Nascimento: {funcionario.datanascimento}</span>
<span>Telefone: {funcionario.telefone}</span>
<span>Email: {funcionario.email}</span>
<button onClick={() => onEdit(funcionario)}>Editar</button>
<button onClick={() => onDelete(funcionario.cpf)}>Deletar</button>
</div>
</li>
))}
</ul>
</div>
);
}
export default ListaFuncionarios;
|
//import React from "react";
//import { Link } from "react-router-dom";
////import * as Icons from ".react-icons/fa";
//import { Route, Routes } from "react-router-dom";
//import Products from "../pages/Products";
//import Button from "./Button";
//import { navItems } from "./NavItems";
//import "./Navbar.css";
//function Navbar()
//{
// return(
// <>
// <nav className="Navbar">
// <Link to="/" className="navbar-logo">
// Nature
// </Link>
// <ul className="nav-item">
// {navItems.map(item=>{
// return(
// <li key={item.id} className={item.class}>
// <Link to={item.path}>{item.title}</Link>
//
//
// </li>
//
// );
// })}
// </ul>
// <Button/>
//
// </nav>
// </>
// );
//}
//export default Navbar;
import { useRef } from "react";
import { FaBars, FaTimes } from "react-icons/fa";
import { Link } from "react-router-dom";
import "./Navbar.css";
function Navbar() {
const navRef = useRef();
const showNavbar = () => {
navRef.current.classList.toggle(
"responsive_nav"
);
};
return (
<header>
<h2> KK Grocery</h2>
<nav ref={navRef}>
<h4><Link to='/'>Home</Link></h4>
<h4><Link to='/features'>Features</Link></h4>
<h4><Link to='/category'>Category</Link></h4>
<h4><Link to='/products'>Products</Link></h4>
<h4><Link to='/contact'>Contact</Link></h4>
<h4><Link to='/Login'>Login</Link></h4>
<button
className="nav-btn nav-close-btn"
onClick={showNavbar}>
<FaTimes />
</button>
<div className="cart">
<span>
<i class="fas fa-cart-plus"></i>
</span>
<span>1</span>
</div>
</nav>
<button
className="nav-btn"
onClick={showNavbar}>
<FaBars />
</button>
</header>
);
}
export default Navbar;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.