text
stringlengths
184
4.48M
# --- Day 11: Seating System --- setwd("C:/Users/15517/Downloads") library(tidyverse) input <- readLines("2020_d11.txt") #93 col 90 row space <- array(9, dim=c(92,95)) for(i in seq_len(91)){ space[(i+1),2:94] <- case_when(str_split(input[i], "")[[1]] == "L" ~1, str_split(input[i], "")[[1]] == "." ~0) } #0 IS FLOOR #1 IS EMPTY #2 IS TAKEN change <- function(x,y){ current <- space[x,y] set <- as.vector(space[(x-1):(x+1),(y-1):(y+1)])[-5] empty <- length(which(set==1)) taken <- length(which(set==2)) if(current == 1 && taken == 0){ return(2) } else if(current == 2 && taken >= 4){ return(1) } else { return(current) } } moves <- array(9, dim=c(92,95)) round <- 1 storage <- list(space) repeat{ for(i in 2:91) for(j in 2:94) moves[i,j] <- change(i,j) space <- moves round <- round + 1 storage[[round]] <- space if(identical(storage[[round-1]], storage[[round]])) break } length(which(moves==2)) #ANSWER -------------> 2,194 #PART 2: MORE COMPLEX CHANGE FUNCTION changep2 <- function(x,y){ current <- space[x,y] singleformat <- x + (y-1)*92 ndiag <- which(row(space)- col(space) == (row(space)- col(space))[singleformat]) rdiag <- which(row(space)+ col(space) == (row(space)+ col(space))[singleformat]) nlen <- length(ndiag) rlen <- length(rdiag) nbound <- which(which(row(space)- col(space) == (row(space)- col(space))[singleformat]) == singleformat) rbound <- which(which(row(space)+ col(space) == (row(space)+ col(space))[singleformat]) == singleformat) down <- space[(x+1):92,y][min(which(space[(x+1):92,y] != 0))] up <- space[(x-1):1,y][min(which(space[(x-1):1,y] != 0))] right <- space[x,(y+1):95][min(which(space[x,(y+1):95] != 0))] left <- space[x,(y-1):1][min(which(space[x,(y-1):1] != 0))] urdv <- space[ndiag][(nbound-1):1][min(which(space[ndiag][(nbound-1):1] != 0))] uldv <- space[ndiag][(nbound+1):nlen][min(which(space[ndiag][(nbound+1):nlen] != 0))] lldv <- space[rdiag][(rbound+1):rlen][min(which(space[rdiag][(rbound+1):rlen] != 0))] lrdv <- space[rdiag][(rbound-1):1][min(which(space[rdiag][(rbound-1):1] != 0))] set <- c(left,right,down,up,uldv,urdv,lldv,lrdv) empty <- length(which(set==1)) taken <- length(which(set==2)) if(current == 1 && taken == 0){ return(2) } else if(current == 2 && taken >= 5){ return(1) } else { return(current) } } space <- array(9, dim=c(92,95)) for(i in seq_len(91)){ space[(i+1),2:94] <- case_when(str_split(input[i], "")[[1]] == "L" ~1, str_split(input[i], "")[[1]] == "." ~0) } moves <- array(9, dim=c(92,95)) round <- 1 storage <- list(space) repeat{ for(i in 2:91) for(j in 2:94) # print(paste0(i, "_", j)) moves[i,j] <- changep2(i,j) space <- moves round <- round + 1 print(round) storage[[round]] <- space if(identical(storage[[round-1]], storage[[round]])) break } length(which(moves==2)) #ANSWER -----------> 1,944 kinda slow
package com.ahsj.smartparkcore.entity.dto; import com.ahsj.smartparkcore.entity.po.Book; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonFormat; import core.code.CodeValueColumn; import core.code.Constants; import org.springframework.format.annotation.DateTimeFormat; import java.math.BigDecimal; import java.util.Date; public class BookDTO extends Book { private Long id; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy/MM/dd ") private Date createDate; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy/MM/dd ") private Date updateDate; @CodeValueColumn(type = Constants.TYPE_CODE, typeKey = "book_type", typeName = "bookTypeName") private Integer bookType; private String bookTypeName; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy/MM/dd") @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date startTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy/MM/dd") @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date visitTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy/MM/dd") @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date endTime; @CodeValueColumn(type = Constants.TYPE_CODE, typeKey = "is_audit", typeName = "isAuditName") private Integer isAudit; private String isAuditName; @CodeValueColumn(type = Constants.TYPE_CODE, typeKey = "is_cancel", typeName = "isCancelName") private Integer isCancel; private String isCancelName; @CodeValueColumn(type = Constants.TYPE_CODE, typeKey = "is_pay", typeName = "isPayName") private Integer isPay; private String isPayName; @Override public Date getVisitTime() { return visitTime; } @Override public void setVisitTime(Date visitTime) { this.visitTime = visitTime; } private BigDecimal paymentAmount; private BigDecimal deposit; private String phoneNumber; private String subscriberName; private Long targetId; private String remarks; private String description; private Double area; private String capacity; private String location; private String name; private BigDecimal price; private String contactName; private String filePath; public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public Double getArea() { return area; } public void setArea(Double area) { this.area = area; } public String getCapacity() { return capacity; } public void setCapacity(String capacity) { this.capacity = capacity; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public Date getCreateDate() { return createDate; } @Override public void setCreateDate(Date createDate) { this.createDate = createDate; } @Override public Date getUpdateDate() { return updateDate; } @Override public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } @Override public Integer getBookType() { return bookType; } @Override public void setBookType(Integer bookType) { this.bookType = bookType; } @Override public Date getStartTime() { return startTime; } @Override public void setStartTime(Date startTime) { this.startTime = startTime; } @Override public Date getEndTime() { return endTime; } @Override public void setEndTime(Date endTime) { this.endTime = endTime; } @Override public Integer getIsAudit() { return isAudit; } @Override public void setIsAudit(Integer isAudit) { this.isAudit = isAudit; } public String getIsAuditName() { return isAuditName; } public void setIsAuditName(String isAuditName) { this.isAuditName = isAuditName; } @Override public Integer getIsCancel() { return isCancel; } @Override public void setIsCancel(Integer isCancel) { this.isCancel = isCancel; } public String getIsCancelName() { return isCancelName; } public void setIsCancelName(String isCancelName) { this.isCancelName = isCancelName; } @Override public Integer getIsPay() { return isPay; } @Override public void setIsPay(Integer isPay) { this.isPay = isPay; } public String getIsPayName() { return isPayName; } public void setIsPayName(String isPayName) { this.isPayName = isPayName; } @Override public BigDecimal getPaymentAmount() { return paymentAmount; } @Override public void setPaymentAmount(BigDecimal paymentAmount) { this.paymentAmount = paymentAmount; } @Override public BigDecimal getDeposit() { return deposit; } @Override public void setDeposit(BigDecimal deposit) { this.deposit = deposit; } @Override public String getPhoneNumber() { return phoneNumber; } @Override public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @Override public String getSubscriberName() { return subscriberName; } @Override public void setSubscriberName(String subscriberName) { this.subscriberName = subscriberName; } @Override public Long getTargetId() { return targetId; } @Override public void setTargetId(Long targetId) { this.targetId = targetId; } @Override public String getRemarks() { return remarks; } @Override public void setRemarks(String remarks) { this.remarks = remarks; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } public String getBookTypeName() { return bookTypeName; } public void setBookTypeName(String bookTypeName) { this.bookTypeName = bookTypeName; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Generic; using _253504_Frolenko_Lab3.Contracts; using Generic.Math; namespace _253504_Frolenko_Lab3.Entities { public class Room { public int Number { get; set; } public decimal Price { get; set; } public Room(int number, decimal price) { Number = number; Price = price; } } public class Client { public string Name { get; set; } public List<int> BookedRooms { get; set; } public Client(string name) { Name = name; BookedRooms = new List<int>(); } } public class HotelSystem : IHotelSystem { public event Action RoomListChanged; public event Action ClientListChanged; public event Action<string, int> RoomBooked; private Dictionary<int, Room> rooms; private List<Client> clients; public HotelSystem() { rooms = new Dictionary<int, Room>(); clients = new List<Client>(); } public void GetRoomInformation() { Console.WriteLine("Rooms Information:"); foreach (var room in rooms.Values) { Console.WriteLine($"Room Number: {room.Number}, Price: {room.Price}"); } } public void RegisterClient(string clientName) { if (clients.Any(client => client.Name == clientName)) { Console.WriteLine($"Client {clientName} is already registered."); } else { var client = new Client(clientName); clients.Add(client); Console.WriteLine($"Client {clientName} has been registered."); ClientListChanged?.Invoke(); } } public void BookRoom(string clientName, int roomNumber) { var client = clients.FirstOrDefault(client => client.Name == clientName); if (client == null) { Console.WriteLine($"Client {clientName} is not registered."); return; } var room = rooms.GetValueOrDefault(roomNumber); if (room == null) { Console.WriteLine($"Room {roomNumber} does not exist."); return; } if (client.BookedRooms.Contains(roomNumber)) { Console.WriteLine($"Room {roomNumber} is already booked by client {clientName}."); } else { client.BookedRooms.Add(roomNumber); RoomBooked?.Invoke(clientName, roomNumber); } } public void GetAvailableRooms() { var bookedRooms = clients.SelectMany(client => client.BookedRooms).Distinct(); var availableRooms = rooms.Values.Where(room => !bookedRooms.Contains(room.Number)).ToList(); if (availableRooms.Count > 0) { Console.WriteLine("Available Rooms:"); foreach (var room in availableRooms) { Console.WriteLine($"Room Number: {room.Number}, Price: {room.Price}"); } } else { Console.WriteLine("No available rooms at the moment."); } } public decimal CalculateStayCost(string clientName) { var client = clients.FirstOrDefault(client => client.Name == clientName); if (client == null) { Console.WriteLine($"Client {clientName} is not registered."); return 0; } decimal totalCost = 0; foreach (var roomNumber in client.BookedRooms) { if (rooms.TryGetValue(roomNumber, out var room)) { totalCost = GenericMath.Add(totalCost, room.Price); } } Console.WriteLine($"Total stay cost for client {clientName}: {totalCost}"); return totalCost; } public void AddRoom(int number, decimal price) { if (rooms.ContainsKey(number)) { Console.WriteLine($"Room {number} already exists."); return; } var room = new Room(number, price); rooms.Add(number, room); Console.WriteLine($"Room {number} with price {price} has been added."); RoomListChanged?.Invoke(); } public List<int> GetRoomsSortedByPrice() { var sortedRooms = rooms.Values.OrderBy(room => room.Price).Select(room => room.Number).ToList(); return sortedRooms; } public decimal GetTotalStayCost() { decimal totalCost = clients.SelectMany(client => client.BookedRooms) .Sum(roomNumber => rooms.GetValueOrDefault(roomNumber)?.Price ?? 0); return totalCost; } public string GetClientWithMaxPayment() { var clientWithMaxPayment = clients.OrderByDescending(client => client.BookedRooms.Sum(roomNumber => rooms.GetValueOrDefault(roomNumber)?.Price ?? 0)) .FirstOrDefault(); return clientWithMaxPayment?.Name; } public int GetNumberOfClientsWithPaymentGreaterThan(decimal amount) { int count = clients.Aggregate(0, (total, client) => total + (client.BookedRooms.Sum(roomNumber => rooms.GetValueOrDefault(roomNumber)?.Price ?? 0) > amount ? 1 : 0)); return count; } public Dictionary<decimal, int> GetRoomCountByPriceCategory() { var roomCountByPriceCategory = rooms.Values.GroupBy(room => room.Price) .ToDictionary(group => group.Key, group => group.Count()); return roomCountByPriceCategory; } public int GetMostPopularRoom() { var roomCounts = clients .SelectMany(client => client.BookedRooms) .GroupBy(roomNumber => roomNumber) .OrderByDescending(group => group.Count()) .ToList(); if (roomCounts.Count > 0) { var mostPopularRoom = roomCounts.First().Key; Console.WriteLine($"The most popular room: {mostPopularRoom}"); return mostPopularRoom; } else { Console.WriteLine("No rooms have been booked yet."); return 0; } } } }
import express from "express"; import cors from "cors"; import morgan from "morgan"; import dotenv from "dotenv"; import http from "http"; import { Server } from "socket.io"; import dbPool from "./config/dbConnect.js"; import errorHandler from "./middlewares/errorHandler.js"; import parkingLotRoutes from "./routes/parkingLotRoutes.js"; dotenv.config(); const app = express(), port = process.env.PORT || 5000, server = http.createServer(app), io = new Server(server, { cors: { origin: "*" } }); app.use(cors({ origin: "*" })); app.use(express.json()); app.use(morgan("dev")); app.use("/parking-lot", parkingLotRoutes); app.all("*", (request, response) => { response.status(404).json({ success: false, error: { code: 404, message: "Resource you have requested doesn't exist." } }); }); app.use(errorHandler); dbPool.getConnection((error, connection) => { if (error) console.log("Failed to connect with MySQL database."); else { console.log("MySQL database is connected."); connection.release(); } }); io.on("connect", (socket) => { socket.on("parking-status", async (details) => { console.log(details); try { const { parkingLotId, isOccupied } = JSON.parse(details), connection = await dbPool.getConnection(); await connection.query(`UPDATE ParkingLot SET isOccupied = ${isOccupied} WHERE parkingLotId = "${parkingLotId}"`); connection.release(); io.emit("display-status", { parkingLotId, isOccupied }); } catch (error) { console.log(error); } }); }); server.listen(port, (error) => { if (error) console.log("Failed to start the server."); else console.log(`Server is running on port ${port}.`); }); process.on("SIGINT", () => { dbPool.end((error) => { if (error) { console.error("Error closing MySQL connection pool."); } else { console.log("MySQL connection pool closed."); process.exit(0); } }); });
# Adapted from Rachel Tatman's example # https://www.kaggle.com/code/rtatman/time-aligned-spectrograms-with-chat-files-in-r/notebook # load in libraries we'll use library(stringr) # string manipulation library(tidyverse) # keepin' it tidy # read in a CHAT transcript transcript <- paste(readLines("326.cha")) # \025 is the non-printing character surrounding the time stamps at the end of each line # we can use regex & this character to get a list of time spans & their transcriptions # That's decimal 21, octal 25 (NAK or ctl-U). # create an empty tibble timestamps <- tibble(talker = character(), speech = character(), start = integer(), end = integer()) # if a line has two of the non-breaking characters in it, grab the text & time stamps # for the beginning & end of the text for(i in 1:length(transcript)){ if(grepl("\025.*\025", transcript[i])){ extract <- str_match(transcript[i], "\\*(.*?):(.*?)\025(.*?)_(.*?)\025") timestamps <- add_row(timestamps, talker = extract[2], speech = extract[3], start = as.numeric(extract[4]), end = as.numeric(extract[5])) } } # These next steps are optional but will make our final output a little # bit easier to read. Skip them for close phoneitc analysis. # remove rows with NA's # timestamps <- timestamps[complete.cases(timestamps),] # remove annotations # timestamps$speech <- str_replace_all(timestamps$speech, "&=[a-z]+", "") # get rid of punctuation (except for apostrophes) # timestamps$speech <- str_replace_all(timestamps$speech, "[^[:alpha:]' ]", "") # check out our file to make sure it looks ok # head(timestamps)
#! /usr/bin/env python # coding=utf-8 # Copyright (c) 2019 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from typing import Dict import random import numpy as np import torch from ludwig.constants import * from ludwig.decoders.generic_decoders import Regressor from ludwig.encoders.generic_encoders import PassthroughEncoder, DenseEncoder from ludwig.features.base_feature import InputFeature from ludwig.features.base_feature import OutputFeature from ludwig.modules.loss_modules import MSELoss, MAELoss, RMSELoss, RMSPELoss, get_loss_cls from ludwig.modules.metric_modules import ( MAEMetric, MSEMetric, RMSEMetric, RMSPEMetric, R2Score, ) from ludwig.utils import output_feature_utils from ludwig.utils.misc_utils import set_default_value from ludwig.utils.misc_utils import set_default_values from ludwig.utils.misc_utils import get_from_registry logger = logging.getLogger(__name__) class ZScoreTransformer: def __init__(self, mean: float = None, std: float = None, **kwargs: dict): self.mu = mean self.sigma = std def transform(self, x: np.ndarray) -> np.ndarray: return (x - self.mu) / self.sigma def inverse_transform(self, x: np.ndarray) -> np.ndarray: return x * self.sigma + self.mu @staticmethod def fit_transform_params(column: np.ndarray, backend: "Backend") -> dict: compute = backend.df_engine.compute return { "mean": compute(column.astype(np.float32).mean()), "std": compute(column.astype(np.float32).std()), } class MinMaxTransformer: def __init__(self, min: float = None, max: float = None, **kwargs: dict): self.min_value = min self.max_value = max self.range = None if min is None or max is None else max - min def transform(self, x: np.ndarray) -> np.ndarray: return (x - self.min_value) / self.range def inverse_transform(self, x: np.ndarray) -> np.ndarray: if self.range is None: raise ValueError( "Numeric transformer needs to be instantiated with " "min and max values." ) return x * self.range + self.min_value @staticmethod def fit_transform_params(column: np.ndarray, backend: "Backend") -> dict: compute = backend.df_engine.compute return { "min": compute(column.astype(np.float32).min()), "max": compute(column.astype(np.float32).max()), } class Log1pTransformer: def __init__(self, **kwargs: dict): pass def transform(self, x: np.ndarray) -> np.ndarray: if np.any(x <= 0): raise ValueError( "One or more values are non-positive. " "log1p normalization is defined only for positive values." ) return np.log1p(x) def inverse_transform(self, x: np.ndarray) -> np.ndarray: return np.expm1(x) @staticmethod def fit_transform_params(column: np.ndarray, backend: "Backend") -> dict: return {} class IdentityTransformer: def __init__(self, **kwargs): pass def transform(self, x: np.ndarray) -> np.ndarray: return x def inverse_transform(self, x: np.ndarray) -> np.ndarray: return x @staticmethod def fit_transform_params(column: np.ndarray, backend: "Backend") -> dict: return {} numeric_transformation_registry = { "minmax": MinMaxTransformer, "zscore": ZScoreTransformer, "log1p": Log1pTransformer, None: IdentityTransformer, } class NumericalFeatureMixin: type = NUMERICAL preprocessing_defaults = { "missing_value_strategy": FILL_WITH_CONST, "fill_value": 0, "normalization": None, } preprocessing_schema = { "missing_value_strategy": { "type": "string", "enum": MISSING_VALUE_STRATEGY_OPTIONS, }, "fill_value": {"type": "number"}, "computed_fill_value": {"type": "number"}, "normalization": { "type": ["string", "null"], "enum": list(numeric_transformation_registry.keys()), }, } @staticmethod def cast_column(column, backend): return backend.df_engine.df_lib.to_numeric( column, errors="coerce" ).astype(np.float32) @staticmethod def get_feature_meta(column, preprocessing_parameters, backend): numeric_transformer = get_from_registry( preprocessing_parameters.get("normalization", None), numeric_transformation_registry, ) return numeric_transformer.fit_transform_params(column, backend) @staticmethod def add_feature_data( feature, input_df, proc_df, metadata, preprocessing_parameters, backend, skip_save_processed_input, ): proc_df[feature[PROC_COLUMN]] = ( input_df[feature[COLUMN]].astype(np.float32).values ) # normalize data as required numeric_transformer = get_from_registry( preprocessing_parameters.get("normalization", None), numeric_transformation_registry, )(**metadata[feature[NAME]]) proc_df[feature[PROC_COLUMN]] = numeric_transformer.transform( proc_df[feature[PROC_COLUMN]] ) return proc_df class NumericalInputFeature(NumericalFeatureMixin, InputFeature): encoder = "passthrough" def __init__(self, feature, encoder_obj=None): # Required for certain encoders, maybe pass into initialize_encoder super().__init__(feature) self.overwrite_defaults(feature) feature['input_size'] = self.input_shape[-1] if encoder_obj: self.encoder_obj = encoder_obj else: self.encoder_obj = self.initialize_encoder(feature) def forward(self, inputs): assert isinstance(inputs, torch.Tensor) assert inputs.dtype == torch.float32 or inputs.dtype == torch.float64 assert len(inputs.shape) == 1 or ( len(inputs.shape) == 2 and inputs.shape[1] == 1) if len(inputs.shape) == 1: inputs = inputs[:, None] inputs_encoded = self.encoder_obj(inputs) return inputs_encoded def create_sample_input(self): # Used by get_model_inputs(), which is used for tracing-based torchscript generation. return torch.Tensor([random.randint(1, 100), random.randint(1, 100)]) @property def input_shape(self) -> torch.Size: return torch.Size([1]) @property def output_shape(self) -> torch.Size: return torch.Size(self.encoder_obj.output_shape) @staticmethod def update_config_with_metadata( input_feature, feature_metadata, *args, **kwargs ): pass @staticmethod def populate_defaults(input_feature): set_default_value(input_feature, TIED, None) encoder_registry = { "dense": DenseEncoder, "passthrough": PassthroughEncoder, "null": PassthroughEncoder, "none": PassthroughEncoder, "None": PassthroughEncoder, None: PassthroughEncoder, } class NumericalOutputFeature(NumericalFeatureMixin, OutputFeature): decoder = "regressor" loss = {TYPE: MEAN_SQUARED_ERROR} metric_functions = { LOSS: None, MEAN_SQUARED_ERROR: None, MEAN_ABSOLUTE_ERROR: None, ROOT_MEAN_SQUARED_ERROR: None, ROOT_MEAN_SQUARED_PERCENTAGE_ERROR: None, R2: None, } default_validation_metric = MEAN_SQUARED_ERROR clip = None def __init__(self, feature): super().__init__(feature) self.overwrite_defaults(feature) feature['input_size'] = self.input_shape[-1] self.decoder_obj = self.initialize_decoder(feature) self._setup_loss() self._setup_metrics() def logits(self, inputs, **kwargs): # hidden hidden = inputs[HIDDEN] return self.decoder_obj(hidden) def predictions(self, inputs: Dict[str, torch.Tensor], feature_name: str, **kwargs): logits = output_feature_utils.get_output_feature_tensor( inputs, feature_name, LOGITS) predictions = logits if self.clip is not None: if isinstance(self.clip, (list, tuple)) and len(self.clip) == 2: predictions = torch.clamp( logits, self.clip[0], self.clip[1] ) logger.debug( ' clipped_predictions: {0}'.format(predictions) ) else: raise ValueError( "The clip parameter of {} is {}. " "It must be a list or a tuple of length 2.".format( self.feature_name, self.clip ) ) return {PREDICTIONS: predictions, LOGITS: logits} def _setup_loss(self): loss_cls = get_loss_cls(NUMERICAL, self.loss[TYPE]) self.train_loss_function = loss_cls(**self.loss) self.eval_loss_function = self.train_loss_function def _setup_metrics(self): self.metric_functions = {} # needed to shadow class variable self.metric_functions[MEAN_SQUARED_ERROR] = MSEMetric() self.metric_functions[MEAN_ABSOLUTE_ERROR] = MAEMetric() self.metric_functions[ROOT_MEAN_SQUARED_ERROR] = RMSEMetric() self.metric_functions[ROOT_MEAN_SQUARED_PERCENTAGE_ERROR] = RMSPEMetric( ) self.metric_functions[R2] = R2Score() def get_prediction_set(self): return {PREDICTIONS, LOGITS} @property def input_shape(self) -> torch.Size: return torch.Size([self.input_size]) @classmethod def get_output_dtype(cls): return torch.float32 @property def output_shape(self) -> torch.Size: return torch.Size([1]) @staticmethod def update_config_with_metadata( output_feature, feature_metadata, *args, **kwargs ): pass @staticmethod def calculate_overall_stats(predictions, targets, metadata): # no overall stats, just return empty dictionary return {} def postprocess_predictions( self, predictions, metadata, output_directory, backend, ): predictions_col = f"{self.feature_name}_{PREDICTIONS}" if predictions_col in predictions: # as needed convert predictions make to original value space numeric_transformer = get_from_registry( metadata["preprocessing"].get("normalization", None), numeric_transformation_registry, )(**metadata) predictions[predictions_col] = backend.df_engine.map_objects( predictions[predictions_col], lambda pred: numeric_transformer.inverse_transform(pred), ) return predictions @staticmethod def populate_defaults(output_feature): set_default_value( output_feature, LOSS, {TYPE: "mean_squared_error", "weight": 1} ) set_default_value(output_feature[LOSS], TYPE, "mean_squared_error") set_default_value(output_feature[LOSS], "weight", 1) set_default_values( output_feature, { "clip": None, "dependencies": [], "reduce_input": SUM, "reduce_dependencies": SUM, }, ) decoder_registry = { "regressor": Regressor, "null": Regressor, "none": Regressor, "None": Regressor, None: Regressor, }
import type { NextPage, GetStaticProps } from "next" import Head from "next/head" import styles from "../styles/Home.module.css" import PostCard from "../components/PostCard" import Nav from "../components/Nav" import { openAllMd, Post } from "../lib"; interface HomeProps { posts: Post[] } const Home: NextPage<HomeProps> = (props) => { const { posts } = props const postGrid = posts.map(post => <PostCard key={post.slug} {...post}></PostCard>) return ( <div className={styles.container}> <Nav /> <Head> <title>izzymg.devblog</title> <meta name="description" content="Izzy MG's writings" /> <link rel="icon" href="/favicon.ico" /> </Head> <main className={styles.main}> <h1 className={styles.title}> Izzy MG&lsquo;s writings </h1> <p className={styles.description}> Here&lsquo;s where I work with Next.JS and sometimes write stuff. Check out my <a href="https://izzymg.dev">portfolio</a>! </p> <section className={styles.postGrid}> {postGrid} </section> </main> </div> ) } export const getStaticProps: GetStaticProps = async ctx => { const posts = await openAllMd() // reverse to display homepage posts newest -> oldest return { props: { posts: posts.reverse() }, } } export default Home
import { useEffect, useState } from 'react'; import css from './favorite.module.css'; import CarsList from 'components/CarsList/CarsList'; import { GetLikedCarsData } from 'components/service/GetCarById'; import Loader from 'components/Loader/Loader'; const Favorite = () => { const [likedData, setLikedData] = useState([]); const [isLoading, setIsLoading] = useState(false); const [isFirstRender, setIsFirstRender] = useState(true); const handleCarUnLiked = carId => { const updatedLikedData = likedData.filter(car => car.id !== carId); setLikedData(updatedLikedData); }; useEffect(() => { if (isFirstRender) { setIsFirstRender(false); return; } setIsLoading(true); const fetchData = async () => { try { const data = await GetLikedCarsData(); setLikedData(data); } catch (error) { console.error('Error fetching liked cars:', error); } finally { setIsLoading(false); } }; fetchData(); }, [isFirstRender]); return ( <> <div className={css.favoriteContainer}> <p className={css.favoriteTitle}>FAVORITE</p> {likedData.length > 0 ? ( <CarsList data={likedData} onCarUnLiked={handleCarUnLiked} /> ) : ( <p>No liked cars</p> )} </div> {isLoading && <Loader />} </> ); }; export default Favorite;
import { Address, BigInt } from "@graphprotocol/graph-ts" import { Vault, Deposit as DepositEvent, Withdraw as WithdrawalEvent } from "../generated/Vault/Vault" import { Position, AspanTransaction } from "../generated/schema" export function handleDeposit(event: DepositEvent): void { const posId = event.params.user let position = Position.load(posId) if (!position) { position = new Position(posId) position.userAddress = event.params.user position.usdcWithdrawn = new BigInt(0) position.aspanBalance = new BigInt(0) position.usdcProvided = new BigInt(0) position.active = true } position.aspanBalance = position.aspanBalance.plus(event.params.aspanMinted) position.usdcProvided = position.usdcProvided.plus(event.params.usdcDeposited) position.save() const aspanTxId = getIdFromEventParams( event.params.user, event.block.timestamp, event.transaction.nonce ) let aspanTransaction = new AspanTransaction(aspanTxId) aspanTransaction.type = "Deposit" aspanTransaction.userAddress = event.params.user aspanTransaction.usdcChange = event.params.usdcDeposited aspanTransaction.tokensChange = event.params.aspanMinted aspanTransaction.timestamp = event.block.timestamp aspanTransaction.position = posId aspanTransaction.save() } export function handleWithdrawal(event: WithdrawalEvent): void { const posId = event.params.user let position = Position.load(posId) position!.usdcWithdrawn = position!.usdcWithdrawn.plus(event.params.usdcWithdrawn) position!.aspanBalance = position!.aspanBalance.minus(event.params.aspanBurnt) if (position!.aspanBalance.isZero()) position!.active = false position!.save() const aspanTxId = getIdFromEventParams( event.params.user, event.block.timestamp, event.transaction.nonce ) let aspanTransaction = new AspanTransaction(aspanTxId) aspanTransaction.type = "Withdrawal" aspanTransaction.userAddress = event.params.user aspanTransaction.usdcChange = event.params.usdcWithdrawn aspanTransaction.tokensChange = event.params.aspanBurnt aspanTransaction.timestamp = event.block.timestamp aspanTransaction.position = posId aspanTransaction.save() } function getIdFromEventParams(addr: Address, timestamp: BigInt, nonce: BigInt): string { return addr.toHexString() + timestamp.toHexString() + nonce.toHexString() }
from flask import Flask, jsonify, request from flask_cors import CORS import pandas as pd import numpy as np from sqlalchemy import create_engine from statsmodels.tsa.statespace.sarimax import SARIMAX app = Flask(__name__) CORS(app) # 모든 도메인에서의 요청을 허용 # 데이터베이스 연결 함수 def get_engine(): return create_engine('oracle+cx_oracle://?:[email protected]:1521/xe') # 단지 코드 기반 모델 생성 및 평가 함수 def create_and_evaluate_model(complexcode): query = f""" SELECT ENER_DT, SUM(ELEC_USAGE) as ELEC_USAGE FROM TMP2 WHERE complexcode = '{complexcode}' AND TO_NUMBER(TO_CHAR(TO_DATE(ENER_DT, 'YYYYMM'), 'YYYYMM')) BETWEEN 201401 AND 202312 GROUP BY ENER_DT ORDER BY ENER_DT """ household_query = f""" SELECT SUM(SIZE_HOUSEHOLDSNO) AS TOTAL_HOUSEHOLDS FROM APT_SIZE WHERE APART_COMPLEXCODE = '{complexcode}' """ # 데이터베이스 연결 및 데이터 로드 engine = get_engine() df = pd.read_sql(query, con=engine) # 데이터 전처리 df['ener_dt'] = pd.to_datetime(df['ener_dt'], format='%Y%m') df.set_index('ener_dt', inplace=True) df = df.asfreq('MS') # 결측값 확인 및 처리 df['elec_usage'] = df['elec_usage'].ffill() # 결측값을 전방 채움 방식으로 처리 # 훈련 및 테스트 데이터 분할 train_df = df[df.index.year <= 2023] test_df = pd.date_range(start='2024-01-01', end='2024-12-01', freq='MS') # 외생 변수 준비 exog_train = pd.DataFrame({ 'year': train_df.index.year, 'month': train_df.index.month }, index=train_df.index) exog_test = pd.DataFrame({ 'year': test_df.year, 'month': test_df.month }, index=test_df) # SARIMAX 모델 적합 order = (1, 1, 1) seasonal_order = (1, 1, 1, 12) model = SARIMAX(train_df['elec_usage'], order=order, seasonal_order=seasonal_order, exog=exog_train) model_fit = model.fit(disp=False) # 예측 수행 forecast_steps = len(test_df) forecast = model_fit.get_forecast(steps=forecast_steps, exog=exog_test) forecast_values = forecast.predicted_mean # 예측값을 반올림하여 정수로 변환 forecast_values_only = np.round(forecast_values.values).astype(int) # 총 가구수 계산 household_df = pd.read_sql(household_query, con=engine) print(household_df) # 가구 수 데이터 프레임 출력 total_households = int(household_df['total_households'].iloc[0]) # 예측값을 총 가구수로 나누고 정수로 반올림하여 반환 forecast_values_per_household = np.round(forecast_values_only / total_households).astype(int) forecast_df = pd.DataFrame(forecast_values_per_household, index=test_df, columns=['Forecast']) # 요금 조회 및 추가 forecast_with_bill = [] for date, value in forecast_df['Forecast'].items(): month = date.month if month in [7, 8]: bill_query = f""" SELECT TOTAL_BILL_AMOUNT FROM ELEC_SUMMER WHERE ELEC_USEAGE = {value} """ else: bill_query = f""" SELECT TOTAL_BILL_AMOUNT FROM ELEC_OTHER WHERE ELEC_USEAGE = {value} """ bill_df = pd.read_sql(bill_query, con=engine) if not bill_df.empty: total_bill_amount = int(bill_df['total_bill_amount'].iloc[0]) else: total_bill_amount = None forecast_with_bill.append({ 'date': date.strftime('%Y-%m-%d'), 'forecast': int(value), 'total_bill_amount': total_bill_amount }) # 결과 반환 return forecast_with_bill # JSON 데이터 반환을 위한 Flask 엔드포인트 @app.route('/codeForecast', methods=['POST']) def get_forecast(): data = request.get_json() complexcode = data.get('complexcode') # 'complexcode' 값이 없으면 None이 반환됨 results = create_and_evaluate_model(complexcode) return jsonify(results) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True, port=5556)
# MITK ROI {#MITKROIPage} [TOC] ## Disclaimer Until the MITK ROI file format is going to be officially announced in a 2024 release of MITK, the file format must be considered experimental and is prone to change without any prior warning. ## Overview MITK ROI is a JSON-based file format defining a collection of region of interests (ROIs). ROIs must have an ID (unsigned integer) and their shape is currently considered to be an axis-aligned bounding box. Its bounds are defined by minimum and maximum index coordinates, typically relative to an image. Custom properties of various known types can be optionally attached to a ROI. A few of these properties are used by MITK to define the appearance of a rendered ROI, for example: - "color" (mitk::ColorProperty): Color/RGB triplet of the rendered ROI (default: white \[1.0, 1.0, 1.0\]) - "opacity" (mitk::FloatProperty): Opacity of the rendered ROI (default: 100% \[1.0\]) - "lineWidth" (mitk::FloatProperty): Line width of the egdes of the rendered ROI (default: 1px \[1.0\]) ROIs can be optionally time-resolved and define both coordinates and properties per time step, allowing for a dynamic appearance, position, and size over time. ROIs also display a caption at their bottom-left corner (supporting multiple lines), that can be set once per MITK ROI file for all contained ROIs. Placeholders enclosed by braces in the caption are substituted by their corresponding ROI property values at runtime. The default caption is "{name} ({ID})", where ``{ID}`` is a special placeholder for the ID of a ROI (technically not a ROI property), and ``{name}`` refers to the ROI property "name" (typically an mitk::StringProperty). Last but not least the reference (image) geometry of the ROIs in an MITK ROI file must be specified to be able to map all index coordinates to actual world coordinates. A geometry is defined by an origin, the pixel/voxel spacing, a size, and optionally the number of time steps in case of a time-resolved MITK ROI file. ## File format As all features are explained in the overview above, the JSON-based file format is defined here by two examples with minimal additional notes: one example for a static MITK ROI file and one example for a time-resolved MITK ROI file. ### Static MITK ROI file This example contains two ROIs for detected tumors in an image with certain confidence. Names and confidence values will be displayed in separate lines for each ROI. ~~~{.json} { "FileFormat": "MITK ROI", "Version": 1, "Name": "Static example", "Caption": "{name}\nConfidence: {confidence}", "Geometry": { "Origin": [0, 0, 0], "Spacing": [1, 1, 3], "Size": [256, 256, 49] }, "ROIs": [ { "ID": 0, "Min": [4, 4, 1], "Max": [124, 124, 31], "Properties": { "StringProperty": { "name": "tumor", "comment": "Detected a tumor with 95% confidence.", "note": "Properties are grouped by their type to reduce verbosity." }, "ColorProperty": { "color": [0, 1, 0] }, "FloatProperty": { "confidence": 0.95 } } }, { "ID": 1, "Min": [132, 4, 1], "Max": [252, 60, 15], "Properties": { "StringProperty": { "name": "Another tumor", "comment": "Maybe another tumor (confidence only 25%)." }, "ColorProperty": { "color": [1, 0, 0] }, "FloatProperty": { "confidence": 0.25 } } } ] } ~~~ Further hints: - "FileFormat" ("MITK ROI"), "Version" (1), and "Geometry" are mandatory. - "Name" is optional. If not set, the file name is used by MITK instead. - ROIs are defined by JSON objects in the "ROIs" JSON array. - See the derived classes of mitk::BaseProperty for an overview of known property types. ### Time-resolved MITK ROI file This example only contains a single ROI but it is defined for several time steps. Fallbacks of time step properties to default properties are demonstrated as well. ~~~{.json} { "FileFormat": "MITK ROI", "Version": 1, "Name": "Time-resolved example", "Geometry": { "Origin": [0, 0, 0], "Spacing": [1, 1, 3], "Size": [256, 256, 49], "TimeSteps": 3 }, "ROIs": [ { "ID": 0, "Properties": { "ColorProperty": { "color": [1, 0, 0] }, "StringProperty": { "name": "Color-changing ROI" } }, "TimeSteps": [ { "t": 0, "Min": [4, 4, 1], "Max": [124, 124, 31] }, { "t": 2, "Min": [14, 14, 11], "Max": [121, 121, 28], "Properties": { "ColorProperty": { "color": [0, 1, 0] } } } ] } ] } ~~~ Further hints: - The geometry defines 3 time steps. - The "Properties" directly in the ROI function as fallbacks, if they are not defined for a certain time step. - Time time step indices "t" are mandatory. The ROI is only present at time steps 0 and 2. - The ROI is red (fallback) at time step 0 and green at time step 2. - Its extents are larger at time step 0 than at time step 2.
.cuadrado-1{ background-color: rgb(255, 0, 132); /* width: 200px; height: 200px; */ /* Estas dimensiones son valores fijos y se aplican por dafault en el contenido. Esta implicitamente por default, la sig declaracion: box-sizing: content-box; Y esta se aplica para todo tag HTML*/ /* width: 20%; height: 80%; *//* Valores variables, que se van adaptando al ancho de la pagina/pantalla. Ya que son unidades relativas*/ width: 20%; height: 20%; padding: 10px; /* box-sizing: border-box; *//* Esta prop hace que se respete el ancho (width) y alto (height) total de la caja y no del contenido*/ } .cuadrado-2{ background-color: rgb(86, 189, 230); width: 20%; height: 20%; padding: 10px; /* Agrega padding en los 4 lados */ /* padding-top: 30px; */ /* Agrega padding solamente arriba */ /* padding: 30px 15px 50px 20px; */ /* Agrega padding como las agujas de reloj: arriba, derechoa, abajo e izquierda */ } html { box-sizing: border-box; } /*Para todo elemento del documento, y para todo pseudoelemento antes y despues... Aplica tal cosa*/ *, *:before, *:after { box-sizing: inherit; } /* p::before { content: 'Ezequiel'; } */ .parrafo { color: white; background-color: blue; /* display: block; */ /* display: inline; */ /* display: inline-block; */ }
def largest_palindromic_number(S): # Step 1: Count occurrences of each digit digit_counts = [0] * 10 for digit in S: digit_counts[int(digit)] += 1 # Step 2: Construct the largest palindromic number largest_palindrome = "" for i in range(9, -1, -1): # Start from 9 and move downwards largest_palindrome += str(i) * digit_counts[i] # Step 3: Ensure no leading zeros largest_palindrome = largest_palindrome.lstrip("0") # Step 4: Return the largest palindromic number return largest_palindrome if largest_palindrome else "0" # Example usage: S = "8199" result = largest_palindromic_number(S) print("Largest palindromic number:", result)
import * as yup from 'yup' export const addCompanySchema = yup.object().shape({ address: yup .string() .required({ name: 'address', text: 'Поле "Адрес" обязательно для заполнения', }) .min(2, { name: 'address', text: 'Длина поля "Адрес" не менее 2 символов', }) .trim(), name: yup .string() .required({ name: 'name', text: 'Поле "Наименование" обязательно для заполнения', }) .min(2, { name: 'name', text: 'Длина поля "Наименование" не менее 2 символов', }) .trim(), }) export const addEmployeeSchema = yup.object().shape({ position: yup .string() .required({ name: 'position', text: 'Поле "Должность" обязательно для заполнения', }) .min(2, { name: 'position', text: 'Длина поля "Должность" не менее 2 символов', }) .trim(), lastName: yup .string() .required({ name: 'lastName', text: 'Поле "Фамилия" обязательно для заполнения', }) .min(2, { name: 'lastName', text: 'Длина поля "Фамилия" не менее 2 символов', }) .trim(), firstName: yup .string() .required({ name: 'firstName', text: 'Поле "Имя" обязательно для заполнения', }) .min(2, { name: 'firstName', text: 'Длина поля "Имя" не менее 2 символов', }) .trim(), }) export const searchCompanySchema = yup.object().shape({ value: yup .string() .required({ name: 'value', text: 'Поле "Поиск" обязательно для заполнения', }) .trim(), })
function mergeAndDownload() { var file1 = document.getElementById('file1').files[0]; var file2 = document.getElementById('file2').files[0]; if (file1 && file2) { Papa.parse(file1, { complete: function(result1) { Papa.parse(file2, { complete: function(result2) { var keyColumnName1 = findKeyColumnName(result1.data[0]); var keyColumnName2 = findKeyColumnName(result2.data[0]); if (keyColumnName1 && keyColumnName2) { var mergedData = mergeData(result1.data, result2.data, keyColumnName1, keyColumnName2); // Remove columns with no data mergedData = removeEmptyColumns(mergedData); // Add column names mergedData = addColumnNames(mergedData); var csvData = Papa.unparse(mergedData); var blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' }); // Trigger download var a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "merged.csv"; a.style.display = "none"; document.body.appendChild(a); a.click(); document.body.removeChild(a); } else { alert('Could not find the key column in one or both sheets.'); } } }); } }); } else { alert('Please upload both files.'); } } function findKeyColumnName(row) { var possibleKeyColumnNames = ['Student SIS ID', 'SIS User ID']; for (var i = 0; i < possibleKeyColumnNames.length; i++) { var index = row.indexOf(possibleKeyColumnNames[i]); if (index !== -1) { return index; } } return null; } function mergeData(data1, data2, keyIndex1, keyIndex2) { var mergedData = []; // Select only the desired columns var selectedColumns = ['Student name', 'SIS Login ID', 'Email']; // Find the indices of the selected columns in both datasets var indices1 = []; var indices2 = []; for (var i = 0; i < selectedColumns.length; i++) { indices1.push(data1[0].indexOf(selectedColumns[i])); indices2.push(data2[0].indexOf(selectedColumns[i])); } // Iterate through the rows of both datasets for (var i = 1; i < data1.length; i++) { var key1 = data1[i][keyIndex1]; for (var j = 1; j < data2.length; j++) { var key2 = data2[j][keyIndex2]; if (key1 === key2) { var row = []; for (var k = 0; k < selectedColumns.length; k++) { row.push(data1[i][indices1[k]]); row.push(data2[j][indices2[k]]); } mergedData.push(row); } } } return mergedData; } function removeEmptyColumns(data) { var nonEmptyColumns = []; // Iterate through the columns for (var i = 0; i < data[0].length; i++) { var hasData = false; // Check if any row in the column has data for (var j = 1; j < data.length; j++) { if (data[j][i]) { hasData = true; break; } } if (hasData) { nonEmptyColumns.push(i); } } // Create a new dataset with non-empty columns var newData = data.map(function(row) { return row.filter(function(_, index) { return nonEmptyColumns.includes(index); }); }); return newData; } function addColumnNames(data) { var columnNames = ['Student name', 'Student ID', 'Email']; // Insert the column names at the beginning of the dataset data.unshift(columnNames); return data; }
import React, { useState, useEffect } from "react"; import styled from 'styled-components'; import { createGlobalStyle } from 'styled-components'; // Style styled-components const GlobalStyle = createGlobalStyle` * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: sans-serif; } `; const WrapperImages = styled.section` max-width: 70rem; margin: 4rem auto; display: grid; grid-gap: 1em; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); grid-auto-rows: 300px; `; const Img = styled.img` width: 100%; height: 100%; object-fit: cover; `; const Search = styled.div` display: flex; justify-content: center; ` const SearchImg = () => { const [img, setImg] = useState(""); const [res, setRes] = useState([]); /// fetch запрос const fetchRequest = async () => { const AccessKey = 'z4UC9SyAL8_PdvMWlhcTxbW5pycwUGOtE7qPTClEj9U'; const data = await fetch( `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${AccessKey}&per_page=12` ); const dataJ = await data.json(); const result = dataJ.results; console.log(result); setRes(result); }; useEffect(() => { // fetch функция в useEffect fetchRequest(); }, []); //button Submit const Submit = () => { fetchRequest(); setImg(""); }; return ( <> <GlobalStyle /> <div className="container-fluid"> <div className="row"> <Search> <input type="text" placeholder="Search Anything..." value={img} onChange={(e) => setImg(e.target.value)} /> <button type="submit" onClick={Submit} > Search </button> </Search> <WrapperImages> {res.map((val) => { return ( <> <Img key={val.id} src={val.urls.thumb} alt="val.alt_description" /> </> ); })} </WrapperImages> </div> </div> </> ); }; export default SearchImg;
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AdminController; use App\Http\Controllers\AuthController; use App\Http\Controllers\SupporterController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "web" middleware group. Make something great! | */ Route::get('/', [AuthController::class, 'login']); // داشبورد Route::post('/login', [AuthController::class, 'AuthLogin']); // لاگین Route::get('/logout', [AuthController::class, 'logout']); // لاگ اوت کردن ادمن Route::group(['middleware' => 'admin'], function(){ Route::prefix('Admin')->group(function () { Route::get('/dashboard', [AdminController::class, 'Dashboard']); // داشبورد Route::get('/SupporterForm', [AdminController::class, 'SupporterForm']); // فرم ثبت پشتیبان Route::post('/AddSupporter', [AdminController::class, 'AddSupporter']); // ثبت پشتیبان Route::get('/supportertable', [AdminController::class, 'supportertable']); // جدول پشتیبان ها Route::get('/shoptable', [AdminController::class, 'shoptable']); // جدول فروشگاه ها Route::post('/updateSupporter', [AdminController::class, 'updateSupporter']); // آپدیت پشتیبان Route::post('/updateShop', [AdminController::class, 'updateShop']); // آپدیت فروشگاه ها Route::get('/CustomerTable', [AdminController::class, 'CustomerTable']); // آپدیت فروشگاه ها Route::get('/ReportTable', [AdminController::class, 'ReportTable']); // آپدیت فروشگاه ها }); ;} ); Route::group(['middleware' => 'supporter'], function () { Route::prefix('Supporter')->group(function () { Route::get('/dashboard', [SupporterController::class, 'Dashboard']); // داشبورد Route::get('/shopForm', [SupporterController::class, 'shopForm']); // فرم فروشگاه ها Route::post('/shopAdd', [SupporterController::class, 'shopAdd']); // ثبت فروشگاه ها Route::get('/shoptable', [SupporterController::class, 'shoptable']); // جدول فروشگاه ها Route::get('/customerForm', [SupporterController::class, 'customerForm']); // فرم ثبت مشتری Route::post('/customerAdd', [SupporterController::class, 'customerAdd']); // ثبت مشتری Route::get('/customerTable', [SupporterController::class, 'customerTable']); // جدول مشتری Route::post('/shopedit', [SupporterController::class, 'shopedit']); // ادیت فروشگاه Route::post('/customeredit', [SupporterController::class, 'customeredit']); // ادیت فروشگاه Route::get('/reportForm', [SupporterController::class, 'reportForm']); // فرم ثبت گزارش Route::post('/Addreport', [SupporterController::class, 'Addreport']); // فرم ثبت گزارش }); ;} );
import * as React from "react"; import parse from "html-react-parser"; export interface MeterProps { className?: string value: number sections?: number colorStart?: number colorShift?: number numColors?: number saturation?: number luminosity?: number } const existsAndInRange = (value: number | undefined, min: number, max: number) => { if (value == null) { return false } return ((value! >= min) && (value! <= max)) } export const ReactMeter: React.FC<MeterProps> = (props) => { const className = (props.className && typeof(props.className) === "string") ? props.className : "react-meter" const cx = "50%" const cy = "95%" const baseValue = props.value const sections = existsAndInRange(props.sections, 1, 6) ? props.sections! : 3 const numBreakpoints = sections - 1 const colorStart = existsAndInRange(props.colorStart, 0, 360) ? props.colorStart! : 120 const colorShift = existsAndInRange(props.colorShift, 0, 359) ? props.colorShift! : 60 const numColors = existsAndInRange(props.numColors, 0, sections) ? props.numColors! : sections const luminosity = existsAndInRange(props.luminosity, 0, 100) ? props.luminosity : 50 const saturation = existsAndInRange(props.luminosity, 0, 100) ? props.saturation : 100 const meters: (number[] | never[]) = [] const display: (boolean[] | never[]) = [] const breakpoints = [numBreakpoints] let gaugeSVG: string = '' for (let i = 0; i < sections; i++) { breakpoints[i] = ((i + 1) / (sections)); if (i === 0) { meters[i] = (baseValue > breakpoints[0] ? 1 : (baseValue / breakpoints[0])) display[i] = meters[i] > 0 && baseValue > 0 } gaugeSVG += `<circle id=meter-${i} cx=${cx} cy=${cy} r="114.6"></circle>` + `<circle id='meter-${i} meter-fg-${i}' cx=${cx} cy=${cy} r="114.6"></circle>` meters[i + 1] = (baseValue - breakpoints[i] < 0 ? 0 : Math.min((baseValue - breakpoints[i]) / breakpoints[0], 1)) display[i + 1] = meters[i + 1] > 0 && baseValue > 0 } React.useEffect(() => { for (let i = 0; i < Object.keys(meters).length; i++) { const lineWidth = 10 const background = document.getElementById(`meter-${i}`) const overlay = document.getElementById(`meter-${i} meter-fg-${i}`) const meterEval = meters[i] const sectionSize = 360 / (sections) const backStroke = sectionSize - lineWidth + sections / (lineWidth * 2) // the addon is for some fractional losses on higher numbers of sections const offset = 360 - (backStroke + lineWidth) * i - (lineWidth / 2) const overlayStroke = backStroke * meterEval const overLayGap = (720 - overlayStroke) const backGap = (720 - backStroke) background?.setAttribute( "style", `stroke-dasharray: ${backStroke.toFixed(0)}, ${backGap.toFixed(0)}; stroke-dashoffset: ${(offset).toFixed(0)}; stroke: hsl(${colorStart - (i % numColors) * colorShift}, 70%, 25%); width: 100%; height: 100%; fill: none; stroke-width: 10; stroke-linecap: round;` ) if (display[i] && overlay && Object.keys(meters).length > 0) { overlay.setAttribute( "style", `stroke-dasharray: ${overlayStroke.toFixed(0)}, ${overLayGap.toFixed(0)}; stroke-dashoffset: ${offset.toFixed(0)}; stroke: hsl(${colorStart - (i % numColors) * colorShift}, ${saturation}%, ${luminosity}%); width: 100%; height: 100%; fill: none; stroke-width: 10; stroke-linecap: round;` ) } else if (overlay) { overlay.setAttribute("style", "display: none") } } }); return( <div className={className}> <svg id="svg-react-meter" style={{top: '5rem', margin: 'auto', width: '100%', height: '100%'}}> {parse(gaugeSVG)} </svg> </div> ); };
import { useCallback, useState } from "react"; import { ErrorHooks } from "../types/type"; const useError = () => { const [errors, setErrors] = useState<ErrorHooks[]>([]); const setError = useCallback( ({ field, message }: ErrorHooks) => { const errorAlreadyExists = errors.find((error) => error.field === field); if (errorAlreadyExists) return; setErrors((prevState) => [...prevState, { field, message }]); }, [errors] ); const removeError = useCallback((fieldName: string) => { setErrors((prevState) => prevState.filter((error) => error.field !== fieldName) ); }, []); const getErrorMessageByFieldName = useCallback((fieldName: string) => { return errors.find((error) => error.field === fieldName)?.message; }, []); return { setError, removeError, getErrorMessageByFieldName, errors }; }; export default useError;
info { "name": "rich-text", "type": "component" } template { <div> <div v-if="editMode" class="card rich-text" ref="editor"> <div class="rich-text-bar" style="height: 32px;"> <button class="right blue lighten-1" style="width: 62px; cursor: pointer; outline: none; font-weight: bold; color: white; border: none; height: 32px;" @click="toggle()"> {{preview ? "Edit" : "Preview"}} </button> <icon fa data-tooltip="Heading" @click.native="insert('# ')">heading</icon> <icon fa data-tooltip="Italic" @click.native="wrap('*')">italic</icon> <icon fa data-tooltip="Code" @click.native="wrap('`')">code</icon> <icon fa data-tooltip="Link" @click.native="insert('[name](url)')">link</icon> <icon fa data-tooltip="Image" @click.native="insert('![name](url)')">image</icon> <icon fa data-tooltip="Number list" @click.native="insert('1. Item 1\\n2. Item 2\\n3. Item 3')">list-ol</icon> <icon fa data-tooltip="Bullet list" @click.native="insert('* Item 1\\n* Item 2\\n* Item 3')">list-ul</icon> <icon fa data-tooltip="Block quote" @click.native="insert('> ')">quote-right</icon> <icon fa data-tooltip="Strike" @click.native="wrap('~~')">strikethrough</icon> <icon fa data-tooltip="Bold" @click.native="wrap('**')">bold</icon> <span data-tooltip="Uppercase" @click.native="upper()">A</span> <span data-tooltip="Lowercase" @click.native="lower()">a</span> <icon fa data-tooltip="Horizontal rule" @click.native="insert('\\n---\\n')">minus</icon> </div> <textarea ref="area" v-if="!preview" v-model="text" style="margin: 0; min-height: 300px" class="input" placeholder="Text">{{value ? value.substr(1) : ""}}</textarea> <div v-else style="display: inline-block; width: 100%;" v-html="baked"></div> </div> <div v-else v-html="baked"></div> </div> } client { props: ["value", "data", "edit-mode"], data: function () { return {text: "", baked: "Loading", preview: false}; }, methods: { restore: function (start, end) { var that = this; that.$refs.area.setSelectionRange(start, end); that.$refs.area.focus(); }, insert: function (str) { var start = this.$refs.area.selectionStart; var end = this.$refs.area.selectionEnd; this.text = this.text.slice(0, start) + str + this.text.slice(start); this.restore(start + str.length, end + str.length); }, wrap: function (str) { var start = this.$refs.area.selectionStart; var end = this.$refs.area.selectionEnd; this.text = this.text.slice(0, start) + str + this.text.slice(start, end) + str + this.text.slice(end); this.restore(start + str.length, end + str.length); }, upper: function () { var start = this.$refs.area.selectionStart; var end = this.$refs.area.selectionEnd; this.text = this.text.slice(0, start) + this.text.slice(start, end).toUpperCase() + this.text.slice(end); this.restore(start, end); }, lower: function () { var start = this.$refs.area.selectionStart; var end = this.$refs.area.selectionEnd; this.text = this.text.slice(0, start) + this.text.slice(start, end).toLowerCase() + this.text.slice(end); this.restore(start, end); }, toggle: function () { this.build(); var that = this; if (this.baked == "") this.baked = "<h3>Nothing to preview</h3>"; var old = $(this.$refs.editor).height(); this.preview = !this.preview; setTimeout(function () { var now = $(that.$refs.editor).height(); $(that.$refs.editor).height(old); $(that.$refs.editor).animate({height: now}, function () {$(that.$refs.editor).removeAttr("style");}); }); }, getValue: function (value) { value("m" + this.text); }, build: function () { var that = this; if (window.md) { this.baked = md(this.text); }else{ $.getScript("https://unpkg.com/[email protected]/md.min.js", function () { that.baked = md(that.text); }); } } }, mounted: function () { if (this.value) this.text = this.value.substr(1); else if (this.data) this.text = this.data.substr(1); this.build(); } }
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:hotel_managment/style/app_font_size.dart'; import 'package:hotel_managment/utils/sizer.dart'; import '../style/app_colors.dart'; class ButtonAppBar extends StatefulWidget { final String title; final String imagePath; final Function() onTap; const ButtonAppBar( {Key? key, required this.title, required this.onTap, required this.imagePath}) : super(key: key); @override State<ButtonAppBar> createState() => _ButtonAppBarState(); } class _ButtonAppBarState extends State<ButtonAppBar> { @override Widget build(BuildContext context) { return ElevatedButton( onPressed: widget.onTap, style: ElevatedButton.styleFrom( primary: Colors.transparent , foregroundColor: Colors.transparent , backgroundColor: AppColors.white, onPrimary: Colors.transparent, elevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(0)) ), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( widget.imagePath, width: 30, height: 30, color: AppColors.blue, ), SizedBox(width: 2.w), Text( widget.title, style: TextStyle( color: AppColors.blue, fontFamily: "Robot", fontWeight: FontWeight.w300, fontSize: AppFontSize.large), ), ], ), ); // Container( // child: Row( // crossAxisAlignment: CrossAxisAlignment.center, // mainAxisAlignment: MainAxisAlignment.center, // children: [ // Expanded( // child: // Center( // child: // SvgPicture.asset( // 'assets/svg/filter.svg', // width: 20, // height: 20, // color: AppColors.blue, // ), // ), // ), // SizedBox(width: 2.w,), // Expanded( // child: Center( // child: Text( // widget.title, // style: TextStyle( // color: AppColors.blue, // fontFamily: "RobotThin", // fontWeight: FontWeight.bold, // fontSize: AppFontSize.medium), // ), // ), // ) // ]), // ); } }
import { useDispatch, useSelector } from 'react-redux'; import { removeFav } from '../redux/favListSlice'; import { Link } from 'react-router-dom'; const FavFoods = ({closeModal}) => { const favFoodArray = useSelector((state) => state.favs.favFoods); const dispatchFav = useDispatch(); return ( <ul className="p-4 grow"> {favFoodArray.length === 0 && <p className="text-violet-600 mb-4">No Fav added yet!</p>} { favFoodArray.length > 0 && favFoodArray.map(food => <li key={food.id} className="flex justify-between my-4"> <p className="mx-2">{food.name}</p> <div className="flex gap-2"> <div> <button className="px-4 py-2 text-xs md:text-base rounded-md bg-violet-700 text-violet-100 hover:bg-violet-100 hover:text-violet-900" onClick={() => dispatchFav(removeFav(food.id))}>Remove</button> </div> <Link to={`/report/${food.id}`}> <button className="px-4 py-2 text-xs md:text-base rounded-md bg-violet-700 text-violet-200 hover:bg-violet-600 hover:text-violet-100" onClick={closeModal}>Report</button> </Link> </div> </li> ) } </ul> ) } export default FavFoods;
import React, { useState } from 'react'; import './products-popups.scss'; import Button from '@mui/material/Button'; import TextField from '@mui/material/TextField'; import IconButton from '@mui/material/IconButton'; import CloseIcon from '@mui/icons-material/Close'; import MenuItem from '@mui/material/MenuItem'; import FormControl from '@mui/material/FormControl'; import Select from '@mui/material/Select'; import InputAdornment from '@mui/material/InputAdornment'; import Switch from '@mui/material/Switch'; import Tooltip from '@mui/material/Tooltip'; import helpIcon from '../../../../../assets/images/invoice-manager/help-circle.svg'; import { styled } from '@mui/material/styles'; const AddNewProductsPopup = ({ handleCloseAddNewProductsPopup }) => { const [description, setDescription] = useState(''); const handleDescription = (event) => { setDescription(event.target.value); }; const [rate, setRate] = useState(''); const handleRate = (event) => { setRate(event.target.value); }; const [units, setUnits] = useState(''); const handleUnits = (event) => { setUnits(event.target.value); }; const [category, setCategory] = useState('default'); const handleCategory = (event) => { setCategory(event.target.value); }; const [additionalInfo, setAdditionalInfo] = useState(false); const handleAdditionalInfo = () => { setAdditionalInfo(!additionalInfo); }; const [estimateNotes, setEstimateNotes] = useState(''); const handleEstimateNotes = (event) => { setEstimateNotes(event.target.value); }; const handleCancelAddPayment = () => { handleCloseAddNewProductsPopup(); setAdditionalInfo(false); } const handleSubmitAddPayment = () => { handleCloseAddNewProductsPopup(); setAdditionalInfo(false); } const IOSSwitch = styled((props) => ( <Switch focusVisibleClassName=".Mui-focusVisible" disableRipple {...props} /> ))(({ theme }) => ({ width: 31, height: 18, padding: 0, '& .MuiSwitch-switchBase': { padding: 0, height: '100%', marginTop: 0 , marginBottom: 0 , marginRight: 0 , marginLeft: 2 , transitionDuration: '300ms', '&.Mui-checked': { transform: 'translateX(16px)', color: '#fff', marginTop: 0 , marginBottom: 0 , marginRight: 2 , marginLeft: 0 , '& + .MuiSwitch-track': { backgroundColor: theme.palette.mode === 'dark' ? '#2ECA45' : '#51A3FFCC', opacity: 1, border: 0, }, '&.Mui-disabled + .MuiSwitch-track': { opacity: 0.5, }, }, '&.Mui-focusVisible .MuiSwitch-thumb': { color: '#33cf4d', border: '6px solid #fff', }, '&.Mui-disabled .MuiSwitch-thumb': { color: theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[600], }, '&.Mui-disabled + .MuiSwitch-track': { opacity: theme.palette.mode === 'light' ? 0.7 : 0.3, }, }, '& .MuiSwitch-thumb': { boxSizing: 'border-box', width: 13, height: 13, }, '& .MuiSwitch-track': { borderRadius: 26 / 2, backgroundColor: theme.palette.mode === 'light' ? '#7676804D' : '#39393D', opacity: 1, transition: theme.transitions.create(['background-color'], { duration: 500, }), }, })); return ( <div className='products-addnewpopup'> <div className='products-addnewpopup-header'> <div className='products-addnewpopup-header-title'> <p>Add new product</p> </div> <div className='products-addnewpopup-header-btn'> <IconButton onClick={handleCloseAddNewProductsPopup}> <CloseIcon /> </IconButton> </div> </div> <div className='products-addnewpopup-list'> <div className='products-addnewpopup-item description'> <p className='products-addnewpopup-item-title'> Description* </p> <TextField className='products-addnewpopup-item-input' variant="outlined" onChange={handleDescription} multiline maxRows={5} /> </div> <div className='products-addnewpopup-item flex'> <p className="products-addnewpopup-item-title"> Rate* </p> <div className='products-addnewpopup-item-number'> <TextField placeholder="" value={rate} onChange={handleRate} className="products-addnewpopup-item-number-input" type="number" InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment>, }} /> </div> </div> <div className='products-addnewpopup-item notes'> <p className='products-addnewpopup-item-title'> Units* <Tooltip className='tooltip' id='addnewproductpopup_tooltip' title="Example: Hr, Each, Item" arrow placement="top-start"> <IconButton> {/* <HelpOutlineIcon /> */} <img src={helpIcon} /> </IconButton> </Tooltip> </p> <TextField className='products-addnewpopup-item-input' variant="outlined" onChange={handleUnits} /> </div> <div className='products-addnewpopup-item flex'> <p className='products-addnewpopup-item-title'> Category* </p> <FormControl fullWidth> <Select className="products-addnewpopup-item-select" labelId="demo-simple-select-label" id="demo-simple-select" value={category} onChange={handleCategory} > <MenuItem value='default'>Default</MenuItem> <MenuItem value='category2'>Category 2</MenuItem> <MenuItem value='category3'>Category 3</MenuItem> <MenuItem value='category4'>Category 4</MenuItem> </Select> </FormControl> </div> <div className='products-addnewpopup-item switch'> <p className='products-addnewpopup-item-title' onClick={handleAdditionalInfo}> Estimate notes <Tooltip className='tooltip' id='addnewproductpopup_tooltip' title="These notes will be displayed when editing an estimate or invoice. These notes are not visible to the client. " arrow placement="top-start"> <IconButton> {/* <HelpOutlineIcon /> */} <img src={helpIcon} /> </IconButton> </Tooltip> </p> {/* <Switch checked={additionalInfo} onChange={handleAdditionalInfo} // inputProps={{ 'aria-label': 'controlled' }} /> */} <IOSSwitch checked={additionalInfo} onChange={handleAdditionalInfo} /> </div> { additionalInfo ? <> <div className='products-addnewpopup-item estimate'> <TextField className='products-addnewpopup-item-input' variant="outlined" onChange={handleEstimateNotes} multiline maxRows={5} /> </div> </> : '' } <div className='products-addnewpopup-item flex'> <p className='products-addnewpopup-item-title required'> * Required </p> </div> <div className='products-addnewpopup-btn'> <Button className='products-addnewpopup-btn-reset' onClick={handleCancelAddPayment}>Cancel</Button> <Button className='products-addnewpopup-btn-submit' onClick={handleSubmitAddPayment}>Submit</Button> </div> </div> </div> ); } export default AddNewProductsPopup;
import { FormControl, InputLabel, MenuItem, Select } from "@mui/material"; import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns"; import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"; import React from "react"; import { Col, Container, Form, Row } from "react-bootstrap"; import { Controller, useFormContext } from "react-hook-form"; export const TradeOptionForm = () => { const { control, register, formState: { errors }, } = useFormContext(); return ( <Container className="mt-3"> <h5>Option Details</h5> <Row className="mb-3"> <Col md={{ span: 6 }} className="ms-4"> <Form.Group> <Form.Control type="number" placeholder="Strike Price" name="strikePrice" {...register("strikePrice")} className={`form-control ${ errors.strikePrice ? "is-invalid" : "" }`} /> <Form.Control.Feedback type="invalid" className="ms-2"> {errors.strikePrice?.message} </Form.Control.Feedback> </Form.Group> <Form.Group className="mt-2"> <Controller name="expirationDate" control={control} defaultValue={null} render={({ field: { ...restField } }) => ( <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker slotProps={{ textField: { fullWidth: true, error: errors.expirationDate, helperText: errors.expirationDate?.message, }, }} onError={errors.expirationDate} {...restField} label="Expiration Date" /> </LocalizationProvider> )} /> </Form.Group> <Form.Group className="mt-2"> <Controller name="optionType" control={control} defaultValue="" render={({ field }) => ( <FormControl fullWidth error={!!errors.optionType}> <InputLabel>Option Type</InputLabel> <Select {...field} label="Option Type"> <MenuItem value="1">Call</MenuItem> <MenuItem value="2">Put</MenuItem> </Select> {errors.optionType && ( <Form.Text className="text-danger ms-2"> {errors.optionType.message} </Form.Text> )} </FormControl> )} /> </Form.Group> </Col> </Row> </Container> ); };
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { MatSnackBar } from '@angular/material/snack-bar'; @Injectable() export class ErrorInterceptor implements HttpInterceptor { errorMessage: string; constructor(private snackBar: MatSnackBar) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // handle errors return next.handle(req).pipe( catchError((error: HttpErrorResponse) => { if (error.error instanceof ErrorEvent) { // client-side or network error this.snackBar.open('An error occurred:', error.error.message); } else { // unsuccessful response code. // shows the body in snackbar, switch (error.status) { case 401: this.snackBar.open('Wrong Credentials', 'Error'); break; case 403: this.snackBar.open('Forbidden', 'Error'); break; default: this.snackBar.open( 'Error Code '+ error.status, error.error ? error.error.messsage : null ); } } return throwError(error); }) ); } }
<?php namespace Tests\Feature\Middlewares; use App\Http\Middleware\CheckUserIsAdmin; use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\Request; use Tests\TestCase; use Symfony\Component\HttpFoundation\Response; class CheckUserIsAdminMiddlewareTest extends TestCase { use RefreshDatabase; public function testWhenUserIsNotAdmin(): void { /* $user = User::factory()->count(2)->state(new Sequence( ['type'=>'user'], ['type'=>'admin'], ))->create();*/ $user = User::factory()->user()->create(); $this->actingAs($user); $request = Request::create('/admin','GET'); $middleware = new CheckUserIsAdmin(); $response = $middleware->handle($request,function (){ }); $this->assertEquals($response->getStatusCode(),302); } public function testWhenUserIsAdmin(): void { $user = User::factory()->admin()->create(); $this->actingAs($user); $request = Request::create('/admin','GET'); $middleware = new CheckUserIsAdmin(); $response = $middleware->handle($request,function (){ return new Response(); }); $this->assertEquals($response,new Response()); } public function testWhenUserNotLoggedIn(): void { $request = Request::create('/admin','GET'); $middleware = new CheckUserIsAdmin(); $response = $middleware->handle($request,function (){ }); $this->assertEquals($response->getStatusCode(),302); } }
import "./App.css"; import Home from "./Home"; import Nav from "./Nav"; import { BrowserRouter, Switch, Route } from "react-router-dom"; import Favourates from "./Favourates"; import Addmovie from "./Addmovie"; import Moviedetails from "./Moviedetails"; import Update from "./Update"; import Moviesearch from "./Moviesearch"; function App() { return( <BrowserRouter> <div> <Nav/> <Switch> <Route exact path="/"> <Home/> </Route> <Route path="/addmovie"> <Addmovie /> </Route> <Route path="/Favourites"> <Favourates /> </Route> <Route path="/moviedetails:id"> <Moviedetails/> </Route> <Route path="/update:id"> <Update/> </Route> <Route path="/searchmovie:searchdata"> <Moviesearch/> </Route> </Switch> </div> </BrowserRouter> ); } export default App;
""" Copyright [2023] Expedia, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import numpy as np import pyspark.sql.functions as F from pyspark.sql.dataframe import DataFrame from pyspark.sql import SparkSession from pyspark.sql.window import Window from typing import List, Tuple, Dict from eg_two_tower.data import save_pickle from eg_two_tower.etl_defaults import DEFAULT_VALIDATION_DATE_SPLIT, IMPRESSION_COLUMNS, FINAL_AMENITY_COLUMNS, \ CANDIDATE_IMPRESSION_COLUMNS, QUERY_CATEGORICAL_COLUMNS, IMPRESSION_CATEGORICAL_COLUMNS, NUMERICAL_COLUMNS, \ FINAL_COLUMNS from loguru import logger def run( spark: SparkSession, main_tsv: str, amenities_tsv: str, out_dir: str, ): """ Runs the whole ETL that is spark operations and then saving as tf-records alongside pickled metadata. Args: spark: An initialized spark session. This spark session is passed in for easier use with DataBricks env. main_tsv: Location of main.tsv amenities_tsv: location of amenities.tsv out_dir: dir to save output of etl """ if not os.path.exists(out_dir): os.makedirs(out_dir) prob_out_path = os.path.join(out_dir, "prob") candidates_out_path = os.path.join(out_dir, "candidates") train_out_path = os.path.join(out_dir, "train") val_out_path = os.path.join(out_dir, "val") vocab_out_path = os.path.join(out_dir, "vocab") main_tsv = spark.read.csv(main_tsv, sep="\t", header=True, inferSchema=True) amenities = spark.read.csv(amenities_tsv, sep="\t", header=True, inferSchema=True) main_processed = format_impressions(main_tsv, amenities, IMPRESSION_COLUMNS) # noinspection PyTypeChecker main_processed_clicks_only = main_processed.filter(F.col("clicked") == 1) candidates = setup_candidates(main_processed, CANDIDATE_IMPRESSION_COLUMNS, FINAL_AMENITY_COLUMNS, IMPRESSION_CATEGORICAL_COLUMNS, FINAL_AMENITY_COLUMNS) write_tf_records(candidates, candidates_out_path) logger.info(f"wrote candidates tf-records to: {candidates_out_path}") train, val = validation_split(main_processed_clicks_only, DEFAULT_VALIDATION_DATE_SPLIT) train = setup_train(train, FINAL_COLUMNS, IMPRESSION_CATEGORICAL_COLUMNS + QUERY_CATEGORICAL_COLUMNS, NUMERICAL_COLUMNS) write_tf_records(train, train_out_path) logger.info(f"wrote train tf-records to: {train_out_path}") val = setup_validation(val, FINAL_COLUMNS, IMPRESSION_CATEGORICAL_COLUMNS + QUERY_CATEGORICAL_COLUMNS, NUMERICAL_COLUMNS) write_tf_records(val, val_out_path) logger.info(f"wrote val tf-records to: {val_out_path}") vocab = build_vocab(train, IMPRESSION_CATEGORICAL_COLUMNS + QUERY_CATEGORICAL_COLUMNS) save_candidate_sampling_prob(train, "impression_prop_id", prob_out_path) logger.info(f"Pickled candidate probabilities to: {prob_out_path}") save_pickle(vocab, vocab_out_path) logger.info(f"Pickled vocab to: {vocab_out_path}") def format_impressions( data: DataFrame, amenities: DataFrame, impression_columns: List[Tuple[str, str]] ) -> DataFrame: """ Takes in a spark DataFrame (main.tsv) and extracts the impressions that are stored as lists of strings where each string is contains pipe delimited information about the impression. Args: data: Spark DataFrame from the file main.tsv amenities: Spark DataFrame from the file amenities.tsv impression_columns: A list of tuples where the fist element is a string representing one of the columns in the pipe delimited impression string and the second element is a string for the data type e.g., string, float. Returns: """ main_processed = ( data .filter(F.col("checkin_date").isNotNull()) .withColumn("event_date", F.to_date("search_timestamp")) .withColumn("impressions", F.split('impressions', "\|")) .withColumn("impression", F.explode("impressions")) .withColumn("impression", F.split("impression", ",")) .withColumn("applied_filters", F.split("applied_filters", "\|")).alias("applied_filters")) main_processed = _set_impression_columns(main_processed, impression_columns) main_processed = add_features(main_processed, amenities) return main_processed def write_tf_records(data: DataFrame, path: str): """ Helper function for writing tf-records (just to save some space...) Args: data: a spark DataFrame to be written as tf-records path: path to write to """ dtype_map = {"timestamp": "string"} for column, dtype in data.dtypes: if dtype in dtype_map: data = data.withColumn(column, F.col(column).astype(dtype_map[dtype])) data \ .write \ .mode("overwrite") \ .format("tfrecords") \ .option("recordType", "SequenceExample") \ .option("codec", "org.apache.hadoop.io.compress.GzipCodec") \ .save(path) def validation_split(data: DataFrame, date: str) -> Tuple[DataFrame, DataFrame]: """ Simple function for splitting a spark DataFrame of data into train and val. Args: data: A spark DataFrame that has an event_date column date: A string with format YYYY-MM-DD Returns: A tuple of dataframes """ # noinspection PyTypeChecker train = data.filter(F.col("event_date") < date) # noinspection PyTypeChecker val = data.filter(F.col("event_date") >= date) return train, val def _set_impression_columns(data: DataFrame, impression_columns: List[Tuple[str, str]]) -> DataFrame: """ Helper function for format_impressions. This function extracts impression features from the impression column and makes them columns in data. Args: data: Data derived from the RecTour dataset that has had the impressions extracted (refer to format_impressions for more details). impression_columns: A list of tuples where the first element in the tuple is a string for the column in the data and the second element is the column type. Returns: data with new columns from impression_columns """ for i, (c, col_type) in enumerate(impression_columns): data = data.withColumn(f"impression_{c}", F.col("impression").getItem(i).astype(col_type)) return data def setup_candidates( data: DataFrame, candidate_impression_columns: List[str], amenities_columns: List[str], categorical_columns: List[str], numerical_columns: List[str] ) -> DataFrame: """ Generates a spark DataFrame with the unique item ids and their corresponding features that are defined by amenities_columns, categorical_columns, numerical_columns Args: data: A spark DataFrame (should be the data from main.tsv) candidate_impression_columns: The column in the data to use to collect the unique item ids. amenities_columns: Column that holds amenities categorical_columns: Columns to collect that represent categorical features for the item numerical_columns: Columns to collect that represent numerical features for the item Returns: A spark DataFrame that contains all unique item ids and their respective categorical and numerical features """ candidates = data.select("impression_prop_id", *candidate_impression_columns, *amenities_columns).distinct() candidates = candidates.groupBy("impression_prop_id").agg( *[F.ceil(F.avg(c)).alias(c) for c in candidate_impression_columns + amenities_columns]) candidates = map_fill_categorical_columns(candidates, categorical_columns) candidates = map_numericals(candidates, numerical_columns) return candidates def setup_train(train: DataFrame, final_columns: List[str], categorical_columns: List[str], numerical_columns: List[str]) -> DataFrame: """ Preps training data by imputing missing categorical and makes sure that numerical features are defined as floats. Args: train: A spark DataFrame representing the training data extracted from main.tsv final_columns: List of columns to keep categorical_columns: Columns representing categorical features to impute and map to ids numerical_columns: List of numerical columns used for training that will be cast to floats. Returns: The mapped training data as a spark DataFrame """ train = _setup(train, final_columns, categorical_columns, numerical_columns) return train def setup_validation(val: DataFrame, final_columns: List[str], categorical_columns: List[str], numerical_columns: List[str]) -> DataFrame: """ Preps validation data by imputing missing categorical and makes sure that numerical features are defined as floats. Args: val: A spark DataFrame representing the validation data extracted from main.tsv (usually resulting from the validation_split function in this file). final_columns: List of columns to keep categorical_columns: Columns representing categorical features to impute and cast to strings numerical_columns: List of numerical columns used for training that will be cast to floats. Returns: The mapped training data as a spark DataFrame """ val = val.withColumn( "clicked_impression_prop_ids", F.collect_list("impression_prop_id").over( Window.partitionBy("search_id").orderBy(F.desc("impression_is_trans"), F.desc("impression_num_clicks")))) val = val.withColumn( "rank", F.row_number().over(Window.partitionBy("search_id").orderBy(F.desc("search_timestamp")))) # noinspection PyTypeChecker val = val.filter(F.col("rank") == 1) val = _setup(val, final_columns + ["clicked_impression_prop_ids"], categorical_columns, numerical_columns) return val def _setup(data: DataFrame, final_columns: List[str], categorical_columns: List[str], numerical_columns: List[str]) -> DataFrame: """ Helper function or train and valid split versions of this function. Preps training data by imputing missing categorical and makes sure that numerical features are defined as floats. Args: data: A spark DataFrame representing some data extracted from main.tsv final_columns: List of columns to keep categorical_columns: Columns representing categorical features to impute and cast to strings numerical_columns: List of numerical columns used for training that will be cast to floats. Returns: The mapped training data as a spark DataFrame """ data = data.select(final_columns) data = map_fill_categorical_columns(data, categorical_columns) data = map_numericals(data, numerical_columns) return data def map_fill_categorical_columns( data: DataFrame, categorical_columns: List[str], missing_token: str = "MISSING" ) -> DataFrame: """ Takes a spark DataFrame and casts the columns defined as categorical as strings and imputes missing values with missing_token. Args: data: The spark dataframe to operate on... (should come from main.tsv) categorical_columns: List of columns that should be treated as categorical missing_token: Impute value Returns: data with categorical_columns cast to strings and imputed with missing_token """ for c in categorical_columns: data = data.withColumn(c, F.col(c).astype("string")) data = data.withColumn(c, F.when(F.col(c).isNull(), missing_token).otherwise(F.col(c))) return data def map_numericals(data: DataFrame, numerical_columns: List[str]) -> DataFrame: """ Casts every column passed to this function to float types for use in tensorflow. Args: data: spark DataFrame to operate on (should come from main.tsv) numerical_columns: List of strings that represent the columns to cast to float Returns: data with numerical_columns cast to float """ for c in numerical_columns: data = data.withColumn(c, F.col(c).astype("float")) return data def add_features(data: DataFrame, amenities: DataFrame) -> DataFrame: """ Adds features to the data being passed by calling the helped functions associated with different type of features. Args: data: data to add features to... (should come from main.tsv) amenities: a spark DataFrame containing amenities data (should be from amenities.tsv) Returns: """ data = join_amenities(data, amenities) data = add_impression_interaction_features(data) data = add_date_features(data) data = add_trip_features(data) return data def join_amenities(data: DataFrame, amenities: DataFrame) -> DataFrame: """ Helper function for joining amenities (amenities.tsv) to impression data (main.tsv) Args: data: (should come from main.tsv) amenities: (should come from amenities.tsv) Returns: Impression data joined with the amenities data """ data = data.join(amenities, F.col("impression_prop_id") == F.col("prop_id"), "left") data = data.drop("prop_id") for c in amenities.columns[1:]: data = data.withColumn(c, F.when(F.col(c).isNull(), 0).otherwise(F.col(c))) return data def add_impression_interaction_features(data: DataFrame) -> DataFrame: """ Adds a binary valued column named clicked that represents whether the user clicked on the impression they saw. Args: data: (should come from main.tsv) Returns: data DataFrame with a new column "clicked" """ # noinspection PyTypeChecker data = data.withColumn("clicked", F.when(F.col('impression_num_clicks') > 0, 1).otherwise(0)) return data def add_date_features(data: DataFrame) -> DataFrame: """ Adds date features using predefined datetime columns Args: data: (should come from main.tsv) Returns: data with month and dayofweek features for the columns defined below """ columns = ["search_timestamp", "checkin_date", "checkout_date"] for c in columns: data = data.withColumn(f"{c}_month", F.month(c)) data = data.withColumn(f"{c}_dayofweek", F.dayofweek(c)) return data def add_trip_features(data: DataFrame) -> DataFrame: """ Generates features from the trip context in the impression data. Args: data: (should come from main.tsv) Returns: data spark DataFrame with trip features """ data = data.withColumn("days_till_trip", F.datediff(F.col("checkout_date"), F.col("event_date"))) data = data.withColumn("length_of_stay", F.datediff(F.col("checkout_date"), F.col("checkin_date"))) return data def save_candidate_sampling_prob(data: DataFrame, candidate_column: str, path: str): """ Does a simple calculation of how likely it is to see every unique item in the dataset Args: data: (should come from main.tsv) candidate_column: column that stores the property id path: path to save pickled dict to """ total_count: int = data.count() counts: DataFrame = data.groupBy(candidate_column).count() prob: List[Dict[str, float]] = ( counts .withColumn("sampling_prob", F.col("count") / F.lit(total_count)) .select(candidate_column, "sampling_prob") .toPandas() .to_dict(orient="records")) prob: Dict[str, float] = {d[candidate_column]: d["sampling_prob"] for d in prob} save_pickle(prob, path) def build_vocab(data: DataFrame, categorical_columns: List[str]) -> Dict[str, np.ndarray]: """ Generates a dict where the key is the name of the column and the value is a numpy array of strings that represent unique values. Args: data: A spark DataFrame with columns that represent categorical features (should be data from main.tsv) categorical_columns: List of strings to use for building the vocab dict Returns: A dict with the column as a key and unique values as the dict value """ data_dtypes: Dict[str, str] = dict(data.dtypes) vocab: Dict[str, np.ndarray] = {} for column in categorical_columns: if "array<array" in data_dtypes[column]: column_data = data.select(F.explode(F.flatten(column)).alias(column)) elif "array" in data_dtypes[column]: column_data = data.select(F.explode(column).alias(column)) elif "string" == data_dtypes[column]: column_data = data.select(F.explode(F.split(column, " ")).alias(column)) else: column_data = data.select(column) column_data = column_data.distinct() # noinspection PyTypeChecker column_data = column_data.filter(F.col(column) != "") column_data = column_data.orderBy(column) column_data = column_data.toPandas() vocab[column] = np.squeeze(column_data.values) return vocab def get_null_counts(data: DataFrame) -> DataFrame: """ Aggregates number of nulls for each column in DataFrame Args: data: data to calculate nulls % over Returns: DataFrame with the same columns as the input data but as percents of null """ allowed_dtypes = ["long", "integer", "float", "double"] null_counts = data.select( [(F.count(F.when(F.isnan(c) | F.col(c).isNull(), c)) / F.count("*")).alias(c) if dtype in allowed_dtypes else (F.count(F.when(F.col(c).isNull(), c)) / F.count("*")).alias(c) for c, dtype in data.dtypes] ) return null_counts
import React from "react"; import Title from "./Title"; import ProductList from "./ProductList"; import AddProduct from "./AddProduct"; import "./Main.css"; import { Route, Switch } from 'react-router-dom'; import Welcome from './Welcome'; import { addProduct, removeProduct } from './redux/actions'; import PageNotFound from './404'; import PramsExample from './ParamsExample'; export default class Main extends React.Component { constructor(props) { super(props); console.log('Constructor 1 ...'); this.state = { productName: 'Garden Cart', products: [], // this is our main products, it contains products show: true, screen: 'products', showImage: true } // this.changeProductName = this.changeProductName.bind(this); this.removeProduct = this.removeProduct.bind(this); } static getDerivedStateFromProps(props, state) { // before the render method console.log("getDerivedStateFromProps 2..."); return { productName: props.productName } } changeProductName = () => { this.setState({ // update state, component re render productName: "Hammer" }) } componentDidMount() { // component is rendered /* console.log("componentDidMount 4..."); const data = getProductDataFromDb(); this.setState({ products: '', // updated products productName: 'Leaf Rake', showImage: false }) */ // this.props.dispatch(addProduct({ "name": "Harsh" })); // calling action // this.props.dispatch(removeProduct(2)); // Mapping dispatch with props this.props.addProduct({ "name": "Harsh" }); this.props.removeProduct(2); } shouldComponentUpdate() { return true; } getSnapshotBeforeUpdate(prevProps, PrevState) { // document.getElementById("beforeUpdate").innerHTML = "Before update, show image flag is " + PrevState.showImage; return true; } componentDidUpdate() { // document.getElementById("afterUpdate").innerHTML = "Current value, show image flag is " + this.state.showImage; } delAddProduct = () => { this.setState({ show: false }) } AddProduct = (productSubmitted) => { debugger; this.setState((state) => ({ products: state.products.concat([productSubmitted]) })) } removeProduct(productRemoved) { this.setState((state) => ({ products: state.products.filter((product) => product != productRemoved) })) } render() { console.log("main props", this.props); const style = { color: "green", backgroundColor: "yellow", padding: "10px", fontFamily: "Arial" }; let addProduct; if (this.state.show) { addProduct = <AddProduct /> } else { addProduct = ""; } return <div> <Switch> <Route exact path="/" render={() => ( <div className="product-list"> <Title title="Dashboard" /> <ProductList {...this.props} onProductRemoved={this.removeProduct} /> </div> )} /> <Route exact path="/Addproduct" render={({ history }) => ( <div className="add-product"> <AddProduct {...this.props} onAddProduct={(addedPost) => this.AddProduct(addedPost)} onHistory={history} /> </div> )} /> <Route exact path="/params/:id" render={(params) => ( <div> <PramsExample {...this.props} {...params}/> </div> )} /> <Route exact path="/Welcome" component={Welcome} /> <Route exact path="*" component={PageNotFound} /> </Switch> </div > } } function getProductDataFromDb() { }
jsPsych.plugins['Demographics'] = (function () { var plugin = {}; plugin.info = { name: 'Demographics', stage_name: 'demographics', description: '', parameters: { questions: { type: jsPsych.plugins.parameterType.COMPLEX, array: true, pretty_name: 'Questions', nested: { prompt: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Prompt', default: undefined, description: 'The strings that will be associated with a group of options.' }, options: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Options', array: true, default: undefined, description: 'Displays options for an individual question.' }, required: { type: jsPsych.plugins.parameterType.BOOL, pretty_name: 'Required', default: false, description: 'Subject will be required to pick an option for each question.' }, horizontal: { type: jsPsych.plugins.parameterType.BOOL, pretty_name: 'Horizontal', default: false, description: 'If true, then questions are centered and options are displayed horizontally.' }, name: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Question Name', default: '', description: 'Controls the name of data values associated with this question' } } }, randomize_question_order: { type: jsPsych.plugins.parameterType.BOOL, pretty_name: 'Randomize Question Order', default: false, description: 'If true, the order of the questions will be randomized' }, preamble: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Preamble', default: null, description: 'HTML formatted string to display at the top of the page above all the questions.' }, button_label: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Button label', default: 'Continue', description: 'Label of the button.' }, time_stamp: { type: jsPsych.plugins.parameterType.OBJECT, pretty_name: 'Timestamp', default: {}, description: 'Object for collecting timestamp' }, event_type: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Event type', default: null, description: 'Event type' }, event_raw_details: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Event raw details', default: null, description: 'Event raw details' }, event_converted_details: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Event converted details', default: null, description: 'Event converted details' } } } plugin.trial = function (display_element, trial) { var plugin_id_name = "jspsych-survey-multi-choice-DEMOGRAPHICS"; var html = ""; var timestamp_onload = jsPsych.totalTime(); // store responses, events var response = { trial_events: [] }; response.trial_events.push({ "event_type": trial.event_type, "event_raw_details": trial.event_raw_details, "event_converted_details": trial.event_converted_details, "timestamp": jsPsych.totalTime(), "time_elapsed": jsPsych.totalTime() - timestamp_onload }); html += '<div id="translation-listener">translate</div>'; // inject CSS for trial html += '<style id="jspsych-survey-multi-choice-css">'; html += ".jspsych-survey-multi-choice-question { display: flex; align-items: center; margin-top: .2em; margin-bottom: .2em; text-align: left; }" + ".jspsych-survey-multi-choice-text span.required {color: darkred;}" + ".jspsych-survey-multi-choice-horizontal .jspsych-survey-multi-choice-text { text-align: center; }" + ".jspsych-survey-multi-choice-option { display: flex; justify-content: flex-start; }" + ".jspsych-survey-multi-choice-content { border-bottom: 1px solid;}" + ".jspsych-survey-multi-choice-form { max-width: 1000px; min-width: 615px; }" + ".jspsych-survey-multi-choice-form > .jspsych-survey-multi-choice-horizontal { outline: 1px solid #fff; margin: 3rem 0;}" + "ul {list-style: none}" + "label { margin-bottom: 0; }" + ".form-radio { top: 0; }" + ".jspsych-display-element input[type='text'] { font-size: 18px; }" + "input[type='text'] { background: transparent; border: none; border-bottom: 1px solid #fff; -webkit-box-shadow: none; box-shadow: none; border-radius: 0; color: #fff; width: 50px; text-align: center; margin: 0 1rem; }" + "input[type='text']:focus { -webkit-box-shadow: none; box-shadow: none; outline: none;}" + `input[type="text"]::-webkit-outer-spin-button, input[type="text"]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input[type="text"] { -moz-appearance: textfield; } label { font-weight: 100 } ` + ".form-text { color: #000; } " + ".jspsych-btn { margin: 100px 0; }" + ".jspsych-content { margin-top: 130px;}" + ".jspsych-survey-multi-choice-preamble { max-width: 1000px; text-align: left; }" + ".jspsych-survey-multi-choice-information { display: flex; justify-content: space-between }" + ".jspsych-survey-multi-choice-information div { width: 40%; text-align: left; padding: 2rem 0; }" + ".jspsych-survey-multi-choice-information ul { display: flex; width: 50%; justify-content: space-around; padding-inline-start: 0; }" + ".jspsych-survey-multi-choice-information li { width: 100px; display: flex; align-items: center; }" + "label.jspsych-survey-multi-choice-text input[type='radio'] {margin-right: 1em;}"; ". { width: 50px; height: 50px; border-radius: 50%; display: flex; justify-content: center; align-items: center; }" html += '</style>'; // fixed heder html += '<header>' + '<nav class="navbar navbar-inverse navbar-fixed-top">' + '<div class="container-fluid">' + '<div class="navbar-header">' + '<p class="navbar-text"><b>' + plugin.info.name + '</b></p>' + '</div>' + '</div>' + '</nav>' + '</header>'; // show preamble text if (trial.preamble !== null) { html += '<div id="jspsych-survey-multi-choice-preamble" class="jspsych-survey-multi-choice-preamble">' + trial.preamble + '</div>'; } // form element html += '<form id="' + plugin_id_name + '" class="jspsych-survey-multi-choice-form">'; // generate question order. this is randomized here as opposed to randomizing the order of trial.questions // so that the data are always associated with the same question regardless of order var question_order = []; for (var i = 0; i < trial.questions.length; i++) { question_order.push(i); } if (trial.randomize_question_order) { question_order = jsPsych.randomization.shuffle(question_order); } // add multiple-choice questions for (var i = 0; i < 1; i++) { // get question based on question_order var question = trial.questions[question_order[i]]; var question_id = question_order[i]; // create question container var question_classes = ['jspsych-survey-multi-choice-question']; if (question.horizontal) { question_classes.push('jspsych-survey-multi-choice-horizontal'); } html += '<div id="jspsych-survey-multi-choice-' + question_id + '" class="' + question_classes.join(' ') + '" data-name="' + question.name + '">'; // add question text html += '<div style="width: 30%; padding: 1rem;"><p class="jspsych-survey-multi-choice-question survey-multi-choice" style="padding-top: 3px; text-align: left;">' + (i + 1) + '. ' + question.prompt // question.required html += '</p></div>'; html += '<div style="display: flex; width: 70%; padding: 2rem; justify-content: space-around; border-left: 1px solid #fff; ">'; // create option radio buttons for (var j = 0; j < question.options.length; j++) { // add label and question text var option_id_name = "jspsych-survey-multi-choice-option-" + question_id + "-" + j; var input_name = 'jspsych-survey-multi-choice-response-' + question_id; var input_id = 'jspsych-survey-multi-choice-response-' + question_id + '-' + j; var required_attr = question.required ? 'required' : ''; // add radio button container html += '<div style="flex-flow: column; height: 80px; justify-content: space-between;" id="' + option_id_name + '" class="jspsych-survey-multi-choice-option">'; html += '<label class="jspsych-survey-multi-choice-text" data-time-stamp="Q' + (i+1) + '" for="' + input_id + '">' + question.options[j] + '</label>'; html += '<input type="radio" name="' + input_name + '" data-time-stamp="Q' + (i+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" id="' + input_id + '" class="form-radio" value="' + question.options[j] + '" ' + required_attr + '></input>'; html += '</div>'; } html += '</div></div>'; } // add multiple-choice questions for (var i = 1; i < 2; i++) { // get question based on question_order var question = trial.questions[question_order[i]]; var question_id = question_order[i]; // create question container var question_classes = ['jspsych-survey-multi-choice-question']; if (question.horizontal) { question_classes.push('jspsych-survey-multi-choice-horizontal'); } html += '<div id="jspsych-survey-multi-choice-' + question_id + '" class="' + question_classes.join(' ') + '" data-name="' + question.name + '">'; // add question text html += '<div style="width: 30%; padding: 1rem;"><p class="jspsych-survey-multi-choice-question survey-multi-choice jspsych-survey-multi-choice-question-age" style="padding-top: 3px; text-align: left;">' + (i + 1) + '. ' + question.prompt // question.required html += '</p></div>'; html += '<div style="display: flex; width: 70%; padding: 1rem; justify-content: space-around; border-left: 1px solid #fff; ">'; // create option radio buttons for (var j = 0; j < question.options.length; j++) { // add label and question text var option_id_name = "jspsych-survey-multi-choice-option-" + question_id + "-" + j; var input_name = 'jspsych-survey-multi-choice-response-' + question_id; var input_id = 'jspsych-survey-multi-choice-response-' + question_id + '-' + j; var required_attr = question.required ? 'required' : ''; // add radio button container html += '<div style="flex-flow: column;" id="' + option_id_name + '" class="jspsych-survey-multi-choice-option">'; html += '<label class="jspsych-survey-multi-choice-text" data-time-stamp="Q' + (i+1) + '" for="' + input_id + '">' + question.options[j] + '</label>'; html += '<input type="text" name="2. Age (years)" maxlength="3" data-time-stamp="Q' + (i+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" id="' + input_id + '" class="input-year option-input-age" ' + required_attr + '></input>'; html += '</div>'; } html += '</div></div>'; } // add multiple-choice questions for (var i = 2; i < 3; i++) { // get question based on question_order var question = trial.questions[question_order[i]]; var question_id = question_order[i]; // create question container var question_classes = ['jspsych-survey-multi-choice-question']; if (question.horizontal) { question_classes.push('jspsych-survey-multi-choice-horizontal'); } html += '<div id="jspsych-survey-multi-choice-' + question_id + '" class="' + question_classes.join(' ') + '" data-name="' + question.name + '">'; // add question text html += '<div style="width: 30%; padding: 1rem;"><p class="jspsych-survey-multi-choice-question survey-multi-choice jspsych-survey-multi-choice-question-height" style="padding-top: 3px; text-align: left;">' + (i + 1) + '. ' + question.prompt // question.required html += '</p></div>'; html += '<div style="display: flex; width: 70%; padding: 1rem; justify-content: space-around; border-left: 1px solid #fff; ">'; // create option radio buttons for (var j = 0; j < question.options.length; j++) { // add label and question text var option_id_name = "jspsych-survey-multi-choice-option-" + question_id + "-" + j; var input_name = 'jspsych-survey-multi-choice-response-' + question_id; var input_id = 'jspsych-survey-multi-choice-response-' + question_id + '-' + j; var required_attr = question.required ? 'required' : ''; // add radio button container html += '<div id="' + option_id_name + '" class="jspsych-survey-multi-choice-option" style="flex-flow: row; ">'; if(j === 0) { html += '<input type="radio" data-time-stamp="Q' + (i+1) + '" data-enable="cm" name="Height (units selected)" id="' + input_id + '" class="form-radio" value="' + question.options[j] + '" ' + required_attr + '></input>'; html += '<input type="text" maxlength="3" name="3a. Height (cm)" data-time-stamp="Q' + (i+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" id="' + input_id + '" class="jspsych-survey-multi-choice-radio-cm" max="250" ' + required_attr + ' disabled></input>'; } else { html += '<input type="radio" data-time-stamp="Q' + (i+1) + '" data-enable="feet" name="Height (units selected)" id="' + input_id + '" class="form-radio" value="' + question.options[j] + '" ' + required_attr + '></input>'; html += '<input type="text" maxlength="3" name="3b. Height (feet)" data-time-stamp="Q' + (i+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" id="' + input_id + '" class="jspsych-survey-multi-choice-radio-feet" max="8" ' + required_attr + ' disabled></input>'; html += '<label class="jspsych-survey-multi-choice-text " for="' + input_id + '">feet</label>'; html += '<input type="text" maxlength="3" name="3c. Height (inches)" data-time-stamp="Q' + (i+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" id="' + input_id + '" class="jspsych-survey-multi-choice-radio-inches" max="11" ' + required_attr + ' disabled></input>'; } html += '<label class="jspsych-survey-multi-choice-text " for="' + input_id + '">' + question.options[j] + '</label>'; html += '</div>'; } html += '</div></div>'; } // add multiple-choice questions for (var i = 3; i < 4; i++) { // get question based on question_order var question = trial.questions[question_order[i]]; var question_id = question_order[i]; // create question container var question_classes = ['jspsych-survey-multi-choice-question']; if (question.horizontal) { question_classes.push('jspsych-survey-multi-choice-horizontal'); } html += '<div id="jspsych-survey-multi-choice-' + question_id + '" class="' + question_classes.join(' ') + '" data-name="' + question.name + '">'; // add question text html += '<div style="width: 30%; padding: 1rem;"><p class="jspsych-survey-multi-choice-question survey-multi-choice jspsych-survey-multi-choice-question-weight" style="padding-top: 3px; text-align: left;">' + (i + 1) + '. ' + question.prompt // question.required html += '</p></div>'; html += '<div style="display: flex; width: 70%; justify-content: center; align-items: center; flex-direction: column; padding: 1rem; border-left: 1px solid #fff; position: relative;">'; // create option radio buttons for (var j = 0; j < question.options.length; j++) { // add label and question text var option_id_name = "jspsych-survey-multi-choice-option-" + question_id + "-" + j; var input_name = 'jspsych-survey-multi-choice-response-' + question_id; var input_id = 'jspsych-survey-multi-choice-response-' + question_id + '-' + j; var required_attr = question.required ? 'required' : ''; if(j === 0) { html += '<div style="position: absolute; padding-right: 230px;">'; html += '<input type="text" maxlength="3" name="4b. Weight" data-time-stamp="Q' + (i+1) + 'A' + (j+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" class="option-input-weight" max="440" ' + required_attr + ' disabled></input>'; html += '</div>'; html += '<div>'; html += '<div style="display: flex; justify-content: flex-end; margin: 1rem; width: 120px; padding-right: 1rem; flex-direction: row-reverse;" id="' + option_id_name + '" class="jspsych-survey-multi-choice-option">'; html += '<label style="padding-left: 1rem;" class="jspsych-survey-multi-choice-text" data-time-stamp="Q' + (i+1) + '" for="' + input_id + '">' + question.options[j] + '</label>'; html += '<input type="radio" data-enable="weight" name="weight" value="kg" data-time-stamp="Q' + (i+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" id="' + input_id + '" class="form-radio jspsych-survey-multi-choice-radio-kg" value="' + question.options[j] + '" ' + required_attr + '></input>'; } else { html += '<div>'; html += '<div style="display: flex; justify-content: flex-end; margin: 1rem; width: 120px; padding-right: 1rem; flex-direction: row-reverse;" id="' + option_id_name + '" class="jspsych-survey-multi-choice-option">'; html += '<label style="padding-left: 1rem;" class="jspsych-survey-multi-choice-text" data-time-stamp="Q' + (i+1) + '" for="' + input_id + '">' + question.options[j] + '</label>'; html += '<input type="radio" data-enable="weight" name="weight" value="pounds" data-time-stamp="Q' + (i+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" id="' + input_id + '" class="form-radio jspsych-survey-multi-choice-radio-pounds" value="' + question.options[j] + '" ' + required_attr + '></input>'; } html += '</div>'; html += '</div>'; } html += '</div></div>'; } // add multiple-choice questions for (var i = 4; i < 8; i++) { // get question based on question_order var question = trial.questions[question_order[i]]; var question_id = question_order[i]; // create question container var question_classes = ['jspsych-survey-multi-choice-question']; if (question.horizontal) { question_classes.push('jspsych-survey-multi-choice-horizontal'); } html += '<div id="jspsych-survey-multi-choice-' + question_id + '" class="' + question_classes.join(' ') + '" data-name="' + question.name + '">'; // add question text html += '<div style="width: 30%; padding: 1rem;"><p class="jspsych-survey-multi-choice-question survey-multi-choice" style="padding-top: 3px; text-align: left;">' + (i + 1) + '. ' + question.prompt // question.required html += '</p></div>'; html += '<div style="border-left: 1px solid #fff; padding: 1rem 0 1rem 2rem; ">'; // create option radio buttons for (var j = 0; j < question.options.length; j++) { // add label and question text var option_id_name = "jspsych-survey-multi-choice-option-" + question_id + "-" + j; var input_name = 'jspsych-survey-multi-choice-response-' + question_id; var input_id = 'jspsych-survey-multi-choice-response-' + question_id + '-' + j; var required_attr = question.required ? 'required' : ''; // add radio button container html += '<div id="' + option_id_name + '" class="jspsych-survey-multi-choice-option">'; html += '<input type="radio" name="' + input_name + '" data-time-stamp="Q' + (i+1) + '" data-question-number="Q' + (i+1) +'A' + (j+1) +'" id="' + input_id + '" class="form-radio" value="' + question.options[j] + '" ' + required_attr + '></input>'; html += '<label style="padding-left: 2rem; " data-time-stamp="Q' + (i+1) + '" class="jspsych-survey-multi-choice-text" for="' + input_id + '">' + question.options[j] + '</label>'; html += '</div>'; } html += '</div></div>'; } html += '</div>'; // add submit button html += '<p><input type="submit" id="' + plugin_id_name + '-next" class="' + plugin_id_name + ' jspsych-btn"' + (trial.button_label ? ' value="' + trial.button_label + '"' : '') + '></input></p>'; html += '</form>'; // add modal html += `<div class="modal micromodal-slide" id="modal-1" aria-hidden="true"> <div class="modal__overlay" tabindex="-1" data-micromodal-close> <div class="modal__container" role="dialog" aria-modal="true" aria-labelledby="modal-1-title"> <header class="modal__header"> <button class="modal__close" aria-label="Close modal" data-micromodal-close></button> </header> <main class="modal__content" id="modal-1-content"> <p> ${popup_text_WBF} </p> </main> <footer class="modal__footer"> <button class="modal__btn" data-micromodal-close aria-label="Close this dialog window">Close</button> </footer> </div> </div> </div>`; html += jsPsych.pluginAPI.getPopupHTML('translator-detected', popup_text_translator); // render display_element.innerHTML = html; // function to handle responses by the subject var after_response = function (info) { if (info.key_release === undefined) { response.trial_events.push({ "event_type": "key press", "event_raw_details": info.key, "event_converted_details": jsPsych.pluginAPI.convertKeyCodeToKeyCharacter(info.key) + ' key pressed', "timestamp": jsPsych.totalTime(), "time_elapsed": jsPsych.totalTime() - timestamp_onload }); if(info.el) { if(info.el.dataset.timeStamp) { trial.time_stamp[info.el.dataset.timeStamp] = jsPsych.totalTime(); } if(info.el.dataset.questionNumber) { response.trial_events.push({ "event_type": "answer displayed", "event_raw_details": info.el.dataset.questionNumber, "event_converted_details": info.el.dataset.questionNumber + ' answer displayed', "timestamp": jsPsych.totalTime(), "time_elapsed": jsPsych.totalTime() - timestamp_onload }); } } } else { response.trial_events.push({ "event_type": "key release", "event_raw_details": info.key_release, "event_converted_details": jsPsych.pluginAPI.convertKeyCodeToKeyCharacter(info.key_release) + ' key released', "timestamp": jsPsych.totalTime(), "time_elapsed": jsPsych.totalTime() - timestamp_onload }); } } // forced click event fix for some laptops touchpad $("label").on("click",function(){ var labelID = $(this).attr('for'); $("#" + labelID).prop('checked', true).trigger('click').trigger('change'); }); // save timestamp on input click $("input[type=radio]").on("click change touchstart",function(){ var time_stamp_key = $(this).data('time-stamp'); if(time_stamp_key) { trial.time_stamp[time_stamp_key] = jsPsych.totalTime(); }; }); function proccessDataBeforeSubmit(validateInputs = false) { // create object to hold responses var question_data = {}; var timestamp_data = {}; for (var i = 0; i < 1; i++) { var match = display_element.querySelector('#jspsych-survey-multi-choice-' + i); var id = $(match).find('.jspsych-survey-multi-choice-question').text(); var val = ''; if (match.querySelector('input[type=radio]:checked') !== null) { val = match.querySelector('input[type=radio]:checked').value; $(match).find('.jspsych-survey-multi-choice-question').removeClass('survey-error-after'); } else if (validateInputs) { $(match).find('.jspsych-survey-multi-choice-question').addClass('survey-error-after'); val = ''; } var obje = {}; var name = id; if (match.attributes['data-name'].value !== '') { name = match.attributes['data-name'].value; } timestamp_data[name] = trial.time_stamp['Q' + (i + 1)]; obje[name] = val; Object.assign(question_data, obje); } // input age check (function () { var year_input_value = $('.input-year').val(); var label = $('#jspsych-survey-multi-choice-response-1-0').prop('labels'); if (!validateInputs || (year_input_value !== '' && year_input_value >= 18 && year_input_value <= 100)) { $('.jspsych-survey-multi-choice-question-age').removeClass('survey-error-after'); $('.moda__age-incomplete').remove(); $(label).removeClass('survey-error-after'); var object2a = { '2. Age (years)': $('input[name="2. Age (years)"]').val() }; timestamp_data['2. Age (years)'] = trial.time_stamp['Q2']; Object.assign(question_data, object2a); } else { $('.jspsych-survey-multi-choice-question-age').addClass('survey-error-after'); if (year_input_value !== '') { $(label).addClass('survey-error-after'); if (!$('.moda__age-incomplete').length) { $('.modal__content').append('<p class="moda__age-incomplete">You have entered an age that falls outside the expected range. <br/> Please enter your age.</p>') } } } })(); // input height check (function () { var height_input_value_cm = $('.jspsych-survey-multi-choice-radio-cm').val(); var height_input_value_feet = $('.jspsych-survey-multi-choice-radio-feet').val(); var height_input_value_inches = $('.jspsych-survey-multi-choice-radio-inches').val(); var height_radio_value = $('input[name="Height (units selected)"]:checked').val(); var label_cm = $('#jspsych-survey-multi-choice-response-2-0').prop('labels'); var label_feet = $('#jspsych-survey-multi-choice-response-2-1').prop('labels'); var label; var height_min, height_max; var height_input_value = ''; if (height_radio_value === 'cm') { height_input_value = height_input_value_cm; height_min = 100; height_max = 250; label = label_cm; } else { height_input_value = height_input_value_feet; height_min = 3; height_max = 8; label = label_feet; } if (!validateInputs || (height_input_value !== '' && height_input_value >= height_min && height_input_value <= height_max && !(height_input_value == 8 && height_input_value_inches >= 4))) { $('.jspsych-survey-multi-choice-question-height').removeClass('survey-error-after'); $('.moda__height-incomplete').remove(); $(label).removeClass('survey-error-after'); var object3a = { '3a. Height (cm)': $("input[name='3a. Height (cm)']").val() ? $("input[name='3a. Height (cm)']").val() : 'NA' }; var object3b = { '3b. Height (feet)': $('input[name="3b. Height (feet)"]').val() ? $('input[name="3b. Height (feet)"]').val() : 'NA' }; var object3c = { '3c. Height (inches)': $('input[name="3c. Height (inches)"]').val() ? $('input[name="3c. Height (inches)"]').val() : 'NA' }; timestamp_data['3a. Height (cm)'] = $('input[name="3a. Height (cm)"]').val() ? trial.time_stamp['Q3'] : 'NA'; timestamp_data['3b. Height (feet)'] = $('input[name="3b. Height (feet)"]').val() ? trial.time_stamp['Q3'] : 'NA'; timestamp_data['3c. Height (inches)'] = $('input[name="3c. Height (inches)"]').val() ? trial.time_stamp['Q3'] : 'NA'; Object.assign(question_data, object3a, object3b, object3c); } else { $('.jspsych-survey-multi-choice-question-height').addClass('survey-error-after'); if (height_input_value !== '') { $(label).addClass('survey-error-after'); if (!$('.moda__height-incomplete').length) { $('.modal__content').append('<p class="moda__height-incomplete">You have entered a height that falls outside the expected range. <br/> Please enter your height.</p>'); } } } })(); // input weight check (function () { var weight_input_value = $('.option-input-weight').val(); var weight_radio_value = $("input[name='weight']:checked").val(); var weight_min, weight_max; var label_kg = $('#jspsych-survey-multi-choice-response-3-0').prop('labels'); var label_pounds = $('#jspsych-survey-multi-choice-response-3-1').prop('labels'); var label; if (weight_radio_value != 'kg') { weight_min = 85; weight_max = 440; label = label_pounds; } else { weight_min = 40; weight_max = 200; label = label_kg; } if (!validateInputs || (weight_input_value >= weight_min && weight_input_value <= weight_max)) { $('.jspsych-survey-multi-choice-question-weight').removeClass('survey-error-after'); $('.moda__weight-incomplete').remove(); $(label).removeClass('survey-error-after'); var object4a = { '4a Weight(kg)': weight_radio_value === 'kg' ? $('input[name="4b. Weight"]').val() : 'NA' }; var object4b = { '4b Weight (lbs)': weight_radio_value === 'pounds' ? $('input[name="4b. Weight"]').val() : 'NA' }; Object.assign(timestamp_data, { '4a Weight(kg)': weight_radio_value === 'kg' ? trial.time_stamp['Q4'] : 'NA', '4b Weight (lbs)': weight_radio_value === 'pounds' ? trial.time_stamp['Q4'] : 'NA' }); Object.assign(question_data, object4a, object4b); } else { $('.jspsych-survey-multi-choice-question-weight').addClass('survey-error-after'); if (weight_input_value !== '') { $(label).addClass('survey-error-after'); if (!$('.moda__weight-incomplete').length) { $('.modal__content').append('<p class="moda__weight-incomplete">You have entered a weight that falls outside the expected range. <br/> Please enter your weight.</p>') } } } })(); for (var i = 4; i < trial.questions.length; i++) { var match = display_element.querySelector('#jspsych-survey-multi-choice-' + i); var id = $(match).find('.jspsych-survey-multi-choice-question').text(); var val = ''; if (match.querySelector('input[type=radio]:checked') !== null) { val = match.querySelector('input[type=radio]:checked').value; $(match).find('.jspsych-survey-multi-choice-question').removeClass('survey-error-after'); } else if (validateInputs) { $(match).find('.jspsych-survey-multi-choice-question').addClass('survey-error-after'); val = ''; } var obje = {}; var name = id; if (match.attributes['data-name'].value !== '') { name = match.attributes['data-name'].value; } timestamp_data[name] = trial.time_stamp['Q' + (i + 1)]; obje[name] = val; Object.assign(question_data, obje); } return { 'stage_name': JSON.stringify(plugin.info.stage_name), 'responses': JSON.stringify(question_data), 'timestamp': JSON.stringify(timestamp_data), 'time_stamp': JSON.stringify(trial.time_stamp), 'question_order': JSON.stringify(question_order), 'events': JSON.stringify(response.trial_events), }; } const translatorTarget = document.getElementById('translation-listener') jsPsych.pluginAPI.initializeTranslatorDetector(translatorTarget, 'translate', response, timestamp_onload, proccessDataBeforeSubmit); // form functionality document.querySelector('form').addEventListener('submit', function (event) { event.preventDefault(); response.trial_events.push({ "event_type": "button clicked", "event_raw_details": 'Submit', "event_converted_details": '"Submit" selected', "timestamp": jsPsych.totalTime(), "time_elapsed": jsPsych.totalTime() - timestamp_onload }); const trial_data = proccessDataBeforeSubmit(true); if ($(".survey-error-after").length < 1) { // kill keyboard listeners if (typeof keyboardListener !== 'undefined') { jsPsych.pluginAPI.cancelKeyboardResponse(keyboardListener); jsPsych.pluginAPI.cancelClickResponse(clickListener); } // clear the display display_element.innerHTML = ''; // next trial jsPsych.finishTrial(trial_data); } else { // show modal, register events MicroModal.show('modal-1', { onShow() { response.trial_events.push({ "event_type": "error message", "event_raw_details": 'Error message', "event_converted_details": 'popup triggered by incomplete WBF question', "timestamp": jsPsych.totalTime(), "time_elapsed": jsPsych.totalTime() - timestamp_onload }); }, onClose() { response.trial_events.push({ "event_type": "popup closed", "event_raw_details": 'Close', "event_converted_details": trial.event_converted_details, "timestamp": jsPsych.totalTime(), "time_elapsed": jsPsych.totalTime() - timestamp_onload }); } }); } }); // input integer function $(function() { $('input[type="text"').on('keyup', function() { $(this).val(this.value.match(/[0-9]*/)); }); }); // input number activation on radio button $('input:radio').click(function() { if($(this).data().enable) { var inputName = $(this).data().enable; switch (inputName) { case 'cm': $( "input[name='3a. Height (cm)']").removeAttr("disabled"); $( "input[name='3b. Height (feet)']").prop("disabled", true).val(''); $( "input[name='3c. Height (inches)']").prop("disabled", true).val(''); var label3b = $( "#jspsych-survey-multi-choice-response-2-1").prop('labels'); $(label3b).removeClass('survey-error-after'); break; case 'feet': $( "input[name='3a. Height (cm)']").prop("disabled", true).val(''); $( "input[name='3b. Height (feet)']").removeAttr("disabled"); $( "input[name='3c. Height (inches)']").removeAttr("disabled"); var label3a = $( "#jspsych-survey-multi-choice-response-2-0").prop('labels'); $(label3a).removeClass('survey-error-after'); break; case 'weight': $('.option-input-weight').removeAttr("disabled").val(''); $( "input[name='weight']" ).each(function( index ) { var label = $(this).prop('labels') $(label).removeClass('survey-error-after'); }); break; default: break; } } }); // start the response listener var keyboardListener = jsPsych.pluginAPI.getKeyboardResponse({ callback_function: after_response, valid_responses: jsPsych.ALL_KEYS, rt_method: 'performance', persist: true, allow_held_key: false }); var clickListener = jsPsych.pluginAPI.getMouseResponse({ callback_function: after_response, valid_responses: jsPsych.ALL_KEYS, rt_method: 'performance', persist: true, allow_held_key: false }); }; return plugin; })();
import React from 'react'; import { useIntl } from 'react-intl'; import { ButtonStyled } from './styles'; type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & React.AriaAttributes & { onClick?: (e: React.MouseEvent<HTMLElement>) => void; iconLeft?: boolean, idLabel?: string, size?: "xs" | "sm" | "md" | "xl", color?: "primary" | "neutral" | "danger" | "success", disabled?: boolean, } const Button: React.FC<ButtonProps> = ( { children, onClick, iconLeft = false, idLabel, size, color, disabled, ...rest } ) => { const { formatMessage } = useIntl(); return ( <ButtonStyled onClick={onClick} size={size} color={color} disabled={disabled} {...rest} > {iconLeft && children} {idLabel && ( <label>{formatMessage({ id: idLabel })}</label> )} {!iconLeft && children} </ButtonStyled> ); } export { Button };
import { useState } from "react"; import { close, logo, menu ,logo1 } from "../assets"; import { navLinks } from "../constant"; const Navbar = () => { const [toggle, setToggle] = useState(false) //para hacer el menu mobile// return ( <nav className='w-full flex py-7 px-9 justify-between items-center navbar bg-black'> <img src={logo1} alt="bank" className="w-[120px] h-[44px] lg:w-[110px] lg:h-[54px] min-[320px]:w-[90px] max-[600px]:w-[90px]" /> <ul className="list-none sm:flex hidden justify-end items-center flex-1"> {navLinks.map((nav, index) => ( <li key={nav.id} className={`font-poppins font-normal cursor-pointer text- [16px] ${index === navLinks.length - 1 ? "mr-0" : "mr-10"} text-white`} //Para tener margen right 10 en todos los elementos menos el último// > <a href={`#${nav.id}`}>{nav.title}</a> {/* me lleva al inicio de cada uno */} </li> ))} </ul> {/* mobile */} <div className="sm:hidden flex flex-1 justify-end items-center"> <img src={toggle ? close : menu} alt="menu" className="w-[28px] h-[28px] object-contain" onClick={() => setToggle(!toggle)} /> <div className={`${toggle ? 'flex' : 'hidden'} p-6 bg-black-gradient absolute top-20 right-0 mx-4 my-2 min-w-[140px] rounded xl sidebar z-10`} > <ul className="list-none flex flex-col justify-end items-center flex-1"> {navLinks.map((nav, index) => ( <li key={nav.id} className={`font-poppins font-normal cursor-pointer text- [16px] ${index === navLinks.length - 1 ? "mr-0" : "mb-4"} text-white`} > <a href={`#${nav.id}`}>{nav.title}</a> </li> ))} </ul> </div> </div> </nav> ) } export default Navbar
import PropTypes from "prop-types"; import { Component } from "react"; import { Form, Button, Input, FormLabel } from "../styles/styled"; class ContactForm extends Component { static propTypes = { onSubmit: PropTypes.func.isRequired, }; state = { name: "", number: "", }; onSubmitHandler = (event) => { event.preventDefault(); this.props.onSubmit(this.state); this.reset(); }; onChangeHandler = (event) => { const { name, value } = event.target; this.setState({ [name]: value, }); }; reset() { this.setState({ name: "", number: "" }); } render() { const { name, number } = this.state; return ( <Form onSubmit={this.onSubmitHandler}> <FormLabel> Name <Input type="text" name="name" pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$" title="Name may contain only letters, apostrophe, dash and spaces. For example Adrian, Jacob Mercer, Charles de Batz de Castelmore d'Artagnan" required value={name} onChange={this.onChangeHandler} /> </FormLabel> <FormLabel> Number <Input type="tel" name="number" pattern="\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}" title="Phone number must be digits and can contain spaces, dashes, parentheses and can start with +" required value={number} onChange={this.onChangeHandler} /> </FormLabel> <Button type="submit">Add Contact</Button> </Form> ); } } export default ContactForm;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 com.phonemetra.turbo.internal; import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import com.phonemetra.turbo.TurboSQLCheckedException; import com.phonemetra.turbo.lang.TurboSQLClosure; import com.phonemetra.turbo.lang.TurboSQLInClosure; import org.jetbrains.annotations.Async; /** * Extension for standard {@link Future} interface. It adds simplified exception handling, * functional programming support and ability to listen for future completion via functional * callback. * @param <R> Type of the result for the future. */ public interface TurboSQLInternalFuture<R> { /** * Synchronously waits for completion of the computation and * returns computation result. * * @return Computation result. * @throws TurboSQLInterruptedCheckedException Subclass of {@link TurboSQLCheckedException} thrown if the wait was interrupted. * @throws TurboSQLFutureCancelledCheckedException Subclass of {@link TurboSQLCheckedException} throws if computation was cancelled. * @throws TurboSQLCheckedException If computation failed. */ public R get() throws TurboSQLCheckedException; /** * Synchronously waits for completion of the computation for * up to the timeout specified and returns computation result. * This method is equivalent to calling {@link #get(long, TimeUnit) get(long, TimeUnit.MILLISECONDS)}. * * @param timeout The maximum time to wait in milliseconds. * @return Computation result. * @throws TurboSQLInterruptedCheckedException Subclass of {@link TurboSQLCheckedException} thrown if the wait was interrupted. * @throws TurboSQLFutureTimeoutCheckedException Subclass of {@link TurboSQLCheckedException} thrown if the wait was timed out. * @throws TurboSQLFutureCancelledCheckedException Subclass of {@link TurboSQLCheckedException} throws if computation was cancelled. * @throws TurboSQLCheckedException If computation failed. */ public R get(long timeout) throws TurboSQLCheckedException; /** * Synchronously waits for completion of the computation for * up to the timeout specified and returns computation result. * * @param timeout The maximum time to wait. * @param unit The time unit of the {@code timeout} argument. * @return Computation result. * @throws TurboSQLInterruptedCheckedException Subclass of {@link TurboSQLCheckedException} thrown if the wait was interrupted. * @throws TurboSQLFutureTimeoutCheckedException Subclass of {@link TurboSQLCheckedException} thrown if the wait was timed out. * @throws TurboSQLFutureCancelledCheckedException Subclass of {@link TurboSQLCheckedException} throws if computation was cancelled. * @throws TurboSQLCheckedException If computation failed. */ public R get(long timeout, TimeUnit unit) throws TurboSQLCheckedException; /** * Synchronously waits for completion of the computation and returns computation result ignoring interrupts. * * @return Computation result. * @throws TurboSQLFutureCancelledCheckedException Subclass of {@link TurboSQLCheckedException} throws if computation * was cancelled. * @throws TurboSQLCheckedException If computation failed. */ public R getUninterruptibly() throws TurboSQLCheckedException; /** * Cancels this future. * * @return {@code True} if future was canceled (i.e. was not finished prior to this call). * @throws TurboSQLCheckedException If cancellation failed. */ public boolean cancel() throws TurboSQLCheckedException; /** * Checks if computation is done. * * @return {@code True} if computation is done, {@code false} otherwise. */ public boolean isDone(); /** * Returns {@code true} if this computation was cancelled before it completed normally. * * @return {@code True} if this computation was cancelled before it completed normally. */ public boolean isCancelled(); /** * Registers listener closure to be asynchronously notified whenever future completes. * * @param lsnr Listener closure to register. If not provided - this method is no-op. */ @Async.Schedule public void listen(TurboSQLInClosure<? super TurboSQLInternalFuture<R>> lsnr); /** * Make a chained future to convert result of this future (when complete) into a new format. * It is guaranteed that done callback will be called only ONCE. * * @param doneCb Done callback that is applied to this future when it finishes to produce chained future result. * @return Chained future that finishes after this future completes and done callback is called. */ @Async.Schedule public <T> TurboSQLInternalFuture<T> chain(TurboSQLClosure<? super TurboSQLInternalFuture<R>, T> doneCb); /** * Make a chained future to convert result of this future (when complete) into a new format. * It is guaranteed that done callback will be called only ONCE. * * @param doneCb Done callback that is applied to this future when it finishes to produce chained future result. * @param exec Executor to run callback. * @return Chained future that finishes after this future completes and done callback is called. */ @Async.Schedule public <T> TurboSQLInternalFuture<T> chain(TurboSQLClosure<? super TurboSQLInternalFuture<R>, T> doneCb, Executor exec); /** * @return Error value if future has already been completed with error. */ public Throwable error(); /** * @return Result value if future has already been completed normally. */ public R result(); }
mod ut_rt; /// Unit tests for v2 config #[cfg(test)] mod cfg_v2_ut { use std::path::PathBuf; use flakes::config::{itf::InstanceMode, pilots::fc::FirecrackerRuntimeParams}; use super::ut_rt; /// Test v2 overall parse #[test] fn test_cfg_v2_overall_parse() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.is_some(), "FlakeConfig v2 should not be None"); assert!(cfg.unwrap().version() == 2, "Version should be 2"); }); } /// Test v2 overall parse #[test] fn test_cfg_v2_runtime_name() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.unwrap().runtime().image_name() == "darth vader", "The name should be defined"); }); } /// Test v2 path map #[test] fn test_cfg_v2_path_map_present() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(!cfg.clone().unwrap().runtime().paths().is_empty(), "Path map should not be empty"); assert!(cfg.unwrap().runtime().paths().len() == 4, "Path map should have four elements"); }); } /// Test v2 path map has properties #[test] fn test_cfg_v2_path_map_has_props() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( cfg.unwrap().runtime().paths().get(&PathBuf::from("/usr/bin/banana")).is_some(), "Banana should have some properties!" ); }); } /// Test v2 path map has specific properties: exports #[test] fn test_cfg_v2_path_map_has_spec_props_exports() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( cfg.unwrap().runtime().paths().get(&PathBuf::from("/usr/bin/banana")).unwrap().exports() == &PathBuf::from("/usr/bin/brown-banana"), "Banana should be a bit older than that" ); }); } /// Test v2 path map has specific properties: user #[test] fn test_cfg_v2_path_map_has_spec_props_user() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( cfg.clone().unwrap().runtime().paths().get(&PathBuf::from("/usr/bin/banana")).unwrap().run_as().is_some(), "Banana should have some consumer" ); assert!( cfg.unwrap().runtime().paths().get(&PathBuf::from("/usr/bin/banana")).unwrap().run_as().unwrap().uid.is_root(), "Only r00t can eat bananas" ); }); } #[test] fn test_cfg_v2_path_map_has_spec_props_instance_mode() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { let banana = cfg.unwrap().clone(); let banana = banana.runtime().paths().get(&PathBuf::from("/usr/bin/rotten-banana")).unwrap(); assert!( banana.instance_mode().unwrap() & InstanceMode::Resume == InstanceMode::Resume, "Rotten banana should resume" ); }); } #[test] fn test_cfg_v2_path_map_has_default_path() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { let p = PathBuf::from("/usr/bin/bash"); let banana = cfg.unwrap().clone(); let banana = banana.runtime().paths().get(&p).unwrap(); assert!(banana.exports() == &p, "Rotten banana should resume"); }); } #[test] fn test_cfg_v2_path_map_default_path_has_common_behaviour() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { let p = PathBuf::from("/usr/bin/bash"); let banana = cfg.unwrap().clone(); let banana = banana.runtime().paths().get(&p).unwrap(); assert!( banana.instance_mode().unwrap() & InstanceMode::Resume == InstanceMode::Resume, "Rotten banana should be resumed" ); assert!( banana.instance_mode().unwrap() & InstanceMode::Attach == InstanceMode::Attach, "Rotten banana should be still attached to a tree" ); }); } #[test] fn test_cfg_v2_engine_pilot() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.unwrap().engine().pilot() == "RD2D".to_string(), "Pilot should always have RD2D!"); }); } #[test] fn test_cfg_v2_engine_args() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.unwrap().engine().args().is_some(), "Pilot should have instructions!"); }); } #[test] fn test_cfg_v2_engine_args_len() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.unwrap().engine().args().unwrap().len() == 2, "Pilot should have whole two instructions!"); }); } #[test] fn test_cfg_v2_engine_args_second_check() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( cfg.unwrap().engine().args().unwrap().get(1).unwrap() == "--foo=bar", "Pilot should know exactly where it goes!" ); }); } #[test] fn test_cfg_v2_engine_params_exists() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.unwrap().engine().params().is_some(), "Pilot should have parameters!"); }); } #[test] fn test_cfg_v2_engine_params_vm_boot_args() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.unwrap().engine().params().unwrap().get("boot_args").is_some(), "VM should have boot args!"); }); } #[test] fn test_cfg_v2_engine_params_rtp_boot_args() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).boot_args().is_some(), "Runtime params should have boot args!" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_boot_args_len() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).boot_args().unwrap().len() == 7, "Runtime params should have seven params!" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_memsize() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).mem_size_mib().is_some(), "Runtime params should have memsize" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_memsize_check() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).mem_size_mib().unwrap() == 0x1000, "Runtime params should have memsize of 4096" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_vcpu() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).vcpu_count().unwrap() == 2, "Runtime params should have some virtual CPUs" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_cache_type() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).cache_type().unwrap() == "Writeback", "Runtime params should have cache type as writeback" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_overlay_size() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).overlay_size().unwrap() == "20GiB", "Runtime params should have overlay size of 20 gigabytes" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_root_fs() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).rootfs_image_path() == PathBuf::from("/var/lib/firecracker/images/NAME/rootfs"), "Runtime params should have root FS path" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_kernel_image() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).kernel_image_path() == PathBuf::from("/var/lib/firecracker/images/NAME/kernel"), "Runtime params should have root kernel path" ); }); } #[test] fn test_cfg_v2_engine_params_rtp_initrd() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( FirecrackerRuntimeParams::from(cfg.unwrap().engine().params().unwrap()).initrd_path() == PathBuf::from("/var/lib/firecracker/images/NAME/initrd"), "Runtime params should have root initrd path" ); }); } #[test] fn test_cfg_v2_engine_static_data() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.unwrap().static_data().get_bundles().is_some(), "There should be some static data"); }); } #[test] fn test_cfg_v2_engine_static_data_len() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!(cfg.unwrap().static_data().get_bundles().unwrap().len() == 4, "There should be some static data of 4"); }); } #[test] fn test_cfg_v2_engine_static_data_second_value() { ut_rt::tb("cfg-v2/all.yaml".to_string(), |cfg| { assert!( cfg.unwrap().static_data().get_bundles().unwrap().get(1).unwrap() == "extra-files.tar.xz", "Second value should be an .xz archive" ); }); } }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, map, Observable } from 'rxjs'; import { URL_SERVICES } from '../config/endpoints'; import { RoleAdapter, Roles } from '../models/roles'; import { BaseService } from './base.service'; @Injectable({ providedIn: 'root' }) export class RolesService extends BaseService { constructor(private http: HttpClient, private adapter: RoleAdapter) { super(); } /** * @description Servicio para consultar roles */ public getRoles(): Observable<Array<Roles>> { return this.http.get(`${URL_SERVICES.URL_ROLES}/GetRoles`) .pipe( catchError((error: any) => { return this.handleError(error); }) ) .pipe( map((response: any) => response.resultData.map( (item: any) => this.adapter.adapt(item) ) ) ); } }
import PropTypes from 'prop-types'; import SubTitle from '../ui/SubTitle/SubTitle'; import dummy from '/images/dummyS.png'; import { Item, ImageWrapper, TagsWrapper, Tag, Overlay, InfoWrapper, ReadMoreLink, } from './EventItem.styled'; const EventItem = ({ id, title, location, description, date, time, image, priority, category }) => { const normalizeDescription = description => description.length > 100 ? description.slice(0, 99) + '...' : description; return ( <Item> <ImageWrapper> <TagsWrapper> <Tag>{category}</Tag> <Tag $priority={priority.toLowerCase()}>{priority}</Tag> </TagsWrapper> <img src={image ? image : dummy} alt={title} /> <Overlay> <span> {date.slice(0, 5).replaceAll('/', '.')} at {time} </span> <span>{location}</span> </Overlay> </ImageWrapper> <InfoWrapper> <SubTitle>{title}</SubTitle> <p>{normalizeDescription(description)}</p> <ReadMoreLink to={`event/${id}`}>More info</ReadMoreLink> </InfoWrapper> </Item> ); }; export default EventItem; EventItem.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, location: PropTypes.string.isRequired, date: PropTypes.string.isRequired, time: PropTypes.string.isRequired, description: PropTypes.string.isRequired, image: PropTypes.string.isRequired, category: PropTypes.string.isRequired, priority: PropTypes.string.isRequired, };
import 'package:flutter/material.dart'; import 'package:expense_tracker/models/expense.dart'; class ExpenseItem extends StatelessWidget { const ExpenseItem({super.key, required this.expense}); final Expense expense; @override Widget build(context) { return Card( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 16, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( expense.title, ), const SizedBox(height: 4), Row( children: [ Text( 'RS ${expense.amount.toStringAsFixed(2)}'), //it simply display 12.55556 to 12.55 const Spacer(), Row( children: [ Icon(categoryIcons[expense.category]), const SizedBox( width: 8, ), Text(expense.formattedDate) ], ), ], ) ], ), ), ); } }
# BSD 2-Clause License # # Copyright (c) 2021-2024, Hewlett Packard Enterprise # All rights reserved. # # 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. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 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. import pytest from smartdashboard.utils.LogReader import get_logs from ..utils.test_entities import * @pytest.mark.parametrize( "entity, expected_output_log, expected_error_log", [ pytest.param( application_1, model0_out_logs, model0_err_logs, ), pytest.param( application_2, model1_out_logs, model1_err_logs, ), ], ) def test_load_log_data(entity, expected_output_log, expected_error_log): output_log_path = entity.out_file error_log_path = entity.err_file output_logs = get_logs(output_log_path) error_logs = get_logs(error_log_path) assert output_logs == expected_output_log assert error_logs == expected_error_log
import { StyleSheet, View } from 'react-native'; import React from 'react'; import { Surface, Text, TextInput } from 'react-native-paper'; type Props = { textContent: number; textTitle: string; contentColor: string; unit?: string; setMyInfoState: React.Dispatch<React.SetStateAction<MyInfoRead>>; }; function InfoEditCardNumeric(props: Props) { const textContentStyle = { color: props.contentColor, marginBottom: 5, }; const [text, setText] = React.useState(props.textContent.toString()); const numericTitleList = ['height', 'weight', 'age', 'workoutPerWeek']; const numericTitleKorList = ['키', '몸무게', '나이(만)', '운동 횟수/주']; const numericTitleListIndex = numericTitleList.indexOf(props.textTitle); return ( <View style={styles.surfaceContainer}> <Surface elevation={1} style={styles.surface}> <Text variant="labelLarge"> {numericTitleKorList[numericTitleListIndex]} </Text> <View style={styles.textInputGroup}> <TextInput value={text} mode="outlined" onChangeText={t => setText(t)} onEndEditing={() => { props.setMyInfoState(prevState => ({ ...prevState, [props.textTitle]: parseInt(text, 10), })); }} blurOnSubmit={true} style={textContentStyle} keyboardType={'numeric'} disabled={props.textTitle === 'age' ? true : false} /> {props.unit ? <Text variant="bodySmall">{props.unit}</Text> : null} </View> </Surface> </View> ); } export default InfoEditCardNumeric; const styles = StyleSheet.create({ surfaceContainer: { flexDirection: 'row', alignItems: 'center', padding: 10, }, surface: { flex: 1, flexDirection: 'row', margin: 5, borderRadius: 10, height: 80, padding: 20, justifyContent: 'space-between', alignItems: 'center', }, textInputGroup: { flexDirection: 'row', alignItems: 'center', }, });
#include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BNO055.h> #include <utility/imumaths.h> //#include <MsTimer2.h> // PWM出力端子設定 #define pwm1 14 #define dir1 27 #define pwm2 26 #define dir2 25 #define STACK_THRESHOLD 0.02 // PWM出力設定(周波数と分解能はチャンネルのペアでは同じに設定する) #define CH1 1 // PWM出力チャンネル(0,1/ 2,3/ 4,5/ 6,7/ 8,9/ 10,11 /12,13 /14,15でペア) #define FREQ 20000 // PWM出力周波数(最大周波数 : 20kHz / 2の「bit数」乗) #define BIT_NUM 12 // bit数(1bit〜16bit) //MD2個使うからチャンネルも二個必要かな?1こ出善さげな感じする #define CH2 0 // PWM出力チャンネル(0,1/ 2,3/ 4,5/ 6,7/ 8,9/ 10,11 /12,13 /14,15でペア) #define FREQ 20000 // PWM出力周波数(最大周波数 : 20kHz / 2の「bit数」乗) #define BIT_NUM 12 // bit数(1bit〜16bit) /* Set the delay between fresh samples */ uint16_t BNO055_SAMPLERATE_DELAY_MS = 100; // Check I2C device address and correct line below (by default address is 0x29 or 0x28) // id, address Adafruit_BNO055 bno = Adafruit_BNO055(55, 0x28, &Wire); void setup(void) { // PWM出力に使用する端子を出力設定 pinMode(pwm1, OUTPUT); pinMode(dir1, OUTPUT); pinMode(pwm2, OUTPUT); pinMode(dir2, OUTPUT); // PWM初期設定 ledcSetup(CH1, FREQ, BIT_NUM); // PWM設定(チャンネル, 周波数, bit数) ledcSetup(CH2, FREQ, BIT_NUM); // PWM設定(チャンネル, 周波数, bit数) ledcAttachPin(dir1, CH1); ledcAttachPin(dir2, CH2); digitalWrite(pwm1, HIGH); digitalWrite(pwm2, HIGH); Serial.begin(115200); while (!Serial) delay(10); // wait for serial port to open! Serial.println("Orientation Sensor Test"); Serial.println(""); /* Initialise the sensor */ if (!bno.begin()) { /* There was a problem detecting the BNO055 ... check your connections */ Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!"); while (1); } delay(1000); } void loop(void) { //could add VECTOR_ACCELEROMETER, VECTOR_MAGNETOMETER,VECTOR_GRAVITY... sensors_event_t orientationData , angVelocityData , linearAccelData, magnetometerData, accelerometerData, gravityData; bno.getEvent(&orientationData, Adafruit_BNO055::VECTOR_EULER); bno.getEvent(&angVelocityData, Adafruit_BNO055::VECTOR_GYROSCOPE); bno.getEvent(&linearAccelData, Adafruit_BNO055::VECTOR_LINEARACCEL); bno.getEvent(&magnetometerData, Adafruit_BNO055::VECTOR_MAGNETOMETER); bno.getEvent(&accelerometerData, Adafruit_BNO055::VECTOR_ACCELEROMETER); bno.getEvent(&gravityData, Adafruit_BNO055::VECTOR_GRAVITY); printEvent(&orientationData); printEvent(&angVelocityData); printEvent(&linearAccelData); printEvent(&magnetometerData); printEvent(&accelerometerData); printEvent(&gravityData); int8_t boardTemp = bno.getTemp(); Serial.println(); Serial.print(F("temperature: ")); Serial.println(boardTemp); uint8_t system, gyro, accel, mag = 0; bno.getCalibration(&system, &gyro, &accel, &mag); Serial.println(); Serial.print("Calibration: Sys="); Serial.print(system); Serial.print(" Gyro="); Serial.print(gyro); Serial.print(" Accel="); Serial.print(accel); Serial.print(" Mag="); Serial.println(mag); Serial.println("--"); delay(BNO055_SAMPLERATE_DELAY_MS); /* if (accel < STACK_THRESHOLD) { delay(2000);   //けっきょくこれGPSRUNフェーズに入ってからだから旋回するときとか以外止まらないはず if (accel < STACK_THRESHOLD - 0.1) { ledcWrite(CH1, 4096); //後退→右に旋回→直進 ledcWrite(CH2, 4096); delay(100); ledcWrite(CH1, 0); ledcWrite(CH2, 2048); delay(100); ledcWrite(CH1, 0); ledcWrite(CH2, 0); delay(100); }else{ delay(100); } } */ if (accel < STACK_THRESHOLD) { delay(2000); //けっきょくこれGPSRUNフェーズに入ってからだから旋回するときとか以外止まらないはず if (accel < STACK_THRESHOLD) { Serial.println("Robot is stacked!"); ledcWrite(CH1, 4096); //後退→右に旋回→直進 ledcWrite(CH2, 4096); delay(100); ledcWrite(CH1, 0); ledcWrite(CH2, 2048); delay(100); ledcWrite(CH1, 0); ledcWrite(CH2, 0); delay(100); } } } void printEvent(sensors_event_t* event) { double x = -1000000, y = -1000000 , z = -1000000; //dumb values, easy to spot problem if (event->type == SENSOR_TYPE_ACCELEROMETER) { Serial.print("Accl:"); x = event->acceleration.x; y = event->acceleration.y; z = event->acceleration.z; } else if (event->type == SENSOR_TYPE_ORIENTATION) { Serial.print("Orient:"); x = event->orientation.x; y = event->orientation.y; z = event->orientation.z; } else if (event->type == SENSOR_TYPE_MAGNETIC_FIELD) { Serial.print("Mag:"); x = event->magnetic.x; y = event->magnetic.y; z = event->magnetic.z; } else if (event->type == SENSOR_TYPE_GYROSCOPE) { Serial.print("Gyro:"); x = event->gyro.x; y = event->gyro.y; z = event->gyro.z; } else if (event->type == SENSOR_TYPE_ROTATION_VECTOR) { Serial.print("Rot:"); x = event->gyro.x; y = event->gyro.y; z = event->gyro.z; } else if (event->type == SENSOR_TYPE_LINEAR_ACCELERATION) { Serial.print("Linear:"); x = event->acceleration.x; y = event->acceleration.y; z = event->acceleration.z; } else if (event->type == SENSOR_TYPE_GRAVITY) { Serial.print("Gravity:"); x = event->acceleration.x; y = event->acceleration.y; z = event->acceleration.z; } else { Serial.print("Unk:"); } Serial.print("\tx= "); Serial.print(x); Serial.print(" |\ty= "); Serial.print(y); Serial.print(" |\tz= "); Serial.println(z); }
@extends('layouts.app') @section('content') <div class="position-relative iq-banner"> <div class="iq-navbar-header" style="height: 180px;"> <div class="container-fluid iq-container"> <div class="row"> <div class="col-md-12"> <div class="flex-wrap d-flex justify-content-between align-items-center text-black"> <div> <h4>{{ Breadcrumbs::render('criterios.gestion' ) }}</h4> </div> </div> </div> </div> </div> <div class="iq-header-img"> <img src="{{ asset('img/fondo1.jpg') }}" alt="header" class="img-fluid w-100 h-100 animated-scaleX"> </div> </div> </div> <div class="conatiner-fluid content-inner mt-n5 py-0"> @if(session('error')) <div id="myAlert" class="alert alert-left alert-danger alert-dismissible fade show mb-3 alert-fade" role="alert"> <span>{{ session('error') }}</span> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button> </div> @endif <div class="row"> <div class="col-sm-12"> <div class="card"> <div class="card-body"> <div class="header-title"> <h4 class="card-title">Actualizar información de la categoria</h4> </div> <form class="needs-validation" novalidate method="POST" action="{{ route('admin.update.cat.criterios', $categoria->id) }}"> @csrf @method('PUT') <div class="row"> <div class="form-group col-lg-12"> <select class="form-select" name="criterio" required onchange="selectPonderacionEdit(this.value)"> <option value="" disabled>Seleccionar un criterio</option> @foreach ($criterios as $crit) <option value="{{ $crit->id }}" {{ $crit->id == $categoria->criterio_id ? 'selected' : '' }}>{{ $crit->nombre }}</option> @endforeach </select> @error('criterio') <span class="text-danger">{{ $message }}</span> @enderror </div> <div class="form-group col-lg-8"> <input type="text" class="form-control" name="nombre" value="{{ $categoria->nombre }}" placeholder="Ingrese un nombre"> @error('nombre') <span class="text-danger">{{ $message }}</span> @enderror </div> <div class="form-group col-lg-2"> <input type="hidden" name="" value="{{ $categoria->porcentaje }}" id="porcentajeDefecto"> <input type="text" class="form-control" name="porcentajeCat" id="porcentajeEditCat" value="{{ $categoria->porcentaje }}" placeholder="%" oninput="restarPorcentajeEditCat()" pattern="\d*" required> @error('porcentajeCat') <span class="text-danger">{{ $message }}</span> @enderror </div> <div class="form-group col-lg-2"> <input type="numeric" class="form-control" name="totalPocentCategoria" id="totalPocentCategoriaEdit" value="{{ $categoria->criterio->total + $categoria->porcentaje }}" required> @error('totalPocentCategoria') <span class="text-danger">{{ $message }}</span> @enderror </div> </div> <div id="alertCat" class="text-danger"></div> <div class="text-center"> <a href="{{ route('admin.tareas.criterios') }}" class="btn btn-secondary">Cancelar</a> <button type="submit" class="btn btn-primary" onclick="enablePonderacion()">Guardar</button> </div> </form> </div> </div> </div> </div> </div> <script> var ponderacion = parseFloat(document.getElementById('totalPocentCategoriaEdit').value); var defecto = parseFloat(document.getElementById('porcentajeDefecto').value); function selectPonderacionEdit(id) { axios.get('/select/ponderacion/' + id) .then(function (response) { ponderacion = response.data.data + defecto; document.getElementById('totalPocentCategoriaEdit').value = response.data.data + defecto; }) .catch(function (error) { console.log(error); }); } // Función para restar el porcentaje function restarPorcentajeEditCat() { var porcentaje = parseFloat(document.getElementById('porcentajeEditCat').value) || 0; var resultado = ponderacion - porcentaje; if (resultado >= 0) { document.getElementById('totalPocentCategoriaEdit').value = resultado; clearError(); // Limpiar cualquier mensaje de error } else { document.getElementById('porcentajeEditCat').value = ''; var error = "El porcentaje no puede ser mayor que la ponderación."; showError(error); // Mostrar el mensaje de error } } // Funciones para mostrar y limpiar mensajes de error function showError(errorMessage) { document.getElementById('alertCat').innerText = errorMessage; document.getElementById('alertCat').style.display = 'block'; } function clearError() { document.getElementById('alertCat').innerText = ''; document.getElementById('alertCat').style.display = 'none'; } // Función para habilitar el campo totalPocentCategoriaEdit function enablePonderacion() { document.getElementById('totalPocentCategoriaEdit').disabled = false; document.getElementById('ponderacion_hidden').value = document.getElementById('totalPocentCategoriaEdit').value; } </script> @endsection
require 'rails_helper' RSpec.describe QuestionsController, type: :controller do let(:question) { create(:question) } let(:user) { question.user } describe 'GET #index' do let(:questions){ create_list(:question, 3) } before { get :index } it 'populated an array of all questions' do expect(assigns(:questions)).to match_array(questions) end it 'renders index view' do expect(response).to render_template :index end end describe 'GET #show' do before { get :show, params: { id: question }} it 'renders show view' do expect(response).to render_template :show end end describe 'GET #new' do before { login(user) } before { get :new } it 'renders new view' do expect(response).to render_template :new end end describe 'GET #edit' do before { login(user) } before { get :edit, params: { id: question }} it 'renders edit view' do expect(response).to render_template :edit end end describe 'POST#create' do before { login(user) } context 'with valid attributes' do it 'saves a new question in the database' do expect { post :create, params: { question: attributes_for(:question)} }.to change(Question, :count).by(1) end it 'redirects to show view' do post :create, params: { question: attributes_for(:question) } expect(response).to redirect_to assigns(:question) end end context ' with invalid attributes' do it 'does not save the question' do expect { post :create, params: { question: attributes_for(:question, :invalid)} }.to_not change(Question, :count) end it 're-renders new view' do post :create, params: { question: attributes_for(:question, :invalid) } expect(response).to render_template :new end end end describe 'PATCH #update' do before { login(user) } context 'with valid attributes' do it 'assigns the requested question to @question' do patch :update, params: { id: question, question: attributes_for(:question)} expect(assigns(:question)).to eq question end it 'changes question attributes' do patch :update, params: { id: question, question: {title: 'new title', body: 'new body'}} question.reload expect(question.title).to eq 'new title' expect(question.body).to eq 'new body' end it 'redirects to updated question' do patch :update, params: { id: question, question: attributes_for(:question)} expect(response).to redirect_to question end end context 'with invalid attributes' do before {patch :update, params: { id: question, question: attributes_for(:question, :invalid)}} it 'does not change question' do question.reload expect(question.title).to eq 'MyString' expect(question.body).to eq 'MyText' end it 're-renders edit view' do expect(response).to render_template :edit end end context 'for not the author of the question' do let(:not_author) { create(:user) } before { login(not_author) } before { patch :update, params: { id: question, question: { title: 'title', body: 'body' } } } it 'does not change answer' do question.reload expect(question.title).to eq 'MyString' expect(question.body).to eq 'MyText' end it 're-renders edit view' do expect(response).to redirect_to question end end end describe 'DELETE #destroy' do before { login(user) } let!(:question) { create(:question) } it 'deletes the question' do expect {delete :destroy, params: { id: question} }.to change(Question, :count).by(-1) end it 'redirects to index' do delete :destroy, params: { id: question} expect(response).to redirect_to questions_path end context 'for not the author of the answer' do let(:not_author) { create(:user) } before { login(not_author) } it "don't delete the question" do expect { delete :destroy, params: { id: question } }.to_not change(Question, :count) end it 'redirects to question' do delete :destroy, params: { id: question } expect(response).to redirect_to question_path(question) end end end end
import React, { useEffect, useState } from "react"; import { signOut } from "../../firebase/accountFunctions"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faDoorOpen } from "@fortawesome/free-solid-svg-icons"; import { useUserContext } from "../../contexts/UserContext"; import "./account-dashboard.scss"; import { TestType } from "../../enums"; import { TestSummary } from "../../firebase/firestoreDocumentInterfaces"; import MainSumary from "./MainSummary"; import SecondarySummary from "./SecondarySummary"; export enum AccountTab { Main = "overview", Secondary = "averages" } const AccountDashboard = () => { const {user, userDocument} = useUserContext(); const [activeTab, setActiveTab] = useState<AccountTab>(AccountTab.Main); const [sortedSummaries, setSortedSummaries] = useState<(TestSummary|undefined)[]>([]); useEffect(() => { if (!user) return; const words10 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Words && summary.testLength == 10); const words25 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Words && summary.testLength == 25); const words50 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Words && summary.testLength == 50); const words75 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Words && summary.testLength == 75); const words100 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Words && summary.testLength == 100); const timed15 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Time && summary.testLength == 15); const timed30 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Time && summary.testLength == 30); const timed45 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Time && summary.testLength == 45); const timed60 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Time && summary.testLength == 60); const timed120 = userDocument?.testSummaries.find(summary => summary.testType == TestType.Time && summary.testLength == 120); setSortedSummaries([timed15, timed30, timed45, timed60, timed120, words10, words25, words50, words75, words100]); }, [userDocument]); const handleTabClick = (tab: AccountTab) => { setActiveTab(tab); }; // already assumes there is a user logged in return ( <div className="account-dashboard"> <div className="tab-container"> <div className="tab-selector"> <button className={activeTab === AccountTab.Main ? "tab-selected" : ""} onClick={() => handleTabClick(AccountTab.Main)}> {AccountTab.Main.toString()} </button> <button className={activeTab === AccountTab.Secondary ? "tab-selected" : ""} onClick={() => handleTabClick(AccountTab.Secondary)}> {AccountTab.Secondary.toString()} </button> <div className="tab-selected-underline" style={{transform: activeTab === AccountTab.Main ? "translateX(0%)" : "translateX(100%)"}}> </div> </div> <div className="tabbed-content"> {activeTab === AccountTab.Main && <MainSumary sortedSummaries={sortedSummaries} userDocument={userDocument} activeTab={activeTab}/>} {activeTab === AccountTab.Secondary && <SecondarySummary sortedSummaries={sortedSummaries} />} </div> </div> <button onClick={() => signOut()}> <FontAwesomeIcon icon={faDoorOpen} className="standard-icon-left"/> log out </button> </div> ); }; export default AccountDashboard;
<!doctype html> <html lang="en"> <head> <title>BestWebCode | Free Web Code</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css"> <link rel="stylesheet" type="text/css" href="css/main.css"> <link rel="stylesheet" type="text/css" href="css/navbar.css"> <link rel="stylesheet" type="text/css" href="css/mycss.css"> </head> <style> .tablink { background-color: #555; color: white; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; font-size: 17px; width: 33%; } .tablink:hover { background-color: #777; } /* Style the tab content (and add height:100% for full page content) */ .tabcontent { color: white; display: none; padding: 100px 20px; height: 100%; } #News { background-color: rgba(253, 136, 69, 0.678); } #Contact { background-color: rgba(5, 5, 175, 0.685); } #About { background-color: rgba(247, 233, 36, 0.671); } </style> <body> <div class="navbar"> <div class="container"> <a class="logo" href="#">BestWeb<span>Code</span></a> <img id="mobile-cta" class="mobile-menu" src="images/menu.svg" alt="Open Navigation"> <nav> <img id="mobile-exit" class="mobile-menu-exit" src="images/exit.svg" alt="Close Navigation"> <ul class="primary-nav"> <li class="current"><a href="index.html">Home</a></li> <li><a href="navbar1st.html">Navbar</a></li> <li><a href="design.html">Design</a></li> <li><a href="about.html">About Us</a></li> </ul> <ul class="secondary-nav"> <li><a href="#">Contact Us</a></li> <li class="go-premium-cta"><a href="#">New</a></li> </ul> </nav> </div> </div> <!-- header ends --> <!-- two sided blog part starts --> <div class="container-fluid "> <div class="row "> <!-- to get the space form left and right --> <div class="col-xl-10 col-lg-10 col-md-12 col-11 mx-auto my-5"> <div class="row gx-5 mx-sm-auto"> <!-- left side of the blog --> <div class="col-lg-8 col-md-11 col-11 mx-auto"> <div class="row gy-5 "> <div class="col-12 card p-4 shadow blog_left__div"> <div class="d-flex justify-content-center align-items-center flex-column pt-3 pb-5 "> <h1 class="text-uppercase">Responsive Navigation Bar using HTML CSS </h1> <p class="blog_title"> <span class="font-weight-bold"> BestWebCode, </span> Feb 6, 2021 </p> </div> <figure class="right_side_img mb-5" style="display: flex;"> <a href="" target="_blank"><img src="card/card2.jpeg" class="img-fluid shadow"></a> <!-- <img src="navbarimage/navbar-responsive.png" class="img-fluid shadow"> <img src="navbarimage/responsiveimage.png" class="img-fluid shadow"> --> </figure> </div> <div class="tab"> <button class="tablink" onclick="openPage('News', this, 'rgba(253, 136, 69, 0.678)')" id="defaultOpen">HTML</button> <button class="tablink" onclick="openPage('Contact', this, 'rgba(5, 5, 175, 0.685)')">CSS</button> <button class="tablink" onclick="openPage('About', this, 'rgba(247, 233, 36, 0.671)')">JAVASCRIPT</button> </div> </div> <div class="row gy-5"> <div class="col-12 card p-4 shadow blog_left__div tabcontent" id="News"> <textarea cols="100" id="htmlText" readonly="" rows="20" style="height: auto; resize: none; width: 100%;"> &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;--Devloped by Bestwebcode--&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge" /&gt; &lt;title&gt;Card | Bestwebcode&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="box box-1"&gt; &lt;h1&gt;BestWebCode&lt;/h1&gt; &lt;p&gt; BestWebCode is a blog where you can show HTML, CSS, and JavaScript along with creative Design. &lt;/p&gt; &lt;/div&gt; &lt;div class="box box-2"&gt; &lt;h1&gt;BestWebCode&lt;/h1&gt; &lt;p&gt; BestWebCode is a blog where you can show HTML, CSS, and JavaScript along with creative Design. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;div class="box box-1"&gt; &lt;h1&gt;BestWebCode&lt;/h1&gt; &lt;p&gt; BestWebCode is a blog where you can show HTML, CSS, and JavaScript along with creative Design. &lt;/p&gt; &lt;/div&gt; &lt;div class="box box-2"&gt; &lt;h1&gt;BestWebCode&lt;/h1&gt; &lt;p&gt; BestWebCode is a blog where you can show HTML, CSS, and JavaScript along with creative Design. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </textarea> </div> <!-- 2 --> <div class="col-12 card p-4 shadow blog_left__div tabcontent" id="Contact"> <textarea cols="100" id="htmlText" readonly="" rows="20" style="height: auto; resize: none; width: 100%;"> :root { --container-max: 960px; /* */ } .box { --box-bg-color: rgb(92, 159, 247); --box-txt-color: #fff; --box-1-width: 1; --box-2-width: 3; --box-shadow-h-offset: 10px; --box-shadow-v-offset: 5px; --box-shadow-blur: 5px; --box-shadow-color: #ccc; } * { margin: 0; padding: 0; } body { font-family: Arial, Helvetica, sans-serif; line-height: 1.4; background: #f4f4f4; } header { /* --header-bg-color: green; */ background-color: var(--header-bg-color); color: var(--header-txt-color); text-align: var(--header-txt-align); } .container { display: flex; margin: auto; max-width: var(--container-max); } .box { padding: 1rem; border-radius: 5px; background: var(--box-bg-color); color: var(--box-txt-color); margin: 1rem; box-shadow: var(--box-shadow-h-offset) var(--box-shadow-v-offset) var(--box-shadow-blur) var(--box-shadow-color); } .box-1 { flex: var(--box-1-width); } .box-2 { flex: var(--box-2-width); } </textarea> </div> <div class="col-12 card p-4 shadow blog_left__div tabcontent" id="About"> <textarea cols="100" id="htmlText" readonly="" rows="20" style="height: auto; resize: none; width: 100%;"> </textarea> </div> </div> </div> <!-- Right ; part --> <div class="col-lg-3 col-md-7 col-11 justify-content-end m-lg-0 m-auto "> <div class="row gy-5 left_div__blog"> <!-- tags --> <div class=" right_div_post"> <div class="right_div__title py-4 pl-2 "> <h2>CODE</h2> </div> <div class="tags_main right_sub__div"> <a href="https://youtu.be/5p8e2ZkbOFU" target="_thapa" class="badge shadow text-capitalize"> html </a> <a href="#" class="badge shadow text-capitalize"> css </a> <a href="#" class="badge shadow text-capitalize"> js </a> </div> </div> <br> <div class=" right_div_post"> <div class="right_div__title py-4 pl-2 "> <h2>Follow Me</h2> </div> <div class="right_sub__div d-flex justify-content-around"> <a href="https://www.facebook.com/Bestwebcode-537405963870091" target="_blank"> <i class="fab fa-facebook-square fa-3x"></i></a> <a href="https://twitter.com/bestwebcode" target="_blank"> <i class="fab fa-3x fa-twitter-square"></i></a> <a href="https://www.linkedin.com/in/bestweb-code-64245b206/" target="_blank"> <i class="fab fa-3x fa-linkedin"></i></a> <a href="https://www.instagram.com/bestwebcode/" target="_blank"><i class="fab fa-3x fa-instagram"></i></a> <a href="#" target="_blank"> <i class="fab fa-3x fa-youtube-square"></i> </a> </div> </div><br> <!-- Design --> <div class=" right_div_post"> <div class="right_div__title py-4 pl-2 "> <h2>Design</h2> </div> <div class="right_sub__div"> <div class="row gx-3"> <div class="col-6"> <a href="design.html"> <figure> <img src="images/cocacola.png" class="img-fluid shadow"> </figure> </a> </div> <div class="col-6"> <a href="design.html"> <figure> <img src="images/traveling.jpg" class="img-fluid shadow"> </figure> </a> </div> <div class="col-6"> <a href="design.html"> <figure> <img src="images/cocacola.jpg" class="img-fluid shadow"> </figure> </a> </div> <!-- <div class="col-6"> <figure> <img src="https://images.pexels.com/photos/196659/pexels-photo-196659.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" class="img-fluid shadow"> </figure> </div> --> </div> </div> </div> <div class=" right_div_post"> <!-- <div class="right_div__title py-4 pl-2 "> <h2>Inspiration</h2> </div> <div class="right_sub__div"> <div class="row gx-3"> <div class="col-6"> <figure> <img src="https://images.pexels.com/photos/196659/pexels-photo-196659.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" class="img-fluid shadow"> </figure> </div> <div class="col-6"> <figure> <img src="https://images.pexels.com/photos/34140/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" class="img-fluid shadow"> </figure> </div> <div class="col-6"> <figure> <img src="https://images.pexels.com/photos/38547/office-freelancer-computer-business-38547.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" class="img-fluid shadow"> </figure> </div> <div class="col-6"> <figure> <img src="https://images.pexels.com/photos/196659/pexels-photo-196659.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" class="img-fluid shadow"> </figure> </div> </div> </div> --> </div> <!-- Follow Me --> <div class=" right_div_post"> <!-- <div class="right_div__title py-4 pl-2 "> <h2>Follow Me</h2> </div> <div class="right_sub__div d-flex justify-content-around"> <a href="#"> <i class="fab fa-facebook-square fa-3x"></i></a> <a href="https://www.instagram.com/vinodthapa55/" target="_thapa"> <i class="fab fa-3x fa-instagram"></i></a> <a href="#"> <i class="fab fa-3x fa-github-square"></i> </a> <a href="#"> <i class="fab fa-3x fa-twitter-square"></i></a> <a href="#"> <i class="fab fa-3x fa-youtube-square"></i> </a> <a href="#"> <i class="fab fa-3x fa-linkedin"></i></a> </div> --> </div> <!-- Subscribe --> <div class=" right_div_post"> <!-- <div class="right_div__title py-4 pl-2 "> <h2>Subscribe</h2> </div> <div class="right_sub__div"> <form> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Enter your e-mail below and get notified on the latest blog posts.</label> <input type="email" class="form-control mt-2" id="exampleFormControlInput1" placeholder="[email protected]"> </div> <div class="col-12"> <button class="subs_btn d-block" type="submit">Subscribe</button> </div> </form> </div> --> </div> </div> </div> </div> </div> </div> </div> <footer> <div class="main-content"> <div class="left box"> <h2>About us</h2> <div class="content "> <p>BestWebCode is a blog where you can show HTML, CSS, and JavaScript along with creative Design .</p> </div> </div> <div class="right box"> <h2>Contact us</h2> <div class="content"> <div class="right_sub__div d-flex justify-content-around"> <a href="https://www.facebook.com/Bestwebcode-537405963870091" target="_blank"> <i class="fab fa-facebook-square fa-3x"></i></a> <a href="https://twitter.com/bestwebcode" target="_blank"> <i class="fab fa-3x fa-twitter-square"></i></a> <a href="https://www.linkedin.com/in/bestweb-code-64245b206/" target="_blank"> <i class="fab fa-3x fa-linkedin"></i></a> <a href="https://www.instagram.com/bestwebcode/" target="_blank"><i class="fab fa-3x fa-instagram"></i></a> <a href="#" target="_blank"> <i class="fab fa-3x fa-youtube-square"></i> </a> </div> </div> </div> </div> </div> <div class="bottom"> <center> <span class="credit">Created By <a href="https://www.bestwebcode.com">BestWebCode</a> | </span> <span class="far fa-copyright"></span><span> 2020 All rights reserved. | <a href="Privacypolicy.html" > Privacy Policy </a> </span> </center> </div> </footer> <!-- Close Footer --> <script> function openPage(pageName, elmnt, color) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablink"); for (i = 0; i < tablinks.length; i++) { tablinks[i].style.backgroundColor = ""; } document.getElementById(pageName).style.display = "block"; elmnt.style.backgroundColor = color; } // Get the element with id="defaultOpen" and click on it document.getElementById("defaultOpen").click(); </script> <!-- Optional JavaScript --> <!-- Popper.js first, then Bootstrap JS --> <script> const mobileBtn = document.getElementById('mobile-cta') nav = document.querySelector('nav') mobileBtnExit = document.getElementById('mobile-exit'); mobileBtn.addEventListener('click', () => { nav.classList.add('menu-btn'); }) mobileBtnExit.addEventListener('click', () => { nav.classList.remove('menu-btn'); }) </script> </body> </html>
### GPT名称:SEO常见问题生成器 [访问链接](https://chat.openai.com/g/g-dfPL6ukjO) ## 简介:准备用于SEO的常见问题结构化数据的JSON-LD代码 ![头像](../imgs/g-dfPL6ukjO.png) ```text Claro, aquí tienes el contenido anterior en forma de lista numerada, manteniendo el idioma original: 1. Actúa como un experto SEO y programador. En base a una palabra clave principal debes ser capaz de analizar el tema en cuestión y poder detectar las preguntas frecuentes asociadas a dicho tema. El objetivo es que esas respuestas de preguntas frecuentes resuelvan las posibles dudas a la intención de búsqueda de la palabra clave principal. 2. Sé preciso en tus respuestas, no añadas temas que no estén directamente relacionados. 3. Sigue las directrices para esto: 4. Los datos estructurados son un formato estandarizado con el que se puede proporcionar información sobre una página y clasificar su contenido. Consulta cómo funcionan los datos estructurados si aún no te has familiarizado con ellos. 5. Directrices de contenido: Usa FAQPage solo si tu página tiene una sección de preguntas frecuentes en la que hay una única respuesta a cada pregunta. Si en tu página hay solo una pregunta y los usuarios pueden enviar varias respuestas, usa mejor QAPage. Ejemplos: a. Casos prácticos que son válidos: - Páginas de preguntas frecuentes del mismo creador que el sitio web donde los usuarios no pueden enviar más respuestas. - Páginas de asistencia de un producto en las que hay preguntas frecuentes, pero donde los usuarios no pueden enviar más respuestas. b. Casos prácticos que no son válidos: - Página de foros donde los usuarios pueden enviar varias respuestas a una misma pregunta. - Páginas de asistencia de un producto donde los usuarios pueden enviar varias respuestas a una misma pregunta. - Páginas de productos en la que los usuarios pueden enviar varias preguntas y respuestas sin salir de la página. 6. No utilices FAQPage con fines publicitarios. 7. Comprueba que en cada elemento Question se incluye el texto completo de la pregunta y que en cada elemento Answer se incluye el texto completo de la respuesta. Se puede mostrar el texto completo de la pregunta y el texto de la respuesta. 8. El contenido de preguntas y respuestas no se puede mostrar como un resultado enriquecido si incluye alguno de estos tipos de contenido: obsceno, soez, sexualmente explícito, gráficamente violento, que promocione actividades peligrosas o ilegales, o lenguaje de odio o acoso. 9. Los usuarios deben poder ver todo el contenido de FAQ en la página de origen. Ejemplos: a. Casos prácticos que son válidos: - La pregunta y la respuesta se pueden ver en la página. - La pregunta se puede ver en la página y la respuesta está oculta en una sección desplegable en la que el usuario puede hacer clic para que la respuesta aparezca. b. Casos prácticos que no son válidos: el usuario no puede encontrar el contenido de preguntas frecuentes en la página. 10. Si en tu sitio web hay contenido de preguntas frecuentes que se repite (es decir, si la misma pregunta y respuesta aparecen en varias páginas), marca el contenido solamente una vez. 11. Definiciones de tipos de datos estructurados: Debes incluir las propiedades obligatorias para que tu contenido pueda mostrarse como un resultado enriquecido. Si quieres, puedes especificar también las propiedades recomendadas para añadir más información estructurada a tus datos, lo que quizá mejore la experiencia de los usuarios. 12. FAQPage: Puedes leer la definición completa de FAQPage en schema.org. a. El tipo FAQPage indica que la página corresponde a preguntas frecuentes con respuestas. Debe haber una definición de tipo FAQPage por página. b. Las propiedades que admite Google son las siguientes: i. Propiedades obligatorias - mainEntity: Question Indica una serie de elementos de Question que comprenden la lista de preguntas respondidas de las que trata el objeto FAQPage. Debes especificar al menos un elemento Question válido. Un elemento Question incluye la pregunta y la respuesta. 13. Question: La definición completa de Question está en schema.org. a. El tipo Question define cada pregunta respondida dentro de una página de preguntas frecuentes. Cada instancia de Question debe estar dentro de la matriz de propiedades mainEntity de schema.org/FAQPage. b. Las propiedades que admite Google son las siguientes: i. Propiedades obligatorias - acceptedAnswer: Answer Es la respuesta a la pregunta. Debe haber una por pregunta. - name: Text Es el texto completo de la pregunta. Por ejemplo, "¿Cuánto tiempo lleva procesar un reembolso?". 14. Answer: La definición completa de Answer está en schema.org. a. El tipo Answer define el objeto acceptedAnswer que corresponde a cada Question de esta página. b. Las propiedades que admite Google son las siguientes: i. Propiedades obligatorias - text: Text Es la respuesta completa a la pregunta. La respuesta puede incluir contenido HTML, como enlaces y listas. En la Búsqueda de Google se muestran las siguientes etiquetas HTML: <br>, <ol>, <ul>, <li>, <a>, <p>, <div>, <b>, <strong>, <i>, <em> y de <h1> a <h6>. Todas las demás etiquetas se ignoran. 15. Monitorizar resultados enriquecidos con Search Console: Search Console es una herramienta que te ayuda a monitorizar el rendimiento de tus páginas en la Búsqueda de Google. No hace falta que te registres en Search Console para que tu sitio web aparezca en los resultados de la Búsqueda de Google, pero, si lo haces, sabrás cómo lo ve Google y qué puedes hacer para mejorarlo. Te recomendamos que consultes Search Console en los siguientes casos: a. Después de implementar datos estructurados por primera vez. b. Una vez que Google haya indexado tus páginas, puedes comprobar si hay algún problema en el informe de estado de resultados enriquecidos correspondiente. Lo ideal es que haya un aumento en el número de elementos válidos y que no lo haya en el número de elementos no válidos. Si detectas problemas en tus datos estructurados, haz lo siguiente: 16. Devuelve el código siempre en este formato listo para copiar: <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{ "@type": "Question", "name": "How to find an apprenticeship?", "acceptedAnswer": { "@type": "Answer", "text": "<p>We provide an official service to search through available apprenticeships. To get started, create an account here, specify the desired region, and your preferences. You will be able to search through all officially registered open apprenticeships.</p>" } }, { "@type": "Question", "name": "Whom to contact?", "acceptedAnswer": { "@type": "Answer", "text": "You can contact the apprenticeship office through our official phone hotline above, or with the web-form below. We generally respond to written requests within 7-10 days." } }] } </script> 17. No hagas nada más, tu único trabajo es analizar, crear y mejorar el fichero JSON para su uso como FAQ de marcado schema. ```
// // VideoFullScreenBottomPopup.swift // gongmanse // // Created by 김우성 on 2021/06/21. // import UIKit import BottomPopup protocol VideoFullScreenBottomPopupControllerDelegate: AnyObject { func bottomPopupSwitchingSubtitleInFullScreenVC(subtitleOn: Bool) func bottomPopupPresentPlayrateBottomPopUpInFullScreenVC() } class VideoFullScreenBottomPopupController: BottomPopupViewController { // MARK: - Properties weak var delegate: VideoFullScreenBottomPopupControllerDelegate? public var currentStateSubtitle = true public var currentStateIsVideoPlayRate = "기본" var tableView = UITableView() var topView = UIView() private let popupImageView: UIImageView = { let imageView = UIImageView() let image = UIImage(systemName: "slider.horizontal.3")?.withTintColor(.black, renderingMode: .alwaysOriginal) imageView.image = image return imageView }() private let titleLabel: UILabel = { let label = UILabel() label.text = "설정" label.font = UIFont.appBoldFontWith(size: 14) return label }() private let dismissButton: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "largeX"), for: .normal) button.addTarget(self, action: #selector(handleDissmiss), for: .touchUpInside) return button }() private let bottomBorderLine: UIView = { let view = UIView() view.backgroundColor = .mainOrange return view }() let fullScreenHeight = Constant.height var height: CGFloat = 44 * 3 var topCornerRadius: CGFloat = 0 var presentDuration: Double = 0.22 var dismissDuration: Double = 0.22 var shouldDismissInteractivelty: Bool = true override var popupHeight: CGFloat { return (44 * 3) } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() configureUI() } // MARK: - Actions @objc func handleDissmiss() { self.dismiss(animated: true) } @objc func handleSwitchingSubtitleIsOn(_ sender: Notification) { } @objc func handleChangingVideoPlayRate(_ sender: Notification) { } override open var shouldAutorotate: Bool { return false } // MARK: - Helpers func configureUI() { /* topView */ view.backgroundColor = .white view.addSubview(topView) topView.backgroundColor = .white topView.setDimensions(height: 44, width: view.frame.width) topView.anchor(top: view.topAnchor, left: view.leftAnchor) // - 최상단 좌측 아이콘 topView.addSubview(popupImageView) popupImageView.setDimensions(height: 25, width: 25) popupImageView.centerY(inView: topView) popupImageView.anchor(left: topView.leftAnchor, paddingLeft: 20) // - 중단 "옵션" 레이블 topView.addSubview(titleLabel) titleLabel.setDimensions(height: 25, width: view.frame.width * 0.77) titleLabel.centerY(inView: topView) titleLabel.anchor(left: popupImageView.rightAnchor, paddingLeft: 7.4) // - 최상단 우측 "X" 버튼 topView.addSubview(dismissButton) dismissButton.setDimensions(height: 25, width: 25) dismissButton.centerY(inView: topView) dismissButton.anchor(right: topView.rightAnchor, paddingRight: 20) // - 하단 경계선 레이블 topView.addSubview(bottomBorderLine) bottomBorderLine.setDimensions(height: 2.25, width: view.frame.width) bottomBorderLine.anchor(left: topView.leftAnchor, bottom: topView.bottomAnchor) /* tableView */ view.addSubview(tableView) tableView.setDimensions(height: 44 * 2, width: view.frame.width) tableView.anchor(top: topView.bottomAnchor, left: view.leftAnchor) tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView() tableView.separatorStyle = .singleLine tableView.isScrollEnabled = false tableView.register(VideoPlayRateCell.self, forCellReuseIdentifier: VideoPlayRateCell.reusableIdentifier) tableView.register(DisplaySubtitleCell.self, forCellReuseIdentifier: DisplaySubtitleCell.reusableIdentifier) } } // MARK: - UITableViewDelegate, UITableViewDataSource extension VideoFullScreenBottomPopupController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView .dequeueReusableCell(withIdentifier: DisplaySubtitleCell.reusableIdentifier, for: indexPath) as! DisplaySubtitleCell cell.isOn = currentStateSubtitle return cell } else { let cell = tableView .dequeueReusableCell(withIdentifier: VideoPlayRateCell.reusableIdentifier, for: indexPath) as! VideoPlayRateCell cell.stateText = self.currentStateIsVideoPlayRate return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 자막 유뮤를 결정하는 cell if indexPath.row == 0 { if currentStateSubtitle { currentStateSubtitle = false // VideoFullScreenController의 자막의 alpha값을 0으로 한다. } else { currentStateSubtitle = true // VideoFullScreenController의 자막의 alpha값을 1으로 한다. } delegate?.bottomPopupSwitchingSubtitleInFullScreenVC(subtitleOn: currentStateSubtitle) tableView.reloadData() } else { // 재생속도를 결정하는 cell dismiss(animated: true) { // 새로운 재생속도 BottomPopup을 호출한다. self.delegate?.bottomPopupPresentPlayrateBottomPopUpInFullScreenVC() } } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./css/style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <!-- START HEADER --> <header class="margin-bottom"> <div class="container"> <div class="row-header"> <div class="col-header"> <div class="link-header"> <a href="#">Donna</a> <a href="#">Uomo</a> <a href="#">Bambini</a> </div> <div class="logo"> <img class="image" src="./img/boolean-logo.png" alt="logo-boolean"> </div> <div class="symbol"> <i class="fa-regular fa-user"></i> <i class="fa-regular fa-heart"></i> <i class="fa fa-lock" aria-hidden="true"></i> </div> </div> </div> </div> </header> <!-- START MAIN --> <main> <div class="container"> <div class="row-main"> <div class="col-main"> <div class="content-main"> <div class="photo"> <div class="position-absolute"> <span class="background red text-white">-50%</span> <span class="background green text-white">Sostenibilità</span> </div> <div class="heart">&hearts;</div> <img src="./img/1.webp" alt="web1"> <div class="overlay"> <div class="position-absolute"> <span class="background red text-white">-50%</span> <span class="background green text-white">Sostenibilità</span> </div> <div class="heart-red">&hearts;</div> <img src="./img/1b.webp" alt="bweb1"> </div> </div> <div class="under-content"> <div>Levi's</div> <h4>RELAXED FIT TEE UNISEX</h4> <div><span class="price">14,99 &euro;</span> <span class="price1">29,99 &euro;</span></div> </div> </div> </div> <div class="col-main"> <div class="content-main"> <div class="photo"> <div class="position-absolute"> <span class="background red text-white">-30%</span> </div> <div class="heart">&hearts;</div> <img src="./img/2.webp" alt="web2"> <div class="overlay"> <div class="position-absolute"> <span class="background red text-white">-30%</span> </div> <div class="heart-red">&hearts;</div> <img src="./img/2b.webp" alt="bweb2"> </div> </div> <div class="under-content"> <div>Guess</div> <h4>ROSES TEE</h4> <div><span class="price">20,99 &euro;</span> <span class="price1">29,99 &euro;</span></div> </div> </div> </div> <div class="col-main"> <div class="content-main"> <div class="photo"> <div class="position-absolute"> <span class="background red text-white">-30%</span> </div> <div class="heart">&hearts;</div> <img src="./img/3.webp" alt="web3"> <div class="overlay"> <div class="position-absolute"> <span class="background red text-white">-30%</span> </div> <div class="heart-red">&hearts;</div> <img src="./img/3b.webp" alt="bweb3"> </div> </div> <div class="under-content"> <div>Come Zucchero Filato</div> <h4>VOGLIO DI COLORE PASTELLO</h4> <div><span class="price">129,99 &euro;</span> <span class="price1">184,99 &euro;</span></div> </div> </div> </div> </div> <div class="row-main"> <div class="col-main"> <div class="content-main"> <div class="photo"> <div class="position-absolute"> <span class="background red text-white">-50%</span> <span class="background green text-white">Sostenibilità</span> </div> <div class="heart">&hearts;</div> <img src="./img/4.webp" alt="web4"> <div class="overlay"> <div class="position-absolute"> <span class="background red text-white">-50%</span> <span class="background green text-white">Sostenibilità</span> </div> <div class="heart-red">&hearts;</div> <img src="./img/4b.webp" alt="bweb4"> </div> </div> <div class="under-content"> <div>Levi's</div> <h4>THE UNISEX</h4> <div><span class="price">14,99 &euro;</span> <span class="price1">29,99 &euro;</span></div> </div> </div> </div> <div class="col-main"> <div class="content-main"> <div class="photo"> <div class="heart">&hearts;</div> <img src="./img/5.webp" alt="web5"> <div class="overlay"> <div class="heart-red">&hearts;</div> <img src="./img/5b.webp" alt="bweb5"> </div> </div> <div class="under-content"> <div>Maya Deluxe</div> <h4>STRIPE BODICE</h4> <div><span class="price">99 ,99 &euro;</span></div> </div> </div> </div> <div class="col-main"> <div class="content-main"> <div class="photo"> <div class="position-absolute"> <span class="background green text-white">Sostenibilità</span> </div> <div class="heart">&hearts;</div> <img src="./img/6.webp" alt="web6"> <div class="overlay"> <div class="position-absolute"> <span class="background green text-white">Sostenibilità</span> </div> <div class="heart-red">&hearts;</div> <img src="./img/6b.webp" alt="bweb6"> </div> </div> <div class="under-content"> <div>Esprit</div> <h4>MAGLIONE - BLACK</h4> <div><span class="price">29,99 &euro;</span></div> </div> </div> </div> </div> </div> </main> <!-- START FOOTER --> <footer> <div class="container"> <div class="row-footer"> <div class="col-footer"> <div class="col-content-left"> <div class="pagraph-left text-white"> <h4>Booleando s.r.l</h4> <span>Informazioni legali</span> <span>Informazioni sulla privacy</span> <span>Diritto di recesso</span> </div> </div> <div class="col-content-right"> <div class="pagraph-right text-white"> <div>Trovaci anche su</div> <i class="fa-brands fa-square-twitter"></i> <i class="fa-brands fa-square-facebook"></i> <i class="fa-brands fa-square-instagram"></i> <i class="fa-brands fa-square-pinterest"></i> <i class="fa-brands fa-square-youtube"></i> </div> </div> </div> </div> </div> </footer> </body> </html>
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Arrays</title> <script> const carros = ['Gol', 'Fusca', 'Virtus', 'Opala'] console.table(carros) carros.push('Corola') console.table(carros) carros.unshift('Civic') console.table(carros) carros.pop() const car = carros.pop() const carro = carros.shift() console.table(carros) console.table(carro) console.table(car) carros.splice(1,0, 'Uno') /* splice serve para: Excluir itens a partir de uma posiçao ex: carros.splice(2, 3) -> exclui 3 itens a partir da posiçao 2 inserir itens a partir de uma posiçao ex: carros.splice(3, 0, 'Uno') -> adiciona o item 'uno' na posiçao 3 alterar itens a partir de uma posiçao ex: carros.splice(1, 1, 'Uno') -> adicionar o item 'Uno' na posiçao 1 após apagar o item que lá estava */ console.table(carros) </script> </head> <body> </body> </html>
import { Request, Response } from 'express'; import Agent from '../database/schemas/Valorant-Agent'; import { agents } from '../utils/agentList'; import { mountAgentData } from '../utils/mountAgentData'; import { mountNewAgentData } from '../utils/mountNewAgentData'; import { Role } from '../types/agentType'; import { addAllAgentsFunction } from '../utils/addAllAgentsFunction'; // ! Controller that adds the agents, will cause error export const addAllAgents = async (req: Request, res: Response) => { try { const result = await addAllAgentsFunction(); res.send({ status: 'ok', champios: result }); } catch (error) { console.log(error); res.send({ status: 'erro' }); } }; // ? Controller that returns all agents. export const getAllAgents = async (req: Request, res: Response) => { try { const agents = await Agent.find({}); console.log('Agentes: ', agents); res.send({agents}); } catch (error) { console.log('error'); res.status(404); } } // ? Controller that returns a random champion export const getRandomAgent = async (req: Request, res: Response) => { const { role } = req.body; try { const match = mountAgentData({ role }); const result = await Agent.aggregate([ { $match: match }, { $sample: { size: 1 } }, ]); if(result.length > 0) return res.send({ requirements: match, result }); res.status(404).send({requirements: match, status: 'There is none agent with your requirements.'}); } catch (error) { console.log(error); res.status(400).send({ status: 'error' }); } }; // ? Controller that adds a new champion in the data base export const addNewAgent = async (req: Request, res: Response) => { const { name } = req.body; const role = req.body.role as Role; if(!role || !name) return res.status(400).send({status: 'error', message: 'Please, send the agent role and name.'}); if(role !== 'controller' && role !== 'duelist' && role !== 'initiator' && role !== 'sentinel') return res.status(400).send({status: 'error', message: 'Please, send a valid role'}); try { const match = mountNewAgentData({name, role}); const result = await Agent.create(match); res.status(200).send({status: 'OK', newAgent: result}); } catch (error) { console.log(error); res.status(400).send({status: 'error', message: error}); } } // Controller that deletes a agent export const deleteAgent = async (req: Request, res: Response) => { const name = req.body.name; if(!name) return res.status(400).send({status: 'error', message: 'Please, send the agent\'s name.'}); try { const result = await Agent.findOne({name}); console.log('Apagando o agente: ', result); if(result === null) return res.status(404).send({status: 'error', message: `There is no ${name} agent in DB`}); await result?.deleteOne(); res.status(201).send({status:'OK', message: `${name} was deleted`}); } catch(error) { console.log(error); res.status(400).send({status: 'error'}); } }
# Point Token Command Line Interface (CLI) This repo contains a Node-based command line interface for interacting with the POINT Token System. The POINT Token System is a multi-tenant, decentralized loyalty and rewards system that runs on the Ethereum Blockchain. To learn more about the POINT Token System, go to [http://www.pointtoken.io](http://www.pointtoken.io). The website has a white paper which thoroughly outlines how the system works. ## Installation Clone the repo. Install the dependencies as follows: ```bash npm install ``` ## Configuration All configuration properties can be found and set in **config.js**. This includes which Ethereum network you are connecting to and what address you are sending transactions as. If you want to use the CLI to write to the Ethereum blockchain, you will need to specify an address and a private key. Write-able transactions do require gas. If you only want to query the blockchain, you don't have to provide an address or private key. ## Usage All commands can be called as follows: ```bash node index.js [command] [arguments] ``` The following commands are supported: ```bash addAward <awardId> ``` If you have been provisioned as an AWARDER, you can use this command to add an AWARD to the system. AWARDS are unsigned integers. Once you have claimed that integer, it is owned by the address that claimed it forever. Returns a transaction ID. Requires gas. ```bash getAward <awardId> ``` You can use this command to determine the address that owns an AWARD. Useful when adding awards so that you don't burn gas trying to claim an AWARD id that is already in use. Returns the address that owns the AWARD. Does not require gas. ```bash isAwarder <address> ``` Pass an Ethereum address. Returns a boolean indicating if that address has the privilege to issue AWARDS in the system. Does not require gas. ```bash getAchievements <address> ``` Pass an Ethereum address to determine which AWARDS an address has earned. Returns the AWARD ID of each achievement earned. Does not require gas. ```bash balanceOf <address> ``` Pass an Ethereum address to determine the number of POINT tokens earned by this address. Does not require gas. ```bash awardAchievement <address> <awardId> <amount> <checkIfEarned> ``` Use this command to award an achievement. This can only be issued by an address that has been provisioned as an AWARDER. If the AWARDER also wants to issue POINT tokens, they can be issued by passing the <amount> parameter. If you want to issue an AWARD without issuing any POINTS, pass zero. If you want the command to fail if the person has already earned the achievement, pass **true** for the <checkIfEarned> command. Returns a transaction ID. Requires gas.
import React from "react"; import { MdPreview, MdEdit, MdDelete, MdCollections } from "react-icons/md"; import { useMutation, useQueryClient } from "react-query"; import { Link } from "react-router-dom"; import { toast } from "react-toastify"; import api from "../../api/api"; import { conf } from "../appConfirm"; const ProductCard = ({ id, img = "", name = "", description = "", setProducts, setProductID, setIsSpecificOpen, search = "", }) => { const queryClient = useQueryClient(); const handleSpecifics = () => { setProductID(id); setIsSpecificOpen(true); }; const handleDelete = async () => { let result = await conf(`Are you sure you want to delete ${name}?`); if (!result) { return; } try { await api.delete(`/products/${id}/delete`); // setProducts((old) => ({ // ...old, // data: old?.data?.filter((product) => product.id !== id), // })); toast.success("product deleted successfully"); queryClient.setQueryData(["admin-products", search], (oldQueryData) => { return { ...oldQueryData, pages: oldQueryData.pages.map((page) => ({ ...page, data: { ...page.data, data: page.data.data.filter((d) => d.id !== id), }, })), }; }); } catch (error) { if (error?.response?.status === 403) { toast.error("Unauthorized"); } else if (error?.response?.status === 404) { toast.error("Product does not exist"); } else { toast.error("An internal error occured"); } } }; return ( <div className="flex flex-col overflow-hidden justify-between pb-3 bg-white ring-1 ring-lightGray/50 shadow-lg shadow-light rounded-md w-64 h-96 transition duration-300 hover:scale-105"> <img className="w-full h-full bg-gradient-to-t from-warning/80 to-info/80" src={img} alt="product's image is not available" /> <div className="flex flex-col h-36 justify-end px-2 "> <h3 className="text-lg font-medium">{name}</h3> <h5 className="text-base text-dark mb-2">{description}</h5> <div className="flex gap-4 items-center justify-center"> {/* <MdPreview className="text-info w-7 h-7 cursor-pointer" /> */} <MdCollections onClick={handleSpecifics} className="text-info w-7 h-7 cursor-pointer" /> <Link to={`/admin/products/edit/${id}`}> <MdEdit className="text-warning w-7 h-7 cursor-pointer" /> </Link> <MdDelete onClick={handleDelete} className="text-danger w-7 h-7 cursor-pointer" /> </div> </div> </div> ); }; export default ProductCard;
import React from "react"; import JavaScript from "../assets/javascript.png"; import ReactImg from "../assets/react.png"; import Node from "../assets/node.png"; import Nextjs from "../assets/nextjs.png"; import GitHub from "../assets/github.png"; import Tailwind from "../assets/tailwind.png"; import CSS from "../assets/css.png"; import HTML from "../assets/html.png"; import MySQL from "../assets/mysql.png"; import mongoDB from "../assets/mongodb.png"; const Skills = () => { return ( <div name="skills" className="w-full h-screen text-[var(--color4)] duration-300 bg-[var(--color1)] sm:rounded-tr-[400px] shadow-lg shadow-[var(--color3)] dark:text-orange-200 dark:shadow-none dark:bg-transparent" > {/*//! Container */} <div className="max-w-[1000px] w-full h-full mx-auto items-center p-4 flex flex-col justify-center "> <div className="text-justify"> <p className="text-4xl font-bold inline border-b-4 border-[var(--color4)] text-[var(--color3)] dark:text-orange-200 dark:border-orange-500"> Skills and knowledge </p> <p data-aos="fade-left" data-aos-duration="1000" className="py-4"> Since I directed my profile towards web development, I have been studying and practicing a lot about all the technologies listed below. And it's also good to mention that I have knowledge of web SEO & Blockchain, and I'm an Industrial Engineer. </p> <p data-aos="fade-left" data-aos-duration="1000"> These are the main technologies I've worked with: </p> {/* <p data-aos="fade-left" data-aos-duration="1000"> (I'm currently learning Next.js 💪🏻) </p> */} </div> <div className="mt-3 w-full grid grid-cols-2 sm:grid-cols-4 gap-4 text-center py-8 shadow-lg shadow-slate-400 bg-[var(--color1)] rounded-[80px] dark:shadow-none dark:bg-transparent"> {/*//! HTML */} <div data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" // className="shadow-md shadow-slate-600 hover:scale-110 duration-500 rounded-full" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={HTML} alt="HTML icon" /> <p className="font-bold">Tattoo Machine</p> </div> {/*//! CSS */} <div data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={CSS} alt="HTML icon" /> <p className="font-bold">Paint Spray</p> </div> {/*//! JAVASCRIPT */} <div data-aos-duration="2000" data-aos-delay="500" data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={JavaScript} alt="HTML icon" /> <p className="font-bold">Brush</p> </div> {/*//! REACT */} <div data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={ReactImg} alt="HTML icon" /> <p className="font-bold">Pencil</p> </div> {/*//! NODE JS */} <div data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={Node} alt="HTML icon" /> <p className="font-bold">Marker</p> </div> {/*//! MYSQL */} <div data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={MySQL} alt="mysql icon" /> <p className="font-bold">Whiteboard</p> </div> {/*//! MONGODB */} <div data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={mongoDB} alt="mongodb icon" /> <p className="font-bold">Watercolors</p> </div> {/*//! TAILWIND */} <div data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={Tailwind} alt="HTML icon" /> <p className="font-bold">Acrylics</p> </div> {/*//! GITHUB */} {/* <div data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={GitHub} alt="HTML icon" /> <p className="font-bold">GitHub</p> </div> */} {/*//! NEXT */} {/* <div // className="shadow-md shadow-[#040c16] hover:scale-110 duration-500" data-aos={window.innerWidth < 700 ? "zoom-in" : "flip-left"} data-aos-duration="2000" data-aos-delay="500" > <img className="w-20 mx-auto hover:scale-110 duration-500" src={Nextjs} alt="HTML icon" /> <p className="font-bold">Next JS</p> </div> */} </div> </div> </div> ); }; export default Skills;
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { StudentService } from './student.service'; import { MainComponent } from './components/main.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { AddComponent } from './components/add.component'; import { LoginComponent } from './components/login.component'; import { LoginStatusComponent } from './components/login-status.component'; import { Router, RouterModule, Routes } from '@angular/router'; import { OKTA_CONFIG, OktaAuthModule, OktaCallbackComponent, OktaAuthGuard } from '@okta/okta-angular'; import myAppConfig from './config/my-app-config'; import { TeachersComponent } from './components/teachers.component'; import { HeaderComponent } from './components/header.component'; import { EmailComponent } from './components/email.component'; const oktaConfig = Object.assign({ onAuthRequired: (oktaAuth, injector) => { const router = injector.get(Router); // redirect to main user page router.navigate(['/login']); } }, myAppConfig.oidc); const routes: Routes = [ { path: 'login/callback', component: OktaCallbackComponent}, { path: '', component: MainComponent }, { path: 'teachers', component: TeachersComponent, canActivate: [ OktaAuthGuard ]}, { path: 'add', component: AddComponent, canActivate: [ OktaAuthGuard ]}, { path: 'login', component: LoginComponent}, { path: 'mail', component: EmailComponent, canActivate: [ OktaAuthGuard ]}, { path: '**', redirectTo: 'login', pathMatch: 'full'} ] @NgModule({ declarations: [ AppComponent, MainComponent, AddComponent, LoginComponent, LoginStatusComponent, TeachersComponent, HeaderComponent, EmailComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, OktaAuthModule, FormsModule, ReactiveFormsModule, NgbModule, RouterModule.forRoot(routes), ], providers: [StudentService, { provide: OKTA_CONFIG, useValue: oktaConfig }, //{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorService, multi: true } ], // token for HTTP interceptors // mulit: true cos we can have multiple interceptors bootstrap: [AppComponent] }) export class AppModule { }
// HRDotNet-Mobile // Designed by : Alex Diane Vivienne Candano // Developed by: Patrick William Quintana Lofranco, Jessie Cuerda import { View, Text, StyleSheet, ActivityIndicator, Linking } from "react-native"; import { Shadow } from "react-native-shadow-2"; import CachedImage from "expo-cached-image"; import { useRoute } from "@react-navigation/native"; import { COLORS } from "../../../../../../constant"; import Hr from "../../../../../../components/use/Hr" import PageHeader from "../../../../../../components/header/PagesHeader"; export default function ContactInfo ({ navigation}) { const route = useRoute() const params = route.params const phoneNum = params?.contactNumber const emailAddress = params?.emailAddress const onHandlePhoneNumPress = (phoneNum) => { const dialNumber = `tel:${phoneNum}` Linking.openURL(dialNumber) } const onHandleEmailAddPress = (emailAddress) => { const sendEmail = `mailto:${emailAddress}` Linking.openURL(sendEmail) } return ( <View style={styles.main}> <PageHeader pageName={'Contact Information'} /> <View style={styles.container}> <Shadow distance={4} style={styles.shadowView}> <View style={styles.centerView}> <CachedImage source={{ uri: params.uri }} cacheKey={`contactsImage-${params.name}`} style={styles.userProfile} placeholderContent={ <ActivityIndicator size={'small'} color={COLORS.powderBlue} style={{ marginBottom: 30 }} /> } /> <Text style={styles.boldText}>{params?.name}</Text> <Text style={styles.regularText}>{params?.position}</Text> </View> <Text style={styles.grayTitle}>Contact Number</Text> <Hr/> <Text style={[styles.semiBoldText, { marginBottom: 20 }]} onPress={() => onHandlePhoneNumPress(phoneNum)} > {phoneNum} </Text> <Text style={styles.grayTitle}>Email Address</Text> <Hr /> <Text style={styles.semiBoldText} onPress={() => onHandleEmailAddPress(emailAddress)} > {emailAddress} </Text> </Shadow> </View> </View> ) } const styles = StyleSheet.create({ main: { flex: 1, backgroundColor: COLORS.clearWhite, }, container: { padding: 30, backgroundColor: COLORS.clearWhite, }, shadowView: { padding: 30, width: '100%', borderRadius: 20, }, centerView: { justifyContent: 'center', alignItems: 'center', marginBottom: 30, }, userProfile: { width: 130, height: 130, borderRadius: 90, marginBottom: 20, }, grayTitle: { fontFamily: 'Inter_500Medium', fontSize: 14, color: COLORS.darkGray }, boldText: { fontFamily: 'Inter_700Bold', fontSize: 16, }, semiBoldText: { fontFamily: 'Inter_600SemiBold', color: COLORS.blue, fontSize: 14 }, regularText: { fontFamily: 'Inter_400Regular', fontSize: 13, } })
using System; using System.Collections.Generic; using Server.Mobiles; using Server.Network; using Server.Spells; using Server.Spells.Necromancy; namespace Server.Items { /// <summary> /// Make your opponent bleed profusely with this wicked use of your weapon. /// When successful, the target will bleed for several seconds, taking damage as time passes for up to ten seconds. /// The rate of damage slows down as time passes, and the blood loss can be completely staunched with the use of bandages. /// </summary> public class BleedAttack : WeaponAbility { private static readonly Dictionary<Mobile, BleedTimer> m_BleedTable = new Dictionary<Mobile, BleedTimer>(); public BleedAttack() { } public override int BaseMana { get { return 10; } } public static bool IsBleeding(Mobile m) { return m_BleedTable.ContainsKey(m); } public static void BeginBleed(Mobile m, Mobile from, bool splintering = false, int damage = 0) { BleedTimer timer = null; if (m_BleedTable.ContainsKey(m)) { if (splintering) { timer = m_BleedTable[m]; timer.Stop(); } else { return; } } BuffInfo.AddBuff(m, new BuffInfo(BuffIcon.Bleed, 1075829, 1075830, TimeSpan.FromSeconds(10), m, String.Format("{0}\t{1}\t{2}", "1", "10", "2"))); timer = new BleedTimer(from, m, CheckBloodDrink(from), damage); m_BleedTable[m] = timer; timer.Start(); from.SendLocalizedMessage(1060159); // Your target is bleeding! m.SendLocalizedMessage(1060160); // You are bleeding! if (m is PlayerMobile) { m.LocalOverheadMessage(MessageType.Regular, 0x21, 1060757); // You are bleeding profusely m.NonlocalOverheadMessage(MessageType.Regular, 0x21, 1060758, m.Name); // ~1_NAME~ is bleeding profusely } m.PlaySound(0x133); m.FixedParticles(0x377A, 244, 25, 9950, 31, 0, EffectLayer.Waist); } public static void DoBleed(Mobile m, Mobile from, int damage, bool blooddrinker) { if (m.Alive && !m.IsDeadBondedPet) { if (!m.Player) damage *= 2; m.PlaySound(0x133); m.Hits -= damage; //AOS.Damage(m, from, damage, false, 0, 0, 0, 0, 0, 0, 100, false, false, false); if (blooddrinker && from.Hits < from.HitsMax) { from.SendLocalizedMessage(1113606); //The blood drinker effect heals you. from.Heal(damage); } Blood blood = new Blood(); blood.ItemID = Utility.Random(0x122A, 5); blood.MoveToWorld(m.Location, m.Map); } else { EndBleed(m, false); } } public static void EndBleed(Mobile m, bool message) { Timer t = null; if (m_BleedTable.ContainsKey(m)) { t = m_BleedTable[m]; m_BleedTable.Remove(m); } if (t == null) return; t.Stop(); BuffInfo.RemoveBuff(m, BuffIcon.Bleed); if (message) m.SendLocalizedMessage(1060167); // The bleeding wounds have healed, you are no longer bleeding! } public static bool CheckBloodDrink(Mobile attacker) { return attacker.Weapon is BaseWeapon && ((BaseWeapon)attacker.Weapon).WeaponAttributes.BloodDrinker > 0; } public override void BeforeAttack(Mobile attacker, Mobile defender, int damage) { BaseWeapon weapon = attacker.Weapon as BaseWeapon; if (!Validate(attacker) || (!attacker.InRange(defender, weapon.MaxRange))) return; if( attacker is PlayerMobile ) { if( attacker.Stam < 10 ) return; attacker.Stam -= 10; } ClearCurrentAbility(attacker); if(defender is BaseCreature && ((BaseCreature)defender).BleedImmune) { attacker.SendLocalizedMessage(1062052); // Your target is not affected by the bleed attack! } else { attacker.SendLocalizedMessage(1060159); // Your target is bleeding! defender.SendLocalizedMessage(1060160); // You are bleeding! if (defender is PlayerMobile) { defender.LocalOverheadMessage(MessageType.Regular, 0x21, 1060757); // You are bleeding profusely defender.NonlocalOverheadMessage(MessageType.Regular, 0x21, 1060758, defender.Name); // ~1_NAME~ is bleeding profusely } } defender.PlaySound(0x133); defender.FixedParticles(0x377A, 244, 25, 9950, 31, 0, EffectLayer.Waist); double hitsBonus = 0.0; if( attacker is PlayerMobile ) { //레벨 체크 흡수 증가 PlayerMobile pm = attacker as PlayerMobile; //hitsBonus += pm.SilverPoint[2] * 0.02; } if( defender is BaseCreature ) { BaseCreature bc = defender as BaseCreature; //hitsBonus *= MonsterTier(bc); } //attacker.Hits += (int)( damage * 2 ); //hitsBonus ); Blood blood = new Blood(); blood.ItemID = Utility.Random(0x122A, 5); blood.MoveToWorld(defender.Location, defender.Map); AOS.Damage(defender, attacker, damage, true, 100, 0, 0, 0, 0, 0, 0, false, false, false); /* // Necromancers under Lich or Wraith Form are immune to Bleed Attacks. TransformContext context = TransformationSpellHelper.GetContext(defender); if ((context != null && (context.Type == typeof(LichFormSpell) || context.Type == typeof(WraithFormSpell))) || (defender is BaseCreature && ((BaseCreature)defender).BleedImmune) || Server.Spells.Mysticism.StoneFormSpell.CheckImmunity(defender)) { attacker.SendLocalizedMessage(1062052); // Your target is not affected by the bleed attack! return; } BeginBleed(defender, attacker); */ } private class BleedTimer : Timer { private readonly Mobile m_From; private readonly Mobile m_Mobile; private int m_Count; private int m_MaxCount; private int m_Damage; private readonly bool m_BloodDrinker; public BleedTimer(Mobile from, Mobile m, bool blooddrinker, int damage = 0 ) : base(TimeSpan.FromSeconds(2.0), TimeSpan.FromSeconds(2.0)) { m_From = from; m_Mobile = m; m_Damage = damage; Priority = TimerPriority.TwoFiftyMS; m_BloodDrinker = blooddrinker; m_MaxCount = Spells.SkillMasteries.ResilienceSpell.UnderEffects(m) ? 3 : 5; } protected override void OnTick() { if (!m_Mobile.Alive || m_Mobile.Deleted) { EndBleed(m_Mobile, true); } else { int damage = m_Damage; if (!Server.Spells.SkillMasteries.WhiteTigerFormSpell.HasBleedMod(m_From, out damage)) damage = Math.Max(1, Utility.RandomMinMax(5 - m_Count, (5 - m_Count) * 2)); DoBleed(m_Mobile, m_From, damage, m_BloodDrinker); if (++m_Count == m_MaxCount) EndBleed(m_Mobile, true); } } } } }
package com.noob.docker_boot.other.spring; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringBeanLifeCycleTest implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean { public SpringBeanLifeCycleTest() { System.out.println("我的构造方法执行了。。。。。。。。。。"); } private String name; @Value("张三") public void setName(String name) { System.out.println("setName 方法执行了。。。。。。。。"); } @Override public void setBeanName(String name) { System.out.println("(BeanNameAware)setBeanName 方法执行了。。。。。。。。"); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println("(BeanFactoryAware)setBeanFactory 方法执行了。。。。。。。。"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("(ApplicationContextAware)setApplicationContext 方法执行了。。。。。。。。"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("(InitializingBean)afterPropertiesSet 方法执行了。。。。。。。。"); } // 依赖注入完成后自动调用 @PostConstruct // 实际由 BeanPostProcessor 处理,是 jdk 定义的初始化注解 public void init() { System.out.println("(PostConstruct)init 方法执行了。。。。。。。。"); } @PreDestroy private void destroy() { System.out.println("(PreDestroy)destroy 方法执行了。。。。。。。。"); } /* 我的构造方法执行了。。。。。。。。。。 setName 方法执行了。。。。。。。。 (BeanNameAware)setBeanName 方法执行了。。。。。。。。 (BeanFactoryAware)setBeanFactory 方法执行了。。。。。。。。 (ApplicationContextAware)setApplicationContext 方法执行了。。。。。。。。 before 执行了 -> springBeanLifeCycleTest (PostConstruct)init 方法执行了。。。。。。。。 (InitializingBean)afterPropertiesSet 方法执行了。。。。。。。。 after 执行了 -> springBeanLifeCycleTest (PreDestroy)destroy 方法执行了。。。。。。。。 */ }
import React, { useContext, useEffect, useState } from "react"; import TodoContext from "../context/TodoContext"; function TaskFormTwo(props) { const init = { title: "", description: "", dueDate: "", }; const { isUpdate, data, changeUpdate } = props; const [formData, setFormData] = useState(init); const { createTask, user, updateTask } = useContext(TodoContext); useEffect(()=>{ if(isUpdate){ setFormData(data); } }, [data, isUpdate]) const handleChange = (e) => { const { name, value } = e.target; setFormData((prev) => ({ ...prev, [name]: value, userId: user?.id, createdOn: new Date() })); }; const onCreateTask = (e) => { e.preventDefault(); createTask(formData); }; const onUpdateTask = (e) => { e.preventDefault(); updateTask(formData); }; const onCancel = (e) => { e.preventDefault(); changeUpdate(); setFormData(init); }; return ( <div className="p-3 w-75"> <h3 className="text-white">{isUpdate ? "Update Task": "Create Task"}</h3> <div className="card bg-white"> <div className="card-body"> <form> <div className="mb-3"> <label className="form-label">Title</label> <input className="form-control" type="text" name="title" onChange={handleChange} value={formData?.title} /> </div> <div className="mb-3"> <label className="form-label">Description</label> <textarea className="form-control" rows="6" name="description" onChange={handleChange} value={formData?.description} ></textarea> </div> <div className="mb-3"> <label className="form-label">Due Date</label> <input className="form-control" type="datetime-local" name="dueDate" onChange={handleChange} value={formData?.dueDate} /> </div> { !isUpdate ? <button className="btn btn-primary" onClick={onCreateTask}> Create Task </button> : <> <button className="btn btn-primary me-2" onClick={onUpdateTask}>Update Task</button> <button className="btn btn-warning" onClick={onCancel}>Cancel</button> </> } </form> </div> </div> </div> ); } export default TaskFormTwo;
import {useState} from "react"; import {CheckBoxInterface} from "../types"; import InteractiveElement from "./InteractiveElement"; const CheckBox = (props: CheckBoxInterface) => { const [checkboxStatus, setCheckboxStatus] = useState("enabled") const handleClick = () => { if (checkboxStatus === "enabled") { setCheckboxStatus("disabled") } else { setCheckboxStatus("enabled") } } const simplifyEmojiOutput = () => { if (props.emoji.checkedEmoji && props.emoji.uncheckedEmoji) { return <span className={props.customClassName ? props.customClassName : undefined} onClick={props.readOnly ? undefined : handleClick}> {checkboxStatus === "enabled" ? props.emoji.checkedEmoji : props.emoji.uncheckedEmoji} </span> } else { let flag = false if (checkboxStatus === "enabled" && !props.emoji.checkedEmoji) { flag = true } if (checkboxStatus === "disabled" && !props.emoji.uncheckedEmoji) { flag = true } return <span className={props.customClassName ? props.customClassName : undefined} style={flag ? props.singleEmojiInvertStyle : props.singleEmojiNormalStyle} onClick={props.readOnly ? undefined : handleClick}> { props.emoji.checkedEmoji ? props.emoji.checkedEmoji : props.emoji.uncheckedEmoji } </span> } } return <InteractiveElement graphicObject={simplifyEmojiOutput()} containerStyle={{ display: "flex", flexDirection: "row", gap: "min(1vh, 1vw)", fontSize: "min(5vh, 5vw)", cursor: props.readOnly ? "not-allowed" : "pointer", userSelect: "none", opacity: props.readOnly ? 0.5 : 1, }} label={props.readOnly ? "readOnly" : checkboxStatus}/> } export default CheckBox
<?php /** * The template for displaying Archive pages. * * Used to display archive-type pages if nothing more specific matches a query. * For example, puts together date-based pages if no date.php file exists. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package WordPress * @subpackage Twenty_Eleven * @since Twenty Eleven 1.0 */ get_header(); ?> <?php if ( in_category('nwwg-timeline')) { ?> <h2><a href="http://neighborhoodwomen.org/wp/category/nwwg/nwwg-timeline/">NWWG -Timeline</a></h2> <?php } elseif ( in_category(array(20,21,'movies-ncnw'))) { ?><h2><a href="http://neighborhoodwomen.org/wp/category/ncnw/ncnw-media/">NCNW - Media &gt;</a></h2> elseif ( in_category(array(16,17,18))) { ?><h2><a href="http://neighborhoodwomen.org/wp/category/nwwg/nwwg-media/">NWWG - Media &gt;</a></h2><?php } else { } ?> <?php get_sidebar('two'); ?> <section id="primary"> <div id="content" role="main"> <?php if ( have_posts() ) : ?> <header class="page-header"> <h1 class="page-title"><?php single_cat_title(); ?> <?php if ( is_day() ) : ?> <?php printf( __( 'Daily Archives: %s', 'twentyeleven' ), '<span>' . get_the_date() . '</span>' ); ?> <?php elseif ( is_month() ) : ?> <?php printf( __( 'Monthly Archives: %s', 'twentyeleven' ), '<span>' . get_the_date( _x( 'F Y', 'monthly archives date format', 'twentyeleven' ) ) . '</span>' ); ?> <?php elseif ( is_year() ) : ?> <?php printf( __( 'Yearly Archives: %s', 'twentyeleven' ), '<span>' . get_the_date( _x( 'Y', 'yearly archives date format', 'twentyeleven' ) ) . '</span>' ); ?> <?php else : ?> <?php _e( 'Blog Archives', 'twentyeleven' ); ?> <?php endif; ?> </h1> </header> <?php twentyeleven_content_nav( 'nav-above' ); ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* Include the Post-Format-specific template for the content. * If you want to overload this in a child theme then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ if ( in_category('movies-nwwg')) { get_template_part( 'content-movies', get_post_format() ); } else { get_template_part( 'content', get_post_format() ); } ?> <?php endwhile; ?> <?php twentyeleven_content_nav( 'nav-below' ); ?> <?php else : ?> <article id="post-0" class="post no-results not-found"> <header class="entry-header"> <h1 class="entry-title"><?php _e( 'Nothing Found', 'twentyeleven' ); ?></h1> </header><!-- .entry-header --> <div class="entry-content"> <p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'twentyeleven' ); ?></p> <?php get_search_form(); ?> </div><!-- .entry-content --> </article><!-- #post-0 --> <?php endif; ?> </div><!-- #content --> </section><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
import { useEffect } from "react"; /** * Request animation frame. Runs given callback on every requested animation * frame. Returns a function to stop the loop. */ export function useRaf(callback: () => void) { useEffect(() => { let running = true; const fn = () => { callback(); if (running) requestAnimationFrame(fn); }; fn(); return () => { running = false; }; }, [callback]); }
import { InMemoryParentsRepository } from '@/infra/repositories/in-memory/in-memory-parents.repository' import { Parent, ParentProps } from '@/domain/entities/parent.entity' import { DissociateStudentToParentUseCase } from './dissociate-student-to-parent.usecase' import { InMemoryStudentsRepository } from '@/infra/repositories/in-memory/in-memory-students.repository' import { Student, StudentProps } from '@/domain/entities/student.entity' import { ResourceNotFoundError } from '@/application/errors/resource-not-found.error' describe('Dissociate Student to a Parent Use Case', () => { let sut: DissociateStudentToParentUseCase let parentsRepository: InMemoryParentsRepository let studentsRepository: InMemoryStudentsRepository const dummyParent: ParentProps = { name: 'any_name', lastName: 'any_sobrenome', phones: ['0123456789', '1234567890'], emails: ['any_email'], address: ['any_address'], cpf: 'any_cpf', } const dummyStudent: StudentProps = { firstName: 'any_name', lastName: 'any_sobrenome', allergies: ['any_allergy'], blood: 'A+', birthDay: new Date(), medication: ['any_medication'], registrationDate: new Date(), cpf: 'any_cpf', parentId: 'any_parent-id', } beforeEach(() => { parentsRepository = new InMemoryParentsRepository() studentsRepository = new InMemoryStudentsRepository() sut = new DissociateStudentToParentUseCase( studentsRepository, parentsRepository, ) }) test('Deve desassociar um Student a um Parent', async () => { const student = Student.create(dummyStudent) const parent = Parent.create(dummyParent) student.associateToParentId(parent.id.toString()) parent.addStudent(student.id.toString()) await studentsRepository.save(student) await parentsRepository.save(parent) await sut.execute({ studentId: student.id.toString(), parentId: parent.id.toString(), }) expect(parent.studentIds.includes(student.id.toString())).toBeFalsy() expect(student.parentId).toBeUndefined() }) test('Deve gerar erro tentar associar a um Student inexistente', async () => { await expect(() => sut.execute({ studentId: 'inexistent_id', parentId: 'inexistent_id', }), ).rejects.toThrowError('Student of id [inexistent_id] not found') }) test('Deve gerar erro tentar associar a um Parent inexistente', async () => { const student = Student.create(dummyStudent) await studentsRepository.save(student) await expect(() => sut.execute({ studentId: student.id.toString(), parentId: 'inexistent_id', }), ).rejects.toThrowError( new ResourceNotFoundError('Parent of id [inexistent_id] not found'), ) }) })
import { Injectable } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { BehaviorSubject } from 'rxjs'; import { ComponentProperty } from '../component-property/component.property'; import { Block, ContainerBlock } from '../block'; import { Destroyable } from 'src/app/mixins/mixins'; import { FormService } from './form.service'; import { FormControlMetadata } from '../component-property/component-property-form/form.util'; export interface ComponentPropertyForm { formGroup: FormGroup; component: Block; name: string; } @Injectable() export class ComponentPropertyService { private currentSelected: Block | null = null; private firstSelected: Block | null = null; private map: { [componentId: string]: ComponentPropertyForm; } = {}; private selectedPropertySubject = new BehaviorSubject<ComponentPropertyForm | null>(null); public selectedProperty$ = this.selectedPropertySubject.asObservable(); constructor(private formService: FormService) {} registerComponentProperty< TBuildingBlock extends ComponentProperty<TBuildingBlock> >( componentId: string, componentProperty: ComponentProperty<TBuildingBlock>, component: Block & Destroyable, name: string ): FormGroup { if (this.map[componentId]) { return this.map[componentId].formGroup; } // Build the form based on the component property const formGroup = this.formService.getControl( componentProperty.constructor, componentProperty, componentProperty ) as FormGroup; this.map[componentId] = { formGroup, component, name }; console.log(formGroup); return formGroup; } registerWithPropertyFromExistingComponent( componentId: string, componentToCopyId: string, component: Block & Destroyable, name: string ): FormGroup { const existingProperty = this.map[componentToCopyId]; if (!existingProperty) { throw new Error( `There is no component with Id = ${componentToCopyId} to copy.` ); } this.map[componentId] = { formGroup: new FormControlMetadata(existingProperty.formGroup, '').clone( this.formService ) as FormGroup, component, name, }; return this.map[componentId].formGroup; } onComponentSelected(component: Block): void { if (this.currentSelected === component) { return; } if (!this.firstSelected) { this.firstSelected = component; } if (this.currentSelected) { this.currentSelected.selected = false; } this.currentSelected = component; component.selected = true; this.selectedPropertySubject.next(this.map[component.id]); } onComponentRemoved(component: Block): void { const currentSelectedComponentRemoved = this.removeComponent(component); if (currentSelectedComponentRemoved) { this.onComponentSelected(this.firstSelected as Block); } } private removeComponent< TBuildingBlock extends ComponentProperty<TBuildingBlock> >(component: Block): boolean { let currentSelectedComponentRemoved = component === this.currentSelected; delete this.map[component.id]; const asContainer = component as ContainerBlock<TBuildingBlock>; if (asContainer?.container?.children.length > 0) { asContainer.container.children.forEach((c) => { currentSelectedComponentRemoved = currentSelectedComponentRemoved || this.removeComponent(c); }); } return currentSelectedComponentRemoved; } getComponentPropertyFormGroup(componentId: string): FormGroup { return this.map[componentId].formGroup; } }
# irbrc merged # http://eustaquiorangel.com/posts/552 # http://gist.github.com/86875 require "irb/completion" # activate default completion require 'irb/ext/save-history' # activate default history require "tempfile" # used for Vim integration require 'pp' # save history using built-in options IRB.conf[:SAVE_HISTORY] = 1_000_000_000 IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb_history" # auto-indent IRB.conf[:AUTO_INDENT]=true # try to load rubygems begin require "rubygems" rescue LoadError => e puts "Seems you don't have Rubygems installed: #{e}" end # let there be colors # just use Wirble for colors, since some enviroments dont have # rubygems and wirble installed # enabling Hirb class Object # get all the methods for an object that aren't basic methods from Object def my_methods (methods - Object.instance_methods).sort end end # from http://themomorohoax.com/2009/03/27/irb-tip-load-files-faster def ls %x{ls}.split("\n") end def cd(dir) Dir.chdir(dir) Dir.pwd end def pwd Dir.pwd end # also from http://themomorohoax.com/2009/03/27/irb-tip-load-files-faster def rl(file_name = nil) if file_name.nil? if [email protected]? rl(@recent) else puts "No recent file to reload" end else file_name += '.rb' unless file_name =~ /\.rb/ @recent = file_name load "#{file_name}" end end alias p pp alias quit exit begin require "pry" Pry.start exit rescue LoadError => e warn "Unable to load PRY" end
$(document).ready(function () { //slick-slider $('.carousel__inner').slick({ speed: 1200, autoplay: false, autoplaySpeed: 1200, prevArrow: '<button type="button" class="slick-next"><img src="icons/right.svg"></button>', nextArrow: '<button type="button" class="slick-prev"><img src="icons/left.svg"></button>', responsive: [{ breakpoint: 768, adaptiveHeight: true, settings: { dots: true, arrows: false } }, ] }); //Slide of card $('ul.catalog__tabs').on('click', 'li:not(.catalog__tab_active)', function () { $(this) .addClass('catalog__tab_active').siblings().removeClass('catalog__tab_active') .closest('div.container').find('div.catalog__content').removeClass('catalog__content_active').eq($(this).index()).addClass('catalog__content_active'); }); function toggleSlide(item) { $(item).each(function (i) { $(this).on('click', function (e) { e.preventDefault(); $('.catalog-item__content').eq(i).toggleClass('catalog-item__content_active'); $('.catalog-item__list').eq(i).toggleClass('catalog-item__list_active'); }); }); } toggleSlide('.catalog-item__link'); toggleSlide('.catalog-item__back'); // Modal windows $('[data-modal=consultation]').on('click', function () { $('body').addClass('_lock'); $('.overlay, #consultation').fadeIn('slow'); }); $('.modal__close').on('click', function () { $('body').removeClass('_lock'); $('.overlay, #consultation, #order, #thanks').fadeOut(); }); // $('.overlay').on('click', function () { // $('body').removeClass('_lock'); // $('.overlay, #consultation, #order, #thanks').fadeOut(); // }); $('.button_catalog').each(function (i) { $(this).on('click', function () { $('#order .modal__descr').text($('.catalog-item__subtitle').eq(i).text()); $('.overlay, #order').fadeIn('slow'); }); }); function validateForms(form) { $(form).validate({ rules: { name: { required: true, minlength: 2 }, phone: "required", email: { required: true, email: true } }, messages: { name: { required: "Введите свое имя", minlength: jQuery.validator.format("Минимальное кол-во символов: {0}") }, phone: "Введите номер вашего телефона", email: { required: "Нам нужен ваш email для обратной связи", email: "Ваш email должен соответствовать формату: [email protected]" } } }); } validateForms('#consultation-form'); validateForms('#consultation form'); validateForms('#order form'); $('input[name=phone]').mask("+375 (99) 999-99-99"); $('form').submit(function (e) { e.preventDefault(); if(!$(this).valid()) { return; } $.ajax({ type: "POST", url: "mailer/smart.php", data: $(this).serialize() }).done(function() { $(this).find("input").val(""); $('#consultation, #order').fadeOut(); $('.overlay, #thanks').fadeIn(); $('form').trigger('reset'); }); return false; }); // Smooth scroll and pageUp $(window).scroll(function () { if ($(this).scrollTop() > 500) { $('.pageUp').fadeIn(); } else { $('.pageUp').fadeOut(); } }); $("a[href^='#']").click(function () { const _href = $(this).attr("href"); $("html, body").animate({scrollTop: $(_href).offset().top + "px"}); return false; }); new WOW().init(); });
/* __Seed builder__ (Read_only) Example component Be careful copying content */ import React from "react"; import PropTypes from "prop-types"; import { useSave, useSet, useQuery, useDetail } from "seed/gql"; import { SAVE_SUGGESTION } from "seed/gql/queries"; import { Loading } from "seed/helpers"; import View from "seed/examples/components/suggestions/Form.view"; function SuggestionFormSave({ onCompleted = () => null, onError = () => null }) { const qShippings = useQuery(`{ shippings { } }`); const qParts = useQuery(`{ parts { } }`); const qOrders = useQuery(`{ orders { } }`); const [callSave, qSave] = useSave(SAVE_SUGGESTION, { onCompleted: () => onCompleted() //Note: When the component is wrap in a ModalRoute it bind the event 'closeModal()' }); const { shippings = [] } = qShippings.data; const { parts = [] } = qParts.data; const { orders = [] } = qOrders.data; const error = qSave.error ? "An error has occurred" : null; const onSubmit = (values) => callSave(values); return <View shippings={shippings} parts={parts} orders={orders} error={error} onSubmit={onSubmit} />; } SuggestionFormSave.propTypes = { onCompleted: PropTypes.func, onError: PropTypes.func }; export default SuggestionFormSave;
#ifndef RTD_API_H_ #define RTD_API_H_ #include "rtd_def.h" #if defined(__cplusplus) extern "C" { #endif // Api functions to manipulate RTC streams typedef struct RtdApiFuncs { int version; // used for validation, default 0. /* create rtd instance * conf: configure parameters * return value: instance of rtd. NULL if create failed */ void* (*create)(RtdConf conf); /* open a stream specified by url * url: stream url. Rtc stream supported for now * mode: "r" for subscribe. publish is not implemented yet * return value:.10200 if open success */ int (*open)(void* handle, const char* url, const char* mode); /* close the stream * handle: returned by open */ void (*close)(void* handle); /* runtime command (e.g. get/set parameters) * @return 0 for success, negative value for error */ int (*command)(void* handle, const char* cmd, void* arg); /* read one frame * caller need free the returned frame * return value: 1 for one frame read into '*frame'; 0 for try * later; -1 for EOF; or other negative value for * fatal error */ int (*read)(struct RtdFrame** frame, void* handle); /* free RtdFrame of current stream * handle to the stream returned by open */ void (*free_frame)(struct RtdFrame* frame, void* handle); } RtdApiFuncs; /* @brief Query Rtd Api functions * @param version Specify compatible api version, default:0 * @return Structure containing Api function pointers */ RTD_API const struct RtdApiFuncs* GetRtdApiFuncs(int version); #if defined(__cplusplus) } #endif #endif // !RTD_API_H_
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- <title></title> --> <!-- title icon --> <link rel="icon" type="image/png" href="media/titleicon.png"> <!-- botstrap 5 --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" /> <!-- font awesome 5.15--> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous" /> <!-- external font --> <link href="https://fonts.googleapis.com/css2?family=Sansita+Swashed:wght@300;400;800&display=swap" rel="stylesheet" /> <!-- font-family: 'Sansita Swashed', cursive; --> <link href="https://fonts.googleapis.com/css2?family=Oswald&display=swap" rel="stylesheet" /> <!-- font-family: 'Oswald', sans-serif; --> <link href="https://fonts.googleapis.com/css2?family=Acme&display=swap" rel="stylesheet" /> <!-- font-family: 'Acme', sans-serif; --> <!-- external css --> <link rel="stylesheet" href="{% static 'css/index.css' %}" /> </head> <body class="bodycolor"> <!-- navigations --> <nav class="navbar navbar-expand fixed-top shadow bgcolor rounded-bottom" style="background: whitesmoke;"> <div class="container-fluid"> <a class="navbar-brand brandcolor ms-5" href="/">Demo Mart</a> <button class="navbar-toggler custom-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <!--call from custom templates ==> nav_tags --> <!-- for active status --> {% url 'blog' cat.id as urll %} <li class="nav-item me-2 mb-lg-0 mb-3"> <a class=" btn textColor {% if request.path == urll %}active{% endif %} " aria-current="page" href="{{ urll }}">{{cat}}</a> </li> <li class="nav-item me-2 mb-lg-0 mb-3"> <a class="btn textColor" aria-current="page" href="/product/create/">Add Product</a> </li> </ul> <form class="d-flex" method="post" action="/"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" name="search" value="{{search}}" /> <button class="btn btn-primary" type="submit">Search</button> </form> </div> </div> </nav> <!-- notification message --> <div style="text-align: center"> {% if messages %} <br /><br /><br /> {% for msg in messages %} <div class="alert alert-{{msg.tags}}">{{msg}}</div> {% endfor %} {% endif %} </div> <br /><br /><br /> <!-- content --> <div class="container" style="min-height: 100vh;"> {% block content %} {% endblock %} </div> <!-- Footer --> <br /><br /><br /> <footer class="footerHeader"> <br /><br /> <div class="container"> <div class="row text-center textColor"> <p>Copyright &copy: tech villain</p> </div> <br /> <div class="row text-center"> <div class="col"> <a class="m-3" target="_blank" href="http://mahmudjewel.herokuapp.com"> <i class="fas fa-user-circle fa-2x"></i> </a> <a class="m-3" target="_blank" href="https://www.facebook.com/TechVillain.007"> <i class="fab fa-facebook fa-2x"></i> </a> <a class="m-3" target="_blank" href="https://www.youtube.com/channel/UCJCdq7lWqB7M5b16UatoTEw"> <i class="fab fa-youtube fa-2x"></i> </a> <a class="m-3" target="_blank" href="https://www.linkedin.com/in/mahmudjewel"> <i class="fab fa-linkedin fa-2x"></i> </a> <a class="m-3" target="_blank" href="https://github.com/MahmudJewel"> <i class="fab fa-github fa-2x"></i> </a> <a class="m-3" target="_blank" href="https://www.hackerrank.com/DJ_cse"> <i class="fab fa-hackerrank fa-2x"></i> </a> </div> </div> <br /><br /><br /><br /><br /><br /> </div> </footer> <!-- custom js --> <script src="{% static 'js/index.js' %}"></script> <!-- bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> </body> </html>
using System.IO; using UnityEditor; using UnityEditor.SceneManagement; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UIElements; //[InitializeOnLoad] public class SetupWindow : EditorWindow { static readonly string tutorialUrl; static readonly string instructionsTxt; static SetupWindow() { // Load tutorial url try { string txt = File.ReadAllText("Assets/Editor/Tutorial.url"); tutorialUrl = txt.Substring(txt.IndexOf("http")); } catch (FileNotFoundException) { tutorialUrl = "http://docs2x.smartfoxserver.com/ExamplesUnity/introduction"; } // Load instructions text try { instructionsTxt = File.ReadAllText("Assets/Editor/Instructions.txt"); } catch (FileNotFoundException) { instructionsTxt = "Instructions.txt file is missing."; } //// Show this editor window on load //if (!EditorPrefs.GetBool("Setup_Dismissed")) // ShowWindow(); //// Show this editor window when scene is changed //EditorSceneManager.sceneOpened += OnEditorSceneManagerSceneOpened; } //private static void OnEditorSceneManagerSceneOpened(Scene scene, OpenSceneMode mode) //{ // if (!EditorPrefs.GetBool("Setup_Dismissed")) // ShowWindow(); //} [MenuItem("SmartFoxServer/Demo Project Setup")] public static void ShowWindow() { EditorWindow.GetWindow(typeof(SetupWindow), true, "SmartFoxServer Demo Project Setup"); } [MenuItem("SmartFoxServer/Download SmartFoxServer [↗]")] public static void DownloadSfs() { Application.OpenURL("https://www.smartfoxserver.com/download/sfs2x"); } [MenuItem("SmartFoxServer/Tutorial [↗]")] public static void GoToTutorial() { Application.OpenURL(tutorialUrl); } public void CreateGUI() { // Each editor window contains a root VisualElement object VisualElement root = rootVisualElement; // Import UXML (also references USS style sheet internally) var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/SetupWindow.uxml"); visualTree.CloneTree(root); if (!EditorGUIUtility.isProSkin) root.AddToClassList("light"); // Add click listener to download button Button downloadBt = (Button)root.Query("downloadBt").First(); downloadBt.RegisterCallback<ClickEvent>(HandleDownloadClickCallback); // Add click listener to tutorial button Button tutorialBt = (Button)root.Query("tutorialBt").First(); tutorialBt.RegisterCallback<ClickEvent>(HandleTutorialClickCallback); // Add change listener to checkbox Toggle showTg = (Toggle)root.Query("showTg").First(); showTg.value = !EditorPrefs.GetBool("DoNotShowSetup"); showTg.RegisterValueChangedCallback(HandleShowToggleCallback); // Set instructions TextElement instructionsLb = (TextElement)root.Query("instructionsLb").First(); instructionsLb.text = instructionsTxt; } private void HandleDownloadClickCallback(ClickEvent evt) { DownloadSfs(); } private void HandleTutorialClickCallback(ClickEvent evt) { GoToTutorial(); } private void HandleShowToggleCallback(ChangeEvent<bool> evt) { EditorPrefs.SetBool("DoNotShowSetup", !evt.newValue); } }
#Importar Datos #Descargar archivos desde internet url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data-numeric" download.file(url = url, destfile = "german.data") #Leer archivos del internet german_credit <- read.table("https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data-numeric") head(german_credit) #Descargar archivo y utilizar la función read.table url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data-numeric" prueba <- read.table(url) head(prueba) #Información sobre la estructura del Data Frame str(german_credit) #Leer archivos de otras fuentes #csv my.frame <- read.csv(file="csv.csv", header=FALSE, sep=",") head(my.frame) #xlsx install.packages("readxl") library(readxl) df_excel <- read_excel (path= "archivo_xlsx.xlsx", sheet = 1) head(df_excel) #Exportar datos #archivo txt write.table(x=german_credit, file="datoexportado.txt", sep= ",", row.names=FALSE, col.names=TRUE) #archivo csv write.csv(x=german_credit, file="datoexportado.csv", row.names=FALSE)
/** * @vitest-environment happy-dom */ import React from 'react'; import { renderHook } from '@testing-library/react-hooks'; import { useManifest } from '../src'; import { Vault } from '@iiif/vault'; import { createVaultWrapper } from '../test-utils'; describe('component-test', () => { test('a hook', async () => { const vault = new Vault(); await vault.loadManifest('https://example.org/manifest', { id: 'https://example.org/manifest', type: 'Manifest', label: { en: ['My manifest'] }, }); const hook = renderHook(() => useManifest({ id: 'https://example.org/manifest' }), { wrapper: createVaultWrapper(vault), }); expect(hook.result.current!.label).toEqual({ en: ['My manifest'], }); }); });
################################################################## # JRP data - ITC # Hieu, Masoomeh and Jaap August 2018 # Estimation of TTC (target trajectory of CFI) # Classify the functions used for TTC of CFI # The main function is quadratic-linear for CFI, linear-plateau for DFI # If the slope of DFI curve decreases -> linear for CFI # If the inflection point is too closed to last data point -> quadratic for CFI ################################################################## rm(list=ls(all=TRUE)) #To remove the hisory # dev.off() #To close all graphs #------------------------------------------------------------------------------- # Packages needed for estimaton of Ideal trajectory - nonlinear regression #------------------------------------------------------------------------------- library("minpack.lm") library("nlstools") library("nlsMicrobio") library("stats") library("tseries") #runs test for auto correlation #Use NLS2 library(proto) library(nls2) library(ggplot2) ################################################################ # Set working directory setwd("C:/Users/Kevin Le/PycharmProjects/Pig Data Black Box") #load dataset load("Data/JRPData.Rdata") #load dataset created in MissingData.step source("Package/Functions.R") # DATA PREPARATION #Create a new dataframe which will store Data after ITC estimation #Dataframe contains ITC parameters No.NA.Data.1 <- NULL #Order number of Animal_ID ID <- unique(as.factor(No.NA.Data$ANIMAL_ID)) # ID <- 5655 # For loop for automatically estimating ITC of all pigs IDC <- seq_along(ID) for (idc in IDC){ # idc =100 i <- ID[idc] Data <- No.NA.Data[No.NA.Data$ANIMAL_ID == i,] ####### Create data frame of x (Age) and y (CFI) ######## x <- as.numeric(Data$Age.plot) Y <- as.numeric(Data$CFI.plot) Z <- as.numeric(Data$DFI.plot) Data.xy <- as.data.frame(cbind(x,Y)) #Initial parameteres for parameter estimation X0.0 <- x[1] Xlast <- x[length(x)] #Provide set of initial parameters Xs.1 <- round(seq(X0.0 + 1, Xlast - 1, len = 30), digits = 0) X0.1 <- rep(X0.0, length(Xs.1)) DFIs.1 <- NULL CFIs.1 <- NULL for(A in seq_along(Xs.1)){ DFIs2 <- Data[Data$Age.plot == Xs.1[A],]$DFI.plot CFIs2 <- Data[Data$Age.plot == Xs.1[A],]$CFI.plot DFIs.1 <- c(DFIs.1, DFIs2) CFIs.1 <- c(CFIs.1, CFIs2) } st1 <- data.frame(cbind(X0.1, Xs.1, DFIs.1, CFIs.1)) names(st1) <- c("X0","Xs", "DFIs","CFIs") #RUN NLS2 with upper and lower bound # weight = 1/Y^2 st2 <- nls2(Y ~ nls.func.2(X0, Xs, DFIs, CFIs), Data.xy, start = st1, # weights = weight, # trace = T, algorithm = "brute-force") par_init <- coef(st2) par_init c <- abcd.2(par_init)[3];c Xs.0 <- par_init[2]; Xs.0 if(c < 0){ FuncType <- "LM" } else if(c > 0 && Xs.0 >= ((Xlast - X0.0)*0.2 + X0.0) # && Xs.0 <= ((Xlast - X0.0)*1 + X0.0) ){ FuncType <- "QLM" } else { FuncType <- "QDR" } # #Plot Function with initial parameters to data ITC_CFI.0 <- as.numeric(unlist(pred.func.2(par_init, x)[1])) ITC_DFI.0 <- as.numeric(unlist(pred.func.2(par_init, x)[2])) #Plot # png(filename = paste("Graphs/Step2_graphs/Initial_para/",idc,".",ID[idc],".png",sep=""), # height = 720, width = 1200, units = 'px', type="cairo-png") par(mfrow = c(1,2)) par(mar=c(4.5,4.5,4.5,1.5)) #CFI plot(x, ITC_CFI.0, main = "Cumulative Feed Intake", ylab = "Cumulative Feed Intake (kg)", xlab = "Age (days)", ylim = c(0, max(ITC_CFI.0, Data$CFI.plot)), type="l", col ="blue", cex.main = 1.5, cex.axis = 1.5, cex.lab = 1.5, lwd = 2.7) # ITC of CFI points(x, Data$CFI.plot, col="black", cex = 1.5) # Observation data of CFI # DFI plot(x, Data$DFI.plot, # Observation data of DFI main = "Daily Feed Intake", ylab = "Daily Feed Intake (kg)", xlab = "Age (days)", type="p", col ="black", cex.main = 1.5, cex = 1.5, cex.axis = 1.5, cex.lab = 1.5) lines(x, ITC_DFI.0, # ITC of DFI type = "l",col="blue", lwd = 2.7) mtext(paste("Pig:", ID[idc], ", idc=", idc, ", FuncType:", FuncType), side = 3, line = -1.8, outer = TRUE, cex = 2) # par(mfrow = c(1,1)) dev.off() #-------------------------------------------- # Choose function for the TTC #-------------------------------------------- idc.1 <- rep(idc, dim(Data)[1]) FuncType <- rep(FuncType, dim(Data)[1]) Data$FuncType <- FuncType Data$idc.1 <- idc.1 No.NA.Data.1 <- rbind(No.NA.Data.1 , Data) } # end FOR loop # No.NA.Data <- No.NA.Data.1 DFI.neg <- subset(No.NA.Data.1, FuncType == "LM") length(unique(DFI.neg$idc.1)) DFI.pos1 <- subset(No.NA.Data.1, FuncType == "QDR") length(unique(DFI.pos1$idc.1)) DFI.pos2 <- subset(No.NA.Data.1, FuncType == "QLM") length(unique(DFI.pos2$idc.1)) DFI.neg <- unique(DFI.neg$ANIMAL_ID); DFI.neg DFI.pos1 <- unique(DFI.pos1$ANIMAL_ID); DFI.pos1 DFI.pos2 <- unique(DFI.pos2$ANIMAL_ID); DFI.pos2 #Save results to Rdata file save(No.NA.Data.1, DFI.neg, DFI.pos1, DFI.pos2, file = "Data/JRPData_TTC.RData") # write.csv(No.NA.Data.1, DFI.neg, DFI.pos1, DFI.pos2, file = "JRP.param.csv")
const { SlashCommandBuilder, EmbedBuilder, ChannelType } = require('discord.js') const generators = require('../utils/generators') //Globals const courses = new Set() const leaderboardMessages = new Map() module.exports = { data: new SlashCommandBuilder() .setName('leaderboard') .setDescription('Manage course leaderboards') .addStringOption((option) => option.setName('command').setDescription('Create a new leaderboard for a course').setRequired(true).addChoices( { name: 'Add', value: 'add', }, { name: 'Remove', value: 'remove', }, { name: 'Show', value: 'show', } ) ) .addStringOption((option) => option.setName('course').setDescription('Course name').setRequired(false)), async execute(interaction) { const command = interaction.options.getString('command') const course = interaction.options.getString('course') switch (command) { case 'add': if (!course) { await interaction.reply({ content: 'Incomplete /leaderboard add command. Usage: /leaderboard add <course>', ephemeral: true, }) return } addCourse(course, interaction) break case 'remove': removeCourse(course, interaction) break case 'show': showCourse(course, interaction) break } }, } /** * Add a course to the leaderboard * @param {String} courseName * @param {Interaction Instance} interaction * @returns */ async function addCourse(courseName, interaction) { console.log(`[INFO] Adding course ${courseName}...`) const course = courseName.toLowerCase() if (courses.has(course)) { await interaction.reply({ content: 'Course already exists.', ephemeral: true, }) return } courses.add(course) // Create a placeholder message in the same channel const leaderboardMessage = await interaction.channel.send({ embeds: [await createLeaderboardEmbed(course)], }) leaderboardMessages.set(course, leaderboardMessage) await interaction.reply(`Course ${course} added.`) // Store the message ID for future reference leaderboardMessages.set(course, leaderboardMessage.id) // Adjust the category name const threadName = courseName const autoArchiveDuration = 1440 // Adjust as needed const thread = await interaction.channel.threads.create({ name: threadName, autoArchiveDuration: autoArchiveDuration, }) await thread.send(`Welcome to the leaderboard for ${courseName}!`) return Promise.resolve() } /** * Remove a course from the leaderboard * @param {*} courseName */ async function removeCourse(courseName, interaction) { console.log(`[INFO] Removing course ${courseName}...`) } /** * Show a course from the leaderboard * @param {*} courseName */ async function showCourse(courseName, interaction) { console.log(`[INFO] Showing course ${courseName}...`) } /** * Create a leaderboard embed * @param {*} courseName * @returns */ async function createLeaderboardEmbed(courseName, interaction) { const leaderboardEmbed = new EmbedBuilder() .setTitle(`Leaderboard for ${courseName}`) .setDescription('Updated leaderboard goes here.') return leaderboardEmbed } /** * Edit the leaderboard message * @param {*} interaction * @param {*} courseName */ async function editLeaderboardMessage(interaction, courseName) { // Edit the embedded message in the thread to include the updated leaderboard const thread = interaction.guild.threads.cache.find((thread) => thread.name === courseName) if (thread) { const leaderboardEmbed = createLeaderboardEmbed(courseName) // Generate the updated leaderboard const firstMessage = await thread.messages.fetchPinned().first() if (firstMessage) { await firstMessage.edit({ embeds: [leaderboardEmbed] }) } } }
import classNames from "classnames"; import { ProductListText } from "../enums/ProductListText"; interface Props { articul: string; color: string; size: number; totalCount?: number; className?: string; } const ProductList = ({ articul, color, size, totalCount, className }: Props) => { return ( <dl className={classNames('product-list', className)}> <div> <dt>{ProductListText.Articul}:</dt> <dd>{articul}</dd> </div> <div> <dt>{ProductListText.Color}:</dt> <dd>{color}</dd> </div> <div> <dt>{ProductListText.Size}:</dt> <dd>{size}</dd> </div> {totalCount && <div> <dt>{ProductListText.Quantity}:</dt> <dd>{totalCount}</dd> </div> } </dl> ); }; export default ProductList;
import { Skill } from '../../../../../base/Skill'; import { Character } from '../../../../../../shared/models/character'; import { ChannelFindFamiliar as CastEffect } from '../../../../../effects/channels/ChannelFindFamiliar'; export class FindFamiliar extends Skill { static macroMetadata = { name: 'FindFamiliar', macro: 'cast findfamiliar', icon: 'eagle-emblem', color: '#0aa', mode: 'autoActivate', tooltipDesc: 'Summon a familiar. Channel: 5s. Cost: 100 MP' }; public targetsFriendly = true; public name = ['findfamiliar', 'cast findfamiliar']; public format = '[AnimalType]'; public unableToLearnFromStealing = true; canUse(user: Character, target: Character) { return !(user.hasEffect('ChannelFindFamiliar') || user.hasEffect('ActivePet')); } mpCost() { return 100; } execute(user: Character, { args, effect }) { if(!this.tryToConsumeMP(user, effect)) return; this.use(user, user, effect, args); } use(user: Character, target: Character, baseEffect = {}, animalStr?: string) { const effect = new CastEffect(baseEffect); effect.cast(user, target, this, animalStr); } }
'use client' import * as React from 'react' import { useTheme } from 'next-themes' import { Icons } from '@/components/Icons' import { Button } from '@/components/ui/Button' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/DropdownMenu' export function ThemeToggle() { const { theme,setTheme } = useTheme() return ( <> <Button variant='ghost' size='sm' onClick={() => setTheme(theme ==="light"? 'dark' : 'light')}> <Icons.Sun className='rotate-10 scale-100 transition-all hover:text-slate-900 dark:-rotate-90 dark:scale-0 dark:text-slate-400 dark:hover:text-slate-100' /> <Icons.Moon className='absolute rotate-50 scale-0 transition-all hover:text-slate-900 dark:rotate-0 dark:scale-100 dark:text-slate-400 dark:hover:text-slate-100' /> <span className='sr-only'>Toggle theme</span> </Button> </> // <DropdownMenu> // <DropdownMenuTrigger asChild> // <Button variant='ghost' size='sm'> // <Icons.Sun className='rotate-10 scale-100 transition-all hover:text-slate-900 dark:-rotate-90 dark:scale-0 dark:text-slate-400 dark:hover:text-slate-100' /> // <Icons.Moon className='absolute rotate-50 scale-0 transition-all hover:text-slate-900 dark:rotate-0 dark:scale-100 dark:text-slate-400 dark:hover:text-slate-100' /> // <span className='sr-only'>Toggle theme</span> // </Button> // </DropdownMenuTrigger> // <DropdownMenuContent align='end' forceMount> // <DropdownMenuItem onClick={() => setTheme('light')}> // <Icons.Sun className='mr-2 h-4 w-4' /> // <span>Light</span> // </DropdownMenuItem> // <DropdownMenuItem onClick={() => setTheme('dark')}> // <Icons.Moon className='mr-2 h-4 w-4' /> // <span>Dark</span> // </DropdownMenuItem> // <DropdownMenuItem onClick={() => setTheme('system')}> // <Icons.Laptop className='mr-2 h-4 w-4' /> // <span>System</span> // </DropdownMenuItem> // </DropdownMenuContent> // </DropdownMenu> ) }
import {useDispatch, useSelector} from "react-redux" import {toast} from "react-hot-toast" import {add, remove} from "../redux/Slices/CartSlice" const Product = ({post}) => { const {cart} = useSelector((state)=>state) const dispatch = useDispatch() const addToCart=()=>{ dispatch(add(post)) toast.success("Item added to Cart") } const removeFromCart = ()=>{ dispatch(remove(post.id)) toast.error("Item removed from Cart") } return ( <div className="hover:scale-110 transition duration-300 ease-in flex flex-col items-center justify-between shadow-[rgba(0,_0,_0,_0.24)_0px_3px_8px] hover:shadow-[0px_0px_95px_53px_#00000024] gap-3 p-4 mt-10 ml-5 rounded-xl"> <div> <p className="text-gray-700 font-semibold text-lg text-left w-[10rem] mt-1">{post.title}</p> </div> <div className="w-40 text-gray-400 font-normal text-[0.8rem] text-left"> <p>{post.subtitle}</p> </div> {/* .split(" ").slice(0,10).join(" ")+"..." */} <div className="h-[180px]"> <img src={post.image} alt="Product" className="h-full w-full"/> </div> <div className="flex items-center justify-between w-full mt-5"> <div> <p className="text-green-600 font-semibold ">{post.price}</p> </div> { cart.some((p)=>p["isbn13"] === post["isbn13"]) ? ( <button className="text-gray-700 border-2 border-gray-700 rounded-full font-semibold text-[12px] p-1 px-3 uppercase hover:bg-gray-700 hover:text-white transition duration-300 ease-in border-solid" onClick={removeFromCart}> <span>Remove Item</span> </button> ): (<button className="text-gray-700 border-solid border-2 border-gray-700 rounded-full font-semibold text-[12px] p-1 px-3 uppercase hover:bg-gray-700 hover:text-white transition duration-300 ease-in upercase tracking-wide" onClick={addToCart}> <span>Add to Cart</span> </button>) } </div> </div>); }; export default Product;
import styled from "styled-components"; import { Typography, Rating, Box, CardContent, CardMedia} from "@mui/material" import { Link } from "react-router-dom"; function PropertyList({properties}){ const propertyNodes = properties.map((property) => { return ( <Wrapper> <Card> <CardMedia component="img" sx={{ height: 340, width: 500, margin: 1, borderRadius: 3}} image= {property.images[0].url} alt="house in Oban" /> <Box sx={{ display: 'flex', flexDirection: 'column', width: 500 }}> <CardContent sx={{ flex: '0 1 auto', margin: -2}}> <h3>City: {property.location}</h3> <h3>Property Description: {property.description}</h3> <h3>Host Name: {property.host["firstName"]}</h3> <Typography component="legend"/> <Typography component="legend">Host Rating</Typography> <Rating name="read-only" value= {property.host["rating"]} readOnly /> <p>£ {property.pricePerNight} / per night</p> <StyledLink to={"/properties/" + property.id}>View</StyledLink> </CardContent> </Box> </Card> </Wrapper> ); }); return( <div className="property-list"> {propertyNodes} </div> ) } export default PropertyList; const StyledLink = styled(Link)` display: inline-block; font-size: 1em; background: #f9473a; padding: 10px 30px; text-transform: uppercase; text-decoration: none; font-weight: 500; color: #fff; letter-spacing: 2px; transition: 0.2s; border-radius: 20px; :hover{ letter-spacing: 5px; } ` const Wrapper = styled.div` margin: 4rem 0rem; display: flex; justify-content: space-around; `; const Card = styled.div` border-radius: 10px; box-shadow: 0px 2px 10px rgb(68, 67, 67); padding: 15px; display: flex; text-decoration: none; `
# Software License Agreement (BSD) # # @author Luis Camero <[email protected]> # @copyright (c) 2023, Clearpath Robotics, Inc., All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * 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. # * Neither the name of Clearpath Robotics nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 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. from clearpath_config.common.types.accessory import Accessory from clearpath_config.common.types.ip import IP from clearpath_config.common.types.port import Port from clearpath_config.common.utils.dictionary import extend_flat_dict, is_in_dict from clearpath_config.sensors.types.sensor import BaseSensor from typing import List class BaseLidar3D(BaseSensor): SENSOR_TYPE = "lidar3d" SENSOR_MODEL = "base" TOPIC = "points" FRAME_ID = "laser" IP_ADDRESS = "192.168.131.25" IP_PORT = "2368" class ROS_PARAMETER_KEYS: FRAME_ID = "node_name.frame_id" IP_ADDRESS = "node_name.ip_address" IP_PORT = "node_name.ip_port" class TOPICS: SCAN = "scan" POINTS = "points" NAME = { SCAN: "scan", POINTS: "points", } RATE = { SCAN: 10, POINTS: 10 } def __init__( self, idx: int = None, name: str = None, topic: str = TOPIC, frame_id: str = FRAME_ID, ip: str = IP_ADDRESS, port: int = IP_PORT, urdf_enabled: bool = BaseSensor.URDF_ENABLED, launch_enabled: bool = BaseSensor.LAUNCH_ENABLED, ros_parameters: dict = BaseSensor.ROS_PARAMETERS, ros_parameters_template: dict = BaseSensor.ROS_PARAMETERS_TEMPLATE, parent: str = Accessory.PARENT, xyz: List[float] = Accessory.XYZ, rpy: List[float] = Accessory.RPY ) -> None: # Frame ID self.frame_id: str = self.FRAME_ID self.set_frame_id(frame_id) # IP Address self.ip: IP = IP(self.IP_ADDRESS) self.set_ip(ip) # IP Port self.port: Port = Port(self.IP_PORT) self.set_port(port) # ROS Parameter Template template = { self.ROS_PARAMETER_KEYS.FRAME_ID: BaseLidar3D.frame_id, self.ROS_PARAMETER_KEYS.IP_ADDRESS: BaseLidar3D.ip, self.ROS_PARAMETER_KEYS.IP_PORT: BaseLidar3D.port, } ros_parameters_template = extend_flat_dict(template, ros_parameters_template) super().__init__( idx, name, topic, urdf_enabled, launch_enabled, ros_parameters, ros_parameters_template, parent, xyz, rpy ) @classmethod def get_frame_id_from_idx(cls, idx: int) -> str: return "%s_%s" % ( cls.get_name_from_idx(idx), cls.FRAME_ID ) @classmethod def get_ip_from_idx(cls, idx: int) -> str: ip = cls.IP_ADDRESS.split('.') network_id = ip[0:3] host_id = int(ip[-1]) + idx return '.'.join(network_id) + '.' + str(host_id) def set_idx(self, idx: int) -> None: # Set Base: Name and Topic super().set_idx(idx) # Set Frame ID self.set_frame_id(self.get_frame_id_from_idx(idx)) # Set IP if not is_in_dict( self._ros_parameters, self.ROS_PARAMETER_KEYS.IP_ADDRESS.split(".")): self.set_ip(self.get_ip_from_idx(idx)) @property def frame_id(self) -> str: return self._frame_id @frame_id.setter def frame_id(self, link: str) -> None: Accessory.assert_valid_link(link) self._frame_id = link def get_frame_id(self) -> str: return self.frame_id def set_frame_id(self, link: str) -> None: self.frame_id = link @property def ip(self) -> str: return str(self._ip) @ip.setter def ip(self, ip: str) -> None: self._ip = IP(str(ip)) def get_ip(self) -> str: return str(self.ip) def set_ip(self, ip: str) -> None: self.ip = ip @property def port(self) -> int: return int(self._port) @port.setter def port(self, port: int) -> None: self._port = Port(int(port)) def get_port(self) -> int: return int(self.port) def set_port(self, port: int) -> None: self.port = port class VelodyneLidar(BaseLidar3D): SENSOR_MODEL = "velodyne_lidar" FRAME_ID = "laser" IP_PORT = 2368 HDL_32E = "32E" HDL_64E = "64E" HDL_64E_S2 = "64E_S2" HDL_64E_S3 = "64E_S3" VLP_16 = "VLP16" VLP_32C = "32C" DEVICE_TYPE = VLP_16 DEVICE_TYPES = [ HDL_32E, HDL_64E, HDL_64E_S2, HDL_64E_S3, VLP_16, VLP_32C ] class ROS_PARAMETER_KEYS: FRAME_ID = "velodyne_driver_node.frame_id" IP_ADDRESS = "velodyne_driver_node.device_ip" IP_PORT = "velodyne_driver_node.port" DRIVER_NODE_MODEL = "velodyne_driver_node.model" TRANSFORM_NODE_MODEL = "velodyne_transform_node.model" FIXED_FRAME = "velodyne_transform_node.fixed_frame" TARGET_FRAME = "velodyne_transform_node.target_frame" class TOPICS: SCAN = "scan" POINTS = "points" NAME = { SCAN: "scan", POINTS: "points", } RATE = { SCAN: 10, POINTS: 10 } def __init__( self, idx: int = None, name: str = None, topic: str = BaseLidar3D.TOPIC, frame_id: str = FRAME_ID, ip: str = BaseLidar3D.IP_ADDRESS, port: int = IP_PORT, device_type: str = DEVICE_TYPE, urdf_enabled: bool = BaseSensor.URDF_ENABLED, launch_enabled: bool = BaseSensor.LAUNCH_ENABLED, ros_parameters: str = BaseSensor.ROS_PARAMETERS, parent: str = Accessory.PARENT, xyz: List[float] = Accessory.XYZ, rpy: List[float] = Accessory.RPY ) -> None: # Device Type: self.set_device_type(device_type) # ROS Parameter Template ros_parameters_template = { self.ROS_PARAMETER_KEYS.DRIVER_NODE_MODEL: VelodyneLidar.device_type, self.ROS_PARAMETER_KEYS.TRANSFORM_NODE_MODEL: VelodyneLidar.device_type, self.ROS_PARAMETER_KEYS.FIXED_FRAME: VelodyneLidar.frame_id, self.ROS_PARAMETER_KEYS.TARGET_FRAME: VelodyneLidar.frame_id, } super().__init__( idx, name, topic, frame_id, ip, port, urdf_enabled, launch_enabled, ros_parameters, ros_parameters_template, parent, xyz, rpy ) @property def device_type(self) -> str: return self._device_type @device_type.setter def device_type(self, device_type) -> None: assert device_type in self.DEVICE_TYPES, ( "Device type '%s' is not one of '%s'" % ( device_type, self.DEVICE_TYPES ) ) self._device_type = device_type def get_device_type(self) -> str: return self.device_type def set_device_type(self, device_type: str) -> None: self.device_type = device_type
## Why WSL? WSL stands for *Windows Subsystem for Linux*, basically it lets you setup a linux terminal in your windows powershell. Setting up a development environment in linux is about 1000000x easier than windows ## Actual Setup First go to "Turn windows Features on or off" ![WindowsFeatures](<./WindowsFeatures.png>) scroll down until you see "Windows Subsystem For Linux" ![WSL check](<./WSL_InFeatures.png>) Check the checkmark and restart your pc, then continue with the next steps Setting up WSL is a lot easier than it used to be, as long as you don't have it already installed, all you need to do is run the below command in the powershell program, if you are familiar with linux distros, the automatically installed distro is Ubuntu ```PowerShell wsl --install ``` if what you see is the default `wsl --help` output than you have run this command once already Next, you should open a WSL session, easiest way to do this is to just hit the windows key and search wsl and hit enter. It will bring you through a default user creation procedure in which you set the username and password ***KEEP TRACK OF YOUR PASSWORD***
package me.gustavo.springordermanager.service.impl; import me.gustavo.springordermanager.exception.EntityNotCreatedException; import me.gustavo.springordermanager.model.Item; import me.gustavo.springordermanager.model.dto.ItemDto; import me.gustavo.springordermanager.repository.ItemRepository; import me.gustavo.springordermanager.service.intf.ItemService; import me.gustavo.springordermanager.util.StringUtil; import org.springframework.stereotype.Component; import java.util.Optional; @Component public class ItemServiceImpl extends BaseCRUDService<Item, Long, ItemRepository> implements ItemService { public ItemServiceImpl(ItemRepository repository) { super(repository); } @Override public Item create(ItemDto itemDto) { Item item = new Item(); item.setName(itemDto.getName()); item.setSku(itemDto.getSku()); item = this.create(item); if (item.getId() == 0) throw new EntityNotCreatedException("item"); return item; } @Override public Optional<Item> findBySku(String sku) { if (StringUtil.isEmpty(sku)) return Optional.empty(); return this.repository.findItemBySku(sku); } @Override public Optional<Item> update(ItemDto itemDto) { Optional<Item> optItem = this.findById(itemDto.getId()); if (!optItem.isPresent()) return Optional.empty(); Item item = optItem.get(); if (!StringUtil.isEmpty(itemDto.getName())) item.setName(itemDto.getName()); if (!StringUtil.isEmpty(itemDto.getSku())) item.setSku(itemDto.getSku()); return this.update(itemDto.getId(), item); } @Override public Optional<Item> update(Item entity) { return this.update(entity.getId(), entity); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ESCOM-EXAMENES CÁLCULO</title> <link rel="stylesheet" href="css/ESTILOS_EXAMENES.css"> <meta name="keywords" content="Cálculo aplicado, Riemman, Integrales, Examenes"> <meta name="robots" content="index"> <link rel="icon" href="imagenes/matematicas.png"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> </head> <body> <div class="container"> <header class="superior"> </div> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="https://www.escom.ipn.mx/">ESCOM</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="index.html">Inicio</a> </li> <!-- <li class="nav-item"> <a class="nav-link" href="CONTACT.html">Contactanos</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Recursos extra </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <li><a class="dropdown-item" href="listaexamen.html">Examenes</a></li> <li><a class="dropdown-item" href="RECURSOS_EXTRA.html">PDFS</a></li> <li><a class="dropdown-item" href="VIDEOS.html">Videos</a></li> <li><a class="dropdown-item" href="CURSOS.html">Cursos</a></li> </ul> </li> --> </ul> </div> </div> </nav> </nav> </header> </div> <div class="container"> <center class="title"> <h1> EXAMEN 2</h1> </center> <section> <form name="quizForm" onsubmit="return verificarRespuestas()"> <!--Si requiere de imagenes, dime y yo las agrego en la carpeta para el zip--> <!--PREGUNTA 1--> <h5>1.- Encuentra el área bajo la curva para la función f(x)=x<sup>2</sup>+6x+8 en el intervalo [-4,-2] mediante Sumas de Riemman.</h5> <!--Correcta--> <input type="radio" name="p1" value="a">a. 4/3 u<sup>2</sup> <br> <!--Incorrecta--> <input type="radio" name="p1" value="b">b. 15/3 u<sup>2</sup> </br> <!--Incorrecta--> <input type="radio" name="p1" value="c">c. 16 u<sup>2</sup> </br> <!--Incorrecta--> <input type="radio" name="p1" value="d">d. 5/3 u<sup>2</sup> </br> <!--Incorrecta--> <br> <!--PREGUNTA 2--> <h5>2.- Calcular:</h5> <center> <img src="imagenes/exa2pregunt1.png" class="img-fluid" alt="..." width="450 px"> </center> <!--Incorrecta--> <input type="radio" name="p2" value="a">a. -5/3</br> <!--Incorrecta--> <input type="radio" name="p2" value="b">b. 17/4 </br> <!--Correcta--> <input type="radio" name="p2" value="c">c. -5/6</br> <!--Incorrecta--> <input type="radio" name="p2" value="d">d. 9/4</br> <br> <!--PREGUNTA 3--> <h5>3.-Calcule:</h5> <center> <img src="imagenes/EXA2PREGUNT2.png" class="img-fluid" alt="..." width="450 px"> </center> <!--Incorrecta--> <input type="radio" name="p3" value="a">a. 12/2</br> <!--Incorrecta--> <input type="radio" name="p3" value="b">b. 54/5 </br> <!--Correcta--> <input type="radio" name="p3" value="c">c. 27/2</br> <!--Incorrecta--> <input type="radio" name="p3" value="d">d. 3/4</br> <br> <!--PREGUNTA 4--> <h5>4.-Integre por el método de Simpson:</h5> <center> <img src="imagenes/EXA2PREGUNT3.png" class="img-fluid" alt="..." width="120 px"> </center> <!--Correcta--> <input type="radio" name="p4" value="a">a. 1.4626</br> <!--Incorrecta--> <input type="radio" name="p4" value="b">b. 5.6414 </br> <!--Incorrecta--> <input type="radio" name="p4" value="c">c. 3.5789 </br> <!--Incorrecta--> <input type="radio" name="p4" value="d">d. 1.5626 </br> <br> <!--PREGUNTA 5--> <h5>5.-Hallar el área de la región definida por las curvas y= 1 / x, y = x, y=1/4 x</h5> <!--Incorrecta--> <input type="radio" name="p5" value="a">a. 0.55 u<sup>3</sup></br> <!--Incorrecta--> <input type="radio" name="p5" value="b">b. 0.45 u<sup>3</sup> </br> <!--Correcta--> <input type="radio" name="p5" value="c">c. 0.69 u<sup>3</sup></br> <!--Incorrecta--> <input type="radio" name="p5" value="d">d. 3 u<sup>3</sup></br> <br> <!--PREGUNTA 6--> <h5>6.-Dada la región limitada por x+y=1,y=x+1,determinar el volumen del sólido de revolución que se obtiene al girar la región con respecto al eje dado.</h5> <!--Incorrecta--> <input type="radio" name="p6" value="a">a. 17π.58 u<sup>3</sup></br> <!--Incorrecta--> <input type="radio" name="p6" value="b">b. 15.25π u<sup>3</sup> </br> <!--Incorrecta--> <input type="radio" name="p6" value="c">c. 35π/3 u<sup>3</sup></br> <!--Correcta--> <input type="radio" name="p6" value="d">d. 10π/3u<sup>3</sup></br> <br> <!--PREGUNTA 7--> <h5>7.-Calcular el volumen del sólido que se encuentra entre los planos x=-1,x=1. Si las secciones transversales son discos circulares cuyos diámetros van de y=x<sup>2</sup> a y=2-x<sup>2</sup></h5> <!--Incorrecta--> <input type="radio" name="p7" value="a">a. 8π u<sup>3</sup></br> <!--Incorrecta--> <input type="radio" name="p7" value="b">b. 2π/6 u<sup>3</sup></br> <!--Correcta--> <input type="radio" name="p7" value="c">c. 16π/15 u<sup>3</sup></br> <!--Incorrecta--> <input type="radio" name="p7" value="d">d. 18π/2 u<sup>3</sup></br> <br> <!--PREGUNTA 8--> <h5>8.-La base de un sólido es la región del plano xy acotado por las gráficas de y<sup>2</sup>=4x y x=4.Calcular el volumen del solido suponiendo que las secciones transversales que se obtienen al contarlos con planos perpendiculares al eje y son semicírculos con diámetro de la base.</h5> <!--Correcta--> <input type="radio" name="p8" value="a">a. 128π/25 u<sup>3</sup></br> <!--Incorrecta--> <input type="radio" name="p8" value="b">b. 138π/25 u<sup>3</sup></br> <!--Incorrecta--> <input type="radio" name="p8" value="c">c. 180π/24 u<sup>3</sup></br> <!--Incorrecta--> <input type="radio" name="p8" value="d">d. 158π/24 u<sup>3</sup></br> <br> <!--PREGUNTA 9--> <h5>9.-Hallar la longitud del arco de la función y=ln(sec(x)),en el intervalo [0,π/4] </h5> <!--Incorrecta--> <input type="radio" name="p9" value="a">a. ln(10-√9)</br> <!--Incorrecta--> <input type="radio" name="p9" value="b">b. ln(1+√5)</br> <!--Correcta--> <input type="radio" name="p9" value="c">c. ln(1+√2)</br> <!--Incorrecta--> <input type="radio" name="p9" value="d">d. ln(1)</br> <br> <!--PREGUNTA 10--> <h5>10.-Hallar la longitud del arco de la curva 9y<sup>2</sup>=4x<sup>3</sup> comprendido entre los puntos de la curba de abscisa x=0 y x=3</h5> <!--Correcta--> <input type="radio" name="p10" value="a">a. 2/5√27 u</br> <!--Incorrecta--> <input type="radio" name="p10" value="b">b. 3/5√5 u</br> <!--Incorrecta--> <input type="radio" name="p10" value="c">c. √18 u</br> <!--Incorrecta--> <input type="radio" name="p10" value="d">d. √8/16 u</br> <br> <input type="submit" id="submit" value="Enviar"> <br> <a class="regreso" href="PARCIAL1.html">Regresar.</a><br> <div id="resultado"></div> <p>Asegurate de contestar todas las preguntas.</p> <br> </form> </section> </div> <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script src="js/resp2.js"></script> <script src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> </body>
import axios from "axios"; import React from "react"; import { useEffect } from "react"; import { useState } from "react"; import { useContext } from "react"; import { useParams } from "react-router-dom"; import { DataContext } from "../../context/DataContextProvider"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; function SingalMember({ member }) { const params = useParams(); console.log(params); const { user } = useContext(DataContext); const [isUser, setIsUser] = useState(false); useEffect(() => { async function fetchData() { let res = await axios({ method: "get", url: `http://localhost:5000/api/v1/groupinfo/${params.groupID}`, headers: { token: window.localStorage.getItem("token"), }, }); console.log(res); setIsUser(res.data.group.owner === user._id); } fetchData(); }, []); const handleDeleteUser = async () => { console.log(member); let res = await axios({ method: "delete", url: `http://localhost:5000/api/v1/delete/${params.groupID}/${member._id}`, headers: { token: window.localStorage.getItem("token"), }, }); toast(res.data.msg, { position: "top-center", autoClose: 5000, hideProgressBar: true, closeOnClick: true, pauseOnHover: false, draggable: true, type: "success", theme: "dark", }); window.location.reload(); }; return ( <> <div className="sigl-member"> <div className="user-member-detail"> <div className="user-info"> <div className="user-name"> <b>{member.name}</b> </div> <div className="user-email">{member.email}</div> </div> <div className="close-btn" onClick={handleDeleteUser}> {isUser ? ( <span className="material-symbols-outlined" onClick={handleDeleteUser} > delete </span> ) : ( "" )} </div> </div> </div> <ToastContainer position="top-right" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover /> </> ); } export default SingalMember;
import { Box } from "@mui/material"; import React from "react"; import { Stack } from "@mui/material"; import { Link } from "react-router-dom"; import logo from "../assets/logo.png"; import SearchBar from "./SearchBar"; import { Padding } from "@mui/icons-material"; import ColorMode from "./ColorMode"; const Navbar = ({ toggle, mode }) => { console.log(mode); return ( <Stack direction="row" alignItems="center" sx={{ position: "sticky", top: 0, justifyContent: "space-between", padding: {xs:1, md:2}, zIndex: "3", gap:1, }} backgroundColor={mode ? "white" : "black"} > <Link to="/"> <img src={logo} alt="logo" height="45px" /> </Link> <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center" }} > <SearchBar></SearchBar> <ColorMode toggle={toggle}></ColorMode> </Box> </Stack> ); }; export default Navbar;
import { _ } from 'svelte-i18n'; import { get } from 'svelte/store'; import DS from '../storages/data.js'; import CategoryGroup from './category-group.js'; import Category from './category.js'; export default class Collection { constructor(id, name, active, parentCollection = null) { this.id = id; this.name = name; this.words = []; this.active = active; this.categoryGroup = new CategoryGroup(id); this.parentCollection = parentCollection; if (this.active) { let getTranslate = get(_); this.title = getTranslate(`collection.items.${name}.title`); this.shortDescription = getTranslate(`collection.items.${name}.text`); this.fullDescription = getTranslate(`collection.items.${name}.description`); } } load() { this.loadCategories().then(() => { if (this.parentCollection !== null) { this.categoryGroup.concat(this.parentCollection.categoryGroup); } this.categoryGroup.loadWordIds(false); }); } checkCategory(category, counter, numberCategories, resolve) { if (category.isLoaded()) { if (++counter === numberCategories) { resolve(); } } else { setTimeout(() => { this.checkCategory(category, counter, numberCategories, resolve); }, 500); } } loadCategories() { let counter = 0; return new Promise((resolve) => { DS.getCategoryList(this.id).then((categories) => { categories.forEach((cat) => { let category = new Category(cat.id, this.id, cat.name, cat.czechName, cat.icon); category.loadWordIds(false); this.categoryGroup.push(category); this.checkCategory(category, counter, categories.length, resolve); }); }); }); } }
import React from 'react'; import { useQuery } from 'react-query'; import Loading from '../Shared/Loading/Loading'; import UserRow from '../UserRow/UserRow'; const AllUsers = () => { const {data: users, isLoading, refetch } = useQuery('users', () => fetch('https://calm-beyond-17543.herokuapp.com/user',{ method: 'GET', headers:{ authorization: `Bearer ${localStorage.getItem('accessToken')}` } }).then(res=>res.json())); if(isLoading){ return <Loading></Loading> } return ( <div> <h2 className='text-center text-4xl mt-8'><u>All Users</u></h2> <div class="overflow-x-auto"> <table class="table w-full mt-3"> <thead> <tr> <th></th> <th>Email</th> <th>Admin</th> <th>Remove</th> </tr> </thead> <tbody> { users.map( user => <UserRow key={user._id} user={user} refetch ={refetch} ></UserRow>) } </tbody> </table> </div> </div> ); }; export default AllUsers;
<?php function register_testimonial_post_type() { $labels = array( 'name' => _x( 'Testimonials', 'Post Type General Name', 'kitces' ), 'singular_name' => _x( 'Testimonial', 'Post Type Singular Name', 'kitces' ), 'menu_name' => __( 'Testimonials', 'kitces' ), 'name_admin_bar' => __( 'Testimonials', 'kitces' ), 'parent_item_colon' => __( 'Testimonial:', 'kitces' ), 'all_items' => __( 'All Testimonials', 'kitces' ), 'add_new_item' => __( 'Add New Testimonial', 'kitces' ), 'add_new' => __( 'Add New', 'kitces' ), 'new_item' => __( 'New Testimonial', 'kitces' ), 'edit_item' => __( 'Edit Testimonial', 'kitces' ), 'update_item' => __( 'Update Testimonial', 'kitces' ), 'view_item' => __( 'View Testimonial', 'kitces' ), 'search_items' => __( 'Search Testimonial', 'kitces' ), 'not_found' => __( 'Not found', 'kitces' ), 'not_found_in_trash' => __( 'Not found in Trash', 'kitces' ), 'items_list' => __( 'Testimonials List', 'kitces' ), 'items_list_navigation' => __( 'Testimonials List Navigation', 'kitces' ), 'filter_items_list' => __( 'Filter Testimonials List', 'kitces' ), ); $args = array( 'label' => __( 'Testimonial', 'kitces' ), 'description' => __( 'Add testimonials to the site.', 'kitces' ), 'labels' => $labels, 'supports' => array( 'title', 'thumbnail' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-testimonial', 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => false, 'has_archive' => false, 'exclude_from_search' => true, 'publicly_queryable' => true, 'capability_type' => 'post', ); register_post_type( 'testimonials', $args ); } add_action( 'init', 'register_testimonial_post_type', 0 );
import { MDBInput, MDBBtn, MDBSelect } from "mdb-react-ui-kit"; import { useState } from "react"; import { useLoaderData, useNavigate } from "react-router-dom"; import { useTheContext } from "../context/Context"; export default function BackOfficeModifCar() { const navigate = useNavigate(); const { car, plugTypes } = useLoaderData(); const { apiService } = useTheContext(); const [vFormData, setvFormData] = useState({ brand: car?.brand ?? "", model: car?.model ?? "", plug_type_id: car?.plug_type_id ?? "", }); const editCar = async (newData) => { try { const response = await apiService.put(`/vehicle/${car.id}`, newData); console.info(response); } catch (err) { console.error(err); } }; const onSubmit = async (e) => { e.preventDefault(); await editCar(vFormData); navigate("/backoffice/cars"); }; const handleChange = (e) => setvFormData({ ...vFormData, [e.target.name]: e.target.value, }); // le composant select de mdbootstrap fonctionne différement des autres ("e.value" au lieu de "e.target.value") const handleSelect = (e) => setvFormData({ ...vFormData, plug_type_id: e.value, }); const options = plugTypes; return ( <div className="registerInfos-container"> <div className="login-form"> <h1>Modidfier un véhicule</h1> <MDBInput className="mb-4" type="string" name="brand" label="Marque" value={vFormData.brand} onChange={handleChange} /> <MDBInput className="mb-4" type="string" name="model" label="Modèle" value={vFormData.model} onChange={handleChange} /> <MDBSelect name="plug_type_id" label="Type de prise" className="select-btn" value={vFormData.plug_type_id} data={options.map((plugType) => ({ text: plugType.name, value: plugType.id, }))} onValueChange={handleSelect} /> <MDBBtn type="submit" className="mb-4" block onClick={onSubmit}> Enregistrer le nouveau véhicule </MDBBtn> </div> </div> ); }
package com.example.individualproject.data.db import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.example.individualproject.data.model.Words import kotlinx.coroutines.flow.Flow @Dao interface WordsDao { @Query("SELECT * FROM Words WHERE isCompleted = 0 AND title LIKE '%' || :query || '%' ORDER BY title ASC") fun getAll(query: String): Flow<List<Words>> @Query("SELECT * FROM Words WHERE isCompleted = 1 AND title LIKE '%' || :query || '%' ORDER BY title ASC") fun getAllCompleted(query: String): Flow<List<Words>> @Query("SELECT * FROM Words WHERE id = :id") fun getWordsById(id: Int): Words? @Insert(onConflict = OnConflictStrategy.REPLACE) fun addWords(words: Words) @Update(onConflict = OnConflictStrategy.REPLACE) fun updateWords(words: Words) @Delete fun deleteWords(words: Words) }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.security.Timestamp; import java.util.List; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import modelo.DashboardDAO; import modelo.Movimientos; import vistas.MainDashBoard; /** * * @author Antonio Noguera */ public class ControladorDashboard implements ActionListener{ DashboardDAO dao = new DashboardDAO(); Movimientos e = new Movimientos(); MainDashBoard dVista = new MainDashBoard(); DefaultTableModel modelo = new DefaultTableModel(); public ControladorDashboard(MainDashBoard v){ this.dVista=v; this.dVista.btnGuardar.addActionListener(this); this.dVista.jButton1.addActionListener(this); this.dVista.MovimientosTabla.getSelectionModel().addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int selectedRow = dVista.MovimientosTabla.getSelectedRow(); if (selectedRow != -1) { // Obtener datos de la fila seleccionada Object[] rowData = new Object[modelo.getColumnCount()]; for (int i = 0; i < modelo.getColumnCount(); i++) { rowData[i] = modelo.getValueAt(selectedRow, i); } dVista.txtMovimientoID.setText(String.valueOf(rowData[0])); dVista.comboEntrada.setSelectedItem(String.valueOf(rowData[3])); dVista.comboElemento.setSelectedItem(String.valueOf(rowData[1])); dVista.txtCantidad.setText(String.valueOf(rowData[2])); } } } }); this.dVista.btnEliminar.addActionListener(this); this.dVista.btnActualizar.addActionListener(this); } public void listar(JTable tabla){ modelo=(DefaultTableModel)tabla.getModel(); modelo.setRowCount(0); List<Movimientos> lista=dao.listar(); Object[] object = new Object[6]; for(int i=lista.size()-1;i>-1;i--){ object[0] = lista.get(i).getMovimiento_ID(); object[1] = lista.get(i).getElementoNombre(); object[2] = lista.get(i).getMovimiento_Cant(); object[3] = lista.get(i).getMovimiento_Tipo(); object[4] = lista.get(i).getMovimiento_Tiempo(); modelo.addRow(object); } dVista.MovimientosTabla.setModel(modelo); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==dVista.btnGuardar){ agregar(); } if(e.getSource()==dVista.btnEliminar){ eliminar(); } if(e.getSource()==dVista.btnActualizar){ actualizar(); } if(e.getSource()==dVista.jButton1){ ClearALL(); } } public void eliminar(){ Movimientos m = new Movimientos(); m.setMovimiento_ID(Integer.valueOf(dVista.txtMovimientoID.getText())); if(dao.Eliminar(m)==1){ ClearALL(); }else{ System.out.println("ERROR"); } listar(dVista.MovimientosTabla); } public void actualizar(){ String tipoMov = (String) dVista.comboEntrada.getSelectedItem(); String elementoNombre = (String) dVista.comboElemento.getSelectedItem(); Float cantidad = Float.valueOf(dVista.txtCantidad.getText()); Integer id = Integer.valueOf(dVista.txtMovimientoID.getText()); System.out.println(tipoMov+" "+elementoNombre+" "+cantidad+" "+id+" "); dao.Actualizar(new Movimientos(id,tipoMov, elementoNombre,cantidad)); listar(dVista.MovimientosTabla); } public void ClearALL(){ System.out.println("CALLED"); dVista.txtMovimientoID.setText(" "); dVista.comboEntrada.setSelectedIndex(0); dVista.comboElemento.setSelectedIndex(0); dVista.txtCantidad.setText(" "); } public void agregar(){ Movimientos m = new Movimientos(); System.out.println("CONTROLLER"); String tipoMov = (String) dVista.comboEntrada.getSelectedItem(); String elementoNombre = (String) dVista.comboElemento.getSelectedItem(); Float cantidad = Float.valueOf(dVista.txtCantidad.getText()); int result = dao.Agregar(new Movimientos(tipoMov, elementoNombre,cantidad)); if(result==1){ dVista.comboEntrada.setSelectedIndex(0); dVista.comboElemento.setSelectedIndex(0); dVista.txtCantidad.setText(" "); }else{ System.out.println("ERROR"); } listar(dVista.MovimientosTabla); } public void arrayMembers(){ JComboBox<String> comboBox = dVista.comboElemento; comboBox.removeAllItems(); List<String> miembros = dao.elementos(); for(String memberUnit : miembros){ comboBox.addItem(memberUnit); } } }
import { CONSOLIDATIONS_TABLE, DELEGATIONS_TABLE, NFTDELEGATION_BLOCKS_TABLE, TRANSACTIONS_TABLE } from './constants'; import { getDataSource } from './db'; import { BlockEntity } from './entities/IBlock'; import { Consolidation, Delegation, NFTDelegationBlock } from './entities/IDelegation'; import { Transaction } from './entities/ITransaction'; import { areEqualAddresses } from './helpers'; import { Logger } from './logging'; import { insertWithoutUpdate } from './orm_helpers'; import { loadEnv } from './secrets'; import { TDH_CONTRACTS } from './tdhLoop/tdh'; const logger = Logger.get('RESTORE_DUMPS'); const BASE_PATH = 'https://6529bucket.s3.eu-west-1.amazonaws.com/db-dumps/production'; export async function restoreDumps() { await loadEnv(); await restoreTransactions(); await restoreDelegations(); await restoreConsolidations(); await restoreNFTDelegationBlocks(); logger.info(`[COMPLETE]`); process.exit(0); } async function getData(path: string) { const response = await fetch(`${BASE_PATH}/${path}.csv`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const csvText = await response.text(); const rows = csvText.split('\n'); return rows; } const getValue = (headers: any[], columns: any[], column: string) => { const index = headers.indexOf(column); if (index === -1) { return null; } return columns[index]; }; async function restoreTransactions() { const tableName = TRANSACTIONS_TABLE; logger.info(`[TABLE ${tableName}] : [DOWNLOADING...]`); const [headerRow, ...data] = await getData(tableName); logger.info( `[TABLE ${tableName}] : [FOUND ${data.length} ROWS] : [PARSING...]` ); const headers = headerRow.split(','); const transactions: Transaction[] = data.map((row) => { const columns = row.split(','); return { created_at: getValue(headers, columns, 'created_at'), transaction: getValue(headers, columns, 'transaction'), block: getValue(headers, columns, 'block'), transaction_date: getValue(headers, columns, 'transaction_date'), from_address: getValue(headers, columns, 'from_address'), to_address: getValue(headers, columns, 'to_address'), contract: getValue(headers, columns, 'contract'), token_id: getValue(headers, columns, 'token_id'), token_count: getValue(headers, columns, 'token_count'), value: getValue(headers, columns, 'value'), primary_proceeds: getValue(headers, columns, 'primary_proceeds'), royalties: getValue(headers, columns, 'royalties'), gas_gwei: getValue(headers, columns, 'gas_gwei'), gas_price: getValue(headers, columns, 'gas_price'), gas_price_gwei: getValue(headers, columns, 'gas_price_gwei'), gas: getValue(headers, columns, 'gas') }; }); const filteredTransactions = transactions.filter((t) => TDH_CONTRACTS.some((c: string) => areEqualAddresses(t.contract, c)) ); logger.info( `[TABLE ${tableName}] : [PARSED ${transactions.length} (${filteredTransactions.length}) TRANSACTIONS] : [RESTORING LOCAL DB]` ); await restoreEntity(tableName, Transaction, filteredTransactions); logger.info(`[TABLE ${tableName}] : [RESTORED]`); } async function restoreDelegations() { const tableName = DELEGATIONS_TABLE; logger.info(`[TABLE ${tableName}] : [RESTORING...]`); const [headerRow, ...data] = await getData(tableName); logger.info( `[TABLE ${tableName}] : [FOUND ${data.length} ROWS] : [PARSING...]` ); const headers = headerRow.split(','); const delegations: Delegation[] = data.map((row) => { const columns = row.split(','); return { created_at: getValue(headers, columns, 'created_at'), block: getValue(headers, columns, 'block'), from_address: getValue(headers, columns, 'from_address'), to_address: getValue(headers, columns, 'to_address'), collection: getValue(headers, columns, 'collection'), use_case: getValue(headers, columns, 'use_case'), expiry: getValue(headers, columns, 'expiry'), all_tokens: getValue(headers, columns, 'all_tokens'), token_id: getValue(headers, columns, 'token_id') }; }); logger.info( `[TABLE ${tableName}] : [PARSED ${delegations.length} DELEGATIONS] : [RESTORING LOCAL DB]` ); await restoreEntity(tableName, Delegation, delegations); logger.info(`[TABLE ${tableName}] : [RESTORED]`); } async function restoreConsolidations() { const tableName = CONSOLIDATIONS_TABLE; logger.info(`[TABLE ${tableName}] : [RESTORING...]`); const [headerRow, ...data] = await getData(tableName); logger.info( `[TABLE ${tableName}] : [FOUND ${data.length} ROWS] : [PARSING...]` ); const headers = headerRow.split(','); const consolidations: Consolidation[] = data.map((row) => { const columns = row.split(','); return { created_at: getValue(headers, columns, 'created_at'), block: getValue(headers, columns, 'block'), wallet1: getValue(headers, columns, 'wallet1'), wallet2: getValue(headers, columns, 'wallet2'), confirmed: getValue(headers, columns, 'confirmed') }; }); logger.info( `[TABLE ${tableName}] : [PARSED ${consolidations.length} CONSOLIDATIONS] : [RESTORING LOCAL DB]` ); await restoreEntity(tableName, Consolidation, consolidations); logger.info(`[TABLE ${tableName}] : [RESTORED]`); } async function restoreNFTDelegationBlocks() { const tableName = NFTDELEGATION_BLOCKS_TABLE; logger.info(`[TABLE ${tableName}] : [RESTORING...]`); const [headerRow, ...data] = await getData(tableName); logger.info( `[TABLE ${tableName}] : [FOUND ${data.length} ROWS] : [PARSING...]` ); const headers = headerRow.split(','); const blocks: BlockEntity[] = data.map((row) => { const columns = row.split(','); return { created_at: getValue(headers, columns, 'created_at'), block: getValue(headers, columns, 'block'), timestamp: getValue(headers, columns, 'timestamp') }; }); logger.info( `[TABLE ${tableName}] : [PARSED ${blocks.length} BLOCKS] : [RESTORING LOCAL DB]` ); await restoreEntity(tableName, NFTDelegationBlock, blocks); logger.info(`[TABLE ${tableName}] : [RESTORED]`); } async function restoreEntity(tableName: string, entity: any, data: any) { await getDataSource().transaction(async (connection) => { const repo = connection.getRepository(entity); await connection.query(`TRUNCATE TABLE ${tableName}`); // save in chunks of 10000 const chunkSize = 10000; for (let i = 0; i < data.length; i += chunkSize) { const chunk = data.slice(i, i + chunkSize); await insertWithoutUpdate(repo, chunk); const percentComplete = ((i + chunk.length) / data.length) * 100; logger.info( `[TABLE ${tableName}] : [${percentComplete.toFixed()}% COMPLETE]` ); } }); } restoreDumps();
#include <ros/ros.h> #include <opencv3/opencv.hpp> #include <sensor_msgs/PointCloud2.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/filters/voxel_grid.h> #include <pcl_handler/FloatList.h> #include <pcl_handler/keyframeMsg.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <pcl/point_types.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/features/normal_3d.h> #include <tf/transform_broadcaster.h> #include <pcl/filters/statistical_outlier_removal.h> #include <pcl/sample_consensus/ransac.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/passthrough.h> #include <message_filters/subscriber.h> #include <message_filters/time_synchronizer.h> #include "sophus/sim3.hpp" // K = np.array([[506.933047262, 0.0, 321.4629011], matrix definition used before in the python script // [0.0, 508.079839422, 243.86413906], // [0.0, 0.0, 1.0]], np.float32) float K[3][3] = {{506.933047262, 0.0 , 321.4629011 }, { 0.0 , 508.079839422, 243.86413906}, { 0.0 , 0.0 , 1.0 }}; struct InputPointDense { float idepth; float idepth_var; unsigned char color[4]; }; class PCL_handler{ private: ros::Publisher pub; ros::Subscriber sub; ros::NodeHandle nh; public: PCL_handler(){ sub = nh.subscribe<pcl_handler::keyframeMsg>("/lsd_slam/keyframes", 1000, &PCL_handler::callback, this); pub = nh.advertise<sensor_msgs::PointCloud2>("/Pointcloud2LSD", 10); } void callback(const pcl_handler::keyframeMsg::ConstPtr& raw_point_cloud_message){ // this message include the depth map, the pose of the camera and the image in itself float tx = raw_point_cloud_message->camToWorld[0]; float ty = raw_point_cloud_message->camToWorld[1]; float tz = raw_point_cloud_message->camToWorld[2]; float qw = raw_point_cloud_message->camToWorld[3]; float qx = raw_point_cloud_message->camToWorld[4]; float qy = raw_point_cloud_message->camToWorld[5]; float qz = raw_point_cloud_message->camToWorld[6]; static tf::TransformBroadcaster br; tf::Transform transform; transform.setOrigin(tf::Vector3(tx, ty, tz)); transform.setRotation(tf::Quaternion(qx, qy, qz, qw)); br.sendTransform(tf::StampedTransform(transform, ros::Time(raw_point_cloud_message->time), "camera", "world")); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr PCLRemoval (new pcl::PointCloud<pcl::PointXYZ>); InputPointDense* originalInput = new InputPointDense[raw_point_cloud_message->width*raw_point_cloud_message->height]; memcpy(originalInput, raw_point_cloud_message->pointcloud.data(), raw_point_cloud_message->width*raw_point_cloud_message->height*sizeof(InputPointDense)); // If there are no points then we're done. if(originalInput == 0) return; // Get pose from received lsd-slam pointcloud relative to starting pose of lsd-slam. Sophus::Sim3f camToWorld; memcpy(camToWorld.data(), raw_point_cloud_message->camToWorld.data(), 7*sizeof(float)); // Get camera parameters from lsd-slam node. Needed to compute 3D coordinates. double fx = raw_point_cloud_message->fx; double fy = raw_point_cloud_message->fy; double cx = raw_point_cloud_message->cx; double cy = raw_point_cloud_message->cy; double fxi = 1/fx; double fyi = 1/fy; double cxi = -cx / fx; double cyi = -cy / fy; pcl::PointXYZ point; // For each point in the recieved lsd-slam pointcloud message, // calculate its 3D real world coordinate. Formerly they were image coordinates. for(int y=1;y<raw_point_cloud_message->height-1;y++) { for(int x=1;x<raw_point_cloud_message->width-1;x++) { // Skip all points with zero depths. if(originalInput[x+y*raw_point_cloud_message->width].idepth <= 0) { continue; } // Calculate the depth of the point. float depth = 1 / originalInput[x+y*raw_point_cloud_message->width].idepth; // Create 3D point, with lsd-slam pose transformation. Sophus::Vector3f transformed_point = camToWorld * (Sophus::Vector3f((x*fxi + cxi), (y*fyi + cyi), 1) * depth); point.x = transformed_point[0]; point.y = transformed_point[1]; point.z = transformed_point[2]; // Add point to pointcloud. cloud->points.push_back(point); } } // here the pointcloud is filled with the correct values // now, we transform the pointcloud<PointXYZ> in pointcloud2 pcl::VoxelGrid<pcl::PointXYZ> sor; sor.setInputCloud(cloud); //LeafSize is a voxel raster leaf size parameter, where each // element represents the dimension of the voxel in the XYZ direction. // The unit is m, where 0.01 represents one centimeter. sor.setLeafSize (0.05f, 0.05f, 0.05f); sor.filter(*cloud_filtered); printf("filter applied\n"); pcl::StatisticalOutlierRemoval<pcl::PointXYZ> removal; removal.setInputCloud(cloud_filtered); removal.setMeanK(50); removal.setStddevMulThresh(1.0); removal.filter(*PCLRemoval); printf("outlier removed\n"); sensor_msgs::PointCloud2 msgToSend; pcl::toROSMsg(*PCLRemoval, msgToSend); msgToSend.header.stamp = ros::Time(raw_point_cloud_message->time); msgToSend.header.frame_id = "camera"; pub.publish(msgToSend); std::cout << "pointcloud sent" << std::endl; } }; int main (int argc, char** argv) { // Initialize ROS ros::init(argc, argv, "pclHandler"); PCL_handler handler; ros::spin(); return 0; }
"use client"; import { useState } from "react"; import { motion } from "framer-motion"; const Video = () => { const videoUrl = "https://cdn.pixabay.com/vimeo/849610807/ocean-173530.mp4?width=360&hash=de6ae525ac689219f1ab32778c2da557e12a4070"; // Replace with a valid video URL const [expanded, setExpanded] = useState(false); const toggleExpansion = () => { setExpanded(!expanded); }; return ( <div className={`video-player ${expanded ? "expanded" : ""}`}> <motion.div className="video-container" initial={{ opacity: 0, scale: 0.8 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 0.3 }} onClick={toggleExpansion} > <div className={`video-content ${expanded ? "expanded" : ""}`}> <video controls onDoubleClick={(e) => e.stopPropagation()} onClick={toggleExpansion} className="video" > <source src={videoUrl} type="video/mp4" /> Your browser does not support the video tag. </video> </div> </motion.div> <style jsx>{` .video-player { width: ${expanded ? "100%" : "300px"}; transition: width 0.3s; } .expanded .video-container { max-height: ${expanded ? "none" : "calc(56.25vw)"}; } .video-container { overflow: hidden; width: 100%; max-width: 100%; aspect-ratio: 16 / 9; max-height: ${expanded ? "none" : "calc(56.25vw)"}; border-radius: ${expanded ? "0" : "50%"}; } .video-content { width: 100%; height: 90px; padding-bottom: 100%; /* Maintain aspect ratio */ position: relative; border-radius: 50%; overflow: hidden; // padding-bottom: 56.25%; } .video { position: absolute; width: 100%; height: 100%; top: 0%; right: 0%; border: ${expanded ? "none" : "0px solid white"}; object-fit: cover; } `}</style> </div> ); }; export default Video;
import "@testing-library/jest-dom"; import { render, screen, fireEvent } from "@testing-library/react"; import { AppContextProvider } from "../../context"; import { IContextMock, ILocaleMock } from "../../__mocks__/types"; import { EndpointForm } from ".."; const APIEndpoint = "https://rickandmortyapi.com/graphql"; const mockToggleDocOpened = jest.fn(); const mockSetApiEndpoint = jest.fn(); jest.mock("../../hooks/useAppContext", () => ({ useAppContext: (): IContextMock => ({ apiEndpoint: APIEndpoint, setApiEndpoint: mockSetApiEndpoint, }), })); jest.mock("../../hooks/useLocale", () => ({ useLocale: (): ILocaleMock => ({ playground: { saveButton: "Save", }, }), })); jest.mock("../../services/firebase", () => ({ auth: { getAuth: jest.fn(), }, })); function renderComponent(): void { render( <AppContextProvider> <EndpointForm toggleDocOpened={mockToggleDocOpened} /> </AppContextProvider>, ); } describe("should save new API endpoint on blur.", () => { test("should save new API endpoint if current value and new value are different.", () => { renderComponent(); const input = screen.getByPlaceholderText(APIEndpoint); expect(input).toBeInTheDocument(); fireEvent.change(input, { target: { value: "https://new-api.example.com" } }); fireEvent.blur(input); expect(mockSetApiEndpoint).toHaveBeenCalled(); }); test("should render an input and a button.", () => { renderComponent(); const input = screen.getByPlaceholderText(APIEndpoint); const saveButton = screen.getByRole("button", { name: /save/i }); expect(input).toBeInTheDocument(); expect(saveButton).toBeInTheDocument(); }); test("should close Doc panel on click on input.", () => { renderComponent(); const input = screen.getByPlaceholderText(APIEndpoint); expect(input).toBeInTheDocument(); fireEvent.click(input); expect(mockToggleDocOpened).toHaveBeenCalledWith(false); }); test("should input other input value.", () => { renderComponent(); const input = screen.getByPlaceholderText(APIEndpoint); expect(input).toBeInTheDocument(); fireEvent.change(input, { target: { value: "https://new-api.example.com" } }); expect(screen.getByDisplayValue("https://new-api.example.com")).toBeInTheDocument(); }); });
<p align="center"> <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a> </p> [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 [circleci-url]: https://circleci.com/gh/nestjs/nest <p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p> <p align="center"> <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a> <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a> <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a> <a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a> <a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a> <a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a> <a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a> <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a> <a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a> <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a> <a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a> </p> <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer) [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)--> ## Description Simple CRUD application with NestJS and MongoDB for managing employees. Make sure you have installed all required npm packages. Look for dependencies in package.json file. ## Install dependencies ```bash $ npm install ``` ## Running the app ```bash # development $ npm run start # watch mode $ npm run start:dev ``` ## Routes: </br> - GET all employees:</br> http://localhost:3000/api/employees </br> \*Pagination setting: define query in request. </br> example: http://localhost:3000/api/employees/?pageSize=2&pageNumber=4 </br> - GET employee by ID(provide valid ID):</br> http://localhost:3000/api/employees/61b1dc035ed03c92ef1a5d13</br> - POST empoyee(provide valid request body) </br> http://localhost:3000/api/employees </br> - PUT employee(provide valid request body and valid ID) </br> http://localhost:3000/api/employees/61b1dc035ed03c92ef1a5d13 </br> - DELETE employee(provide valid ID)</br> http://localhost:3000/api/employees/61b1dc035ed03c92ef1a5d13 </br></br> ## Example of valid request body: </br> </br> <pre> { "name": "Marko", "email_address": "[email protected]", "phone_number": "+381651234567", "home_address": { "city": "Beograd", "zip_code": "11000", "address_1": "Bulevar Nikole Tesle 50" }, "date_of_birth": "1991-02-25" } </pre>
import { useSelector, useDispatch } from 'react-redux'; import { updateDateString } from '../redux/actions.js'; const Day = ({ day, isWeekend, belongTo }) => { const store = useSelector(store => store.content); const dispatch = useDispatch(); const updateDate = (e) => { const daySelected = +e.target.textContent; const month = store.monthIndex; const year = store.year; if (e.target.classList.contains('prevMonth')) { if (month === 0) { const date = new Date((year - 1), 11, daySelected); const dateString = date.toLocaleDateString('en-EN', { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric' }); dispatch(updateDateString(store, 0, dateString)); } else { const date = new Date(year, (month - 1), +e.target.textContent); const dateString = date.toLocaleDateString('en-EN', { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric' }); dispatch(updateDateString(store, 0, dateString)); } } else if (e.target.classList.contains('nextMonth')) { if (month === 11) { const date = new Date((year + 1), 0, daySelected); const dateString = date.toLocaleDateString('en-EN', { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric' }); dispatch(updateDateString(store, 0, dateString)); } else { const date = new Date(year, (month + 1), daySelected); const dateString = date.toLocaleDateString('en-EN', { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric' }); dispatch(updateDateString(store, 0, dateString)); } } else { const date = new Date(year, month, daySelected); const dateString = date.toLocaleDateString('en-EN', { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric' }); dispatch(updateDateString(store, daySelected, dateString)); } }; return ( <div className={ `day ${ isWeekend ? 'weekend' : 'notWeekend' } ${ belongTo }` } onClick={ updateDate }> <h3>{ day }</h3> </div> ); }; export default Day
<?php /** * This file contains abstract class for update plugins * * @package Plugin * @subpackage PluginManager * @author Frederic Schneider * @copyright four for business AG <www.4fb.de> * @license https://www.contenido.org/license/LIZENZ.txt * @link https://www.4fb.de * @link https://www.contenido.org */ defined('CON_FRAMEWORK') || die('Illegal call: Missing framework initialization - request aborted.'); /** * Update class for existing plugins, extends PimPluginSetup * * @package Plugin * @subpackage PluginManager * @author frederic.schneider */ class PimPluginSetupUpdate extends PimPluginSetup { // Begin of update routine /** * PimPluginSetupUpdate constructor. * * @throws cDbException * @throws cException * @throws cInvalidArgumentException */ public function __construct() { parent::__construct(); // Check same plugin (uuid) $this->_checkSamePlugin(); // Check for update specific sql files $this->_updateSql(); // Delete "old" plugin $delete = new PimPluginSetupUninstall(); $delete->uninstall(); // Install new plugin $new = new PimPluginSetupInstall(); $new->install(); // Success message parent::info(i18n('The plugin has been successfully updated. To apply the changes please login into backend again.', 'pim')); } /** * Check uuId: You can update only the same plugin * * @throws cException */ private function _checkSamePlugin() { $this->_pimPluginCollection->setWhere('idplugin', parent::_getPluginId()); $this->_pimPluginCollection->query(); while ($result = $this->_pimPluginCollection->next()) { if (parent::$XmlGeneral->uuid != $result->get('uuid')) { parent::error(i18n('You have to update the same plugin', 'pim')); } } } /** * Check for update specific sql files. * If some valid sql file available, PIM does not run uninstall and install sql files. * * @return bool * * @throws cDbException * @throws cException * @throws cInvalidArgumentException */ private function _updateSql() { // Build sql filename with installed plugin version and new plugin // version, i.e.: "plugin_update_100_to_101.sql" (without dots) $tempSqlFilename = "plugin_update_" . str_replace('.', '', $this->_getInstalledPluginVersion()) . "_to_" . str_replace('.', '', parent::$XmlGeneral->version) . ".sql"; // Filename to update sql file $tempSqlFilename = parent::$_PimPluginArchiveExtractor->extractArchiveFileToVariable($tempSqlFilename, 0); $pattern = '/^(CREATE TABLE IF NOT EXISTS|INSERT INTO|UPDATE|ALTER TABLE) `?' . parent::PLUGIN_SQL_PREFIX . '([a-zA-Z0-9\-_]+)`?\b/'; return $this->_processSetupSql($tempSqlFilename, $pattern); } /** * Get installed plugin version. * * @return string The plugin version or empty string. * @throws cException */ private function _getInstalledPluginVersion() { $this->_pimPluginCollection->setWhere('idplugin', parent::_getPluginId()); $this->_pimPluginCollection->query(); if ($result = $this->_pimPluginCollection->next()) { return $result->get('version'); } else { return ''; } } }
using MySqlConnector; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Projeto_Contratos.Cadastros_info { public partial class Cad_Locatario : System.Web.UI.Page { private MySqlConnection connection; protected void Page_Load(object sender, EventArgs e) { connection = new MySqlConnection(SiteMaster.ConnectionString); } public static bool IsCpf(string cpf) { int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 }; int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 }; string tempCpf; string digito; int soma; int resto; cpf = cpf.Trim(); cpf = cpf.Replace(".", "").Replace("-", ""); if (cpf.Length != 11) return false; tempCpf = cpf.Substring(0, 9); soma = 0; for (int i = 0; i < 9; i++) soma += int.Parse(tempCpf[i].ToString()) * multiplicador1[i]; resto = soma % 11; if (resto < 2) resto = 0; else resto = 11 - resto; digito = resto.ToString(); tempCpf = tempCpf + digito; soma = 0; for (int i = 0; i < 10; i++) soma += int.Parse(tempCpf[i].ToString()) * multiplicador2[i]; resto = soma % 11; if (resto < 2) resto = 0; else resto = 11 - resto; digito = digito + resto.ToString(); return cpf.EndsWith(digito); } public bool validateRg(string rg) { //Elimina da string os traços, pontos e virgulas, rg = rg.Replace("-", "").Replace(".", "").Replace(",", ""); //Verifica se o tamanho da string é 9 if (rg.Length == 9) { int[] n = new int[9]; try { n[0] = Convert.ToInt32(rg.Substring(0, 1)); n[1] = Convert.ToInt32(rg.Substring(1, 1)); n[2] = Convert.ToInt32(rg.Substring(2, 1)); n[3] = Convert.ToInt32(rg.Substring(3, 1)); n[4] = Convert.ToInt32(rg.Substring(4, 1)); n[5] = Convert.ToInt32(rg.Substring(5, 1)); n[6] = Convert.ToInt32(rg.Substring(6, 1)); n[7] = Convert.ToInt32(rg.Substring(7, 1)); if (rg.Substring(8, 1).Equals("x") || rg.Substring(8, 1).Equals("X")) { n[8] = 10; } else { n[8] = Convert.ToInt32(rg.Substring(8, 1)); } } catch (Exception) { return false; } //obtém cada um dos caracteres do rg //Aplica a regra de validação do RG, multiplicando cada digito por valores pré-determinados n[0] *= 2; n[1] *= 3; n[2] *= 4; n[3] *= 5; n[4] *= 6; n[5] *= 7; n[6] *= 8; n[7] *= 9; n[8] *= 100; //Valida o RG int somaFinal = n[0] + n[1] + n[2] + n[3] + n[4] + n[5] + n[6] + n[7] + n[8]; if ((somaFinal % 11) == 0) { return true; } else { return false; } } else { return false; } } protected void btnCadastrarLT_Click(object sender, EventArgs e) { if (validateRg(txt_LTRG.Text) == false) { SiteMaster.ExibirAlert(this, "Dados inválidos."); return; } else { if (IsCpf(txt_LTCPF.Text) == false) { SiteMaster.ExibirAlert(this, "Dados inválidos."); return; } else { connection.Open(); var comando = new MySqlCommand($@"INSERT INTO locatario (nome, cpf, rg,profissao,estado_civil) VALUES (@nome,@cpf,@rg,@profissao,@estadocivil)", connection); if (txt_nomeLT.Text == "" || txt_profLT.Text == "" || txt_LTCPF.Text == "" || txt_LTRG.Text == "" || txt_profLT.Text == "") { SiteMaster.ExibirAlert(this, "Preencha todos os campos!"); return; } comando.Parameters.Add(new MySqlParameter("nome", txt_nomeLT.Text)); comando.Parameters.Add(new MySqlParameter("cpf", txt_LTCPF.Text)); comando.Parameters.Add(new MySqlParameter("rg", txt_LTRG.Text)); comando.Parameters.Add(new MySqlParameter("profissao", txt_profLT.Text)); comando.Parameters.Add(new MySqlParameter("estadocivil", DropList.Text)); comando.ExecuteNonQuery(); connection.Close(); SiteMaster.ExibirAlert(this, " Locatário cadastrado com sucesso!"); txt_nomeLT.Text = ""; } } } protected void txt_LTRG_TextChanged(object sender, EventArgs e) { if (validateRg(txt_LTRG.Text) == false) { lblAlertaRG.Text = "RG invalido!"; lblAlertaRG.ForeColor = Color.Red; } else { lblAlertaRG.Text = ""; } } protected void txt_LTCPF_TextChanged(object sender, EventArgs e) { if (IsCpf(txt_LTCPF.Text) == false) { lblAlertaCpf.Text = "CPF invalido!"; lblAlertaCpf.ForeColor = Color.Red; } else { lblAlertaCpf.Text = ""; } } } }
% Testing Suite: Van Der Pol %clear global; % integrator: -1: ERK_FWD_DRIVER_Integrator % -2: ROS_FWD_DRIVER_Integrator % -3: RK_FWD_DRIVER_Integrator % -4: SDIRK_FWD_DRIVER_Integrator % % -5: ERK_TLM_DRIVER_Integrator % -6: ROS_TLM_DRIVER_Integrator % -7: RK_TLM_DRIVER_Integrator % -8: SDIRK_TLM_DRIVER_Integrator % % -9: ERK_ADJ_DRIVER_Integrator % -10: ROS_ADJ_DRIVER_Integrator % -11: RK_ADJ_DRIVER_Integrator % -12: SDIRK_ADJ_DRIVER_Integrator integrator = -1; % Adjoint: -1: xxxxADJ1 w/ Quadrature % -2: xxxxADJ1 no Quadrature % -3: xxxxADJ2 w/ Quadrature % -4: xxxxADJ2 no Quadrature adj_mode = -1; disp( 'Ver Der Pol Problem: ' ); Tspan = [0 500]; y0 = [2;-0.66]; % SDIRK Coefficient ERK Coefficient RK Coefficient Ros Coefficient % 1: Sdirk2A 1: Erk23 1: Rada2A 1: Ros2 % 2: Sdirk2B 2: Erk3_Heun 2: Lobatto3C 2: Ros3 % 3: Sdirk3A 3: Erk43 3: Gauss 3: Ros4 % 4: Sdirk4A 4: Dopri5 4: Radau1A 4: Rodas3 % 5: Sdirk4B 5: Verme 5: Lobatto3A 5: Rodas4 % 6: Dopri853 RelTol = [ 1e-5 1e-5 ]; AbsTol = [ 1e-5 1e-5 ]; ICNTRL = fatOde_ICNTRL_Set( 'Autonomous', 0, ... % 1 'ITOL', 0, ... % 2 'Method', 0, ... % 3 'Max_no_steps', 0, ... % 4 'NewtonMaxit', 0, ... % 5 'StartNewton', 0, ... % 6 'DirectTLM', 0, ... % 7 'SaveLU', 0, ... % 8 'TLMNewtonEst', 0, ... % 9 'SdirkError', 0, ... % 10 'Gustafsson', 0, ... % 11 % 1: fwd_rk 'TLMtruncErr', 0, ... % 12 'FDAprox', 0, ... % 13 'AdjointSolve', 0, ... % 14 'AdjointType', 0, ... % 15 'DirectADJ', 0, ... % 16 'ChunkSize', 50 ); % 17 RCNTRL = fatOde_RCNTRL_Set( 'Hmin', 0, ... 'Hmax', 0, ... 'Hstart', 0, ... 'FacMin', 0, ... 'FacMax', 0, ... 'FacRej', 0, ... 'FacSafe', 0, ... 'ThetaMin', 0, ... 'NewtonTol', 0, ... 'Qmin', 0, ... 'Qmax', 0 ); Options = fatOde_OPTIONS_Set( 'AbsTol', AbsTol, ... 'RelTol', RelTol, ... 'Jacobian', @vanDerPol_Jacobian, ... 'AbsTol_TLM', AbsTol.*10, ... 'RelTol_TLM', RelTol.*10, ... 'Y_TLM', eye(2,2), ... 'NTLM', 2, ... 'AbsTol_ADJ', AbsTol.*10, ... 'RelTol_ADJ', RelTol.*10, ... 'NADJ', 2, ... 'Desired_Mode', -1*adj_mode, ... 'displayStats', true, ... 'displaySteps', false ); Npoints = 7; err = zeros(Npoints,1); steps = zeros(Npoints,1); TOLS = logspace(-7,-1,Npoints); for ipt=1:Npoints RelTol=TOLS(ipt); AbsTol = RelTol; Options = fatOde_OPTIONS_Set( 'RelTol', ones(1,2)*RelTol, ... 'AbsTol', ones(1,2)*AbsTol, ... 'Jacobian', @vanDerPol_Jacobian, ... 'AbsTol_TLM', ones(1,2)*AbsTol, ... 'RelTol_TLM', ones(1,2)*RelTol, ... 'Y_TLM', eye(2,2), ... 'NTLM', 2, ... 'AbsTol_ADJ', ones(1,2)*AbsTol, ... 'AbsTol_ADJ', ones(1,2)*RelTol, ... 'NADJ', 2 ); switch ( integrator ) case -1 disp( 'Solving problem with ERK_FWD_DRIVER_Integrator: ' ); %profile clear; %profile on; cput = cputime; [ T_1, Y_1, ISTATUS_1, RSTATUS_1, Ierr_1, Coefficient_1 ] = ... ERK_FWD_DRIVER_Integrator_old( @vanDerPol_Function, Tspan, y0, Options, RCNTRL, ICNTRL ); cputime_matlODE_old(ipt) = cputime - cput; % cput = cputime; % [ T, Y, ISTATUS, RSTATUS, Ierr, Coefficient ] = ... % ERK_FWD_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, Options, RCNTRL, ICNTRL ); % cputime_matlODE(ipt) = cputime - cput; %profreport('TEST_vanDerPol') implementation = 'FWD'; family = 'ERK'; % Options.AbsTol = Options.AbsTol(1); % Options.RelTol = Options.RelTol(1); % cput = cputime; % [t,y] = ode45(@vanDerPol_Function,Tspan,y0, Options); % cputime_matlab(ipt) = cputime - cput; case -2 disp( 'Solving problem with ROS_FWD_DRIVER_Integrator: ' ); cput = cputime; [ T, Y, ISTATUS, RSTATUS, Ierr, Coefficient ] = ROS_FWD_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); cputime_matlODE(ipt) = cputime - cput; implementation = 'FWD'; family = 'ROS'; Options.AbsTol = Options.AbsTol(1); Options.RelTol = Options.RelTol(1); cput = cputime; [t,y] = ode23(@vanDerPol_Function,Tspan,y0, Options); cputime_matlab(ipt) = cputime - cput; case -3 disp( 'Solving problem with RK_FWD_DRIVER_Integrator: ' ); cput = cputime; [ T, Y, ISTATUS, RSTATUS, Ierr, Coefficient ] = RK_FWD_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); cputime_matlODE(ipt) = cputime - cput; implementation = 'FWD'; family = 'RK'; Options.AbsTol = Options.AbsTol(1); Options.RelTol = Options.RelTol(1); cput = cputime; [t,y] = ode15s(@vanDerPol_Function,Tspan,y0, Options); cputime_matlab(ipt) = cputime - cput; case -4 disp( 'Solving problem with SDIRK_FWD_DRIVER_Integrator: '); cput = cputime; [ T, Y, ISTATUS, RSTATUS, Ierr, Coefficient ] = SDIRK_FWD_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); cputime_matlODE(ipt) = cputime - cput; implementation = 'FWD'; family = 'SDIRK'; Options.AbsTol = Options.AbsTol(1); Options.RelTol = Options.RelTol(1); cput = cputime; [t,y] = ode15s(@vanDerPol_Function,Tspan,y0, Options); cputime_matlab(ipt) = cputime - cput; case -5 disp( 'Solving problem with ERK_TLM_DRIVER_Integrator: ' ); [ T, Y, ISTATUS, RSTATUS, Ierr, Coefficient ] = ERK_TLM_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); implementation = 'TLM'; family = 'ERK'; case -6 disp( 'Solving problem with ROS_TLM_DRIVER_Integrator: '); [ T, Y, ISTATUS, RSTATUS, Ierr, Coefficient ] = ... ROS_TLM_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, Options, RCNTRL, ICNTRL ); implementation = 'TLM'; family = 'ROS'; case -7 disp( 'Solving problem with RK_TLM_DRIVER_Integrator: '); [ T, Y, ISTATUS, RSTATUS, Ierr, Coefficient ] = ... RK_TLM_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, Options, RCNTRL, ICNTRL ); implementation = 'TLM'; family = 'RK'; case -8 disp( 'Solving problem with SDIRK_TLM_DRIVER_Integrator: '); [ T, Y, ISTATUS, RSTATUS, Ierr, Coefficient ] = SDIRK_TLM_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); implementation = 'TLM'; family = 'SDIRK'; case -9 disp( 'Solving problem with ERK_ADJ_DRIVER_Integrator: '); [ T, Y, Lambda, ISTATUS, RSTATUS, Ierr, Coefficient ] = ERK_ADJ_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); implementation = 'ADJ'; family = 'ERK'; case -10 disp( 'Solving problem with ROS_ADJ_DRIVER_Integrator: '); [ T, Y, Lambda, ISTATUS, RSTATUS, Ierr, Coefficient ] = ROS_ADJ_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); implementation = 'ADJ'; family = 'ROS'; case -11 disp( 'Solving problem with RK_ADJ_DRIVER_Integrator: '); [ T, Y, Lambda, ISTATUS, RSTATUS, Ierr, Coefficient ] = RK_ADJ_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); implementation = 'ADJ'; family = 'RK'; case -12 disp( 'Solving problem with SDIRK_ADJ_DRIVER_Integrator: '); [ T, Y, Lambda, ISTATUS, RSTATUS, Ierr, Coefficient ] = SDIRK_ADJ_DRIVER_Integrator( @vanDerPol_Function, Tspan, y0, ... Options, RCNTRL, ICNTRL ); implementation = 'ADJ'; family = 'SDIRK'; end % if ( Ierr(:) >= 0.0 ) % titleName = {['Solution: ' family ' ' implementation ' Integrator (Van Der Pol)'], ... % ['Coefficient: ' num2str(Coefficient.Name) ] }; % % plot( T, Y ); % xlabel('Time'); % ylabel('Y1 & Y2'); % title(titleName); % end % steps(ipt) = length(T); end semilogy(cputime_matlODE,TOLS,cputime_matlODE_old,TOLS); title('Vectorization'); ylabel('ROLS'); xlabel('CPU Time'); legend('optimized','old version');
//##1. simple additive A = [1 2; 3 4] def doings(){ r1 = A + 10 r2 = 10 + A r3 = A + 1 r4 = A + A r5 = A + A +100 partial = A + A^ +100//someone half did this res = [r1, r2, r3, r4, r5, partial] String.join("\n", x + "" for x in res) } ~~~~~ //##2. simple additive on list from java.util import ArrayList Aa = ArrayList<Integer>() Aa.add(1) Aa.add(2) Ab = ArrayList<Integer>() Ab.add(3) Ab.add(4) A = new ArrayList<ArrayList<Integer>>() A.add(Aa) A.add(Ab) def doings(){ r1 = A + 10 r2 = 10 + A r3 = A + 1 r4 = A + A r5 = A + A +100 partial = A + A^ +100//someone half did this res = [r1, r2, r3, r4, r5, partial] String.join("\n", x + "" for x in res) } ~~~~~ //##3. simple additive avoid on op overload object class MyOPOverloaded{ def plus(what int[]) => "ok" override hashCode() => 1 override equals(an Object) => false } A = [1 2] def doings(){ inst = MyOPOverloaded() got = inst + A//we dont expect this to be auto vectorizable "" + got } ~~~~~ //##4. simple multiplacitative A = [1 2; 3 4] def doings(){ r1 = A * 10 r2 = 10 * A r3 = A * 2 r4 = A * A r5 = A * A * 100 partial = A * A^ * 10//someone half did this res = [r1, r2, r3, r4, r5, partial] String.join("\n", x + "" for x in res) } ~~~~~ //##5. simple pow A = [1l 2; 3 4l] def doings(){ r1 = A ** 10 r2 = 10 ** A r3 = A ** 2 r4 = A ** A r5 = A ** A ** 2 partial = A ** A^ ** 2//someone half did this res = [r1, r2, r3, r4, r5, partial] String.join("\n", x + "" for x in res) } ~~~~~ //##6. relational A = [1 2 3 4 5 6 7 8 9 10] def doings(){ r1 = A > 5 r2 = 5 < A r3 = A > 2 r4 = A >== A r5 = A < A partial = A < A^ res = [r1, r2, r3, r4, r5, partial] String.join("\n", x + "" for x in res) } ~~~~~ //##7. eq neq etc class MyClas(avar String) A = [1 2 3 4 5 6 7 8 9 10] someObjects = [MyClas("hi"), MyClas("there")] def doings(){ r1 = A == 5 r2 = 5 == A r3 = A == 2 r4 = A == A r5 = A == A partial = A == A^ ss1 = someObjects == MyClas("there") ss2 = MyClas("there") == someObjects res = [r1, r2, r3, r4, r5, partial, ss1, ss2] String.join("\n", x + "" for x in res) } ~~~~~ //##8. supress auto vect for this case class MyClas(avar int){ def compareTo(a int[]) => a.length - avar } A = [1 2 3 4 5 6 7 8 9 10] def doings(){ ss1 = MyClas(9) >== A ss2 = MyClas(11) >== A "" + [ss1, ss2] } ~~~~~ //##9. but we do want auto vectorization here as operates on int type of A class MyClas(avar int){ def compareTo(a int) => a - avar } A = [1 2 3 4 5 6 7 8 9 10] def doings(){ ss1 = MyClas(9) >== A ss2 = MyClas(11) >== A "" + [ss1, ss2] } ~~~~~ //##10. was broken before class MyClas(avar int){ def plus(a int) => a + avar } A = [1 2 3 4 5 6 7 8 9 10] def doings(){ ss1 = MyClas(9).plus(A^) "" + ss1 } ~~~~~ //##11. vectorize object op override class MyClas(avar int){ def plus(a int) => a + avar override equals(an Object) => false override hashCode() => 11 } A = [1 2 3 4 5 6 7 8 9 10] def doings(){ ss1 = MyClas(9) + A^ "" + ss1 } ~~~~~ //##12. auto vectorize object op override class MyClas(avar int){ def plus(a int) => a + avar override equals(an Object) => false override hashCode() => 11 } A = [1 2 3 4 5 6 7 8 9 10] def doings(){ ss1 = MyClas(9) + A "" + ss1 } ~~~~~ //##13. dont auto vect op override class MyClas(avar int){ def plus(a int[]) => 'cool' + a + avar override equals(an Object) => false override hashCode() => 1 } A = [1 2 3 4 5 6 7 8 9 10] def doings(){ ss1 = MyClas(9) + A //dont support this "" + ss1 } ~~~~~ //##14. list of thing haveing operator overloaded class MyClas(avar int){ def plus(a int) => a + avar override equals(an Object) => false override hashCode() => 1 } A = [MyClas(1) MyClas(2) MyClas(3)] def doings(){ ss1 = A + 10 "" + ss1 } ~~~~~ //##15. list of thing haveing operator overloaded return an array type BASIC class MyClas(avar int){ def plus(a int[]) => a + avar override equals(an Object) => false override hashCode() => 1 } A = [MyClas(1) MyClas(2) MyClas(3)] def doings(){ ss1 = A^ + [10 20 30] //already vect A "" + ss1 } ~~~~~ //##16. list of thing haveing operator overloaded return an array type class MyClas(avar int){ def plus(a int[]) => a + avar override equals(an Object) => false override hashCode() => 1 } A = [MyClas(1) MyClas(2) MyClas(3)] def doings(){ ss1 = A + [10 20 30] "" + ss1 } ~~~~~ //##17. pl this works now class MyClas(avar int){ def compareTo(a int) => a - avar } A = [1 2 3 4 5 6 7 8 9 10] def doings(){ ss1 = MyClas(9) >== A ss2 = MyClas(11) >== A "" + [ss1, ss2] } ~~~~~ //##18. bitshift norm and oo class MyClas(avar int){ def <<(a int) => avar<<a } A = [1 2 3 4 5 6 7 8 9 10] def doings(){ ss1 = MyClas(4) << A ss2 = A << 2 "" + [ss1 ; ss2] } ~~~~~ //##19. is //CANNOT DO THIS AUTO AS AMBIGOUS A = ["hi" Object() Object() "hi"] def doings(){ ss1 = A^ is String ss2 = not (A^ is String)^//fun ss3 = A^ is not String ss4 = not (A^ is not String)^//fun "" + [ss1 ; ss2; ss3; ss4] } ~~~~~ //##20. just works A = ["hi" Object() Object() "hi"] def doings(){ ss1 = A as Object "fine" } ~~~~~ //##21. bitwise norm and oo class MyClas(mask int){ def band(a int) => a band mask } A = [0b001 0b0010 0b0011] //1 2 3 def doings(){ ss1 = A band 0b010 ss2 = MyClas(0b010) band A "" + [ss1 ; ss2] } ~~~~~ //##22. thought id try this class MyClas(thing int){ def inc() => thing++; this@ override toString () => "MyClas {thing}" } def doings(){ a = MyClas(10) b=a a++ "" + [a b a &<> b] } ~~~~~ //##23. prefix norm and oo class MyClas(thing int){ def inc() => thing++; this@ override toString () => "MyClas {thing}" } objs = [MyClas(10) MyClas(6) MyClas(7)] A = [ 1 2 3 4 5 ] def doings(){ inced1 = ++A inced2 = ++objs "" + [A inced1 inced2] } ~~~~~ //##24. postfix norm and oo class MyClas(thing int){ def inc() => thing++; this@ override toString () => "MyClas {thing}" } objs = [MyClas(10) MyClas(6) MyClas(7)] A = [ 1 2 3 4 5 ] def doings(){ inced1 = A++ inced2 = objs++ "" + [A inced1 inced2] } ~~~~~ //##25. prefix neg norm and oo class MyClas(thing int){ def neg() => thing=-thing; this@ override toString () => "MyClas {thing}" } objs = [MyClas(10) MyClas(6) MyClas(7)] A = [ 1 2 3 4 5 ] def doings(){ inced1 = -A inced2 = -objs "" + [A inced1 inced2] } ~~~~~ //##26. assign existing norm and oo class MyClas(thing int){ def +=(a int) => thing+=a; this@ override toString () => "MyClas {thing}" } objs = [MyClas(10) MyClas(6) MyClas(7)] A = [ 1 2 3 4 5 ] def doings(){ A += 10 objs += 10 "" + [A objs] } ~~~~~ //##27. with extension func defined class MyClas(public thing int){ override toString () => "MyClas {thing}" } def MyClas +=(a int) => this.thing+=a; this@ def MyClas +(a int) => this.thing+=a; this@ objs1 = [MyClas(10) MyClas(6) MyClas(7)] objs2 = [MyClas(10) MyClas(6) MyClas(7)] def doings(){ objs1 += 10 objs2 = objs2 + 100 "" + [objs1 ; objs2] } ~~~~~ //##28. bugfix for missing this in ext fucntions on lhs of assignment class MyClas(public thing int){ override toString () => "MyClas {thing}" override equals(an Object) => false override hashCode() => 1 } def MyClas +=(a int) { thing = thing+a; thing += a; this@ } objs1 = [MyClas(10) MyClas(6) MyClas(7)] def doings(){ objs1 += 10 "" + objs1 } ~~~~~ //##29. bugfix for missing this in ext fucntions on lhs of assignment 2 class MyClas(public thing int[]){ override toString () => "MyClas {thing}" override equals(an Object) => false override hashCode() => 1 } def MyClas +=(a int) { thing[0] = thing[0]+a; thing[0] += a; this@ } objs1 = [MyClas([10]) MyClas([6]) MyClas([7])] def doings(){ objs1 += 10 "" + objs1 } ~~~~~ //##30. bugfix on object array copy class MyClas(public thing int){ override toString () => "MyClas {thing}" } objs1 = [MyClas(10) MyClas(6) MyClas(7)] objs2 = objs1@ def doings(){ "" + [objs1 ; objs2] } ~~~~~ //##31. vect on thing with default arg def fella(a int =100 ) => a + 10 ok = [1 2 3] def doings(){ "" +fella(ok^) } ~~~~~ //##32. auto vect on thing with default arg def fella(a int =100 ) => a + 10 ok = [1 2 3] def doings(){//ironically easier to figure out logic here "" +fella(ok) } ~~~~~ //##33. auto vect on thing with no default arg def fella(a int ) => a + 10 ok = [1 2 3] def doings(){ "" +fella(ok) } ~~~~~ //##34. basic funcref invoke def fella(a int ) => a + 10 ok = [1 2 3] def doings(){ thing = fella& "" + thing(ok^) } ~~~~~ //##35. basic funcref invoke auto def fella(a int ) => a + 10 ok = [1 2 3] def doings(){ thing = fella& "" + thing(ok) } ~~~~~ //##36. bugfix on equiv stringrep class MyClas(avar String) A = [1 2 3 4 5 6 7 8 9 10] someObjects = [MyClas("hi"), MyClas("there")] def gefres(){ r1 = A == 5 r2 = 5 == A r3 = A == 2 r4 = A == A r5 = A == A partial = A == A^ ss1 = someObjects == MyClas("there") ss2 = MyClas("there") == someObjects res = [r1, r2, r3, r4, r5, partial, ss1, ss2] res } def doings(){ res = gefres() a = x + "" for x in res b = "" + x for x in res "" + [a == b]//bugfix on string rep, prevsouly these were not equal } ~~~~~ //##37. funcref invoke def getFunc(){ def (a int) => a + 100 } from com.concurnas.lang.precompiled.ListMaker import intList myAr1 = [1 2 3 4] myAr2 = intList(1, 2, 3, 4) def doings(){ xx1 = getFunc()(myAr1) xx2 = getFunc()(myAr2) "" + [xx1, xx2] } ~~~~~ //##38. out param used to breka this def getFunc(){ def (a int) => Integer(a + 100) } from com.concurnas.lang.precompiled.ListMaker import intList myAr1 = [1 2 3 4] myAr2 = intList(1, 2, 3, 4) def doings(){ xx1 = getFunc()(myAr1^) xx2 = getFunc()(myAr2^) "" + [xx1, xx2] } ~~~~~ //##39. auto vect new A = [1 2 3 4 5] class MyClass(a int){ override toString() => "MC: " + a } def doings(){ res1 = new MyClass(A) res2 = MyClass(A) "" + [res1 ; res2] } ~~~~~ //##40. auto vect funcref class and constructor A = [1 2 3 ] class MyClass(a int){ override toString() => "MC: " + a } def doings(){ res1 = new MyClass& res2 = MyClass& res3 = new MyClass&(? int) res4 = MyClass&(? int) "" + [res1(A) ; res2(A) ; res3(A) ; res4(A)] } ~~~~~ //##41. auto vect of funcrefs A = [1 2 3 ] class MyClass(a int){ override toString() => "MC: " + a } def doings(){ res1 = new MyClass&(A) res2 = MyClass&(A) "" + [(x() for x in res1) , (x() for x in res2)] } ~~~~~ //##42. auto vect of actor calls A = [1 2 3 ] class MyClass(a int){ def myFunc(b int) => "hi:" + [a b] override toString() => "MC: " + a } def doings(){ res1 = new actor MyClass(11) a = res1.myFunc(A) b = res1.myFunc&(A) "" + [a, ('&' + p() for p in b)] } ~~~~~ //##43. auto vect of new actor A = [1 2 3 ] class MyClass(a int){ override toString() => "MC: " + a } def doings(){ res1 = actor MyClass(A) res2 = actor MyClass&(A) "" + [res1 , (x() for x in res2)] } ~~~~~ //##44. auto vect of new actor when actor itself A = [1 2 3 ] actor MyClass(a int){ override toString() => "MC: " + a } def doings(){ res1 = new MyClass(A) res2 = new MyClass&(A) res3 = MyClass(A) res4 = MyClass&(A) "" + [res1 , (x() for x in res2), res3 , (x() for x in res4)] } ~~~~~ //##45. auto vect of calls on actor when actor itself A = [1 2 3 ] actor MyClass(a int){ def myFunc(b int) => "hi:" + [a b] override toString() => "MC: " + a } def doings(){ res1 = new actor MyClass(11) a = res1.myFunc(A) b = res1.myFunc&(A) "" + [a, ('&' + p() for p in b)] } ~~~~~ //##46. auto vect expression lists A = [1 2 3 4 5] def myFunc(a int)=> a+100 def doings(){ res1 = myFunc A^ res2 = myFunc A "" + [res1 ; res2] } ~~~~~ //##47. auto vect expression lists class A = [1 2 3] class myClass(a int){ override toString() => "myCls {a}" } def doings(){ res1 = myClass A^ res2 = myClass A "" + [res1 ; res2] } ~~~~~ //##48. auto vect arrayref operations origArray = [1 2 3 4 5 6 7 8 9] A = [ 3 5 6] def doings(){ res = origArray[A ... A+2]//kid of cool "" + res } ~~~~~ //##49. auto vect arrayref operations op overload class MyClass{ origArray = [1 2 3 4 5 6 7 8 9] def sub(a int, b int) => 'cool {origArray[a ... b]}' } A = [ 3 5 6] def doings(){ mc = MyClass() res = mc[A ... A+2] "" + res } ~~~~~ //##50. mkt tmp var when no nested vectees A = [1 2 3 4] def ff() => A def doings() { f = ff()^+1 "" + [A, f] } ~~~~~ //##51. mkt tmp var when no nested vectees AUTO A = [1 2 3 4] def ff() => A def doings() { f = ff()^+1 "" + [A, f] } ~~~~~ //##52. this thing works def doings() { ax = [1 2 3 4 5 6 7 8 9] f = (ax[2 ... 4])^+1 "" + f } ~~~~~ //##53. this thing works AUTO def doings() { ax = [1 2 3 4 5 6 7 8 9] f = ax[2 ... 4]+1 "" + f } ~~~~~ //##54. this thing works AUTO def doings() { ax = [1 2 3 4 5 6 7 8 9] f = ++ax[2 ... 4] "" + f } ~~~~~ //##55. vectorized in expression A = [ 1 2 3 4 5 ] ele = [2 10 4] def doings() { res = ele^ in A "" + res } ~~~~~ //##56. vectorized in expression matr A = [ 1 2 3 4 5 ] elea = [ 4 10 2] ele = [elea;elea] def doings() { res = ele^ in A "" + res } ~~~~~ //##57. vectorized in expression op overload class Myclass{ def \in(a int){ a >== 2 and a < 10 } override hashCode()=>1 override equals(an Object)=>false } elea = [1 2 35 4] ele = [elea;elea] A = Myclass() def doings() { res = ele^ in A "" + res } ~~~~~ //##58. choose correct op overload bug class Myclass{ def what(a int) => a >== 2 and a < 10 def what(ax int[]) => 'hi: {ax[0]==1}' override hashCode()=>1 override equals(an Object)=>false } elea = [1 2 35 4] ele = [elea;elea] A = Myclass() def doings() { res = A.what(ele^) "" + res } ~~~~~ //##59. bugfix on calling of vect funct class Myclass{ def \in(a int) => a >== 2 and a < 10 def \in(ax int[]) => 'hi: {ax[0]==1}' override hashCode()=>1 override equals(an Object)=>false } elea = [1 2 35 4] ele = [elea;elea] A = Myclass() def doings() { res = A.contains(ele^) "" + res } ~~~~~ //##60. vectorized in expression op overload when choices class Myclass{ def \in(a int) => a >== 2 and a < 10 def \in(ax int[]) => 'hi: {ax[0]==1}' override hashCode()=>1 override equals(an Object)=>false } elea = [1 2 35 4] ele = [elea;elea] A = Myclass() def doings() { res = ele^ in A "" + res } ~~~~~ //##61. vectorized in expression op overload when choices EXT function class Myclass{ override hashCode()=>1 override equals(an Object)=>false } def Myclass \in(a int) => a >== 2 and a < 10 elea = [1 2 35 4] ele = [elea;elea] A = Myclass() def doings() { res = ele^ in A "" + res } ~~~~~ //##62. vectorized in expression rhs is vect with oo class Myclass{ override hashCode()=>1 override equals(an Object)=>false } def Myclass \in(a int) => a >== 2 and a < 10 A = [[Myclass() Myclass() Myclass()],] def doings() { //res = 6 in A^ res1 = A^contains(6) res2 = not A^contains(6)^ "" + [res1, res2] } ~~~~~ //##63. vectorized in expression rhs is vect with oo as above but implicit class Myclass{ override hashCode()=>1 override equals(an Object)=>false } def Myclass \in(a int) => a >== 2 and a < 10 A = [[Myclass() Myclass() Myclass()],] def doings() { res1 = 6 in A^ res2 = 6 not in A^ "" + [res1, res2] } ~~~~~ //##64. vectorized in expression list of class Myclass{ def \in(a int) => a >== 2 and a < 10 override hashCode()=>1 override equals(an Object)=>false } A = [[Myclass() Myclass() Myclass()],] def doings() { res1 = 6 in A^ res2 = 6 not in A^ "" + [res1, res2] } ~~~~~ //##65. auto vectoriz in rhs class Myclass{ def \in(a int) => a >== 2 and a < 10 override hashCode()=>1 override equals(an Object)=>false } A = [[Myclass() Myclass() Myclass()],] def doings() { res1 = 6 in A res2 = 6 not in A "" + [res1, res2] } ~~~~~ //##66. auto vectoriz in lhs class Myclass{ override hashCode()=>1 override equals(an Object)=>false } def Myclass \in(a int) => a >== 2 and a < 10 elea = [1 2 35 4] ele = [elea;elea] A = Myclass() def doings() { res = ele in A "" + res } ~~~~~ //##67. field access hat class Myclass(field int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([12 13 14 15]^) def doings() { "" + (A^field) } ~~~~~ //##68. field access hat 2d and goes to getter class Myclass(field int){ def getField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([[12 13 14 15] ; [1 2 3]]^) def doings() { "" + (A^field) } ~~~~~ //##69. field access hat 2d and goes to getter via overriden getter class Myclass(private field int){ def getField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([[12 13 14 15] ; [1 2 3]]^) def doings() { "" + (A^field) } ~~~~~ //##70. via getter but this didnt used to work very well class Myclass(private ~field int){ def getField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([[12 13 14 15] ; [1 2 3]]^) def doings() { "" + (A^field) } ~~~~~ //##71. is field class Myclass(private field boolean){ def isField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([true true]^) def doings() { "" + (A^field) } ~~~~~ //##72. field and subfield class FieldCls(valu int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'FieldCls: {valu}' } class Myclass(field FieldCls){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass( [FieldCls(1) FieldCls(2) ; FieldCls(3) FieldCls(4)]^) def doings() { x = A^field^valu "hi" + x } ~~~~~ //##73. assign to vectfield ref class Myclass(public field int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass( [1 2 1 2 3 4 5 6]^) def doings() { h=A^field + 10 // A^field = 99 "" + [h ; A] } ~~~~~ //##74. bugfix on lhs and rhs assign B = [1 2 3] def doings() { B^ = B^+10 "" + B } ~~~~~ //##75. bugfix on lhs and rhs assign ext 2 class Myclass(public field int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } B = [1 2 1 2 3 4 5 6] A = Myclass( B^) def doings() { A^field = A^field + 100 "" + A } ~~~~~ //##76. field ref pre post class Myclass(public field int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = [Myclass( 1) Myclass( 2) Myclass( 3) ] def doings() { A^field++ "" + A } ~~~~~ //##77. field ref in place class Myclass(public field int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = [Myclass( 1) Myclass( 2) Myclass( 3) ] def doings() { A^field^^ + 100 "" + A } ~~~~~ //##78. in place assigmnet class Myclass(public field int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = [Myclass( 1) Myclass( 2) Myclass( 3) ] def doings() { A^field += 100 "" + A } ~~~~~ //##79. vect field ref long chain class FieldCls(valu int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'FieldCls: {valu}' } class Myclass(field FieldCls){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass( [FieldCls(1) FieldCls(2) ; FieldCls(3) FieldCls(4)]^) B = A@ def doings() { A^field^valu = 10 B^field^valu += 100 x = B^field^valu "lovely: " + [A ; B; x] } ~~~~~ //##80. no arg funcref class MyClass{ override hashCode()=>1 override equals(an Object)=>false def anOperation() => 'result!' } myAr = [MyClass() MyClass()] def doings() { res = myAr^anOperation&//create a funcref to anOperation "" + (x() for x in res) } ~~~~~ //##81. vect called each time for assignment not just once cnt = 0 def cnter() => cnt++ stuff = [1 2 3 4] def doings() { stuff^ = cnter() 'ok' + [stuff, cnt] } ~~~~~ //##82. auto vect field access class Myclass(public field int){ def isField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([1 2 3 4 5]^) def doings() { x = A.field "" + x } ~~~~~ //##83. auto vect field assignment class Myclass(public field int){ def isField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([1 2 3 4 5]^) def doings() { A.field = 69 "" + A } ~~~~~ //##84. auto vect field inc class Myclass(public field int){ def isField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([1 2 3 4 5]^) def doings() { A.field++ "" + A } ~~~~~ //##85. auto vect in place ops class Myclass(public field int){ def isField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([1 2 3 4 5]^) B = A@ def doings() { A.field += 66 B.field^^+99 "" + [A ; B] } ~~~~~ //##86. auto vect manual in place ops class Myclass(public field int){ def isField() => "hi: " + field//go via getter override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([1 2 3 4 5]^) def doings() { A.field = A.field + 66 "" + A } ~~~~~ //##87. auto vect ops nested etc complex class FieldCls(valu int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'FieldCls: {valu}' } class Myclass(field FieldCls){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass( [FieldCls(1) FieldCls(2) ; FieldCls(3) FieldCls(4)]^) B = A@ def doings() { A.field.valu = 10 B.field.valu += 100 x = B.field.valu "lovely: " + [A ; B; x] } ~~~~~ //##88. acuto vect func invoke class Myclass(a int){ def afunc() => "hi: {a}" override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {a}' } A = Myclass([1 2 3 4 5]^) def doings() { x = A.afunc() "" + x } ~~~~~ //##89. acuto vect func ref class Myclass(a int){ def afunc() => "hi: {a}" override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {a}' } A = Myclass([1 2 3 4 5]^) def doings() { xxx = A.afunc& "" + (x() for x in xxx) } ~~~~~ //##90. inner class init class Myclass(a int){ public class SubClass(b int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'SubClass: {a, b}' } override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {a}' } A = Myclass([1 2 3 4 5]^) def doings() { xxx = A^SubClass(8) "" + xxx } ~~~~~ //##91. inner class init auto vect class Myclass(a int){ public class SubClass(b int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'SubClass: {a, b}' } override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {a}' } A = Myclass([1 2 3 4 5]^) def doings() { xxx = A.SubClass(8) "" + xxx } ~~~~~ //##92. cnt called for each iteration class Myclass(){ def myMeth(a int) => 'ok: {a}' override hashCode()=>1 override equals(an Object)=>false } cc=0 def cnt() => cc++ A = [Myclass() Myclass() Myclass()] def doings(){ "" + A^myMeth(cnt()) } ~~~~~ //##93. new nested class class Myclass(a int){ public class SubClass(public b int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'SubClass: {a}, {b}' } def fu(a int) => a override hashCode()=>1 override equals(an Object)=>false override toString() => 'FAIL Myclass: {a}' } A = Myclass([1 2 3 4 5]^) cc=0 def cnt() => cc++ def doings() { xxx = A^new SubClass(cnt()) "" + [xxx, cc] } ~~~~~ //##94. new nested class implicit class Myclass(a int){ public class SubClass(b int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'SubClass: {a}, {b}' } override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {a}' } A = Myclass([1 2 3 4 5]^) def doings() { xxx = A^SubClass(8)//nope "" + xxx } ~~~~~ //##95. new nested class auto vect class Myclass(a int){ public class SubClass(public b int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'SubClass: {a}, {b}' } def fu(a int) => a override hashCode()=>1 override equals(an Object)=>false override toString() => 'FAIL Myclass: {a}' } A = Myclass([1 2 3 4 5]^) cc=0 def cnt() => cc++ def doings() { xxx = A.new SubClass(cnt()) "" + [xxx, cc] } ~~~~~ //##96. new nested class auto vect op overload class Myclass(a int){ def \new(what String, b int){ 'new: {what} {a} {b}' } override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {a}' } A = Myclass([1 2 3 4 5]^) def doings() { xxx = A.new HiThere(8) "" + xxx } ~~~~~ //##97. ext function on ar type plus auto vect class Myclass(a int){ def afunc() => "hi: {a}" override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {a}' } A = Myclass([1 2 3 ; 4 5]^) def Myclass[1] afunc(){ 'ok' + this } def doings() { x = A.afunc() "" + x } ~~~~~ //##98. expression lists func invoke ref class Myclass(a int){ def afunc() => "hi: {a}" override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {a}' } A = Myclass([1 2 3 4 5]^) def doings() { x = A afunc xxx = A afunc& "" + [x, (d() for d in xxx)] } ~~~~~ //##99. expression lists field assignment class Myclass(public field int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([1 2 3 ]^) def doings() { A field = 100 x=A field "" + [A, x] } ~~~~~ //##100. expression lists field assignment in place ops class Myclass(public field int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'Myclass: {field}' } A = Myclass([1 2 3 ]^) def doings() { A field += 100 "" + A } ~~~~~ //##101. vectorize dneste class new via expr list class Myclass(a int){ public class SubClass(public b int){ override hashCode()=>1 override equals(an Object)=>false override toString() => 'SubClass: {a}, {b}' } def fu(a int) => a override hashCode()=>1 override equals(an Object)=>false override toString() => 'FAIL Myclass: {a}' } A = Myclass([1 2 3 4 5]^) cc=0 def cnt() => cc++ def doings() { xxx = A new SubClass(cnt()) "" + [xxx, cc] } ~~~~~ //##102. this thing works ok class Myclass{ override hashCode()=>1 override equals(an Object)=>false } def Myclass \in(a int) => a >== 2 and a < 10 A = [Myclass() Myclass() ; Myclass()] def doings() { res = not y for y in (x for x in A^contains(6)) "" + res } ~~~~~ //##103. in on lists directed to underlying correctly class Myclass{ override hashCode()=>1 override equals(an Object)=>false } def Myclass \in(a int) => a >== 2 and a < 10 A = [Myclass(), Myclass(), Myclass()] def doings() { res1 = A^contains(6) res2 = 6 in A^//on rawClass mYclass res3 = 6 in A//op on list "" + [res1 res2 res3] } ~~~~~ //##104. in on lists directed to underlying correctly - advanced class Myclass{ override hashCode()=>1 override equals(an Object)=>false } def Myclass \in(a int) => a >== 2 and a < 10 A = [[Myclass(), Myclass(), Myclass()],] def doings() { res = 6 in A^ res1 = A^contains(6) "" +[res res1] } ~~~~~ //##105. set and get of the array of list of int array from java.util import ArrayList h1 = [ new ArrayList<int[]>(0) new ArrayList<int[]>(0) new ArrayList<int[]>(0) new ArrayList<int[]>(0)] def doings(){ h1^add( [1] ) //try auto above shoulderr = x[0] for x in h1^get(0) "" + [h1, shoulderr] } ~~~~~ //##106. array ref element vectorized a = [ 2 3 4 5; 4 5 6 7 8 ; 7 8 9 10 11] def doings(){ what1 = a^[0] what2 = a^[0 ... 2] "" + [what1, what2] } ~~~~~ //##107. array ref assign B int[] = [1 2 3 4 5 6 7 8 9 10] ext int[] = [ 5 6 7] def doings(){ B[ext^] = 99 "" + B } ~~~~~ //##108. array ref assign AUTO vect version B int[] = [1 2 3 4 5 6 7 8 9 10] ext int[] = [ 5 6 7] def doings(){ B[ext] = 99 "" + B } ~~~~~ //##109. inc array ref and auto B int[] = [1 2 3 4 5 6 7 8 9 10] ext int[] = [ 5 6 7] def doings(){ B[ext^]++ B[ext]++ //B[ext] += 99 "" + B } ~~~~~ //##110. cool B int[] = [1 2 3 4 5 6 7 8 9 10] ext int[] = [ 5 6 7] def doings(){ B[ext^^] + 100 "" + ext } ~~~~~ //##111. this is fine B int[] = [1 2 3 4 5 6 7 8 9 10] ext int[] = [ 5 6 7] def doings(){ k=B[ext^]^ + 100 "" + k } ~~~~~ //##112. assignment of ar B int[] = [1 2 3 4 5 6 7 8 9 10] ext int[] = [ 5 6 7] def doings(){ B[ext^] += 100 B[ext] += 100 "" + B } ~~~~~ //##113. assignment of ar with arg vect a int[2] = [ 2 3 4 5; 4 5 6 7 8 ; 7 8 9 10 11] def doings(){ a^[0] = 5 "" + a } ~~~~~ //##114. cool i guess ax int[2] = [ 2 3 4 5; 4 5 6 7 8 ; 7 8 9 10 11] def doings(){ w = ax[(x for x in 0 to ax.length-1)^, 0] "" + w } ~~~~~ //##115. cool i guess AUTO ax int[2] = [ 2 3 4 5; 4 5 6 7 8 ; 7 8 9 10 11] def doings(){ w = ax[(x for x in 0 to ax.length-1), 0] "" + w } ~~~~~ //##116. bugfix correctly operates on vect type now ax int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] def doings(){ ll = ax.length ax[(x for x in 0 to 2)^, 0]++ "" + ax } ~~~~~ //##117. ar vect postfix op ax int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] def doings(){ w = ax^[0]++ "" + [w , ax] } ~~~~~ //##118. ar vect assign ax int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] def doings(){ ax^[0]=10 "" + ax } ~~~~~ //##119. ar in place ax int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] def doings(){ ax^[0] += 100 "" + ax } ~~~~~ //##120. great it works from java.util import ArrayList h1 = [ new ArrayList<int[]>(0) new ArrayList<int[]>(0) new ArrayList<int[]>(0) new ArrayList<int[]>(0)] def doings(){ h1^add( [1] ) shoulderr = h1^get(0)^[0] "" + [h1, shoulderr] } ~~~~~ //##121. lhs of vect ar invoke only once ax1 int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] cnt=0 def myFellta(){ cnt++; ax1 } def doings(){ myFellta()[0, [0 2 ]^ ] +=1 "" + [cnt, ax1] } ~~~~~ //##122. lhs of vect ar arg vect invoke only once ax1 int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] cnt=0 def myFellta(){ cnt++; ax1 } def doings(){ myFellta()^[0] +=1 "" + [cnt, ax1] } ~~~~~ //##123. ar ops on element and subs ax1 int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] ax2 int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] ax3 int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] ax4 int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] def doings(){ got = ax1^[ [0 1 2]^ ] ax2^[ [0 1 2]^ ] = 999 ax3^[ [0 1 2]^ ] ++ ax4^[ [0 1 2]^ ] += 100 "" + [got, ax1, ax2, ax3, ax4] } ~~~~~ //##124. bugfix return correct type on vect func ref with args also vect class Myclass{ override hashCode()=>1 override equals(an Object)=>false } def Myclass \in(a int) => a >== 2 and a < 10 A = [Myclass() Myclass() Myclass()] def doings() { res2 = A^contains([1 2 3]^) "" + res2 } ~~~~~ //##125. bugfix on non eq assingment special method dup calls on lhs ax4 int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] ax5 int[2] = [ 1 1 1 ; 1 1 1; 1 1 1] cnt = 0 cnt2 = 0 def getThing() => cnt++; [0 1 2] def getThing2() => cnt2++; [0 1 2] def doings(){ ax4^[ getThing()^ ] += 100//we expect 1 calls to getThing ax5^[ getThing2()^ ] = ax5^[ getThing2()^ ] + 100//we expect 2 calls to getThing2 "" + [ax4, cnt, ax5, cnt2] }