text stringlengths 184 4.48M |
|---|
/*
This software is subject to the license described in the license.txt file
included with this software distribution. You may not use this file except in compliance
with this license.
Copyright (c) Dynastream Innovations Inc. 2014
All rights reserved.
*/
/**@file
* @defgroup ant_broadcast_rx_example ANT Broadcast RX Example
* @{
* @ingroup nrf_ant_broadcast
*
* @brief Example of basic ANT Broadcast RX.
*
* Before compiling this example for NRF52, complete the following steps:
* - Download the S212 SoftDevice from <a href="https://www.thisisant.com/developer/components/nrf52832" target="_blank">thisisant.com</a>.
* - Extract the downloaded zip file and copy the S212 SoftDevice headers to <tt>\<InstallFolder\>/components/softdevice/s212/headers</tt>.
* If you are using Keil packs, copy the files into a @c headers folder in your example folder.
* - Make sure that @ref ANT_LICENSE_KEY in @c nrf_sdm.h is uncommented.
*/
#include <stdbool.h>
#include <stdint.h>
#include "app_error.h"
#include "nrf.h"
#include "ant_interface.h"
#include "ant_parameters.h"
#include "nrf_soc.h"
#include "nrf_sdm.h"
#include "app_timer.h"
#include "bsp.h"
#include "hardfault.h"
#include "nordic_common.h"
#include "ant_stack_config.h"
#include "ant_channel_config.h"
#include "softdevice_handler.h"
#define APP_TIMER_PRESCALER 0x00 /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_OP_QUEUE_SIZE 0x04 /**< Size of timer operation queues. */
// Channel configuration.
#define ANT_BROADCAST_CHANNEL_NUMBER 0x00 /**< ANT Channel 0. */
#define EXT_ASSIGN_NONE 0x00 /**< ANT Ext Assign. */
// Miscellaneous defines.
#define ANT_NETWORK_NUMBER 0x00 /**< Default public network number. */
/**@brief Function for dispatching a ANT stack event to all modules with an ANT stack event handler.
*
* @details This function is called from the ANT stack event interrupt handler after an ANT stack
* event has been received.
*
* @param[in] p_ant_evt ANT stack event.
*/
void ant_evt_dispatch(ant_evt_t * p_ant_evt)
{
uint32_t err_code;
if (p_ant_evt->channel == ANT_BROADCAST_CHANNEL_NUMBER)
{
ANT_MESSAGE * p_message = (ANT_MESSAGE *)p_ant_evt->msg.evt_buffer;
switch (p_ant_evt->event)
{
case EVENT_RX:
if (p_message->ANT_MESSAGE_ucMesgID == MESG_BROADCAST_DATA_ID
|| p_message->ANT_MESSAGE_ucMesgID == MESG_ACKNOWLEDGED_DATA_ID
|| p_message->ANT_MESSAGE_ucMesgID == MESG_BURST_DATA_ID)
{
err_code = bsp_indication_set(BSP_INDICATE_RCV_OK);
APP_ERROR_CHECK(err_code);
}
break;
default:
break;
}
}
}
/**@brief Function for the Timer and BSP initialization.
*/
static void utils_setup(void)
{
uint32_t err_code;
APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, false);
err_code = bsp_init(BSP_INIT_LED,
APP_TIMER_TICKS(100, APP_TIMER_PRESCALER),
NULL);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for ANT stack initialization.
*
* @details Initializes the SoftDevice and the ANT event interrupt.
*/
static void softdevice_setup(void)
{
uint32_t err_code;
nrf_clock_lf_cfg_t clock_lf_cfg = NRF_CLOCK_LFCLKSRC;
err_code = softdevice_ant_evt_handler_set(ant_evt_dispatch);
APP_ERROR_CHECK(err_code);
err_code = softdevice_handler_init(&clock_lf_cfg, NULL, 0, NULL);
APP_ERROR_CHECK(err_code);
err_code = ant_stack_static_config();
APP_ERROR_CHECK(err_code);
}
/**@brief Function for setting up the ANT module to be ready for RX broadcast.
*/
static void ant_channel_rx_broadcast_setup(void)
{
uint32_t err_code;
ant_channel_config_t broadcast_channel_config =
{
.channel_number = ANT_BROADCAST_CHANNEL_NUMBER,
.channel_type = CHANNEL_TYPE_SLAVE,
.ext_assign = EXT_ASSIGN_NONE,
.rf_freq = RF_FREQ,
.transmission_type = CHAN_ID_TRANS_TYPE,
.device_type = CHAN_ID_DEV_TYPE,
.device_number = CHAN_ID_DEV_NUM,
.channel_period = CHAN_PERIOD,
.network_number = ANT_NETWORK_NUMBER,
};
err_code = ant_channel_init(&broadcast_channel_config);
APP_ERROR_CHECK(err_code);
// Open channel.
err_code = sd_ant_channel_open(ANT_BROADCAST_CHANNEL_NUMBER);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for application main entry. Does not return.
*/
int main(void)
{
utils_setup();
softdevice_setup();
ant_channel_rx_broadcast_setup();
// Main loop.
for (;;)
{
#if CPU_LOAD_TRACE
// Disabling interrupts in this way is highly not recommended. It has an impact on the work
// of the SoftDevice and is used only to show CPU load.
__disable_irq();
bsp_board_led_off(BSP_BOARD_LED_0);
__WFI();
bsp_board_led_on(BSP_BOARD_LED_0);
__enable_irq();
#else
// Put CPU in sleep if possible.
uint32_t err_code = sd_app_evt_wait();
APP_ERROR_CHECK(err_code);
#endif // CPU_LOAD_TRACE
}
}
/**
*@}
**/ |
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://xmlns.jcp.org/jsf/passthrough">
<h:head>
<title>更新</title>
</h:head>
<h:body>
<h1>更新</h1>
<h:form>
<h:panelGrid columns="3">
血圧値上<h:inputText id="bldup" value="#{bb.bldup}"/>
<h:message for="bldup" styleClass="error"/>
血圧値下<h:inputText id="blddn" value="#{bb.blddn}"/>
<h:message for="blddn" styleClass="error"/>
心拍数<h:inputText id="rate" value="#{bb.rate}"/>
<h:message for="rate" styleClass="error"/>
日付
<h:inputText id="date" value="#{bb.date}" p:type="date" p:placeholder="2019/1/1" >
<f:convertDateTime pattern="yyyy-M-d" timeZone="JST"/>
<f:validateRequired/>
</h:inputText>
<h:message for="date" styleClass="error"/>
時間
<h:selectOneMenu value="#{bb.time}" styleClass="sel">
<f:selectItems value="#{bb.timeitems}" />
</h:selectOneMenu>
<h:message for="time" styleClass="error"/>
どんな時
<h:selectOneRadio value="#{bb.state}" styleClass="inp">
<f:selectItems value="#{bb.items}"/>
</h:selectOneRadio>
<h:message for="state" styleClass="error"/>
</h:panelGrid>
<h:panelGrid columns="3">
<h:commandButton value="更新" action="#{bb.update()}"/>
<h:commandButton value="取消" action="#{bb.clear()}" >
<f:ajax render="@all"/>
</h:commandButton>
<h:link outcome="index.xhtml">戻る</h:link>
</h:panelGrid>
<hr/>
<h:dataTable value="#{bb.all}" var="item">
<f:facet name="header">登録内容</f:facet>
<h:column>
<f:facet name="header">血圧値上</f:facet>
#{item.bldup}
</h:column>
<h:column>
<f:facet name="header">血圧値下</f:facet>
#{item.blddn}
</h:column>
<h:column>
<f:facet name="header">心拍数</f:facet>
#{item.rate}
</h:column>
<h:column>
<f:facet name="header">日付</f:facet>
<h:outputText value="#{item.date}">
<f:convertDateTime pattern="yyyy/MM/dd"/>
</h:outputText>
</h:column>
<h:column>
<f:facet name="header">時間</f:facet>
#{item.time}
</h:column>
<h:column>
<f:facet name="header">どんな時</f:facet>
#{item.state}
</h:column>
</h:dataTable>
<hr/>
<h:dataTable value="#{bb.all}" var="item">
<h:column>
<f:facet name="header">CSV出力</f:facet>
#{item.bldup},#{item.blddn},#{item.rate},<h:outputText value="#{item.date}"><f:convertDateTime pattern="yyyy/MM/dd"/></h:outputText>,#{item.time},#{item.state}
</h:column>
</h:dataTable>
<hr/>
<canvas id="chart" height="450" width="600"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<h:dataTable value="#{bb.all}" var="item">
<script type="text/javascript">
//<![CDATA[
var barChartData = {
labels : ["#{item.date}"],
datasets : [
{
fillColor : /*"#d685b0"*/"rgba(214,133,176,0.7)",
strokeColor : /*"#d685b0"*/"rgba(214,133,176,0.7)",
highlightFill: /*"#eebdcb"*/"rgba(238,189,203,0.7)",
highlightStroke: /*"#eebdcb"*/"rgba(238,189,203,0.7)",
data : [#{item.bldup}]
},
{
fillColor : /*"#7fc2ef"*/"rgba(127,194,239,0.7)",
strokeColor : /*"#7fc2ef"*/"rgba(127,194,239,0.7)",
highlightFill : /*"#a5d1f4"*/"rgba(165,209,244,0.7)",
highlightStroke : /*"#a5d1f4"*/"rgba(165,209,244,0.7)",
data : [#{item.blddn}]
}
]
}
window.onload = function(){
var ctx = document.getElementById("chart").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true,
animation : false
});
}
//]]>
</script>
</h:dataTable>
</h:form>
</h:body>
</html> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas</title>
<style>
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="800"></canvas>
<script>
// 用選擇器建立變數
const canvas = document.querySelector('#myCanvas');
// 固定公式,建立繪畫物件
const ctx = canvas.getContext('2d');
// 將瀏覽器的寬高設為畫布的寬高,整個瀏覽器的視窗都是畫布
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 畫筆顏色
// ctx.strokeStyle = '#bada55'; 後用hue 設定,此處可以取消
// 畫筆轉折處的樣式 有圓弧round, 方形bevel, 尖角miter 三種
ctx.lineJoin = 'round';
// 畫筆頭尾兩端的樣式 有圓弧round, 方形butt, 較butt 突出的方形square 三種
ctx.lineCap = 'round';
// 畫筆的寬度,這個設定會影響第一筆下筆的粗度,不能取消
ctx.lineWidth = 100;
// 線條重疊處會有的效果,供參
// ctx.globalCompositeOperation = 'multiply';
let isDrawing = false;
let x = 0;
let y = 0;
let hue = 0;
let thickness = true;
function draw(e){
//如果沒有作畫,不要執行程式
if (!isDrawing) return;
// 設定畫筆顏色
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
// 開始作畫
ctx.beginPath();
// 從哪個位置開始
ctx.moveTo(x, y);
// 線條長度
ctx.lineTo(e.offsetX, e.offsetY)
// 執行從beginPath() 開始以下的程式
ctx.stroke();
// offsetY 忘了加e , 導致畫筆都從0開始畫,沒辦法從中間開始畫
[x, y] = [e.offsetX, e.offsetY]
hue++;
if (hue >= 360) {
hue = 0;
}
// 畫筆粗度隨hue 參數變化
// ctx.lineWidth = hue;
if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1){
thickness = !thickness;
}
if (thickness) {
ctx.lineWidth++;
} else {
ctx.lineWidth--;
}
}
// 監聽滑鼠的狀態
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mousedown', (e)=> {
isDrawing = true;
[x, y] = [e.offsetX, e.offsetY] // offsetY 忘了加e , 導致畫筆都從0開始畫,沒辦法從中間開始畫
});
canvas.addEventListener('mouseout', ()=> {
isDrawing = false;
});
canvas.addEventListener('mouseup', ()=> {
isDrawing = false;
});
// https://mothereffinghsl.com/ 畫筆想要的特效
</script>
</body>
</html> |
---
title: 'Complex join'
---
# Complex join
You can provide a function as the second argument to get a join
builder for creating more complex joins. The join builder has a
bunch of `on*` methods for building the `on` clause of the join.
There's basically an equivalent for every `where` method
(`on`, `onRef` etc.). You can do all the same things with the
`on` method that you can with the corresponding `where` method.
See the `where` method documentation for more examples.
import {
Playground,
exampleSetup,
} from '../../../src/components/Playground'
import {
complexJoin
} from './0030-complex-join'
<div style={{ marginBottom: '1em' }}>
<Playground code={complexJoin} setupCode={exampleSetup} />
</div>
:::info More examples
The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/)
but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always
just one hover away!
For example, check out these sections:
- [innerJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#innerJoin)
- [leftJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#leftJoin)
- [rightJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#rightJoin)
- [fullJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#fullJoin)
::: |
const router = require("express").Router();
const { Category, Product } = require("../../models");
const { sequelize } = require("../../models/Category");
// The `/api/categories` endpoint for get all -- status code 500 = error on the server-side
router.get("/", (req, res) => {
Category.findAll({
include: [{ model: Product }],
})
.then((dbCategoryData) => res.json(dbCategoryData))
.catch((err) => {
console.log(err);
res.status(500).json(err);
});
});
// find one category by its `id` value
// be sure to include its associated Products
router.get("/:id", (req, res) => {
Category.findOne({
where: {
id: req.params.id,
},
include: [
{
model: Product,
},
],
})
.then((dbCategoryData) => {
if (!dbCategoryData) {
res.status(404).json({ message: "No Category found with this id" });
return;
}
res.json(dbCategoryData);
})
.catch((err) => {
console.log(err);
res.status(500).json(err);
});
});
// create a new category
router.post("/", (req, res) => {
Category.create({
category_name: req.body.category_name,
})
.then((dbCategoryData) => res.json(dbCategoryData))
.catch((err) => {
console.log(err);
res.status(500).json(err);
});
});
router.put("/:id", (req, res) => {
Category.update(req.body, {
where: {
id: req.params.id,
},
})
.then((dbCategoryData) => {
if (!dbCategoryData[0]) {
res.status(404).json({ message: "No category found with this id" });
return;
}
res.json(dbCategoryData);
})
.catch((err) => {
console.log(err);
res.status(500).json(err);
});
});
router.delete("/:id", (req, res) => {
Category.destroy({
where: {
id: req.params.id,
},
})
.then((dbCategoryData) => {
if (!dbCategoryData) {
res.status(404).json({ message: "No Category found with this id" });
return;
}
res.json(dbCategoryData);
})
.catch((err) => {
console.log(err);
res.json(500).json(err);
});
});
module.exports = router; |
import { NextFunction, Request, Response } from 'express';
import Category from './model';
import { categorySchema } from './validator';
import unprocessableEntity from '../../errors/unprocessable-entity';
import { UniqueViolationError } from 'objection';
import categoriesErrors from './errors';
import badRequestError from '../../errors/bad-request';
import notFoundError from '../../errors/not-found-error';
async function createCategory(request: Request, response: Response, next: NextFunction) {
try {
const {user, body} = request;
const values = {
...body,
user_id: user.id
};
const {error} = categorySchema.validate(values);
if (error) badRequestError(response, error.details[0].message);
const category = await Category.query().insertAndFetch(values);
return response.status(200)
.json(category);
} catch (error: any) {
if (error instanceof UniqueViolationError) {
return unprocessableEntity(response, categoriesErrors.duplicatedCategory);
}
next(error);
}
}
async function getCategories(request: Request, response: Response, next: NextFunction) {
try {
const {user, query} = request;
const {category} = query;
const categoriesQuery = Category.query()
.where('user_id', user.id)
.where('deleted_at', null)
.withGraphFetched('lists(lists)')
.modifiers({
lists(builder) {
builder.select([
'id',
'name',
'status',
])
.where('deleted_at', null);
}
});
if (category) {
categoriesQuery.where('category', 'LIKE', `%${String(category)}%`);
}
const categories = await categoriesQuery;
response.status(200)
.json(categories);
} catch (error) {
next(error);
}
}
async function getCategory(request: Request, response: Response, next: NextFunction) {
try {
const {user, params} = request;
const {category_id: idCategory} = params;
const category = await Category.query()
.findById(idCategory)
.where('user_id', user.id)
.where('deleted_at', null)
.withGraphFetched('lists(lists)')
.modifiers({
lists(builder) {
builder.select([
'id',
'name',
'status',
])
.where('deleted_at', null);
}
});
if(!category) return notFoundError(response);
response.status(200)
.json(category);
} catch (error) {
next(error);
}
}
export default {
createCategory,
getCategories,
getCategory,
}; |
import React from "react";
import { useNavigate } from "react-router-dom";
class CreateProject extends React.Component { constructor(props) {
super(props);
this.state = {title: '', description: '', image: null, url_name:'',url:'',};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
if (event.target.name === "image") {
this.setState({ image: event.target.files[0] });
} else {
this.setState({ [event.target.name]: event.target.value });
}
}
handleSubmit(event) {
event.preventDefault();
const { title, description, image, url_name, url } = this.state;
// Client-side validation
if (!title || !description || !url_name|| !url) {
this.setState({ error: "Title and description are required." });
return;
}
const formData = new FormData();
formData.append("image", image);
formData.append("title", title);
formData.append("description", description);
formData.append("url_name", url_name);
formData.append("url", url);
fetch("http://127.0.0.1:8000/api/banner/post/", {
method: "POST",
body: formData,
})
.then((res) => res.json())
.then(
(result) => {
console.log(result);
this.setState({
image: null,
description: "",
title: "",
url_name: "",
url: "",
error: null,
});
this.props.navigate("/projects");
},
(error) => {
console.error("Error:", error);
this.setState({ error: "An error occurred while submitting the form." });
}
);
}
render() {
const { error } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<div>{error && <p style={{color: "red"}}>{error}</p>}</div>
<label>
<h3 className="welcom">Image:</h3>
<input type="file" name="image" onChange={this.handleChange}/>
</label>
{this.state.image && <p>Selected file: {this.state.image.name}</p>}
<label>
<h3 className="welcom">Title:</h3>
<input type="text" name="title" value={this.state.title} onChange={this.handleChange}/>
</label>
<label>
<h3 className="welcom">Description:</h3>
<input type="text" name="description" value={this.state.description} onChange={this.handleChange}/>
</label>
<label>
<h3 className="welcom">Url name:</h3>
<input type="text" name="url_name" value={this.state.url_name} onChange={this.handleChange}/>
</label>
<label>
<h3 className="welcom">Url:</h3>
<input type="text" name="url" value={this.state.url} onChange={this.handleChange}/>
</label>
<input type="submit" value="Submit"/>
</form>
)
;
}
}
function WithNavigate(props) {
let navigate = useNavigate();
return <CreateProject {...props} navigate={navigate}/>}
export default WithNavigate; |
<%@ Page Title="" Language="C#" MasterPageFile="HrMaster.master" AutoEventWireup="true" CodeBehind="Specifics.aspx.cs" Inherits="SkyServer.Proj.Teachers.Advanced.HR.Specifics" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HrContent" runat="server">
<div id="transp">
<table WIDTH=600 border=0 cellspacing="3" cellpadding="3">
<tr><td>
<h1>Teacher's Guide to Specific Sections</h1>
<a name="intro"></a>
<p><b>Introduction</b></p>
<p>The H-R diagram is one of the fundamental tools astronomers use to classify stars.
You can clearly see several different types of stars on an H-R diagram. In
this lesson, students will look at the H-R diagram as a snapshot of all stars at a
particular point in time. In a future lesson on stellar evolution, they will
look at how stars evolve and move around the H-R diagram as they age.</p>
<a name="brightest"></a>
<p><b>The Brightest Stars</b></p>
<p>The first H-R diagram is very straightforward. Students will make a
graph of absolute magnitude vs b-v. The quantity b-v is a measure of color, which in
turn is a measure of a star's temperature. A lower b-v value corresponds
to a higher temperature. The graph may seem backwards, since hotter stars
are on the left and cooler stars are on the right.</p>
<p>The H-R diagram for the brightest stars in the sky is biased toward red and
blue giant stars. These stars are the most luminous, so they will be the most
easily visible in our night sky. Most of the stars close to Earth are much
smaller and less luminous. They appear fainter in our night sky in spite
of their proximity. Our Sun looks fainter than average when you compare it
to the brightest stars.</p>
<a name="nearest"></a>
<p><b>The Nearest Stars</b></p>
<p>For the closest stars, students will make a graph of absolute magnitude
vs. spectral type, which is also a measure of temperature.
Emphasize that they really are making the same type of graph, although the axes
are labeled differently. A useful analogy might be that they are using
different units than the first graph.</p>
<p>When you look at the closest stars, you see a lot fewer giants and a lot more
main sequence and dwarf stars. The stars that are closer to us are less
luminous, so they do not appear as bright in the night sky. Our Sun has above
average luminosity when compared to the closest stars. You can clearly
see the main sequence on this graph - a diagonal line across the diagram. Stars on
the main sequence have hydrogen-burning cores.</p>
<a name="thehr"></a>
<p><b>The H-R Diagram</b></p>
<p>A star's position on the H-R diagram tells you a great deal of information
about it. The diagonal strip is called the main sequence. Main
sequence stars are hydrogen-burning stars like our Sun. More massive main sequence
stars are hotter, and are found at the top left of the strip. Less massive stars are
cooler, and are found at the bottom right.</p>
<p>Massive stars burn through all their hydrogen quickly, in only
a few million years. Smaller stars burn their
hydrogen relatively slowly. Our Sun has been a main sequence star for
about five billion years and will stay on the main sequence for another four to
five billion years. </p>
<p>When stars have exhausted all their hydrogen fuel, they evolve to red giants. Their outer
layers of gas expand and cool; therefore, the stars move to the right on the H-R diagram.
Although a star cools when it becomes a red giant, it grows so large its luminosity
(or total power emitted) increases. Therefore, the star also moves up the H-R diagram.
The region above and to the right of the main sequence is occupied by the red giants.</p>
<p>When a red giant exhausts its fuel, its fate depends on its mass.
Large red giants become neutron stars or black holes. Neutron stars are
too faint to see in SDSS data and black holes, well, they are black!</p>
<p>Smaller stars, like our Sun, become white dwarf stars. White dwarfs are
the cores of stars that have exhausted all their nuclear fuel. They are very
hot when formed, but they are not very luminous because they are so small. White
dwarfs are less luminous and hotter than main sequence stars, so they lie below and
to the left of the main sequence on the H-R diagram. They will not be commonly
seen in the data for this project, but there may be a few.</p>
<a name="hipparcos"></a>
<p><b>The Hipparcos Data</b></p>
<p>The most difficult part of finding the absolute magnitude of a star is
determining its distance. A bright star far away looks very similar to a
faint star nearby. Unless you know the distances to both stars, you can't know
how bright the stars actually are - their absolute magnitudes.</p>
<p>One method used to find distances to stars is called parallax. Parallax involves making
two observations at different points, then using the distance between those points
and the angle between the observations to determine the distance.
As the photo in the student project shows, our eyes effectively use parallax to
enhance our depth perception. Each eye sees a slightly different image. The brain
combines the two images to give a sense of depth. </p>
<p>Stars are so far away that their parallax angles are very small.
Astronomers use the orbit of the Earth to give a large baseline to
increase the parallax angle. They observe a star at two different
occasions separated by six months. For the second observation, the Earth is
on the opposite side of the Sun, giving an effective baseline of about 186 million miles. </p>
<p>Stars are so far away that even this enormous baseline produces very little change in
their positions. Only the very closest stars can have their distances
determined using this technique. The blurring caused by Earth's atmosphere
put severe restrictions on using parallax to find the distance to stars.</p>
<p>In 1989, the European Space Agency launched the Hipparcos satellite.
Above the blurring effects of the atmosphere, Hipparcos was able to get much more
accurate parallax measurements to a large number of stars. The satellite also
measured the visual magnitudes and b-v colors for each star.</p>
<p>Students use a point and click interface to retrieve Hipparcos data.
The interface opens in a new window. They must first click on a star to select it.
Then, clicking on the "Get Info" button will retrieve data for
that star. Practice using the interface yourself, so you can help students with
any difficulties in using the interface.</p>
<p>After Exercise 5, there is a brief section where students are asked to find the
distances to a few stars and then find their absolute magnitudes. This section serves are
practice for using Hipparcos data to make an H-R diagram. You may wish to
check students' work at this point to be sure they understand the mathematics.</p>
<a name="pleiades"></a>
<p><b>The Pleiades Data</b></p>
<p>Working with the Hipparcos data involves a lot of mathematical manipulation;
this section is where good spreadsheet skills come in handy.
Students need to calculate the distances to stars. Using the
distances, they then need to calculate absolute magnitudes. The
b-v value for each star is given in column T37 of the star's data table.</p>
<p>If students want information for more stars, they can widen the field of view.
Alternatively, you may want to have each student look at a different star
cluster, rather than having them all look at the Pleiades.</p>
<p>The Pleiades are a rather young star cluster with a lot of hot stars.
When students make an H-R diagram, they will see a strong main sequence with
some red giants.
It's OK if students pick up a couple of foreground stars in this
section, since they will calculate the stars' distances absolute
magnitudes in the next few exercises.</p>
<p>Here are a few other star clusters you may use in this section as well,
if you would like to see some different H-R diagrams.</p>
<table border="1" cellpadding="1" cellspacing="1" style="border-collapse: collapse" width="100%" id="AutoNumber1">
<tr>
<td width="33%"><font face="Arial" color="#F5F5F5"><em>Cluster</em></font></td>
<td width="33%"><font face="Arial" color="#F5F5F5"><em>RA</em></font></td>
<td width="34%"><font face="Arial" color="#F5F5F5"><em>Dec</em></font></td>
</tr>
<tr>
<td width="33%"><font face="Arial" color="#F5F5F5">Hyades</font></td>
<td width="33%"><font face="Arial" color="#F5F5F5">66.73</font></td>
<td width="34%"><font face="Arial" color="#F5F5F5">15.52</font></td>
</tr>
<tr>
<td width="33%"><font face="Arial" color="#F5F5F5">M41</font></td>
<td width="33%"><font face="Arial" color="#F5F5F5">101.73</font></td>
<td width="34%"><font face="Arial" color="#F5F5F5">-20.44</font></td>
</tr>
<tr>
<td width="33%"><font face="Arial" color="#F5F5F5">NGC 457 (The Blair Witch
Cluster)</font></td>
<td width="33%"><font face="Arial" color="#F5F5F5">19.78</font></td>
<td width="34%"><font face="Arial" color="#F5F5F5">58.20</font></td>
</tr>
<tr>
<td width="33%"><font face="Arial" color="#F5F5F5">Double Cluster</font></td>
<td width="33%"><font face="Arial" color="#F5F5F5">34.75</font></td>
<td width="34%"><font face="Arial" color="#F5F5F5">57.15</font></td>
</tr>
<tr>
<td width="33%"><font face="Arial" color="#F5F5F5">NGC 2451</font></td>
<td width="33%"><font face="Arial" color="#F5F5F5">116.35</font></td>
<td width="34%"><font face="Arial" color="#F5F5F5">37.97</font></td>
</tr>
<tr>
<td width="33%"><font face="Arial" color="#F5F5F5">M34</font></td>
<td width="33%"><font face="Arial" color="#F5F5F5">40.5</font></td>
<td width="34%"><font face="Arial" color="#F5F5F5">42.78</font></td>
</tr>
</table>
<a name="radius"></a>
<p>You can find more open clusters
<a target="_blank" href="http://www.arval.org.ve/OClust.htm">here</a>.</p>
<p><b>Radius of a Star</b></p>
<p>The link below Question 9 leads to an optional section on calculating
the radius of a star. This section involves a lot of mathematical manipulation,
but students may find it rewarding to be able to calculate the size of a star.
The stars given in the table will always be in the middle of the field of view.
Except for Barnard's star, they will also be the brightest. Students
can identify Barnard's star by carefully checking the coordinates.</p>
<a name="globular"></a>
<p><b>Globular Clusters</b></p>
<p>The two star clusters in the SDSS data are both old and distant globular
clusters. When students try to make an H-R diagram for these clusters by
hand, they will probably not find much of a discernable pattern. There are
so many stars in the field, some of which are foreground stars, that it would be
difficult to take enough data by hand to create a good H-R diagram.
Literally hundreds of stars are needed. That observation leads naturally to the next section:
using a search tool to retrieve the data for many stars at one time.</p>
<a name="searching"></a>
<p><b>Searching for Data</b></p>
<p>Students will use the cluster Pal 5 for this section, since Pal 3 does
not have enough stars to create a good diagram. Students have two options for retrieving the
data: SkyServer's Radial Search tool plus Excel's data filters, or SkyServer's SQL Search tool.
Both tools should give the same results, so which tool they use is up to you. Learning the
SQL Search tool will open up many new possiblities for SkyServer, and will enable students to
do much more sophisticated independent research. Using the Radial Search tool is simpler, and will
allow students to learn to use Excel, which can be a valuable technology skill.</p>
<p>Microsoft Excel will open .csv files, so students can import data directly into
an Excel spreadsheet. See SkyServer's <a href="../../../../help/howto/graph/open.aspx"
target="help">Graphing and Analyzing Data</a> tutorial to learn how to properly open a CSV
file with Excel. Instead of v and b-v, we use SDSS's r filter and g-r color. The diagram
will be recognizable as an H-R diagram. Most of the stars with g-r > 1
are not part of the cluster, and you will see some foreground stars in the field.
Students should also notice what is called a "turnoff point" at around magnitude 17.5.
The main sequence ends at around this magnitude and abruptly "turns off" onto the red
giant branch. The cluster is so old that all of the brightest main sequence stars
have exhausted their hydrogen fuel and have evolved into red giants.</p>
<a name="conclusion"></a>
<p><b>Conclusion</b></p>
<p>Students may send in their H-R diagrams of clusters that interest them.
We'll evaluate the results we receive, and we will post the best
of them on our web pages for others to see!</p>
<p>Students should <a href="mailto:raddick@pha.jhu.edu?subject=student H-R diagram">E-mail us</a> their results
as Excel (.xls) or .csv files.</p>
<p> </p>
</td>
</tr>
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td align=center><A href="default.aspx" >
<IMG align=left src="images/previous.jpg" ></A>
<A href="correlations.aspx" >
<IMG align=right src="images/next.jpg" ></A></td></tr>
<tr><td>
</table>
<P></P>
</div>
</asp:Content> |
<template>
<div>
<div class="text-start">
<router-link to="/AddTask" class="btn btn-success btn-lg"
>Add task</router-link
>
</div>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="task in tasks" :key="task.id">
<td>
<router-link :to="{ name: 'task-id-edit', params: { task } }">{{
task._id
}}</router-link>
</td>
<td>{{ task.name }}</td>
<td>{{ task.description }}</td>
<td class="d-flex">
<router-link
class="btn btn-outline-warning btn-lg"
:to="{ name: 'task-id-edit', params: { task }}"
>Edit</router-link
>
<router-link
class="btn btn-outline-danger btn-lg"
:to="{ name: 'task-id-delete', params: { task }}"
>Delete</router-link
>
</td>
</tr>
</tbody>
</table>
<div class="text-center">
<button @click="deleteAll" class="btn btn-danger btn-lg">
Delete all tasks
</button>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
tasks: [],
};
},
methods: {
getTasks() {
axios.get('http://127.0.0.1:8000')
.then(({ data }) => {
this.tasks = data;
})
.catch(err => console.error(err));
},
deleteAll() {
axios.delete('http://127.0.0.1:8000/delete/all')
.then(() => {
this.tasks = [];
})
.catch(err => console.log(err));
},
},
beforeMount() {
this.getTasks();
},
};
</script>
<style scoped>
.btn {
margin: 1%;
}
</style> |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* 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.
*/
#include "Vibrator.h"
#include <android-base/logging.h>
#include <fstream>
namespace aidl {
namespace android {
namespace hardware {
namespace vibrator {
ndk::ScopedAStatus Vibrator::setNode(const std::string path, const int32_t value) {
std::ofstream file(path);
if (!file.is_open()) {
LOG(ERROR) << "Failed to write " << value << " to " << path;
return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_SERVICE_SPECIFIC));
}
file << value << std::endl;
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus Vibrator::activate(const int32_t timeoutMs) {
ndk::ScopedAStatus status;
/* timeoutMs under 1 = turn off vibrator */
if (timeoutMs < 1) {
return off();
}
status = setNode(kVibratorState, 1);
if (!status.isOk())
return status;
status = setNode(kVibratorDuration, timeoutMs);
if (!status.isOk())
return status;
status = setNode(kVibratorActivate, 1);
if (!status.isOk())
return status;
return ndk::ScopedAStatus::ok();
}
#ifdef VIBRATOR_SUPPORTS_EFFECTS
bool Vibrator::exists(const std::string path) {
std::ofstream file(path);
return file.is_open();
}
int Vibrator::getNode(const std::string path, const int fallback) {
std::ifstream file(path);
int value;
if (!file.is_open()) {
LOG(ERROR) << "failed to read from " << path.c_str();
return fallback;
}
file >> value;
return value;
}
#endif
} // namespace vibrator
} // namespace hardware
} // namespace android
} // namespace aidl |
<!DOCTYPE html>
<html>
<head>
<title>AppRails</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark">
<a class="navbar-brand" href="/">Home Rails</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="/cars">Cars</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="<%= categories_path %>">Categories</a>
</li>
</ul>
</div>
</nav>
<% if flash[:notice] %>
<div class="alert alert-success" <%= flash[:notice] %>></div>
<%end%>
<%= yield %>
</body>
</html> |
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { VocabularyInterface } from '@app/interfaces/vocabulary.interface';
import { LessonsInterface } from '@app/interfaces/lessons.interface';
import { ExerciseInterface } from '@app/interfaces/exercise.interface';
import { FeedbackSchemaInterface } from '@app/interfaces/FeedbackSchema.interface';
@Injectable({
providedIn: 'root'
})
export class RequestService {
constructor(private http: HttpClient) { }
public getVocabulary(): Observable<VocabularyInterface[]> {
// tslint:disable-next-line: max-line-length
return this.http.get(`https://raw.githubusercontent.com/litospayaso/gotzon/master/src/resources/vocabulary.json`) as Observable<VocabularyInterface[]>;
}
public getVocabularyFromLesson(id: string): Observable<VocabularyInterface[]> {
// tslint:disable-next-line: max-line-length
return this.http.get(`https://raw.githubusercontent.com/litospayaso/gotzon/master/src/resources/vocabulary/${id}.json`) as Observable<VocabularyInterface[]>;
}
public getLessons(): Observable<LessonsInterface[][]> {
// tslint:disable-next-line: max-line-length
return this.http.get(`https://raw.githubusercontent.com/litospayaso/gotzon/master/src/resources/lessons.json`) as Observable<LessonsInterface[][]>;
}
public getFeedbackSchema(): Observable<FeedbackSchemaInterface> {
// tslint:disable-next-line: max-line-length
return this.http.get(`https://raw.githubusercontent.com/litospayaso/gotzon/master/src/resources/feedback.json`) as Observable<FeedbackSchemaInterface>;
}
public getLesson(id: string): Observable<string> {
// tslint:disable-next-line: max-line-length
return this.http.get(`https://raw.githubusercontent.com/litospayaso/gotzon/master/src/resources/lessons/${id}.html`, {responseType: 'text'}) as Observable<string>;
}
public getExercises(id: string): Observable<ExerciseInterface[]> {
// tslint:disable-next-line: max-line-length
return this.http.get(`https://raw.githubusercontent.com/litospayaso/gotzon/master/src/resources/exercises/${id}.json`) as Observable<ExerciseInterface[]>;
}
} |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="resources/bootstrap/css/bootstrap.css">
<link href="resources/bootstrap/css/simple-sidebar.css" rel="stylesheet">
<script type="text/javascript" src="resources/jquery/jquery.js"></script>
<script type="text/javascript">
$(function() {
// 모달창 오픈시 기능
$('#myModal').on('show.bs.modal', function (e) {
$("#name").val('${clients.name}')
$(".modal-body p").hide();
});
// 수정 버튼 기능
$("form").submit(function() {
if(!$.trim($("#name").val())) {
$(".non").show();
$("#name").focus();
return false;
}
return true;
});
$("#search-btn").click(function() {
var keyword = $("input:text[name='keyword']").val().trim();
if(keyword == '') {
keyword = 'null';
}
});
});
</script>
<style>
h1{color:white;}
.price{background-color: #EBFBFF}
.non{color: red;}
th,td {text-align:center;}
</style>
<title>Big Store</title>
</head>
<body>
<div id="wrapper">
<%@ include file="/WEB-INF/views/sidebartemplate/sidebar.jsp" %>
<a href="#menu-toggle" class="btn btn-default btn-xs" id="menu-toggle">side bar</a>
<!-- 메신저 modal창 -->
<div class="modal fade" id="messenger" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
<%@ include file="../message/messagebutton.jsp" %>
</div>
<div id="page-context-wrapper">
<%@ include file="../companynotice/backgroundVideo.jsp" %>
<div class="container" style="margin-top:10px">
<h1>거래처 상세정보</h1>
<hr>
<div class="well" style="opacity:0.8">
<div style="text-align:right">
<form role="form" action="clientDetail.do?pn=1" method="POST">
<div class="form-group col-sm-9">
<input type="hidden" name="no" value="${param.no }">
<input type="text" class="form-control" name="keyword" placeholder="상품명을 입력하세요.">
</div>
<div class="form-group col-sm-3">
<input type="submit" id="search-btn" class="btn btn-info form-control" value="검색" />
</div>
</form>
</div>
<table class="table table-bordered">
<colgroup>
<col width="20%">
<col width="15%">
<col width="25%">
<col width="20%">
<col width="20%">
</colgroup>
<thead>
<tr>
<th>거래처번호</th>
<th>거래처 명</th>
<th>제품명</th>
<th>거래처 가격</th>
<th class="price">소비자 가격</th>
</tr>
</thead>
<tbody id="tbody">
<c:forEach var="product" items="${products}">
<tr>
<td>${product.clientNo }</td>
<td>${product.maker }</td>
<td>${product.name }</td>
<td><fmt:formatNumber value="${product.price * 0.7}" type="number" /></td>
<td class="price"><fmt:formatNumber value="${product.price}" type="number" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="pull-right">
<c:if test="${LoginUser.dept eq 'PM' or LoginUser.dept eq 'Master'}">
<button type="button" class="btn btn-warning" data-toggle="modal" data-target="#myModal" id="btn" >수정</button>
</c:if>
<a href="clientList.do" class="btn btn-default">목록</a>
</div>
<div class="text-center">
<ul class="pagination">
<c:if test="${pageVo.pageNo gt 1 }">
<li>
<a href="clientDetail.do?no=${param.no }&pn=${pageVo.pageNo - 1 }" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach var="num" begin="${pageVo.beginPage }" end="${pageVo.endPage }">
<c:choose>
<c:when test="${pageVo.pageNo eq num }">
<li><a class="active" href="clientDetail.do?no=${param.no }&pn=${num }">${num }</a></li>
</c:when>
<c:otherwise>
<li><a href="clientDetail.do?no=${param.no }&pn=${num }">${num }</a></li>
</c:otherwise>
</c:choose>
</c:forEach>
<c:if test="${pageVo.pageNo lt pageVo.totalPages }" >
<li>
<a href="clientDetail.do?no=${param.no }&pn=${pageVo.pageNo + 1 }" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
</ul>
</div>
<!-- 수정 모달 창 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">거래처 수정</h4>
</div>
<form action="updateClient.do" method="post" role="form">
<div class="modal-body">
<div>
<label>거래처 번호</label>
<input type="text" name="no" class="form-control" readonly="readonly" value="${clients.no}">
</div>
<div>
<label>거래처 명</label>
<input type="text" name="name" id="name" class="form-control" value="${clients.name}">
<p class="non"><strong>거래처명</strong>을 입력하세요.</p>
</div>
<div>
<label>거래 여부</label><br />
<input type="radio" name="isAdmit" value="Y" ${clients.isAdmit eq 'Y' ? 'checked=checked': '' }> 거래중
<input type="radio" name="isAdmit" value="N" ${clients.isAdmit eq 'N' ? 'checked=chedked': '' }> 거래중지
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" id="add" value="확인" />
<button type="button" class="btn btn-default" data-dismiss="modal">취소</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html> |
import { ZodObject, TypeOf, ZodTypeAny } from 'zod';
import {
DatabasePool,
DatabaseTransactionConnection,
IdentifierSqlToken,
QueryResult,
QuerySqlToken,
sql,
} from 'slonik';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { AggregateRoot, Mapper } from 'src/domain/ddd';
import { RepositoryPort } from 'src/domain/ddd/repository.port';
import { RequestCtxService } from '../application/context';
export abstract class SqlRepositoryBase<
Aggregate extends AggregateRoot<any>,
DbModel,
> implements RepositoryPort<Aggregate>
{
protected tableName: string;
protected schema: ZodObject<any>;
constructor(
private readonly _pool: DatabasePool,
protected readonly mapper: Mapper<Aggregate, DbModel>,
protected readonly eventEmitter: EventEmitter2,
) {
//
}
async insert(entity: Aggregate | Aggregate[]): Promise<void> {
const entities = Array.isArray(entity) ? entity : [entity];
const records = entities.map(this.mapper.toPersistance);
}
/**
* Start a global transaction to save
* results of all event hanlders in one operation
*/
public async transaction<T>(handler: () => Promise<T>): Promise<T> {
return this.pool.transaction(async (connection) => {
if (!RequestCtxService.getTransactionConnection()) {
RequestCtxService.setTransactionConnection(connection);
}
try {
const result = await handler();
return result;
} catch (error: any) {
//
} finally {
RequestCtxService.cleanTransactionConnection();
}
});
}
/**
* Utility method for write queries when you need to mutate an entity.
* Executes entity validation, publishes events,
* and does some debug logging.
* For read queries use `this.pool` directly
*
* @param sql
* @param entity
*/
protected async writeQuery<T extends ZodTypeAny>(
sql: QuerySqlToken<T>,
entity: Aggregate | Aggregate[],
): Promise<QueryResult<TypeOf<T>>> {
const entities = Array.isArray(entity) ? entity : [entity];
entities.forEach((entity) => entity.validate());
// TODO: Implement logging to display those ids
const entityIds = entities.map((entity) => entity.id);
const result = await this.pool.query(sql);
Promise.all(
entities.map((entity) => {
entity.publishEvents(this.eventEmitter);
}),
);
return result;
}
protected async generateInsertQuery(models: DbModel[]) {
const entries = Object.entries(models);
const values: any = [];
const propertyNames: IdentifierSqlToken[] = [];
entries.forEach((entry) => {
if (entry[0] && entry[1] !== undefined) {
propertyNames.push(sql.identifier([entry[0]]));
if (entry[1] instanceof Date) {
values.push(sql.timestamp(entry[1]));
} else {
values.push(entry[1]);
}
}
});
}
/**
* Get database pool.
* If global request transaction is started
* returns a transaction pool.
*/
protected get pool(): DatabasePool | DatabaseTransactionConnection {
return RequestCtxService.getTransactionConnection() ?? this._pool;
}
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ARFA6.1 - Goals</title>
<link rel="stylesheet" href="flash-style.css" />
</head>
<body>
<div id="container">
<div id="flashcard">
<h1 id="word" style="font-size: 70px; font-family: 'PingFang SC'">Word goes here</h1>
<h1 id="definition" style="font-family: 'Baloo Bhaina 2 Regular';">Definition goes here</h1>
</div>
<div id="button-container">
<button class="button" id="left-button">Translate</button>
<button class="button" id="right-button">I got it right</button>
<button class="button" id="next-button">Next words</button>
<input type="number" class="set-num" id="set-num" min="1" max="1000">
</div>
</div>
<script>
const lessonWords = [
{word: "بردگان", definition: "slaves", score: 0},
{word: "چنان", definition: "so", score: 0},
{word: "كالايى", definition: "a commodity", score: 0},
{word: "محروم", definition: "Deprived", score: 0},
{word: "هويّت", definition: "identity", score: 0},
{word: "حقوق", definition: "Rights", score: 0},
{word: "بشرى", definition: "human", score: 0},
{word: "مزارع", definition: "farms", score: 0},
{word: "غل", definition: "shackle", score: 0},
{word: "سنگينى", definition: "heaviness", score: 0},
{word: "مىبستند", definition: "They were closing", score: 0},
{word: "فرار", definition: "Escape", score: 0},
{word: "مقدارى", definition: "some", score: 0},
{word: "حق", definition: "Right", score: 0},
{word: "سهم", definition: "share", score: 0},
{word: "حيوانات", definition: "animals", score: 0},
{word: "درختان", definition: "trees", score: 0},
{word: "سهميّه", definition: "quota", score: 0},
{word: "حين", definition: "when", score: 0},
{word: "نيز", definition: "too", score: 0},
{word: "شلّاق", definition: "whip", score: 0},
{word: "پشت", definition: "Back", score: 0},
{word: "نواخته", definition: "played", score: 0},
{word: "ارباب", definition: "the master", score: 0},
{word: "مباشر", definition: "Steward", score: 0},
{word: "وى", definition: "his, its", score: 0},
{word: "لذّت", definition: "Pleasure", score: 0},
{word: "بيشترى", definition: "more", score: 0},
{word: "شكنجه", definition: "torture", score: 0},
{word: "روزانه", definition: "Daily", score: 0},
{word: "سلول", definition: "cell", score: 0},
{word: "تاريك", definition: "dark", score: 0},
{word: "بدبو", definition: "Funky", score: 0},
{word: "مىخوابيدند", definition: "They were sleeping", score: 0},
{word: "حشرات", definition: "Insects", score: 0},
{word: "موشها", definition: "mouses", score: 0},
{word: "جولان", definition: "Golan", score: 0},
{word: "همراه", definition: "Along", score: 0},
{word: "زنجير", definition: "chain", score: 0},
{word: "انداخته", definition: "dropped", score: 0},
{word: "مىشدند", definition: "would be", score: 0},
{word: "بدين", definition: "give", score: 0},
{word: "بدين سان", definition: "in this way", score: 0},
{word: "حتّى", definition: "even", score: 0},
{word: "اندازه", definition: "Size", score: 0},
{word: "فضاى", definition: "space", score: 0},
{word: "خالى", definition: "empty", score: 0},
{word: "ميان", definition: "between", score: 0},
{word: "وحش", definition: "wild", score: 0},
{word: "برده", definition: "a slave", score: 0},
{word: "محيط", definition: "environment", score: 0},
{word: "رومى", definition: "Roman", score: 0},
{word: "گونه", definition: "Kind", score: 0},
{word: "نيازى", definition: "a need", score: 0},
{word: "نيست", definition: "is not", score: 0},
{word: "سخن", definition: "speech", score: 0},
{word: "قوانين", definition: "Rules", score: 0},
{word: "مربوط", definition: "related", score: 0},
{word: "گفته", definition: "said", score: 0},
{word: "اينكه", definition: "that", score: 0},
{word: "مالك", definition: "the owner", score: 0},
{word: "كشتن", definition: "to kill", score: 0},
{word: "بند كشيدن", definition: "tie up", score: 0},
{word: "شكايت", definition: "complaint", score: 0},
{word: "داشته", definition: "had", score: 0},
{word: "باشد", definition: "be", score: 0},
{word: "مرجعى", definition: "reference", score: 0},
{word: "رسيدگى", definition: "handling", score: 0}
];
const definition = document.getElementById("definition");
const word = document.getElementById("word");
let wordOnDisplay = false;
let currentWords = lessonWords.slice(0, 9);
let currentIndex = 0;
let setNum = 1;
let setSize = 9;
let dieRoll = 0;
let tapCount = 0;
//let timer;
let translateButtonTapped = false;
const exclamatories = ["Oops", "I Forgor", "RIP Memory", "Uh-Oh"];
let currentEx = 0; //Exclamatory at this index will be displayed next.
init();
function init() {
// Display the first word and definition
word.innerHTML = currentWords[0].word;
definition.innerHTML = currentWords[0].definition;
displaySetNum();
// Event listeners for the buttons
document.getElementById("left-button").addEventListener("touchstart", function () {
if (translateButtonTapped === false) {
translateButtonTapped = true;
} else {
translateButtonTapped = false;
}
});
document.getElementById("left-button").addEventListener("click", function () {
this.blur();
if (wordOnDisplay === true) {
// Move the current word back in the queue by 3 positions
// or to the back if there are less than 4 words in the queue
let currentWord = currentWords.shift();
if (currentWords.length < 4) {
currentWords.push(currentWord); //put it at the very end
console.log(currentWords);
} else {
currentWords.splice(3, 0, currentWord);
console.log(currentWords);
}
currentWord.score = -1;
definition.style.visibility = "hidden";
definition.style.textTransform = "lowercase";
displayDone();
displayNextWord();
document.getElementById("left-button").innerHTML = "Translate";
wordOnDisplay = false;
} else {
wordOnDisplay = true;
definition.style.visibility = "visible";
dieRoll = getRandomNumber();
//If dieRoll < 98, display "Again" instead of an exclamatory remark
if (dieRoll < 98) {
document.getElementById("left-button").innerHTML = "Again";
} else {
if (currentEx > 3) {
currentEx = 0;
}
document.getElementById("left-button").innerHTML = exclamatories[currentEx];
currentEx += 1;
}
}
});
document.getElementById("right-button").addEventListener("click", function () {
this.blur();
// Move the current word to the back of the queue
let currentWord = currentWords.shift();
currentWords.push(currentWord);
currentWord.score++;
// If the word's score is 2, remove it from the queue
if (currentWord.score === 2) {
currentWords = currentWords.filter((word) => word !== currentWord);
}
definition.style.visibility = "hidden";
definition.style.textTransform = "lowercase";
document.getElementById("left-button").innerHTML = "Translate";
displayDone();
displayNextWord();
wordOnDisplay = false;
});
document.getElementById("next-button").addEventListener("click", function () {
this.blur();
// Load the next setSize words from the lessonWords array
currentIndex += setSize;
currentWords = lessonWords.slice(currentIndex, currentIndex + setSize);
definition.style.visibility = "hidden";
definition.style.textTransform = "lowercase";
setNum += 1;
displaySetNum();
displayDone();
displayNextWord();
wordOnDisplay = false;
});
document.addEventListener("keydown", (event) => {
// Check if the key that was pressed is the space key
if (event.key === " ") {
const numInput = document.getElementById("set-num");
numInput.value = numInput.value.replaceAll(" ", "");
if (wordOnDisplay === false) {
displayDone();
definition.style.visibility = "visible";
wordOnDisplay = true;
dieRoll = getRandomNumber();
//If dieRoll < 98, display "Again" instead of an exclamatory remark
if (dieRoll < 98) {
document.getElementById("left-button").innerHTML = "Again";
} else {
if (currentEx > 3) {
currentEx = 0;
}
document.getElementById("left-button").innerHTML = exclamatories[currentEx];
currentEx += 1;
}
} else {
let currentWord = currentWords.shift();
currentWords.push(currentWord);
currentWord.score++;
// If the word's score is 2, remove it from the queue
if (currentWord.score === 2) {
currentWords = currentWords.filter((word) => word !== currentWord);
}
definition.style.visibility = "hidden";
definition.style.textTransform = "lowercase";
document.getElementById("left-button").innerHTML = "Translate";
displayDone();
displayNextWord();
wordOnDisplay = false;
}
}
if (event.key === "Enter") {
const numInput = document.getElementById("set-num");
numInput.blur();
displaySet();
}
});
document.addEventListener("keydown", (event) => {
// Check if the key that was pressed is the space key
if (event.key !== "1") return;
let currentWord = currentWords.shift();
if (currentWords.length < 4) {
currentWords.push(currentWord);
console.log(currentWords);
} else {
currentWords.splice(3, 0, currentWord);
console.log(currentWords);
}
currentWord.score = -1;
definition.style.visibility = "hidden";
definition.style.textTransform = "lowercase";
displayDone();
displayNextWord();
wordOnDisplay = false;
});
document.addEventListener("touchend", (event) => {
// Check if the event target is an input or textarea
if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
return;
}
displayDone();
if (translateButtonTapped === true) {
translateButtonTapped = false;
return;
}
if (wordOnDisplay === false) {
displayDone();
definition.style.visibility = "visible";
wordOnDisplay = true;
dieRoll = getRandomNumber();
// If dieRoll < 98, display "Again" instead of an exclamatory remark
if (dieRoll < 98) {
document.getElementById("left-button").innerHTML = "Again";
} else {
if (currentEx > 3) {
currentEx = 0;
}
document.getElementById("left-button").innerHTML = exclamatories[currentEx];
currentEx += 1;
}
}
});
document.addEventListener("touchstart", (event) => {
tapCount++; // increment the tapCount variable when a tap is detected
});
}
function displaySet() {
const numInput = document.getElementById("set-num");
setNum = parseInt(numInput.value);
currentIndex = setNum * setSize - setSize;
currentWords = lessonWords.slice(currentIndex, currentIndex + setSize);
currentWords.forEach((word) => (word.score = 0));
definition.style.visibility = "hidden";
definition.style.textTransform = "lowercase";
displaySetNum();
displayDone();
displayNextWord();
}
function displaySetNum() {
//Find input box
const numInput = document.getElementById("set-num");
numInput.value = setNum;
}
function displayNextWord() {
// Display the next word and definition
let currentWord = currentWords[0];
document.getElementById("word").innerHTML = currentWord.word;
definition.innerHTML = currentWord.definition;
}
function displayDone() {
if (currentWords.length !== 0) return;
const definition = document.getElementById("definition");
definition.style.visibility = "visible";
definition.innerHTML = "Set Done " + setNum;
//definition.style.textTransform = "capitalize";
}
function getRandomNumber() {
return Math.floor(Math.random() * 100) + 1;
}
</script>
</body>
</html> |
#include <stdio.h>
#include <stdlib.h>
typedef struct No {
int dado;
struct No* proximo;
struct No* anterior;
} No;
No* criarNo(int dado)
{
No* novoNo = (No*)malloc(sizeof(No));
if (novoNo == NULL) {
printf("Erro: Falha na alocação de memória\n");
exit(1);
}
novoNo->dado = dado;
novoNo->proximo = NULL;
novoNo->anterior = NULL;
return novoNo;
}
void inserirNoInicio(No** cabeca, int dado)
{
No* novoNo = criarNo(dado);
novoNo->proximo = *cabeca;
if (*cabeca != NULL) {
(*cabeca)->anterior = novoNo;
}
*cabeca = novoNo;
}
void inserirNoFim(No** cabeca, int dado)
{
No* novoNo = criarNo(dado);
if (*cabeca == NULL) {
*cabeca = novoNo;
return;
}
No* temp = *cabeca;
while (temp->proximo != NULL) {
temp = temp->proximo;
}
temp->proximo = novoNo;
novoNo->anterior = temp;
}
void inserirNaPosicao(No** cabeca, int dado, int posicao)
{
if (posicao < 1) {
printf("Erro: Posição inválida\n");
return;
}
if (posicao == 1) {
inserirNoInicio(cabeca, dado);
return;
}
No* novoNo = criarNo(dado);
No* temp = *cabeca;
for (int i = 1; i < posicao - 1 && temp != NULL; i++) {
temp = temp->proximo;
}
if (temp == NULL) {
printf("Erro: Posição inválida\n");
return;
}
novoNo->proximo = temp->proximo;
novoNo->anterior = temp;
if (temp->proximo != NULL) {
temp->proximo->anterior = novoNo;
}
temp->proximo = novoNo;
}
void excluirNoInicio(No** cabeca)
{
if (*cabeca == NULL) {
printf("Erro: Lista vazia\n");
return;
}
No* temp = *cabeca;
*cabeca = temp->proximo;
if (*cabeca != NULL) {
(*cabeca)->anterior = NULL;
}
free(temp);
}
void excluirNoFim(No** cabeca)
{
if (*cabeca == NULL) {
printf("Erro: Lista vazia\n");
return;
}
No* temp = *cabeca;
while (temp->proximo != NULL) {
temp = temp->proximo;
}
if (temp->anterior != NULL) {
temp->anterior->proximo = NULL;
} else {
*cabeca = NULL;
}
free(temp);
}
void excluirNaPosicao(No** cabeca, int posicao)
{
if (*cabeca == NULL || posicao < 1) {
printf("Erro: Lista vazia ou posição inválida\n");
return;
}
No* temp = *cabeca;
for (int i = 1; i < posicao && temp != NULL; i++) {
temp = temp->proximo;
}
if (temp == NULL) {
printf("Erro: Posição inválida\n");
return;
}
if (temp->anterior != NULL) {
temp->anterior->proximo = temp->proximo;
} else {
*cabeca = temp->proximo;
}
if (temp->proximo != NULL) {
temp->proximo->anterior = temp->anterior;
}
free(temp);
}
No* buscarNo(No* cabeca, int chave)
{
No* temp = cabeca;
while (temp != NULL && temp->dado != chave) {
temp = temp->proximo;
}
return temp;
}
void exibirLista(No* cabeca)
{
No* temp = cabeca;
while (temp != NULL) {
printf("%d ", temp->dado);
temp = temp->proximo;
}
printf("\n");
}
void liberarLista(No** cabeca)
{
No* atual = *cabeca;
No* proximo;
while (atual != NULL) {
proximo = atual->proximo;
free(atual);
atual = proximo;
}
*cabeca = NULL;
}
int main()
{
No* cabeca = NULL;
inserirNoInicio(&cabeca, 10);
inserirNoFim(&cabeca, 20);
inserirNaPosicao(&cabeca, 15, 2);
printf("Lista após inclusão: ");
exibirLista(cabeca);
excluirNoInicio(&cabeca);
excluirNoFim(&cabeca);
excluirNaPosicao(&cabeca, 1);
printf("Lista após exclusão: ");
exibirLista(cabeca);
No* resultadoBusca = buscarNo(cabeca, 20);
if (resultadoBusca != NULL) {
printf("Nó encontrado: %d\n", resultadoBusca->dado);
} else {
printf("Nó não encontrado\n");
}
liberarLista(&cabeca);
return 0;
} |
// Copyright (C) 2004-2018 by The Allacrost Project
// All Rights Reserved
//
// This code is licensed under the GNU GPL version 2. It is free software
// and you may modify it and/or redistribute it under the terms of this license.
// See http://www.gnu.org/copyleft/gpl.html for details.
/** ****************************************************************************
*** \file battle_utils.h
*** \author Tyler Olsen (Roots)
*** \brief Header file for battle mode utility code
***
*** This file contains utility code that is shared among the various battle mode
*** classes.
*** ***************************************************************************/
#pragma once
#include "defs.h"
#include "utils.h"
#include "system.h"
#include "global_objects.h"
#include "global_utils.h"
namespace hoa_battle {
namespace private_battle {
//! \name Screen dimension constants
//@{
//! \brief Battle scenes are visualized via an invisible grid of 64x64 tiles
const uint32 TILE_SIZE = 64;
//! \brief The length of the screen in number of tiles (16 x 64 = 1024)
const uint32 SCREEN_LENGTH = 16;
//! \brief The height of the screen in number of tiles (12 x 64 = 768)
const uint32 SCREEN_HEIGHT = 12;
//@}
/** \name Action Type Constants
*** \brief Identifications for the types of actions a player's characters may perform
*** \note These are not enums because they have to map to selection indexes within a GUI OptionBox
**/
//@{
const uint32 CATEGORY_SKILL = 0;
const uint32 CATEGORY_ITEM = 1;
const uint32 CATEGORY_RECOVER = 2;
//@}
//! \brief Position constants representing the significant locations along the action meter
//@{
//! \brief The bottom most position of the action bar
const float ACTION_LOCATION_BOTTOM = 128.0f;
//! \brief The location where each actor is allowed to select a command
const float ACTION_LOCATION_COMMAND = ACTION_LOCATION_BOTTOM + 354.0f;
//! \brief The top most position of the action bar where actors are ready to execute their actions
const float ACTION_LOCATION_TOP = ACTION_LOCATION_BOTTOM + 508.0f;
//@}
//! \brief Determines how much SP a character regenerates each turn. This value is divided into the character's active max SP
const uint32 CHARACTER_SP_REGENERATION_RATE = 10;
//! \brief Returned as an index when looking for a character or enemy and they do not exist
const uint32 INVALID_BATTLE_ACTOR_INDEX = 999;
//! \brief This is the idle state wait time for the fastest actor, used to set idle state timers for all other actors
const uint32 MIN_IDLE_WAIT_TIME = 7500;
//! \brief Warm up time for using items (try to keep short, should be constant regardless of item used)
const uint32 ITEM_WARM_UP_TIME = 1000;
//! \brief Warm up time for selecting the "Recover" action for a character
const uint32 RECOVER_WARM_UP_TIME = 1000;
//! \brief The amount of time to take while transitioning between sprite frames for an enemy
const uint32 ENEMY_SPRITE_TRANISITION_TIME = 1000;
//! \brief Used to indicate what state the overall battle is currently operating in
enum BATTLE_STATE {
BATTLE_STATE_INVALID = -1,
BATTLE_STATE_INITIAL = 0, //!< Character sprites are running in from off-screen to their battle positions
BATTLE_STATE_NORMAL = 1, //!< Normal state where player is watching actions play out and waiting for a turn
BATTLE_STATE_COMMAND = 2, //!< Player is choosing a command for a character
BATTLE_STATE_EVENT = 3, //!< A scripted event is taking place, suspending all standard action
BATTLE_STATE_END = 4, //!< Battle has ended, final actions and deaths are being played out
BATTLE_STATE_VICTORY = 5, //!< Battle has ended with the characters victorious
BATTLE_STATE_DEFEAT = 6, //!< Battle has ended with the characters defeated
BATTLE_STATE_EXITING = 7, //!< Player has closed battle windows and battle mode is fading out
BATTLE_STATE_TOTAL = 8
};
//! \brief Represents the possible states that a BattleActor may be in as they pertain to the action bar
enum ACTOR_STATE {
ACTOR_STATE_INVALID = -1,
ACTOR_STATE_IDLE = 0, //!< Actor is recovering stamina so they can execute another action
ACTOR_STATE_COMMAND = 1, //!< Actor is finished with the idle state but has not yet selected an action to execute
ACTOR_STATE_WARM_UP = 2, //!< Actor has selected an action and is preparing to execute it
ACTOR_STATE_READY = 3, //!< Actor is prepared to execute action and is waiting their turn to act
ACTOR_STATE_ACTING = 4, //!< Actor is in the process of executing their selected action
ACTOR_STATE_DEAD = 5, //!< Actor has perished and is inactive in battle
ACTOR_STATE_PARALYZED = 6, //!< Actor is in some state of paralysis and can not act nor recover stamina
ACTOR_STATE_TOTAL = 7
};
//! \brief Used for determining the proper sprite frame to draw for an enemy baed on the degree of damage that an enemy has taken, broken up into percentiles of 25%.
enum ENEMY_SPRITE_TYPE {
ENEMY_SPRITE_INVALID = -1,
ENEMY_SPRITE_OVER75 = 0, //!< Enemy has between 100% and 75% health
ENEMY_SPRITE_OVER50 = 1, //!< Enemy has between 75% and 50% health
ENEMY_SPRITE_OVER25 = 2, //!< Enemy has between 50% and 25% health
ENEMY_SPRITE_OVER0 = 3, //!< Enemy has between 25% and 0% health
ENEMY_SPRITE_0GRAY = 4, //!< Enemy has 0% health and is transitioning to grayscale
ENEMY_SPRITE_0DEAD = 5, //!< Enemy has 0% health and is transitioning from grayscale to vanished
ENEMY_SPRITE_TOTAL = 6
};
//! \brief Enums for the various states that the CommandSupervisor class may be in
enum COMMAND_STATE {
COMMAND_STATE_INVALID = -1,
//! Player is selecting the type of action to execute
COMMAND_STATE_CATEGORY = 0,
//! Player is selecting from a list of actions to execute
COMMAND_STATE_ACTION = 1,
//! Player is selecting the actor target to execute the action on
COMMAND_STATE_ACTOR = 2,
//! Player is viewing information about the selected action
COMMAND_STATE_INFORMATION = 3,
COMMAND_STATE_TOTAL = 4
};
/** \name Command battle calculation functions
*** These functions perform many of the common calculations that are needed in battle such as determining
*** evasion and the amount of damage dealt. Lua functions that implement the effect of skills and items
*** make the most use of these functions. Thus, these functions are specifically designed for that use
*** and do not utilize C++ features that Lua can not take advantage of, such as references or default
*** values for function arguments.
***
*** There are also many functions that share the same name but have a different function signature. These
*** functions perform the same task but some take extra arguments to make the calculation more flexible. For
*** example, many functions have a version that allows adjustment of the variation by accepting a standard deviation
*** argument.
***
*** \note These calculations only work for valid non-party type targets. If it is desired to use these methods
*** on a party target, a set of targets for each actor in the target party must be extracted and those actor
*** targets used individually for these various methods.
**/
//@{
/** \brief Determines if a target has evaded an attack or other action
*** \param target A pointer to the target to calculate evasion for
*** \return True if the target evasion was successful
**/
bool CalculateStandardEvasion(BattleTarget* target);
/** \brief Determines if a target has evaded an attack or other action, utilizing an addition modifier
*** \param target A pointer to the target to calculate evasion for
*** \param add_eva A modifier value to be added/subtracted to the standard evasion rating
*** \return True if the target evasion was successful
***
*** The additional_evasion may be positive or negative. If the total evasion value falls below 0.0f
*** the function will return false and if that value exceeds 100.0f it will return true. Otherwise the total
*** evade value will serve as a standard probability distribution to determine whether the evasion was
*** successful or not.
**/
bool CalculateStandardEvasionAdder(BattleTarget* target, float add_eva);
/** \brief Determines if a target has evaded an attack or other action, utilizing a multiplication modifier
*** \param target A pointer to the target to calculate evasion for
*** \param mul_eva A modifier value to be multiplied to the standard evasion rating
*** \return True if the target evasion was successful
***
*** This function operates the same as the CalculateStandardEvasion(...) functions with the exception that
*** its float argument is used as a multiple in the evasion calculation instead of an addition. So for instance
*** if the user wants the evasion chance to increase by 20%, 1.2f would be passed in for the multiple_evasion
*** argument. A decrease by 35% would need a value of 0.65f. Negative multiplier values will cause a warning to
*** be printed and the absolute value of the multiplier will be used.
**/
bool CalculateStandardEvasionMultiplier(BattleTarget* target, float mul_eva);
/** \brief Determines the amount of damage caused with a physical attack
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** This function uses the physical attack/defense ratings to calculate the total damage caused. This function
*** uses a gaussian random distribution with a standard deviation of ten percent to perform variation in the
*** damage caused. Therefore this function may return different values each time it is called with the same arguments.
*** If the amount of damage calculates out to zero, a small random non-zero value will be returned instead.
**/
uint32 CalculatePhysicalDamage(BattleActor* attacker, BattleTarget* target);
/** \brief Determines the amount of damage caused with a physical attack
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param std_dev The standard deviation to use in the gaussian distribution, where "0.075f" would represent 7.5% standard deviation
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** The std_dev value is always relative to the amount of absolute damage calculated prior to the gaussian randomization.
*** This means that you can -not- use this function to declare an absolute standard deviation, such as a value of 20 damage
*** points.
**/
uint32 CalculatePhysicalDamage(BattleActor* attacker, BattleTarget* target, float std_dev);
/** \brief Determines the amount of damage caused with a physical attack, utilizing an addition modifier
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param add_atk An additional amount to add to the physical damage dealt
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** The add_atk argument may be positive or negative. Large negative values can skew the damage calculation
*** and cause the damage dealt to drop to zero, so be cautious when setting this argument to a negative value.
**/
uint32 CalculatePhysicalDamageAdder(BattleActor* attacker, BattleTarget* target, int32 add_atk);
/** \brief Determines the amount of damage caused with a physical attack, utilizing an addition modifier
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param add_atk An additional amount to add to the physical damage dealt
*** \param std_dev The standard deviation to use in the gaussian distribution, where "0.075f" would represent 7.5% standard deviation
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
**/
uint32 CalculatePhysicalDamageAdder(BattleActor* attacker, BattleTarget* target, int32 add_atk, float std_dev);
/** \brief Determines the amount of damage caused with a physical attack, utilizing a mulitplication modifier
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param mul_atk An additional amount to be multiplied to the physical damage dealt
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** This function operates the same as the CalculatePhysicalDamageAdder(...) functions with the exception that
*** its float argument is used as a multipler in the damage calculation instead of an integer addition modifier.
*** So for instance if the user wants the physical damage to decrease by 20% the value of mul_atk would
*** be 0.8f. If a negative multiplier value is passed to this function, its absoute value will be used and
*** a warning will be printed.
**/
uint32 CalculatePhysicalDamageMultiplier(BattleActor* attacker, BattleTarget* target, float mul_phys);
/** \brief Determines the amount of damage caused with a physical attack, utilizing a multiplication modifier
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param mul_atk A modifier to be multiplied to the physical damage dealt
*** \param std_dev The standard deviation to use in the gaussian distribution, where "0.075f" would represent 7.5% standard deviation
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** This function signature allows the additional option of setting the standard deviation in the gaussian random value calculation.
**/
uint32 CalculatePhysicalDamageMultiplier(BattleActor* attacker, BattleTarget* target, float mul_atk, float std_dev);
/** \brief Determines the amount of damage caused with an ethereal attack
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** This function uses the ethereal attack/defense ratings to calculate the total damage caused. This function
*** uses a gaussian random distribution with a standard deviation of ten percent to perform variation in the
*** damage caused. Therefore this function may return different values each time it is called with the same arguments.
*** If the amount of damage calculates out to zero, a small random non-zero value will be returned instead.
**/
uint32 CalculateEtherealDamage(BattleActor* attacker, BattleTarget* target);
/** \brief Determines the amount of damage caused with an ethereal attack
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param std_dev The standard deviation to use in the gaussian distribution, where "0.075f" would represent 7.5% standard deviation
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** The std_dev value is always relative to the amount of absolute damage calculated prior to the gaussian randomization.
*** This means that you can -not- use this function to declare an absolute standard deviation, such as a value of 20 damage
*** points.
**/
uint32 CalculateEtherealDamage(BattleActor* attacker, BattleTarget* target, float std_dev);
/** \brief Determines the amount of damage caused with an ethereal attack, utilizing an addition modifier
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param add_atk An additional amount to add to the ethereal damage dealt
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** The add_atk argument may be positive or negative. Large negative values can skew the damage calculation
*** and cause the damage dealt to drop to zero, so be cautious when setting this argument to a negative value.
**/
uint32 CalculateEtherealDamageAdder(BattleActor* attacker, BattleTarget* target, int32 add_atk);
/** \brief Determines the amount of damage caused with a physical attack, utilizing an addition modifier
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param add_atk An additional amount to add to the ethereal damage dealt
*** \param std_dev The standard deviation to use in the gaussian distribution, where "0.075f" would represent 7.5% standard deviation
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
**/
uint32 CalculateEtherealDamageAdder(BattleActor* attacker, BattleTarget* target, int32 add_atk, float std_dev);
/** \brief Determines the amount of damage caused with a physical attack, utilizing a mulitplication modifier
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param mul_phys An additional amount to be multiplied to the ethereal damage dealt
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** This function operates the same as the CalculateEtherealDamageAdder(...) functions with the exception that
*** its float argument is used as a multipler in the damage calculation instead of an integer addition modifier.
*** So for instance if the user wants the ethereal damage to decrease by 20% the value of mul_atk would
*** be 0.8f. If a negative multiplier value is passed to this function, its absoute value will be used and
*** a warning will be printed.
**/
uint32 CalculateEtherealDamageMultiplier(BattleActor* attacker, BattleTarget* target, float mul_atk);
/** \brief Determines the amount of damage caused with an ethereal attack, utilizing a multiplication modifier
*** \param attacker A pointer to the attacker who is causing the damage
*** \param target A pointer to the target that will be receiving the damage
*** \param mul_atk A modifier to be multiplied to the ethereal damage dealt
*** \param std_dev The standard deviation to use in the gaussian distribution, where "0.075f" would represent 7.5% standard deviation
*** \return The amount of damage dealt, which will always be a non-zero value unless there was an error
***
*** This function signature allows the additional option of setting the standard deviation in the gaussian random value calculation.
**/
uint32 CalculateEtherealDamageMultiplier(BattleActor* attacker, BattleTarget* target, float mul_atk, float std_dev);
//@}
/** ****************************************************************************
*** \brief Builds upon the SystemTimer to provide more flexibility and features
***
*** Battle mode timers are a bit more advanced over the standard system engine
*** timer to meet the needs of some timers in battle mode. The additional features
*** available to battle timers over system timers include the following.
***
*** - The ability to set the expiration time of the current loop to any value
*** - Apply a floating-point multiplier to speed up or slow down the timer
***
*** \note Not all timers in battle mode will require the features of this class.
*** Evaluate the needs of a timer in the battle code and determine whether or not
*** it should use this class or if the standard SystemTimer will meet its needs.
*** ***************************************************************************/
class BattleTimer : public hoa_system::SystemTimer {
friend class SystemEngine; // For allowing SystemEngine to call the _AutoUpdate() method
public:
BattleTimer();
/** \brief Creates and places the timer in the SYSTEM_TIMER_INITIAL state
*** \param duration The duration (in milliseconds) that the timer should count for
*** \param loops The number of times that the timer should loop for. Default value is set to no looping.
**/
BattleTimer(uint32 duration, int32 loops = 0);
~BattleTimer()
{}
//! \brief Overrides the SystemTimer::Update() method
void Update();
/** \brief Overrides the SystemTimer::Update(uint32) method
*** \param time The amount of time to increment the timer by
**/
void Update(uint32 time);
//! \brief Overrides the SystemTimer::Reset() method
void Reset();
/** \brief Sets the time expired member and updates the timer object appropriately
*** \param time The value to set for the expiration time
***
*** This method will do nothing if the state of the object is SYSTEM_TIMER_INVALID or SYSTEM_TIMER_FINISHED.
*** The new expiration time applies only to the current loop. So for example, if the timer is on loop #2
*** of 5 and the loop duration is 1000ms, setting the time to 1500ms will result in the timer
*** state changing to loop #3 and set the expiration time back to zero. Reaching the last loop
*** will set the timer to the FINISHED state. Using a zero value for the time while on the first loop will
*** change the timer to the INITIAL state.
***
*** If you're only looking to increment the expiration time and wish for that increment to take
*** effect for more than just the current loop, use the Update(uint32) method. Although be aware that
*** Update() will take into account any timer multipliers that are active while this method ignores
*** the timer multiplier.
**/
void SetTimeExpired(uint32 time);
/** \brief Stops the timer for the amount of time specified before it can continue
*** \param time The number of milliseconds for the timer to remain "stunned"
***
*** You can call this function multiple times and the stun time values will accumulate. For example, if you
*** call the function with a value of 100, then 20ms later call it again with a value of 50, the stun time
*** will be 130ms after the second call (100 - 20 + 50).
**/
void StunTimer(uint32 time)
{ _stun_time += time; }
/** \brief Activates or deactivates the timer multiplier
*** \param activate True will activate and set the multiplier while false will deactivate.
*** \param multiplier The multiplier value to apply towards the timer, which should be positive.
***
*** If the activate argument is false, the multiplier value will be ignored. The multiplier
*** value is multiplied directly to the raw update time to obtain the actual update time.
*** So for example if the raw update time is 25 and the multiplier value is 0.8f, the actual
*** update time for the class will be 20.
**/
void ActivateMultiplier(bool activate, float multiplier);
//! \name Class member accessor methods
//@{
bool IsStunActive() const
{ return (_stun_time > 0); }
bool IsMultiplierActive() const
{ return _multiplier_active; }
float GetMultiplierFactor() const
{ return _multiplier_factor; }
//@}
protected:
//! \brief This value must be consumed by the update process before the _time_expired member can continue to be updated
uint32 _stun_time;
/** \brief Constantly tries to approach the value of _time_expired in a gradual manner
***
*** This member allows us to show "gradual shifts" whenever the _time_expired member jumps to a new value. For example,
*** if a battle skill is used that reduces the _time_expired value of the target to zero, instead of instantly jumping the
*** action portrait of the target to the zero mark on the action bar, this member will show a quick but gradual move downward.
**/
uint32 _visible_time_expired;
//! \brief When true the timer multiplier is applied to all timer updates
bool _multiplier_active;
//! \brief A zero or positive value that is multiplied to the update time
float _multiplier_factor;
//! \brief Accumulates fractions of a millisecond that were applied by a mutliplier (ie, an update of 15.5ms would store the 0.5)
float _multiplier_fraction_accumulator;
//! \brief Overrides the SystemTimer::_AutoUpdate() method
virtual void _AutoUpdate();
private:
/** \brief Computes and returns the update time after any stun duration has been accounted for
*** \param time The update time to apply to any active stun effect
*** \return The modified update time after stun has been acounted for
***
*** If the value of _stun_time is zero, this function will do nothing and return the value that it was passed.
*** It is possible that this function may consume the entire update time to reduce an active stun effect, and
*** thus would return a zero value.
**/
uint32 _ApplyStun(uint32 time);
/** \brief Computes and returns the update time after the multiplier has been applied
*** \param time The raw update time to use in the calculation
*** \return The modified update time
***
*** This method does not do any error checking such as whether the multiplier is a valid number
*** (non-negative) or whether or not the multiplier is active. The code that calls this function
*** is responsible for that condition checking.
***
*** This function also adds any remainders after applying the multiplier to the accumulator. If it
*** finds the value of the accumulator is greater than or equal to 1.0f, it adds the integer amount
*** to the return value and subtracts this amount from the accumulator. For example, if the accumulator
*** held a value of 0.85f before this function was called, and the multiplier application left an additional
*** 0.5f remainder, the value of the accumulator after the call returns will be 0.35f and a value of 1 will
*** be added into the value that the function returns.
**/
uint32 _ApplyMultiplier(uint32 time);
/** \brief Updates the value of the _visible_time_expired member to reduce the distance between it and _UpdateTime
*** \param time The amount of time that the actual timer was just updated by. Zero if no update was applied to the timer.
***
*** This function aims to make the _visible_time_expired member equal to the _time_expired member over a series of gradual steps.
*** The time argument is used to keep the two members in sync when they are already equal in value.
**/
void _UpdateVisibleTimeExpired(uint32 time);
}; // class BattleTimer : public hoa_system::SystemTimer
/** ****************************************************************************
*** \brief Container class for representing the target of a battle action
***
*** Valid target types include both actors and actor parties. This class is
*** somewhat of a wrapper and allows a single instance of BattleTarget to represent
*** any of these types. It also contains a handful of methods useful in determining
*** the validity of a selected target and selecting another target of the same type.
***
*** Many of these functions are dependent on receiving a pointer to a BattleActor
*** object that is using or intends to use the BattleTarget object. This is necessary
*** because the different types of the GLOBAL_TARGET enum are relative and the class
*** selects different targets relative to the user. For example, selecting the next
*** actor when the target type is GLOBAL_TARGET_ALLY requires knowing whether the user
*** is a character or an enemy.
*** ***************************************************************************/
class BattleTarget {
public:
BattleTarget();
~BattleTarget()
{}
//! \brief Resets all class members, invalidating the target
void InvalidateTarget();
/** \brief Used to set the initial target
*** \param user A pointer to the actor which will use the target
*** \param type The type of target to set
***
*** If the function fails to find an initial target, the target type will be set to
*** GLOBAL_TARGET_INVALID. The initial actor will always be the first valid actor in their respective
*** party (index 0).
**/
void SetInitialTarget(BattleActor* user, hoa_global::GLOBAL_TARGET type);
/** \brief Sets the target to an actor
*** \param type The type of target to set, must be one of the actor type targets
*** \param actor A pointer to the actor to set for the target
**/
void SetActorTarget(hoa_global::GLOBAL_TARGET type, BattleActor* actor);
/** \brief Sets the target to a party
*** \param type The type of target to set, must be one of the party type targets
*** \param actor A pointer to the party to set for the target
**/
void SetPartyTarget(hoa_global::GLOBAL_TARGET type, std::deque<BattleActor*>* party);
/** \brief Returns true if the target is valid (non-zero HP)
*** This method assumes that a valid target is one that is alive (non-zero HP). If the target type
*** is an actor, the function returns true so long as the target actor is alive. If the target type
*** is a party, this method will always return true as parties always have at least one living actor
*** unless the battle has ended.
***
*** Not all actions/skills/items should rely on this method for determining whether or not the
*** target is valid for their particular circumstances. For example, a revive item is only valid
*** to use on a dead actor. Other actions/items may have their own criteria for determining what
*** is a valid target.
**/
bool IsValid();
/** \brief Changes the target actor to reference the next available actor
*** \param user A pointer to the actor which is using this target
*** \param direction Tells the method to look either forward or backward (true/false) for the next target
*** \param valid_criteria When true the method will only select actors determined to be valid by IsValid()
*** \return True if the _actor member was changed, false if it was not
***
*** This method should only be called when the target type is not one of the party types.
**/
bool SelectNextActor(BattleActor* user, bool direction = true, bool valid_criteria = true);
/** \brief Retrieves a pointer to the actor of a party at the specified index
*** \param index The location in the party container of the actor to retrieves
*** \return nullptr if the target is not a party or the index is invalid. Otherwise a pointer to the actor specified
***
*** The primary purpose for the existence of this function is for Lua to be able to access all the actors within a
*** party target. The GetParty() method can not be used by Lua as Lua does not understand that container format
*** (std::deque<BattleActor*>). To retrieve each actor, Lua code starts at index 0 and makes repeated calls to this
*** function while incrementing the index by 1 until it returns a nullptr value.
**/
BattleActor* GetPartyActor(uint32 index);
/** \brief Returns the name of the target
***
*** Party type targets will return "All Allies" or "All Enemies". Actor type targets return the name of the character or
*** enemy, for example "Claudius" or "Red Spider". Invalid targets will return "[Invalid Target]".
**/
hoa_utils::ustring GetName();
//! \name Class member accessor methods
//@{
hoa_global::GLOBAL_TARGET GetType() const
{ return _type; }
BattleActor* GetActor() const
{ return _actor; }
std::deque<BattleActor*>* GetParty() const
{ return _party; }
//@}
private:
//! \brief The type of target this object represents (actor or party)
hoa_global::GLOBAL_TARGET _type;
//! \brief The actor to target
BattleActor* _actor;
//! \brief The party to target
std::deque<BattleActor*>* _party;
}; // class BattleTarget
/** ****************************************************************************
*** \brief A simple container class for items that may be used in battle
***
*** This class adds an additional member to be associated with GlobalItem objects
*** which keeps track of how many of that item are available to use. This is necessary
*** because when an actor selects an item to use, they do not immediately use that
*** item and may ultimately not use the item due to the user becoming incapacitated
*** or having no valid target for the item. At all times, the available count of an item
*** will be less than or equal to the actual count of the item.
***
*** The proper way to use this class is to call the following methods for the following
*** situations.
***
*** - DecrementAvailableCount(): call when an actor has selected to use an item
*** - IncrementAvaiableAcount(): call when an actor does not use an item that it selected
*** - DecrementCount(): call when the item is actually used
***
*** \note Do not call the IncrementCount(), DecrementCount(), or SetCount() methods on the GlobalItem
*** pointer. This will circumvent the ability of this class to keep an accurate and correct available
*** count. Instead, use the IncrementCount() and DecrementCount() methods of this BattleItem class
*** directly.
*** ***************************************************************************/
class BattleItem {
public:
//! \param item A pointer to the item to represent. Should be a non-nullptr value.
BattleItem(hoa_global::GlobalItem item);
~BattleItem();
//! \brief Class member accessor methods
//@{
hoa_global::GlobalItem& GetItem()
{ return _item; }
uint32 GetAvailableCount() const
{ return _available_count; }
//@}
/** \brief Increases the available count of the item by one
*** The available count will not be allowed to exceed the GlobalItem _count member
**/
void IncrementAvailableCount();
/** \brief Decreases the available count of the item by one
*** The available count will not be allowed to decrement below zero
**/
void DecrementAvailableCount();
/** \brief Increments the count of an item by one
*** \note This method should not be called under normal battle circumstances
**/
void IncrementCount();
/** \brief Decrements the count of the item by one
*** Will also decrement the available count if the two counts are equal
**/
void DecrementCount();
/** \brief A wrapper function that retrieves the actual count of the item
*** \note Calling this function is equivalent to calling GetItem().GetCount()
**/
uint32 GetCount() const
{ return _item.GetCount(); }
/** \brief A wrapper function that retrieves the target type of the item
*** \note Calling this function is equivalent to calling GetItem().GetTargetType()
**/
hoa_global::GLOBAL_TARGET GetTargetType() const
{ return _item.GetTargetType(); }
private:
//! \brief The item that this class represents
hoa_global::GlobalItem _item;
//! \brief The number of instances of this item that are available to be selected to be used
uint32 _available_count;
}; // class BattleItem
} // namespace private_battle
} // namespace hoa_battle |
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/detrin/lunch-watchdog-backend/watchdog"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
func main() {
var menus []watchdog.Menu
menuKolkovna, err := watchdog.ScrapeMenuKolkovna()
if err != nil {
log.Fatalf("Error scraping menu: %v", err)
}
fmt.Printf("Menu for %s - %s\n", menuKolkovna.Name, menuKolkovna.Date)
for i, item := range menuKolkovna.MenuItems {
fmt.Printf("Item %d: %#v\n", i+1, item)
}
menuKolkovna.TranslateEN()
menus = append(menus, *menuKolkovna)
menuMerkur, err := watchdog.ScrapeMenuMerkur()
if err != nil {
log.Fatalf("Error scraping menu: %v", err)
}
fmt.Printf("Menu for %s - %s\n", menuMerkur.Name, menuMerkur.Date)
for i, item := range menuMerkur.MenuItems {
fmt.Printf("Item %d: %#v\n", i+1, item)
}
menuMerkur.TranslateEN()
menus = append(menus, *menuMerkur)
jsonData, err := json.MarshalIndent(menus, "", " ")
if err != nil {
log.Fatalf("Error marshaling menu to JSON: %v", err)
}
fmt.Println(string(jsonData))
endpoint := "eu2.contabostorage.com"
accessKeyID := os.Getenv("AWS_ACCESS_KEY_ID")
secretAccessKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
s3Client, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Secure: true,
})
if err != nil {
log.Fatalln(err)
}
bucketName := "lunch-watchdog"
objectName := "menus.json"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
_, err = s3Client.StatObject(ctx, bucketName, objectName, minio.StatObjectOptions{})
if err == nil {
// The object exists, so delete it.
err := s3Client.RemoveObject(ctx, bucketName, objectName, minio.RemoveObjectOptions{})
if err != nil {
log.Fatalf("Error deleting existing object: %v", err)
}
log.Printf("Successfully deleted %s\n", objectName)
} else {
// Handle errors other than "object not found."
if minio.ToErrorResponse(err).Code != "NoSuchKey" {
log.Fatalf("Error checking object: %v", err)
}
}
// Then proceed to upload the new file.
content := bytes.NewReader(jsonData)
opts := minio.PutObjectOptions{ContentType: "application/json"}
info, err := s3Client.PutObject(ctx, bucketName, objectName, content, int64(content.Len()), opts)
if err != nil {
log.Fatalf("Error uploading new object: %v", err)
}
log.Printf("Successfully uploaded %s of size %d\n", objectName, info.Size)
} |
/*
Arduino Chicken Coop Controller
Based loosely on code by Will Vincent <will@willvincent.com>
This Sketch is designed to work on a ESP-8266 MUANODE 0.9 board
*/
#include "options.h"
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <Wire.h> // https://www.arduino.cc/en/Reference/Wire
#include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient
#include <Bounce2.h> // https://github.com/thomasfredericks/Bounce2
#include <RTClib.h> // https://github.com/adafruit/RTClib
#ifdef LCD_DISPLAY
#include <LiquidCrystal_I2C.h>
#endif
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson
#define mClientID "coop-duino"
#include "pins.h" // holds pin definitions
#define CoopTrollerVersion "3.04e"
// MQTT Subscription Channels
#define sTime "time/beacon"
#define sRemote "coop/remotetrigger"
#define sSunRise "sun/rise"
#define sSunSet "sun/set"
// MQTT Publish Channels
#define pLight "coop/brightness"
#define pStatus "coop/status"
// DOOR motion. Relays are active on low
#define GO 0
#define STOP 1
// Misc Settings
const unsigned long millisPerDay = 86400000; // Milliseconds per day
const unsigned long lightReadRate = 30000; // How often to read light level (30 sec)
const unsigned long remoteOverride = 600000; // Length of time to lockout readings. (10 min)
const unsigned long publishInterval = 600000; // How often to publish light sensor readings. (10 min)
const unsigned long maxMotorOn = 6000; // Maximum time for the motor to be on (6 seconds)
const unsigned long lcdUpdateRate = 5000; // LCD update rate (5 seconds)
// Night time lockout to prevent reaction to light sensor readings if an exterior light source causes
// a reading otherwise bright enough to activate the interior light and/or door.
const boolean nightLock = false; // Enable night time lockout
/*************************************************
DO NOT EDIT BELOW THIS LINE
*************************************************/
// Runtime variables
int nightLockStart = 22; // Hour (in 24hr time) to initiate night time lockout (10pm)
int nightLockEnd = 4; // Hour (in 24hr time) to end night time lockout (4am)
unsigned long lastDebounce = 0;
unsigned long lastLightRead = 0;
unsigned long lastRTCSync = 0;
unsigned long remoteLockStart = 0;
unsigned long motorRunning = 0; // how long has the motor been on
unsigned long motorTimeOut = 300000; // Time to wait before running motor again (5 minutes)
unsigned long lastMotorRun = 0; // last time the motor was activated
unsigned long lastLcdUpdate = 0; // last time LCD was updated
String doorState = "Uninitialzed"; // Values will be one of: closed, closing, open, opening, unknown
String doorStatePrev = "";
int brightness = 0;
int openBright = 40; // brightness to wait until opening the door
int closeBright = 25; // brightness to wait until closing the door
int doorTopVal = 0;
int doorTopVal2 = 0;
int doorTopState = 0;
int doorTopPrev = 0;
int doorBottomVal = 0;
int doorBottomVal2 = 0;
int doorBottomState = 0;
int doorBottomPrev = 0;
//uint32_t bootTime = 0;
char mqtt_msg_buf[100]; // Max MQTT incoming message size
DateTime now;
boolean wifiConnected = false;
#ifdef LCD_DISPLAY
char lcd_buf[21]; // LCD cols + 1 for null character
#endif
//define your default values here, if there are different values in config.json, they are overwritten.
char mqtt_server[40];
char mqtt_port[6] = "1883";
//flag for saving data
bool shouldSaveConfig = false;
// Define the hardware components
// Real Time Clock
RTC_DS3231 RTC;
// ESP8266 instance
EspClass esp;
// WiFi instance
WiFiClient espClient;
// LCD (if enabled)
#ifdef LCD_DISPLAY
LiquidCrystal_I2C lcd(0x27, 20, 4); // i2c address x27, 20 cols x 4 rows
#endif
// MQTT
PubSubClient mqtt(espClient);
// Setup switch debounce software
Bounce debounceTop = Bounce();
Bounce debounceBot = Bounce();
/**
* WiFi Manager callback notifying us of the need to save config
*/
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;
}
/**
* Manage WIFI connection
*/
void wifiCb(WiFiEvent_t event) {
if (Debugging) {
Serial.printf("\n[WiFi-event] event: %d\n", event);
}
switch(event) {
case WIFI_EVENT_STAMODE_GOT_IP:
if (Debugging) {
Serial.print("WiFi IP: ");
Serial.println(WiFi.localIP());
}
mqtt.connect(mClientID);
if ( !mqtt.connected() ) {
delay(100);
mqtt.connect(mClientID);
}
wifiConnected = true;
break;
case WIFI_EVENT_STAMODE_DISCONNECTED:
if (Debugging) {
Serial.println("WiFi lost connection");
}
wifiConnected = false;
mqtt.disconnect();
break;
}
}
/**
* MQTT Connection event handler.
*
* Subscribes to desired channels
*/
void mqttSubscribe() {
if (wifiConnected) {
if (Debugging) {
Serial.println("MQTT Subscribing");
}
// Subscribe to time beacon channel to keep RTC up to date.
mqtt.subscribe(sTime, 0); // QoS 0 means no verification, 1 means verificaton
// Subscribe to remote trigger channel to allow remote control of chicken coop
mqtt.subscribe(sRemote, 1);
// Subscribe to sunrise/set updates
mqtt.subscribe(sSunRise, 1);
mqtt.subscribe(sSunSet, 1);
// Publish that we're online!
mqtt.publish(pStatus, "mqttOnline");
} else {
if (Debugging) {
Serial.println("MQTT NOT Subscribed because WIFI is not connected");
}
}
}
/**
* Handle incoming MQTT messages.
*
* This allows us to remotely trigger events via WIFI!
*/
void mqttData(char* topic, byte* payload, unsigned int plen) {
// Copy the payload to the MQTT message buffer
if( plen > sizeof(mqtt_msg_buf)) { // buffer is only 100 bytes long
plen = sizeof(mqtt_msg_buf);
}
memset(mqtt_msg_buf,'\0',plen+1);
memcpy(mqtt_msg_buf,payload,plen);
String data = String((char *) mqtt_msg_buf);
if(Debugging) {
Serial.print("mqttTopic*Len*Data: |");
Serial.print(topic);
Serial.print("| * |");
Serial.print(plen);
Serial.print("| * |");
Serial.print(data);
Serial.println("|");
}
if (strcmp(topic,sRemote)==0) {
// If door movement is triggered, toggle door state to
// opening or closing based on current state.
// If door is currently moving, the trigger is ignored.
if (data == "status") { // get a general status ... (obviously WiFi and MQTT are ok)
char buf[100];
String pubString;
pubString="Door:"+String(doorState)+", Top:"+String(doorTopState)+", Bot:"+String(doorBottomState)+", Light:"+String(brightness);
pubString.toCharArray(buf, pubString.length()+1);
if (wifiConnected) {
mqtt.publish(pStatus, buf);
}
}
/* not ready for prime time
if (data == "jstatus") { // JSON status
char buf[201];
StaticJsonBuffer<200> jsonBuffer;
JsonObject& mqttJson = jsonBuffer.createObject();
mqttJson["tstamp"]=RTC.now();
JsonArray& data = mqttJson.createArray();
JsonObject& data = createNestedObject();
data["brightness"]=Brightness;
date["doorState"]=doorState;
data["topState"]=doorTopState;
data["botState"]=doorBottomState;
mqttJson.printTo(buf,200);
mqtt.publish(pStatus,buf);
}
*/
if (data == "unlock") { // this will immediately put the system back into normal operation (i.e., using the light sensor)
remoteLockStart = 0;
if (wifiConnected) {
mqtt.publish(pStatus, "remotetrigger|unlock");
}
if(Debugging) {
Serial.println("remoteLockStart unset");
}
}
if (data == "reboot") {
if (wifiConnected) {
mqtt.publish(pStatus, "remotetrigger|reboot");
}
ESP.restart();
}
if (data == "debug") {
Debugging = 1 - Debugging;
Serial.print("Debugging now: ");
Serial.println(Debugging);
}
if (data == "door") {
if(Debugging) {
Serial.println("remoteLockStart set");
}
if (doorState == "open") {
doorState = "closing";
remoteLockStart = millis();
}
else if (doorState == "closed") {
doorState = "opening";
remoteLockStart = millis();
}
}
}
// Adjust sunrise/set times for nightlock
if (strcmp(topic,sSunRise)==0) {
nightLockEnd = atoi(data.c_str());
if (Debugging) {
Serial.print("Night lock end updated to: ");
Serial.println(nightLockEnd);
}
}
if (strcmp(topic,sSunSet)==0) {
nightLockStart = atoi(data.c_str());
if (Debugging) {
Serial.print("Night lock start updated to: ");
Serial.println(nightLockStart);
}
}
// Sync RTC to time beacon once/day
if (strcmp(topic,sTime)==0) {
if (lastRTCSync == 0 || ((unsigned long)(millis() - lastRTCSync) > millisPerDay)) {
RTC.adjust(strtoul(data.c_str(), NULL, 0));
lastRTCSync = millis();
if (Debugging) {
now = RTC.now();
char dateStr[11];
char timeStr[9];
sprintf(dateStr, "%02d/%02d/%04d", now.month(), now.day(), now.year());
int hr = now.hour();
boolean ampm = false;
if (hr > 12) {
hr = hr - 12;
ampm = true;
}
else if (hr == 12) {
ampm = true;
}
else if (hr == 0) {
hr = 12;
}
sprintf(timeStr, "%02d:%02d:%02d", hr, now.minute(), now.second());
Serial.println("RTC Updated:");
Serial.print(dateStr);
Serial.print(" ");
Serial.print(timeStr);
if (ampm) {
Serial.println("pm");
}
else {
Serial.println("am");
}
}
}
}
}
/**
* Handle movement of the door
*/
void doorMove() {
if (doorState != "halted" ) {
if(motorRunning > 0) {
if (motorRunning + maxMotorOn < millis()){
digitalWrite(doorClose, STOP);
digitalWrite(doorOpen, STOP);
if (Debugging) {
Serial.println("Motor on too long - Halting!");
}
if (doorStatePrev != doorState && wifiConnected) {
mqtt.publish(pStatus, "door|runaway");
}
//motorHalted = 1;
doorState="halted";
}
}
doorStatePrev = doorState;
if (doorState == "closed" || doorState == "closing") {
if (doorBottomState != 0) {
// Door isn't closed, run motor until it is.
if(motorRunning == 0) { // start your engines
digitalWrite(doorClose, GO);
digitalWrite(doorOpen, STOP);
motorRunning = millis();
if (Debugging) {
Serial.printf("Motor CLOSE ON: %i\n", motorRunning);
}
}
}
else {
if (motorRunning > 0) {
// Door is closed, stop motor
digitalWrite(doorClose, STOP);
digitalWrite(doorOpen, STOP);
doorState = "closed";
motorRunning = 0; // stop the motor running counter
if (doorStatePrev != doorState && wifiConnected) {
mqtt.publish(pStatus, "door|closed");
}
if (Debugging) {
Serial.println("Motor CLOSE OFF");
}
}
}
}
if (doorState == "open" || doorState == "opening") {
if (doorTopState != 0) {
if(motorRunning == 0) { // start your engines
// Door isn't open, run motor until it is.
digitalWrite(doorClose, STOP);
digitalWrite(doorOpen, GO); motorRunning = millis();
if (Debugging) {
Serial.printf("Motor OPEN ON: %i \n",motorRunning);
}
}
}
else {
// Door is open, stop motor.
if (motorRunning > 0) {
digitalWrite(doorClose, STOP);
digitalWrite(doorOpen, STOP);
doorState = "open";
motorRunning = 0; // stop the motor running counter
if (doorStatePrev != doorState && wifiConnected) {
mqtt.publish(pStatus, "door|open");
}
if (Debugging) {
Serial.println("Motor OPEN OFF");
}
}
}
}
}
}
/**
* Read current sensor data
*/
void readSensors() {
if (lastLightRead == 0 || (unsigned long)millis() - lastLightRead > lightReadRate) {
// Read light sensor and convert to brightness percentage
brightness = analogRead(lightSense);
brightness = map(brightness, 0, 1023, 0, 100); // Remap value to a 0-100 scale
brightness = constrain(brightness, 0, 100); // constrain value to 0-100 scale
lastLightRead = millis();
char buf[100];
String pubString = String(brightness);
pubString.toCharArray(buf, pubString.length()+1);
if (wifiConnected) {
mqtt.publish(pLight, buf);
}
if (Debugging) {
Serial.print("MQTT State: ");
Serial.println(mqtt.state());
Serial.print("Wifi State: ");
Serial.println(WiFi.status());
}
if (Debugging) {
now = RTC.now();
Serial.printf("Time:%02d:%02d Light:%03d\n",now.hour(),now.minute(),brightness);
}
}
}
/**
* Respond to updated sensor data.
*/
void handleSensorReadings() {
// Light based reactions
// ---------------------
// Fetch current time from RTC
now = RTC.now();
// If nightlock is enabled, and we are within the designated time period, simply
// ensure door is closed.
//if(Debugging) {
// Serial.printf("Nightlock: %i, Time: %0d:%0d\n",nightLock, now.hour(),now.minute());
//}
if (nightLock && ( (now.hour() >= nightLockStart || now.hour() <= nightLockEnd)) ) {
// Close door if it is open
if (doorState == "open" || doorState == "unknown") {
if (Debugging) {
Serial.println("NIGHTLOCK ENABLED: Closing door.");
}
doorState = "closing";
if (wifiConnected) {
mqtt.publish(pStatus, "door|closing");
}
}
}
// Otherwise, handle brightness level based reactions
// NOTE: We need a bit of a gap between these thresholds to prevent
// bouncing if light readings fluctuate by a percentage or two.
else {
// Open door when brightness level is greater than 5%
if (brightness >= openBright) {
if (doorState == "closed" || doorState == "unknown") {
if (Debugging) {
Serial.println("Opening door.");
}
doorState = "opening";
if (wifiConnected) {
mqtt.publish(pStatus, "door|opening");
}
}
}
// Otherwise, close door when light level falls below 2%.
else if (brightness < closeBright) {
if (doorState == "open" || doorState == "unknown") {
if (Debugging) {
Serial.println("Closing door.");
}
doorState = "closing";
if (wifiConnected) {
mqtt.publish(pStatus, "door|closing");
}
}
}
}
}
int stringToNumber(String thisString) {
int i, value, length;
length = thisString.length();
char blah[(length + 1)];
for (i = 0; i < length; i++) {
blah[i] = thisString.charAt(i);
}
blah[i] = 0;
value = atoi(blah);
return value;
}
#ifdef LCD_DISPLAY
void lcdUpdate(){
// 1111111111
// 01234567890123456789
// +--------------------+
// |IP:xxx.xxx.xxx.xxx | 0
// |T:xxxx B:xxx | 1
// |D:xxxxxxxx L:x | 2
// |MQ:xx T:x B:x | 3
// +--------------------+
if (lastLcdUpdate == 0 || (unsigned long)millis() - lastLcdUpdate > lcdUpdateRate) {
lastLcdUpdate = millis();
lcd.setCursor(0,0);
int a1 = WiFi.localIP()[0];
int a2 = WiFi.localIP()[1];
int a3 = WiFi.localIP()[2];
int a4 = WiFi.localIP()[3];
snprintf(lcd_buf,20,"I:%03i.%03i.%03i.%03i ",a1,a2,a3,a4);
lcd.print(lcd_buf);
lcd.setCursor(0,1);
now = RTC.now();
snprintf(lcd_buf,20,"T:%02d%02d B:%03d",now.hour(),now.minute(),brightness);
lcd.print(lcd_buf);
lcd.setCursor(0,2);
String RLS;
RLS = "N";
if(remoteLockStart>0) {
RLS = "Y";
}
snprintf(lcd_buf,20,"D:%-8s L:%1s",doorState.c_str(),RLS.c_str());
lcd.print(lcd_buf);
lcd.setCursor(0,3);
int mqs = mqtt.state();
snprintf(lcd_buf,20,"MQ:%02i T:%1i B:%1i ",mqs,doorTopState,doorBottomState);
lcd.print(lcd_buf);
}
}
#endif
void WiFiConfig(int reset_config) {
//clean FS, for testing
//SPIFFS.format();
//read configuration from FS json
Serial.println("mounting FS...");
if (SPIFFS.begin()) {
Serial.println("mounted file system");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
Serial.println("\nparsed json");
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
} else {
Serial.println("failed to load json config");
}
}
}
} else {
Serial.println("failed to mount FS");
}
//end read
// The extra parameters to be configured (can be either global or just in the setup)
// After connecting, parameter.getValue() will get you the configured value
// id/name placeholder/prompt default length
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
//set static ip
//wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//add all your parameters here
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
//reset settings - for testing
if (reset_config) {
wifiManager.resetSettings();
}
//set minimu quality of signal so it ignores AP's under that quality
//defaults to 8%
//wifiManager.setMinimumSignalQuality();
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
//wifiManager.setTimeout(120);
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
json.printTo(Serial);
json.printTo(configFile);
configFile.close();
//end save
}
Serial.println("local ip");
Serial.println(WiFi.localIP());
}
/**
* Initialization on startup.
*/
void setup() {
if (Debugging) {
Serial.begin(115200);
Serial.println("Initialising...");
Serial.println("Setting motor status to STOP");
Serial.print("MQTT info: ");
Serial.println(pStatus);
}
#ifdef DEBUG_ESP_CORE
Serial.setDebugOutput(true);
#endif
digitalWrite(doorOpen, STOP); // Set the moto control relays
digitalWrite(doorClose, STOP);
pinMode(doorOpen, OUTPUT);
pinMode(doorClose, OUTPUT);
pinMode(TRIGGER_PIN, INPUT);
// Define the top & bottom sensors
pinMode(doorTop, INPUT_PULLUP);
debounceTop.attach(doorTop);
debounceTop.interval(5); //inteval in ms
pinMode(doorBottom, INPUT_PULLUP);
debounceBot.attach(doorBottom);
debounceBot.interval(5); //inteval in ms
// Again, just in case
digitalWrite(doorOpen, STOP);
digitalWrite(doorClose, STOP);
// Get the RTC going
Wire.begin(i2cSDA,i2cSCL);
#ifdef LCD_DISPLAY
lcd.init();
delay(500);
lcd.init();
lcd.backlight();
lcd.print("CoopTroller ");
lcd.print(CoopTrollerVersion);
lcd.setCursor(0,1);
lcd.print("2016 - Pablo Sanchez");
lcd.setCursor(0,2);
lcd.print("Compiled on:");
lcd.setCursor(0,3);
DateTime now = DateTime(__DATE__,__TIME__);
lcd.print(now.day(), DEC);
lcd.print('/');
lcd.print(now.month(), DEC);
lcd.print('/');
lcd.print(now.year(), DEC);
lcd.print(' ');
if (now.hour()<10)
lcd.print('0');
lcd.print(now.hour(), DEC);
lcd.print(':');
if (now.minute()<10)
lcd.print('0');
lcd.print(now.minute(), DEC);
lcd.print(':');
if (now.second()<10)
lcd.print('0');
lcd.print(now.second(), DEC);
delay(7000);
lcd.init();
#endif
// Set the outputs
if (! RTC.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
/* RTC_DS1307
if (! RTC.isrunning() ) {
//clockmode = NOT_SET;
if (Debugging) {
Serial.println("RTC is not running");
}
RTC.adjust(DateTime(__DATE__, __TIME__)); // try kick starting the clock with the compile time
}
*/
if (Debugging) {
now = RTC.now();
Serial.printf("RTC time is: %0d:%0d\n",now.hour(),now.minute());
}
if (Debugging) {
Serial.println("ARDUINO: Setup WIFI");
}
// Wifi Connect
//WiFi.disconnect();
//delay(200);
WiFiConfig(0);
//WiFi.begin(wHost, wPass);
//int wifitry = 60; // try for 30 seconds then move on
//while (WiFi.status() != WL_CONNECTED && wifitry >0 ) {
// delay(100);
// wifitry--;
// if (Debugging) {
// Serial.print(".");
// }
//}
if (WiFi.status() == WL_CONNECTED) {
wifiConnected = true;
if (Debugging) {
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
} else {
wifiConnected = false;
#ifdef LCD_DISPLAY
lcd.clear();
lcd.print("No WiFi");
#endif
if (Debugging) {
Serial.println("");
Serial.println("WiFi UNconnected");
}
}
if (Debugging) {
Serial.println("ARDUINO: Setup MQTT client");
Serial.print("Client|port: ");
Serial.print(mqtt_server);
Serial.print("|");
Serial.println(mqtt_port);
}
mqtt.setCallback(&mqttData);
mqtt.setServer(mqtt_server, stringToNumber(mqtt_port)); // client_id, port
mqtt.connect(mClientID);
delay(100);
if ( !mqtt.connected() ) {
mqtt.connect(mClientID);
delay(100);
}
if ( !mqtt.connected() ) {
if (Debugging) {
Serial.println("ARDUINO: Failed to setup MQTT");
}
}
if (Debugging) {
Serial.print("MQTT Status: ");
Serial.println(mqtt.state());
}
WiFi.onEvent(wifiCb);
mqttSubscribe();
// Findout door status
debounceTop.update();
debounceBot.update();
doorTopState = debounceTop.read();
doorBottomState = debounceBot.read();
switch (doorTopState + doorBottomState) {
case 0:
doorState = "broken";
if (Debugging) {
Serial.println("Door broken. Opened and closed simultaneously. Halting");
}
#ifdef LCD_DISPLAY
//lcd.setCursor(0,2);
//lcd.print("Door sensors Halting");
lcdUpdate();
#endif
if (wifiConnected) {
mqtt.publish(pStatus,"door|insane");
}
// Goto to the corner and stay there
while(1){
yield();
}
break;
case 1:
if(doorTopState==0){
doorState="open";
if (wifiConnected) {
mqtt.publish(pStatus, "door|open");
}
} else {
doorState="closed";
if (wifiConnected) {
mqtt.publish(pStatus, "door|closed");
}
}
break;
case 2:
doorState = "unknown";
if (wifiConnected) {
mqtt.publish(pStatus, "door|unknown");
}
break;
}
if (Debugging) {
Serial.print("Initial door state: ");
Serial.println(doorState);
}
// Port defaults to 8266 for OTA
ArduinoOTA.setPort(8266);
// Hostname defaults to esp8266-[ChipID]
// ArduinoOTA.setHostname("myesp8266");
// No authentication by default
//ArduinoOTA.setPassword((const char *)"123");
ArduinoOTA.onStart([]() {
Serial.println("Start");
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Basic OTA Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
/**
* Main program loop
*/
void loop() {
if (Debugging) {
Serial.println("Loop start");
}
ArduinoOTA.handle(); // Check for OTA activity
// See if user has requested a new WiFi config
if ( digitalRead(TRIGGER_PIN) == LOW ) {
//reset settings to allow a new WiFi connection
//WiFi.removeEvent(wifiCb);
WiFiConfig(1);
WiFi.onEvent(wifiCb);
}
// Update the LCD screen
#ifdef LCD_DISPLAY
if (Debugging) {
Serial.println("LCD Update");
}
lcdUpdate();
#endif
if (Debugging) {
Serial.println("MQTT Update");
}
// Reconnect MQTT if needed
if ( !mqtt.connected() ) {
mqtt.connect(mClientID);
if ( mqtt.connected() ) {
mqttSubscribe();
}
} else {
mqtt.loop(); // MQTT queue flush
}
debounceTop.update();
doorTopState = debounceTop.read();
debounceBot.update();
doorBottomState = debounceBot.read();
// Read new data from sensors
if (Debugging) {
Serial.println("Read Sensors");
} readSensors();
if (remoteLockStart == 0 || (unsigned long)(millis() - remoteLockStart) > remoteOverride) {
// Respond to sensor data
handleSensorReadings();
}
// Move the door as needed
if (Debugging) {
Serial.println("Door Move");
}
doorMove();
} |
package com.example.uptrend;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.os.Bundle;
import com.example.uptrend.Adapter.RatingProductAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import DataModel.Order;
public class rating_products extends AppCompatActivity {
RecyclerView productReview;
DatabaseReference orderRef;
FirebaseUser firebaseUser;
ArrayList<Order> orderArrayList;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating_products);
productReview=findViewById(R.id.productReview);
firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
displayProductReview(firebaseUser.getUid());
}
public void displayProductReview(String userId){
orderArrayList = new ArrayList<>();
orderRef = FirebaseDatabase.getInstance().getReference("Order");
Query userQuery = orderRef.orderByChild("userId").equalTo(userId);
userQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
HashSet<String> reviewedProducts = new HashSet<>(); // HashSet to keep track of reviewed product IDs
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Order order = dataSnapshot.getValue(Order.class);
if(order.getOrderStatus().equals("delivered")) {
// Check if the product ID has already been reviewed
if (!reviewedProducts.contains(order.getProductId())) {
orderArrayList.add(order);
reviewedProducts.add(order.getProductId());
}
}
}
// Reverse the orderArrayList
Collections.reverse(orderArrayList);
RatingProductAdapter ratingProductAdapter = new RatingProductAdapter(rating_products.this, orderArrayList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(rating_products.this, LinearLayoutManager.VERTICAL, false);
productReview.setLayoutManager(linearLayoutManager);
productReview.setAdapter(ratingProductAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// Handle onCancelled event
}
});
}
// public void displayProductReview(String userId){
// orderArrayList=new ArrayList<>();
// orderRef= FirebaseDatabase.getInstance().getReference("Order");
// Query userQuery=orderRef.orderByChild("userId").equalTo(userId);
// userQuery.addValueEventListener(new ValueEventListener() {
// @Override
// public void onDataChange(@NonNull DataSnapshot snapshot) {
// for(DataSnapshot dataSnapshot:snapshot.getChildren()){
// Order order=dataSnapshot.getValue(Order.class);
// if(order.getOrderStatus().equals("delivered")){
// orderArrayList.add(order);
// }
// }
// RatingProductAdapter ratingProductAdapter=new RatingProductAdapter(rating_products.this,orderArrayList);
// LinearLayoutManager linearLayoutManager=new LinearLayoutManager(rating_products.this,LinearLayoutManager.VERTICAL,false);
// productReview.setLayoutManager(linearLayoutManager);
// productReview.setAdapter(ratingProductAdapter);
//
// }
//
// @Override
// public void onCancelled(@NonNull DatabaseError error) {
//
// }
// });
// }
} |
package dev.marco.example.springboot.rest;
import dev.marco.example.springboot.exception.*;
import dev.marco.example.springboot.model.Dashboard;
import dev.marco.example.springboot.service.DashboardService;
import dev.marco.example.springboot.util.ApiAddresses;
import dev.marco.example.springboot.util.ControllerUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import java.math.BigInteger;
import java.util.Properties;
@RestController
public class DashboardController implements ApiAddresses {
private final DashboardService dashboardService;
private static final Logger log = Logger.getLogger(DashboardController.class);
private final Properties properties = new Properties();
@Autowired
public DashboardController(DashboardService dashboardService) {
this.dashboardService = dashboardService;
try {
ControllerUtil.getProperty(properties);
} catch (ControllerConfigException e) {
log.error(e.getMessage());
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, properties.getProperty(CONFIG_EXCEPTION));
}
}
public void setTestConnection() throws DAOConfigException {
dashboardService.setTestConnection();
}
@GetMapping(API_GENERATE_DASHBOARD)
public Dashboard generateDashboard(@PathVariable BigInteger id) {
try {
return dashboardService.generateDashboard(id);
} catch (DAOLogicException e) {
log.error(MessagesForException.DAO_LOGIC_EXCEPTION);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
} catch (QuizDoesNotExistException e) {
log.error(MessagesForException.MESSAGE_ERROR);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
} catch (UserDoesNotExistException e) {
log.error(MessagesForException.USER_NOT_FOUND_EXCEPTION);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
} catch (AnnouncementDoesNotExistException | AnnouncementException e) {
log.error(MessagesForException.ANNOUNCEMENT_NOT_FOUND_EXCEPTION);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
}
}
} |
import { Observable, ReplaySubject, tap } from 'rxjs';
import { ApiService } from './../../core/services/api/api.service';
import { Injectable } from '@angular/core';
import { User } from 'src/app/shared/models/user.model';
@Injectable({
providedIn: 'root',
})
export class AccountService {
readonly apiUrl: string = 'api/account';
private currentUserSource = new ReplaySubject<User>(1);
currentUser$ = this.currentUserSource.asObservable();
constructor(private apiService: ApiService) {}
login(username: string, password: string): Observable<User> {
return this.apiService
.post<User>(`${this.apiUrl}/login`, {
username,
password,
})
.pipe(
tap((user) => {
if (user) {
this.setCurrentUserToLocalStorage(user);
}
})
);
}
register(model: any): Observable<User> {
return this.apiService.post<User>(`${this.apiUrl}/register`, model).pipe(
tap((user: User) => {
if (user) {
this.setCurrentUserToLocalStorage(user);
}
})
);
}
logout(): void {
localStorage.removeItem('user');
this.currentUserSource.next(null);
}
setCurrentUserFromLocalStorage() {
const user: User = JSON.parse(localStorage.getItem('user'));
this.currentUserSource.next(user);
}
setCurrentUserToLocalStorage(user: User) {
this.currentUserSource.next(user);
localStorage.setItem('user', JSON.stringify(user));
}
} |
import React, { Component } from 'react'
export default class Item extends Component {
constructor() {
super();
this.state={
inEdit:false
}
this.myInput=React.createRef();
}
//更改Item组件自身状态值this.state.inEdit
changeInEdit=()=>{
let {todo} = this.props;
//this.state状态更新后,执行的匿名回调函数
this.setState({inEdit:true},()=>{
this.myInput.current.value=todo.title;//文本框显示todo.title
this.myInput.current.focus();//原生 js模拟触发
})
}
render() {
let {todo,delTodo,changeHasCompleted,editTodo}=this.props;
let {inEdit} = this.state;
let completed=todo.hasCompleted?"completed":"";
let classes=inEdit?completed+" editing":completed;
return (
<li className={classes}>
<div className="view">
<input type="checkbox" className="toggle"
onChange={()=>changeHasCompleted(todo)}
checked={todo.hasCompleted}
/>
<label onDoubleClick={this.changeInEdit}>{todo.title}</label>
<button className="destroy"
onClick={()=>delTodo(todo)}
></button>
</div>
<input type="text" className="edit" ref={this.myInput}
//如何在react进行事件解绑
onBlur={inEdit?()=>{
console.log("onBlur");
//已经把文本框里面的字符串存储到当前todo.title中了
todo.title=this.myInput.current.value.trim();
editTodo(todo);
this.setState({inEdit:false});
}:null
}
onKeyUp={event=>{
if(event.key==="Enter"){
console.log("Enter")
todo.title=this.myInput.current.value.trim();
editTodo(todo);
this.setState({inEdit:false});
}
if(event.key==="Escape"){
console.log("ESC");
this.setState({inEdit:false});
}
}
}
/>
</li>
)
}
} |
package practice;
import java.util.ArrayList;
class Util
{
static void sleep(long millis)
{
try
{
Thread.sleep(millis);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
class CommonTaskThread extends Thread
{
@Override
public void run()
{
while(true)
{
synchronized (this)
{
try
{
this.wait();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
for(int i = 1; i <= 10; i++)
{
System.out.println(i + "by" + Thread.currentThread().getName());
Util.sleep(100);
}
synchronized (this) {
this.notify();
}
}
}
}
class ThreadPoolManager
{
private ArrayList<CommonTaskThread> pool = new ArrayList<CommonTaskThread>();
public void init()
{
CommonTaskThread ct = null;
for(int i = 1; i <= 10; i++)
{
ct = new CommonTaskThread();
ct.start();
pool.add(ct);
}
}
public CommonTaskThread checkOut()
{
CommonTaskThread ct = null;
if(pool.size() > 0)
{
ct = pool.remove(0);
}
else
{
ct = new CommonTaskThread();
ct.start();
}
return ct;
}
public void checkIn(CommonTaskThread ct)
{
if(pool.size() < 10)
{
pool.add(ct);
}
else
{
ct = null;
}
}
public void release()
{
CommonTaskThread ct = null;
for(int i=0; i<pool.size();)
{
ct = pool.remove(0);
ct = null;
}
pool = null;
}
}
class Customer1 extends Thread
{
private ThreadPoolManager tpm;
Customer1(ThreadPoolManager tpm)
{
this.tpm = tpm;
}
@Override
public void run() {
while(true)
{
System.out.println("Customer is trying to get a thread from the pool");
CommonTaskThread ct = tpm.checkOut();
synchronized (ct) {
ct.notify();
}
synchronized (ct) {
try {
ct.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("customer is sending used thread back to pool");
tpm.checkIn(ct);
Util.sleep(10000);
}
}
}
class Customer2 extends Thread
{
private ThreadPoolManager tpm;
Customer2(ThreadPoolManager tpm)
{
this.tpm = tpm;
}
@Override
public void run() {
while(true)
{
System.out.println("Customer is trying to get a thread from the pool");
CommonTaskThread ct = tpm.checkOut();
synchronized (ct) {
ct.notify();
}
synchronized (ct) {
try {
ct.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("customer is sending used thread back to pool");
tpm.checkIn(ct);
Util.sleep(10000);
}
}
}
class Customer3 extends Thread
{
private ThreadPoolManager tpm;
Customer3(ThreadPoolManager tpm)
{
this.tpm = tpm;
}
@Override
public void run() {
while(true)
{
System.out.println("Customer is trying to get a thread from the pool");
CommonTaskThread ct = tpm.checkOut();
synchronized (ct) {
ct.notify();
}
synchronized (ct) {
try {
ct.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("customer is sending used thread back to pool");
tpm.checkIn(ct);
Util.sleep(10000);
}
}
}
public class N2_thread_pool {
public static void main(String[] args) throws InterruptedException {
ThreadPoolManager tpm = new ThreadPoolManager();
tpm.init();
Customer1 c1 = new Customer1(tpm);
c1.start();
Customer2 c2 = new Customer2(tpm);
c2.start();
Customer3 c3 = new Customer3(tpm);
c3.start();
// Thread.sleep(2*10000);
// Util.sleep(3*10000);
Util.sleep(5000);
Util.sleep(5000);
// Util.sleep(10000);
c1.stop();
c2.stop();
c3.stop();
tpm.release();
System.out.println("end of thread pool");
}
} |
/* Copyright (C) 2011 [Gobierno de Espana]
* This file is part of "Cliente @Firma".
* "Cliente @Firma" is free software; you can redistribute it and/or modify it under the terms of:
* - the GNU General Public License as published by the Free Software Foundation;
* either version 2 of the License, or (at your option) any later version.
* - or The European Software License; either version 1.1 or (at your option) any later version.
* You may contact the copyright holder at: soporte.afirma@seap.minhap.es
*/
package es.gob.afirma.core.misc.protocol;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import es.gob.afirma.core.misc.SecureXmlBuilder;
/** Utilidades para en análisis de URL de invocación por protocolo. */
public final class ProtocolInvocationUriParserUtil {
static final String DEFAULT_URL_ENCODING = StandardCharsets.UTF_8.name();
private static final String DEFAULT_OPERATION = "SIGN"; //$NON-NLS-1$
private ProtocolInvocationUriParserUtil() {
// No instanciable
}
/** Recupera los parámetros necesarios para la configuración de una
* operación de guardado de datos en el dispositivo. Si falta algún parámetro o
* es erróneo se lanzará una excepción.
* @param params Parámetros de con la configuración de la operación.
* @return Parámetros
* @throws ParameterException Si algún parámetro proporcionado es incorrecto. */
public static UrlParametersToSave getParametersToSave(final Map<String, String> params) throws ParameterException {
final UrlParametersToSave ret = new UrlParametersToSave();
ret.setCommonParameters(params);
ret.setSaveParameters(params);
return ret;
}
/** Recupera los parámetros necesarios para la configuración de una
* operación de firma de lote. Si falta algún parámetro o
* es erróneo se lanzará una excepción.
* @param params Parámetros de con la configuración de la operación.
* @return Parámetros
* @throws ParameterException Si algún parámetro proporcionado es incorrecto. */
public static UrlParametersForBatch getParametersToBatch(final Map<String, String> params) throws ParameterException {
final UrlParametersForBatch ret = new UrlParametersForBatch();
ret.setCommonParameters(params);
ret.setBatchParameters(params);
return ret;
}
/** Recupera los parámetros necesarios para la configuración de una
* operación de carga de datos. Si falta algún parámetro o
* es erróneo se lanzará una excepción.
* @param params Parámetros de con la configuración de la operación.
* @return Parámetros
* @throws ParameterException Si algún parámetro proporcionado es incorrecto. */
public static UrlParametersToLoad getParametersToLoad(final Map<String, String> params) throws ParameterException {
final UrlParametersToLoad ret = new UrlParametersToLoad();
ret.setCommonParameters(params);
ret.setLoadParameters(params);
return ret;
}
/** Recupera los parámetros necesarios para la configuración de una
* operación de obtención del log actual de la aplicación
* @param params Parámetros de con la configuración de la operación.
* @return Parámetros
* @throws ParameterException Si algún parámetro proporcionado es incorrecto. */
public static UrlParametersToGetCurrentLog getParametersToGetCurrentLog(final Map<String, String> params) throws ParameterException {
final UrlParametersToGetCurrentLog ret = new UrlParametersToGetCurrentLog();
ret.setCommonParameters(params);
ret.setGetCurrentLogParameters(params);
return ret;
}
/** Analiza un XML de entrada para obtener la lista de parámetros asociados
* @param xml XML con el listado de parámetros.
* @return Devuelve una tabla <i>hash</i> con cada parámetro asociado a un valor
* @throws ParameterException Cuando el XML de entrada no es v´lido. */
public static Map<String, String> parseXml(final byte[] xml) throws ParameterException {
final Map<String, String> params = new HashMap<>();
final NodeList elems;
try {
final Element docElement = SecureXmlBuilder.getSecureDocumentBuilder()
.parse(new ByteArrayInputStream(xml)).getDocumentElement();
// Si el elemento principal es OPERATION_PARAM entendemos que es una firma
params.put(
ProtocolConstants.OPERATION_PARAM,
ProtocolConstants.OPERATION_PARAM.equalsIgnoreCase(docElement.getNodeName())
? DEFAULT_OPERATION : docElement.getNodeName());
elems = docElement.getChildNodes();
}
catch (final Exception e) {
throw new ParameterException("Error grave durante el analisis del XML: " + e, e); //$NON-NLS-1$
}
for (int i = 0; i < elems.getLength(); i++) {
final Node element = elems.item(i);
if (!"e".equals(element.getNodeName())) { //$NON-NLS-1$
throw new ParameterException("El XML no tiene la forma esperada"); //$NON-NLS-1$
}
final NamedNodeMap attrs = element.getAttributes();
final Node keyNode = attrs.getNamedItem("k"); //$NON-NLS-1$
final Node valueNode = attrs.getNamedItem("v"); //$NON-NLS-1$
if (keyNode == null || valueNode == null) {
throw new ParameterException("El XML no tiene la forma esperada"); //$NON-NLS-1$
}
try {
params.put(keyNode.getNodeValue(), URLDecoder.decode(valueNode.getNodeValue(), DEFAULT_URL_ENCODING));
}
catch (final UnsupportedEncodingException e) {
Logger.getLogger("es.gob.afirma").warning("Codificacion no soportada para la URL (" + DEFAULT_URL_ENCODING + "): " + e); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
params.put(keyNode.getNodeValue(), valueNode.getNodeValue());
}
}
return params;
}
/** Comprueba que estén disponibles todos los parametros disponibles en la entrada de
* datos para la operación de firma.
* @param params Parámetros para el proceso de firma.
* @return Parámetros para la operación de firma.
* @throws ParameterException Si algún parámetro proporcionado es incorrecto. */
public static UrlParametersToSign getParametersToSign(final Map<String, String> params) throws ParameterException {
final UrlParametersToSign ret = new UrlParametersToSign();
ret.setCommonParameters(params);
ret.setSignParameters(params);
ret.setAnotherParams(params);
return ret;
}
/** Comprueba que estén disponibles todos los parametros disponibles en la entrada de
* datos para la operación de firma.
* @param params Parámetros para el proceso de firma.
* @return Parámetros para la operación de firma y guardado.
* @throws ParameterException Si algún parámetro proporcionado es incorrecto. */
public static UrlParametersToSignAndSave getParametersToSignAndSave(final Map<String, String> params) throws ParameterException {
final UrlParametersToSignAndSave ret = new UrlParametersToSignAndSave();
ret.setCommonParameters(params);
ret.setSignAndSaveParameters(params);
return ret;
}
/** Comprueba que estén disponibles todos los parametros disponibles en la entrada de
* datos para la operación de selección de certificado.
* @param params Parámetros para el proceso de firma
* @return Parámetros para la operación de selección de certificado.
* @throws ParameterException Si algún parámetro proporcionado es incorrecto. */
public static UrlParametersToSelectCert getParametersToSelectCert(final Map<String, String> params) throws ParameterException {
final UrlParametersToSelectCert ret = new UrlParametersToSelectCert();
ret.setCommonParameters(params);
ret.setSelectCertParameters(params);
return ret;
}
} |
pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (v2/strategies/TempleTokenBaseStrategy.sol)
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ITempleBaseStrategy } from "contracts/interfaces/v2/strategies/ITempleBaseStrategy.sol";
import { AbstractStrategy } from "contracts/v2/strategies/AbstractStrategy.sol";
import { CommonEventsAndErrors } from "contracts/common/CommonEventsAndErrors.sol";
import { ITempleERC20Token } from "contracts/interfaces/core/ITempleERC20Token.sol";
/**
* @title Temple Token Base Strategy
* @notice Temple is directly minted and burned in order to provide for strategies.
*/
contract TempleTokenBaseStrategy is AbstractStrategy, ITempleBaseStrategy {
using SafeERC20 for ITempleERC20Token;
string private constant VERSION = "1.0.0";
/**
* @notice The Temple token which is directly minted/burned.
*/
ITempleERC20Token public immutable templeToken;
event TempleMinted(uint256 amount);
event TempleBurned(uint256 amount);
constructor(
address _initialRescuer,
address _initialExecutor,
string memory _strategyName,
address _treasuryReservesVault,
address _templeToken
) AbstractStrategy(_initialRescuer, _initialExecutor, _strategyName, _treasuryReservesVault) {
templeToken = ITempleERC20Token(_templeToken);
}
/**
* @notice A hook where strategies can optionally update approvals when the trv is updated
*/
function _updateTrvApprovals(
address oldTrv,
address newTrv
) internal override
// solhint-disable-next-line no-empty-blocks
{
// No approvals required since it is a direct mint/burn
}
/**
* The version of this particular strategy
*/
function strategyVersion() external override pure returns (string memory) {
return VERSION;
}
/**
* @notice The base strategy can pull any idle Temple from the TRV and burn them.
*/
function borrowAndDeposit(uint256 amount) external override onlyElevatedAccess {
treasuryReservesVault.borrow(templeToken, amount, address(this));
emit TempleBurned(amount);
templeToken.burn(amount);
}
/**
* @notice The latest checkpoint of each asset balance this strategy holds, and the current debt.
* This will be used to report equity performance: `sum(asset value in STABLE) - debt`
* The conversion of each asset price into the stable token (eg DAI) will be done off-chain
*
* @dev The asset value may be stale at any point in time, depending on the strategy.
* It may optionally implement `checkpointAssetBalances()` in order to update those balances.
*/
function latestAssetBalances() public override(AbstractStrategy, ITempleBaseStrategy) view returns (
AssetBalance[] memory assetBalances
) {
// Since we always mint/burn on demand, the balance is always zero.
// TreasuryReservesVault::totalAvailable depends on the first asset with base strategies.
assetBalances = new AssetBalance[](1);
assetBalances[0] = AssetBalance({
asset: address(templeToken),
balance: 0
});
}
/**
* @notice The TRV sends the tokens to deposit (and also mints equivalent dTokens)
* @dev For Temple, we just burn the tokens out of circulating supply
*/
function trvDeposit(uint256 amount) external override {
if (msg.sender != address(treasuryReservesVault)) revert OnlyTreasuryReserveVault(msg.sender);
if (amount == 0) revert CommonEventsAndErrors.ExpectedNonZero();
emit TempleBurned(amount);
templeToken.burn(amount);
}
/**
* @notice The TRV is able to withdraw on demand in order to fund other strategies which
* wish to borrow from the TRV.
* @dev For Temple, we just mint the tokens.
*/
function trvWithdraw(uint256 requestedAmount) external override returns (uint256) {
address _trvAddr = address(treasuryReservesVault);
if (msg.sender != _trvAddr) revert OnlyTreasuryReserveVault(msg.sender);
if (requestedAmount == 0) revert CommonEventsAndErrors.ExpectedNonZero();
emit TempleMinted(requestedAmount);
templeToken.mint(_trvAddr, requestedAmount);
return requestedAmount;
}
/**
* @notice The strategy executor can shutdown this strategy, only after Governance has
* marked the strategy as `isShuttingDown` in the TRV.
* This should handle all liquidations and send all funds back to the TRV, and will then call `TRV.shutdown()`
* to apply the shutdown.
* @dev Each strategy may require a different set of params to do the shutdown. It can abi encode/decode
* that data off chain, or by first calling populateShutdownData()
* Shutdown data isn't required for a DSR automated shutdown.
*/
function _doShutdown(bytes calldata /*data*/) internal pure override {
revert CommonEventsAndErrors.Unimplemented();
}
} |
import unittest
from trees.CheckCompletenessOfABinaryTree import is_complete_tree
from trees.TreeNode import TreeNode
class MyTestCase(unittest.TestCase):
def test_is_complete_tree(self):
root = TreeNode(
val=1,
left=TreeNode(
val=2,
left=TreeNode(4),
right=TreeNode(5)
),
right=TreeNode(
val=3,
left=TreeNode(6)
)
)
self.assertEqual(True, is_complete_tree(self, root))
def test_is_complete_tree_1(self):
root = TreeNode(
val=1,
left=TreeNode(
val=2,
left=TreeNode(4),
right=TreeNode(5)
),
right=TreeNode(
val=3,
right=TreeNode(7)
)
)
self.assertEqual(False, is_complete_tree(self, root))
if __name__ == '__main__':
unittest.main() |
/* global $STM_Config */
import { isDefaultImageSize, defaultSrcSet } from 'app/utils/ProxifyUrl';
import { getPhishingWarningMessage, getExternalLinkWarningMessage } from 'shared/HtmlReady'; // the only allowable title attributes for div and a tags
import { validateIframeUrl as validateEmbbeddedPlayerIframeUrl } from 'app/components/elements/EmbeddedPlayers';
export const noImageText = '(Image not shown due to low ratings)';
export const allowedTags = `
div, iframe, del,
a, p, b, i, q, br, ul, li, ol, img, h1, h2, h3, h4, h5, h6, hr,
blockquote, pre, code, em, strong, center, table, thead, tbody, tr, th, td,
strike, sup, sub, span, details, summary
`
.trim()
.split(/,\s*/);
// Medium insert plugin uses: div, figure, figcaption, iframe
export default ({
large = true, highQualityPost = true, noImage = false, sanitizeErrors = []
}) => ({
allowedTags,
// figure, figcaption,
// SEE https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
allowedAttributes: {
// "src" MUST pass a whitelist (below)
iframe: [
'src',
'width',
'height',
'frameborder',
'allowfullscreen',
'webkitallowfullscreen',
'mozallowfullscreen',
'sandbox',
'class',
],
// class attribute is strictly whitelisted (below)
// and title is only set in the case of a phishing warning
div: ['class', 'title'],
// style is subject to attack, filtering more below
td: ['style'],
th: ['style'],
img: ['src', 'srcset', 'alt', 'class'],
// title is only set in the case of an external link warning
a: ['href', 'rel', 'title', 'class', 'target', 'id'],
span: ['data-bg', 'style'],
},
allowedSchemes: ['http', 'https', 'steem', 'esteem'],
transformTags: {
iframe: (tagName, attribs) => {
const srcAtty = attribs.src;
const widthAtty = attribs.width;
const heightAtty = attribs.height;
const {
validUrl,
useSandbox,
sandboxAttributes,
width,
height,
providerId,
} = validateEmbbeddedPlayerIframeUrl(srcAtty, large, widthAtty, heightAtty);
if (validUrl !== false) {
const iframe = {
tagName: 'iframe',
attribs: {
frameborder: '0',
allowfullscreen: 'allowfullscreen',
webkitallowfullscreen: 'webkitallowfullscreen', // deprecated but required for vimeo : https://vimeo.com/forums/help/topic:278181
mozallowfullscreen: 'mozallowfullscreen', // deprecated but required for vimeo
src: validUrl,
width,
height,
class: `${providerId}-iframe`,
},
};
if (useSandbox) {
if (sandboxAttributes.length > 0) {
iframe.attribs.sandbox = sandboxAttributes.join(' ');
} else {
iframe.attribs.sandbox = true;
}
}
return iframe;
}
console.log('Blocked, did not match iframe "src" white list urls:', tagName, attribs);
sanitizeErrors.push('Invalid iframe URL: ' + srcAtty);
return { tagName: 'div', text: `(Unsupported ${srcAtty})` };
},
img: (tagName, attribs) => {
if (noImage) return { tagName: 'div', text: noImageText };
//See https://github.com/punkave/sanitize-html/issues/117
let { src } = attribs;
const { alt } = attribs;
if (!/^(https?:)?\/\//i.test(src)) {
console.log('Blocked, image tag src does not appear to be a url', tagName, attribs);
sanitizeErrors.push('An image in this post did not save properly.');
return { tagName: 'img', attribs: { src: 'brokenimg.jpg' } };
}
// replace http:// with // to force https when needed
src = src.replace(/^http:\/\//i, '//');
const atts = { src };
if (alt && alt !== '') atts.alt = alt;
if (isDefaultImageSize(src)) {
atts.srcset = defaultSrcSet(src);
}
return { tagName, attribs: atts };
},
div: (tagName, attribs) => {
const attys = {};
const classWhitelist = [
'pull-right',
'pull-left',
'text-justify',
'text-rtl',
'text-center',
'text-right',
'videoWrapper',
'iframeWrapper',
'redditWrapper',
'tweetWrapper',
'phishy',
'table-responsive',
];
const validClass = classWhitelist.find((e) => attribs.class == e);
if (validClass) attys.class = validClass;
if (validClass === 'phishy' && attribs.title === getPhishingWarningMessage()) attys.title = attribs.title;
return {
tagName,
attribs: attys,
};
},
th: (tagName, attribs) => {
const attys = {};
const allowedStyles = ['text-align:right', 'text-align:left', 'text-align:center'];
if (allowedStyles.indexOf(attribs.style) !== -1) {
attys.style = attribs.style;
}
return {
tagName,
attribs: attys,
};
},
td: (tagName, attribs) => {
const attys = {};
const allowedStyles = ['text-align:right', 'text-align:left', 'text-align:center'];
if (allowedStyles.indexOf(attribs.style) !== -1) {
attys.style = attribs.style;
}
return {
tagName,
attribs: attys,
};
},
a: (tagName, attribs) => {
let { href } = attribs;
if (!href) href = '#';
href = href.trim();
const attys = {
...attribs,
href
};
// If it's not a (relative or absolute) hive URL...
if (
!href.match(`^(/(?!/)|${$STM_Config.img_proxy_prefix})`)
&& !href.match(`^(/(?!/)|https://${$STM_Config.site_domain})`)
) {
attys.target = '_blank';
attys.rel = highQualityPost ? 'noreferrer noopener' : 'nofollow noreferrer noopener';
attys.title = getExternalLinkWarningMessage();
attys.class = 'external_link';
}
return {
tagName,
attribs: attys,
};
},
span: (tagName, attribs) => {
const data = {
tagName,
attribs: {
...(('data-bg' in attribs) ? {
style: `background-image: url(${attribs['data-bg']})`,
} : {}),
},
};
return data;
}
},
}); |
import { Button, Select, Table } from "antd";
import { useEffect } from "react";
import { ImEye } from "react-icons/im";
import { IoTrashOutline } from "react-icons/io5";
import { RiEditLine } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import { getEnquiries } from "../../features/enquiry/enquirySlice";
const columns = [
{
title: "SL",
dataIndex: "key",
sorter: (a, b) => a.key - b.key,
width: "80px",
align: "center",
},
{
title: "Name",
dataIndex: "name",
},
Table.EXPAND_COLUMN,
{
title: "Email",
dataIndex: "email",
},
{
title: "Mobile",
dataIndex: "mobile",
},
{
title: "Status",
dataIndex: "status",
},
{
title: "Action",
dataIndex: "action",
align: "right",
width: "100px",
},
];
const Enquires = () => {
const dispatch = useDispatch();
useEffect(() => {
document.title = "Enquires - Admin";
dispatch(getEnquiries());
}, [dispatch]);
const enquiryState = useSelector((state) => state.enquiry.enquiries);
const handleChange = (value) => {
console.log(value);
};
const statusOptions = [
{
value: "submitted",
label: "Submitted",
},
{
value: "in-progress",
label: "In Progress",
},
{
value: "resolved",
label: "Resolved",
},
];
const data = [];
enquiryState.forEach((enquiry, index) => {
data.push({
key: index + 1,
name: enquiry.name,
email: enquiry.email,
mobile: enquiry.mobile,
comment: enquiry.comment,
status: (
<Select
labelInValue
defaultValue={{ value: enquiry.status, label: enquiry.status }}
style={{ width: 150 }}
onChange={handleChange}
options={statusOptions}
/>
),
action: (
<div className="d-flex gap-1 justify-content-end align-items-center ">
<Button
type="primary"
shape="circle"
className="d-flex justify-content-center align-items-center"
icon={<ImEye style={{ width: "20px" }} />}
/>
<Link to={`/admin/products/${enquiry._id}`}>
<Button
type="primary"
shape="circle"
className="d-flex justify-content-center align-items-center bg-info"
icon={<RiEditLine style={{ width: "20px" }} />}
/>
</Link>
<Button
type="primary"
shape="circle"
className="d-flex justify-content-center align-items-center bg-danger"
icon={<IoTrashOutline style={{ width: "20px" }} />}
/>
</div>
),
});
});
return (
<>
<h3 className="mb-4 title">Enquires</h3>
<Table
columns={columns}
expandable={{
expandedRowRender: (enquiry) => (
<p
style={{
margin: 0,
}}
>
{enquiry.comment}
</p>
),
rowExpandable: (record) => record.name !== "Not Expandable",
}}
dataSource={data}
/>
</>
);
};
export default Enquires; |
/* Copyright (C) 2024, Manuel Meitinger
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useLiveQuery } from "dexie-react-hooks";
import React, { useMemo } from "react";
import { ButtonGroup, Card, Col, Form, Row, Table } from "react-bootstrap";
import { useAuth } from "./auth";
import {
CenteredSpinner,
DialogButton,
InlineSpinner,
SpinnerRow,
} from "./common";
import { Database, Product, Storage } from "./db";
import {
Dialog,
ObjectDeleteDialog,
ObjectDialog,
ObjectPermissionDialog,
} from "./dialog";
import { CheckboxInput, PermissionInput, TextInput } from "./form";
import { Globals } from "./globals";
import { ProductList } from "./product";
import { StockInput } from "./stock";
import { useStrings } from "./strings";
const PermissionDialog: React.FC<{ storage?: Storage }> = ({ storage }) => {
const strings = useStrings();
return (
<ObjectPermissionDialog api="storagePermission" object={storage} size="lg">
<Row>
<Col>
<Form.Check
type="switch"
checked={true}
label={strings.label.listStoragePermission}
disabled={true}
/>
</Col>
<Col>
<PermissionInput
name="stock"
label={strings.label.stockStoragePermission}
/>
</Col>
</Row>
</ObjectPermissionDialog>
);
};
const PermissionDialogButton: React.FC<{ storage?: Storage }> = ({
storage,
}) => {
const strings = useStrings();
const count = useLiveQuery(
async () =>
await Database.instance.storagePermission
.where("storageId")
.equals(storage === undefined ? "*" : storage.id)
.count(),
[storage]
);
return (
<DialogButton
variant="secondary"
open={<PermissionDialog storage={storage} />}
>
{storage === undefined
? strings.button.globalPermissions
: strings.button.permissions}
<> ({count ?? <InlineSpinner />})</>
</DialogButton>
);
};
const ProductCount: React.FC<{ storageId: string }> = ({ storageId }) => {
const count = useLiveQuery(
async () =>
await Database.instance.stock
.where("storageId")
.equals(storageId)
.count(),
[storageId]
);
return <>{count ?? <InlineSpinner />}</>;
};
const StockDialog: React.FC<{
storage: Storage;
readOnly?: boolean;
}> = ({ storage, readOnly }) => {
const strings = useStrings();
const productIds = useLiveQuery(
async () =>
Object.freeze(
await Database.instance.stock
.where("storageId")
.equals(storage.id)
.toArray((stock) => stock.map((e) => e.productId))
),
[storage.id]
);
return (
<Dialog title={strings.title.storageStockDialog(storage)} size="xl">
{productIds === undefined ? (
<CenteredSpinner />
) : (
<ProductList ids={productIds} storage={storage} readOnly={readOnly} />
)}
</Dialog>
);
};
const StorageDialog: React.FC<{
method: "PUT" | "POST";
template: Storage;
}> = ({ method, template }) => (
<ObjectDialog template={template} api="storage" method={method}>
<TextInput name="name" maxLength={255} required />
<CheckboxInput name="active" />
</ObjectDialog>
);
export const StorageList: React.FC<{ product?: Product }> = ({ product }) => {
const strings = useStrings();
const { userId, isAdmin } = useAuth();
const allStorages = useLiveQuery(
async () =>
Object.freeze(
(await Database.instance.storage.toArray()).sort((a, b) =>
strings.collator.compare(a.name, b.name)
)
),
[strings]
);
const permittedIds = useLiveQuery(async () => {
const result = new Map<string, boolean>();
await Database.instance.storagePermission
.where("userId")
.equals(userId)
.each((perm) => result.set(perm.storageId, perm.stock));
return Object.freeze(result);
}, [userId]);
const storages = useMemo(
() =>
product === undefined && isAdmin
? allStorages
: permittedIds === undefined || allStorages === undefined
? undefined
: Object.freeze(
allStorages.filter(
(storage) =>
(storage.active || isAdmin) &&
(permittedIds.has("*") || permittedIds.has(storage.id))
)
),
[product, isAdmin, allStorages, permittedIds]
);
return (
<Table bordered hover responsive>
<thead>
<tr>
<th>{strings.column.name}</th>
<th>
{product === undefined
? strings.column.productCount
: strings.column.stock}
</th>
{product === undefined && <th>{strings.column.manage}</th>}
</tr>
</thead>
<tbody>
{storages === undefined || permittedIds === undefined ? (
<SpinnerRow colSpan={2 + (product === undefined ? 1 : 0)} />
) : (
storages.map((storage) => (
<StorageRow
key={storage.id}
readOnly={
!(permittedIds?.get("*") || permittedIds?.get(storage.id))
}
storage={storage}
product={product}
/>
))
)}
</tbody>
</Table>
);
};
const StorageRow: React.FC<{
readOnly?: boolean;
storage: Storage;
product?: Product;
}> = ({ readOnly, storage, product }) => {
const strings = useStrings();
const { isAdmin } = useAuth();
const className = storage.active ? undefined : "text-muted";
return (
<tr>
<td className={className}>{storage.name}</td>
<td className={className}>
{product === undefined && <ProductCount storageId={storage.id} />}
{product !== undefined && (
<StockInput readOnly={readOnly} storage={storage} product={product} />
)}
</td>
{product === undefined && (
<td>
<ButtonGroup>
<DialogButton
variant="primary"
open={<StockDialog storage={storage} readOnly={readOnly} />}
>
{strings.button.stock}
</DialogButton>
{isAdmin && (
<>
<DialogButton
variant="secondary"
open={<StorageDialog method="POST" template={storage} />}
>
{strings.button.modify}
</DialogButton>
<PermissionDialogButton storage={storage} />
<DialogButton
variant="danger"
open={<ObjectDeleteDialog api="storage" object={storage} />}
>
{strings.button.delete}
</DialogButton>
</>
)}
</ButtonGroup>
</td>
)}
</tr>
);
};
export const Storages: React.FC = () => {
const strings = useStrings();
const { isAdmin } = useAuth();
return (
<Card>
<Card.Header>{strings.title.storages}</Card.Header>
<Card.Body>
<StorageList />
</Card.Body>
{isAdmin && (
<Card.Footer className="text-end">
<ButtonGroup>
<DialogButton
variant="primary"
open={
<StorageDialog method="PUT" template={Globals.defaultStorage} />
}
>
{strings.button.newStorage}
</DialogButton>
<PermissionDialogButton />
</ButtonGroup>
</Card.Footer>
)}
</Card>
);
}; |
import { useMemo, useRef } from "react";
import { formatDate, formatTimes } from "../core/dateFunctions";
import { Settings, SuitableTime } from "../weather/interpretWeather";
export function Result({
suitableTime,
settings,
}: {
suitableTime: SuitableTime;
settings: Settings;
}) {
const tempIndicatorCss = useMemo(() => {
if (suitableTime.avg_temperature_2m >= 20)
return "fa-solid fa-temperature-full text-red-600";
if (suitableTime.avg_temperature_2m >= 18)
return "fa-solid fa-temperature-three-quarters text-orange-600";
return "fa-solid fa-temperature-empty text-amber-400";
}, [suitableTime.avg_temperature_2m]);
const tempIndicatorDescription = useMemo(() => {
const prefix = "Temperature:";
if (suitableTime.avg_temperature_2m >= 20)
return `${prefix} Averages over 20 degress celsius.`;
if (suitableTime.avg_temperature_2m >= 18)
return `${prefix} Averages between 18 and 20 degress celsius.`;
return `${prefix} Averages between ${settings.minTemperature} and 18 degress celsius.`;
}, [settings.minTemperature, suitableTime.avg_temperature_2m]);
const weatherIndicatorCss = useMemo(() => {
if (suitableTime.avg_weathercode === 0) return "fa-solid fa-sun";
if (suitableTime.avg_weathercode < 1.5) return "fa-regular fa-sun";
if (suitableTime.avg_weathercode < 2.5) return "fa-solid fa-cloud-sun";
return "fa-solid fa-cloud";
}, [suitableTime.avg_weathercode]);
const weatherIndicatorDescription = useMemo(() => {
const prefix = "Predominant weather: ";
if (suitableTime.avg_weathercode === 0) return `${prefix} Clear skies`;
if (suitableTime.avg_weathercode < 0.5) return `${prefix} Mostly clear`;
if (suitableTime.avg_weathercode < 1.5) return `${prefix} Partly Cloudy`;
if (suitableTime.avg_weathercode < 2.5) return `${prefix} Cloudy`;
return `${prefix} Overcast`;
}, [suitableTime.avg_weathercode]);
const now = useRef(new Date());
return (
<div className="grid grid-flow-col grid-cols-2">
<div className="row-span-2">
<h2 className="align-top">
{suitableTime.perfect && <i className="fa-solid fa-star mr-2"></i>}
{formatDate(suitableTime.timeFrom, now.current)}{" "}
</h2>
<h3>
{formatTimes(suitableTime.timeFrom, suitableTime.timeTo)}{" "}
<small className="hidden sm:inline text-xs text-slate-600">
({suitableTime.hours} hours)
</small>
</h3>
</div>
<div className="text-lg">
<i className={tempIndicatorCss} title={tempIndicatorDescription}></i>{" "}
{Math.round(suitableTime.avg_temperature_2m)}℃{" "}
<i
className={weatherIndicatorCss}
title={weatherIndicatorDescription}
></i>
</div>
<div className="flex flex-row gap-2 text-slate-600">
<div>
<i
className="fa-solid fa-umbrella"
title="Percentage chance of precipitation"
></i>{" "}
{Math.round(suitableTime.avg_precipitation_probability)}%
</div>
<div>
<i
className="fa-solid fa-cloud-sun"
title="Percentage cloudcover"
></i>{" "}
{Math.round(suitableTime.avg_cloudcover)}%
</div>
<div>UV: {suitableTime.max_uv_index}</div>
</div>
</div>
);
} |
<template>
<div class="color-picker">
<span
v-for="(color, index) in props.colorOptions"
:key="index + color"
class="color-option-label"
:class="{ selected: color === selectedColor }"
:style="{ backgroundColor: color }"
@click="selectColor(color)"
></span>
</div>
</template>
<script setup lang="ts">
const props = withDefaults(defineProps<{ colorOptions?: string[], selected?: string }>(), {
colorOptions: () => ['#2E3A8C', '#3B755F', '#F2EBDB', '#FFFFFF', '#212121']
});
const emit = defineEmits(['change']);
let selectedColor = props.selected ?? '' ;
const selectColor = (color: string) => {
selectedColor = color;
emit('change', color);
}
</script>
<style scoped>
.color-picker {
display: flex;
flex-wrap: wrap;
}
.color-option-label {
width: 16px;
height: 16px;
margin: 3px;
cursor: pointer;
}
.color-option-label:hover {
opacity: 0.8;
}
.selected {
border: #b0b0b0 2px solid;
}
</style> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<title>BOOTSTRAP</title>
</head>
<body>
<section id="home">
<nav
class="navbar navbar-expand-lg navbar-light bg-light sticky-top"
style="height: 10vh"
>
<div class="container-fluid">
<a class="navbar-brand" href="#">LOGO</a>
<button
class="navbar-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 ms-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#"
>Section</a
>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#"
>About Us</a
>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#"
>Contact Us</a
>
</li>
</ul>
</div>
</div>
</nav>
<div
id="carouselExampleIndicators"
class="carousel slide"
data-bs-ride="carousel"
style="display: 90vh"
>
<div class="carousel-indicators">
<button
type="button"
data-bs-target="#carouselExampleIndicators"
data-bs-slide-to="0"
class="active"
aria-current="true"
aria-label="Slide 1"
></button>
<button
type="button"
data-bs-target="#carouselExampleIndicators"
data-bs-slide-to="1"
aria-label="Slide 2"
></button>
<button
type="button"
data-bs-target="#carouselExampleIndicators"
data-bs-slide-to="2"
aria-label="Slide 3"
></button>
</div>
<div class="carousel-inner" style="height: 90vh">
<div class="carousel-item active h-100">
<img
src="https://images.unsplash.com/photo-1693385330159-8bb735b72953?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE0fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60"
class="d-block w-100 h-100"
alt="..."
/>
</div>
<div class="carousel-item h-100">
<img
src="https://images.unsplash.com/photo-1693385330159-8bb735b72953?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE0fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60"
class="d-block w-100 h-100"
alt="..."
/>
</div>
<div class="carousel-item h-100">
<img
src="https://images.unsplash.com/photo-1693362287391-fc96c0e5e489?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE2fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60"
class="d-block w-100 h-100"
alt="..."
/>
</div>
</div>
<button
class="carousel-control-prev"
type="button"
data-bs-target="#carouselExampleIndicators"
data-bs-slide="prev"
>
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button
class="carousel-control-next"
type="button"
data-bs-target="#carouselExampleIndicators"
data-bs-slide="next"
>
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</section>
<!-- Section Start -->
<section id="section" class="mt-5">
<div class="container">
<div class="row">
<div class="col-12">
<p class="h2">Our Team</p>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing.</p>
</div>
<div class="row">
<div class="col-12 col-md-6 col-lg-4 col-xl-3">
<div class="card text-light text-center bg-white pb-2">
<div class="card-body text-dark">
<div class="img">
<img class="img-fluid" src="https://images.unsplash.com/photo-1693246346926-82f1e403cf0b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE3fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt="">
<h3 class="card-title">Content 1</h3>
<p class="lead">lorem ok</p>
<button class="btn btn-outline-info">Learn</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4 col-xl-3">
<div class="card text-light text-center bg-white pb-2">
<div class="card-body text-dark">
<div class="img">
<img class="img-fluid" src="https://images.unsplash.com/photo-1693246346926-82f1e403cf0b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE3fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt="">
<h3 class="card-title">Content 1</h3>
<p class="lead">lorem ok</p>
<button class="btn btn-outline-info">Learn</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4 col-xl-3">
<div class="card text-light text-center bg-white pb-2">
<div class="card-body text-dark">
<div class="img">
<img class="img-fluid" src="https://images.unsplash.com/photo-1693246346926-82f1e403cf0b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE3fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt="">
<h3 class="card-title">Content 1</h3>
<p class="lead">lorem ok</p>
<button class="btn btn-outline-info">Learn</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4 col-xl-3">
<div class="card text-light text-center bg-white pb-2">
<div class="card-body text-dark">
<div class="img">
<img class="img-fluid" src="https://images.unsplash.com/photo-1693246346926-82f1e403cf0b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE3fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt="">
<h3 class="card-title">Content 1</h3>
<p class="lead">lorem ok</p>
<button class="btn btn-outline-info">Learn</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4 col-xl-3">
<div class="card text-light text-center bg-white pb-2">
<div class="card-body text-dark">
<div class="img">
<img class="img-fluid" src="https://images.unsplash.com/photo-1693246346926-82f1e403cf0b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE3fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt="">
<h3 class="card-title">Content 1</h3>
<p class="lead">lorem ok</p>
<button class="btn btn-outline-info">Learn</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4 col-xl-3">
<div class="card text-light text-center bg-white pb-2">
<div class="card-body text-dark">
<div class="img">
<img class="img-fluid" src="https://images.unsplash.com/photo-1693246346926-82f1e403cf0b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE3fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt="">
<h3 class="card-title">Content 1</h3>
<p class="lead">lorem ok</p>
<button class="btn btn-outline-info">Learn</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4 col-xl-3">
<div class="card text-light text-center bg-white pb-2">
<div class="card-body text-dark">
<div class="img">
<img class="img-fluid" src="https://images.unsplash.com/photo-1693246346926-82f1e403cf0b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE3fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt="">
<h3 class="card-title">Content 1</h3>
<p class="lead">lorem ok</p>
<button class="btn btn-outline-info">Learn</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4 col-xl-3">
<div class="card text-light text-center bg-white pb-2">
<div class="card-body text-dark">
<div class="img">
<img class="img-fluid" src="https://images.unsplash.com/photo-1693246346926-82f1e403cf0b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE3fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt="">
<h3 class="card-title">Content 1</h3>
<p class="lead">lorem ok</p>
<button class="btn btn-outline-info">Learn</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Section End -->
<!-- Aboutus Start -->
<section id="about" class="about mt-5">
<div class="container">
<h2 class="text-center text-info mb-5">About us</h2>
<div class="row">
<div class="col-lg-4 col-md-6 col-12">
<div class="about-image">
<img src="https://images.unsplash.com/photo-1442507320796-a2ae07a5699d?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDMyfHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D&auto=format&fit=crop&w=500&q=60" class="img-fluid" alt="">
</div>
</div>
<div class="col-lg-8 col-md-6 col-12 mt-sm-0 mt-4">
<div class="about-text">
<h2>Best services ever.</h2>
<p class="lead">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Cupiditate, expedita harum repudiandae nisi quam accusamus nihil similique consequatur suscipit incidunt, dolore vitae esse dolorem error sequi voluptas doloremque, repellendus fugiat saepe? Voluptas, obcaecati quia, molestiae exercitationem doloremque veritatis nam totam autem enim soluta tempora?
</p>
<a href="" class="btn btn-outline-info">Learn More</a>
</div>
</div>
</div>
</div>
</section>
<!-- Aboutus End -->
<!-- Contactus FOrm start -->
<section id="contact" class="mt-5 container">
<h3 class="text-center text-secondary fw-bold">Contact us</h3>
<form action="" class="form">
<div class="row">
<div class="form-group mb-3 col">
<label for="" class="form-label">Name</label>
<input type="text" class="form-control" placeholder="Enter your name here">
</div>
<div class="form-group mb-3 col">
<label for="" class="form-label">Email</label>
<input type="email" class="form-control" placeholder="Enter your email here">
</div>
<!-- <div class="form-floating mb-3 col">
<input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
<label for="floatingInput">Email address</label>
</div> -->
</div>
<div class="row">
<div class="form-group mb-3 col">
<label for="" class="form-label">Address</label>
<input type="text" class="form-control" placeholder="Enter your address here">
</div>
<!-- <div class="form-group mb-3 col">
<label for="" class="form-label">Description</label>
<textarea name="" id="" cols="30" rows="10" class="form-control" placeholder="Enter your desc here"></textarea>
</div> -->
<div class="form-group mb-3 col">
<label for="" class="form-label">Photo</label>
<input type="file" class="form-control">
</div>
</div>
<div class="form-group mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="flexCheckChecked" checked>
<label class="form-check-label" for="flexCheckChecked">
I agree to terms and conditions.
</label>
</div>
<button class="btn btn-primary mt-3">Submit</button>
</div>
</form>
</section>
<!-- Contactus FOrm end -->
<footer class="bg-dark p-2 text-center">
<div class="container">
<p class="text-light">All rights reserved y @websiteName</p>
</div>
</footer>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"
></script>
</body>
</html> |
import * as React from 'react';
import {Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material';
import { useEffect, useState } from 'react';
import { getSirenUsersWhere, setSirenUser } from '../../firebase/queries';
import ApproveDeny from './ApproveDeny';
import { SirenUser } from '../../../types';
export default function SirenApprovalTable() {
const [sirenUsers, setSirenUsers] = useState([]);
const getPendingSirenUsers = async () => {
const queryParams = [
{field: 'status', operator: '==', value: 'Pending'}
]
const users = await getSirenUsersWhere(queryParams);
setSirenUsers(users);
}
const handleStatusChange = async (user: SirenUser, status: string) => {
const updatedUser = {...user};
updatedUser.status = status;
setSirenUser(updatedUser);
setSirenUsers(sirenUsers.filter(u => u.uid != updatedUser.uid))
}
useEffect(() => {
getPendingSirenUsers();
}, []);
return (
<TableContainer sx={{border: 1, borderRadius: 2}}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Staff Name</TableCell>
<TableCell>Email</TableCell>
<TableCell>Decision</TableCell>
</TableRow>
</TableHead>
<TableBody>
{sirenUsers.map((user) => (
<TableRow
key={user.uid}
sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
>
<TableCell component="th" scope="row">{user.name}</TableCell>
<TableCell component="th" scope="row">{user.email}</TableCell>
<TableCell component="th" scope="row"><ApproveDeny user={user} handleStatusChange={handleStatusChange}/></TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
} |
import { Product } from '../entities';
import { HttpService } from './http-service';
export class ProductsService {
private httpService: HttpService;
constructor() {
this.httpService = HttpService.getInstance();
}
async create(name: string, quantity: number) {
try {
const response = await this.httpService.execute({
method: 'POST',
url: '/products',
data: { name, quantity },
headers: {
Authorization: `Bearer ${this.httpService.getAccessToken()}`,
},
});
return { data: response.data as Product, errorMsg: null };
} catch (error) {
return { data: null, errorMsg: this.httpService.handleError(error) };
}
}
async delete(id: string) {
try {
await this.httpService.execute({
method: 'DELETE',
url: `/products/${id}`,
headers: {
Authorization: `Bearer ${this.httpService.getAccessToken()}`,
},
});
return { errorMsg: null };
} catch (error) {
return { errorMsg: this.httpService.handleError(error) };
}
}
async getAll(search?: string) {
try {
const response = await this.httpService.execute({
method: 'GET',
url: '/products',
params: { name: search },
headers: {
Authorization: `Bearer ${this.httpService.getAccessToken()}`,
},
});
return { products: response.data as Product[], errorMsg: null };
} catch (error) {
return { products: [], errorMsg: this.httpService.handleError(error) };
}
}
} |
"use client";
import { NavBarBox } from "@/app/components/NavBarBox";
import { pasingCsv } from "@/app/lib/parsingCsv";
import Link from "next/link";
import React, { useState } from "react";
export default function ParseCsv() {
const [result, setResult] = useState([]);
const handleSumbit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault(); // Prevent form submission from refreshing the page
const formData = new FormData(event.currentTarget);
const data: any = await pasingCsv(formData);
setResult(data);
};
return (
<main className="bg-[radial-gradient(circle_farthest-side,rgba(255,0,182,.20),rgba(255,255,255,0.0))] bg-gray-900 flex h-screen items-center p-24">
<div className="w-screen flex justify-center h-4/6">
<div className="flex justify-center items-center w-4/6 h-full max-lg:inline-block ">
<div className="bg-gray-900 shadow-xl shadow-violet-900 h-full rounded-3xl w-11/12 md:w-9/12 md:h-full overflow-y-auto">
<NavBarBox />
<div className="p-4 bg-[radial-gradient(circle_farthest-side,rgba(255,0,182,.20),rgba(255,255,255,0.0))] bg-gray-900 text-white">
<form
onSubmit={handleSumbit}
className="flex flex-col items-center bg-gray-800 p-6 rounded-lg shadow-lg"
>
<div className="flex items-center">
<input
type="file"
name="csvFile"
className="mb-4 p-3 border-2 border-gray-500 rounded-lg text-gray-300 bg-gray-700 focus:outline-none focus:ring-2 focus:ring-pink-500 transition-all duration-300 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-pink-200 file:text-pink-700 hover:file:bg-pink-300"
/>
<div className="relative inline-flex h-14 group">
<div className="ml-10 absolute transitiona-all duration-1000 opacity-70 -inset-px bg-gradient-to-r from-[#44BCFF] via-[#FF44EC] to-[#FF675E] rounded-xl blur-lg group-hover:opacity-100 group-hover:-inset-1 group-hover:duration-200 animate-tilt"></div>
<button className="px-4 h-11 ml-10 text-white rounded relative inline-flex items-center justify-center px-8 py-4 text-lg font-bold text-white transition-all duration-200 bg-gray-900 font-pj rounded-xl focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900">
Send
</button>
</div>
</div>
</form>
</div>
<div className="p-6 bg-[radial-gradient(circle_farthest-side,rgba(255,0,182,.20),rgba(255,255,255,0.0))] bg-gray-900 min-h-screen text-white">
{result.length > 0 && (
<div className="bg-gray-800 p-6 shadow-lg rounded-lg">
<div className="flex justify-center">
<h1 className="relative top-0 w-fit h-auto py-4 justify-center flex bg-gradient-to-r items-center from-blue-500 to-pink-500 bg-clip-text font-extrabold text-transparent text-center select-auto text-3xl">
Parsed CSV Data
</h1>
</div>
{result.map((entry: [], index) => (
<div
key={index}
className="mb-6 p-4 border-2 border-pink-500 rounded-lg bg-gray-700"
>
{entry.map((item: object, subIndex) => (
<div key={subIndex} className="mb-4">
{Object.entries(item).map(
([key, value]: [string, string]) => (
<p key={key} className="text-md mb-2">
<strong className="text-pink-700">
{key}:
</strong>
{value}
</p>
)
)}
</div>
))}
</div>
))}
</div>
)}
</div>
</div>
</div>
</div>
</main>
);
} |
module;
#include <cstdint>
#include <cassert>
#include <ranges>
#include <compare>
export module Brawler.FileMagicHandler;
import Brawler.NZStringView;
export namespace Brawler
{
class FileMagicHandler
{
public:
consteval explicit FileMagicHandler(const NZStringView magicStr);
consteval FileMagicHandler(const FileMagicHandler& rhs) = default;
consteval FileMagicHandler& operator=(const FileMagicHandler& rhs) = default;
consteval FileMagicHandler(FileMagicHandler&& rhs) noexcept = default;
consteval FileMagicHandler& operator=(FileMagicHandler&& rhs) noexcept = default;
consteval std::uint32_t GetMagicIntegerValue() const;
consteval NZStringView GetMagicString() const;
private:
NZStringView mMagicStr;
};
}
// -------------------------------------------------------------------------------------------------------------------
namespace Brawler
{
consteval FileMagicHandler::FileMagicHandler(const NZStringView magicStr) :
mMagicStr(magicStr)
{
assert(magicStr.GetSize() <= 4 && "ERROR: An attempt was made to create a magic string which was more than 4 characters long!");
}
consteval std::uint32_t FileMagicHandler::GetMagicIntegerValue() const
{
std::uint32_t magicNumValue = 0;
std::uint32_t bitShiftAmount = 24;
// We reverse the bytes for little-endian serialization. Using std::views::reverse is causing
// an MSVC crash, for some reason.
for (auto itr = mMagicStr.rbegin(); itr != mMagicStr.rend(); ++itr)
{
magicNumValue |= (static_cast<std::uint32_t>(*itr) << bitShiftAmount);
bitShiftAmount -= 8;
}
return magicNumValue;
}
consteval NZStringView FileMagicHandler::GetMagicString() const
{
return mMagicStr;
}
} |
import unittest
import time
from selenium import webdriver
class TestSauceDemo(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Configurar o driver do Selenium
cls.driver = webdriver.Chrome()
cls.driver.get("https://www.saucedemo.com/")
# CT01 | Login com credenciais válidas
username = cls.driver.find_element("id", "user-name")
password = cls.driver.find_element("id", "password")
login_button = cls.driver.find_element("id", "login-button")
time.sleep(2)
username.send_keys("standard_user")
password.send_keys("secret_sauce")
time.sleep(2)
login_button.click()
time.sleep(3)
@classmethod
def tearDownClass(cls):
# Fechar o navegador após o teste
cls.driver.quit()
def test_verificacao_detalhes_do_produto(self):
# CT05 | Verificação de detalhes do produto
product_link = self.driver.find_element("id", "item_4_title_link")
product_link.click()
time.sleep(3)
# Verificar se as informações do produto correspondem às expectativas
expected_name = "Sauce Labs Backpack"
expected_price = "$29.99"
product_name = self.driver.find_element("class name", "inventory_details_name")
product_price = self.driver.find_element("class name", "inventory_details_price")
self.assertEqual(expected_name, product_name.text)
self.assertEqual(expected_price, product_price.text)
if __name__ == "__main__":
unittest.main() |
-- Table Tweets
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| tweet_id | int |
| content | varchar |
+----------------+---------+
-- tweet_id is the primary key for this table.
-- This table contains all the tweets in a social media app.
-- Write an SQL query to find the IDs of the invalid tweets.
-- The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.
-- Return the result table in any order.
-- The query result format is in the following example:
-- Tweets table:
+----------+----------------------------------+
| tweet_id | content |
+----------+----------------------------------+
| 1 | Vote for Biden |
| 2 | Let us make America great again! |
+----------+----------------------------------+
-- Result table:
+----------+
| tweet_id |
+----------+
| 2 |
+----------+
-- Tweet 1 has length = 14. It is a valid tweet.
-- Tweet 2 has length = 32. It is an invalid tweet.
-- Solution
select tweet_id
from tweets
where length(content) > 15 |
# Import required libraries
from langchain import PromptTemplate
import streamlit as st
from langchain.llms import OpenAI
from dotenv import load_dotenv
# Load the environment variables from the .env file
load_dotenv()
# Define the template for the email conversion task
query_template = query_template = """
Below is an email that may be unstructured and poorly worded.
Your goal is to:
- Format the email properly
- Convert the input email into the tone specified in curly braces.
- Convert the input email into the dialect specified in curly braces.
Take these examples of different tones as reference:
- Formal: We went to Hyderabad for the weekend. We have a lot of things to tell you.
- Informal: Went to Hyderabad for the weekend. Lots to tell you.
Below are some examples of words in different dialects:
- American: Garbage, cookie, green thumb, parking lot, pants, windshield,
French Fries, cotton candy, apartment
- British: Green fingers, car park, trousers, windscreen, chips, candyfloss,
flag, rubbish, biscuit
Example Sentences from each dialect:
- American: As they strolled through the colorful neighborhood, Sarah asked her
friend if he wanted to grab a coffee at the nearby café. The fall
foliage was breathtaking, and they enjoyed the pleasant weather,
chatting about their weekend plans.
- British: As they wandered through the picturesque neighbourhood, Sarah asked her
friend if he fancied getting a coffee at the nearby café. The autumn
leaves were stunning, and they savoured the pleasant weather, chatting
about their weekend plans.
Please start the email with a warm introduction. Add the introduction if you need to.
Below is the email, tone, and dialect:
TONE: {tone}
DIALECT: {dialect}
EMAIL: {email}
YOUR {dialect} RESPONSE:
"""
# Create a PromptTemplate instance to manage the input variables and the template
prompt = PromptTemplate(
input_variables=["tone", "dialect", "email"],
template=query_template,
)
# Function to load the Language Model
def loadLanguageModel(api_key_openai):
llm = OpenAI(temperature=.7)
return llm
# Set up Streamlit app with Header and Title
st.set_page_config(page_title="Professional Email Writer", page_icon=":robot:")
st.header("Professional Email Writer")
# Create columns for the Streamlit layout
column1, column2 = st.columns(2)
# Display text input for OpenAI API Key
def fetchAPIKey():
input_text = st.text_input(
label="OpenAI API Key ", placeholder="Ex: vk-Cb8un42twmA8tf...", key="openai_api_key_input")
return input_text
# Get the OpenAI API Key from the user
openai_api_key = fetchAPIKey()
# Display dropdowns for selecting tone and dialect
column1, column2 = st.columns(2)
with column1:
tone_drop_down = st.selectbox(
'Which tone would you like your email to have?',
('Formal', 'Informal'))
with column2:
dialect_drop_down = st.selectbox(
'Which English Dialect would you like?',
('American', 'British'))
# Get the user input email text
def getEmail():
input_text = st.text_area(label="Email Input", label_visibility='collapsed',
placeholder="Your Email...", key="input_text")
return input_text
input_text = getEmail()
# Check if the email exceeds the word limit
if len(input_text.split(" ")) > 700:
st.write("Maximum limit is 700 words. Please enter a shorter email")
st.stop()
# Function to update the text box with an example email
def textBoxUpdateWithExample():
print("in updated")
st.session_state.input_text = "Vinay I am starts work at yours office from monday"
# Button to show an example email
st.button("*Show an Example*", type='secondary',
help="Click to see an example of the email you will be converting.", on_click=textBoxUpdateWithExample)
st.markdown("### Your Email:")
# If the user has provided input_text, proceed with email conversion
if input_text:
# if not openai_api_key:
# # If API Key is not provided, show a warning
# st.warning(
# 'Please insert OpenAI API Key. Instructions [here](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key)', icon="")
# st.stop()
# Load the Language Model with the provided API Key
llm = loadLanguageModel(api_key_openai=openai_api_key)
# Format the email using the PromptTemplate and the Language Model
prompt_with_email = prompt.format(
tone=tone_drop_down, dialect=dialect_drop_down, email=input_text)
formatted_email = llm(prompt_with_email)
# Display the formatted email
st.write(formatted_email) |
function tf = loadtf(fname,variable,preprocess,postprocess)
%LOADTF Load output of tflab.
%
% tf = LOADTF(filename) load all output of a tflab run.
%
% var = LOADTF(filename, varstring) load a top-level structure variable.
%
% Example:
% In = LOADTF(filename, 'In');
% Out = LOADTF(filename, 'Out');
%
% tf = LOADTF(filename, '', preprocess, postprocess) executes
% tf = tflab_preprocess(tf)
% if preprocess = 1 and
% tf = tflab_postprocess(tf)
% if postprocess = 1.
%
% See also TFLAB.
fnamefull = fname;
if ~endsWith(fnamefull,'.mat')
fnamefull = append(fnamefull,'.mat');
end
logmsg(sprintf('Reading: %s\n',fnamefull));
if exist('variable','var') && ~isempty(variable)
tf = load(fname,variable);
tf = tf.(variable);
logmsg(sprintf('Read: ''%s'' from %s\n',variable,fnamefull));
else
tf = load(fname);
logmsg(sprintf('Read: %s\n',fnamefull));
end
if nargin > 2 && preprocess
tf = tflab_preprocess(tf);
end
if nargin > 3 && postprocess
tf = tflab_metrics(tf);
end |
<template>
<div class="bg-gray-100 rounded shadow flex items-center justify-between p-2">
<p v-if="!props.done" class="font-semibold">{{props.title}}</p>
<del v-else class="font-semibold">{{props.title}}</del>
<div>
<button @click="isDone" class="bg-blue-500 shadow-md hover:bg-blue-700 rounded p-1 text-white font-semibold mr-1">Done</button>
<button @click="hapus" class="bg-red-500 shadow-md hover:bg-red-700 rounded p-1 text-white font-semibold">Hapus</button>
</div>
</div>
</template>
<script>
export default {
props:{
title:{
type: String,
default: ""
},
done:{
type: Boolean,
},
id:{
type: Number,
default: null
}
},
setup(props, {emit}){
const hapus = ()=>{
emit("hapus", props.id)
}
const isDone = ()=>{
emit("isDone", {done: true, id: props.id})
}
return{
props,
hapus,
isDone
}
}
}
</script> |
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="zh-CN">
<head>
<title>书城首页 - 书城</title>
<%@ include file="../common/head.jsp" %>
<link rel="stylesheet" href="static/css/index.css">
</head>
<body class="d-flex flex-column h-100">
<%@ include file="../common/shortcut.jsp" %>
<%@ include file="../common/header_with_cart.jsp" %>
<main class="container-fluid bg-light">
<div class="container d-flex flex-column align-items-center py-4">
<form class="mb-2" action="client/bookServlet" method="get">
<input type="hidden" name="action" value="pageByPrice">
<span>价格:</span>
<input type="number" id="inputMinPrice" name="minPrice" class="form-control form-control-sm d-inline-block price" step="0.01" value="${param.minPrice}">
<label for="inputMinPrice">元</label>
<span> - </span>
<input type="number" id="inputMaxPrice" name="maxPrice" class="form-control form-control-sm d-inline-block price" step="0.01" value="${param.maxPrice}">
<label for="inputMaxPrice">元</label>
<input type="submit" class="btn btn-sm btn-outline-danger ml-2" value="查询">
</form>
<div class="mb-2${not empty sessionScope.lastItemName and sessionScope.cart.totalCount > 0 ? "" : " d-none"}">
您刚刚将 <span id="cartLastItemName" class="text-important">${sessionScope.lastItemName}</span> 加入到了购物车中
</div>
<div class="row w-100">
<c:forEach var="book" items="${requestScope.page.records}">
<div class="col-lg-3 col-md-4 col-6 mb-4">
<div class="card h-100 shadow-sm">
<div class="card-body">
<img class="card-img mb-2" src="${book.imgPath}" alt="${book.name}">
<h5 class="card-title">${book.name}</h5>
<h6 class="card-subtitle small text-muted text-truncate">${book.author}</h6>
<div class="text-red">¥<span class="text-important">${book.price}</span></div>
<div class="d-flex justify-content-between align-items-center">
<div>销量:<span class="font-weight-bold">${book.sales}</span></div>
<div>库存:<span class="font-weight-bold">${book.stock}</span></div>
</div>
</div>
<div class="card-footer">
<button type="button" class="btn btn-danger add-to-cart" data-book-id="${book.id}">加入购物车</button>
</div>
</div>
</div>
</c:forEach>
</div>
</div>
<%@ include file="../common/pagination.jsp" %>
</main>
<%@ include file="../common/footer.jsp" %>
<script src="static/js/index.js"></script>
</body>
</html> |
import { useEffect, useState } from 'react'
import PropTypes from 'prop-types';
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import '../../pages/Chat.css'
const ChatMessages = ({messages}) => {
const [currentUsername, setCurrentUsername] = useState(null)
useEffect(() => {
setCurrentUsername(localStorage.getItem('username'))
}, [])
return (
<TransitionGroup component='ul' className='Chat-messages-list'>
{
messages.map(msg => {
return (
<CSSTransition
key={msg.id}
timeout={500}
classNames="item"
>
<li className={msg.owner === 'ADMIN' ? 'Chat-messages__item--admin' : 'Chat-messages__item'}>
{
msg.owner !== 'ADMIN' ?
(<span
className={`Chat-messages__user-name ${msg.owner === currentUsername ? 'Chat-messages__user-name--owner' : ''}`}>
{msg.owner === currentUsername ? 'You' : msg.owner}
</span>) :
null
}
<span
className={msg.owner === 'ADMIN' ? `Chat-messages__text--admin ${msg.status ? msg.status === 'connected' ? 'connected' : 'disconnected' : null}` : `Chat-messages__text ${msg.owner === currentUsername ? 'Chat-messages__text--owner' : ''}`}>
{msg.owner === 'ADMIN' ? (msg.nameUser === currentUsername ? 'You ' : msg.nameUser) + msg.message : msg.message}
</span>
</li>
</CSSTransition>
)
})
}
</TransitionGroup>
)
}
ChatMessages.propTypes = {
messages: PropTypes.array,
}
export default ChatMessages |
package com.goldax.goldax.util;
import android.view.View;
import androidx.annotation.NonNull;
/**
* Glide 이미지 요청 시 필요 데이터 class
*/
public class ImageRequest {
public @NonNull
View view;
public @NonNull
String url;
public int errorResId;
public boolean isRound;
private ImageRequest(Builder builder) {
view = builder.view;
url = builder.url;
errorResId = builder.errorResId;
isRound = builder.isRound;
}
// 빌더 패턴을 이용해 유연하게 이미지를 로드
public static class Builder {
private final @NonNull
View view;
private final @NonNull
String url;
private int errorResId;
private boolean isRound;
public Builder(View view, String url) {
this.view = view;
this.url = url;
this.errorResId = 0;
}
public Builder setErrorResId(int errorResId) {
this.errorResId = errorResId;
return this;
}
public Builder setRound(boolean isRound) {
this.isRound = isRound;
return this;
}
public ImageRequest build() {
return new ImageRequest(this);
}
}
} |
package bg.softuni.pcstore.service.impl;
import bg.softuni.pcstore.events.UserRegistrationEvent;
import bg.softuni.pcstore.exception.ObjectNotFoundException;
import bg.softuni.pcstore.model.entity.UserEntity;
import bg.softuni.pcstore.model.entity.VerificationToken;
import bg.softuni.pcstore.repository.UserRepository;
import bg.softuni.pcstore.repository.VerificationTokenRepository;
import bg.softuni.pcstore.service.EmailService;
import bg.softuni.pcstore.service.UserActivationService;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
@Service
public class UserActivationServiceImpl implements UserActivationService {
private final EmailService emailService;
private final VerificationTokenRepository verificationTokenRepository;
private final UserRepository userRepository;
public UserActivationServiceImpl(EmailService emailService, VerificationTokenRepository verificationTokenRepository, UserRepository userRepository) {
this.emailService = emailService;
this.verificationTokenRepository = verificationTokenRepository;
this.userRepository = userRepository;
}
@EventListener(UserRegistrationEvent.class)
@Override
public void userRegistered(UserRegistrationEvent event) {
String activationToken = createVerificationToken(event.getUsername());
emailService.sendActivationEmail(event.getUserEmail(), event.getFullName(), activationToken);
}
@Override
public String createVerificationToken(String username) {
String token = UUID.randomUUID().toString();
VerificationToken verificationToken = new VerificationToken();
verificationToken
.setToken(token)
.setCreated(Instant.now())
.setUser(userRepository.findByUsername(username).orElseThrow(() -> new ObjectNotFoundException("User not found!")));
verificationTokenRepository.save(verificationToken);
return token;
}
@Override
public void cleanUpLinks() {
if (verificationTokenRepository.count() <= 0) {
return;
}
List<VerificationToken> all = verificationTokenRepository.findAll();
all.forEach(token -> {
boolean tokenExpired = token.getCreated().isBefore(Instant.now().minusSeconds(600));
if (token.getUser().isDisabled() && tokenExpired) {
UserEntity user = token.getUser();
verificationTokenRepository.delete(token);
userRepository.delete(user);
}
if (!token.getUser().isDisabled()) {
verificationTokenRepository.delete(token);
}
});
}
} |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSupplierGroupsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if(!Schema::hasTable('supplier_groups')){
Schema::create('supplier_groups', function (Blueprint $table) {
$table->id();
$table->integer('branch_id')->nullable();
$table->string('name',100)->nullable();
$table->text('description')->nullable();
$table->string('company_name',150)->nullable();
$table->text('address')->nullable();
$table->text('note')->nullable();
$table->tinyInteger('status')->nullable();
$table->string('verified',25)->nullable();
$table->integer('verified_by')->nullable();
$table->integer('created_by')->nullable();
$table->softDeletes();
$table->timestamps();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('supplier_groups');
}
} |
// 배달
// https://www.acmicpc.net/problem/1175
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef pair<int, int> pr;
typedef pair<pr, pr> prrr;
int dx[4] = { -1, 0, 1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int main(void) {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int n, m;
cin >> n >> m;
int sx, sy;
vector<vector<char>> board(n, vector<char>(m));
vector<pr> goal(2);
int gi = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> board[i][j];
if (board[i][j] == 'S') {
sx = i;
sy = j;
}
if (board[i][j] == 'C') {
goal[gi].first = i;
goal[gi].second = j;
gi++;
}
}
}
vector<vector<vector<vector<int>>>> visit(n, vector<vector<vector<int>>>(m, vector<vector<int>>(5, vector<int>(4, -1))));
queue<prrr> q;
q.push({ {sx, sy}, {4, 0} });
visit[sx][sy][4][0] = 0;
int res = -1;
while (!q.empty()) {
int x = q.front().first.first;
int y = q.front().first.second;
int dir = q.front().second.first;
int cnt = q.front().second.second;
q.pop();
if (cnt == 3) {
res = visit[x][y][dir][cnt];
break;
}
for (int i = 0; i < 4; i++) {
if (i == dir)
continue;
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 0 || yy < 0 || xx >= n || yy >= m || board[xx][yy] == '#')
continue;
if (visit[xx][yy][i][cnt] == -1) {
int ncnt = cnt;
for (int j = 0; j < 2; j++) {
if (goal[j].first == xx && goal[j].second == yy && (ncnt >> j) % 2 == 0) {
ncnt += 1 << j;
}
}
visit[xx][yy][i][ncnt] = visit[x][y][dir][cnt] + 1;
q.push({ {xx, yy}, {i, ncnt} });
}
}
}
cout << res << '\n';
}
// n*m 공간에 2개의 배달 지점이 있고, 배달원은 상하좌우로 움직이되 이전에 움직인 방향으로는 이동할 수 없을 때, 두 지점에 모두 배달하는데 걸리는 최소 시간은?
// bfs - 이전 이동 방향에 따라 이동 가능 방향이 갈리는 등의 경우 visit를 한차원 더 키워서 관리해야 함
// 게다가 여기서는 한번 밟은 곳을 다시 밞으면 안 된다는 제한 사항은 없음 - 물론 밟은 땅을 다시 밟으면 최단거리가 될 수 없음은 자명함
// 그런데 어떤 배달 지점을 찍으면 새로운 경로가 열리는 것으로 볼 수 있음 - 반대로 새로운 배달 지점을 찍기 전까지는 밟은 땅을 다시 밟았을 때 비효율적임
// 추가로 배달 지점이 모두 독립적이기에, visit에서도 독립적으로 관리해주어야 함 - 두 지점을 모두 밟으면 미션 완료
// 따라서 bfs visit는 4차원으로 관리 - x, y, 이전 이동 방향, 밟은 배달 지점(비트)
// 이전 이동 방향의 경우 초반에는 무뱡향으로 표시 - 따라서 이동 방향 차원 폭은 5가 되어야 함(상하좌우'무')
// 우선 보드를 받으며 출발 지점을 기록한다 - 도착 지점의 경우 배열 형태로 기록하여 각 지점에 인덱스를 부여한다
// 이후 출발 지점부터 bfs를 돌리는데, 이전 이동 방향은 무방향, 밟은 지점 수는 0으로 하여 시작
// bfs 탐색 중 이전 이동 방향과 같은 방향으로 갈 경우, 그리고 벽을 만난 경우는 탐색 생략
// 그리고 도착지를 밟은 경우 밟은 배달 지점을 새로 기록해준 후 큐에 삽입
// 그렇게 탐색하다 밟은 배달 지점이 11이 되면 그때까지의 길이 출력하고 탐색 종료 |
#!/usr/bin/python3
"""The followiong scripts starts a Flask web application:"""
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_hbnb():
"""Return “Hello HBNB!” string when route quired"""
return "Hello HBNB!"
@app.route('/hbnb')
def hello_hbnb2():
"""Return a "HBNB" string when quired."""
return "HBNB"
@app.route('/c/<text>')
def C_is_fun(text):
"""Returns string “C ” followed by the value of the text variable
when quired"""
return 'C ' + text.replace('_', ' ')
@app.route('/python/')
@app.route('/python/<text>')
def python_is_cool(text='is cool'):
"""Return a string “Python ”, followed by the value of the text variable
when quired"""
return 'Python ' + text.replace('_', ' ')
if __name__ == '__main__':
app.url_map.strict_slashes = False
app.run(host='0.0.0.0', port=5000) |
<?php
/**
* @file
* Tests for the File (Field) Paths module.
*/
/**
* Class FileFieldPathsTestCase
*/
class FileFieldPathsTestCase extends FileFieldTestCase {
var $content_type = NULL;
var $public_files_directory = NULL;
/**
* @inheritdoc
*/
function setUp() {
// Setup required modules.
$modules = func_get_args();
if (isset($modules[0]) && is_array($modules[0])) {
$modules = $modules[0];
}
$modules[] = 'filefield_paths_test';
$modules[] = 'image';
parent::setUp($modules);
// Create a content type.
$content_type = $this->drupalCreateContentType();
$this->content_type = $content_type->name;
}
/**
* Creates a new image field.
*
* @param $name
* The name of the new field (all lowercase), exclude the "field_" prefix.
* @param $type_name
* The node type that this field will be added to.
* @param $field_settings
* A list of field settings that will be added to the defaults.
* @param $instance_settings
* A list of instance settings that will be added to the instance defaults.
* @param $widget_settings
* A list of widget settings that will be added to the widget defaults.
*/
function createImageField($name, $type_name, $field_settings = array(), $instance_settings = array(), $widget_settings = array()) {
$field = array(
'field_name' => $name,
'type' => 'image',
'settings' => array(),
'cardinality' => !empty($field_settings['cardinality']) ? $field_settings['cardinality'] : 1,
);
$field['settings'] = array_merge($field['settings'], $field_settings);
field_create_field($field);
$instance = array(
'field_name' => $name,
'label' => $name,
'entity_type' => 'node',
'bundle' => $type_name,
'required' => !empty($instance_settings['required']),
'settings' => array(),
'widget' => array(
'type' => 'image_image',
'settings' => array(),
),
);
$instance['settings'] = array_merge($instance['settings'], $instance_settings);
$instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
field_create_instance($instance);
}
}
/**
* Class FileFieldPathsGeneralTestCase
*/
class FileFieldPathsGeneralTestCase extends FileFieldPathsTestCase {
/**
* @inheritdoc
*/
public static function getInfo() {
return array(
'name' => 'General functionality',
'description' => 'Test general functionality.',
'group' => 'File (Field) Paths',
);
}
/**
* Test that the File (Field) Paths UI works as expected.
*/
public function testAddField() {
// Create a File field.
$field_name = strtolower($this->randomName());
$instance_settings = array('file_directory' => "fields/{$field_name}");
$this->createFileField($field_name, $this->content_type, array(), $instance_settings);
// Ensure File (Field) Paths settings are present.
$this->drupalGet("admin/structure/types/manage/{$this->content_type}/fields/{$field_name}");
$this->assertText('Enable File (Field) Paths?', t('File (Field) Path settings are present.'));
// Ensure that 'Enable File (Field) Paths?' is a direct sibling of
// 'File (Field) Path settings'.
$element = $this->xpath('//div[contains(@class, :class)]/following-sibling::*[1]/@id', array(':class' => 'form-item-instance-settings-filefield-paths-enabled'));
$this->assert(isset($element[0]) && 'edit-instance-settings-filefield-paths' == (string) $element[0], t('Enable checkbox is next to settings fieldset.'));
// Ensure that the File path used the File directory as it's default value.
$this->assertFieldByName('instance[settings][filefield_paths][file_path][value]', "fields/{$field_name}");
}
/**
* Test File (Field) Paths works as normal when no file uploaded.
*/
public function testNoFile() {
// Create a File field.
$field_name = strtolower($this->randomName());
$instance_settings['filefield_paths']['file_path']['value'] = 'node/[node:nid]';
$instance_settings['filefield_paths']['file_name']['value'] = '[node:nid].[file:ffp-extension-original]';
$this->createFileField($field_name, $this->content_type, array(), $instance_settings);
// Create a node without a file attached.
$this->drupalCreateNode(array('type' => $this->content_type));
}
/**
* Test a basic file upload with File (Field) Paths.
*/
public function testUploadFile() {
// Create a File field with 'node/[node:nid]' as the File path and
// '[node:nid].[file:ffp-extension-original]' as the File name.
$field_name = strtolower($this->randomName());
$instance_settings['filefield_paths']['file_path']['value'] = 'node/[node:nid]';
$instance_settings['filefield_paths']['file_name']['value'] = '[node:nid].[file:ffp-extension-original]';
$this->createFileField($field_name, $this->content_type, array(), $instance_settings);
// Create a node with a test file.
$test_file = $this->getTestFile('text');
$nid = $this->uploadNodeFile($test_file, $field_name, $this->content_type);
// Ensure that the File path has been processed correctly.
$this->assertRaw("{$this->public_files_directory}/node/{$nid}/{$nid}.txt", t('The File path has been processed correctly.'));
}
/**
* Tests a multivalue file upload with File (Field) Paths.
*/
public function testUploadFileMultivalue() {
$langcode = LANGUAGE_NONE;
// Create a multivalue File field with 'node/[node:nid]' as the File path
// and '[file:fid].txt' as the File name.
$field_name = strtolower($this->randomName());
$field_settings['cardinality'] = FIELD_CARDINALITY_UNLIMITED;
$instance_settings['filefield_paths']['file_path']['value'] = 'node/[node:nid]';
$instance_settings['filefield_paths']['file_name']['value'] = '[file:fid].txt';
$this->createFileField($field_name, $this->content_type, $field_settings, $instance_settings);
// Create a node with three (3) test files.
$text_files = $this->drupalGetTestFiles('text');
$this->drupalGet("node/add/{$this->content_type}");
$this->drupalPost(NULL, array("files[{$field_name}_{$langcode}_0]" => drupal_realpath($text_files[0]->uri)), t('Upload'));
$this->drupalPost(NULL, array("files[{$field_name}_{$langcode}_1]" => drupal_realpath($text_files[1]->uri)), t('Upload'));
$edit = array(
'title' => $this->randomName(),
"files[{$field_name}_{$langcode}_2]" => drupal_realpath($text_files[1]->uri),
);
$this->drupalPost(NULL, $edit, t('Save'));
// Get created Node ID.
$matches = array();
preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
$nid = $matches[1];
// Ensure that the File path has been processed correctly.
$this->assertRaw("{$this->public_files_directory}/node/{$nid}/1.txt", t('The first File path has been processed correctly.'));
$this->assertRaw("{$this->public_files_directory}/node/{$nid}/2.txt", t('The second File path has been processed correctly.'));
$this->assertRaw("{$this->public_files_directory}/node/{$nid}/3.txt", t('The third File path has been processed correctly.'));
}
/**
* Test File (Field) Paths slashes cleanup functionality.
*/
public function testSlashes() {
$langcode = LANGUAGE_NONE;
// Create a File field with 'node/[node:nid]' as the File path and
// '[node:nid].[file:ffp-extension-original]' as the File name.
$field_name = strtolower($this->randomName());
$instance_settings['filefield_paths']['file_path']['value'] = 'node/[node:title]';
$instance_settings['filefield_paths']['file_name']['value'] = '[node:title].[file:ffp-extension-original]';
$this->createFileField($field_name, $this->content_type, array(), $instance_settings);
// Create a node with a test file.
$test_file = $this->getTestFile('text');
$title = "{$this->randomName()}/{$this->randomName()}";
$edit['title'] = $title;
$edit["body[{$langcode}][0][value]"] = '';
$edit["files[{$field_name}_{$langcode}_0]"] = drupal_realpath($test_file->uri);
$this->drupalPost("node/add/{$this->content_type}", $edit, t('Save'));
// Get created Node ID.
$matches = array();
preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
$nid = $matches[1];
// Ensure slashes are present in file path and name.
$node = node_load($nid);
$this->assertEqual("public://node/{$title}/{$title}.txt", $node->{$field_name}[$langcode][0]['uri']);
// Remove slashes.
$edit = array(
'instance[settings][filefield_paths][file_path][options][slashes]' => TRUE,
'instance[settings][filefield_paths][file_name][options][slashes]' => TRUE,
'instance[settings][filefield_paths][retroactive_update]' => TRUE,
);
$this->drupalPost("admin/structure/types/manage/{$this->content_type}/fields/{$field_name}", $edit, t('Save settings'));
// Ensure slashes are not present in file path and name.
$node = node_load($nid, NULL, TRUE);
$title = str_replace('/', '', $title);
$this->assertEqual("public://node/{$title}/{$title}.txt", $node->{$field_name}[$langcode][0]['uri']);
}
/**
* Test a file usage of a basic file upload with File (Field) Paths.
*/
public function testFileUsage() {
// Create a File field with 'node/[node:nid]' as the File path.
$field_name = strtolower($this->randomName());
$instance_settings['filefield_paths']['file_path']['value'] = 'node/[node:nid]';
$this->createFileField($field_name, $this->content_type, array(), $instance_settings);
$this->drupalPost("admin/structure/types/manage/{$this->content_type}/fields/{$field_name}", array(), t('Save settings'));
// Create a node with a test file.
$test_file = $this->getTestFile('text');
$nid = $this->uploadNodeFile($test_file, $field_name, $this->content_type);
// Get file usage for uploaded file.
$node = node_load($nid, NULL, TRUE);
$items = field_get_items('node', $node, $field_name);
$file = file_load($items[0]['fid']);
$usage = file_usage_list($file);
// Ensure file usage count for new node is correct.
$this->assert(isset($usage['file']['node'][$nid]) && $usage['file']['node'][$nid] == 1, t('File usage count for new node is correct.'));
// Update node.
$this->drupalPost("node/{$nid}/edit", array(), t('Save'));
$usage = file_usage_list($file);
// Ensure file usage count for updated node is correct.
$this->assert(isset($usage['file']['node'][$nid]) && $usage['file']['node'][$nid] == 1, t('File usage count for updated node is correct.'));
// Update node with revision.
$this->drupalPost("node/{$nid}/edit", array('revision' => TRUE), t('Save'));
$usage = file_usage_list($file);
// Ensure file usage count for updated node with revision is correct.
$this->assert(isset($usage['file']['node'][$nid]) && $usage['file']['node'][$nid] == 2, t('File usage count for updated node with revision is correct.'));
}
/**
* Test File (Field) Paths works with read-only stream wrappers.
*/
public function testReadOnly() {
// Create a File field.
$field_name = strtolower($this->randomName());
$field_settings = array('uri_scheme' => 'ffp');
$instance_settings = array('file_directory' => "fields/{$field_name}");
$this->createFileField($field_name, $this->content_type, $field_settings, $instance_settings);
// Get a test file.
$file = $this->getTestFile('image');
// Prepare the file for the test 'ffp://' read-only stream wrapper.
$file->uri = str_replace('public', 'ffp', $file->uri);
$uri = file_stream_wrapper_uri_normalize($file->uri);
// Create a file object.
$file = new stdClass();
$file->fid = NULL;
$file->uri = $uri;
$file->filename = basename($file->uri);
$file->filemime = file_get_mimetype($file->uri);
$file->uid = $GLOBALS['user']->uid;
$file->status = FILE_STATUS_PERMANENT;
$file->display = TRUE;
file_save($file);
// Attach the file to a node.
$node = array();
$node['type'] = $this->content_type;
$node[$field_name][LANGUAGE_NONE][0] = (array) $file;
$node = $this->drupalCreateNode($node);
// Ensure file has been attached to a node.
$this->assert(isset($node->{$field_name}[LANGUAGE_NONE][0]) && !empty($node->{$field_name}[LANGUAGE_NONE][0]), t('Read-only file is correctly attached to a node.'));
$edit = array();
$edit['instance[settings][filefield_paths][retroactive_update]'] = TRUE;
$edit['instance[settings][filefield_paths][file_path][value]'] = 'node/[node:nid]';
$this->drupalPost("admin/structure/types/manage/{$this->content_type}/fields/{$field_name}", $edit, t('Save settings'));
// Ensure file is still in original location.
$this->drupalGet("node/{$node->nid}");
$this->assertRaw("{$this->public_files_directory}/{$file->filename}", t('Read-only file not affected by Retroactive updates.'));
}
}
/**
* Class FileFieldPathsTextReplaceTestCase
*/
class FileFieldPathsTextReplaceTestCase extends FileFieldPathsTestCase {
/**
* @inheritdoc
*/
public static function getInfo() {
return array(
'name' => 'Text replace functionality',
'description' => 'Tests text replace functionality.',
'group' => 'File (Field) Paths',
);
}
/**
* Generates all variations of the URI for text replacement.
*
* @param $uri
* @param string $type
*
* @return mixed
*/
protected function getPathVariations($uri, $type = 'image') {
$variations['uri'] = $uri;
$variations['absolute'] = urldecode(file_create_url($uri));
$variations['relative'] = parse_url($variations['absolute'], PHP_URL_PATH);
if ($type == 'image') {
global $base_url;
$variations['image_style'] = urldecode(image_style_url('thumbnail', $uri));
$variations['image_style_relative'] = str_replace($base_url, '', $variations['image_style']);
}
foreach ($variations as $key => $value) {
$variations["{$key}_urlencode"] = urlencode($value);
$variations["{$key}_drupal_encode_path"] = drupal_encode_path($value);
}
return $variations;
}
/**
* Test text replace with multiple file uploads.
*/
public function testTextReplace() {
$langcode = LANGUAGE_NONE;
// Create a File field with 'node/[node:nid]' as the File path and
// '[node:nid].png’ as the File name,
$field_name = strtolower($this->randomName());
$instance_settings['filefield_paths']['file_path']['value'] = 'node/[node:nid]';
$instance_settings['filefield_paths']['file_name']['value'] = '[node:nid].png';
$this->createImageField($field_name, $this->content_type, array(), $instance_settings);
// Prepare test files.
$test_files['basic_image'] = $this->getTestFile('image');
$test_files['complex_image'] = $this->getTestFile('image');
file_unmanaged_copy($test_files['complex_image']->uri, 'public://test image.png');
$files = file_scan_directory('public://', '/test image\.png/');
$test_files['complex_image'] = current($files);
// Iterate over each test file.
foreach ($test_files as $type => $test_file) {
// Get the available file paths for the test file.
$uri = file_destination($test_file->uri, FILE_EXISTS_RENAME);
$paths = $this->getPathVariations($uri);
// Upload a file and reference the original path(s) to the file in the body
// field.
$edit['title'] = $this->randomName();
$edit["body[{$langcode}][0][value]"] = '';
$edit["files[{$field_name}_{$langcode}_0]"] = drupal_realpath($test_file->uri);
foreach ($paths as $key => $value) {
$edit["body[{$langcode}][0][value]"] .= "{$key}: {$value}\n";
}
$this->drupalPost("node/add/{$this->content_type}", $edit, t('Save'));
// Get created Node ID.
$matches = array();
preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
$nid = $matches[1];
// Ensure body field has updated file path.
$node = node_load($nid);
$paths = $this->getPathVariations($node->{$field_name}[$langcode][0]['uri']);
foreach ($paths as $key => $value) {
$this->assert(strpos($node->body[$langcode][0]['value'], "{$key}: {$value}") !== FALSE, t('@type %key file path replaced successfully.', array(
'@type' => str_replace('_', ' ', ucfirst($type)),
'%key' => $key
)));
}
}
}
}
/**
* Class FileFieldPathsTokensTestCase
*/
class FileFieldPathsTokensTestCase extends FileFieldPathsTestCase {
/**
* @inheritdoc
*/
public static function getInfo() {
return array(
'name' => 'Token functionality',
'description' => 'Tests File (Field) Paths tokens.',
'group' => 'File (Field) Paths',
);
}
/**
* @param $token
* @param $value
* @param $data
*/
public function assertToken($token, $value, $data) {
$result = token_replace($token, $data);
$this->assertEqual($result, $value, t('Token @token equals @value', array(
'@token' => $token,
'@value' => $value
)));
}
/**
* Test token values with a text file.
*/
public function testTokensBasic() {
// Prepare a test text file.
$text_file = $this->getTestFile('text');
file_save($text_file);
// Ensure tokens are processed correctly.
$data = array('file' => $text_file);
$this->assertToken('[file:ffp-name-only]', 'text-0', $data);
$this->assertToken('[file:ffp-name-only-original]', 'text-0', $data);
$this->assertToken('[file:ffp-extension-original]', 'txt', $data);
}
/**
* Test token values with a moved text file.
*/
public function testTokensMoved() {
// Prepare a test text file.
$text_file = $this->getTestFile('text');
file_save($text_file);
// Move the text file.
$moved_file = file_move($text_file, 'public://moved.diff');
// Ensure tokens are processed correctly.
$data = array('file' => $moved_file);
$this->assertToken('[file:ffp-name-only]', 'moved', $data);
$this->assertToken('[file:ffp-name-only-original]', 'text-0', $data);
$this->assertToken('[file:ffp-extension-original]', 'txt', $data);
}
/**
* Test token values with a multi-extension text file.
*/
public function testTokensMultiExtension() {
// Prepare a test text file.
$text_file = $this->getTestFile('text');
file_unmanaged_copy($text_file->uri, 'public://text.multiext.txt');
$files = file_scan_directory('public://', '/text\.multiext\.txt/');
$multiext_file = current($files);
file_save($multiext_file);
// Ensure tokens are processed correctly.
$data = array('file' => $multiext_file);
$this->assertToken('[file:ffp-name-only]', 'text.multiext', $data);
$this->assertToken('[file:ffp-name-only-original]', 'text.multiext', $data);
$this->assertToken('[file:ffp-extension-original]', 'txt', $data);
}
/**
* Test token value with a UTF file.
* @see https://www.drupal.org/node/1292436
*/
public function testTokensUTF() {
// Prepare a test text file.
$text_file = $this->getTestFile('text');
file_unmanaged_copy($text_file->uri, 'public://тест.txt');
$files = file_scan_directory('public://', '/тест\.txt/');
$utf_file = current($files);
file_save($utf_file);
// Ensure tokens are processed correctly.
$data = array('file' => $utf_file);
$this->assertToken('[file:ffp-name-only]', 'тест', $data);
}
}
/**
* Class FileFieldPathsUpdatesCase
*/
class FileFieldPathsUpdatesCase extends FileFieldPathsTestCase {
/**
* @inheritdoc
*/
public static function getInfo() {
return array(
'name' => 'Update functionality',
'description' => 'Tests retroactive and active updates functionality.',
'group' => 'File (Field) Paths',
);
}
/**
* Test behaviour of Retroactive updates when no updates are needed.
*/
public function testRetroEmpty() {
// Create a File field.
$field_name = strtolower($this->randomName());
$this->createFileField($field_name, $this->content_type);
// Trigger retroactive updates.
$edit = array(
'instance[settings][filefield_paths][retroactive_update]' => TRUE
);
$this->drupalPost("admin/structure/types/manage/{$this->content_type}/fields/{$field_name}", $edit, t('Save settings'));
// Ensure no errors are thrown.
$this->assertNoText('Error', t('No errors were found.'));
}
/**
* Test basic Retroactive updates functionality.
*/
public function testRetroBasic() {
// Create an Image field.
$field_name = strtolower($this->randomName());
$this->createImageField($field_name, $this->content_type, array());
// Modify instance settings.
$instance = field_info_instance('node', $field_name, $this->content_type);
$instance['display']['default']['settings']['image_style'] = 'thumbnail';
$instance['display']['default']['settings']['image_link'] = 'content';
field_update_instance($instance);
$this->drupalGet("admin/structure/types/manage/{$this->content_type}/display");
$original_instance = field_info_instance('node', $field_name, $this->content_type);
// Create a node with a test file.
$test_file = $this->getTestFile('image');
$nid = $this->uploadNodeFile($test_file, $field_name, $this->content_type);
// Ensure that the file is in the default path.
$this->drupalGet("node/{$nid}");
$this->assertRaw("{$this->public_files_directory}/styles/thumbnail/public/{$test_file->name}", t('The File is in the default path.'));
// Trigger retroactive updates.
$edit['instance[settings][filefield_paths][retroactive_update]'] = TRUE;
$edit['instance[settings][filefield_paths][file_path][value]'] = 'node/[node:nid]';
$this->drupalPost("admin/structure/types/manage/{$this->content_type}/fields/{$field_name}", $edit, t('Save settings'));
// Ensure instance display settings haven't changed.
// @see https://www.drupal.org/node/2276435
drupal_static_reset('_field_info_field_cache');
$instance = field_info_instance('node', $field_name, $this->content_type);
$this->assert($original_instance['display'] === $instance['display'], t('Instance settings have not changed.'));
// Ensure that the file path has been retroactively updated.
$this->drupalGet("node/{$nid}");
$this->assertRaw("{$this->public_files_directory}/styles/thumbnail/public/node/{$nid}/{$test_file->name}", t('The File path has been retroactively updated.'));
}
} |
/*
* Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 3 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 3 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.r.runtime;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Random;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.TruffleFile;
import com.oracle.truffle.r.runtime.context.RContext;
import com.oracle.truffle.r.runtime.ffi.BaseRFFI;
/**
*
* As per the GnuR spec, the tempdir() directory is identified on startup. It <b>must</b>be
* initialized before the first RFFI call as the value is available in the R FFI.
*
*/
public class TempPathName implements RContext.ContextState {
private static final String RANDOM_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyz";
private static final int RANDOM_CHARACTERS_LENGTH = RANDOM_CHARACTERS.length();
private static final int RANDOM_LENGTH = 12; // as per GnuR
private String tempDirPath;
private static Random rand;
private static Random getRandom() {
if (rand == null) {
/* We don't want random seeds in the image heap. */
rand = new Random();
}
return rand;
}
@Override
public RContext.ContextState initialize(RContext context) {
if (context.getKind() == RContext.ContextKind.SHARE_PARENT_RW) {
// share tempdir with parent
tempDirPath = context.getParent().stateTempPath.tempDirPath;
return this;
}
String startingTempDir = Utils.getUserTempDir();
TruffleFile startingTempDirPath = context.getSafeTruffleFile(startingTempDir).resolve("Rtmp");
// ensure absolute, to avoid problems with R code does a setwd
if (!startingTempDirPath.isAbsolute()) {
startingTempDirPath = startingTempDirPath.getAbsoluteFile();
}
String t = (String) BaseRFFI.MkdtempRootNode.create().getCallTarget().call(startingTempDirPath.toString() + "XXXXXX");
if (t != null) {
tempDirPath = t;
} else {
RSuicide.rSuicide("cannot create 'R_TempDir'");
}
return this;
}
@Override
@TruffleBoundary
public void beforeDispose(RContext context) {
if (context.getKind() == RContext.ContextKind.SHARE_PARENT_RW) {
return;
}
try {
FileSystemUtils.walkFileTree(context.getSafeTruffleFile(tempDirPath), new DeleteVisitor());
} catch (Throwable e) {
// unexpected and we are exiting anyway
}
}
public static String tempDirPath(RContext context) {
return context.stateTempPath.tempDirPath;
}
public static String tempDirPathChecked(RContext ctx) {
String path = tempDirPath(ctx);
TruffleFile tFile = ctx.getSafeTruffleFile(path);
if (!tFile.isDirectory()) {
if (ctx.getKind() == RContext.ContextKind.SHARE_PARENT_RW) {
RContext parentCtx = ctx.getParent();
parentCtx.stateTempPath.initialize(parentCtx);
}
ctx.stateTempPath.initialize(ctx);
path = tempDirPath(ctx);
}
return path;
}
public static TempPathName newContextState() {
return new TempPathName();
}
@TruffleBoundary
public static String createNonExistingFilePath(RContext ctx, String pattern, String tempDir, String fileExt) {
while (true) {
StringBuilder sb = new StringBuilder(ctx.getSafeTruffleFile(tempDir).resolve(pattern).toString());
appendRandomString(sb);
if (fileExt.length() > 0) {
sb.append(fileExt);
}
String path = sb.toString();
if (!ctx.getSafeTruffleFile(path).exists()) {
return path;
}
}
}
private static void appendRandomString(StringBuilder sb) {
for (int i = 0; i < RANDOM_LENGTH; i++) {
sb.append(RANDOM_CHARACTERS.charAt(getRandom().nextInt(RANDOM_CHARACTERS_LENGTH)));
}
}
private static final class DeleteVisitor extends SimpleFileVisitor<TruffleFile> {
@Override
public FileVisitResult visitFile(TruffleFile file, BasicFileAttributes attrs) throws IOException {
return del(file);
}
@Override
public FileVisitResult postVisitDirectory(TruffleFile dir, IOException exc) throws IOException {
return del(dir);
}
private static FileVisitResult del(TruffleFile p) throws IOException {
p.delete();
return FileVisitResult.CONTINUE;
}
}
} |
<template>
<nav>
<router-link to="/">
<img src="../assets/logo.png">
</router-link>
<Hamburger />
<div class="site-menu">
<ul>
<li
v-for="(category, index) in categories[0]"
:key="index"
:style="{
backgroundColor: '#' + colors[categories[1][index]]
}"
>
<router-link
:to="'/' + category.toLowerCase()"
>
{{category}}
</router-link>
</li>
</ul>
</div>
</nav>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import Hamburger from './navbar/Hamburger.vue'
import { colors } from '../data/arrays'
import { fetchCategories } from '../scripts/methods'
export default defineComponent({
data () {
return {
books: {},
categories:{},
colors
}
},
components: {
Hamburger
},
methods: {
fetchCategories
},
mounted () {
this.fetchCategories().then(
data => this.categories = data
)
},
})
</script>
<style lang="scss" scoped>
@import '../assets/styles/main.scss';
nav {
position: fixed;
width:100%;
background:$main;
height: $height;
padding: 10px;
display: flex;
justify-content: space-around;
align-items: center;
box-shadow: 0px 15px 15px rgba(0, 0, 0, 0.185);
z-index: 1;
}
.site-menu {
display: flex;
position: absolute;
top: $height;
right:0;
height: calc(100vh - $height);
width: calc(200px + 20vw);
background:#e3e3e3;
border-left:5px solid $main;
transform: translateX(100%);
transition:.3s transform ease-in-out;
}
ul {
margin:10px;
padding:0;
width:100%;
list-style-type: none;
display:flex;
flex-wrap:wrap;
align-content: flex-start;
}
li {
background: #307182;
margin-top:10px;
border-radius:5px;
flex-basis:100%;
height:40px;
box-shadow: inset 2px 2px 15px rgba(0, 42, 53, 0.245);
}
a {
display:block;
height:100%;
}
.site-menu a {
display:flex;
padding:10px;
text-decoration: none;
align-items: center;
height:100%;
width:100%;
color:#fff;
}
button:focus ~ .site-menu, .site-menu:hover {
transform: translateX(0);
@media (max-width:600px) {
box-shadow: -15px 0 15px rgba(0, 0, 0, 0.585);
}
}
img {
height:100%;
filter: invert(.5) brightness(100);
}
</style> |
/************************************************************************
**
** @file abstracttest.cpp
** @author Roman Telezhynskyi <dismine(at)gmail.com>
** @date 7 5, 2015
**
** @brief
** @copyright
** This source code is part of the Valentina project, a pattern making
** program, whose allow create and modeling patterns of clothing.
** Copyright (C) 2015 Valentina project
** <https://gitlab.com/smart-pattern/valentina> All Rights Reserved.
**
** Valentina is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Valentina is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Valentina. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include "abstracttest.h"
#include <QApplication>
#include <QByteArray>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFlags>
#include <QIODevice>
#include <QJsonArray>
#include <QJsonObject>
#include <QLineF>
#include <QPointF>
#include <QProcess>
#include <QScopedPointer>
#include <QStringList>
#include <QVector>
#include <QtGlobal>
#include <qtestcase.h>
#include "../vgeometry/vgobject.h"
#include "../vgeometry/vpointf.h"
#include "../vgeometry/vspline.h"
#include "../vgeometry/vsplinepath.h"
#include "../vlayout/vabstractpiece.h"
#include "../vpatterndb/vcontainer.h"
#include "../vpatterndb/vpassmark.h"
#include "../vpatterndb/vpiece.h"
#include "../vpatterndb/vpiecenode.h"
#if QT_VERSION < QT_VERSION_CHECK(6, 4, 0)
#include "../vmisc/compatibility.h"
#endif
using namespace Qt::Literals::StringLiterals;
namespace
{
auto FillPath(const QVector<QPointF> &path, qreal accuracy) -> QVector<QPointF>
{
QVector<QPointF> pathFilled;
pathFilled.reserve(path.size());
for (int i = 0; i < path.size() - 1; ++i)
{
pathFilled.append(path.at(i));
QLineF line(path.at(i), path.at(i + 1));
if (line.length() > accuracy)
{
qreal len = accuracy;
do
{
QLineF l = line;
l.setLength(len);
pathFilled.append(l.p2());
len += accuracy;
} while (line.length() > len);
}
}
pathFilled.append(path.constLast());
return pathFilled;
}
} // namespace
//---------------------------------------------------------------------------------------------------------------------
AbstractTest::AbstractTest(QObject *parent)
: QObject(parent)
{
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::PieceFromJson(const QString &json, VPiece &piece, QSharedPointer<VContainer> &data)
{
QByteArray saveData;
PrepareDocument(json, saveData);
QJsonDocument loadDoc(QJsonDocument::fromJson(saveData));
const QString testCaseKey = QStringLiteral("testCase");
const QString bdKey = QStringLiteral("bd");
const QString pieceKey = QStringLiteral("piece");
QJsonObject testCaseObject = loadDoc.object();
TestRoot(testCaseObject, testCaseKey, json);
QJsonObject testCase = testCaseObject[testCaseKey].toObject();
if (testCase.contains(bdKey))
{
DBFromJson(testCase[bdKey].toObject(), data);
}
else
{
const QString error = QStringLiteral("Test case json object does not contain db data.");
QFAIL(qUtf8Printable(error));
}
if (testCase.contains(pieceKey))
{
MainPathFromJson(testCase[pieceKey].toObject(), piece);
}
else
{
const QString error = QStringLiteral("Test case json object does not contain piece data.");
QFAIL(qUtf8Printable(error));
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::PassmarkDataFromJson(const QString &json, VPiecePassmarkData &data)
{
QByteArray saveData;
PrepareDocument(json, saveData);
QJsonDocument loadDoc(QJsonDocument::fromJson(saveData));
const QString dataKey = QStringLiteral("data");
QJsonObject dataObject = loadDoc.object();
TestRoot(dataObject, dataKey, json);
QJsonObject passmarkData = dataObject[dataKey].toObject();
try
{
VSAPoint previousSAPoint;
PointFromJson(passmarkData[QStringLiteral("previousSAPoint")].toObject(), previousSAPoint);
data.previousSAPoint = previousSAPoint;
VSAPoint passmarkSAPoint;
PointFromJson(passmarkData[QStringLiteral("passmarkSAPoint")].toObject(), passmarkSAPoint);
data.passmarkSAPoint = passmarkSAPoint;
VSAPoint nextSAPoint;
PointFromJson(passmarkData[QStringLiteral("nextSAPoint")].toObject(), nextSAPoint);
data.nextSAPoint = nextSAPoint;
}
catch (const VException &e)
{
const QString error = QStringLiteral("Invalid json file '%1'. %2").arg(json, e.ErrorMessage());
QFAIL(qUtf8Printable(error));
}
qreal saWidth = 0;
AbstractTest::ReadDoubleValue(passmarkData, QStringLiteral("saWidth"), saWidth);
data.saWidth = saWidth;
QString nodeName;
AbstractTest::ReadStringValue(passmarkData, QStringLiteral("nodeName"), nodeName);
data.nodeName = nodeName;
QString pieceName;
AbstractTest::ReadStringValue(passmarkData, QStringLiteral("pieceName"), pieceName);
data.pieceName = pieceName;
PassmarkLineType passmarkLineType = PassmarkLineType::OneLine;
AbstractTest::ReadDoubleValue(passmarkData, QStringLiteral("passmarkLineType"), passmarkLineType,
QString::number(static_cast<int>(PassmarkLineType::OneLine)));
data.passmarkLineType = passmarkLineType;
PassmarkAngleType passmarkAngleType = PassmarkAngleType::Straightforward;
AbstractTest::ReadDoubleValue(passmarkData, QStringLiteral("passmarkAngleType"), passmarkAngleType,
QString::number(static_cast<int>(PassmarkAngleType::Straightforward)));
data.passmarkAngleType = passmarkAngleType;
bool isMainPathNode = true;
AbstractTest::ReadBooleanValue(passmarkData, QStringLiteral("isMainPathNode"), isMainPathNode);
data.isMainPathNode = isMainPathNode;
bool isShowSecondPassmark = true;
AbstractTest::ReadBooleanValue(passmarkData, QStringLiteral("isShowSecondPassmark"), isShowSecondPassmark);
data.isShowSecondPassmark = isShowSecondPassmark;
int passmarkIndex = -1;
AbstractTest::ReadDoubleValue(passmarkData, QStringLiteral("passmarkIndex"), passmarkIndex, QStringLiteral("-1"));
data.passmarkIndex = passmarkIndex;
vidtype id = NULL_ID;
AbstractTest::ReadDoubleValue(passmarkData, QStringLiteral("id"), id, QString::number(NULL_ID));
data.id = id;
qreal globalPassmarkLength;
AbstractTest::ReadDoubleValue(passmarkData, QStringLiteral("globalPassmarkLength"), globalPassmarkLength,
QString::number(NULL_ID));
data.globalPassmarkLength = globalPassmarkLength;
qreal globalPassmarkWidth;
AbstractTest::ReadDoubleValue(passmarkData, QStringLiteral("globalPassmarkWidth"), globalPassmarkWidth,
QString::number(NULL_ID));
data.globalPassmarkWidth = globalPassmarkWidth;
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::PassmarkShapeFromJson(const QString &json, QVector<QLineF> &shape)
{
QByteArray saveData;
PrepareDocument(json, saveData);
QJsonDocument loadDoc(QJsonDocument::fromJson(saveData));
const QString shapeKey = QStringLiteral("shape");
const QString typeKey = QStringLiteral("type");
QJsonObject shapeObject = loadDoc.object();
TestRoot(shapeObject, shapeKey, json);
QJsonArray vectorArray = shapeObject[shapeKey].toArray();
for (auto item : vectorArray)
{
QJsonObject lineObject = item.toObject();
QString type;
AbstractTest::ReadStringValue(lineObject, typeKey, type);
if (type != "QLineF"_L1)
{
const QString error = QStringLiteral("Invalid json file '%1'. Unexpected class '%2'.")
.arg(json, lineObject[typeKey].toString());
QFAIL(qUtf8Printable(error));
}
shape.append(QLineFromJson(lineObject));
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ComparePaths(const QVector<QPointF> &actual, const QVector<QPointF> &expected)
{
QVERIFY2(actual.size() >= 2, "Not enough points");
QVERIFY2(expected.size() >= 2, "Not enough points");
const qreal accuracy = accuracyPointOnLine * 4.;
QVector<QPointF> actualFilled = FillPath(actual, accuracy);
bool onLine = false;
QSet<int> usedEdges;
for (auto p : actualFilled)
{
for (int i = 0; i < expected.size() - 1; ++i)
{
if (VGObject::IsPointOnLineSegment(p, expected.at(i), expected.at(i + 1), accuracyPointOnLine * 2.))
{
usedEdges.insert(i + 1);
onLine = true;
}
}
if (not onLine)
{
QFAIL("Paths are not the same. Point is not on edge.");
}
onLine = false;
}
QVERIFY2(expected.size() - 1 == usedEdges.size(), "Paths are not the same. Not all edges were used.");
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ComparePathsDistance(const QVector<QPointF> &ekv, const QVector<QPointF> &ekvOrig) const
{
// Begin comparison
QCOMPARE(ekv.size(), ekvOrig.size()); // First check if sizes are equal
const qreal testAccuracy = MmToPixel(1.);
for (int i = 0; i < ekv.size(); i++)
{
ComparePointsDistance(ekv.at(i), ekvOrig.at(i), testAccuracy);
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ComparePointsDistance(const QPointF &result, const QPointF &expected, qreal testAccuracy) const
{
const QString msg = QStringLiteral("Actual '%2;%3', Expected '%4;%5'. Distance between points %6 mm.")
.arg(result.x())
.arg(result.y())
.arg(expected.x())
.arg(expected.y())
.arg(UnitConvertor(QLineF(result, expected).length(), Unit::Px, Unit::Mm));
// Check each point. Don't use comparison float values
QVERIFY2(VFuzzyComparePoints(result, expected, testAccuracy), qUtf8Printable(msg));
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::CompareLinesDistance(const QVector<QLineF> &result, const QVector<QLineF> &expected) const
{
// Begin comparison
QCOMPARE(result.size(), expected.size()); // First check if sizes equal
for (int i = 0; i < result.size(); i++)
{
const QLineF &line1 = result.at(i);
const QLineF &line2 = expected.at(i);
// Check each point. Don't use comparison float values
QVERIFY2(
VFuzzyComparePoints(line1.p1(), line2.p1()) && VFuzzyComparePoints(line1.p2(), line2.p2()),
qUtf8Printable(QStringLiteral("Index: %1. Got line '(%2;%3):(%4;%5)', Expected line '(%6;%7):(%8;%9)'.")
.arg(i)
.arg(line1.p1().x())
.arg(line1.p1().y())
.arg(line1.p2().x())
.arg(line1.p2().y())
.arg(line2.p1().x())
.arg(line2.p1().y())
.arg(line2.p2().x())
.arg(line2.p2().y())));
}
}
//---------------------------------------------------------------------------------------------------------------------
auto AbstractTest::PuzzlePath() const -> QString
{
#ifdef QBS_BUILD
return QStringLiteral(PUZZLE_BUILDDIR);
#else
const QString path = QStringLiteral("/../../../app/puzzle/bin/puzzle");
#ifdef Q_OS_WIN
return QCoreApplication::applicationDirPath() + path + ".exe"_L1;
#else
return QCoreApplication::applicationDirPath() + path;
#endif
#endif
}
//---------------------------------------------------------------------------------------------------------------------
auto AbstractTest::ValentinaPath() const -> QString
{
#ifdef QBS_BUILD
return QStringLiteral(VALENTINA_BUILDDIR);
#else
const QString path = QStringLiteral("/../../../app/valentina/bin/valentina");
#ifdef Q_OS_WIN
return QCoreApplication::applicationDirPath() + path + ".exe"_L1;
#else
return QCoreApplication::applicationDirPath() + path;
#endif
#endif
}
//---------------------------------------------------------------------------------------------------------------------
auto AbstractTest::TapePath() const -> QString
{
#ifdef QBS_BUILD
return QStringLiteral(TAPE_BUILDDIR);
#else
const QString path = QStringLiteral("/../../../app/tape/bin/tape");
#ifdef Q_OS_WIN
return QCoreApplication::applicationDirPath() + path + ".exe"_L1;
#else
return QCoreApplication::applicationDirPath() + path;
#endif
#endif
}
//---------------------------------------------------------------------------------------------------------------------
auto AbstractTest::TranslationsPath() -> QString
{
#ifdef QBS_BUILD
return QStringLiteral(TRANSLATIONS_DIR);
#else
return QCoreApplication::applicationDirPath() + QStringLiteral("/../../../app/valentina/bin/translations");
#endif
}
//---------------------------------------------------------------------------------------------------------------------
auto AbstractTest::RunTimeout(int defMsecs) -> int
{
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
QString timeout = QString::fromLocal8Bit(qgetenv("VTEST_RUN_TIMEOUT"));
if (timeout.isEmpty())
{
return defMsecs;
}
#else
QString timeout = qEnvironmentVariable("VTEST_RUN_TIMEOUT", QString::number(defMsecs));
#endif
bool ok = false;
int msecs = timeout.toInt(&ok);
return ok ? msecs : defMsecs;
}
//---------------------------------------------------------------------------------------------------------------------
auto AbstractTest::Run(int exit, const QString &program, const QStringList &arguments, QString &error, int msecs) -> int
{
msecs = AbstractTest::RunTimeout(msecs);
const QString parameters =
QStringLiteral("Program: %1 \nArguments: %2.").arg(program, arguments.join(QStringLiteral(", ")));
QFileInfo info(program);
if (not info.exists())
{
error = QStringLiteral("Can't find binary.\n%1").arg(parameters);
return TST_EX_BIN;
}
QScopedPointer<QProcess> process(new QProcess());
process->setWorkingDirectory(info.absoluteDir().absolutePath());
process->start(program, arguments);
if (not process->waitForStarted(msecs))
{
error = QStringLiteral("The start operation timed out or an error occurred.\n%1\n%2")
.arg(parameters, QString(process->readAllStandardError()));
process->kill();
return TST_EX_START_TIME_OUT;
}
if (not process->waitForFinished(msecs))
{
error = QStringLiteral("The finish operation timed out or an error occurred.\n%1\n%2")
.arg(parameters, QString(process->readAllStandardError()));
process->kill();
return TST_EX_FINISH_TIME_OUT;
}
if (process->exitStatus() == QProcess::CrashExit)
{
error = QStringLiteral("Program crashed.\n%1\n%2").arg(parameters, QString(process->readAllStandardError()));
return TST_EX_CRASH;
}
if (process->exitCode() != exit)
{
error = QStringLiteral("Unexpected finish. Exit code: %1\n%2")
.arg(process->exitCode())
.arg(QString(process->readAllStandardError()));
return process->exitCode();
}
return process->exitCode();
}
//---------------------------------------------------------------------------------------------------------------------
auto AbstractTest::CopyRecursively(const QString &srcFilePath, const QString &tgtFilePath) const -> bool
{
QFileInfo srcFileInfo(srcFilePath);
if (srcFileInfo.isDir())
{
QDir targetDir(tgtFilePath);
targetDir.cdUp();
const QString dirName = QFileInfo(tgtFilePath).fileName();
if (not targetDir.mkdir(dirName))
{
const QString msg = QStringLiteral("Can't create dir '%1'.").arg(dirName);
QWARN(qUtf8Printable(msg));
return false;
}
QDir sourceDir(srcFilePath);
const QStringList fileNames =
sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
for (auto &fileName : fileNames)
{
const QString newSrcFilePath = srcFilePath + QDir::separator() + fileName;
const QString newTgtFilePath = tgtFilePath + QDir::separator() + fileName;
if (not CopyRecursively(newSrcFilePath, newTgtFilePath))
{
return false;
}
}
}
else
{
if (QFileInfo::exists(tgtFilePath))
{
const QString msg = QStringLiteral("File '%1' exists.").arg(srcFilePath);
QWARN(qUtf8Printable(msg));
if (QFile::remove(tgtFilePath))
{
QWARN("File successfully removed.");
}
else
{
QWARN("Can't remove file.");
return false;
}
}
// Check error: Cannot open %file for input
QFile srcFile(srcFilePath);
if (not srcFile.open(QFile::ReadOnly))
{
const QString msg =
QStringLiteral("Can't copy file '%1'. Error: %2").arg(srcFilePath, srcFile.errorString());
QWARN(qUtf8Printable(msg));
return false;
}
srcFile.close();
if (not srcFile.copy(tgtFilePath))
{
const QString msg = QStringLiteral("Can't copy file '%1' to '%2'. Error: %3")
.arg(srcFilePath, tgtFilePath, srcFile.errorString());
QWARN(qUtf8Printable(msg));
return false;
}
}
return true;
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::PrepareDocument(const QString &json, QByteArray &data)
{
QFile loadFile(json);
if (not loadFile.open(QIODevice::ReadOnly))
{
const QString error = QStringLiteral("Couldn't open json file. %1").arg(loadFile.errorString());
QFAIL(qUtf8Printable(error));
}
data = loadFile.readAll();
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::TestRoot(const QJsonObject &root, const QString &attribute, const QString &file)
{
if (not root.contains(attribute))
{
const QString error = QStringLiteral("Invalid json file '%1'. File doesn't contain root object.").arg(file);
QFAIL(qUtf8Printable(error));
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ReadStringValue(const QJsonObject &itemObject, const QString &attribute, QString &value,
const QString &defaultValue)
{
if (itemObject.contains(attribute))
{
QJsonValue attributeValue = itemObject[attribute];
if (attributeValue.isString())
{
value = attributeValue.toString();
}
else
{
const QString error = QStringLiteral("%1 is not string '%2'.").arg(attribute, attributeValue.toString());
QFAIL(qUtf8Printable(error));
}
}
else
{
if (not defaultValue.isEmpty())
{
value = defaultValue;
}
else
{
const QString error = QStringLiteral("Json object does not contain attribute '%1'.").arg(attribute);
QFAIL(qUtf8Printable(error));
}
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ReadBooleanValue(const QJsonObject &itemObject, const QString &attribute, bool &value,
const QString &defaultValue)
{
if (itemObject.contains(attribute))
{
QJsonValue attributeValue = itemObject[attribute];
if (attributeValue.isBool())
{
value = attributeValue.toBool();
}
else
{
const QString error =
QStringLiteral("%1 is not boolean value '%2'.").arg(attribute, attributeValue.toString());
QFAIL(qUtf8Printable(error));
}
}
else
{
if (not defaultValue.isEmpty())
{
bool ok = false;
int defVal = defaultValue.toInt(&ok);
if (not ok)
{
const QString error = QStringLiteral("Cannot convert default value '%1' to int.").arg(defaultValue);
QFAIL(qUtf8Printable(error));
}
value = static_cast<bool>(defVal);
}
else
{
const QString error = QStringLiteral("Json object does not contain attribute '%1'.").arg(attribute);
QFAIL(qUtf8Printable(error));
}
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ReadPointValue(const QJsonObject &itemObject, const QString &attribute, VPointF &value)
{
if (itemObject.contains(attribute))
{
PointFromJson(itemObject[attribute].toObject(), value);
}
else
{
const QString error = QStringLiteral("Json object does not contain attribute '%1'.").arg(attribute);
QFAIL(qUtf8Printable(error));
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ReadSplinePointValues(const QJsonObject &itemObject, const QString &attribute,
QVector<VSplinePoint> &points)
{
points.clear();
if (itemObject.contains(attribute))
{
QJsonArray nodes = itemObject[attribute].toArray();
for (int i = 0; i < nodes.size(); ++i)
{
QJsonObject item = nodes[i].toObject();
VSplinePoint point;
ReadSplinePointValue(item, point);
points.append(point);
}
}
else
{
const QString error = QStringLiteral("Json object does not contain attribute '%1'.").arg(attribute);
QFAIL(qUtf8Printable(error));
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ReadSplinePointValue(const QJsonObject &itemObject, VSplinePoint &point)
{
qreal angle1 = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("angle1"), angle1);
QString angle1Formula;
AbstractTest::ReadStringValue(itemObject, QStringLiteral("angle1Formula"), angle1Formula);
qreal angle2 = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("angle2"), angle2);
QString angle2Formula;
AbstractTest::ReadStringValue(itemObject, QStringLiteral("angle2Formula"), angle2Formula);
qreal length1 = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("length1"), length1);
QString length1Formula;
AbstractTest::ReadStringValue(itemObject, QStringLiteral("length1Formula"), length1Formula);
qreal length2 = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("length2"), length2);
QString length2Formula;
AbstractTest::ReadStringValue(itemObject, QStringLiteral("length2Formula"), length2Formula);
VPointF pSpline;
ReadPointValue(itemObject, QStringLiteral("point"), pSpline);
point = VSplinePoint(pSpline, angle1, angle1Formula, angle2, angle2Formula, length1, length1Formula, length2,
length2Formula);
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::ReadPieceNodeValue(const QJsonObject &itemObject, VPieceNode &node)
{
vidtype id = NULL_ID;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("id"), id);
Tool typeTool = Tool::LAST_ONE_DO_NOT_USE;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("type"), typeTool);
bool reverse = false;
AbstractTest::ReadBooleanValue(itemObject, QStringLiteral("reverse"), reverse, QChar('0'));
node = VPieceNode(id, typeTool, reverse);
}
//---------------------------------------------------------------------------------------------------------------------
template <typename T, typename std::enable_if<std::is_floating_point<T>::value>::type *>
void AbstractTest::ReadDoubleValue(const QJsonObject &itemObject, const QString &attribute, T &value,
const QString &defaultValue)
{
if (itemObject.contains(attribute))
{
QJsonValue attributeValue = itemObject[attribute];
if (attributeValue.isDouble())
{
value = static_cast<T>(attributeValue.toDouble());
}
else
{
const QString error = QStringLiteral("%1 is not double '%2'.").arg(attribute, attributeValue.toString());
QFAIL(qUtf8Printable(error));
}
}
else
{
if (not defaultValue.isEmpty())
{
bool ok = false;
value = static_cast<T>(defaultValue.toDouble(&ok));
if (not ok)
{
const QString error = QStringLiteral("Cannot convert default value '%1' to double.").arg(defaultValue);
QFAIL(qUtf8Printable(error));
}
}
else
{
const QString error = QStringLiteral("Json object does not contain attribute '%1'.").arg(attribute);
QFAIL(qUtf8Printable(error));
}
}
}
//---------------------------------------------------------------------------------------------------------------------
template <typename T, typename std::enable_if<std::is_enum<T>::value>::type *>
void AbstractTest::ReadDoubleValue(const QJsonObject &itemObject, const QString &attribute, T &value,
const QString &defaultValue)
{
if (itemObject.contains(attribute))
{
QJsonValue attributeValue = itemObject[attribute];
if (attributeValue.isDouble())
{
value = static_cast<T>(static_cast<int>(attributeValue.toDouble()));
}
else
{
const QString error = QStringLiteral("%1 is not double '%2'.").arg(attribute, attributeValue.toString());
QFAIL(qUtf8Printable(error));
}
}
else
{
if (not defaultValue.isEmpty())
{
bool ok = false;
value = static_cast<T>(defaultValue.toInt(&ok));
if (not ok)
{
const QString error = QStringLiteral("Cannot convert default value '%1' to int.").arg(defaultValue);
QFAIL(qUtf8Printable(error));
}
}
else
{
const QString error = QStringLiteral("Json object does not contain attribute '%1'.").arg(attribute);
QFAIL(qUtf8Printable(error));
}
}
}
//---------------------------------------------------------------------------------------------------------------------
template <typename T, typename std::enable_if<std::is_integral<T>::value>::type *>
void AbstractTest::ReadDoubleValue(const QJsonObject &itemObject, const QString &attribute, T &value,
const QString &defaultValue)
{
if (itemObject.contains(attribute))
{
QJsonValue attributeValue = itemObject[attribute];
if (attributeValue.isDouble())
{
value = static_cast<T>(attributeValue.toDouble());
}
else
{
const QString error = QStringLiteral("%1 is not double '%2'.").arg(attribute, attributeValue.toString());
QFAIL(qUtf8Printable(error));
}
}
else
{
if (not defaultValue.isEmpty())
{
bool ok = false;
value = static_cast<T>(defaultValue.toInt(&ok));
if (not ok)
{
const QString error = QStringLiteral("Cannot convert default value '%1' to int.").arg(defaultValue);
QFAIL(qUtf8Printable(error));
}
}
else
{
const QString error = QStringLiteral("Json object does not contain attribute '%1'.").arg(attribute);
QFAIL(qUtf8Printable(error));
}
}
}
//---------------------------------------------------------------------------------------------------------------------
auto AbstractTest::QLineFromJson(const QJsonObject &itemObject) -> QLineF
{
QPointF p1;
QPointF p2;
PointFromJson(itemObject[QStringLiteral("p1")].toObject(), p1);
PointFromJson(itemObject[QStringLiteral("p2")].toObject(), p2);
return {p1, p2};
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::SplineFromJson(const QJsonObject &itemObject, QSharedPointer<VContainer> &data)
{
vidtype id = NULL_ID;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("id"), id);
qreal aScale = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("aScale"), aScale);
qreal angle1 = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("angle1"), angle1);
QString angle1Formula;
AbstractTest::ReadStringValue(itemObject, QStringLiteral("angle1Formula"), angle1Formula);
qreal angle2 = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("angle2"), angle2);
QString angle2Formula;
AbstractTest::ReadStringValue(itemObject, QStringLiteral("angle2Formula"), angle2Formula);
qreal c1Length = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("c1Length"), c1Length);
QString c1LengthFormula;
AbstractTest::ReadStringValue(itemObject, QStringLiteral("c1LengthFormula"), c1LengthFormula);
qreal c2Length = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("c2Length"), c2Length);
QString c2LengthFormula;
AbstractTest::ReadStringValue(itemObject, QStringLiteral("c2LengthFormula"), c2LengthFormula);
VPointF p1;
ReadPointValue(itemObject, QStringLiteral("p1"), p1);
data->UpdateGObject(p1.id(), new VPointF(p1));
VPointF p4;
ReadPointValue(itemObject, QStringLiteral("p4"), p4);
data->UpdateGObject(p4.id(), new VPointF(p4));
VSpline *spl = new VSpline(p1, p4, angle1, angle1Formula, angle2, angle2Formula, c1Length, c1LengthFormula,
c2Length, c2LengthFormula);
spl->SetApproximationScale(aScale);
data->UpdateGObject(id, spl);
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::SplinePathFromJson(const QJsonObject &itemObject, QSharedPointer<VContainer> &data)
{
vidtype id = NULL_ID;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("id"), id);
qreal aScale = 0;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("aScale"), aScale);
QVector<VSplinePoint> points;
AbstractTest::ReadSplinePointValues(itemObject, QStringLiteral("nodes"), points);
for (auto &point : points)
{
data->UpdateGObject(point.P().id(), new VPointF(point.P()));
}
VSplinePath *path = new VSplinePath(points);
path->SetApproximationScale(aScale);
data->UpdateGObject(id, path);
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::DBFromJson(const QJsonObject &dbObject, QSharedPointer<VContainer> &data)
{
const QString itemsKey = QStringLiteral("items");
if (dbObject.contains(itemsKey))
{
QJsonArray items = dbObject[itemsKey].toArray();
for (auto item : items)
{
QJsonObject itemObject = item.toObject();
GOType objectType;
AbstractTest::ReadDoubleValue(itemObject, QStringLiteral("type"), objectType);
switch (objectType)
{
case GOType::Point:
{
VPointF point;
PointFromJson(itemObject, point);
data->UpdateGObject(point.id(), new VPointF(point));
break;
}
case GOType::Spline:
SplineFromJson(itemObject, data);
break;
case GOType::SplinePath:
SplinePathFromJson(itemObject, data);
break;
default:
{
const QString error =
QStringLiteral("Not supported item type '%1'.").arg(static_cast<int>(objectType));
QFAIL(qUtf8Printable(error));
}
}
}
}
else
{
const QString error = QStringLiteral("DB json object does not contain items.");
QFAIL(qUtf8Printable(error));
}
}
//---------------------------------------------------------------------------------------------------------------------
void AbstractTest::MainPathFromJson(const QJsonObject &pieceObject, VPiece &piece)
{
qreal saWidth = 0;
AbstractTest::ReadDoubleValue(pieceObject, QStringLiteral("saWidth"), saWidth);
bool seamAllowance = false;
AbstractTest::ReadBooleanValue(pieceObject, QStringLiteral("seamAllowance"), seamAllowance);
piece.SetSeamAllowance(seamAllowance);
piece.SetSAWidth(saWidth);
piece.GetPath().Clear();
const QString nodesKey = QStringLiteral("nodes");
if (pieceObject.contains(nodesKey))
{
QJsonArray nodes = pieceObject[nodesKey].toArray();
for (int i = 0; i < nodes.size(); ++i)
{
QJsonObject itemObject = nodes[i].toObject();
VPieceNode node;
ReadPieceNodeValue(itemObject, node);
piece.GetPath().Append(node);
}
}
else
{
const QString error = QStringLiteral("Piece json object does not contain nodes.");
QFAIL(qUtf8Printable(error));
}
} |
#ifndef BST_H
#define BST_H
#include <iomanip>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
template <class TKey> class bst {
struct node {
node(int = 0);
void print();
TKey key;
int ID;
// parent info
node *pLink;
node *link[2];
};
public:
class iterator {
public:
// default constructor (no argument)
iterator() { p = NULL; }
iterator *operator++();
bool operator==(const iterator &other) const { return (other.p == p); }
TKey operator*() { return p->key; }
private:
friend class bst<TKey>;
iterator(node *start) { p = start; }
node *p;
};
iterator begin() {
iterator T;
T.p = Troot;
while (T.p->link[0])
T.p = T.p->link[0];
return T;
}
iterator end() { return iterator(); }
bst() {
Troot = NULL;
nodeID = 1;
}
~bst() { clear(Troot); }
bool empty() { return Troot == NULL; }
void insert(TKey &);
void print_bylevel();
private:
void clear(node *);
node *insert(node *, TKey &);
// ID parameter
int nodeID;
node *Troot;
};
// bst<TKey>::node constructor goes here
template <class TKey> bst<TKey>::node::node(int id) {
ID = id;
pLink = nullptr;
link[0] = nullptr;
link[1] = nullptr;
}
template <class TKey> void bst<TKey>::node::print() {
cout << ID;
cout << setw(3) << key << " :";
if (pLink)
cout << "P=" << setw(3) << pLink->ID;
else
cout << "ROOT ";
// output node and parent ID information
// change below to output subtree ID information
if (link[0])
cout << " L=" << setw(3) << link[0]->ID;
else
cout << " ";
if (link[1])
cout << " R=" << setw(3) << link[1]->ID;
else
cout << " ";
cout << "\n";
}
// specialized string version of the above goes here
template <> void bst<string>::node::print() {
cout << ID;
cout << setw(20) << key << " :";
if (pLink)
cout << "P=" << setw(3) << pLink->ID;
else
cout << "ROOT ";
// output node and parent ID information
// change below to output subtree ID information
if (link[0])
cout << " L=" << setw(3) << link[0]->ID;
else
cout << " ";
if (link[1])
cout << " R=" << setw(3) << link[1]->ID;
else
cout << " ";
cout << "\n";
}
// bst<TKey>::iterator functions not defined above go here
template <class TKey> void bst<TKey>::clear(node *T) {
if (T) {
clear(T->link[0]);
clear(T->link[1]);
delete T;
T = NULL;
}
}
template <class TKey> void bst<TKey>::insert(TKey &key) {
Troot = insert(Troot, key);
}
template <class TKey>
class bst<TKey>::node *bst<TKey>::insert(node *T, TKey &key) {
// set parent link below
if (T == NULL) {
// update and set node ID
T = new node(nodeID++);
T->key = key;
} else if (T->key == key) {
;
} else if (key < T->key) {
T->link[0] = insert(T->link[0], key);
T->link[0]->pLink = T;
} else {
T->link[1] = insert(T->link[1], key);
T->link[1]->pLink = T;
}
return T;
}
template <class TKey>
class bst<TKey>::iterator *bst<TKey>::iterator::operator++() {
// If no right branch, go up and return that parent.
// If there's a right branch, take it, then go to the leftmost point from
// there
if (!(p->link[1])) {
if (!p->pLink) {
p = NULL;
return this;
}
while (p == p->pLink->link[1]) {
p = p->pLink;
if (!p->pLink)
break;
if (p == p->pLink->link[1] && p->pLink->pLink == NULL) {
p = NULL;
return this;
}
}
p = p->pLink;
}
// if(!(p->link[1]))
else {
p = p->link[1];
while (p->link[0])
p = p->link[0];
}
return this;
}
template <class TKey>
void bst<TKey>::print_bylevel() {
if (Troot == NULL)
return;
queue<node *> Q;
node *T;
Q.push(Troot);
while (!Q.empty()) {
T = Q.front();
Q.pop();
T->print();
if (T->link[0])
Q.push(T->link[0]);
if (T->link[1])
Q.push(T->link[1]);
}
}
#endif |
=== GoUrl WooCommerce - Bitcoin Altcoin Payment Gateway Addon ===
Contributors: gourl, GoUrl.io
Plugin Name: GoUrl WooCommerce - Bitcoin Altcoin Payment Gateway Addon. White Label Solution
Plugin URI: https://gourl.io/bitcoin-payments-woocommerce.html
Author URI: https://gourl.io
Tags: woocommerce, bitcoin, accept bitcoin, bitcoin payments, bitcoin woocommerce, bitcoin wordpress plugin, bitcoin wordpress, bitcoincash, bitcoin cash, bitcoinsv, bitcoins, gourl, cryptocurrency, btc, coinbase, bitpay, ecommerce, bitcoin sv, white label, paypal, accept bitcoin, shop, payment, payment gateway, litecoin, dogecoin, dash, speedcoin, vertcoin, reddcoin, feathercoin, potcoin, peercoin
Requires at least: 3.5
Tested up to: 5.6
Stable Tag: 1.3.8
License: GNU Version 2 or Any Later Version
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Provides Bitcoin/Altcoin Payment Gateway for WooCommerce 2.1+ or higher. White Label Product. Accept Bitcoin, Bitcoin Cash, Bitcoin SV, Litecoin, Dash, Dogecoin, etc Payments on Your Website
== Description ==
**[SEE INSTRUCTION](https://tishonator.com/blog/how-to-add-bitcoin-payment-to-your-woocommerce-store) and [Forum](https://bitcointalk.org/index.php?topic=1043437.0) - START YOUR OWN FREE BITCOIN SHOP IN 10 MINUTES** - Bitcoin/Paypal Payments in WordPress/WooCommerce.
[Screenshots](https://gourl.io/bitcoin-payments-woocommerce.html#screenshot)
Bitcoin/Altcoin Plugin for WooCommerce Features -
* 100% Free Open Source Plugin on [Github.com](https://github.com/cryptoapi/Bitcoin-Payments-Woocommerce)
* Provides a Cryptocurrency Payment Gateway for [WooCommerce 2.1 or higher](https://wordpress.org/plugins/woocommerce/)
* No Monthly Fee, No Bank Account Needed, Transaction Fee from 0%
* No Chargebacks, Global, Secure. All in automatic mode.
* NEW!!! SUPPORT WooCommerce Subscriptions 3 (free plugin on [Github](https://github.com/wp-premium/woocommerce-subscriptions))
* Accept Bitcoin, BitcoinCash, BitcoinSV, Litecoin, Dash, Dogecoin, Speedcoin, Reddcoin, Potcoin, Feathercoin, Vertcoin, Peercoin, MonetaryUnit payments in WooCommerce
* Mobile Friendly customizable Payment Box; Direct Integration on your website, no external payment pages opens (as other payment gateways offer)
* White Label Solution with Your Logo ([see Demo](https://gourl.io/lib/examples/box_only.php)) - user browser receive payment data from your server/website only; your server receive data from our server.
* Display additional crypto price with fiat price on the WooCommerce product page ([screenshot](https://gourl.io/images/woocommerce/screenshot-8.png))
* Get crypto payments straight to your bitcoin/altcoin wallet addresses. [Read here](https://gourl.io/#usd) how to convert cryptocurrency to USD/EUR/etc
* Live Exchange Rates with additional Exchange Rate Multiplier (i.e. 1.05 - will add extra 5% to the total price in bitcoins)
* If you intend plugin to be used in a language other than English, see the [Language Translations page](https://gourl.io/languages.html)
* [Free Tech Support](https://gourl.io/view/contact/Contact_Us.html) for You
.
= Three GoUrl Payment Integration Options for WooCommerce - =
* Standard Way - Product prices in USD/EUR/GBP/etc and use GoUrl Bitcoin/Altcoin Gateway together with paypal/credit card gateways
* You set product prices in USD/EUR/etc in the admin panel, and display those prices in Bitcoins for front-end users ([demo](https://gourl.io/images/woocommerce/woocommerce-usd-btc.html))
* You set product prices in Bitcoin/Altcoin directly
.
Plugin Page: [https://gourl.io/bitcoin-payments-woocommerce.html](https://gourl.io/bitcoin-payments-woocommerce.html)
Twitter: [https://twitter.com/CryptocoinAPI](https://twitter.com/CryptocoinAPI)
Github: [https://github.com/cryptoapi/Bitcoin-Payments-Woocommerce](https://github.com/cryptoapi/Bitcoin-Payments-Woocommerce)
== Installation ==
= Requirements =
You need to install also -
* [WooCommerce Plugin](https://wordpress.org/plugins/woocommerce/)
* [GoUrl Main Wordpress Gateway Plugin](https://wordpress.org/plugins/gourl-bitcoin-payment-gateway-paid-downloads-membership/)
= Automatic installation =
Automatic installation is the easiest option as WordPress handles the file transfers itself and you don't need to leave your web browser. To do an automatic install of GoUrl Bitcoin/Altcoin Gateway for WooCommerce, log in to your WordPress dashboard, navigate to the Plugins menu and click Add New.
In the search field type "GoUrl WooCommerce" and click Search Plugins. Once you've found our plugin you can view details about it such as the the rating and description. Most importantly, of course, you can install it by simply clicking Install Now.
= Manual Installation =
* Go to Wordpress Plugins > Add New
* Click Upload Plugin Zip File
* Upload the zipped gourl_wordpress file and click "Upload Now"
* Go to Installed Plugins
* Activate the "GoUrl WooCommerce - Bitcoin Altcoin Payment Gateway Addon"
== Screenshots ==
1. Bitcoin/Altcoin Payments Gateway for WooCommerce - Options
2. WooCommerce Checkout Page
3. WooCommerce Bitcoin Payment Page
4. Bitcoin Payment for WooCommerce Received Successfully
5. WooCommerce Edit Order Page
6. Optional - Display or use product prices in Bitcoin/Altcoin directly
== Changelog ==
= 1.3.8 =
* Compatible with WooCommerce 4.9
= 1.3.7 =
* Compatible with WooCommerce 4.7
= 1.3.6 =
Minor updates
= 1.3.5 =
* Compatible with WooCommerce 4.2
= 1.3.4 =
* Compatible with Woocommerce Subscriptions Free Trial option
= 1.3.3 =
Minor updates
= 1.3.2 =
Minor updates
= 1.3.1 =
* Compatible with WooCommerce 4.0
= 1.3.0 =
* Several new enhancements
* Added Albanian Language (Thanks to Meso J.)
* Added Czech Language (Thanks to Kneebo T.)
* Added Estonian Language (Thanks to Aimar)
* Added Finnish Language (Thanks to Rami V.)
* Added Greek Language (Thanks to Charalampos P, Bay)
* Added Serbian Language (Thanks to Nikola L.)
* Added Slovenian Language (Thanks to Grega J.)
* Added Swedish Language (Thanks to Jack)
= 1.2.8 =
Added support currencyconverterapi.com free/premium keys
= 1.2.7 =
Added Bitcoin Cash logos
= 1.2.6 =
Minor updates
= 1.2.5 =
* Added Bitcoin SV (BSV/BCHSV)
* Tested on Wordpress 5.0. Recommended Update
= 1.2.4 =
Update live exchange rates websites
= 1.2.3 =
Woocommerce Subscriptions support
Display crypto price with fiat price on the WooCommerce product pages
= 1.2.2 =
Added Mobile Friendly Payment Box
= 1.2.1 =
Minor updates
= 1.2.0 =
Fully Compatible with WooCommerce 3.x+
= 1.1.12 =
* Added Bitcoin Cash (BCH / BCC)
= 1.1.11 =
Minor updates
= 1.1.10 =
* Added Italian Language (Thanks to Lorenzo)
= 1.1.8 =
* Added Japanese Language (Thanks to Takiko)
* Added Indonesian Language (Thanks to Tejo)
* Added Polish Language (Thanks to Kacper)
= 1.1.7 =
* Added Korean Language (Thanks to Arthur)
* Added Portuguese Language (Thanks to Miguel)
* Minor updates
= 1.1.6 =
* Added German Language (Thanks to Sebastian, Julius)
* Added Persian Language (Thanks to Kaveh, Ali-Mehdi)
* Enables iranian Rials in WooCommerce
= 1.1.5 =
Add MonetaryUnit [MUE] cryptocurrency
= 1.1.4 =
* Localisation - You can easy change/localize any text in plugin
* Add Bulgarian translation (Thanks to Velcho)
= 1.1.2 =
Three GoUrl Payment Integration Options for WooCommerce:
* Standard Way - Product prices in USD/EUR/GBP/etc and use GoUrl Bitcoin/Altcoin Gateway together with paypal/credit card gateways.
* You set product prices in USD/EUR/etc in the admin panel, and display those prices in Bitcoins for front-end users.
* You set product prices in Bitcoin/Altcoin directly.
= 1.1.0 =
* Add Peercoin [PPC] cryptocurrency
* Add Spanish Payment Box translation (Thanks to Alberto)
= 1.0.5 =
Customize payment box style
= 1.0.4 =
Customize payment logo
= 1.0.1 =
Minor updates
= 1.0.0 =
Initial Release |
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="/bjc-r/llab/loader.js"></script>
<title>Unidad 8 Laboratorio 4: Construir funciones de orden superior, Página 2</title>
</head>
<body>
<h2>Generalizar el modelo <code>mapear</code></h2>
<div class="learn">
<p><strong>En esta página</strong>, generalizarás el patrón del código que has estado explorando para conocer otros problemas en que este patrón de código puede aplicarse.</p>
</div>
<p>
Aquí hay una versión del código para cada bloque de la página anterior.<br />
<img class="indent" src="/bjc-r/img/8-recursive-reporters/plurals.es.png"
alt="plurales (palabras){si(¿vacío?(palabras)){reportar(lista{})}sino{reportar(unir(elemento(1) de (palabras) (s) delante de (plurales(todas menos la primera(palabras))))}}"
title="plurales (palabras){si(¿vacío?(palabras)){reportar(lista{})}sino{reportar(unir(elemento(1) de (palabras) (s) delante de (plurales(todas menos la primera(palabras))))}}" />
<div class="sidenote">
Tu bloque <code>palabra exagerada</code> puede verse muy diferente, pero aquí hay una versión:<br />
<img src="/bjc-r/img/8-recursive-reporters/exaggerate-word.es.png"
alt="palabra exagerada (palabra){si(es (palabra) un (número)?){reportar(2*palabra)}; si(palabra=bueno){reportar(excelente)}; si(palabra=malo){reportar(terrible)}; si(palabra=me gusta){reportar(me encanta)}; si(palabra=no me gusta){reportar(lo odio)}; reportar(palabra)}"
title="palabra exagerada (palabra){si(es (palabra) un (número)?){reportar(2*palabra)}; si(palabra=bueno){reportar(excelente)}; si(palabra=malo){reportar(terrible)}; si(palabra=me gusta){reportar(me encanta)}; si(palabra=no me gusta){reportar(lo odio)}; reportar(palabra)}" />
</div>
<img class="indent" src="/bjc-r/img/8-recursive-reporters/squares.es.png"
alt="raíz cuadrada(números){si(¿vacío?(números)){reportar(lista{})}sino{(elemento(1)de(números)*elemento(1)de(números)) delante de (raíz cuadrada(todos menos el primero(números))))}}"
title="raíz cuadrada(números){si(¿vacío?(números)){reportar(lista{})}sino{(elemento(1)de(números)*elemento(1)de(números)) delante de (raíz cuadrada(todos menos el primero(números))))}}" /><br />
<img class="indent" src="/bjc-r/img/8-recursive-reporters/exaggerate-wordlist.es.png"
alt="exagerar lista de palabras(palabras){si(¿vacío? (palabras)){reportar(lista vacía)}sino{reportar((exagerar palabra(elemento(1) de (palabras))) delante de (exagerar lista de palabras(todas menos la primera (palabras))))}}"
title="exagerar lista de palabras(palabras){si(¿vacío? (palabras)){reportar(lista vacía)}sino{reportar((exagerar palabra(elemento(1) de (palabras))) delante de (exagerar lista de palabras(todas menos la primera (palabras))))}}" />
</p>
<p>
Los bloques <code>plurales</code>, <code>raíz cuadrada</code> y <code>lista de palabras exagerada</code> parecen casi idénticos. La única diferencia es la parte circular de arriba: la función particular que se aplica al <code>elemento 1 de</code> la lista de entrada. Aquí tienes una generalización del patrón:<br />
</p>
<img class="indent" src="/bjc-r/img/8-recursive-reporters/map-start.es.png"
alt="definición de mapear sin la función de llamar: mapear (función) sobre (datos){si (¿vací? (datos)){reportar(lista vacío)} sino{reportar(() delante de (mapear(función) sobre(todos menos el primero (datos))))}}"
title="definición de mapear sin la función de llamar: mapear (función) sobre (datos){si (¿vací? (datos)){reportar(lista vacío)} sino{reportar(() delante de (mapear(función) sobre(todos menos el primero (datos))))}}" />
<p>Pero, ¿qué ponemos en la primera ranura de entrada de <code>delante de</code>?</p>
<p>
Hay dos pequeños detalles que tienes que aprender para terminar esta definición. La primera es que la entrada <code>función</code> tiene que ser un reportero. Ya sabe cómo configurar una entrada para que sea de un tipo específico. Establecer esto como reportero no es diferente:<br />
<img class="indent" src="/bjc-r/img/8-recursive-reporters/reporter-type.es.png" alt="declaración de tipo reportero" title="declaración de tipo reportero" />
</p>
<p>La letra griega λ que aparece en el Editor de bloques junto a la palabra <code>función</code> en el óvalo naranja es un recordatorio de tipo, al igual que el ︙para las listas.</p>
<p>
Ahora debes saber cómo aplicar la función al <code>elemento 1 de datos</code>. Busca el bloque <code>llamar</code> en la paleta Control y haz clic en su punta de flecha derecha para darle una segunda ranura de entrada. Luego complétalo así:<br />
<img class="indent" src="/bjc-r/img/8-recursive-reporters/map.es.png"
alt="definición de mapear: mapear (función lambda) sobre (datos){si (¿vacío? (datos)){reportar(lista vacío)} sino{reportar((llamar(función) con entradas (elemento(1) de (datos))) delante de (mapear(función) sobre(todo menos el primero (datos))))}}"
title="definición de mapear: mapear (función lambda) sobre (datos){si (¿vacío? (datos)){reportar(lista vacío)} sino{reportar((llamar(función) con entradas (elemento(1) de (datos))) delante de (mapear(función) sobre(todo menos el primero (datos))))}}" />
</p>
<p>¡Eso es todo! ¡Has escrito <code>mapear</code>, una función de orden superior!</p>
<p>El bloque <code>llamar</code> encuentra ranuras de entrada vacías en su entrada de función y las llena con los valores de entrada dados.</p>
<div class="takeNote">Las funciones de orden superior no son difíciles, una vez que comprendes la recursividad y cómo generalizar un procedimiento agregando una entrada. ¡No son nada del otro mundo de escribir! Y son muy potentes al usarlos.</div>
<div class="forYouToDo" id="first">
<ol>
<li>Reconstruye el bloque <code>exagerar</code> usando una llamada a <code>mapear</code>. ¿Qué le sucede a la función ayudante?</li>
<li>
De vez en cuando surge un problema que no <em>exactamente </em>coincide con el modelo <code>mapear</code>, pero se parece. En ese caso, no puedes usar <code>mapear</code>, pero tu comprensión del patrón aún ayuda. He aquí un ejemplo:<br />
<img class="indent" src="/bjc-r/img/8-recursive-reporters/odds.es.png"
alt="elementos impares de (datos){si(¿vacío? (datos)){reportar(lista vacía)} sino{si(¿vacío? (todos menos el primero de (datos))){reportar(datos)} sino{ reportar((elemento(1) de (datos)) delante de (elementos impares de(todos menos el primero de (todos menos el primero de (datos)))))}}}"
title="elementos impares de (datos){si(¿vacío? (datos)){reportar(lista vacía)} sino{si(¿vacío? (todos menos el primero de (datos))){reportar(datos)} sino{ reportar((elemento(1) de (datos)) delante de (elementos impares de(todos menos el primero de (todos menos el primero de (datos)))))}}}" /><br />
Completa los espacios en blanco: este guion es como el patrón de mapear excepto por ______ (caso base) y _____ (en el caso recursivo).
</li>
<li>
Construye el bloque <code>emparejar</code>:<br />
<img class="indent" src="/bjc-r/img/8-recursive-reporters/pairup.es.png"
alt="emparejar(lista{salta, monte, video, juego}), reportar {saltamonte, montevideo, videojuego}"
title="emparejar(lista{salta, monte, video, juego}), reportar {saltamonte, montevideo, videojuego}" />
</li>
</ol>
</div>
</body>
</html> |
import { IsNotEmpty, MinLength } from 'class-validator';
import { Field } from '../decorators/Field';
import { ErrorMessages } from '../lib/errors/ErrorMessage';
import { createErrorMessageOption } from '../lib/errors/createErrorMessage';
export class ResetPasswordRequestDto {
@IsNotEmpty({ message: 'Missing reset password token!' })
public token!: string;
@IsNotEmpty({ message: 'Missing reset password email!' })
public email!: string;
@IsNotEmpty(createErrorMessageOption(ErrorMessages.ShouldNotBeEmpty, 'Password'))
@MinLength(8, createErrorMessageOption(ErrorMessages.ShouldHaveAtLeastNCharacters, 'Password', '8'))
public password!: string;
@IsNotEmpty(createErrorMessageOption(ErrorMessages.ShouldNotBeEmpty, 'Password confirmation'))
@MinLength(8, createErrorMessageOption(ErrorMessages.ShouldHaveAtLeastNCharacters, 'Password confirmation', '8'))
@Field('passwordConfirmation', { toPlainOnly: true })
public passwordConfirmation!: string;
} |
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<title>loadeo {% block title %}{% endblock %}</title>
</head>
<body>
{% if pickups %}
{% for pickup in pickups.all %}
<section id="results">
<div class="container mt-3 mx-auto">
<div class="body-container mt-md-3">
<div class="row">
<div class="col-md-12">
<h5 class="text-uppercase font-weight-bold">Tracking ID: <span id="parcel_id">{{ pickup.trackingid }}</span></h5>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="card bg-primary text-dark">
<div class="card-body">
<h6 class="font-weight-bold">SHIPMENT DATE</h6>
</div>
<div class="table-responsive">
<table class="table">
<tbody>
<tr class="table-secondary">
<td>Estimated Date of Departure (ETD)</td>
<td><span id="departure_date">{{ pickup.Estimated_Date_of_Departuer }}</span></td>
</tr>
<tr class="table-secondary">
<td>Estimated Date of Arrival (ETA)</td>
<td><span id="arrival_day">{{ pickup.Estimated_Date_of_Arrival }}</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card bg-primary text-dark">
<div class="card-body">
<h6 class="font-weight-bold">SHIPMENT DETAILS</h6>
</div>
<div class="table-responsive">
<table class="table">
<tbody>
<tr class="table-secondary">
<td>From</td>
<td><span id="cur_location">{{ pickup.From }}</span></td>
</tr>
<tr class="table-secondary">
<td>To</td>
<td><span id="recepient_country">{{ pickup.To }}</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-md-6">
<div class="card bg-primary text-dark">
<div class="card-body">
<h6 class="font-weight-bold">SENDER'S DETAILS</h6>
</div>
<div class="table-responsive">
<table class="table">
<tbody>
<tr class="text-capitalize table-secondary">
<td>Name</td>
<td><span id="sender">{{ pickup.Sender_Name }}</span></td>
</tr>
<tr class="text-capitalize table-secondary">
<td>Origin</td>
<td><span id="logistic">{{ pickup.Sender_Origin }}</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card bg-primary text-dark">
<div class="card-body">
<h6 class="font-weight-bold">RECEIVER'S DETAILS</h6>
</div>
<div class="table-responsive">
<table class="table">
<tbody>
<tr class="text-capitalize table-secondary">
<td>Name</td>
<td><span id="recepient">{{ pickup.Reciver_Name }}</span></td>
</tr>
<tr class="text-capitalize table-secondary">
<td>Email</td>
<td><span id="recepient_email">{{ pickup.Reciver_Email }}</span></td>
</tr>
<tr class="text-capitalize table-secondary">
<td>Phone</td>
<td><span id="tel">{{ pickup.Reciver_Phone }}</span></td>
</tr>
<tr class="text-capitalize table-secondary">
<td>Address</td>
<td><span id="recepient_address">{{ pickup.Reciver_Address }}</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-md-12">
<div class="card bg-primary text-dark">
<div class="card-body">
<h6 class="font-weight-bold">SHIPPING DETAILS</h6>
</div>
<div class="row">
<div class="col-md-6">
<div class="table-responsive">
<table class="table">
<tbody>
<tr class="text-capitalize table-secondary">
<td>Item Description</td>
<td><span id="descr">{{ pickup.Item_Description }}</span></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-6">
<div class="table-responsive">
<table class="table">
<tbody>
<tr class="text-capitalize table-secondary">
<td>Weight and Dimension</td>
<td><span id="weight">{{ pickup.Weight_And_Dimension }}</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-md-12">
<div class="card bg-primary text-dark">
<div class="card-body">
<h6 class="font-weight-bold">TRAVEL TIMELINE</h6>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr class="table-secondary">
<th>Date</th>
<th>Time</th>
<th>Activity</th>
<th>Location</th>
</tr>
</thead>
<tbody id="logs_table">
{% for timeline in pickup.timeline.all %}
<tr class="text-capitalize">
<td>{{ timeline.Date }}</td>
<td>{{ timeline.Time }}</td>
<td>{{ timeline.Activity }}</td>
<td>{{ timeline.Location }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{% endfor %}
{% else %}
<div class="container">
<h4>Enter a Valid Tracking ID</h4>
</div>
{% endif %}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</body>
</html> |
package productsapi.api.rest.adapters.endpoints;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import productsapi.domain.model.Product;
import productsapi.domain.model.enums.Status;
import productsapi.domain.service.ProductServiceUseCase;
import java.math.BigDecimal;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class ProductControllerIT {
@Autowired
private MockMvc mockMvc;
@Mock
private ProductServiceUseCase productServiceUseCase;
@Autowired
private ObjectMapper objectMapper;
Product product;
@BeforeEach
void setUp() {
product = new Product("1", "Product Test", BigDecimal.valueOf(100), Status.ENABLED.ENABLED);
}
@Test
void givenValidProduct_whenCreateProduct_thenReturnsSuccessfully() throws Exception {
//when
Mockito.when(productServiceUseCase.create(anyString(), any())).thenReturn(product);
String jsonCreated = "{\"name\":\"Product Test\",\"price\":100}";
//act //verify
mockMvc.perform(post("/products")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonCreated))
.andExpect(status().isCreated());
}
@Test
void givenValidProduct_whenFindById_thenReturnsSuccessfully() throws Exception {
Mockito.when(productServiceUseCase.get(anyString())).thenReturn(product);
Mockito.when(productServiceUseCase.create(anyString(), any())).thenReturn(product);
String jsonCreated = "{\"name\":\"Product Test\",\"price\":100}";
MvcResult result = mockMvc.perform(post("/products")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonCreated))
.andExpect(status().isCreated())
.andReturn();
// Extrai o conteúdo da resposta
String contentAsString = result.getResponse().getContentAsString();
// Converte a resposta em um objeto Product
Product createdProduct = objectMapper.readValue(contentAsString, Product.class);
// Usa o ID do produto criado para a requisição GET
mockMvc.perform(get("/products/{id}", createdProduct.getId())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(objectMapper.writeValueAsString(createdProduct)));
}
@Test
void givenValidProduct_whenDisabled_thenReturnsSuccessfully() throws Exception {
Mockito.when(productServiceUseCase.get(anyString())).thenReturn(product);
Mockito.when(productServiceUseCase.create(anyString(), any())).thenReturn(product);
String jsonCreated = "{\"name\":\"Product Test\",\"price\":100}";
MvcResult result = mockMvc.perform(post("/products")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonCreated))
.andExpect(status().isCreated())
.andReturn();
String contentAsString = result.getResponse().getContentAsString();
Product createdProduct = objectMapper.readValue(contentAsString, Product.class);
createdProduct.disable();
mockMvc.perform(patch("/products/{productId}/disabled", createdProduct.getId())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(objectMapper.writeValueAsString(createdProduct)));
}
@Test
void givenValidProduct_whenEnabled_thenReturnsSuccessfully() throws Exception {
Mockito.when(productServiceUseCase.get(anyString())).thenReturn(product);
Mockito.when(productServiceUseCase.create(anyString(), any())).thenReturn(product);
String jsonCreated = "{\"name\":\"Product Test\",\"price\":100}";
String jsonEnabled = "{\"price\":100}";
MvcResult result = mockMvc.perform(post("/products")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonCreated))
.andExpect(status().isCreated())
.andReturn();
String contentAsString = result.getResponse().getContentAsString();
Product createdProduct = objectMapper.readValue(contentAsString, Product.class);
mockMvc.perform(patch("/products/{productId}/enabled", createdProduct.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(jsonEnabled))
.andExpect(status().isOk())
.andExpect(content().json(objectMapper.writeValueAsString(createdProduct)));
}
} |
// This module contains integration tests for the my_encryption_lib crate.
#[cfg(test)]
mod integration_tests {
// Importing the modules from the library to test.
use my_encryption_lib::{mel_presets, mel_912, mel_mdp};
// Tests for the mel_1 function from mel_presets module.
#[test]
fn test_mel_1() {
// Encrypting "abc" with a shift of 1 should result in "bcd".
assert_eq!(mel_presets::mel_1("abc", true).unwrap(), "bcd");
// Decrypting "bcd" with a shift of 1 should result in "abc".
assert_eq!(mel_presets::mel_1("bcd", false).unwrap(), "abc");
// Testing accented characters and special symbols with mel_1.
assert_eq!(mel_presets::mel_1("à mangé forêt !? ë", true).unwrap(), "b nbohf gpsfu !? f");
assert_eq!(mel_presets::mel_1("b nbohf gpsfu !? f", false).unwrap(), "a mange foret !? e");
// Testing error handling for empty strings.
assert!(mel_presets::mel_1("", true).is_err());
assert!(mel_presets::mel_1("", false).is_err());
}
// Similar tests are conducted for mel_2 to mel_25 functions, each using a different shift value.
#[test]
fn test_mel_2() {
assert_eq!(mel_presets::mel_2("abc", true).unwrap(), "cde");
assert_eq!(mel_presets::mel_2("cde", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_2("à mangé forêt !? ë", true).unwrap(), "c ocpig hqtgv !? g");
assert_eq!(mel_presets::mel_2("c ocpig hqtgv !? g", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_2("", true).is_err());
assert!(mel_presets::mel_2("", false).is_err());
}
#[test]
fn test_mel_3() {
assert_eq!(mel_presets::mel_3("abc", true).unwrap(), "def");
assert_eq!(mel_presets::mel_3("def", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_3("à mangé forêt !? ë", true).unwrap(), "d pdqjh iruhw !? h");
assert_eq!(mel_presets::mel_3("d pdqjh iruhw !? h", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_3("", true).is_err());
assert!(mel_presets::mel_3("", false).is_err());
}
#[test]
fn test_mel_4() {
assert_eq!(mel_presets::mel_4("abc", true).unwrap(), "efg");
assert_eq!(mel_presets::mel_4("efg", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_4("à mangé forêt !? ë", true).unwrap(), "e qerki jsvix !? i");
assert_eq!(mel_presets::mel_4("e qerki jsvix !? i", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_4("", true).is_err());
assert!(mel_presets::mel_4("", false).is_err());
}
#[test]
fn test_mel_5() {
assert_eq!(mel_presets::mel_5("abc", true).unwrap(), "fgh");
assert_eq!(mel_presets::mel_5("fgh", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_5("à mangé forêt !? ë", true).unwrap(), "f rfslj ktwjy !? j");
assert_eq!(mel_presets::mel_5("f rfslj ktwjy !? j", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_5("", true).is_err());
assert!(mel_presets::mel_5("", false).is_err());
}
#[test]
fn test_mel_6() {
assert_eq!(mel_presets::mel_6("abc", true).unwrap(), "ghi");
assert_eq!(mel_presets::mel_6("ghi", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_6("à mangé forêt !? ë", true).unwrap(), "g sgtmk luxkz !? k");
assert_eq!(mel_presets::mel_6("g sgtmk luxkz !? k", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_6("", true).is_err());
assert!(mel_presets::mel_6("", false).is_err());
}
#[test]
fn test_mel_7() {
assert_eq!(mel_presets::mel_7("abc", true).unwrap(), "hij");
assert_eq!(mel_presets::mel_7("hij", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_7("à mangé forêt !? ë", true).unwrap(), "h thunl mvyla !? l");
assert_eq!(mel_presets::mel_7("h thunl mvyla !? l", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_7("", true).is_err());
assert!(mel_presets::mel_7("", false).is_err());
}
#[test]
fn test_mel_8() {
assert_eq!(mel_presets::mel_8("abc", true).unwrap(), "ijk");
assert_eq!(mel_presets::mel_8("ijk", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_8("à mangé forêt !? ë", true).unwrap(), "i uivom nwzmb !? m");
assert_eq!(mel_presets::mel_8("i uivom nwzmb !? m", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_8("", true).is_err());
assert!(mel_presets::mel_8("", false).is_err());
}
#[test]
fn test_mel_9() {
assert_eq!(mel_presets::mel_9("abc", true).unwrap(), "jkl");
assert_eq!(mel_presets::mel_9("jkl", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_9("à mangé forêt !? ë", true).unwrap(), "j vjwpn oxanc !? n");
assert_eq!(mel_presets::mel_9("j vjwpn oxanc !? n", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_9("", true).is_err());
assert!(mel_presets::mel_9("", false).is_err());
}
#[test]
fn test_mel_10() {
assert_eq!(mel_presets::mel_10("abc", true).unwrap(), "klm");
assert_eq!(mel_presets::mel_10("klm", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_10("à mangé forêt !? ë", true).unwrap(), "k wkxqo pybod !? o");
assert_eq!(mel_presets::mel_10("k wkxqo pybod !? o", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_10("", true).is_err());
assert!(mel_presets::mel_10("", false).is_err());
}
#[test]
fn test_mel_11() {
assert_eq!(mel_presets::mel_11("abc", true).unwrap(), "lmn");
assert_eq!(mel_presets::mel_11("lmn", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_11("à mangé forêt !? ë", true).unwrap(), "l xlyrp qzcpe !? p");
assert_eq!(mel_presets::mel_11("l xlyrp qzcpe !? p", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_11("", true).is_err());
assert!(mel_presets::mel_11("", false).is_err());
}
#[test]
fn test_mel_12() {
assert_eq!(mel_presets::mel_12("abc", true).unwrap(), "mno");
assert_eq!(mel_presets::mel_12("mno", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_12("à mangé forêt !? ë", true).unwrap(), "m ymzsq radqf !? q");
assert_eq!(mel_presets::mel_12("m ymzsq radqf !? q", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_12("", true).is_err());
assert!(mel_presets::mel_12("", false).is_err());
}
#[test]
fn test_mel_13() {
assert_eq!(mel_presets::mel_13("abc", true).unwrap(), "nop");
assert_eq!(mel_presets::mel_13("nop", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_13("à mangé forêt !? ë", true).unwrap(), "n znatr sberg !? r");
assert_eq!(mel_presets::mel_13("n znatr sberg !? r", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_13("", true).is_err());
assert!(mel_presets::mel_13("", false).is_err());
}
#[test]
fn test_mel_14() {
assert_eq!(mel_presets::mel_14("abc", true).unwrap(), "opq");
assert_eq!(mel_presets::mel_14("opq", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_14("à mangé forêt !? ë", true).unwrap(), "o aobus tcfsh !? s");
assert_eq!(mel_presets::mel_14("o aobus tcfsh !? s", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_14("", true).is_err());
assert!(mel_presets::mel_14("", false).is_err());
}
#[test]
fn test_mel_15() {
assert_eq!(mel_presets::mel_15("abc", true).unwrap(), "pqr");
assert_eq!(mel_presets::mel_15("pqr", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_15("à mangé forêt !? ë", true).unwrap(), "p bpcvt udgti !? t");
assert_eq!(mel_presets::mel_15("p bpcvt udgti !? t", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_15("", true).is_err());
assert!(mel_presets::mel_15("", false).is_err());
}
#[test]
fn test_mel_16() {
assert_eq!(mel_presets::mel_16("abc", true).unwrap(), "qrs");
assert_eq!(mel_presets::mel_16("qrs", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_16("à mangé forêt !? ë", true).unwrap(), "q cqdwu vehuj !? u");
assert_eq!(mel_presets::mel_16("q cqdwu vehuj !? u", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_16("", true).is_err());
assert!(mel_presets::mel_16("", false).is_err());
}
#[test]
fn test_mel_17() {
assert_eq!(mel_presets::mel_17("abc", true).unwrap(), "rst");
assert_eq!(mel_presets::mel_17("rst", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_17("à mangé forêt !? ë", true).unwrap(), "r drexv wfivk !? v");
assert_eq!(mel_presets::mel_17("r drexv wfivk !? v", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_17("", true).is_err());
assert!(mel_presets::mel_17("", false).is_err());
}
#[test]
fn test_mel_18() {
assert_eq!(mel_presets::mel_18("abc", true).unwrap(), "stu");
assert_eq!(mel_presets::mel_18("stu", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_18("à mangé forêt !? ë", true).unwrap(), "s esfyw xgjwl !? w");
assert_eq!(mel_presets::mel_18("s esfyw xgjwl !? w", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_18("", true).is_err());
assert!(mel_presets::mel_18("", false).is_err());
}
#[test]
fn test_mel_19() {
assert_eq!(mel_presets::mel_19("abc", true).unwrap(), "tuv");
assert_eq!(mel_presets::mel_19("tuv", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_19("à mangé forêt !? ë", true).unwrap(), "t ftgzx yhkxm !? x");
assert_eq!(mel_presets::mel_19("t ftgzx yhkxm !? x", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_19("", true).is_err());
assert!(mel_presets::mel_19("", false).is_err());
}
#[test]
fn test_mel_20() {
assert_eq!(mel_presets::mel_20("abc", true).unwrap(), "uvw");
assert_eq!(mel_presets::mel_20("uvw", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_20("à mangé forêt !? ë", true).unwrap(), "u guhay zilyn !? y");
assert_eq!(mel_presets::mel_20("u guhay zilyn !? y", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_20("", true).is_err());
assert!(mel_presets::mel_20("", false).is_err());
}
#[test]
fn test_mel_21() {
assert_eq!(mel_presets::mel_21("abc", true).unwrap(), "vwx");
assert_eq!(mel_presets::mel_21("vwx", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_21("à mangé forêt !? ë", true).unwrap(), "v hvibz ajmzo !? z");
assert_eq!(mel_presets::mel_21("v hvibz ajmzo !? z", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_21("", true).is_err());
assert!(mel_presets::mel_21("", false).is_err());
}
#[test]
fn test_mel_22() {
assert_eq!(mel_presets::mel_22("abc", true).unwrap(), "wxy");
assert_eq!(mel_presets::mel_22("wxy", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_22("à mangé forêt !? ë", true).unwrap(), "w iwjca bknap !? a");
assert_eq!(mel_presets::mel_22("w iwjca bknap !? a", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_22("", true).is_err());
assert!(mel_presets::mel_22("", false).is_err());
}
#[test]
fn test_mel_23() {
assert_eq!(mel_presets::mel_23("abc", true).unwrap(), "xyz");
assert_eq!(mel_presets::mel_23("xyz", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_23("à mangé forêt !? ë", true).unwrap(), "x jxkdb clobq !? b");
assert_eq!(mel_presets::mel_23("x jxkdb clobq !? b", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_23("", true).is_err());
assert!(mel_presets::mel_23("", false).is_err());
}
#[test]
fn test_mel_24() {
assert_eq!(mel_presets::mel_24("abc", true).unwrap(), "yza");
assert_eq!(mel_presets::mel_24("yza", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_24("à mangé forêt !? ë", true).unwrap(), "y kylec dmpcr !? c");
assert_eq!(mel_presets::mel_24("y kylec dmpcr !? c", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_24("", true).is_err());
assert!(mel_presets::mel_24("", false).is_err());
}
#[test]
fn test_mel_25() {
assert_eq!(mel_presets::mel_25("abc", true).unwrap(), "zab");
assert_eq!(mel_presets::mel_25("zab", false).unwrap(), "abc");
assert_eq!(mel_presets::mel_25("à mangé forêt !? ë", true).unwrap(), "z lzmfd enqds !? d");
assert_eq!(mel_presets::mel_25("z lzmfd enqds !? d", false).unwrap(), "a mange foret !? e");
assert!(mel_presets::mel_25("", true).is_err());
assert!(mel_presets::mel_25("", false).is_err());
}
// Tests for the mel_912 function from mel_912 module.
#[test]
fn test_mel_912() {
// Encrypting and decrypting a string with mel_912 and checking the results.
assert_eq!(mel_912::mel_912("Héllo World!", true).unwrap(), "Qmsrt Arcvm!");
assert_eq!(mel_912::mel_912("Qmsrt Arcvm!", false).unwrap(), "Hello World!");
// Testing error handling for empty strings with mel_912.
assert!(mel_912::mel_912("", true).is_err());
}
// Tests for the mel_mdp function from mel_mdp module.
#[test]
fn test_mel_mdp() {
// Encrypting "Hello World" with password "key" using mel_mdp.
assert_eq!(mel_mdp::mel_mdp("Hello World", "key", true).unwrap(), "Rijvs Uyvjn");
// Testing error handling for empty strings and invalid passwords with mel_mdp.
assert!(mel_mdp::mel_mdp("", "key", true).is_err());
assert!(mel_mdp::mel_mdp("Hello World", "k3y", true).is_err());
}
} |
{% liquid
assign section_anchor_id = section.settings.section_anchor_id | handleize
assign color_scheme = section.settings.color_scheme
assign title = section.settings.title
assign pt_mob = section.settings.pt_mob
assign pb_mob = section.settings.pb_mob
assign pt_tab = section.settings.pt_tab
assign pb_tab = section.settings.pb_tab
assign pt_desk = section.settings.pt_desk
assign pb_desk = section.settings.pb_desk
%}
{% render 'section-paddings',
section_id: section.id,
pt_mob: pt_mob,
pb_mob: pb_mob,
pt_tab: pt_tab,
pb_tab: pb_tab,
pt_desk: pt_desk,
pb_desk: pb_desk
%}
<div
id="{{ section_anchor_id }}"
data-section-id="{{ section.id }}"
class="color-scheme-{{ color_scheme }} bg-sc-bg-primary bg-primary-gradient"
>
<div class="2k:max-w-[1150px] container overflow-hidden xl:max-w-4xl xl:px-8">
{% if title != blank %}
<div
class="animate__animated rte text-sc-title font-primary 2k:text-3xl text-center text-lg font-medium opacity-0 md:text-2xl"
x-intersect="$el.classList.add('animate__fadeInUp')"
>
{{- title -}}
</div>
{% endif %}
</div>
</div>
{% schema %}
{
"name": "Large title",
"tag": "section",
"settings": [
{
"type": "text",
"id": "section_anchor_id",
"label": "Section anchor id",
"default": "Large title"
},
{
"type": "color_scheme",
"id": "color_scheme",
"label": "Color scheme"
},
{
"type": "richtext",
"id": "title",
"label": "Section title",
"default": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>"
},
{
"type": "header",
"content": "Padding Y settings"
},
{
"type": "number",
"id": "pt_mob",
"label": "Mobile padding top in px",
"default": 40
},
{
"type": "number",
"id": "pb_mob",
"label": "Mobile padding bottom in px",
"default": 40
},
{
"type": "number",
"id": "pt_tab",
"label": "Tablet padding top in px",
"default": 60
},
{
"type": "number",
"id": "pb_tab",
"label": "Tablet padding bottom in px",
"default": 60
},
{
"type": "number",
"id": "pt_desk",
"label": "Desktop padding top in px",
"default": 60
},
{
"type": "number",
"id": "pb_desk",
"label": "Desktop padding bottom in px",
"default": 60
}
],
"presets": [
{
"name": "Large title",
"category": "Repeatable"
}
]
}
{% endschema %} |
package com.example.comickufinal.network
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response
import java.util.concurrent.TimeUnit
abstract class OfflineInterceptor : Interceptor {
private val HEADER_CACHE_CONTROL = "Cache-Control"
private val HEADER_PRAGMA = "Pragma"
abstract fun isInternetAvailable(): Int
abstract fun onInternetUnavailable()
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
if (isInternetAvailable() == 0) {
onInternetUnavailable()
val cacheControl = CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build()
request = request.newBuilder()
.removeHeader(HEADER_PRAGMA)
.removeHeader(HEADER_CACHE_CONTROL)
.cacheControl(cacheControl)
.build()
}
return chain.proceed(request)
}
} |
## Énoncé
Contrairement à une boucle *tant que* qui s'arrête sur une condition, une boucle *pour* en Python permet de parcourir un ensemble d'éléments.
Bien que ce type de boucle soit tout à fait intuitif, de nombreuses opérations ont lieu dans notre dos dès lors que l'on l'utilise la construction `for X in Y` en Python.
Ce sont ces opérations cachées qui nous permettent de parcourir à l'aide d'une simple boucle `for` :
- un ensemble de nombres, c'est à dire un `range`, pour obtenir les nombres un à un ;
- une chaîne de caractères pour obtenir les caractères un à un ;
- un tuple pour obtenir les éléments qui le composent un à un ;
- une `list` pour obtenir les éléments qui la composent un à un ;
- un fichier ouvert avec `open` pour obtenir les lignes qu'il contient une par une.
Nous ne rentrerons pas dans le détail des opérations cachées pour le moment.
L'objectif de cet exercice est simplement d'utiliser des boucles `for`.
Écrivez un programme `for.py` affichant un à un les éléments (caractère ou nombre), avec retour à la ligne après chaque élément, contenus dans les variables ci-dessous. Vous utiliserez une boucle, contenant éventuellement une ou deux sous boucle, pour chaque variable.
```python
une_chaine = "123"
une_list = [1, 2, 3]
un_tuple = (1, 2, 3)
un_intervalle = range(1, 4)
une_list_2D = ["toto", range(3), ["t", "o", "t", "o"]]
un_tuple_2D = ([1, 2, 3], [4, 5, 6])
une_liste_3D = [[[1, 2], [3, 4]], [[5, 6]]]
```
Factorisez ensuite votre code en créant 3 fonctions :
- une fonction pour afficher tous les éléments d'une variable à "une dimension" ;
- une fonction pour afficher tous les éléments d'une variable à "deux dimension" ;
- une fonction pour afficher tous les éléments d'une variable à "trois dimensions" ;
## Correction
<details markdown="1">
<summary>Cliquez ici pour révéler la correction.</summary>
`for.py` :
```python
#!/usr/bin/env python3
"""exemples d'utilisation de boucle for"""
# Les variables que l'on souhaite parcourir
une_chaine = "123"
une_list = [1, 2, 3]
un_tuple = (1, 2, 3)
un_intervalle = range(1, 4)
une_list_2D = ["toto", range(3), ["t", "o", "t", "o"]]
un_tuple_2D = ([1, 2, 3], [4, 5, 6])
une_liste_3D = [[[1, 2], [3, 4]], [[5, 6]]]
# Variables à une dimension --> une seule boucle
print("éléments de une_chaine :")
for car in une_chaine:
print(f" {car}")
print("éléments de une_list :")
for nb in une_list:
print(f" {nb}")
print("éléments de un_tuple :")
for nb in un_tuple:
print(f" {nb}")
print("éléments de un_intervalle :")
for nb in un_intervalle:
print(f" {nb}")
# Variables à deux dimensions --> deux boucles
print("éléments de une_list_2D :")
for sous_ensemble in une_list_2D:
for element in sous_ensemble:
print(f" {element}") # l'appel à str est nécessaire, pourquoi ?
print("éléments de un_tuple_2D :")
for sous_ensemble in un_tuple_2D:
for element in sous_ensemble:
print(f" {element}")
# Variable à trois dimensions --> trois boucles
print("éléments de une_liste_3D :")
for sous_ensemble in une_liste_3D:
for sous_sous_ensemble in sous_ensemble:
for element in sous_sous_ensemble:
print(f" {element}")
# Pour factoriser notre code, grace au typage dynamique
# du langage Python, nous pourrions définir des fonctions
# de parcours de dimension donnée
def parcourt_une_dimension(a_parcourir):
"""Parcourt une variable de dimension 1"""
for elem in a_parcourir:
print(f" {elem}")
def parcourt_deux_dimensions(a_parcourir):
"""Parcourt une variable de dimension 2"""
for sous_ens in a_parcourir:
for elem in sous_ens:
print(f" {elem}")
def parcourt_trois_dimensions(a_parcourir):
"""Parcourt une variable de dimension 3"""
for sous_ens in a_parcourir:
for sous_sous_ens in sous_ens:
for elem in sous_sous_ens:
print(f" {elem}")
# Et ensuite utiliser ces fonctions pour afficher à nouveau
# nos variables
# Variables à une dimension --> une seule boucle
print("éléments de une_chaine :")
parcourt_une_dimension(une_chaine)
print("éléments de une_list :")
parcourt_une_dimension(une_list)
print("éléments de un_tuple :")
parcourt_une_dimension(un_tuple)
print("éléments de un_intervalle :")
parcourt_une_dimension(un_intervalle)
# Variables à deux dimensions --> deux boucles
print("éléments de une_list_2D :")
parcourt_deux_dimensions(une_list_2D)
print("éléments de un_tuple_2D :")
parcourt_deux_dimensions(un_tuple_2D)
# Variables à trois dimensions --> trois boucles
print("éléments de une_liste_3D :")
parcourt_trois_dimensions(une_liste_3D)
```
</details> |
package com.example.bmo.adapters
import android.content.Context
import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.bmo.R
import com.example.bmo.pojo.Filter
class NewsFilterAdapter(val items: ArrayList<Filter>, val on_item_click: OnItemClick): RecyclerView.Adapter<NewsFilterAdapter.ViewHolder>() {
private lateinit var context: Context
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val filter_container: LinearLayout = itemView.findViewById(R.id.filter_container)
val filter_category: TextView = itemView.findViewById(R.id.filter_category)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.recycler_item_filter_card, parent, false))
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.apply {
context = filter_category.context
items[position].apply {
filter_category.text = category
filter_container.backgroundTintList =
ColorStateList.valueOf(context.getColor(if (is_chosen) R.color.color_primary_3 else R.color.transparent))
filter_container.setOnClickListener {
is_chosen = !is_chosen
items.filter { item -> item.category != this.category }.forEach { it.is_chosen = false }
on_item_click.on_article_click(position)
notifyDataSetChanged()
}
}
}
}
override fun getItemCount() = items.size
fun item_at(position: Int) = items[position]
} |
//
// CardView.swift
// Movie
//
// Created by Marius Stefanita Jianu on 28.04.2024.
//
import SwiftUI
struct CardView: View {
let movie: Movie
var image: UIImage?
var isFavorite: Bool
var toggleFavorite: () -> Void
var body: some View {
VStack(spacing: 0.0) {
if let image = image {
Image(uiImage: image)
.resizable()
.frame(width: 180, height: 270)
.cornerRadius(5)
} else {
Rectangle()
.fill(Color.gray.opacity(0.3))
.frame(width: 180, height: 270)
.cornerRadius(5)
.overlay(Text("Loading..."))
}
HStack {
Text(movie.releaseDate.prefix(4))
.font(.system(size: 14, weight: .semibold))
Spacer()
HStack {
Image("ic_star")
.frame(width: 14, height: 14)
Text(String(movie.voteAverage).toFormattedNumberString(maxFractionDigits: 1) ?? "")
.font(.system(size: 14, weight: .semibold))
}
Spacer()
Button(action: {
toggleFavorite()
}) {
Image(self.isFavorite ? "ic_add_to_favorites_red" : "ic_add_to_favorites_black")
.frame(width: 14, height: 12.25)
}
}
.padding(.horizontal, 14)
.frame(width: 180, height: 40)
}
.frame(width: 180, height: 310)
.background(.white)
.cornerRadius(5, corners: .allCorners)
}
}
#Preview {
@State var isFavorite = true
return CardView(
movie: Movie(id: 123, voteCount: 1, video: false, voteAverage: 8.6, title: "MR.Robot", popularity: 7.34, posterPath: "", originalLanguage: "English", originalTitle: "English", genreIds: [18,22], backdropPath: "", adult: false, overview: "", releaseDate: "2016-08-28"),
isFavorite: isFavorite,
// Implementăm toggleFavorite pentru a schimba starea de favorit în previzualizare
toggleFavorite: {
isFavorite.toggle()
}
)
} |
import { Component, ComponentFactoryResolver, Input, OnInit, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-widgets',
templateUrl: './widgets.component.html',
styleUrls: ['./widgets.component.scss']
})
export class WidgetsComponent implements OnInit {
loading: boolean = false;
illegalWidget: boolean = false;
constructor(private vcref: ViewContainerRef,private cfr: ComponentFactoryResolver){ }
@Input() widget: any;
@Input() data:any;
async ngOnInit(): Promise<void> {
this.vcref.clear();
this.loading = true;
if (this.widget=='actionButton') {
const { ActionButtonComponent } = await import('./action-button/action-button.component');
const componentFactory = this.cfr.resolveComponentFactory(ActionButtonComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
// await import ('./action-button/action-button.module').then(m => m.ActionButtonModule)
this.loading = false;
} else if (this.widget=='subscribe'){
const { SubscribeComponent } = await import('./subscribe/subscribe.component');
const componentFactory = this.cfr.resolveComponentFactory(SubscribeComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='postCarousel'){
const { PostCarouselComponent } = await import('./post-carousel/post-carousel.component');
const componentFactory = this.cfr.resolveComponentFactory(PostCarouselComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='tagCloud'){
const { TagCloudComponent } = await import('./tag-cloud/tag-cloud.component');
const componentFactory = this.cfr.resolveComponentFactory(TagCloudComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='socialButtons'){
const { SocialButtonsComponent } = await import('./social-buttons/social-buttons.component');
const componentFactory = this.cfr.resolveComponentFactory(SocialButtonsComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='youtubeEmbed'){
const { YoutubeEmbedComponent } = await import('./youtube-embed/youtube-embed.component');
const componentFactory = this.cfr.resolveComponentFactory(YoutubeEmbedComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='twitterFeed'){
const { TwitterFeedComponent } = await import('./twitter-feed/twitter-feed.component');
const componentFactory = this.cfr.resolveComponentFactory(TwitterFeedComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='poll'){
const { PollComponent } = await import('./poll/poll.component');
const componentFactory = this.cfr.resolveComponentFactory(PollComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='survey'){
const { SurveyComponent } = await import('./survey/survey.component');
const componentFactory = this.cfr.resolveComponentFactory(SurveyComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='flashMessage'){
const { FlashMessageComponent } = await import('./flash-message/flash-message.component');
const componentFactory = this.cfr.resolveComponentFactory(FlashMessageComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='calendar'){
const { CalendarComponent } = await import('./calendar/calendar.component');
const componentFactory = this.cfr.resolveComponentFactory(CalendarComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='maps'){
const { MapsComponent } = await import('./maps/maps.component');
const componentFactory = this.cfr.resolveComponentFactory(MapsComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='search'){
const { SearchComponent } = await import('./search/search.component');
const componentFactory = this.cfr.resolveComponentFactory(SearchComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else if (this.widget=='testimonials'){
const { TestimonialsComponent } = await import('./testimonials/testimonials.component');
const componentFactory = this.cfr.resolveComponentFactory(TestimonialsComponent);
const componentRef = this.vcref.createComponent(componentFactory);
componentRef.instance.data = this.widget;
this.loading = false;
} else {
this.illegalWidget = true;
}
}
} |
import {
Animated,
Easing,
Image,
StyleSheet,
Text,
TouchableOpacity,
TouchableWithoutFeedback,
View,
} from 'react-native';
import React, {FC, useEffect, useState} from 'react';
import RatingIcon from './ratingIcon';
interface Props{
value: number;
maximumRating: number;
color: string;
size: number;
onRate?: (n: number)=> void;
readonly?: boolean;
}
const Rating:FC<Props> = ({
value,
maximumRating,
color,
size,
onRate,
readonly,
})=>{
const [animation, setAnimation] = useState(new Animated.Value(1));
const [newRating, setNewRating] = useState(5);
const animate = () => {
Animated.timing(animation, {
toValue: 2.5,
duration: 500,
easing: Easing.ease,
useNativeDriver: true,
}).start(() => {
animation.setValue(1);
});
};
let icons: any = [];
const animateScale = animation.interpolate({
inputRange: [1,1.5,2],
outputRange: [1,1.4,1],
});
const animateOpacity = animation.interpolate({
inputRange: [1,1.2,2],
outputRange: [1,0.5,1],
});
const animateWobble = animation.interpolate({
inputRange:[1,1.25,1.75, 2],
outputRange: ["0deg", "-30deg", "30deg", "0deg"],
});
const animationStyle = {
transform: [{scale: animateScale}, {rotate: animateWobble}],
opacity: animateOpacity,
};
useEffect(()=>{
setNewRating(value);
}, [value]);
for(let x=1; x<=maximumRating; x++){
if(readonly){
icons.push(
<RatingIcon
key = {x}
size = {size}
filled = {x <= newRating ? true : false}
color = {color}
/>
);
}else{
icons.push(
<TouchableWithoutFeedback
key = {x}
onPress = {() => {
if(onRate){
onRate(x)
}
setNewRating(x);
animate();
}}
>
<Animated.View
style = {x <= newRating ? animationStyle : null}
>
<RatingIcon
size = {size}
filled = {x <= newRating ? true: false}
color = {color}
/>
</Animated.View>
</TouchableWithoutFeedback>
);
}
}
return(
<View style={styles.ratingContainer}>
{icons}
</View>
);
};
const styles = StyleSheet.create({
ratingContainer: {
flexDirection: 'row',
},
});
export default Rating; |
import { gql, useMutation, useSubscription } from "@apollo/client";
import GoogleMapReact from "google-map-react";
import { useEffect, useState } from "react";
import { FULL_ORDER_FRAGMENT } from "../../fragments";
import {
CoockedOrdersSubscription,
TakeOrderMutation,
TakeOrderMutationVariables,
} from "../../__api__/types";
import { Link, useHistory } from "react-router-dom";
const COOKED_ORDERS_SUBSCRIPTION = gql`
subscription coockedOrders {
cookedOrders {
...FullOrderParts
}
}
${FULL_ORDER_FRAGMENT}
`;
const TAKE_ORDER_MUTATION = gql`
mutation takeOrder($input: TakeOrderInput!) {
takeOrder(input: $input) {
ok
error
}
}
`;
interface ICoords {
lat: number;
lng: number;
}
interface IDriverProps {
lat: number;
lng: number;
$hover?: any;
}
const Driver: React.FC<IDriverProps> = () => <div className="text-lg">🚗</div>;
export const Dashboard = () => {
const key: string | undefined = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;
const [driverCoords, setDriverCoords] = useState<ICoords>({ lng: 0, lat: 0 });
const [map, setMap] = useState<google.maps.Map>();
const [maps, setMaps] = useState<any>();
const onSuccess = ({
coords: { latitude, longitude },
}: GeolocationPosition) => {
setDriverCoords({ lat: latitude, lng: longitude });
};
const onError = (error: GeolocationPositionError) => {
console.log(error);
};
useEffect(() => {
navigator.geolocation.watchPosition(onSuccess, onError, {
enableHighAccuracy: true,
});
}, []);
useEffect(() => {
if (map && maps) {
map.panTo(new google.maps.LatLng(driverCoords.lat, driverCoords.lng));
const geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
location: new google.maps.LatLng(driverCoords.lat, driverCoords.lng),
},
(results, status) => {
console.log(status, results);
}
);
}
}, [driverCoords]);
/**
*
* @param map 지금 현재 보이는 지도의 정보
* @param maps 지도 전체에서 사용할 수 있는 정보
*/
const onApiLoaded = ({ map, maps }: { map: any; maps: any }) => {
map.panTo(new maps.LatLng(driverCoords.lat, driverCoords.lng));
setMap(map);
setMaps(maps);
};
const makeRoute = () => {
if (map) {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: "#000",
strokeOpacity: 1,
strokeWeight: 3,
},
});
directionsRenderer.setMap(map);
directionsService.route(
{
origin: {
location: new google.maps.LatLng(
driverCoords.lat,
driverCoords.lng
),
},
destination: {
location: new google.maps.LatLng(
driverCoords.lat + 0.05,
driverCoords.lng + 0.05
),
},
travelMode: google.maps.TravelMode.DRIVING,
},
(result, status) => {
directionsRenderer.setDirections(result);
}
);
}
};
const { data: cookedOrderData } = useSubscription<CoockedOrdersSubscription>(
COOKED_ORDERS_SUBSCRIPTION
);
useEffect(() => {
if (cookedOrderData?.cookedOrders.id) {
makeRoute();
}
}, [cookedOrderData]);
const history = useHistory();
const onCompleted = (data: TakeOrderMutation) => {
if (data.takeOrder.ok) {
history.push(`/orders/${cookedOrderData?.cookedOrders.id}`);
}
};
const [takeOrderMutation] = useMutation<
TakeOrderMutation,
TakeOrderMutationVariables
>(TAKE_ORDER_MUTATION, {
onCompleted,
});
const triggerMutation = (orderId: number) => {
takeOrderMutation({
variables: {
input: {
id: orderId,
},
},
});
};
return (
<div>
<div
className="overflow-hidden"
style={{ width: window.innerWidth, height: "50vh" }}
>
<GoogleMapReact
defaultZoom={16}
defaultCenter={{ lat: 37.58, lng: 125.95 }}
bootstrapURLKeys={{ key: key ? key : "" }}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={onApiLoaded}
>
{/* <Driver lat={driverCoords.lat} lng={driverCoords.lng}></Driver> */}
</GoogleMapReact>
</div>
<div className=" max-w-screen-sm mx-auto bg-white relative -top-10 shadow-lg py-8 px-5">
{cookedOrderData?.cookedOrders.restaurant ? (
<>
<h1 className="text-center text-3xl font-medium">
New Cooked Order
</h1>
<h4 className="text-center my-3 text-2xl font-medium">
Pick it up soon @ {cookedOrderData?.cookedOrders.restaurant?.name}
</h4>
<button
onClick={() => triggerMutation(cookedOrderData.cookedOrders.id)}
className="btn w-full block text-center mt-5"
>
Accept Challenge →
</button>
</>
) : (
<h1>No Orders yet...</h1>
)}
</div>
</div>
);
}; |
// Kalyis Alexander|| Spaceship game||Nov 29,22
ArrayList<Rock> rocks = new ArrayList<Rock>();
ArrayList<PowerUp> powerups = new ArrayList<PowerUp>();
ArrayList<Laser> lasers = new ArrayList<Laser>();
Ship s1;
Timer rockTimer, puTimer;
Star []stars=new Star[200];
int score, level;
boolean play;
void setup() {
size(800, 800);
s1=new Ship();
rockTimer=new Timer(500);
rockTimer.start();
puTimer=new Timer(50000);
puTimer.start();
for (int i=0; i<stars.length; i++) {
stars[i]=new Star();
}
score=0;
level=1;
play=false;
}
void draw() {
background(0);
// render Stars
for (int i=0; i<stars.length; i++) {
stars[i].display();
stars[i].move();
}
noCursor();
//powerups
if (puTimer.isFinished()) {
powerups.add(new PowerUp());
puTimer.start();
}
//render powerups
for (int i = 0; i < powerups.size(); i++) {
PowerUp pu = powerups.get(i);
if (pu.intersect(s1)) {
if (pu.type=='H') {
s1.health+=100;
} else if (pu.type=='T') {
//s1.turrentCount++;
}
powerups.remove(pu);
}
if (pu.reachedBottom()) {
powerups.remove(pu);
} else {
pu.display();
pu.move();
println(powerups.size());
}
}
//adding rocks
if (rockTimer.isFinished()) {
rocks.add(new Rock());
rockTimer.start();
}
//render rocks
for (int i = 0; i < rocks.size(); i++) {
Rock r = rocks.get(i);
if (s1.intersect(r)) {
s1.health-=r.diam;
score+=r.diam;
//todo;make an explosion sound and animation
//todo:add health to rocks
rocks.remove(r);
}
if (r.reachedBottom()) {
rocks.remove(r);
} else {
r.display();
r.move();
println(rocks.size());
}
}
//render Lasers
for (int i = 0; i < lasers.size(); i++) {
Laser l =lasers .get(i);
for (int j=0; j<rocks.size(); j++) {
Rock r= rocks.get(j);
if (l.intersect(r)) {
score+=100;
//add explosion sound
//add explosin
lasers.remove(l);
rocks.remove(r);
}
}
if (l.reachedTop()) {
rocks.remove(l);
} else {
l.display();
l.move();
println(rocks.size());
}
}
//ship
s1.display();
s1.move(mouseX, mouseY);
infoPanel();
}
void mousePressed() {
if (s1.fire() && s1.turretCount == 1) {
lasers.add(new Laser(s1.x, s1.y));
println(lasers.size());
} else if (s1.fire() && s1.turretCount == 2) {
lasers.add(new Laser(s1.x-20, s1.y));
lasers.add(new Laser(s1.x+20, s1.y));
println(lasers.size());
}
}
void infoPanel() {
fill(128, 128);
rectMode(CENTER);
rect(width/2, 25, width, 50);
fill(255);
textSize(25);
text("Score:"+ score +"Health"+s1.health+ "| level"+level+ "Ammo:"+s1.laserCount, 20, 40);
}
void startScreen() {
background(0);
fill(225);
textAlign(CENTER);
text("Press any key to start playing!", width/2, height/2);
}
void gameOver() {
} |
# How to contribute to this project
* 🔎 Please ensure your findings have not already been reported by searching on the project repository under [Issues](https://github.com/bytemare/crypto).
* If you think your findings can be complementary to an existing issue, don't hesitate to join the conversation 😃☕
* If there's no issue addressing the problem, [open a new one](https://github.com/bytemare/crypto/issues/new). Please be clear in the title and description, and add relevant information. Bonus points if you provide a **code sample** and everything needed to reproduce the issue when expected behaviour is not occurring.
* If possible, use the relevant issue templates.
### Do you have a fix?
🎉 That's awesome! Pull requests are welcome!
* Please [open an issue](https://github.com/bytemare/crypto) beforehand, so we can discuss this.
* Fork this repo from `main`, and ensure your fork is up-to-date with it when submitting the PR.
* If your changes impact the documentation, please update it accordingly.
* If you added code that impact tests, please add tests with relevant coverage and test cases. Bonus points for fuzzing.
* 🛠️ Make sure the test suite passes.
If your changes might have an impact on performance, please benchmark your code and measure the impact, share the results and the tests that lead to these results.
Please note that changes that are purely cosmetic and do not add anything substantial to the stability, functionality, or testability of the project may not be accepted.
### Coding Convention
This project tries to be as Go idiomatic as possible. Conventions from [Effective Go](https://golang.org/doc/effective_go) apply here. Tests use a very opinionated linting configuration that you can use before committing to your changes.
### Licence
By contributing to this project, you agree that your contributions will be licensed under the project's [License](https://github.com/bytemare/crypto/blob/main/LICENSE).
All contributions (including pull requests) must agree to the [Developer Certificate of Origin (DCO) version 1.1](http://developercertificate.org). It states that the contributor has the right to submit the patch for inclusion into the project. Simply submitting a contribution implies this agreement, however, please include the "Signed-off-by" git tag in every commit (this tag is a conventional way to confirm that you agree to the DCO).
Thanks! :heart: |
import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './shared/material-module';
import { HomeComponent } from './home/home.component';
import { BestSellerComponent } from './best-seller/best-seller.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FlexLayoutModule } from '@angular/flex-layout';
import { SharedModule } from './shared/shared.module';
import { FullComponent } from './layouts/full/full.component';
import { AppHeaderComponent } from './layouts/full/header/header.component';
import { AppSidebarComponent } from './layouts/full/sidebar/sidebar.component';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { SignupComponent } from './signup/signup.component';
import { NgxUiLoaderConfig, NgxUiLoaderModule, SPINNER } from 'ngx-ui-loader';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { ForgotPasswordComponent } from './forgot-password/forgot-password.component';
import { LoginComponent } from './login/login.component';
import { TokenInterceptorInterceptor } from './services/token-interceptor.interceptor';
import { ManageCategoryComponent } from './material-component/manage-category/manage-category.component';
const ngxUiLoaderConfig:NgxUiLoaderConfig={
text:"Loading...",
textColor:"#FFFFFF",
textPosition:"center-center",
bgsColor:"#7b1fa2",
fgsColor:"#7b1fa2",
fgsType:SPINNER.squareJellyBox,
fgsSize:100,
hasProgressBar:false,
}
@NgModule({
declarations: [
AppComponent,
HomeComponent,
BestSellerComponent,
FullComponent,
AppHeaderComponent,
AppSidebarComponent,
SignupComponent,
ForgotPasswordComponent,
LoginComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
MaterialModule,
FlexLayoutModule,
SharedModule,
HttpClientModule,
NgxUiLoaderModule.forRoot(ngxUiLoaderConfig),
MatIconModule,
MatButtonModule,
],
providers: [HttpClientModule,{provide:HTTP_INTERCEPTORS,useClass:TokenInterceptorInterceptor,multi:true}],
bootstrap: [AppComponent]
})
export class AppModule { } |
# 2020-06-18 William A. Hudson
# rgIic Hardware Register Description.
#---------------------------------------------------------------------------
# See also: perlpod(1) perlpodstyle(1)
=head1 NAME
rgIic Hardware Description -- I2C Master
=head1 SYNOPSIS
Hardware registers of each I2C Master: (iic0, .. iic7)
rgIic
Register BCM Name Description
-------- -------- ------------------
Cntl C Control
Stat S Status
DatLen DLEN Data Length
Addr A Slave Address
Fifo FIFO Data FIFO
ClkDiv DIV Clock Divider
Delay DEL Data Delay
ClkStr CLKT Clock Stretch Timeout
Reg.Field Bits BCM
----.--------------- ------ -----
Cntl.IicEnable_1 [15] I2CEN
Cntl.IrqRxHalf_1 [10] INTR
Cntl.IrqTxHalf_1 [9] INTT
Cntl.IrqDone_1 [8] INTD
Cntl.StartTrans_1 [7] ST (WO)
Cntl.ClearFifo_2 [5:4] CLEAR (WO)
Cntl.ReadPacket_1 [0] READ
Stat.ClkTimeout_1 [9] CLKT (R/C)
Stat.AckErr_1 [8] ERR (R/C)
Stat.RxFull_1 [7] RXF (RO)
Stat.TxEmpty_1 [6] TXE (RO)
Stat.RxHasData_1 [5] RXD (RO)
Stat.TxHasSpace_1 [4] TXD (RO)
Stat.RxHalf_1 [3] RXR (RO)
Stat.TxHalf_1 [2] TXW (RO)
Stat.TransDone_1 [1] DONE (R/C)
Stat.TransActive_1 [0] TA (RO)
DatLen.DataLen_16 [15:0] DLEN
Addr.SlaveAddr_7 [6:0] ADDR
Fifo.Data_8 [7:0] DATA
ClkDiv.ClkDiv_16 [15:0] CDIV
Delay.Fall2Out_16 [31:16] FEDL
Delay.Rise2In_16 [15:0] REDL
ClkStr.TimeOut_16 [15:0] TOUT
(WO) = Write-only, (RO) = Read-only, (R/C) = Read/Clear,
otherwise all are read-write.
Field names incorporate the number of bits in the field, making the field
size self documenting.
All registers are 32-bits.
Unspecified bit fields in each register are typically reserved, and should
be write as 0, and read as don't care.
=head2 Abbreviations in Register/Field names
Clk Clock
Trans Transfer
Fifo First In First Out (FIFO) memory
Rx Receive FIFO
Tx Transmit FIFO
Irq Interrupt Request (IRQ)
=head1 DESCRIPTION
I2C (or IIC) stands for "Inter-Integrated Circuit" serial communication.
The Raspberry Pi (RPi) has 8 I2C Master controllers named as:
iic0, iic1, iic2 in RPi3 (BCM2837) and earlier
iic3, iic4, iic5, iic6, iic7 added in RPi4 (BCM2711)
Note that iic2 and iic7 are dedicated for use by the HDMI interfaces and
should not be accessed by user programs.
The BCM doc describes it as the Broadcom Serial Controller (BSC), and the bus
as a proprietary bus compliant with I2C.
Each controller has the same interface structure described here.
See the BCM doc for a description of 10-Bit Addressing.
=head2 Features
- I2C single Master only operation.
- Fast mode, 400 K bits/s
- Clock stretching wait states are supported.
- Both 7-bit and 10-bit addressing is supported.
- Timing completely software controllable via registers.
- Compliant with the Philips I2C bus/interface version 2.1 January 2000.
Note: The BSC controller in the BCM2711 (RPi4) fixes the clock-stretching
bug that was present in BCM283x (RPi3 and earlier) devices.
=head2 Hardware Signals
GPIO Alternate Function names (hardware signals) are:
iic0_SCL Serial Clock, driven by master
iic0_SDA Serial Data
...
Similarly for iic1_*, iic3_*, iic4_*, iic5_*, iic6_*.
No alternate function pins are identified for iic2_* and iic7_*.
=head2 Signal Electrical Characteristics
Both SCL and SDA are bidirectional signals having open-drain (open-collector)
drivers. They each require a pull-up resistor to the 3.3 V power supply,
which may be provided internally, or externally.
Normal GPIO pin outputs have push-pull drivers. When the GPIO pins are
configured for SCL and SDA, the driver is operated in an open-drain mode,
essentially by disabling the active pull-up FET (Field Effect Transistor).
Be aware the internal GPIO pin pull up/down resistors can be configured to
pull up, pull down, or be turned off.
Note that RPi4 and earlier boards have 1.8 kohm pullup resistors on the
iic1 pins Gpio[2] and Gpio[3]. See RPi schematics.
=head2 Signal Timing
Start and Stop conditions are indicated by an SDA edge when SCL is high.
Normal data changes are allowed only when SCL is low.
_______ ___ _ _ ___ _________
SCL |___| |___| ... |___| |___|
_____ _______ ___ ___ _______ _______
SDA |___X_______X___ ... ___X_______|___|
^ ^
| Start| Data Transfer |Stop | Idle
Typically SDA is sampled on the rising edge of SCL, and changed on the
falling edge of SCL. The B<Delay> register can be used to adjust timing of
the RPi master.
=head2 I2C Operation
A transaction consists of Start condition followed by an address packet,
zero or more data packets, and a Stop condition.
A packet consists of 8 data bits signaled by the sender, MSB first, followed
by an acknowledge (ACK) bit signaled by the receiver.
An address packet has data that consists of the 7-bit device address, MSB
first, followed by the B<ReadPacket_1> read/write bit.
Address transaction, no data.
S | A6 A5 A4 A3 A2 A1 A0 Rw Ks | P
Write transaction.
S | A6 A5 A4 A3 A2 A1 A0 0 Ks | D7 D6 D5 D4 D3 D2 D1 D0 Ks |... P
Read transaction.
S | A6 A5 A4 A3 A2 A1 A0 1 Ks | d7 d6 d5 d4 d3 d2 d1 d0 Km |... P
Start| address packet | data packet |... Stop
S = Start condition, by master
P = Stop condition, by master
A6..A0 = device address, always sent by master
Rw = Read/write bit, by master
Ks = Acknowledge, by slave
Km = Acknowledge, by master
D7..D0 = data byte, by master
d7..d0 = data byte, by slave
Acknowledge bit: 0= ACK acknowledge (actively driven low), 1= NACK
not acknowledge (passively pulled high).
ACK is driven by the receiver of the packet to indicate OK to continue.
See I2C documentation below for diagrams and more details.
=head2 RPi Master Operation
This short summary of highlights for the RPi I2C Master is derived from
documentation and experiment.
The RPi master is intended to control a single transaction in one direction
at a time. It has no controls to create a repeated start.
It has no mechanism to queue up multiple transactions, although data for
successive transactions can be placed in the FIFO.
A transaction is started by setting B<StartTrans_1>=1. Note that status
B<TransActive_1> is not immediately set, and becomes 1 some time later.
The address packet is sent immediately, even if there is no data in the FIFO.
A write transaction with no data, i.e. B<DataLen_16>=0, will send just the
address. This can be used to probe for devices on the bus, looking for
addresses that do not result in an acknowledge error B<AckErr_1>=1.
If a write transaction runs out of data in the FIFO, the master will wait
indefinitely, holding SCL high. [Is there a timeout?]
The receiving slave will have acknowledged the previous packet, and is forced
to continue holding SDA low, since SDA changes are not allowed when SCL is
high.
Note some slaves may have a timeout to avoid locking up the bus, and will
raise SDA anyway (signaling Stop). The RPi master sees this, and responds
by sending Stop.
If the FIFO becomes full on a read transaction, the master will wait
indefinitely, holding SCL high. When the processor removes an entry, the
master will receive another packet.
It is not necessary to clear B<TransDone_1> to start another transaction,
but it is necessary in order to change B<DataLen_16>.
The B<IicEnable_1> control can be used to suspend an active transaction, and
later resume it.
The B<ClearFifo_2> control can be used to abort an active transaction.
A read transaction with no data, B<DataLen_16>=0, can hang the bus if the
slave was expecting to send more data and the first read data bit is 0.
What happens: The master issues one more SCL cycle, low then high, in order
to send a Stop condition. However the slave is holding SDA low for the
first read data bit, preventing the master from signaling Stop by raising SDA.
Now SCL is left high by the master, and the slave is stuck holding SDA low
since changes are not allowed while SCL is high.
=head2 Hardware FIFO
There is only one data FIFO, which has 16 entries of 8 bits.
The FIFO has 4 data ports: Processor Writes to the B<Fifo> register inserts
entries, and Reads remove entries. The I2C receiver (Rx) inserts entries,
and the transmitter (Tx) removes entries.
The Processor can read or write while the I2C master is active.
The various FIFO status fields are updated as entries are inserted or removed.
The I2C bus only sends N data bytes in one direction for each Start address
byte. Thus it can use the same data FIFO for both Receive (Rx) and
Transmit (Tx). This differs from SPI, which has two FIFOs that operate
simultaneously.
It seems likely a previous chip version had two FIFOs.
Control and Status Register operation would remain the same, but two FIFOs
would have the ability to queue up Tx data while a Rx transfer is in progress.
Instead with a single FIFO, we see processor reads can return FIFO data from
previous processor writes.
The documentation refers to Rx and Tx FIFOs as if they are separate, but
keep in mind they are one and the same.
Some FIFO flags for Rx and Tx are redundant with a single FIFO. It may be
best to use the flags as if they were separate FIFOs, i.e. use Tx flags
when sending, and Rx flags when receiving.
=head1 REGISTER BIT FIELDS
The numeric suffix on the field name indicates the number of bits in the field.
=head2 Cntl Register
Control register.
=over
=item B<IicEnable_1> - Enable the I2C interface.
1= Enabled
0= Disabled
Enables interface activity. When disabled, hardware transfers are not
performed, but software register access is allowed.
[Can operation be suspended in the middle of a transfer?
Intended only as a way to disable all interrupt sources?
]
=item B<IrqRxHalf_1> - Interrupt on Rx FIFO over "half" full.
1= Generate interrupt while Stat.RxHalf_1=1
0= Not
The interrupt remains active until the condition is cleared by reading
sufficient data from the Rx FIFO.
=item B<IrqTxHalf_1> - Interrupt on Tx FIFO under "half" full.
1= Generate interrupt while Stat.TxHalf_1=1
0= Not
The interrupt remains active until the condition is cleared by writing
sufficient data to the Tx FIFO.
=item B<IrqDone_1> - Interrupt on Transfer Done.
1= Generate interrupt while Stat.TransDone_1=1
0= Not
The interrupt remains active until the condition is cleared by writing
a 1 to the B<Stat.TransDone_1> field.
=item B<StartTrans_1> - Start Transfer. (WO)
1= Start a new transfer
0= No action
Writing 1 is a one-shot operation, and always reads back as 0.
=item B<ClearFifo_2> - Clear FIFO. (WO)
0= No action
1= Clear
2= Clear
3= Clear
Clear the FIFO in a one-shot operation, always reads back as 0.
If both B<StartTrans_1> and B<ClearFifo_2> are set in the same write register
operation, the FIFO is cleared before the new transfer is started.
Clearing the FIFO during a transfer will result in the transfer being aborted.
Note: The 2 bits are redundant to maintain compatibility with a previous
chip version [perhaps when there were separate Rx and Tx FIFOs].
=item B<ReadPacket_1> - I2C transfer Read/Write type.
1= Read
0= Write
This is the Read/Write bit value in the Start byte of the transfer,
sent along with the slave address.
=back
=head2 Stat Register
Status register.
(RO) = Read-only. (R/C) = Read/Clear, cleared by writing 1.
=over
=item B<ClkTimeout_1> - Slave clock stretch timeout. (R/C)
1= Timeout
0= Not
Slave has held the SCL signal low (clock stretching) for longer
than specified by B<ClkStr.TimeOut_16>.
Cleared by writing 1. Writing 0 has no effect.
=item B<AckErr_1> - Slave acknowledge error. (R/C)
1= Slave acknowledge error
0= Not
Slave has not acknowledged its address or a data byte written to it.
Cleared by writing 1. Writing 0 has no effect.
=item B<RxFull_1> - Rx FIFO is Full. (RO)
1= Rx FIFO is full
0= Not
When full, no more SCL clocks will be generated and no further serial data
will be received. (Assuming Read transfers.)
=item B<TxEmpty_1> - Tx FIFO is Empty. (RO)
1= Tx FIFO is empty
0= Not
When empty, no more SCL clocks will be generated and no further serial data
bytes will be sent. (Assuming Write transfers.)
=item B<RxHasData_1> - Rx FIFO has data. (RO)
1= Rx FIFO contains at least 1 byte.
0= Is empty.
Software reads from an empty FIFO will return invalid data.
=item B<TxHasSpace_1> - Tx FIFO has space. (RO)
1= Tx FIFO has space for at least 1 byte.
0= Is full.
Software writes to a full Tx FIFO are ignored.
=item B<RxHalf_1> - Rx FIFO is over "half" full. (RO)
1= Rx FIFO is over "half" full and a Read transfer is underway.
0= Not
Here "half" is fuzzy, but the idea is to signal that more data should be
read from the FIFO before it overflows.
Observation indicates that (B<RxHalf_1> = 1) when the FIFO has >= 12 entries
and (B<ReadPacket_1> = 1), and is zero otherwise. It does not depend on
B<TransDone_1> or B<TransActive_1>.
=item B<TxHalf_1> - Tx FIFO is under "half" full. (RO)
1= Tx FIFO is under "half" full and a Write transfer is underway.
0= Not
Here "half" is fuzzy, but the idea is to signal that more data should be
written to the FIFO before it goes empty.
Observation suggests this bit is non-functional, and seems to be stuck zero.
#!! Also zero if there is sufficient data to send?
=item B<TransDone_1> - Transfer Done. (R/C)
1= Transfer completed
0= Not
The specified number of bytes in B<DatLen.DataLen_16> have been transferred.
Cleared by writing 1. Writing 0 has no effect.
=item B<TransActive_1> - Transfer Active. (RO)
1= Transfer is in progress.
0= Idle
=back
=head2 DatLen Register
Data length register.
=over
=item B<DataLen_16> - Data Transfer Length.
Is the number of data bytes remaining to be sent or received.
It behaves as a single register that counts down, and does not remember the
last processor write value.
Processor writes are ignored unless (B<TransDone_1> = 0).
Starting a transfer with (B<DataLen_16> = 0) will send only the address byte,
followed by a STOP condition.
The BCM Doc indicates additional functionality: Reading when
(B<TransActive_1> = 0) and (B<TransDone_1> = 0) returns the value last written
by the processor. Essentially it would have a second register holding the
original number of bytes. That value can be left over multiple packets,
i.e. no need to re-write the same value.
This behavior is not observed (perhaps it was in a previous chip version).
Bummer! Each transaction must clear TransDone_1 and then re-write DataLen_16.
=back
=head2 Addr Register
Address register.
=over
=item B<SlaveAddr_7> - Slave Address
Slave address of the I2C device.
The value can be left across multiple transfers.
=back
=head2 Fifo Register
The single data FIFO is 16 entries of 8-bits each, and is used for both
transmit (Tx) and receive (Rx).
There appears to be no mechanism that keeps Rx data separate from Tx data.
Thus a Fifo register read can return data inserted by a Fifo register write,
and it is likely Fifo register writes can mix data with received Rx data.
=over
=item B<Data_8> - Fifo Data
Write inserts a data byte in the FIFO, intended for transmit (Tx).
Read removes a data byte from the FIFO, expected from receive (Rx).
Data writes to a full FIFO will be ignored and data reads from an empty
FIFO will return invalid data.
The FIFO can be cleared using B<Cntl.ClearFifo_2> field.
Note reads from an empty FIFO may appear to return the last valid value, but
that is just coincidence and often is whatever register was read last.
=back
=head2 ClkDiv Register
Clock divider register.
=over
=item B<ClkDiv_16> - Clock Divisor value.
The value is always rounded down to an even number.
SCL clock frequency is:
Fscl = Fcore / ClkDiv_16
where
Fcore = core clock frequency, nominally 150 MHz.
The BCM Doc states: The reset value of 1500 (0x05dc) should result in a
100 kHz SCL clock frequency. A value of zero is the maximum value 65536
(0x10000).
Note the actual clock frequency depends on the processor core clock frequency,
which may vary with operating system power-save and thermal management.
Observation on Raspberry Pi 3B indicates: A value of (ClkDiv_16 = 2500)
gives a 10 us period (100 kHz) when processor is idle,
and a 6.25 us period (160 kHz) when busy.
[The BCM doc is inconsistent between the equation and divisor values.]
What specifies the core clock frequency?
Is there an associated Clock Manager?
=back
=head2 Delay Register
Data delay register. Provides fine control of the SDA signal sample/change
point.
Caution: Delay values should be less than (ClkDiv_16 / 2).
Otherwise the delay may be longer than the SCL clock high or low time, causing
the controller to malfunction.
=over
=item B<Fall2Out_16> - Falling Edge Delay to output.
Number of core clock cycles to wait after the falling edge of SCL before
outputting next data bit. (Change when SCL is low.)
=item B<Rise2In_16> - Rising Edge Delay to input.
Number of core clock cycles to wait after the rising edge of SCL before
sampling the next data bit. (Sample when SCL is high.)
=back
=head2 ClkStr Register
Clock Stretch Timeout register.
Provides a timeout on how long the master waits for a slave stretching the
clock before deciding that the slave has hung.
=over
=item B<TimeOut_16> - Clock Stretch Timeout value.
Number of SCL clock cycles to wait after the rising edge of SCL before
deciding that the slave is not responding.
A value of 0 disables timeout.
When a timeout occurs, the B<Stat.ClkTimeout_1> status bit is set.
=back
=head1 FILES
In the librgpio/ source tree:
src/rgIic.h
src/rgIic.cpp
=head1 SEE ALSO
rgIic(3)
rgpio-iic(1)
librgpio(3)
BCM doc: BCM2835 ARM Peripherals (06 February 2012)
p.28-37 ch 3. BSC (Broadcom Serial Controller)
https://www.raspberrypi.org/documentation/hardware/raspberrypi/bcm2835/BCM2835-ARM-Peripherals.pdf
BCM doc: BCM2711 ARM Peripherals (2020-10-16)
p.24-30 ch 3. BSC (Broadcom Serial Controller)
http://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf
https://elinux.org/BCM2835_datasheet_errata
Understanding the I2C Bus
https://www.ti.com/lit/pdf/slva704
Texas Instruments, Application Report SLVA704 - June 2015, 7 pages
UM10204 I2C-bus specification and user manual
https://www.nxp.com/docs/en/user-guide/UM10204.pdf
Version 6, April 2014, 64 pages
=cut |
return {
{
"stevearc/conform.nvim",
-- event = 'BufWritePre', -- uncomment for format on save
config = function()
require "configs.conform"
end,
},
{
"mfussenegger/nvim-lint",
config = function()
local lint = require "lint"
lint.linters_by_ft = {
python = { "ruff" },
}
end,
},
-- These are some examples, uncomment them if you want to see them work!
{
"neovim/nvim-lspconfig",
config = function()
require("nvchad.configs.lspconfig").defaults()
require "configs.lspconfig"
end,
},
{
"williamboman/mason.nvim",
opts = {
ensure_installed = {
"lua-language-server",
"stylua",
"html-lsp",
"css-lsp",
"prettier",
"pyright",
"isort",
"ruff",
},
},
},
{
"nvim-treesitter/nvim-treesitter",
opts = {
ensure_installed = {
"vim",
"lua",
"vimdoc",
"html",
"css",
"python",
},
},
},
{
"stevearc/aerial.nvim",
lazy = true,
opts = {
lazy_load = true,
backends = { ["_"] = { "treesitter", "lsp", "markdown", "man" } },
layout = {
max_width = { 40, 0.3 },
width = nil,
min_width = { 10, 0.2 },
-- key-value pairs of window-local options for aerial window (e.g. winhl)
win_opts = {},
-- Determines the default direction to open the aerial window. The 'prefer'
-- options will open the window in the other direction *if* there is a
-- different buffer in the way of the preferred direction
-- Enum: prefer_right, prefer_left, right, left, float
default_direction = "right",
-- Determines where the aerial window will be opened
-- edge - open aerial at the far right/left of the editor
placement = "edge",
-- When the symbols change, resize the aerial window (within min/max constraints) to fit
resize_to_content = false,
-- Preserve window size equality with (:help CTRL-W_=)
preserve_equality = false,
},
-- Determines how the aerial window decides which buffer to display symbols for
-- global - aerial window will display symbols for the current window
attach_mode = "global",
close_automatic_events = { "unfocus", "unsupported" },
-- A list of all symbols to display. Set to false to display all symbols.
-- This can be a filetype map (see :help aerial-filetype-map)
-- To see all available values, see :help SymbolKind
filter_kind = false,
-- filter_kind = {
-- "Class",
-- "Constructor",
-- "Enum",
-- "Function",
-- "Interface",
-- "Module",
-- "Method",
-- "Struct",
-- },
-- Jump to symbol in source window when the cursor moves
autojump = false,
-- Use symbol tree for folding. Set to true or false to enable/disable
-- Set to "auto" to manage folds if your previous foldmethod was 'manual'
-- This can be a filetype map (see :help aerial-filetype-map)
manage_folds = true,
-- When you fold code with za, zo, or zc, update the aerial tree as well.
-- Only works when manage_folds = true
link_folds_to_tree = false,
-- Fold code when you open/collapse symbols in the tree.
-- Only works when manage_folds = true
link_tree_to_folds = false,
-- Call this function when aerial attaches to a buffer.
on_attach = function(bufnr)
local aerial = require "aerial"
-- make sure source code is unfolded
aerial.open_all()
aerial.sync_folds(bufnr)
-- set default fold level to 1
aerial.tree_set_collapse_level(bufnr, 1)
end,
show_trailing_blankline_indent = false,
use_treesitter = true,
char = "▏",
context_char = "▏",
show_current_context = true,
buftype_exclude = {
"nofile",
"terminal",
},
filetype_exclude = {
"help",
"startify",
"aerial",
"alpha",
"dashboard",
"lazy",
"neogitstatus",
"NvimTree",
"neo-tree",
"Trouble",
},
context_patterns = {
"class",
"return",
"function",
"method",
"^if",
"^while",
"jsx_element",
"^for",
"^object",
"^table",
"block",
"arguments",
"if_statement",
"else_clause",
"jsx_element",
"jsx_self_closing_element",
"try_statement",
"catch_clause",
"import_statement",
"operation_type",
},
},
-- Optional dependencies
dependencies = {
"nvim-treesitter/nvim-treesitter",
"nvim-tree/nvim-web-devicons",
},
keys = { { "<leader>a", "<cmd>AerialToggle!<cr>", desc = "Tag Outline" } },
},
} |
import { useState } from 'react'
import { toast } from 'sonner'
import { NewNoteCard, NoteCard } from './components'
import { INote } from './interfaces/Note'
import logo from './assets/logo-nlw-expert.svg'
export function App() {
const [search, setSearch] = useState('')
const [notes, setNotes] = useState<INote[]>(() => {
const notesOnStorage = localStorage.getItem('notes')
if (notesOnStorage) {
return JSON.parse(notesOnStorage)
}
return []
})
const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
const query = event.target.value
setSearch(query)
}
const filteredNotes =
search !== ''
? notes.filter((note) => note.content.toLocaleLowerCase().includes(search.toLocaleLowerCase()))
: notes
const onNoteCreated = (content: string) => {
const newNote = {
id: crypto.randomUUID(),
date: new Date(),
content,
}
const notesArray = [newNote, ...notes]
handleSaveNotes(notesArray)
}
const handleSaveNotes = (currentNotes: INote[]) => {
localStorage.setItem('notes', JSON.stringify(currentNotes))
setNotes(currentNotes)
}
const onNoteDeleted = (id: string) => {
const notesArray = notes.filter((note) => note.id !== id)
handleSaveNotes(notesArray)
toast.success('Nota deletada com sucesso.')
}
const renderNotes = () => {
return filteredNotes.map((note) => <NoteCard key={note.id} note={note} onNoteDeleted={onNoteDeleted} />)
}
return (
<div className="mx-auto max-w-6xl my-12 space-y-6 px-5">
<img src={logo} />
<form className="w-full">
<input
className="w-full bg-transparent text-3xl font-semibold tracking-tight outline-none placeholder:text-slate-500"
type="text"
placeholder="Busque em suas notas..."
onChange={handleSearch}
/>
</form>
<div className="h-px bg-slate-700" />
<div className="grid grid-cols-1 md:grid-cols-5 lg:grid-cols-3 gap-6 auto-rows-[250px]">
<NewNoteCard onNoteCreated={onNoteCreated} />
{renderNotes()}
</div>
</div>
)
} |
<?php
/**
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
*
* AppConsentRequestScope File
* PHP version 7
*
* @category Library
* @package Microsoft.Graph
* @copyright (c) Microsoft Corporation. All rights reserved.
* @license https://opensource.org/licenses/MIT MIT License
* @link https://graph.microsoft.com
*/
namespace Microsoft\Graph\Model;
/**
* AppConsentRequestScope class
*
* @category Model
* @package Microsoft.Graph
* @copyright (c) Microsoft Corporation. All rights reserved.
* @license https://opensource.org/licenses/MIT MIT License
* @link https://graph.microsoft.com
*/
class AppConsentRequestScope extends Entity
{
/**
* Gets the displayName
* The name of the scope.
*
* @return string|null The displayName
*/
public function getDisplayName()
{
if (array_key_exists("displayName", $this->_propDict)) {
return $this->_propDict["displayName"];
} else {
return null;
}
}
/**
* Sets the displayName
* The name of the scope.
*
* @param string $val The value of the displayName
*
* @return AppConsentRequestScope
*/
public function setDisplayName($val)
{
$this->_propDict["displayName"] = $val;
return $this;
}
} |
;;; Who Drinks Water? And Who owns the Zebra?
;;;
;;; direct translation of a CLIPS Version 6.0 Example
;;; this is a dangerous benchmark since performance
;;; depends mostly on instantiation order
;;; A much better approach is to use the ECLAIR library
;;; However, the measure of rules/s is interesting
;;;
House :: (1 .. 5)
Problem <: thing(house:integer = 0)
// use naive backtracking to solve a problem
store(house)
// used to count triggers
RuleCount:integer :: 0
// check in CLAIRE
check(p:property,x:any,y:any) : void
=> (RuleCount :+ 1,
if (get(p,x) = 0) write(p,x,y)
else if (get(p,x) != y) contradiction!())
checknot(p:property,x:any,y:any) : void
=> (RuleCount :+ 1,
if (get(p,x) = y) contradiction!())
// Data for the problem
Color <: Problem()
red :: Color()
green :: Color()
ivory :: Color()
yellow :: Color()
blue :: Color()
Person <: Problem()
englishman :: Person()
spaniard :: Person()
ukrainian :: Person()
norwegian :: Person()
japanese :: Person()
Pet <: Problem()
dog :: Pet()
snails :: Pet()
fox :: Pet()
horse :: Pet()
zebra :: Pet()
Drink <: Problem()
water :: Drink()
coffee :: Drink()
milk :: Drink()
orange-juice :: Drink()
tea :: Drink()
Smoke <: Problem()
old-golds :: Smoke()
kools :: Smoke()
chesterfields :: Smoke()
lucky-strikes :: Smoke()
parliaments :: Smoke()
final(Color)
final(Person)
final(Pet)
final(Drink)
final(Smoke)
; The Englishman lives in the red house.
rule1() :: rule(p.house := h & p = englishman => check(house,red,h))
; notice that the Alldifferent constraint is spelled in many rules in the original code
allDifferent() :: rule(p.house := h => use-house(p,h))
use-house(p:Problem,h:House)
-> (case p (Person for p2 in (Person but p) checknot(house,p2,h),
Color for p2 in (Color but p) checknot(house,p2,h),
Pet for p2 in (Pet but p) checknot(house,p2,h),
Drink for p2 in (Drink but p) checknot(house,p2,h),
Smoke for p2 in (Smoke but p) checknot(house,p2,h)))
; The Spaniard owns the dog.
rule2() :: rule(p.house := h & p = spaniard => check(house,dog,h))
; The ivory house is immediately to the left of the green house,
; where the coffee drinker lives.
rule3() :: rule(p.house := h1 & p = ivory =>
(if (h1 <= 4) check(house,green,h1 + 1) else contradiction!()))
rule4() :: rule(p.house := h & p = coffee => check(house,green,h))
; The milk drinker lives in the middle house.
(milk.house := 3)
; The man who smokes Old Golds also keeps snails.
rule5() :: rule(p.house := h & p = old-golds => check(house,snails,h))
; The Ukrainian drinks tea.
rule6() :: rule(p.house := h & p = ukrainian => check(house,tea,h))
; The Norwegian resides in the first house on the left.
(norwegian.house := 1)
; Chesterfields smoker lives next door to the fox owner.
rule7() :: rule(p.house := h & p = chesterfields => next-to(fox,h))
rule7bis() :: rule(p.house := h & p = fox => next-to(chesterfields,h))
next-to(p:Problem,h:House) : void
=> (if (p.house > 0 & p.house != (h - 1)) check(house,p,h + 1))
; The Lucky Strike smoker drinks orange juice.
rule8() :: rule(p.house := h & p = lucky-strikes => check(house,orange-juice,h))
; The Japanese smokes Parliaments
rule9() :: rule(p.house := h & p = japanese => check(house,parliaments,h))
; The horse owner lives next to the Kools smoker, whose house is yellow.
rule10() :: rule(p.house := h & p = horse => next-to(kools,h))
rule10bis() :: rule(p.house := h & p = kools => next-to(horse,h))
rule11() :: rule( p.house := h & p = kools => check(house,yellow,h))
; The Norwegian lives next to the blue house.
rule12() :: rule(p.house := h & p = norwegian => next-to(blue,h))
rule12bis() :: rule(p.house := h & p = blue => next-to(norwegian,h))
// to solve we use the same instantiation order as the original CLIPS example
find-solution()
-> solve(list<Problem>(
englishman,
red,
spaniard,
dog,
ivory,
green,
coffee,
milk,
old-golds,
snails,
ukrainian,
tea,
norwegian,
chesterfields,
fox,
lucky-strikes,
orange-juice,
japanese,
parliaments,
horse,
kools,
yellow,
blue,
water,
zebra))
// generate and test
solve(l:list[Problem]) : boolean -> solve(l,1)
solve(l:list[Problem],n:integer) : boolean
-> (if (n > length(l))
// (print-solution(), false)
(if (verbose() >= 1) print-solution(),false) // no more problems
else let p := l[n] in
(if (p.house = 0)
exists(h in (1 .. 5) |
branch( (//[5] (~A) try ~S -> ~S // n, p, h,
p.house := h,
solve(l, n + 1))))
else solve(l, n + 1))) // move to next
// prints the solution
print-solution()
; -> (for h in (1 .. 5)
; printf("~A:~S\n",h, {p in Problem | p.house = h}))
-> (for h in (1 .. 5)
printf("~A:~S ~S ~S ~S ~S\n",h,
some(x in Color | x.house = h),
some(x in Person | x.house = h),
some(x in Pet | x.house = h),
some(x in Smoke | x.house = h),
some(x in Drink | x.house = h)))
// start
do_test() : void
-> (time_set(),
RuleCount := 0,
find-solution(),
time_show(),
printf("~A rules firings\n",RuleCount))
do_test1() : void
-> (time_set(),
verbose() := 0,
RuleCount := 0,
for i in (1 .. 100) find-solution(),
time_show(),
printf("~A rules firings\n",RuleCount))
main() : void ->
(//[0] look for a solution 100 time ..... //,
do_test1(),
exit(0)) |
package com.weiquding.netty.learning.netty.codecs.protobuf.client;
import com.weiquding.netty.learning.netty.codecs.protobuf.domain.SubscribeReqProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
/**
* @author wubai
* @date 2018/9/22 1:19
*/
public class SubReqClient {
public void connect(int port, String host) throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
socketChannel.pipeline().addLast(new ProtobufDecoder(SubscribeReqProto.SubscribeReq.getDefaultInstance()));
socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
socketChannel.pipeline().addLast(new ProtobufEncoder());
socketChannel.pipeline().addLast(new SubReqClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
channelFuture.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if(args != null && args.length > 0){
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e){
}
}
new SubReqClient().connect(8080, "127.0.0.1");
}
} |
package com.teamforce.thanksapp.presentation.viewmodel.onboarding
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.teamforce.thanksapp.data.response.onboarding.InviteLinkResponse
import com.teamforce.thanksapp.domain.interactors.OnBoardingInteractor
import com.teamforce.thanksapp.utils.ResultWrapper
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class InviteMembersViewModel @Inject constructor(
private val onBoardingInteractor: OnBoardingInteractor
): ViewModel() {
private val _isLoading = MutableLiveData<Boolean>()
val isLoading: LiveData<Boolean> = _isLoading
private val _invitationData = MutableLiveData<InviteLinkResponse?>()
val invitationData: LiveData<InviteLinkResponse?> = _invitationData
private val _invitationError = MutableLiveData<Boolean?>()
val invitationError: LiveData<Boolean?> = _invitationError
fun getInvitationData(organizationId: String?) {
_isLoading.postValue(true)
viewModelScope.launch {
withContext(Dispatchers.IO) {
_isLoading.postValue(true)
when (val result = onBoardingInteractor.getInviteLink(organizationId?.toIntOrNull())) {
is ResultWrapper.Success -> {
_invitationData.postValue(result.value)
_isLoading.postValue(false)
_invitationError.postValue(false)
}
else -> {
if (result is ResultWrapper.GenericError) {
if(result.code == 403){
_isLoading.postValue(false)
_invitationError.postValue(true)
}
} else if (result is ResultWrapper.NetworkError) {
}
}
}
}
}
}
} |
from mock import *
from gp_unittest import *
from gppylib.gparray import GpArray, Segment
from gppylib.commands.base import CommandResult
from gppylib.operations.rebalanceSegments import GpSegmentRebalanceOperation
from gppylib.operations.rebalanceSegments import replay_lag
class RebalanceSegmentsTestCase(GpTestCase):
def setUp(self):
self.pool = Mock()
self.pool.getCompletedItems.return_value = []
mock_logger = Mock(spec=['log', 'warn', 'info', 'debug', 'error', 'warning', 'fatal'])
self.apply_patches([
patch("gppylib.commands.base.WorkerPool.__init__", return_value=None),
patch("gppylib.commands.base.WorkerPool", return_value=self.pool),
patch('gppylib.programs.clsRecoverSegment.GpRecoverSegmentProgram'),
patch('gppylib.operations.rebalanceSegments.logger', return_value=mock_logger),
patch('gppylib.db.dbconn.connect', autospec=True),
patch('gppylib.db.dbconn.execSQLForSingleton', return_value='5678')
])
self.mock_gp_recover_segment_prog_class = self.get_mock_from_apply_patch('GpRecoverSegmentProgram')
self.mock_parser = Mock()
self.mock_gp_recover_segment_prog_class.createParser.return_value = self.mock_parser
self.mock_parser.parse_args.return_value = (Mock(), Mock())
self.mock_gp_recover_segment_prog = Mock()
self.mock_gp_recover_segment_prog_class.createProgram.return_value = self.mock_gp_recover_segment_prog
self.failure_command_mock = Mock()
self.failure_command_mock.get_results.return_value = CommandResult(
1, "stdout failure text", "stderr text", True, False)
self.success_command_mock = Mock()
self.success_command_mock.get_results.return_value = CommandResult(
0, "stdout success text", "stderr text", True, False)
self.subject = GpSegmentRebalanceOperation(Mock(), self._create_gparray_with_2_primary_2_mirrors(), 1, 1, 10)
self.subject.logger = Mock(spec=['log', 'warn', 'info', 'debug', 'error', 'warning', 'fatal'])
self.mock_logger = self.get_mock_from_apply_patch('logger')
def tearDown(self):
super(RebalanceSegmentsTestCase, self).tearDown()
def test_rebalance_returns_success(self):
self.pool.getCompletedItems.return_value = [self.success_command_mock]
result = self.subject.rebalance()
self.assertTrue(result)
def test_rebalance_raises(self):
self.pool.getCompletedItems.return_value = [self.failure_command_mock]
self.mock_gp_recover_segment_prog.run.side_effect = SystemExit(1)
with self.assertRaisesRegexp(Exception, "Error synchronizing."):
self.subject.rebalance()
def test_rebalance_returns_failure(self):
self.pool.getCompletedItems.side_effect = [[self.failure_command_mock], [self.success_command_mock]]
result = self.subject.rebalance()
self.assertFalse(result)
@patch('gppylib.db.dbconn.execSQLForSingleton', return_value='56780000000')
def test_rebalance_returns_warning(self, mock1):
with self.assertRaises(Exception) as ex:
self.subject.rebalance()
self.assertEqual('56780000000 bytes of xlog is still to be replayed on mirror with dbid 2, let mirror catchup '
'on replay then trigger rebalance. Use --replay-lag to configure the allowed replay lag limit.'
, str(ex.exception))
self.assertEqual([call("Get replay lag on mirror of primary segment with host:sdw1, port:40000")],
self.mock_logger.debug.call_args_list)
self.assertEqual([call("Determining primary and mirror segment pairs to rebalance"),
call('Allowed replay lag during rebalance is 10 GB')],
self.subject.logger.info.call_args_list)
@patch('gppylib.db.dbconn.execSQLForSingleton', return_value='5678000000')
def test_rebalance_does_not_return_warning(self, mock1):
self.subject.rebalance()
self.assertEqual([call("Get replay lag on mirror of primary segment with host:sdw1, port:40000")],
self.mock_logger.debug.call_args_list)
@patch('gppylib.db.dbconn.connect', side_effect=Exception())
def test_replay_lag_connect_exception(self, mock1):
with self.assertRaises(Exception) as ex:
replay_lag(self.primary0)
self.assertEqual('Failed to query pg_stat_replication for host:sdw1, port:40000, error: ', str(ex.exception))
@patch('gppylib.db.dbconn.execSQLForSingleton', side_effect=Exception())
def test_replay_lag_query_exception(self, mock1):
with self.assertRaises(Exception) as ex:
replay_lag(self.primary0)
self.assertEqual('Failed to query pg_stat_replication for host:sdw1, port:40000, error: ', str(ex.exception))
def _create_gparray_with_2_primary_2_mirrors(self):
master = Segment.initFromString(
"1|-1|p|p|s|u|mdw|mdw|5432|/data/master")
self.primary0 = Segment.initFromString(
"2|0|p|m|s|u|sdw1|sdw1|40000|/data/primary0")
primary1 = Segment.initFromString(
"3|1|p|p|s|u|sdw2|sdw2|40001|/data/primary1")
self.mirror0 = Segment.initFromString(
"4|0|m|p|s|u|sdw2|sdw2|50000|/data/mirror0")
mirror1 = Segment.initFromString(
"5|1|m|m|s|u|sdw1|sdw1|50001|/data/mirror1")
return GpArray([master, self.primary0, primary1, self.mirror0, mirror1])
if __name__ == '__main__':
run_tests() |
package sample.model;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
public class Sender {
private String username;
private String password;
private Properties props;
public Sender(String username, String password) {
this.username = username;
this.password = password;
props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
}
public void send(String subject, String text, String to) {
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
} |
import router from '@ohos.router'
import { TutorialEntity } from '../../model/entity/TutorialEntity'
import { getTutorialData } from '../../viewmodel/Net'
@Component
export struct TutorialPage {
@State tutorialData: TutorialEntity[] = []
aboutToAppear() {
getTutorialData().then((data: TutorialEntity[]) => {
this.tutorialData = data
})
}
build() {
List() {
ForEach(this.tutorialData, (item: TutorialEntity) => {
ListItem() {
TutorialComponent({ tutorialEntity: item })
.onClick(() => {
router.pushUrl({
url: 'pages/home/TutorialDetailPage',
params: item
}, router.RouterMode.Standard)
})
}
}, (item: TutorialEntity) => {
return item.id + ""
})
}
.alignListItem(ListItemAlign.Start)
.width('100%')
.height('100%')
}
}
@Component
struct TutorialComponent {
tutorialEntity: TutorialEntity
build() {
Row({ space: 16 }) {
Image(this.tutorialEntity.cover)
.width(100)
Column({ space: 16 }) {
Text(this.tutorialEntity.name)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.fontColor(Color.Black)
Text(`作者:${this.tutorialEntity.author}`)
.fontSize(14)
.fontColor($r('app.color.color_666666'))
Text(this.tutorialEntity.desc)
.fontSize(14)
.fontColor($r('app.color.color_666666'))
}
.alignItems(HorizontalAlign.Start) // 交叉轴的排列
.justifyContent(FlexAlign.Start) // 主轴的排列
.width('100%')
}
.width('100%')
.padding(16)
}
} |
import { ModelInit, MutableModel, PersistentModelConstructor } from "@aws-amplify/datastore";
export declare class Image {
readonly resMode: string;
readonly image?: S3Object;
readonly thumb?: string;
constructor(init: ModelInit<Image>);
}
export declare class S3Object {
readonly bucket: string;
readonly region: string;
readonly key: string;
constructor(init: ModelInit<S3Object>);
}
export declare class Post {
readonly id: string;
readonly title: string;
readonly description: string;
readonly createdAt?: string;
readonly userID: string;
readonly tags?: TaggedPost[];
readonly thumb: string;
readonly resolutions: Image[];
readonly monthlyViews?: number;
readonly totalViews?: number;
readonly votes?: Vote[];
readonly totalScore?: number;
constructor(init: ModelInit<Post>);
static copyOf(source: Post, mutator: (draft: MutableModel<Post>) => MutableModel<Post> | void): Post;
}
export declare class TaggedPost {
readonly id: string;
readonly post?: Post;
readonly tag?: Tag;
constructor(init: ModelInit<TaggedPost>);
static copyOf(source: TaggedPost, mutator: (draft: MutableModel<TaggedPost>) => MutableModel<TaggedPost> | void): TaggedPost;
}
export declare class Tag {
readonly id: string;
readonly name: string;
readonly description?: string;
readonly posts?: TaggedPost[];
constructor(init: ModelInit<Tag>);
static copyOf(source: Tag, mutator: (draft: MutableModel<Tag>) => MutableModel<Tag> | void): Tag;
}
export declare class Vote {
readonly id: string;
readonly postID: string;
readonly owner: string;
readonly upvote: number;
constructor(init: ModelInit<Vote>);
static copyOf(source: Vote, mutator: (draft: MutableModel<Vote>) => MutableModel<Vote> | void): Vote;
}
export declare class User {
readonly id: string;
readonly username: string;
readonly location?: string;
readonly description?: string;
readonly website?: string;
readonly monthlyViews?: number;
readonly posts?: Post[];
constructor(init: ModelInit<User>);
static copyOf(source: User, mutator: (draft: MutableModel<User>) => MutableModel<User> | void): User;
} |
import React from "react";
import { useNavigate } from "react-router-dom";
import "../CSS/butacahora.css";
import "../CSS/anular.css";
function Butacahora({ data }) {
console.log("Movie ID en Butacahora: ", data.movieId);
const dataAcordion = [
{ id: 'collapseOne', tipoPantalla: '2D', subtitulos: 'DOBLADA', tipoButacas: [{ tipo: 'BUTACA TRADICIONAL', horarios: ['12:00', '16:00', '20:00'] }, { tipo: 'BUTACA PREMIUM', horarios: ['12:00', '16:00', '20:00'] }] },
{ id: 'collapseTwo', tipoPantalla: '2D', subtitulos: 'SUBTITULADA', tipoButacas: [{ tipo: 'BUTACA TRADICIONAL', horarios: ['12:00', '16:00', '20:00'] }, { tipo: 'BUTACA PREMIUM', horarios: ['12:00', '16:00', '20:00'] }] },
{ id: 'collapseThree', tipoPantalla: '3D', subtitulos: 'DOBLADA', tipoButacas: [{ tipo: 'BUTACA TRADICIONAL', horarios: ['12:00', '16:00', '20:00'] }, { tipo: 'BUTACA PREMIUM', horarios: ['12:00', '16:00', '20:00'] }] },
{ id: 'collapseFour', tipoPantalla: '3D', subtitulos: 'SUBTITULADA', tipoButacas: [{ tipo: 'BUTACA TRADICIONAL', horarios: ['12:00', '16:00', '20:00'] }, { tipo: 'BUTACA PREMIUM', horarios: ['12:00', '16:00', '20:00'] }] },
]
return (
<div className="container-lg reset-card-styles">
<h1><p className="text-start fw-bold mt-3">Horarios</p></h1>
<Acordion items={dataAcordion} movieId={data.movieId} movieTitle={data.titulo} movieImage={data.image} />
</div>
);
}
function VisualizarHorario({ horario, tipoPantalla, subtitulos, tipoButacas, movieId, movieTitle, movieImage }) {
const navigate = useNavigate();
const handleClick = () => {
console.log("Horario:", horario);
console.log("Tipo de Pantalla:", tipoPantalla);
console.log("Subtítulos:", subtitulos);
console.log("Tipo de Butacas:", tipoButacas);
console.log("Movie ID:", movieId);
console.log("Movie Title:", movieTitle);
console.log("Movie Image:", movieImage);
navigate(`/compraentrada?horario=${horario}&tipoPantalla=${tipoPantalla}&subtitulos=${subtitulos}&tipoButacas=${JSON.stringify(tipoButacas)}&movieId=${movieId}&movieTitle=${encodeURIComponent(movieTitle)}&movieImage=${encodeURIComponent(movieImage)}`);
}
return (
<button type="button" className="btn btn-outline-primary" onClick={handleClick}>
{horario}
</button>
);
}
function TipoButaca ({ tipo, horarios, tipoPantalla, subtitulos, movieId, movieTitle, movieImage }) {
return (
<div className="accordion-body">
<p className="mt-1">{tipo}</p>
{horarios.map((horario, index) => (
<VisualizarHorario
key={index}
horario={horario}
tipoPantalla={tipoPantalla}
subtitulos={subtitulos}
tipoButacas={tipo}
movieId={movieId}
movieTitle={movieTitle}
movieImage={movieImage}
/>
))}
</div>
)
}
function ItemAcordion ({ id, tipoPantalla, subtitulos, tipoButacas, movieId, movieTitle, movieImage }) {
return (
<div className="accordion-item">
<h2 className="accordion-header">
<button
className={`accordion-button ${id === 'collapseOne' ? 'fw-semibold' : 'collapsed fw-semibold'}`}
type="button"
data-bs-toggle="collapse"
data-bs-target={`#${id}`}
aria-expanded="false"
aria-controls={id}
>
<button type="button" className="btn btn-secondary">{tipoPantalla}</button>
<button type="button" className="btn btn-outline-primary">{subtitulos}</button>
{id === 'collapseThree' || id === 'collapseFour' ? (
<svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-stereo-glasses" width="40" height="40" viewBox="0 0 24 24" strokeWidth="1.5" stroke="#000000" fill="none" strokeLinecap="round" strokeLinejoin="round">
<path stroke="none" d="M0 0h24v24H0z" fill="none"/>
<path d="M8 3h-2l-3 9" />
<path d="M16 3h2l3 9" />
<path d="M3 12v7a1 1 0 0 0 1 1h4.586a1 1 0 0 0 .707 -.293l2 -2a1 1 0 0 1 1.414 0l2 2a1 1 0 0 0 .707 .293h4.586a1 1 0 0 0 1 -1v-7h-18z" />
<path d="M7 16h1" />
<path d="M16 16h1" />
</svg>
) : null}
</button>
</h2>
<div id={id} className="accordion-collapse collapse" data-bs-parent="#accordionExample">
{tipoButacas.map((tipoButaca, index) => (
<TipoButaca
key={index}
tipo={tipoButaca.tipo}
horarios={tipoButaca.horarios}
tipoPantalla={tipoPantalla}
subtitulos={subtitulos}
movieId={movieId}
movieTitle={movieTitle}
movieImage={movieImage}
/>
))}
</div>
</div>
);
}
function Acordion ({ items, movieId, movieTitle, movieImage }) {
return (
<div className="accordion mb-4" id="accordionExample">
{items.map((item, index) => (
<ItemAcordion key={index} {...item} movieId={movieId} movieTitle={movieTitle} movieImage={movieImage} />
))}
</div>
);
}
export default Butacahora; |
"use client";
import useSWR from "swr";
const fetcher = (userInput: string) =>
fetch("/api/suggestions?userInput=" + userInput).then((res) => res.json());
function AISuggestion({ userInput }: { userInput: string }) {
const { data, error, isLoading, isValidating } = useSWR(
"suggestions",
() => fetcher(userInput),
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
);
const generateText = () => {
if (isLoading || isValidating)
return (
<>
<div className="animate-spin rounded-full h-10 w-10 border-b-2 border-white" />
<p className="text-sm text-gray-400">AI Assistant is thinking...</p>
</>
);
if (error) return <>Error...</>;
if (!data) return <>No data</>;
console.log(`MESSAGE: ${data.message}`);
return (
<>
<div className="animate-pulse rounded-full bg-gradient-to-t from-white h-10 w-10 border-2 flex-shrink-0 border-white" />
<div>
<p className="text-sm text-gray-400">
AI (Azure Functions) Assistant Suggests:{" "}
</p>
<p className="italic text-xl">{data.message}</p>
</div>
</>
);
};
return (
<div className="flex space-x-5 items-center px-10">{generateText()}</div>
);
}
export default AISuggestion; |
# Thiết lập nút đồng thuận
## Tải về <a id="download"></a>
Bạn có thể tải về phiên bản mới nhất của `kcn` trên trang [Tải xuống](../../downloads/downloads.md).
## Cài đặt <a id="installation"></a>
### Phân bổ lưu trữ Linux <a id="linux-archive-distribution"></a>
Tập tin lưu trữ bao gồm tập tin nhị phân thực thi và cấu hình có cấu trúc như sau.
**Lưu ý**: KHÔNG thay đổi cấu trúc hoặc tên tập tin. Nếu bạn thay đổi điều đó, nút có thể sẽ không hoạt động đúng.
```text
- bin
|- kcn
|- kcnd
- conf
|- kcnd.conf
```
| Tên tập tin | Mô tả tập tin |
|:-------------- |:-------------------------------- |
| bin/kcn | Tập tin thực thi CN |
| bin/kcnd | Tập tin lệnh bắt đầu/kết thúc CN |
| conf/kcnd.conf | Tập tin cấu hình CN |
Quá trình cài đặt chính là giải nén gói đã tải về tại nơi bạn muốn cài đặt gói.
```bash
$ tar zxf kcn-vX.X.X-linux-amd64.tar.gz
```
Hoặc,
```bash
$ tar zxf kcn-baobab-vX.X.X-linux-amd64.tar.gz
```
**Lưu ý**: nên thêm đường dẫn thư mục chưa giải nén `kcn-linux-amd64/bin` vào biến môi trường `$PATH` để chạy `kcn` và `kcnd` trên toàn hệ thống. Ví dụ,
```bash
$ export PATH=$PATH:~/downloaded/path/kcn-linux-amd64/bin
```
Các phần khác giả định rằng đường dẫn đã được thêm vào biến.
### Phân bổ RPM \(RHEL/CentOS/Fedora\) <a id="rpm-rhel-centos-fedora"></a>
Bạn có thể cài đặt RPM đã tải về với lệnh `yum` sau đây.
```bash
$ yum install kcnd-vX.X.X.el7.x86_64.rpm
```
Hoặc,
```bash
$ yum install kcnd-baobab-vX.X.X.el7.x86_64.rpm
```
### Cài đặt từ Klaytn Yum Repo <a id="install-from-klaytn-yum-repo"></a>
Ngoài ra, bạn có thể cài đặt `kcnd` từ Klaytn Yum repo, chạy:
```bash
$ sudo curl -o /etc/yum.repos.d/klaytn.repo https://packages.klaytn.net/config/rhel/7/prod.repo && sudo yum install kcnd
```
### Vị trí đã cài đặt <a id="installed-location"></a>
Tập tin đã cài đặt nằm ở vị trí như sau.
| Tên tập tin | Vị trí |
|:----------- |:------------------------ |
| kcn | /usr/bin/kcn |
| kcnd.conf | /etc/kcnd/conf/kcnd.conf |
## Cấu hình <a id="configuration"></a>
Cấu hình CN dùng để tạo thư mục dữ liệu và thiết lập các giá trị trong tập tin cấu hình `kcnd.conf`.
1. Tạo thư mục dữ liệu CN.
2. Cài đặt khóa nút
3. Định cấu hình CN với `kcnd.conf`.
### Tạo thư mục dữ liệu CN <a id="cn-data-directory-creation"></a>
Kích thước của dữ liệu blockchain Klaytn sẽ luôn tăng lên thế nên cần sử dụng một dung lượng lưu trữ đủ lớn. Bạn có thể cần phải tạo thư mục trên đường dẫn bạn muốn.
```bash
$ mkdir -p /var/kcnd/data
```
### Cài đặt Khóa nút <a id="install-node-key"></a>
Để vận hành CN cần có `khóa nút`. Nhị phân KCN sẽ tạo ra một nút mới nếu bạn không có sẵn. Nếu bạn đã có, bạn cần chuyển `khóa nút` vào thư mục dữ liệu CN. Cách để tạo `khóa nút` được mô tả trong phần '[Trước khi bạn cài đặt](./before-you-install.md)'. Dòng lệnh sau sao chép`khóa nút` vào thư mục dữ liệu CN.
```bash
$ cp nodekey /var/kcnd/data
```
### Cập nhật Tập tin cấu hình <a id="update-the-configuration-file"></a>
Vị trí tập tin cấu hình:
* Nếu phân bổ lưu trữ, vị trí thư mục cấu hình mặc định là `$INSTALL_PATH/kcn-linux-amd64/conf/`.
* Nếu phân bổ gói, vị trí thư mục cấu hình mặc định là `/etc/kpnd/conf/`.
#### Thêm Thư mục dữ liệu <a id="add-data-directory"></a>
Bạn nên cập nhật biến môi trường thư mục dữ liệu `$DATA_DIR`trên tập tin cấu hình `kcnd.conf`.
```text
...
DATA_DIR=/var/kcnd/data
...
```
#### Thiếp lập Rewardbase <a id="setup-rewardbase"></a>
Người vận hành CN sẽ nhận được KLAY như phần thưởng của việc tham gia vào đồng thuận mạng lưới Klaytn. Vì lý do này, cần phải thiết lập một địa chỉ trên tập tin cấu hình `kcnd.conf`.
Có nhiều cách để tạo tài khoản mới nhưng `kcn` cũng cung cấp các chức năng. Bạn có thể xem tin nhắn trợ giúp bằng lệnh sau.
```bash
$ kcn tài khoản new --help
```
Một trong những ví dụ về việc thực quy trình này như sau. Trước hết, bạn cần tạo một tài khoản mới để gửi phần thưởng KLAY đến.
```bash
$ kcn tài khoản new --datadir ~/kcnd_home
INFO[03/15,09:04:43 +09] [17] Setting connection type nodetype=cn conntype=-0
INFO[03/15,09:04:43 +09] [17] Maximum peer count KLAY=25 LES=0 total=25
INFO[03/15,09:04:43 +09] [17] SBN is disabled.
Tài khoản mới của bạn được khóa bằng mật khẩu. Vui lòng nhập mật khẩu. Đừng quên mật khẩu này.
Cụm mật khẩu:
Nhắc lại cụm mật khẩu:
Địa chỉ: {d13f7da0032b1204f77029dc1ecbf4dae2f04241}
```
Sau đó, lưu trữ khóa liên kết sẽ được tạo trên đường dẫn bạn đã xác định. Tiếp theo, bạn cần cho địa chỉ đã tạo vào tập tin `kcnd.conf` như sau.
```text
...
REWARDBASE="d13f7da0032b1204f77029dc1ecbf4dae2f04241"
...
```
Hãy nhớ rằng lưu trữ khóa và mật khẩu mà bạn đã tạo là vô cùng quan trọng. Do đó, bạn phải quản lý chúng thật cẩn thận. Xem thêm thông tin về `kcnd.conf` trên phần [Tập tin cấu hình](../../../misc/operation/configuration.md).
### Đồng bộ nhanh \(Tùy chọn\) <a id="fast-sync-optional"></a>
Mỗi CN duy trì một bản sao dữ liệu chuỗi của mạng lưới. Nếu một nút không được đồng bộ, nút này có thể lấy dữ liệu này từ các nút khác trong mạng lưới -- một quá trình được gọi là đồng bộ hóa. Khi một CN mới được bắt đầu lần đầu tiên, nó phải tải xuống toàn bộ dữ liệu chuỗi từ mạng lưới.
Để đẩy nhanh quá trình này, bạn cần thực hiện đồng bộ nhanh bằng cách tải về bản thu thập dữ liệu của dữ liệu chuỗi trước khi bắt đầu CN. Điều này giúp giảm đáng kể thời gian CN cần để đồng bộ khi bắt đầu lần đầu tiên.
Tải xuống bản thu thập dữ liệu chuỗi mới nhất từ [Lưu trữ thu thập dữ liệu Cypress](http://packages.klaytn.net/cypress/chaindata/) hoặc[Lưu trữ thu thập dữ liệu Baobab](http://packages.klaytn.net/baobab/chaindata/). Trước khi bắt đầu `kcnd`, trích xuất bản thu thập dữ liệu trong DATA\_DIR mà bạn định cấu hình trong `kcnd.conf`.
Ví dụ:
```bash
$ tar -C ~/kcnd_home -xvf klaytn-cypress-chaindata-latest.tar.gz
```
Hoặc,
```bash
$ tar -C ~/kcnd_home -xvf klaytn-baobab-chaindata-latest.tar.gz
```
Sau khi dữ liệu được trích xuất, bạn có thể bắt đầu CN như bình thường.
Bạn có thể tham khảo thông tin chi tiết tại [Thay đổi dữ liệu chuỗi](../../../misc/operation/chaindata-change.md)
## Khởi động CN <a id="startup-the-cn"></a>
### Bắt đầu/Dừng CN <a id="cn-start-stop"></a>
Bạn có thể bắt đầu/dừng dịch vụ Klaytn bằng lệnh `systemctl` sau đây.
**Lưu ý**: Việc này yêu cầu quyền root.
**bắt đầu**
```bash
$ systemctl start kcnd.service
```
**dừng**
```bash
$ systemctl stop kcnd.service
```
**trạng thái**
```bash
$ systemctl trạng thái kcnd.service
```
### Khắc phục sự cố <a id="troubleshooting"></a>
Nếu bạn gặp lỗi sau,
```bash
Không thể bắt đầu kcnd.service: Không tìm thấy đơn vị.
```
tải lại cấu hình trình quản lý hệ thống bằng lệnh sau.
```bash
$ systemctl daemon-reload
```
### Export BLS public key info <a id="export-bls-public-key-info"></a>
If the network has activated or will activate the Randao hardfork, each CN maintainer must submit its BLS public key info to the [KIP-113 smart contract](https://kips.klaytn.foundation/KIPs/kip-113).
The BLS public key info can be calculated from the nodekey. To extract it, first start the node. Then use the command:
```
$ kcn account bls-info --datadir /var/kcnd/data
```
As a result, `bls-publicinfo-NODEID.json` file will be created.
# Kiểm tra Core Cell <a id="testing-the-core-cell"></a>
Đã đến lúc kiểm tra xem Core Cell đã được cài đặt thành công chưa và nó có hoạt động như mong đợi sau khi cài đặt không.
## Tình trạng xử lý <a id="process-status"></a>
Có thể kiểm tra trạng thái quy trình của CN bằng các lệnh trạng thái `systemctl` và `kcnd`.
### systemctl <a id="systemctl"></a>
`systemctl` được cài đặt cùng với RPM, có thể kiểm tra trạng thái của CN như sau.
```bash
$ systemctl trạng thái kcnd.service
● kcnd.service - (null)
Loaded: loaded (/etc/rc.d/init.d/kcnd; bad; vendor preset: disabled)
Active: active (running) since Wed 2019-01-09 11:42:39 UTC; 1 months 4 days ago
Docs: man:systemd-sysv-generator(8)
Process: 29636 ExecStart=/etc/rc.d/init.d/kcnd start (code=exited, trạng thái=0/SUCCESS)
Main PID: 29641 (kcn)
CGroup: /system.slice/kcnd.service
└─29641 /usr/local/bin/kcn --networkid 1000 --datadir /kcnd_home --port 32323 --srvtype fasthttp --metrics --prometheus --verbosity 3 --txpool.global...
Jan 09 11:42:39 ip-10-11-2-101.ap-northeast-2.compute.internal systemd[1]: Starting (null)...
Jan 09 11:42:39 ip-10-11-2-101.ap-northeast-2.compute.internal kcnd[29636]: Starting kcnd: [ OK ]
Jan 09 11:42:39 ip-10-11-2-101.ap-northeast-2.compute.internal systemd[1]: Started (null).
```
Bạn có thể kiểm tra trạng thái hiện tại như `Active: active (running)` trong ví dụ trên.
### kcnd <a id="kcnd-kpnd"></a>
`kcnd` được cài đặt cùng với gói và trạng thái của CN có thể được kiểm tra như sau.
```bash
$ kcnd trạng thái
kcnd is running
```
## Nhật ký <a id="logs"></a>
Nhật ký được lưu ở `kcnd.out` tại đường dẫn xác định trong trường `LOG_DIR` của tập tin `kcnd.conf`. Khi nút hoạt động bình thường, bạn có thể thấy rằng mỗi giây sẽ có một khối được tạo như sau.
Ví dụ:
```bash
$ tail kcnd.out
INFO[02/13,07:02:24 Z] [35] Commit new mining work number=11572924 txs=0 elapsed=488.336µs
INFO[02/13,07:02:25 Z] [5] Imported new chain segment blocks=1 txs=0 mgas=0.000 elapsed=1.800ms mgasps=0.000 number=11572924 hash=f46d09…ffb2dc cache=1.59mB
INFO[02/13,07:02:25 Z] [35] Commit new mining work number=11572925 txs=0 elapsed=460.485µs
INFO[02/13,07:02:25 Z] [35] 🔗 block reached canonical chain number=11572919 hash=01e889…524f02
INFO[02/13,07:02:26 Z] [14] Committed address=0x1d4E05BB72677cB8fa576149c945b57d13F855e4 hash=1fabd3…af66fe number=11572925
INFO[02/13,07:02:26 Z] [5] Imported new chain segment blocks=1 txs=0 mgas=0.000 elapsed=1.777ms mgasps=0.000 number=11572925 hash=1fabd3…af66fe cache=1.59mB
INFO[02/13,07:02:26 Z] [35] Commit new mining work number=11572926 txs=0 elapsed=458.665µs
INFO[02/13,07:02:27 Z] [14] Committed address=0x1d4E05BB72677cB8fa576149c945b57d13F855e4 hash=60b9aa…94f648 number=11572926
INFO[02/13,07:02:27 Z] [5] Imported new chain segment blocks=1 txs=0 mgas=0.000 elapsed=1.783ms mgasps=0.000 number=11572926 hash=60b9aa…94f648 cache=1.59mB
INFO[02/13,07:02:27 Z] [35] Commit new mining work number=11572927 txs=0 elapsed=483.436µs
```
## bảng điều khiển kcn <a id="kcn-console-kpn-console"></a>
Klaytn cung cấp một CLI khách: `bảng điều khiển kcn`. Tuy nhiên, CN có thể vô hiệu hóa giao diện RPC cho máy khách vì lý do bảo mật. Một cách khác để sử dụng máy khách là kết nối với quy trình thông qua IPC (giao tiếp giữa các quy trình).
Tập tin IPC `klay.ipc` nằm ở thư mục `data` trên CN.
Hãy thực hiện lệnh sau và kiểm tra kết quả.
```bash
$ ken attach /var/kend/data/klay.ipc
Chào mừng bạn đến với bảng điều khiển Klaytn JavaScript!
instance: Klaytn/vX.X.X/XXXX-XXXX/goX.X.X
datadir: /var/kend/data
modules: admin:1.0 debug:1.0 governance:1.0 istanbul:1.0 klay:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0
>
```
Bạn có thể kiểm tra các lệnh có thể sử dụng trên [Tài liệu API](../../../references/json-rpc/json-rpc.md)
API hữu dụng để kiểm tra trạng thái của CN:
* `klay.blockNumber` (để lấy số khối mới nhất)
* `net.peerCount` (để lấy số nút Klaytn được kết nối hiện tại)
### klay.blockNumber <a id="klay-blocknumber"></a>
Bạn có thể lấy số khối mới nhất để xem liệu các khối được tạo (đối với CN) hay được truyền (đối với CN và PN) đúng cách không dựa trên loại nút của bạn.
```javascript
> klay.blockNumber
11573819
```
### net.peerCount <a id="net-peercount"></a>
```javascript
> net.peerCount
14
```
Dòng lệnh trên trả về một giá trị khác dựa trên loại nút.
* CN: số CN được kết nối + số PN được kết nối.
* PN: số CN được kết nối + số PN được kết nối + số EN được kết nối. |
<?php
namespace App\Http\Controllers;
use App\Models\Project;
use App\Models\Server;
use Illuminate\Http\Request;
use Inertia\Inertia;
class ProjectController extends Controller
{
public function index()
{
$projects = Project::query()
->with('latest_deployment')
->paginate(20);
$data = $projects->getCollection();
$data->each(fn ($item) => $item->setHidden([]));
$projects->setCollection($data);
return Inertia::render('Projects/Index', [
'projects' => $projects,
]);
}
public function create()
{
$servers = Server::query()
->where('status', 'connected')
->pluck('name', 'id');
return Inertia::modal('Projects/Create')
->with(['servers' => $servers])
->baseRoute('projects.index');
}
public function store(Request $request)
{
$validator = validator()->make($request->input(), [
'name' => ['required', 'string', 'max:255'],
'repository' => ['required', 'string', 'max:255'],
'branch' => ['required', 'string', 'max:255'],
'serverId' => ['required', 'exists:servers,id'],
'environment' => ['required', 'string', 'max:255'],
'deployPath' => ['required', 'string', 'max:255'],
]);
$validator->validate();
$this->validateRepo($request->repository, $request->branch, $validator);
$server = Server::find($request->serverId);
if (! $server) {
$validator->errors()->add('serverId', 'Server not found.');
}
if (count($validator->errors()->messages())) {
return redirect()
->back()
->withErrors($validator)
->withInput($request->input());
}
$project = new Project();
$project->user_id = auth()->id();
$project->name = $request->name;
$project->repository = $request->repository;
$project->live_url = $request->liveUrl;
$project->branch = $request->branch;
$project->server_id = $request->serverId;
$project->environment = $request->environment;
$project->deploy_path = $request->deployPath;
// Laravel preset
if ($request->useLaravelPreset) {
$project->cron_jobs = '* * * * * ' . ($server->cmd_php ?? 'php') . ' ' . $project->deploy_path . '/current/artisan schedule:run >> ' . $project->deploy_path . '/shared/storage/logs/scheduler.log';
$project->linked_dirs = ['storage/app', 'storage/framework', 'storage/logs'];
$project->hooks = [
'built' => ''
. 'cd {!! $release_path !!}' . PHP_EOL
. PHP_EOL
. 'echo "⭐ Laravel magic!"' . PHP_EOL
. PHP_EOL
. 'php artisan down' . PHP_EOL
. PHP_EOL
. 'php artisan storage:link' . PHP_EOL
. PHP_EOL
. 'php artisan config:clear' . PHP_EOL
. 'php artisan view:clear' . PHP_EOL
. 'php artisan cache:clear' . PHP_EOL
. 'php artisan clear-compiled' . PHP_EOL
. 'php artisan config:cache' . PHP_EOL
. PHP_EOL
. 'php artisan migrate --force' . PHP_EOL
. PHP_EOL
. 'php artisan up' . PHP_EOL,
];
// Try to load .env.example
[$user, $repo] = explode('/', $project->repository);
$ghClient = auth()->user()->github()->repository()->contents();
$project->env = rescue(fn () => base64_decode($ghClient->show($user, $repo, '.env.example')['content']), null, false);
}
$project->save();
return redirect()->route('projects.show', $project->id);
}
public function show(Project $project)
{
$deploymentsStats = [
'today' => $project->deployments()->whereBetween('created_at', [now()->startOfDay(), now()->endOfDay()])->count(),
'thisWeek' => $project->deployments()->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
'latestDuration' => $project->deployments()->latest()->first()?->duration,
];
return Inertia::render('Projects/Show', [
'project' => $project,
'deploymentsStats' => $deploymentsStats,
]);
}
public function edit(Project $project)
{
return redirect()->route('projects.edit.common', $project);
}
public function editCommon(Project $project)
{
$project->makeVisible(['server_id', 'environment', 'deploy_path']);
$servers = Server::query()
->where('status', 'connected')
->pluck('name', 'id');
return Inertia::render('Projects/Edit/Common', [
'project' => $project,
'servers' => $servers,
]);
}
public function updateCommon(Request $request, Project $project)
{
$validator = validator()->make($request->input(), [
'name' => ['required', 'string', 'max:255'],
'repository' => ['required', 'string', 'max:255'],
'branch' => ['required', 'string', 'max:255'],
'liveUrl' => ['string', 'max:255'],
'serverId' => ['required', 'exists:servers,id'],
'environment' => ['required', 'string', 'max:255'],
'deployPath' => ['required', 'string', 'max:255'],
]);
$validator->validate();
$this->validateRepo($request->repository, $request->branch, $validator);
$server = Server::find($request->serverId);
if (! $server) {
$validator->errors()->add('serverId', 'Server not found.');
}
if (count($validator->errors()->messages())) {
return redirect()
->back()
->withErrors($validator)
->withInput($request->input());
}
$project->name = $request->name;
$project->repository = $request->repository;
$project->live_url = $request->liveUrl;
$project->server_id = $request->serverId;
$project->environment = $request->environment;
$project->deploy_path = $request->deployPath;
$project->save();
return redirect()
->route('projects.edit.common', $project)
->with('success', 'Project updated!');
}
public function editEnvFile(Project $project)
{
$project->makeVisible(['env']);
return Inertia::render('Projects/Edit/EnvFile', [
'project' => $project,
]);
}
public function updateEnvFile(Request $request, Project $project)
{
$project->env = $request->env;
$project->save();
return redirect()
->route('projects.edit.env-file', $project)
->with('success', 'Environment file updated!');
}
public function editHooks(Project $project)
{
$project->makeVisible(['hooks']);
return Inertia::render('Projects/Edit/Hooks', [
'project' => $project,
]);
}
public function updateHooks(Request $request, Project $project)
{
$project->hooks = [
'started' => $request->started,
'provisioned' => $request->provisioned,
'built' => $request->built,
'published' => $request->published,
'finished' => $request->finished,
];
$project->save();
return redirect()
->route('projects.edit.hooks', $project)
->with('success', 'Hooks updated!');
}
public function editCronJobs(Project $project)
{
$project->makeVisible(['cron_jobs']);
return Inertia::render('Projects/Edit/CronJobs', [
'project' => $project,
]);
}
public function updateCronJobs(Request $request, Project $project)
{
$project->cron_jobs = $request->cronJobs;
$project->save();
return redirect()
->route('projects.edit.cron-jobs', $project)
->with('success', 'Cron jobs updated!');
}
public function editShared(Project $project)
{
$project->makeVisible(['linked_dirs', 'linked_files']);
return inertia('Projects/Edit/Shared', [
'project' => $project,
]);
}
public function updateShared(Request $request, Project $project)
{
$project->linked_dirs = $request->linkedDirs;
$project->linked_files = $request->linkedFiles;
$project->save();
return redirect()
->route('projects.edit.shared', $project)
->with('success', 'Linked directories updated!');
}
public function destroy(Project $project)
{
$project->delete();
return redirect()->route('projects.index');
}
protected function validateRepo($repository, $branch, &$validator)
{
// Can we access the project?
[$user, $repo] = explode('/', $repository);
$ghClient = auth()->user()->github()->repository();
if (! rescue(fn () => $ghClient->show($user, $repo), null, false)) {
$validator->errors()->add('repository', "Whoops! It seems that we can't access this repository.");
}
if (! rescue(fn () => $ghClient->branches($user, $repo, $branch), null, false)) {
$validator->errors()->add('branch', 'Whoops! Unknown branch.');
}
}
} |
#include <stdio.h>
#include <stdbool.h>
void conversionTabletFromFahrenheitToCelsius(const bool r) {
const int upper = 300;
const int lower = 0;
int fahr = lower;
printf("Temperature conversion table\n");
printf("\nFº\tCº\n");
// If r == true, the table will be printed in reverse order
if (r) {
fahr = upper;
while (fahr >= lower) {
const int step = 20;
const int celsius = 5 * (fahr - 32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr - step;
}
return;
}
while (fahr <= upper) {
const int step = 20;
const int celsius = 5 * (fahr - 32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
}
void conversionTabletFromCelsiusToFahrenheit(const bool r) {
const int upper = 300;
const int lower = 0;
int celsius = lower;
printf("Temperature conversion table\n");
printf("\nCº\tFº\n");
// if r == true, the table will be printed in reverse order
if (r) {
celsius = upper;
while (celsius >= lower) {
const int step = 20;
const int fahr = (9 * celsius) / 5 + 32;
printf("%d\t%d\n", celsius, fahr);
celsius = celsius - step;
}
return;
}
while (celsius <= upper) {
const int step = 20;
const int fahr = (9 * celsius) / 5 + 32;
printf("%d\t%d\n", celsius, fahr);
celsius = celsius + step;
}
}
int main() {
conversionTabletFromFahrenheitToCelsius(0);
printf("\n");
conversionTabletFromCelsiusToFahrenheit(0);
printf("\n");
conversionTabletFromFahrenheitToCelsius(1);
return 0;
} |
import React, { createContext, useContext, useState, useEffect } from "react";
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("theme1"); // Default theme
useEffect(() => {
// Load the theme from local storage if available
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
setTheme(savedTheme);
}
}, []);
const toggleTheme = (newColor) => {
const newTheme = newColor;
console.log(newTheme);
setTheme(newTheme);
localStorage.setItem("theme", newTheme); // Save theme to local storage
};
function getColor(theme) {
if (theme === "theme1") {
return "#f57272";
} else if (theme === "theme2") {
return "#72a7f5";
} else if (theme === "theme3") {
return "#2ecc71";
} else {
return "white";
}
}
return (
<ThemeContext.Provider value={{ theme, toggleTheme, getColor }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
return useContext(ThemeContext);
} |
<!DOCTYPE html>
<html>
<head>
<title>Lab 17</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="css/lab17.css" type="text/css" rel="stylesheet">
<script src="js/lab17.js" defer></script>
<link href="https://fonts.googleapis.com/css2?family=Baloo+Bhaina+2:wght@500&display=swap" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-6">
<div class="row">
<h1 id="title">Lab 17: Advanced jQuery</h1>
</div>
<div class="row">
<h2>Challenge</h2>
<p>The real Challenge was getting this entire assignment to work. The goal was to create buttons which can then be toggled using jQuery.</p>
</div>
<div class="row">
<h2>Problems</h2>
<p>I had the most difficulty with this assignment for some reason. At first, I created buttons in my HTML and then using the html() Method I tried to add innerHTML to the buttons, like Wes showed in class, but that didn't work. Then I tried instead to hard code everything in jquery, so I created a variable with a button element. I then tried adding text to the buttons by using the html() Method and then using the append() Method to append the html to the button, which worked for the text inside the button, but didn't properly work for toggling the classes of each button as directed. I then instead redid my original code, but instead of using the html() Method, I made buttons in my html and added a text label. For my Javascript/jQuery, I added a .click event to each button and using removeClass and toggleClass to have the buttons toggle between different classes. However I was unable to get the desired result, which was to toggle the button between the green color and the color I changed each button to.</p>
</div>
<div class="row">
<strong><a href="https://itcdland.csumb.edu/~jwoldstad/cst252/lab17/js/lab17.js">JavaScript Link</a></strong>
</div>
<div class="row space"></div>
<div class="row">
<h2>Task X</h2>
</div>
<div class="row">
<p>Unlike the rest of my code, this was much more straightforward. To cycle the button between different classes, I made an array of different colors for the button to change to. I then added a click event and used the css() method, to change the color of the button from colors in the array. To have the color1 variable sift through the colors starting at 0, I added ++. Lastly, I then created a for loop to have the color array sift back to 0 once it reaches the end of the array.</p>
</div>
</div>
<div class="col-1"></div>
<div class="col-5">
<div class="row">
<h2>Results!</h2>
</div>
<div class="row">
<p>Click the button belows below for the desired result.</p>
</div>
<div id="output">
<div class="row">
<button id="button1" class="green">Click me!</button>
</div>
<div class="row">
<button id="button2" class="green">No me!</button>
</div>
<div class="row">
<button id="button3" class="green">Hey Click me!</button>
</div>
<div class="row">
<button id="button4" class="taskx">Keep clicking me!</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html> |
@once
@push('css')
<style>
:root {
--l2p-height: 400px;
--l2p-background-color: aliceblue;
}
.l2p-root,
.l2p-root * {
box-sizing: border-box;
}
.l2p-root {
width: 100%;
height: var(--l2p-height);
display: flex;
flex-direction: column;
}
.l2p-root > .l2p-top {
display: flex;
flex-direction: row;
align-items: end;
}
.l2p-root > .l2p-top > label {
flex: 1;
font-size: 0.9em;
padding: 0;
margin: 0;
}
.l2p-root > .l2p-top > .l2p-pop-button {
padding: 3px 6px;
}
.l2p-root > iframe {
flex: 1;
overflow: auto;
background-color: var(--l2p-background-color);
}
</style>
@endpush
@endonce
@push('js')
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('label2_preview', () => ({
_form: null,
_init: function() {
this._form = this.$root.closest('form');
this._form.addEventListener('change', this.updateURL.bind(this));
},
updateURL: function() {
let params = {
settings: Object.assign({}, ...$(this._form)
.serializeArray()
.filter((value, index, all) => value.name.includes('label2_'))
.map((value, index, all) => ({[value.name]: value.value}))
)
};
let template = params.settings.label2_template;
if (!template) return;
this.previewURL = '{{ route("labels.show", ["labelName" => ":label"]) }}'
.replace(':label', template.replaceAll('\\', '/'))
.concat('?', $.param(params), '#toolbar=0');
},
_previewURL: '',
get previewURL() { return this._previewURL; },
set previewURL(url) {
this._previewURL = url;
if (this._popped) this._popped.location = this.previewURL;
},
_popped: null,
popout: function() { this._popped = window.open(this.previewURL); }
}));
});
</script>
@endpush
<div x-data="label2_preview" x-init="_init" class="l2p-root">
<div class="l2p-top">
<label for="label2-preview">Preview</label>
<button class="l2p-pop-button btn btn-default" x-on:click.prevent="popout" title="Pop Out"><i class="fa-solid fa-maximize"></i></button>
</div>
<iframe id="label2-preview" x-bind:src="previewURL"></iframe>
</div> |
import { useEffect, useState } from 'react';
import { nanoid } from 'nanoid';
import { Layout } from './Layout/Layout';
import { Section } from './Section/Section';
import { ContactForm } from './ContactForm/ContactForm';
import { Filter } from './Filter/Filter';
import { ContactList } from './ContactList/ContactList';
export function App() {
const defaultContacts = [
{ id: 'id-1', name: 'Rosie Simpson', number: '459-12-56' },
{ id: 'id-2', name: 'Hermione Kline', number: '443-89-12' },
{ id: 'id-3', name: 'Eden Clements', number: '645-17-79' },
{ id: 'id-4', name: 'Annie Copeland', number: '227-91-26' },
];
const existingContacts = window.localStorage.getItem('contacts');
const [contacts, setContacts] = useState(
() => JSON.parse(existingContacts) ?? defaultContacts
);
const [filter, setFilter] = useState('');
useEffect(() => {
window.localStorage.setItem('contacts', JSON.stringify(contacts));
}, [contacts]);
let filterInputId = nanoid();
const addContact = (name, number) => {
const contact = {
id: nanoid(),
name,
number,
};
const findContact = contacts.find(contact => contact.name === name);
if (findContact) {
alert(`${findContact.name} is already in contacts`);
return;
}
setContacts(prevState => [...prevState, contact]);
};
const handleChangeFilter = event => {
const { value } = event.target;
setFilter(value);
};
const getVisibleContacts = () => {
return contacts.filter(contact =>
contact.name.toLowerCase().includes(filter.toLowerCase())
);
};
const deleteContact = contactId => {
setContacts(prevState => prevState.filter(({ id }) => id !== contactId));
};
return (
<Layout title="phonebook">
<ContactForm onAddContact={addContact}></ContactForm>
{contacts.length > 0 && (
<Section title="Contacts">
{contacts.length > 2 && (
<Filter
id={filterInputId}
value={filter}
onChangeFilter={handleChangeFilter}
/>
)}
<ContactList
contacts={getVisibleContacts()}
onDeleteContact={deleteContact}
></ContactList>
</Section>
)}
</Layout>
);
} |
<template>
<div>
<div v-if="characters.length > 0 || episodes.length > 0 || locations.length > 0">
<div
class="text-6xl text-center font-normal leading-normal mt-0 mb-2 text-pink-800"
>
VOS LIKES
</div>
<!-- list characters -->
<div v-if="characters.length > 0">
<div class="flex items-center justify-center mt-4">
<div class="text-3xl title">
Vos personnages préférés
<Toggle @update:parent="toggleCharacter = !$event" class="toggle" />
</div>
</div>
<div
class="container-character flex flex-wrap items-center justify-center"
:class="{ hidden: toggleCharacter }"
>
<div
class="card relative"
v-for="(item, index) in characters"
v-bind:key="index"
>
<div v-if="item != null">
<n-link :to="'/characters/' + substr(item)">
<CardCharacter :idCharacter="substr(item)" />
</n-link>
<Like :id="'c' + substr(item)" :type="'character'" :url="item" />
</div>
</div>
</div>
</div>
<!-- List épisodes -->
<div v-if="episodes.length > 0">
<div class="flex items-center justify-center mt-4">
<div class="text-3xl title">
Vos épisodes préférés
<Toggle @update:parent="toggleEpisode = !$event" class="toggle" />
</div>
</div>
<div
v-for="(item, index) in episodes"
v-bind:key="index"
class="relative"
:class="{ hidden: toggleEpisode }"
>
<div v-if="item != null">
<n-link :to="'/episodes/' + substr(item)">
<CardEpisode :episodeId="substr(item)" />
</n-link>
<Like :id="'e' + substr(item)" :type="'episode'" :url="item" />
</div>
</div>
</div>
<!-- List épisodes -->
<div v-if="locations.length > 0">
<div class="flex items-center justify-center mt-4">
<div class="text-3xl title">
Vos planètes préférées
<Toggle @update:parent="toggleLocation = !$event" class="toggle" />
</div>
</div>
<div
v-for="(item, index) in locations"
v-bind:key="index"
class="relative"
:class="{ hidden: toggleLocation }"
>
<div v-if="item != null">
<n-link :to="'/locations/' + substr(item)">
<CardLocation :locationId="substr(item)" />
</n-link>
<Like :id="'l' + substr(item)" :type="'location'" :url="item" />
</div>
</div>
</div>
</div>
<div v-else id="presentation-like" class="flex justify-center items-center">
<div class="text-4xl text-center">
Bienvenue sur le site de la série<br />
<strong>Rick et Morty</strong><br /><br />
Vous pouvez liker des épisodes, personnages ou localisations et les retrouver sur
cette page !!!
</div>
</div>
</div>
</template>
<style lang="scss" scoped>
.container-character {
.card {
padding: 10px;
}
}
#presentation-like {
div {
margin: 100px;
}
}
.title {
position: relative;
}
.toggle {
position: absolute;
top: 50%;
transform: translateY(-50%);
right: -80px;
}
@media only screen and (max-width: 600px) {
.title {
position: static;
}
.toggle {
justify-content: center;
position: static;
transform: translateY(0);
top: 0;
right: 0;
}
}
</style>
<script>
import CardCharacter from "~/components/character/CardCharacter.vue";
import CardEpisode from "~/components/episode/CardEpisode.vue";
import CardLocation from "~/components/location/CardLocation.vue";
export default {
name: "IndexPage",
components: {
CardCharacter,
CardEpisode,
CardLocation,
},
data() {
return {
characters: [],
episodes: [],
locations: [],
toggleCharacter: false,
toggleEpisode: false,
toggleLocation: false,
};
},
mounted() {
if (localStorage.getItem("character")) {
let tabTempo = [];
tabTempo = JSON.parse(localStorage.getItem("character"));
this.characters = tabTempo;
}
if (localStorage.getItem("episode")) {
let tabTempo = [];
tabTempo = JSON.parse(localStorage.getItem("episode"));
this.episodes = tabTempo;
}
if (localStorage.getItem("location")) {
let tabTempo = [];
tabTempo = JSON.parse(localStorage.getItem("location"));
this.locations = tabTempo;
}
},
methods: {
substr: function (data) {
return data.substring(data.lastIndexOf("/") + 1);
},
},
};
</script> |
/**
* 객체의 키-값 쌍을 FormData 객체에 추가하는 함수
* @param params - 키-값 쌍을 포함한 객체
* @param excludeKeys - FormData에 추가하지 않을 키 목록
* @returns 데이터가 추가된 FormData 객체
*/
export const convertFormData = ({
params,
excludeKeys = [],
}: {
params: { [key: string]: any }
excludeKeys: string[]
}): FormData => {
const formData = new FormData()
// 객체의 각 키-값 쌍을 순회하며 FormData에 추가
Object.entries(params).forEach(([key, value]) => {
// 제외할 키 목록에 없고, 값이 undefined가 아닌 경우만 추가
if (value !== undefined && !excludeKeys.includes(key)) {
formData.append(key, value)
}
})
return formData
} |
<!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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<title>bootstrap test</title>
</head>
<body>
<h1 class="text-light bg-primary"> Bootstrap Test with my own.</h1>
<div class="container">
<h1 class="bg bg-dark text-center display-3 text-light">This is my h1 tag.</h1>
</div>
<div class="container">
<h1>Bootstrap button's</h1>
<button class="btn btn-warning">warning</button>
<button class="btn btn-primary">primary</button>
<button class="btn btn-success">success</button>
<button class="btn btn-danger">danger</button>
<button class="btn btn-info">info</button>
<button class="btn btn-secondary">secondary</button>
<button class="btn btn-light">light</button>
<button class="btn btn-dark">Dark</button>
<button class="btn btn-link border">link</button>
</div>
<div class="container bg-warning border">
<h3>example of disabled button</h3>
<button class="btn btn-dark" disabled>warning</button>
<h2>Example of outline button.</h2>
<button class="btn btn-outline-danger">danger</button>
<h1>Example of button badge </h1>
<button class="btn btn-primary">updates <span class="badge text-dark">9+</span></button>
<p class="bg bg-info text-dark border">Lorem ipsum dolor sit amet consectetur adipisicing elit. Id sint nihil voluptatem debitis consequuntur blanditiis reprehenderit laboriosam? Explicabo, architecto possimus. Voluptatem exercitationem sit temporibus? Veniam maiores dolor quibusdam laudantium consectetur placeat, saepe est hic autem minima voluptates atque tempore sequi voluptatem. Officiis, aliquid! Earum iusto magnam veritatis architecto saepe hic odio obcaecati aliquam nesciunt distinctio voluptatem necessitatibus ex quia exercitationem molestiae similique non modi porro, expedita alias debitis optio ducimus corporis laborum! Dolor laborum ducimus libero, saepe magni ratione unde enim quibusdam ullam, repellendus fuga obcaecati ipsum. Nemo unde voluptatum omnis sit minima fugiat aliquid, temporibus enim, porro libero alias! Facilis voluptas enim maiores ut laboriosam asperiores fuga eligendi sint, nobis repudiandae fugiat quis pariatur sequi praesentium cum temporibus ducimus distinctio? Incidunt nisi obcaecati corrupti, aspernatur officia ipsam ea, soluta eius, debitis libero recusandae nam possimus? Quia impedit illo labore! Saepe eveniet quod soluta, labore nesciunt dolore error aliquam tempora praesentium velit est? Soluta nesciunt accusamus, voluptate officiis deleniti perferendis harum eaque laudantium? Eaque tempora nesciunt dolor voluptatum tempore, similique quo. Sequi saepe similique vero atque, ipsa officia illum assumenda nemo sint tempore iste blanditiis earum deleniti cumque ullam ipsam nihil nobis placeat hic dolorum, dolores praesentium sit perspiciatis. Velit eligendi nostrum a eveniet vel officiis iste soluta. Natus, ad sapiente. Magnam ab itaque, minus placeat dolor at sit iusto animi incidunt, fugit ullam odio corrupti. Ducimus ab voluptates id aspernatur! Illo atque assumenda officia voluptate dolore aperiam esse, accusantium expedita iure saepe similique consectetur adipisci vitae ipsam tempora repellendus quaerat! Dolor vel et voluptatem culpa sint, nobis consequuntur labore sequi deleniti beatae id consequatur quasi totam dicta dolorum ex quisquam magnam, ducimus quas dignissimos dolore nemo officiis iusto laudantium. Expedita debitis et, ex rerum ad officiis? Itaque cum optio tempora pariatur fuga impedit provident. Illo mollitia et iusto illum.</p>
<h1 class="display-1">This is my h1 tag.</h1>
<h1 class="display-2">This is my h2 tag.</h1>
<h1 class="display-3">This is my h3 tag.</h1>
<h1 class="display-4">This is my h4 tag.</h1>
<h2>Blockquote</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quo molestias quaerat suscipit magnam maxime. Maxime minus, ut omnis distinctio assumenda corporis? Rem officiis aliquam natus maiores autem! Facere odio aperiam minima nam magni perspiciatis itaque ullam temporibus officia pariatur laudantium ea, eligendi reprehenderit fuga molestias, tempora, inventore illum dicta consequuntur illo labore quasi facilis architecto molestiae.<blockquote class="text-primary">Suscipit est culpa ipsa dolore perferendis tempore nisi unde! Nihil temporibus rerum labore ratione enim optio nostrum autem, quod ex at repudiandae harum sapiente aut.</blockquote> Quam iure placeat consequatur minus veritatis necessitatibus tempora quibusdam corrupti excepturi non labore, eos animi illo voluptates at laboriosam vel temporibus? Aut quisquam consequuntur ab vitae libero minima sint quos eligendi veniam vel? Numquam saepe sed obcaecati sapiente distinctio necessitatibus deserunt repellat sint velit laborum enim voluptates impedit blanditiis vel, architecto vero fugit nostrum? Exercitationem perferendis molestiae ab nisi placeat dolores aliquam rerum commodi rem reprehenderit mollitia expedita unde quo distinctio quos, corrupti esse sapiente corporis. Repudiandae voluptas deleniti nisi praesentium aspernatur labore possimus distinctio cumque quas. Ullam blanditiis, ipsam, incidunt sit hic veniam perspiciatis, sapiente laborum in laudantium nam fugiat maiores placeat. Ipsum, earum libero ullam dolore officiis nisi consectetur voluptatum possimus vero, sit quos, repudiandae quisquam mollitia?</p>
<h2>Bootstrap Alerts</h2>
<p class="alert alert-light text-primary"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem itaque ipsam culpa illum eligendi. Voluptatem ab voluptates fuga amet placeat quaerat asperiores. A eveniet atque ad. Illo quis eveniet doloremque aspernatur. Ea soluta, cum eius fuga molestiae iure, autem exercitationem rem ad atque sunt obcaecati pariatur illum architecto illo placeat beatae eveniet a. Quas voluptates voluptatibus at illum aliquam excepturi minus, atque nisi amet magnam porro voluptas mollitia laboriosam adipisci cum, perferendis quo iste! Minima alias numquam eius esse amet.</p>
</div>
<div class="container">
<h2>Bootstrap Form</h2>
<form action="http://www.google.com">
<label for="name"><input type="text" placeholder="first name"></label>
</form>
<!-- As a link -->
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
</div>
</nav>
<!-- As a heading -->
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<span class="navbar-brand mb-0 h1">Navbar</span>
</div>
</nav>
</div>
</body>
</html> |
package package_marcus_herbert;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
/**
* Threads used to test the Bakery algorithm for mutual exclusion
*/
public class BakeryProcess extends Thread{
private static ArrayList<BakeryProcess> processes;
private static int nextID;
private static boolean[] choosing;
private static long[] number;
private int id;
private Comparator<BakeryProcess> comp;
/**
* Sets all the shared information to it's required initial state for the Bakery algorithm
*/
public static void initializeSharedInfo () {
//comparator used to sort by id
Comparator<BakeryProcess> idComp = new Comparator<BakeryProcess>() {
@Override
public int compare(BakeryProcess o1, BakeryProcess o2) {
return o1.id-o2.id;
}
};
Collections.sort(processes, idComp);
int n = processes.size();
choosing = new boolean[n];
number = new long[n];
for (int i = 0; i < n; i++) {//setting all the information to its initial state
choosing[i] = false;
number[i] = 0;
}
}
/**
* Finds the largest long in an array of long
*
* @param nums
* @return
*/
public static long max (long[] nums) {
long highest = Long.MIN_VALUE;
for (long i: nums) {
if (i > highest) {
highest = i;
}
}
return highest;
}
/**
* Creates a process with the next id that has not been used
*/
public BakeryProcess () {
this.id = nextID++;
if (processes == null) {//if this is the first to be created, create a list for the processes
processes = new ArrayList<BakeryProcess>();
}
processes.add(this);
//comparator used to determine order of entry for threads entering the critical section
//first takes the smallest number obtained from the bakery algorithm, takes smallest id if there is a tie for the number
comp = new Comparator<BakeryProcess>() {
@Override
public int compare(BakeryProcess o1, BakeryProcess o2) {
if (number[o1.id] == number[o2.id]) {
return o1.id-o2.id;
}else{
return (int)(number[o1.id]-number[o2.id]);
}
}
};
}
/**
* Enters the critical section once allowed to by the Bakery algorithm
* Prints it's id and it's number obtained from the Bakery algorithm
* Stops
*/
@Override
public void run() {
Random rand = new Random();
//randomly wait for up to a millisecond, so threads don't necessarily arrive in order of id
try {
sleep(0, rand.nextInt(1000));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//start of acquiring a number
choosing[id] = true;
number[id] = Long.MIN_VALUE;
number[id] = 1+max(number);
choosing[id] = false;
//end of acquiring a number
int n = number.length;
//it is this threads turn to enter the critical section when:
// no other process is choosing a number
// it has the smallest number that has not gone through
// if there is a tie for the number, if it has the smallest id of those that are tied
for (int i = 0; i < n; i++) {
while (choosing[i] != false) {
}
while (number[i] != 0 && comp.compare(this, processes.get(i)) > 0) {
try {
sleep(0, 1);//sleep fixes code
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
//start of critical section
System.out.println("ID: " + id + " Number: " + number[id]);
//end of critical section
number[id] = 0;//resets this thread
}
} |
// HomeScreen.tsx
import React, { useEffect, useState } from 'react';
import { View, StyleSheet, TouchableOpacity, ActivityIndicator, FlatList, Linking, Pressable } from 'react-native';
import Colors from '../theme/colors'; // Import color palette
import { StackNavigationProp } from '@react-navigation/stack';
import { CustomText } from '../components';
import { getAPI, getLocalData } from '../utils/helper';
import { BASE_URL } from '../utils/constant';
type HomeNavigationProp = StackNavigationProp<MainTabsParamList, 'Home'>;
type Courses = {
id: string;
name: string;
};
interface HomeScreenProps {
navigation: HomeNavigationProp; // Adjust the type as needed
}
// HomeScreen functional component
const HomeScreen: React.FC<HomeScreenProps> = ({ navigation }) => {
const handleContinue = () => {
// navigation.navigate(''); // Navigate to the next screen
};
// Function to navigate to the website
const goToWebsite = () => {
Linking.openURL('https://google.com');
}
// State hooks for loading status and courses data
const [isLoading, setLoading] = useState(false);
const [data, setData] = useState<Courses[]>([]);
// Function to fetch courses data from API
const getCourses = async () => {
const universityName = await getLocalData('universityName');
try {
const response = await getAPI({ apiUrl: `${BASE_URL}/${universityName}/depts` });
setData(response);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
// Effect hook to initiate data fetching on component mount
useEffect(() => {
setLoading(true);
setTimeout(() => {
getCourses();
}, 3000);
}, []);
const handleOnItemPress = (id: string) => {
alert(id)
// navigation.navigate(''); // Navigate to the next screen with the course id
}
// Function to render each item in the list
const renderItem = ({ item }: { item: Courses }) => {
return (
<Pressable style={styles.itemBlock} onPress={() => handleOnItemPress(item.id)}>
<CustomText textStyle={styles.itemText} content={item.name} />
</Pressable>
)
}
// Main render function for HomeScreen
return (
<View style={styles.container}>
<CustomText
fontSize={24}
fontWeight='bold'
content="Welcome Patel"
/>
<TouchableOpacity onPress={goToWebsite}>
<CustomText
fontSize={16}
color={Colors.green}
content="Click here to Go to Website"
/>
</TouchableOpacity>
<View style={styles.listBlock}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={data}
keyExtractor={({ id }) => id}
renderItem={renderItem}
numColumns={3}
/>
)}
</View>
</View>
);
};
// Styles for the HomeScreen components
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
backgroundColor: Colors.white,
paddingTop: 20
},
welcomeText: {
fontSize: 24,
fontWeight: 'bold',
},
itemBlock: {
borderWidth: 1,
borderRadius: 10,
width: 100,
margin: 10,
justifyContent: 'center',
height: 70
},
itemText: {
textAlign: 'center'
},
listBlock: {
flex: 1,
padding: 24
}
});
export { HomeScreen }; |
import React, { useState } from "react";
import {HiMenu, HiMenuAlt4} from "react-icons/hi";
import {AiOutlineClose} from "react-icons/ai";
import logo from "../../images/logo.png";
const NavMenuListitem = ({itemName, itemStyleClass}) => {
return(
<li className={`mx-4 cursor-pointer ${itemStyleClass}`}>{itemName}</li>
);
}
const Navbar = () => {
const [navToggleMenu, setNavToggleMenuState] = useState(false);
return(
<nav className="w-full flex md:justify-center justify-between items-center p-4">
<div className="md:flex-[0.5] flex-initial justify-center items-center">
<img src={logo} alt="logo" className="w-32 cursor-pointer"/>
</div>
<ul className="text-white md:flex hidden list-none flex-row justify-between items-center flex-initial">
{["Market","Exchange","Tutorials","Wallets"].map((item, index) => {
return (<NavMenuListitem key={item+index} itemName={item} itemStyleClass=""/>);
})}
<li className="bg-[#2952e3] py-2 px-7 mx-4 rounded-full cursor-pointer hover:bg-[#2546bd]">
Login
</li>
</ul>
<div className="flex relative">
{navToggleMenu ? <AiOutlineClose fontSize={28} className="text-white md:hidden cursor-pointer" onClick={() => setNavToggleMenuState(false)}/>
: <HiMenu fontSize={28} className="text-white md:hidden cursor-pointer" onClick={() => setNavToggleMenuState(true)}/>}
{navToggleMenu && (
<ul className="z-10 fixed top-0 -right-2 p-3 w-[70vw] h-screen shadow-2xl md:hidden list-none
flex flex-col justify-start items-end rounded-md blue-glassmorphism text-white animate-slide-in">
<li className="text-xl w-full my-2">
<AiOutlineClose onClick={() => setNavToggleMenuState(false)}/>
</li>
{["Market","Exchange","Tutorials","Wallets"].map((item, index) => {
return (<NavMenuListitem key={item+index} itemName={item} itemStyleClass="my-2 text-lg"/>);
})}
</ul>
)}
</div>
</nav>
);
}
export default Navbar; |
import { mockAuthenticationParams } from '@/tests/domain/mock-account'
import { LoadAccountByEmailRepositorySpy, HashComparerSpy, EncrypterSpy } from '@/tests/data/mocks'
import { DbAuthentication } from '@/data/usecases/account/db-authentication'
import { throwError } from '@/tests/domain/test-helpers'
type SutTypes = {
sut: DbAuthentication
loadAccountByEmailRepositorySpy: LoadAccountByEmailRepositorySpy
hashComparerSpy: HashComparerSpy
encrypterSpy: EncrypterSpy
}
const makeSut = (): SutTypes => {
const loadAccountByEmailRepositorySpy = new LoadAccountByEmailRepositorySpy()
const hashComparerSpy = new HashComparerSpy()
const encrypterSpy = new EncrypterSpy()
const sut = new DbAuthentication(loadAccountByEmailRepositorySpy, hashComparerSpy, encrypterSpy)
return {
sut,
loadAccountByEmailRepositorySpy,
hashComparerSpy,
encrypterSpy,
}
}
describe('DbAuthentication Usecase', () => {
test('Should call Encryter with correct plaintext', async () => {
const { sut, encrypterSpy, loadAccountByEmailRepositorySpy } = makeSut()
await sut.auth(mockAuthenticationParams())
expect(encrypterSpy.plaintext).toBe(loadAccountByEmailRepositorySpy.result.id)
})
test('Should throw if Encrypter throws', async () => {
const { sut, encrypterSpy } = makeSut()
jest.spyOn(encrypterSpy, 'encrypt').mockImplementationOnce(throwError)
const promise = sut.auth(mockAuthenticationParams())
await expect(promise).rejects.toThrow()
})
test('Should call HashComparer with correct values', async () => {
const { sut, hashComparerSpy, loadAccountByEmailRepositorySpy } = makeSut()
await sut.auth(mockAuthenticationParams())
expect(hashComparerSpy.plaintext).toBe(mockAuthenticationParams().password)
expect(hashComparerSpy.digest).toBe(loadAccountByEmailRepositorySpy.result.password)
})
test('Should throw if HashComparer throws', async () => {
const { sut, hashComparerSpy } = makeSut()
await sut.auth(mockAuthenticationParams())
jest.spyOn(hashComparerSpy, 'compare').mockImplementationOnce(throwError)
const promise = sut.auth(mockAuthenticationParams())
await expect(promise).rejects.toThrow()
})
test('Should return null if LoadAccountByEmailRepository returns null', async () => {
const { sut, loadAccountByEmailRepositorySpy } = makeSut()
loadAccountByEmailRepositorySpy.result = null
const response = await sut.auth(mockAuthenticationParams())
expect(response).toBeNull()
})
test('Should call LoadAccountByEmailRepository with correct email', async () => {
const { sut, loadAccountByEmailRepositorySpy } = makeSut()
await sut.auth(mockAuthenticationParams())
expect(loadAccountByEmailRepositorySpy.email).toBe(mockAuthenticationParams().email)
})
test('Should throw if LoadAccountByEmailRepository throws', async () => {
const { sut, loadAccountByEmailRepositorySpy } = makeSut()
await sut.auth(mockAuthenticationParams())
jest.spyOn(loadAccountByEmailRepositorySpy, 'loadByEmail').mockImplementationOnce(throwError)
const promise = sut.auth(mockAuthenticationParams())
await expect(promise).rejects.toThrow()
})
test('Should return an data on success', async () => {
const { sut, encrypterSpy, loadAccountByEmailRepositorySpy } = makeSut()
const { accessToken, name } = await sut.auth(mockAuthenticationParams())
expect(accessToken).toBe(encrypterSpy.ciphertext)
expect(name).toBe(loadAccountByEmailRepositorySpy.result.name)
})
}) |
const types = [
{ regex: /^-?\d+(\.\d+)?$/, name: "NUMBER" },
{ regex: /^"([^"]*)"$/, name: "STRING" },
{ regex: /^ADD$/, name: "ADD" },
{ regex: /^SUBTRACT$/, name: "SUBTRACT" },
{ regex: /^MULTIPLY$/, name: "MULTIPLY" },
{ regex: /^DIVIDE$/, name: "DIVIDE" },
{ regex: /^CONCAT$/, name: "CONCAT" },
{ regex: /^PRINT$/, name: "PRINT" },
{ regex: /^SWAP$/, name: "SWAP" },
{ regex: /^DROP$/, name: "DROP" },
{ regex: /^POP$/, name: "POP" },
{ regex: /^OUTPUT$/, name: "OUTPUT" },
{ regex: /^DUPLICATE$/, name: "DUPLICATE" },
{ regex: /^OVER$/, name: "OVER" },
{ regex: /^TIMES$/, name: "TIMES" },
{ regex: /^INDEX$/, name: "INDEX" },
{ regex: /^BEGIN$/, name: "BEGIN" },
{ regex: /^STOP$/, name: "STOP" },
{ regex: /^\.$/, name: "." },
{ regex: /^END$/, name: "END" },
{ regex: /^IF$/, name: "IF" },
{ regex: /^ELSE$/, name: "ELSE" },
{ regex: /^==$/, name: "==" },
{ regex: /^>$/, name: ">" },
{ regex: /^<$/, name: "<" },
{ regex: /^>=$/, name: ">=" },
{ regex: /^<=$/, name: "<=" },
{ regex: /^:/, name: ":" },
];
let reserved = [...types.map((d) => d.name)];
const words = [];
const ignored = [/^\s+$/];
export function compile(input) {
const result = [];
const out = ["let stack = [];", "let array = [];", "let index = 0;"];
const lines = input.split("\n");
for (const [lineIndex, line] of lines.entries()) {
if (!line.startsWith("--")) {
const tokens = line
.split(/("[^"]*"|\S+)/)
.filter((d) => d)
.filter((d) => {
for (const ignore of ignored) {
if (ignore.test(d)) {
return false;
}
}
return true;
});
for (const [tokenIndex, token] of tokens.entries()) {
let result;
let matched = false;
for (const type of types) {
const match = type.regex.test(token);
if (match) {
matched = true;
result = {
type: type.name,
value: token,
};
break;
}
}
for (const word of words) {
const match = token === word;
if (match) {
matched = true;
result = {
type: "VARIABLE",
value: word,
};
break;
}
}
if (!matched) {
throw new Error(
`Unknown token "${token}" at line index ${lineIndex} and token index ${tokenIndex}!`,
);
}
switch (result.type) {
// Variable.
case "VARIABLE":
out.push(`stack.push(${result.value}());`);
break;
// Types.
case "NUMBER":
out.push(`stack.push(${parseFloat(result.value)});`);
break;
case "STRING":
out.push(`stack.push("${result.value.replace(/^"|"$/g, "")}");`);
break;
// Math, etc.
case "ADD":
out.push("stack.push(stack.pop() + stack.pop());");
break;
case "SUBTRACT":
out.push("stack.push(stack.pop() - stack.pop());");
break;
case "MULTIPLY":
out.push("stack.push(stack.pop() * stack.pop());");
break;
case "DIVIDE":
out.push("stack.push(stack.pop() / stack.pop());");
break;
case "CONCAT":
out.push("stack.push(`${stack.pop()}${stack.pop()}`);");
break;
// Stack manipulation.
case "DUPLICATE":
out.push("stack.push(stack[stack.length - 1]);");
break;
case "OVER":
out.push("stack.push(stack[stack.length - 2]);");
break;
case "SWAP":
out.push(
"stack = [...stack.slice(0, -2), stack[stack.length - 1], stack[stack.length - 2]];",
);
break;
case "DROP":
out.push("stack = [];");
break;
case "POP":
out.push("stack.pop()");
break;
// Printing.
case "PRINT":
out.push("console.log(stack[stack.length - 1]);");
break;
case "OUTPUT":
out.push("console.log(stack.pop());");
break;
// Control.
case "TIMES":
out.push("array = Array.from({ length: stack.pop() })");
out.push("for (let i = 0; i < array.length; i++) {");
out.push("index = i;");
break;
case "INDEX":
out.push("stack.push(index);");
break;
case "STOP":
out.push("break;");
break;
case "END":
out.push("}");
break;
case "==":
out.push("stack.push(stack.pop() === stack.pop() ? 1 : 0);");
break;
case ">":
out.push("stack.push(stack.pop() < stack.pop() ? 1 : 0);");
break;
case "<":
out.push("stack.push(stack.pop() > stack.pop() ? 1 : 0);");
break;
case ">=":
out.push("stack.push(stack.pop() <= stack.pop() ? 1 : 0);");
break;
case "<=":
out.push("stack.push(stack.pop() >= stack.pop() ? 1 : 0);");
break;
case "IF":
out.push("if (stack.pop()) {");
break;
case "BEGIN":
out.push("while (true) {");
break;
case ":":
out.push("stack.pop()");
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_";
const name = tokens[tokenIndex - 1].replace(/^"|"$/g, "");
let isValid = reserved.includes(name) ? false : true;
for (const character of name.split("")) {
if (!alphabet.includes(character)) {
console.log(character);
isValid = false;
}
}
if (!isValid) {
throw new Error(
"Variables must contain only uppercase letters or the underscore and may not be reserved.",
);
}
words.push(name);
reserved = ["VARIABLE", ...types.map((d) => d.name)];
out.push(`const ${name} = () => {`);
break;
case ".":
out.push("return stack.pop(); }");
break;
}
}
}
}
return out.join("\n");
} |
'use client'
import React from 'react'
import { SlidingChoices } from './ui/sliding-choices'
import { cn, useWindowSize } from '@/lib/utils'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger
} from './ui/dropdown-menu'
import { Pin, LogOut, LogIn, Home, Search, Plus, UserRound, Info } from 'lucide-react'
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
import { Button } from './ui/button'
import { Dialog, DialogContent, DialogTrigger } from './ui/dialog'
import NewEntryForm from './NewEntryForm'
const menuValues = ['Home', 'Search', 'Add Location', 'Profile', 'Info']
const menuValuesIcons = [
<Home key={0} width={16} />,
<Search key={1} width={16} />,
<Plus key={2} width={16} />,
<UserRound key={3} width={16} />,
<Info key={4} width={16} />
]
const SlidingMenu = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const size = useWindowSize()
const [profileActive, setProfileActive] = React.useState(false)
const mouseEnterFunctions = menuValues.map((elem) => {
if (elem === 'Profile') {
return () => setProfileActive(true)
}
})
const mouseLeaveFunctions = menuValues.map((elem) => {
if (elem === 'Profile') {
return () => setProfileActive(false)
}
})
return (
<div className={cn('flex sm', className)} ref={ref}>
<SlidingChoices
childrenClassName=''
childrenOnMouseEnter={mouseEnterFunctions}
childrenOnMouseLeave={mouseLeaveFunctions}
>
{menuValues.map((elem, idx) => {
if (elem === 'Profile') {
return (
<React.Fragment key={idx}>
<Profile
open={profileActive}
isLoggedIn={true}
elem={size.isSmall ? menuValuesIcons[idx] : 'Profile'}
className={size.isSmall ? 'py-1' : 'py-5'}
isSmall={size.isSmall}
/>
</React.Fragment>
)
} else
return (
<React.Fragment key={idx}>
<DialogTemp
value={size.isSmall ? menuValuesIcons[idx] : elem}
className={size.isSmall ? 'py-1' : 'py-5'}
isSmall ={size.isSmall}
/>
</React.Fragment>
)
})}
</SlidingChoices>
</div>
)
}
)
SlidingMenu.displayName = 'SlidingMenu'
const Profile = ({
open,
isLoggedIn,
elem,
className,
isSmall
}: {
open: boolean
isLoggedIn: boolean
elem: React.ReactNode
className: string
isSmall: boolean | undefined
}) => {
return (
<DropdownMenu modal={false} open={open}>
<DropdownMenuTrigger className={cn('px-6 focus-visible:outline-none', className)}>{elem}</DropdownMenuTrigger>
<DropdownMenuContent
className={cn(
'rounded-3xl shadow-none border-2 border-foreground p-3 my-3 flex flex-col justify-center',
isSmall ? 'w-60' : 'w-72'
)}
sideOffset={0}
>
{!isLoggedIn && (
<Button className='rounded-full gap-2 text-base font-medium py-6' size={'lg'}>
<LogIn />
Sign In
</Button>
)}
{isLoggedIn && <ProfileOptions isSmall={isSmall} />}
</DropdownMenuContent>
</DropdownMenu>
)
}
const ProfileOptions = ({ isSmall }: { isSmall: boolean | undefined }) => {
return (
<React.Fragment>
<DropdownMenuItem className='text-base font-medium rounded-2xl'>
<Avatar className={cn('border-2 border-background mr-2', isSmall ? 'w-8 h-8' : 'w-12 h-12')}>
<AvatarImage src='https://github.com/shadcn.png' alt='user' />
<AvatarFallback>PP</AvatarFallback>
</Avatar>
Profile Name
</DropdownMenuItem>
<DropdownMenuItem className={cn(' rounded-2xl text-base font-medium', isSmall ? 'h-10' : 'h-14')}>
My List
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className={cn('rounded-2xl text-base font-medium', isSmall ? 'h-10' : 'h-14')}>
Log out
<LogOut className='ml-2' />
</DropdownMenuItem>
</React.Fragment>
)
}
const DialogTemp = ({ value, className, isSmall }: { value: string | React.ReactNode; className: string; isSmall: boolean| undefined }) => {
return (
<Dialog>
<DialogTrigger asChild>
<Button variant={'ghost'} className={cn(' px-6 hover:bg-inherit hover:text-inherit', className)}>
{value}
</Button>
</DialogTrigger>
<DialogContent
// className="top-[10svh] translate-y-[-10svh] "
className='w-fit max-w-sm lg:max-w-5xl p-4 pt-12 lg:p-10'
>
{/* className="grid gap-3 p-8 w-fit h-fit lg:grid-cols-[1fr_1fr] lg:rounded-none sm:rounded-none" */}
<NewEntryForm isSmall={isSmall}/>
</DialogContent>
</Dialog>
)
}
export { SlidingMenu } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.