text
stringlengths 184
4.48M
|
|---|
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Студія</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/2.0.0/modern-normalize.min.css"
integrity="sha512-4xo8blKMVCiXpTaLzQSLSw3KFOVPWhm/TRtuPVc4WG6kUgjH6J03IBuG7JZPkcWMxJ5huwaBpOpnwYElP/m6wg=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<!-- <link rel="stylesheet" href="./CSS/styles.css" /> -->
<link rel="stylesheet" href="./CSS/main.min.css" />
</head>
<body>
<!-- <header class="header">
<div class="container header-wrap">
<a class="logo-link link" id="webstudio" href="#" lang="en"
><span class="logo">Web</span>Studio</a
>
<nav class="header-nav">
<ul class="header-list list">
<li class="header-iteam">
<a class="header-link link current" href="#">Студія</a>
</li>
<li class="header-iteam">
<a class="header-link link" href="./portfolio.html">Портфоліо</a>
</li>
<li class="header-iteam">
<a class="header-link link" href="#contacts">Контакти</a>
</li>
</ul>
</nav>
<ul class="header-list-contacts list">
<li class="header-iteam contacts">
<a class="header-link link" href="mailto:info@devstudio.com"
><svg class="header-contacts-icon" width="16" height="12">
<use href="./images/icons.svg#icon-mail_icon"></use>
</svg>
info@devstudio.com
</a>
</li>
<li class="header-iteam contacts">
<a class="header-link link" href="tel:+380961111111">
<svg class="header-contacts-icon" width="10" height="16">
<use href="./images/icons.svg#icon-smartphone"></use>
</svg>
+38 096 111 11 11
</a>
</li>
</ul>
</div>
</header> -->
<main>
<section class="hero">
<div class="container">
<div class="hero-wrap">
<h1 class="hero-title">Ефективні рішення для вашого бізнесу</h1>
</div>
<button class="hero-button" type="button" data-modal-open>
Замовити послугу
</button>
</div>
</section>
<section class="advantage">
<div class="container">
<h2 class="hide">Переваги</h2>
<ul class="advantage-list list">
<li class="advantage-iteam">
<h3 class="advantage-iteam-title">УВАГА ДО ДЕТАЛЕЙ</h3>
<p class="advantage-iteam-text">
Ідейні міркування, і навіть початок повсякденної роботи з
формування позиції.
</p>
</li>
<li class="advantage-iteam">
<h3 class="advantage-iteam-title">ПУНКТУАЛЬНІСТЬ</h3>
<p class="advantage-iteam-text">
Завдання організації, особливо рамки і місце навчання кадрів
тягне у себе.
</p>
</li>
<li class="advantage-iteam">
<h3 class="advantage-iteam-title">ПЛАНУВАННЯ</h3>
<p class="advantage-iteam-text">
Так само консультація з широким активом значною мірою зумовлює.
</p>
</li>
<li class="advantage-iteam">
<h3 class="advantage-iteam-title">СУЧАСНІ ТЕХНОЛОГІЇ</h3>
<p class="advantage-iteam-text">
Значимість цих проблем настільки очевидна, що реалізація
планових завдань.
</p>
</li>
</ul>
</div>
</section>
<section class="services">
<div class="container">
<h2 class="title">Чим ми займаємося</h2>
<ul class="services-list list">
<li class="services-iteam">
<div class="services-top-wraper">
<img
src="./images/new_box1.jpg"
alt="Людина, яка програмує"
width="370"
height="294"
/>
<p class="services-top-text">Десктопні додатки</p>
</div>
</li>
<li class="services-iteam">
<div class="services-top-wraper">
<img
src="./images/new_box2.jpg"
alt="Дизайнер порівнює макети"
width="370"
height="294"
/>
<p class="services-top-text">Мобільні додатки</p>
</div>
</li>
<li class="services-iteam">
<div class="services-top-wraper">
<img
src="./images/new_box3.jpg"
alt="Пленшет в руках з зобраежням куба"
width="370"
height="294"
/>
<p class="services-top-text">Дизайнерські рішення</p>
</div>
</li>
</ul>
</div>
</section>
<section class="team">
<div class="container">
<h2 class="title">Наша команда</h2>
<ul class="team-list list">
<li class="team-iteam">
<img
src="./images/foto_Igor_new.jpg"
alt="Фото Ігоря Дем'яненко"
width="270"
height="260"
/>
<div class="team-wraper">
<h3 class="team-title">Ігор Дем'яненко</h3>
<p class="team-text" lang="en">Product Designer</p>
<ul class="team-soc-list list">
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-iteam">
<img
src="./images/foto_Olga_new.jpg"
alt="Фото Ольги Рєпіної"
width="270"
height="260"
/>
<div class="team-wraper">
<h3 class="team-title">Ольга Рєпіна</h3>
<p class="team-text" lang="en">Frontend Developer</p>
<ul class="team-soc-list list">
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-iteam">
<img
src="./images/foto_Mykola_new.jpg"
alt="Фото Миколи Тарасова"
width="270"
height="260"
/>
<div class="team-wraper">
<h3 class="team-title">Микола Тарасов</h3>
<p class="team-text" lang="en">Marketing</p>
<ul class="team-soc-list list">
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-iteam">
<img
src="./images/foto_Myhailo_new.jpg"
alt="Фото Михайла Єрмакова"
width="270"
height="260"
/>
<div class="team-wraper">
<h3 class="team-title">Михайло Єрмаков</h3>
<p class="team-text" lang="en">UI Designer</p>
<ul class="team-soc-list list">
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="team-soc-iteam">
<a class="team-soc-link" href="#">
<svg class="team-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
</ul>
</div>
</section>
<section class="clients">
<div class="container">
<h2 class="title">Постійні клієнти</h2>
<ul class="clients-list list">
<li class="clients-iteam">
<a href="#" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./images/icons.svg#icon-Logo_1"></use>
</svg>
</a>
</li>
<li class="clients-iteam">
<a href="#" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./images/icons.svg#icon-Logo_2"></use>
</svg>
</a>
</li>
<li class="clients-iteam">
<a href="#" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./images/icons.svg#icon-Logo_3"></use>
</svg>
</a>
</li>
<li class="clients-iteam">
<a href="#" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./images/icons.svg#icon-Logo_4"></use>
</svg>
</a>
</li>
<li class="clients-iteam">
<a href="#" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./images/icons.svg#icon-Logo_5"></use>
</svg>
</a>
</li>
<li class="clients-iteam">
<a href="#" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./images/icons.svg#icon-Logo_6"></use>
</svg>
</a>
</li>
</ul>
</div>
</section>
</main>
<footer class="footer">
<div class="container footer-wrap">
<div class="footer-container-address">
<div class="footer-block-address">
<a class="logo-link link footer-logo" href="#webstudio" lang="en"
><span class="logo">Web</span>Studio</a
>
<address class="footer-address-list" id="contacts">
<ul class="footer-list list">
<li class="footer-iteam">
<a
class="footer-link link footer-address"
href="https://www.bing.com/maps?osid=c63089d1-bdf8-47fa-8909-ece39b428c00&cp=50.42718~30.53534&lvl=17&pi=0&v=2&sV=2&form=S00027"
>
м. Київ, пр-т Лесі Українки, 26
</a>
</li>
<li class="footer-iteam">
<a class="footer-link link" href="mailto:info@devstudio.com"
>info@devstudio.com</a
>
</li>
<li class="footer-iteam">
<a class="footer-link link" href="tel:+380961111111"
>+38 096 111 11 11</a
>
</li>
</ul>
</address>
</div>
</div>
<div class="footer-container-address footer-block-soc">
<div>
<p class="footer-soc-text">приєднуйтесь</p>
<ul class="footer-soc-list list">
<li class="footer-soc-iteam">
<a class="footer-soc-link" href="#">
<svg class="footer-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="footer-soc-iteam">
<a class="footer-soc-link" href="#">
<svg class="footer-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="footer-soc-iteam">
<a class="footer-soc-link" href="#">
<svg class="footer-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="footer-soc-iteam">
<a class="footer-soc-link" href="#">
<svg class="footer-soc-icon" width="20" height="20">
<use href="./images/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</div>
<div class="footer-container-address footer-block-form">
<div>
<p class="footer-soc-text">Підпишіться на розсилку</p>
<form class="footer-form">
<input
type="text"
name="online-name"
placeholder="E-mail"
class="footer-input"
/>
<button type="submit" class="footer-subscribe">Підписатися</button>
</form>
</div>
</div>
</div>
</footer>
<!-- <div class="backdrop is-hidden" data-modal>
<div class="modal">
<button type="button" class="modal-button-exit" data-modal-close>
<svg class="modal-icon-exit" width="11" height="11">
<use href="./images/icons.svg#icon-Modal-X"></use>
</svg>
</button>
<p class="modal-text">Залиште свої дані, ми вам передзвонимо</p>
<form class="modal-form">
<div class="modal-field">
<label for="user-name" class="modal-label">Ім'я</label>
<div class="modal-wraper">
<input
type="text"
name="user-name"
class="modal-input"
id="user-name"
/>
<svg class="modal-icon-input" width="13" height="13">
<use href="./images/icons.svg#icon-Modal-person"></use>
</svg>
</div>
</div>
<div class="modal-field">
<label for="user-tel" class="modal-label">Телефон</label>
<div class="modal-wraper">
<input
type="tel"
name="user-tel"
class="modal-input"
id="user-tel"
/>
<svg class="modal-icon-input" width="13" height="13">
<use href="./images/icons.svg#icon-Modal-tel"></use>
</svg>
</div>
</div>
<div class="modal-field">
<label for="email" class="modal-label">Пошта</label>
<div class="modal-wraper">
<input
type="email"
name="user-email"
class="modal-input"
id="user-email"
/>
<svg class="modal-icon-input" width="13" height="13">
<use href="./images/icons.svg#icon-Modal-mail"></use>
</svg>
</div>
</div>
<div class="modal-field-waper">
<label for="user-text" class="modal-label">Коментар</label>
<textarea
name="user-text"
id="user-text"
placeholder="Введіть текст"
class="modal-comment"
></textarea>
</div>
<div class="modal-field-chek">
<input
type="checkbox"
name="policy"
id="policy"
class="modal-chek hide"
/>
<label for="policy" class="modal-chek-text"
>Погоджуюся з розсилкою та приймаю
<a href="#">Умови договору</a>
</label>
</div>
<div class="modal-send">
<button type="submit" class="send-button">Відправити</button>
</div>
</form>
</div>
</div>
<script src="./js/modal.js"></script> -->
</body>
</html>
|
var pageCounter = 1;
var show = document.getElementById("animal-info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function () {
var ourRequest = new XMLHttpRequest();
ourRequest.open(
"GET",
`https://learnwebcode.github.io/json-example/animals-${pageCounter}.json`
);
ourRequest.onload = function () {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
} else {
console.log("we connected to the server but it returned an error");
}
};
ourRequest.onerror = function () {
console.log("Connection error");
};
ourRequest.send();
pageCounter++;
if (pageCounter > 3) {
btn.classList.add("hide-me");
}
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString +=
"<p>" + data[i].name + "is a " + data[i].species + "that likes to eat ";
for (ii = 0; ii < data[i].foods.likes.length; ii++) {
if (ii == 0) {
htmlString += data[i].foods.likes[ii] + " ";
} else {
htmlString += " and " + data[i].foods.likes[ii] + " ";
}
}
htmlString += "and dislikes" + " ";
for (j = 0; j < data[i].foods.dislikes.length; j++) {
if (j == 0) {
htmlString += data[i].foods.dislikes[j] + " ";
} else {
htmlString += " and " + data[i].foods.dislikes[j] + " ";
}
}
htmlString += ".</p>";
}
show.insertAdjacentHTML("Beforeend", htmlString);
}
|
import { expect } from "chai";
import { describe, it } from "mocha";
import DocumentFactory from "../../src/DocumentFactoryClass.js";
import { isValidEmail } from "../testUtils.js";
describe("Testing email type for DocumentFactoryClass", function () {
it("1. Given a valid schema, it should return the correct response", function () {
const schema = {
test: {
type: "email",
},
};
const documentFactory = new DocumentFactory(schema, 0, {});
const resultDocument = documentFactory.getDocument();
expect(resultDocument).to.haveOwnProperty("test");
expect(resultDocument.test).to.be.a("string");
expect(isValidEmail(resultDocument.test)).to.be.true;
});
it("2. Given a 100% nullable percentage, it should return the correct property with a null value", function () {
const maxNullablePercentage = 1;
const schema = {
test: {
type: "email",
isNullable: true,
nullablePercentage: maxNullablePercentage,
},
};
const documentFactory = new DocumentFactory(schema, 0, {});
const resultDocument = documentFactory.getDocument();
expect(resultDocument.test).to.be.null;
});
});
|
"""
Remove K Digits
Given string num representing a non-negative integer num, and an
integer k, return the smallest possible integer after removing k
digits from num.
Example 1:
Input: num = "1432219", k = 3
Output: "1219"
Example 2:
Input: num = "10200", k = 1
Output: "200"
"""
import sys
sys.set_int_max_str_digits(0)
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
if k >= len(num):
return '0'
# Initializing the stack
stk = []
for n in num:
print(k, stk, n)
# While there are pending removals k
while k > 0 and stk and n < stk[-1]:
stk.pop()
k -= 1
print(' ', k, stk, n)
# Adding the current n
stk.append(n)
# Confirming remaining removals
while k > 0 and stk:
stk.pop()
k -= 1
return str(int(''.join(list(map(str, stk)))))
# print(Solution().removeKdigits("1432219", 3))
# print(Solution().removeKdigits("10200", 1))
# print(Solution().removeKdigits("10", 2))
# print(Solution().removeKdigits("112", 1))
# print(Solution().removeKdigits("1234567890", 9))
print(Solution().removeKdigits("9964143", 5))
|
import axios from "axios";
import {
Move,
PokeapiResponse,
} from "../interfaces/pokeapi-response.interface";
export class Pokemon {
get imageUrl(): string {
return `https:pokemon.com/${this.id}.jpg`;
}
constructor(
public readonly id: number,
public name: string // public imageUrl: string,
) {}
public scream() {
console.log(`${this.name.toUpperCase()}!!!`);
this.speak();
}
private speak() {
console.log(`${this.name}, ${this.name}`);
}
async getMoves(): Promise<Move[]> {
//const moves = 10;
const { data } = await axios.get<PokeapiResponse>(
"https://pokeapi.co/api/v2/pokemon/4"
);
console.log(data.moves);
return data.moves;
}
}
export const charmander = new Pokemon(4, "Charmander");
// console.log(charmander.imageUrl);
// charmander.scream()
// charmander.speak()
//console.log(charmander.getMoves());
charmander.getMoves();
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('product_variants', function (Blueprint $table) {
$table->char('id', length: 36)->primary();
$table->char('product_id', length: 36);
$table->foreign('product_id')->references('id')->on('products');
$table->string('name');
$table->integer('price');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('product_variants');
}
};
|
package com.entity.view;
import org.apache.tools.ant.util.DateUtils;
import com.annotation.ColumnInfo;
import com.entity.ChongwuyongpinEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
import com.utils.DateUtil;
/**
* 商品
* 后端返回视图实体辅助类
* (通常后端关联的表或者自定义的字段需要返回使用)
*/
@TableName("chongwuyongpin")
public class ChongwuyongpinView extends ChongwuyongpinEntity implements Serializable {
private static final long serialVersionUID = 1L;
//当前表
/**
* 商品类型的值
*/
@ColumnInfo(comment="商品类型的字典表值",type="varchar(200)")
private String chongwuyongpinValue;
/**
* 是否上架的值
*/
@ColumnInfo(comment="是否上架的字典表值",type="varchar(200)")
private String shangxiaValue;
public ChongwuyongpinView() {
}
public ChongwuyongpinView(ChongwuyongpinEntity chongwuyongpinEntity) {
try {
BeanUtils.copyProperties(this, chongwuyongpinEntity);
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//当前表的
/**
* 获取: 商品类型的值
*/
public String getChongwuyongpinValue() {
return chongwuyongpinValue;
}
/**
* 设置: 商品类型的值
*/
public void setChongwuyongpinValue(String chongwuyongpinValue) {
this.chongwuyongpinValue = chongwuyongpinValue;
}
//当前表的
/**
* 获取: 是否上架的值
*/
public String getShangxiaValue() {
return shangxiaValue;
}
/**
* 设置: 是否上架的值
*/
public void setShangxiaValue(String shangxiaValue) {
this.shangxiaValue = shangxiaValue;
}
@Override
public String toString() {
return "ChongwuyongpinView{" +
", chongwuyongpinValue=" + chongwuyongpinValue +
", shangxiaValue=" + shangxiaValue +
"} " + super.toString();
}
}
|
//
// Copyright 2010, Darren Lafreniere
// <http://www.lafarren.com/theseus-minotaur-solver/>
//
// This file is part of lafarren.com's Theseus and Minotaur Maze Solver,
// or tmmaze-solver.
//
// tmmaze-solver 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.
//
// tmmaze-solver 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 tmmaze-solver, named License.txt. If not, see
// <http://www.gnu.org/licenses/>.
//
package com.lafarren.tmmaze.ui
{
import flash.display.InteractiveObject;
import flash.events.FocusEvent;
import mx.core.Application;
/**
* Manages a stack of focus targets. A target can be pushed onto the
* stack, which will restrict keyboard focus to it and, if its exclusive
* flag is false, to any child component of it. If its exclusive flag is
* true, only the target is allowed to have focus, until it is popped, or
* another target is pushed onto the stack. When a target is popped, the
* target below it will receive focus according to its exclusivity rule.
*/
public class FocusStack
{
// Singleton instance.
private static var m_focusStack:FocusStack;
private const m_items:Vector.<Item> = new Vector.<Item>();
private var m_focusChangeCount:int;
public function FocusStack()
{
if (m_focusStack)
{
throw new Error("The FocusStack singleton has already been created!");
}
registerForFocusEvents();
}
public static function get focusStack():FocusStack
{
if (!m_focusStack)
{
m_focusStack = new FocusStack();
}
return m_focusStack;
}
/**
* Pushes a new target and its exclusivity.
* @param target The target for which focus is allowed for it and, if exclusive is false, its children.
* Pushing a null target to the top will disable the stack's focus adjustment.
* @param exclusive If true, only the target can receive focus, otherwise its children may as well.
*/
public function push(target:InteractiveObject, exclusive:Boolean):void
{
m_items.push(new Item(target, exclusive));
adjustFocus();
}
/**
* Pops the current target from the stack and returns it.
* @return The target that was popped from the stack.
*/
public function pop():InteractiveObject
{
var item:Item = this.itemTop;
if (item)
{
remove(item.target);
}
else
{
throw new Error("pop without a matching push");
}
return item ? item.target : null;
}
/**
* Removes the top-most stack item found for the specified target.
* @param target The target for which to remove the top-most item for.
* @return True if the target was found in the stack, false otherwise.
*/
public function remove(target:InteractiveObject):Boolean
{
var result:Boolean = false;
for (var i:int = m_items.length; --i >= 0; )
{
if (m_items[i].target == target)
{
m_items.splice(i, 1);
result = true;
break;
}
}
adjustFocus();
return result;
}
private function registerForFocusEvents():void
{
var app:Application = Application.application as Application;
if (app && app.stage)
{
app.stage.addEventListener(FocusEvent.FOCUS_IN, onFocusChange);
app.stage.addEventListener(FocusEvent.FOCUS_OUT, onFocusChange);
}
else
{
app.callLater(registerForFocusEvents);
}
}
private function onFocusChange(event:FocusEvent):void
{
// Accumulate focus changes until the next update, and do a single
// adjustment later.
++m_focusChangeCount;
Application.application.callLater(handleFocusChanges);
}
private function handleFocusChanges():void
{
if (m_focusChangeCount > 0)
{
m_focusChangeCount = 0;
adjustFocus();
}
}
private function adjustFocus():void
{
var app:Application = Application.application as Application;
if (app && app.stage)
{
var item:Item = this.itemTop;
if (item && item.target)
{
if (item.exclusive)
{
if (app.stage.focus != item.target)
{
app.stage.focus = item.target;
}
}
else
{
var isDescendant:Boolean = false;
{
var current:InteractiveObject = Application.application.stage.focus;
while (!isDescendant && current)
{
isDescendant = (current == item.target);
current = current.parent;
}
}
if (!isDescendant)
{
app.stage.focus = item.target;
}
}
}
}
}
private function get itemTop():Item
{
return (m_items.length > 0) ? m_items[m_items.length - 1] : null;
}
}
}
import flash.display.InteractiveObject;
// Internal stack item class.
internal class Item
{
public var target:InteractiveObject;
public var exclusive:Boolean;
public function Item(target:InteractiveObject, exclusive:Boolean)
{
this.target = target;
this.exclusive = exclusive;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RSS feeds</title>
<!-- 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-dark bg-dark">
<div class="container-fluid">
<span class="navbar-brand mb-0 h1">Tech Feed</span>
</div>
</nav>
<main class="flex container-fluid">
<div class="d-flex flex-row">
<div>
<form action="{{ url_for('index') }}"
method="post">
<ul class="list-group">
<li class="list-group-item"><button type="submit" class="btn btn-dark"
name="blog"
value="medium">Medium</button></li>
<li class="list-group-item"><button type="submit" class="btn btn-dark"
name="blog"
value="codinghorror">Coding Horror</button></li>
<li class="list-group-item"><button type="submit"
class="btn btn-dark"
name="blog"
value="devtea">Developer's Tea</button></li>
<li class="list-group-item"><button type="submit"
class="btn btn-dark"
name="blog"
value="hackernoon">HackerNoon</button></li>
<li class="list-group-item"><button type="submit"
class="btn btn-dark"
name="blog"
value="codewall">CodeWall</button></li>
</ul>
</form>
</div>
<div class="articles">
{% for article in articles %}
<div class="card mb-3"
style="max-width: 540px;">
<div class="row no-gutters">
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">{{article.title}}</h5>
<p class="card-text">{{article.author}}</p>
<p class="card-text"><small class="text-muted">{{article.published}}</small></p>
<a href={{article.link}} target="_blank" class="btn btn-primary stretched-link">Read More</a>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</main>
</body>
</html>
|
using CompetitionWebApi.Application.Dtos;
using CompetitionWebApi.Application.Interfaces;
using CompetitionWebApi.Application.Requests;
using CompetitionWebApi.Application.Responses;
using CompetitionWebApi.Attributes;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CompetitionWebApi.Controllers;
[Route("api/[controller]s")]
[ApiController]
public class PerformanceController : ControllerBase
{
private readonly IPerformanceService _performanceService;
private readonly IValidationService _validationService;
public PerformanceController(IPerformanceService performanceService, IValidationService validationService)
{
_performanceService = performanceService;
_validationService = validationService;
}
[HttpPost("information")]
[Authorize(Roles = "Contestant")]
public async Task<IActionResult> CreatePerformanceInfo([FromBody] PerformanceRequest request)
{
await _validationService.ValidateRequestAsync(request);
IActionResult result = await _performanceService.CreatePerformanceInfoAsync(request);
return result;
}
[HttpPost("videos/{performanceId}")]
[DisableFormValueModelBinding]
[RequestSizeLimit(314_572_800)] // 300 MB
[Authorize(Roles = "Contestant")]
public async Task<IActionResult> UploadPerformanceVideo([FromRoute] int performanceId)
{
string boundary = _validationService.ValidateMultipartRequest(Request);
await _performanceService.SavePerformanceVideoAsync(boundary, Request.Body, performanceId);
var response = new SuccessResponse<string>
{
Message = "Performance video uploaded successfully.",
Payload = null
};
return Created(string.Empty, response);
}
[HttpGet("videos/{performanceId}")]
[Authorize(Roles = "Spectator")]
public async Task<IActionResult> DownloadPerformanceVideo([FromRoute] int performanceId)
{
PerformanceVideoDto result = await _performanceService.GetPerformanceVideoAsync(performanceId);
return File(result.VideoStream, "video/mp4", result.FileName);
}
[HttpGet]
[Authorize(Roles = "Spectator")]
public async Task<IActionResult> GetAllPerformances()
{
var performances = await _performanceService.GetAllPerformancesAsync();
var response = new SuccessResponse<List<PerformanceDto>>
{
Message = "Performances retrieved successfully.",
Payload = performances
};
return Ok(response);
}
}
|
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path");
// const createError = require("http-errors");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const dotenv = require("dotenv");
dotenv.config();
const PORT = process.env.PORT || 8080;
const indexRouter = require("./routes/index");
mongoose.set("strictQuery", false);
const mongoDB = process.env.MONGO_URL;
(async function () {
await mongoose.connect(mongoDB);
})();
app.use(
cors({
credentials: true,
origin: [
"http://localhost:3000",
"https://nrod42.github.io",
"https://nrod42.github.io/",
"https://trakr.onrender.com",
"https://trakr.onrender.com/",
"http://trakr.onrender.com",
"http://trakr.onrender.com/",
"https://cinetrakr.onrender.com",
"https://cinetrakr.onrender.com/",
"http://cinetrakr.onrender.com",
"http://cinetrakr.onrender.com/",
"https://onrender.com",
"https://onrender.com/",
"http://onrender.com",
],
})
);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use("/", indexRouter);
app.listen(PORT);
console.log(`Server is listening on port ${PORT}`);
module.exports = app;
|
---
layout: post
title: "Retrospectiva histórica"
date: 2023-08-16 14:08:14 -0500
categories: HTML
---
## Retrospectiva Histórica: La Evolución de la Interacción Humano-Computador (HCI)
<div style='text-align: center'>
<iframe width="560" height="315" src="https://www.youtube.com/embed/6WqcB0UQHSQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div> <br>
<div style='text-align: justify'>
La historia de la Interacción Humano-Computador (HCI) es un relato fascinante de cómo los seres humanos han interactuado con las máquinas a lo largo de los años, desde los primeros días de la computación hasta la era actual de interfaces intuitivas y experiencia de usuario centrada en el usuario. Esta retrospectiva histórica nos llevará a través de los hitos clave que han dado forma a la HCI, explorando los avances tecnológicos, las teorías cognitivas y los enfoques de diseño que han transformado la manera en que interactuamos con las computadoras.
</div><br>
<div style='text-align: center'>
<iframe width="560" height="315" src="https://www.youtube.com/embed/LJ0sIHj-OWo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div><br>
### Los Primeros Pasos: La Era de la Computación Temprana
<div style='text-align: justify'>
La historia de la HCI comienza en la década de 1940, cuando las computadoras eran enormes máquinas que requerían operadores altamente capacitados para interactuar con ellas. Las interfaces eran primitivas y basadas en tarjetas perforadas y cintas perforadas. Los usuarios tenían que aprender lenguajes de programación específicos para comunicarse con las máquinas, lo que limitaba la accesibilidad y la usabilidad.
El avance clave en esta época fue la invención del mouse en la década de 1960 por Douglas Engelbart. El mouse permitía una interacción más directa con las computadoras, al permitir a los usuarios apuntar y hacer clic en elementos en la pantalla. Aunque el mouse no se popularizó de inmediato, sentó las bases para una interacción más intuitiva en el futuro.
</div><br>
### La Revolución de la GUI y la Informática Personal
<div style='text-align: justify'>
La década de 1980 marcó un hito crucial con el desarrollo de la Interfaz Gráfica de Usuario (GUI) en el Laboratorio de Investigación de Xerox PARC. La GUI introdujo elementos visuales como ventanas, iconos y menús desplegables, lo que simplificó enormemente la interacción con las computadoras. El sistema Alto, desarrollado en Xerox PARC, fue uno de los primeros en incorporar estas ideas revolucionarias.
El lanzamiento de la Macintosh en 1984 por Apple popularizó aún más la GUI y cambió para siempre la forma en que las personas interactuaban con las computadoras. La introducción del mouse como dispositivo de entrada estándar y la interfaz intuitiva allanaron el camino para la informática personal en hogares y oficinas.
</div><br>
### La Emergencia de la Web y la Interacción Móvil
<div style='text-align: justify'>
La década de 1990 presenció la llegada de la World Wide Web, lo que dio lugar a una nueva forma de interacción: la navegación web. La Web trajo consigo desafíos únicos de diseño de interfaces, ya que los diseñadores tuvieron que adaptar el contenido para una variedad de tamaños y tipos de pantalla.
Con la proliferación de dispositivos móviles en la década de 2000, la HCI se enfrentó a nuevos desafíos. El tamaño reducido de las pantallas y la interacción táctil llevaron a la necesidad de interfaces altamente sensibles y eficientes en términos de espacio. Las aplicaciones móviles y las interfaces táctiles se convirtieron en norma, lo que exigió un enfoque en el diseño centrado en el usuario y la usabilidad.
</div><br>
### La Era de la Experiencia de Usuario y la Inteligencia Artificial
<div style='text-align: justify'>
A medida que avanzamos hacia la década de 2010, la Experiencia de Usuario (UX) tomó un papel central en la IHC. El enfoque cambió de la simple usabilidad a la creación de interacciones emocionalmente significativas y valiosas. Los diseñadores comenzaron a considerar no solo cómo los usuarios interactúan con las interfaces, sino también cómo se sienten al hacerlo.
La inteligencia artificial (IA) también emergió como un actor importante en la HCI. La IA permitió la creación de sistemas más inteligentes y adaptables, capaces de comprender y anticipar las necesidades de los usuarios. Los asistentes virtuales, como Siri de Apple y Google Assistant, demostraron cómo la HCI podía combinar la tecnología avanzada con una interacción más natural.
</div><br>
### La Actualidad y el Futuro de la HCI
<div style='text-align: justify'>
Hoy en día, la HCI sigue evolucionando a medida que nos adentramos en la era de la computación ubicua, la realidad virtual y aumentada, y la interacción basada en gestos y voz. Las interfaces están integradas en nuestra vida diaria, desde los relojes inteligentes hasta los dispositivos domésticos conectados.
El diseño centrado en el usuario, la accesibilidad y la ética en la HCI se han convertido en pilares fundamentales a medida que enfrentamos desafíos como la privacidad de los datos, la inclusión y la equidad en el diseño. Los diseñadores buscan crear interfaces que sean no solo funcionales, sino también éticas y culturalmente sensibles.
</div>
|
/*
* This file is part of the tutorial on Gson
* see https://github.com/mischwartz23/GsonTutorial.git
* Author: M I Schwartz
*/
package edu.du.ict4315.gsontutorial;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
/**
* Step 1: create the object class Step 2: create needed getters, setters, and constructors
*
* @author michael
*/
public class CustomerFour {
private int customerId;
private String name;
private Address address;
private String phoneNumber;
private CustomerType type;
private List<String> parkingIds = new ArrayList<>();
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Customer:");
sb.append("[");
sb.append("Id: ");
sb.append(customerId);
sb.append("; ");
sb.append("Name: ");
sb.append(name);
sb.append("; ");
sb.append("Address: ");
sb.append(address);
sb.append("; ");
sb.append("Phone number: ");
sb.append(phoneNumber);
sb.append("; ");
sb.append("Customer type: ");
sb.append(type);
sb.append("; ");
sb.append("Parking ids: [");
sb.append(String.join(", ", parkingIds));
sb.append("]");
sb.append("]");
return sb.toString();
}
// Step 3: Add a toJsonString method
public String toJsonString() {
Gson gson = new GsonBuilder().create(); // new Gson();
return gson.toJson(this);
}
public String toJsonStringPretty() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this);
}
// Step 4: Add a fromJsonString method
public static CustomerFour fromJsonString(String jsonString) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
CustomerFour customer = new CustomerFour();
try {
customer = gson.fromJson(jsonString, CustomerFour.class);
} catch (JsonParseException exc) {
System.err.println("Transaction incomplete: Cannot parse JSON: " + exc);
}
return customer;
}
// Step 5: In addition to creating a set of test cases, create a small "smoke test" main
public static void main(String[] args) {
CustomerFour customer1 = new CustomerFour();
customer1.customerId = 2;
customer1.name = "Martha Washington";
customer1.address = new Address.AddressBuilder()
.withStreet1("1600 Pennsylvania Avenue")
.withCity("Washington DC")
.withZipcode("20001")
.build();
customer1.phoneNumber = "202-555-1212";
customer1.type = CustomerType.INDIVIDUAL;
customer1.parkingIds.add("L17P33");
customer1.parkingIds.add("L19P11");
System.out.println(customer1);
String jsonString = customer1.toJsonString();
System.out.println(jsonString);
CustomerFour customer2 = CustomerFour.fromJsonString(jsonString);
System.out.println(customer2);
System.out.println("The first and third lines should look the same!");
System.out.println("Here is a pretty printed JSON string:");
System.out.println(customer2.toJsonStringPretty());
}
}
|
# Load packages
library(tidyverse)
library(ggplot2)
# Read the krona report from SOURMASH TAX METAGENOME
SRR19888796 <- read.table('/media/bio03/DATA/quyen/INTERNSHIP/nextflow/sourmash_official/sourmash_results/tax_metagenome/SRR19888796_tax.krona.tsv', header=TRUE, sep="\t")
SRR19888810 <- read.table('/media/bio03/DATA/quyen/INTERNSHIP/nextflow/sourmash_official/sourmash_results/tax_metagenome/SRR19888810_tax.krona.tsv', header=TRUE, sep="\t")
SRR19888832 <- read.table('/media/bio03/DATA/quyen/INTERNSHIP/nextflow/sourmash_official/sourmash_results/tax_metagenome/SRR19888832_tax.krona.tsv', header=TRUE, sep="\t")
# Using add_column with sample ID
SRR19888796 <- SRR19888796 %>%
add_column(sampleID = "SRR19888796")
SRR19888810 <- SRR19888810 %>%
add_column(sampleID = "SRR19888810")
SRR19888832 <- SRR19888832 %>%
add_column(sampleID = "SRR19888832")
# merge 3 krona output from 3 sample
data.frame <- rbind(SRR19888796, SRR19888810, SRR19888832)
dim(data.frame)
table(data.frame$sampleID)
data.frame <- data.frame[!(data.frame$species == "unclassified"), ]
# barplot geom_bar official
ggplot(data.frame, aes(fill=phylum, y=fraction, x=sampleID)) +
geom_bar(position="fill", stat="identity") +
xlab("sampleID") +
ylab("fraction") +
ggtitle("Phylum-level Metagenomic Data") +
## color
scale_fill_manual(values = c("darkblue", "darkgoldenrod1", "darkseagreen", "darkorchid", "darkolivegreen1", "lightskyblue", "darkgreen", "deeppink", "khaki2", "firebrick", "brown1", "darkorange1", "cyan1", "royalblue4", "darksalmon", "darkblue",
"royalblue4", "dodgerblue3", "steelblue1", "lightskyblue", "darkseagreen", "darkgoldenrod1", "darkseagreen", "darkorchid", "darkolivegreen1", "brown1", "darkorange1", "cyan1", "darkgrey")) +
theme(legend.position="bottom") + guides(fill=guide_legend(nrow=5)) +
coord_flip() #convert vertical --> horizontal barplot
|
package objects;
import com.codeborne.selenide.CollectionCondition;
import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;
import io.qameta.allure.Step;
import java.util.Arrays;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;
public class CareerPage {
private final SelenideElement careerKeywordField = $("#keyword"),
careerCountryField = $(".form-group-select-country .career-jobs__text"),
careerCountryInput = $(".form-group-select-country input"),
careerSpecializationField = $(".form-group-select-specialization .career-jobs__text"),
careerSpecializationInput = $(".form-group-select-specialization input"),
submitCareerFilterButton = $(".career-jobs__btn");
private final ElementsCollection careerTitles = $$("a[data-offers='title']"),
fullCareerResults = $$("tbody[role='rowgroup'] tr");
@Step("Initiate the career search by keyword {careerKeyword}")
public CareerPage searchCareerKeyword(String careerKeyword) {
careerKeywordField.setValue(careerKeyword).pressEnter();
return this;
}
@Step("Verify that all search results have keyword {careerKeyword} in their title")
public void verifyCareersHaveKeyword(String careerKeyword) {
String[] careers = new String[10];
Arrays.fill(careers, careerKeyword);
careerTitles.shouldHave(CollectionCondition.texts(Arrays.asList(careers)));
}
@Step("Initiate the career search by country {careerCountry}")
public CareerPage searchCareerCountry(String careerCountry) {
careerCountryField.click();
careerCountryInput.setValue(careerCountry).pressEnter();
submitCareerFilterButton.click();
return this;
}
@Step("Verify that all search results have keyword {careerCountryShort} in their title")
public void verifyCareersFromCountry(String careerCountryShort) {
String[] careers = new String[10];
Arrays.fill(careers, careerCountryShort);
fullCareerResults.shouldHave(CollectionCondition.texts(Arrays.asList(careers)));
}
@Step("Initiate the career search by specialization {careerSpecialization}")
public CareerPage searchCareerSpecialization(String careerSpecialization) {
careerSpecializationField.click();
careerSpecializationInput.setValue(careerSpecialization).pressEnter();
submitCareerFilterButton.click();
return this;
}
@Step("Verify that all search results have keyword {careerSpecialization} in their title")
public void verifyCareersSpecialization(String careerSpecialization) {
String[] specializations = new String[10];
Arrays.fill(specializations, careerSpecialization);
fullCareerResults.shouldHave(CollectionCondition.texts(Arrays.asList(specializations)));
}
}
|
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/core/services/user/auth.service';
@Component({
selector: 'app-update-password',
templateUrl: './update-password.component.html',
styleUrls: ['./update-password.component.css'],
})
export class UpdatePasswordComponent implements OnInit {
updatePasswordForm!: FormGroup;
hideOldPassword: boolean = true;
hidePassword: boolean = true;
constructor(private authService: AuthService, private router: Router) {}
ngOnInit(): void {
this.updatePasswordForm = new FormGroup({
oldPassword: new FormControl(''),
newPassword: new FormControl(''),
confirmNewPassword: new FormControl(''),
});
}
async onUpdatePasswordBtnClick() {
const { oldPassword, newPassword, confirmNewPassword } =
this.updatePasswordForm.value;
if (newPassword === confirmNewPassword) {
const res = await this.authService.updatePassword(
oldPassword,
newPassword
);
if (res.success) {
this.router.navigate(['dashboard']);
}
switch (res.error) {
case 'auth/requires-recent-login':
await this.authService.logOut();
this.router.navigate(['']);
break;
case 'auth/wrong-password':
alert('Password is not correct!!');
break;
case 'auth/user-mismatch':
this.router.navigate(['']);
break;
default:
console.log(res.error);
break;
}
}
}
goBackToDashboard() {
this.router.navigate(['dashboard']);
}
}
|
import { undo, redo, history } from "prosemirror-history";
import { keymap } from "prosemirror-keymap";
import { EditorState } from "prosemirror-state";
import { baseKeymap, setBlockType } from "prosemirror-commands";
import { EditorView } from "prosemirror-view";
import { schema } from 'prosemirror-schema-basic';
function setup(el: HTMLElement) {
let state = EditorState.create({
schema,
plugins: [
history(),
keymap({"Mod-z": undo, "Mod-y": redo}),
keymap(baseKeymap),
keymap({
'Mod-x': setBlockType(schema.nodes.heading, { level: 1 }),
}),
]
});
let view = new EditorView(el, {
state,
dispatchTransaction(tr) {
console.log('tr', tr);
let newState = view.state.apply(tr);
view.updateState(newState);
},
});
return view;
}
export default {
setup,
title: 'Basic example',
desc: 'A simple text editor',
}
|
/*
* Copyright (C) 2015 Universidade Federal de Itajuba
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package br.edu.unifei.gpesc.core.modules;
/**
*
* @author isaac
*/
public enum NeuralCharacteristic {
/**
* The HAM constant.
*/
HAM("not spam", Spam.HAM),
/**
* The SPAM constant.
*/
SPAM("spam", Spam.SPAM),
/**
* The error constant.
*/
ERROR("unknown");
/**
* The max value that the minor value may have.
*/
public static final float MINOR_MAX_VALUE = 0.4f;
/**
* The min value that the major value may have.
*/
public static final float MAJOR_MIN_VALUE = 0.6f;
/**
* The name of this enum.
*/
public final String NAME;
/**
* The string value for this enum. This is used to send data to the
* neural network.
*/
public final String STR_VALUE;
/**
* The int array for this enum. This is used for identify the result of the
* neural network.
*/
public final double[] INT_VALUE;
/**
* Creates a new enum.
* @param name The name of this enum.
* @param firstValue The first value of this enum.
* @param secondValue The second value of this enum.
*/
private NeuralCharacteristic(String name, double... values) {
NAME = name;
if (values.length > 0) {
STR_VALUE = values[0] + " " + values[1];
}
else {
STR_VALUE = "0 0";
}
INT_VALUE = values;
}
/**
* Find the enum that can be represented by the first and second values.
* @param firstValue The first value.
* @param secondValue The second value.
* @return The enum that is represented by the arguments.
*/
public static NeuralCharacteristic getCharacteristic(float firstValue, float secondValue) {
if ((firstValue <= MINOR_MAX_VALUE) && (MAJOR_MIN_VALUE <= secondValue)) {
return HAM;
}
else if ((secondValue <= MINOR_MAX_VALUE) && (MAJOR_MIN_VALUE <= firstValue)) {
return SPAM;
}
return ERROR;
}
}
|
import { useState, useContext, } from 'react';
import User from "./User";
import CheckedContext from "../contexts/checkedContext";
function UsersTable({ users, isLoading, checkedAll, setCheckedAll, handleDelete, handleEdit, }) {
const value = useContext(CheckedContext);
const handleSelectAllChange = (e) => {
const { checked } = e.target; // target or currentTarget
setCheckedAll(checked);
const checkboxes = document.querySelectorAll("table tbody input[type='checkbox']");
checkboxes.forEach(checkbox => checkbox.checked = checked);
let checkedAllUser = [];
if (checked) {
//setCheckedAll(true);
//const checkboxes = document.querySelectorAll("table tbody input[type='checkbox']");
//checkboxes.forEach(checkbox => checkbox.checked = true);
users?.map(user => checkedAllUser.push(user.id));
} else {
// setCheckedAll(false);
// value.setCheckedUser(checkedAllUser);
}
value.setCheckedUser(checkedAllUser);
}
const userGenerator = () => {
return (
<>
{
users &&
users?.length > 0 &&
users?.map(user => {
return (
<User
key={user.id}
user={user}
total={users.length}
checkedAll={checkedAll}
setCheckedAll={setCheckedAll}
handleDelete={handleDelete}
handleEdit={handleEdit}
/>
)
})
}
</>
)
}
return (
<>
<table className="table table-striped table-hover">
<thead>
<tr>
<th>
<span className="custom-checkbox">
<input type="checkbox" id="selectAll" checked={checkedAll} onChange={(e) => handleSelectAllChange(e)} />
<label htmlFor="selectAll"></label>
</span>
</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{isLoading && <tr><td colSpan={4} className="text-center">Carregando...</td></tr>}
{!isLoading && (!users || users?.length == 0) && <tr><td colSpan={4} className="text-center">Nenhum registro encontrado...</td></tr>}
{userGenerator()}
</tbody>
</table>
</>
)
}
export default UsersTable;
|
<?php
/**
* Login Form
*
* This template can be overridden by copying it to yourtheme/woocommerce/myaccount/form-login.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
* will need to copy the new files to your theme to maintain compatibility. We try to do this.
* as little as possible, but it does happen. When this occurs the version of the template file will.
* be bumped and the readme will list any important changes.
*
* @see http://docs.woothemes.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.2.6
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
?>
<?php wc_print_notices(); ?>
<?php do_action('woocommerce_before_customer_login_form'); ?>
<?php if (get_option('woocommerce_enable_myaccount_registration') === 'yes') : ?>
<div class="col2-set" id="customer_login">
<?php endif; ?>
<div class="login_wrapper">
<div class="container">
<div class="col-lg-6 col-sm-6">
<div class="login_wrap">
<div class="box">
<h1><?php _e('Login', 'woocommerce'); ?></h1>
<p class="text-muted">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies
mi vitae est. Mauris placerat eleifend leo.</p>
<form method="post" class="login">
<?php do_action('woocommerce_login_form_start'); ?>
<div class="form-group">
<label for="username"><?php _e('Username or email address', 'woocommerce'); ?> <span class="required">*</span></label>
<input type="text" class="form-control" name="username" id="username" value="<?php if (!empty($_POST['username'])) echo esc_attr($_POST['username']); ?>" />
</div>
<div class="form-group">
<label for="password"><?php _e('Password', 'woocommerce'); ?> <span class="required">*</span></label>
<input class="form-control" type="password" name="password" id="password" />
</div>
<?php do_action('woocommerce_login_form'); ?>
<div class="login_box">
<?php wp_nonce_field('woocommerce-login'); ?>
<input type="submit" class="btn btn-primary" name="login" value="<?php esc_attr_e('Login', 'woocommerce'); ?>" />
<label for="rememberme" class="inline">
<input name="rememberme" type="checkbox" id="rememberme" value="forever" /> <?php _e('Remember me', 'woocommerce'); ?>
</label>
</div>
<p class="lost_password">
<a href="<?php echo esc_url(wp_lostpassword_url()); ?>"><?php _e('Lost your password?', 'woocommerce'); ?></a>
</p>
<?php do_action('woocommerce_login_form_end'); ?>
</form>
</div></div>
</div>
<?php if (get_option('woocommerce_enable_myaccount_registration') === 'yes') : ?>
<div class="col-lg-6 col-sm-6">
<div class="login_wrap">
<div class="box">
<form method="post" class="register">
<h1><?php _e('Register', 'woocommerce'); ?></h1>
<p class="text-muted">If you already have an account with us, please login.</p>
<?php do_action('woocommerce_register_form_start'); ?>
<?php if ('no' === get_option('woocommerce_registration_generate_username')) : ?>
<div class="form-group">
<label for="reg_username"><?php _e('Username', 'woocommerce'); ?> <span class="required">*</span></label>
<input type="text" class="form-control" name="username" id="reg_username" value="<?php if (!empty($_POST['username'])) echo esc_attr($_POST['username']); ?>" />
</div>
<?php endif; ?>
<div class="form-group">
<label for="reg_email"><?php _e('Email address', 'woocommerce'); ?> <span class="required">*</span></label>
<input type="email" class="form-control" name="email" id="reg_email" value="<?php if (!empty($_POST['email'])) echo esc_attr($_POST['email']); ?>" />
</div>
<?php if ('no' === get_option('woocommerce_registration_generate_password')) : ?>
<div class="form-group">
<label for="reg_password"><?php _e('Password', 'woocommerce'); ?> <span class="required">*</span></label>
<input type="password" class="form-control" name="password" id="reg_password" />
</div>
<?php endif; ?>
<!-- Spam Trap -->
<div style="<?php echo ( ( is_rtl() ) ? 'right' : 'left' ); ?>: -999em; position: absolute;"><label for="trap"><?php _e('Anti-spam', 'woocommerce'); ?></label><input type="text" name="email_2" id="trap" tabindex="-1" /></div>
<?php do_action('woocommerce_register_form'); ?>
<?php do_action('register_form'); ?>
<div class="login_box">
<?php wp_nonce_field('woocommerce-register'); ?>
<input type="submit" class="btn btn-primary" name="register" value="<?php esc_attr_e('Register', 'woocommerce'); ?>" />
</div>
<?php do_action('woocommerce_register_form_end'); ?>
</form>
</div>
</div>
</div>
<?php endif; ?>
<?php do_action('woocommerce_after_customer_login_form'); ?>
</div>
</div>
</div>
|
{% load static %}
---
layout: default
---
<h1 class="primary">Cargar propiedad</h1>
<form class="needs-validation">
<div class="form-row">
<label class="form-label" for="tipo" name="tipo" required>Seleccionar el tipo de la propiedad: </label>
<select name="tipo">
<!-- TODO pasar a javascript -->
{% for tipo in site.data.tipos %}
<option value="{{tipo.tipo}}">{{tipo.tipo}}</option>
{% endfor %}
</select>
<div class="valid-feedback">
Looks good!
</div>
</div>
<h3>Ubicacion</h3>
<div class="row">
<div class="form-group needs-validation col-3">
<label class="form-label" for="pais">Pais: </label>
<input class="form-control" list="pais" name="pais" class="form-control" required id="pais">
<datalist id="pais">
{% for pais in site.data.paises %}
<option value="{{pais.name}}">{{pais.name}}</option>
{% endfor %}
</datalist>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Mal
</div>
</div>
<div class="form-group col-3" id="provincias">
<label class="form-label" for="provincia">Provincia: </label>
<input class="form-control" name="provincia" class="form-control">
</div>
<div class="form-group col-3">
<label class="form-label" for="localidad">Localidad: </label>
<input class="form-control" name="localidad" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Mal
</div>
</div>
<div class="form-group col-3">
<label class="form-label" for="CP">CP: </label>
<input class="form-control" name="CP" type="number">
</div>
</div>
<h4>Direccion</h4>
<div class="row">
<div class="form-group col-8">
<label class="form-label" for="calle">Calle</label>
<input class="form-control" name="calle">
</div>
<div class="form-group col-2">
<label class="form-label" for="piso">Piso</label>
<input class="form-control" name="piso" type="number" min="0" max="100">
</div>
<div class="form-group col-2">
<label class="form-label" for="numero">Numero</label>
<input class="form-control" name="numero">
</div>
</div>
<h4>Datos generales</h4>
<div class="row">
<div class="form-group col-4">
<label class="form-label" for="antiguedad">Antiguedad</label>
<input class="form-control" name="antiguedad" type="number">
</div>
<div class="form-group col-4">
<label class="form-label" for="Artefactos">Artefactos</label>
<input class="form-control" name="Artefactos" type="number">
</div>
<div class="form-group col-4">
<label class="form-label" for="ambientes">Ambientes</label>
<input class="form-control" name="ambientes" type="number">
</div>
</div>
<div class="row">
<div class="form-group col-4">
<label class="form-label" for="banios">Cant. de baños</label>
<input class="form-control" name="banios" type="number">
</div>
<div class="form-group col-4">
<label class="form-label" for="dormintorios">Cant. de dormitorios</label>
<input class="form-control" name="dormintorios" type="number">
</div>
<div class="form-group col-4">
<label class="form-label" for="suite">Cant. de suite</label>
<input class="form-control" name="suite" type="number">
</div>
</div>
<label class="form-label" for="desc"> Ingrese una descripcion corta</label>
<input class="form-control" name="desc">
<br>
<label class="form-label" for="descripcion"> Ingrese una descripcion larga.</label>
<textarea class="form-control" name="descripcion"></textarea>
<h4>Propietarios</h4>
<label class="form-label" name="propietario">Propietario: </label>
<input class="form-control" list="propietarios" name="propietario">
<datalist id="propietarios">
{% for prop in site.data.propietario %}
<option value="{{prop.nombre}}">{{prop.nombre}}</option>
{% endfor %}
</datalist>
<h4>Contrato</h4>
<div class="row">
<div class="form-group col-6">
<label class="form-label" for="contrato">Seleccione el tipo de contrato:</label>
<select name="contrato">
{% for tipo in site.data.contrato %}
<option value="{{tipo.nombre}}">{{tipo.nombre}}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-6">
<label class="form-label" for="precio">Precio: </label>
<input class="form-control" name="precio" type="number">
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
// function generar(elemento, json){
// Object.entries(json).forEach(element => {
// var elementoHijo = document.createElement('OPTION')
// elementoHijo.setAttribute('value', element.name)
// elementoHijo.setAttribute('text', element.name)
// elemento.appendChild(elementoHijo)
// });
// }
</script>
|
package webapp;
import javax.servlet.http.HttpServletRequest;
import java.sql.*;
import java.util.ArrayList;
public class Ward {
private String name;
private ArrayList<Drug> drugList;
private int id;
private ArrayList<Batch> batchList;
private StringBuilder errorMessage;
private boolean error;
public Ward(String name) {
this.name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
}
public Ward(String name, int id) {
this.name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
this.id = id;
}
public static Ward getWard(int wardId) {
Ward ward = null;
try {
String sql = "SELECT * from wards WHERE id = ?";
Connection connection = DbOp.connect();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, wardId);
ResultSet resultSet = statement.executeQuery();
String wardName = resultSet.getString("name");
connection.close();
ward = new Ward(wardName, wardId);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return ward;
}
public Ward(HttpServletRequest request) {
this.errorMessage = new StringBuilder();
this.error = false;
this.name = request.getParameter("name");
if (this.name.equals("")) {
this.error = true;
this.errorMessage.append("<li>Ward name cannot be empty</li>");
}
if (wardExists(this.name)) {
this.error = true;
this.errorMessage.append("<li>Ward already exists</li>");
}
}
public static boolean wardExists(String name) {
try {
Connection connection = DbOp.connect();
String getWardSql = "SELECT * from wards WHERE name = ?";
PreparedStatement getWardStatement = connection.prepareStatement(getWardSql);
getWardStatement.setString(1, name);
ResultSet resultSet = getWardStatement.executeQuery();
boolean wardExists = resultSet.next();
connection.close();
return wardExists;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Drug> getDrugList() {
return drugList;
}
public void setDrugList(ArrayList<Drug> drugList) {
this.drugList = drugList;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ArrayList<Batch> getBatchList() {
return batchList;
}
public void setBatchList(ArrayList<Batch> batchList) {
this.batchList = batchList;
}
public StringBuilder getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(StringBuilder errorMessage) {
this.errorMessage = errorMessage;
}
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
public void addWard() {
if (!this.error) {
try {
Connection connection = DbOp.connect();
String sql = "INSERT INTO wards(name) VALUES(?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, this.name);
statement.executeUpdate();
String getWardSql = "SELECT * from wards WHERE name = ?";
PreparedStatement getWardStatement = connection.prepareStatement(getWardSql);
getWardStatement.setString(1, this.name);
ResultSet resultSet = getWardStatement.executeQuery();
this.id = resultSet.getInt("id");
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
public static double getWardDrugQuantity(int wardId, int drugId) {
String sql = "SELECT * from drugQuantities WHERE wardID = ? AND drugID = ?";
double quantity = -1;
try {
Connection connection = DbOp.connect();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, wardId);
statement.setInt(2, drugId);
ResultSet resultSet = statement.executeQuery();
quantity = resultSet.getDouble("quantity");
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return quantity;
}
public static void setWardDrugQuantity(int wardId, int drugId, double newQuantity) {
String sql = "UPDATE drugQuantities SET quantity = ? WHERE wardID = ? and drugID = ?";
try {
Connection connection = DbOp.connect();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setDouble(1, newQuantity);
statement.setInt(2, wardId);
statement.setInt(3, drugId);
statement.executeUpdate();
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void setWardDrugAlert(int wardId, int drugId, double alert) {
String sql = "UPDATE drugQuantities SET alert = ? WHERE wardID = ? and drugID = ?";
try {
Connection connection = DbOp.connect();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setDouble(1, alert);
statement.setInt(2, wardId);
statement.setInt(3, drugId);
statement.executeUpdate();
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static double getWardDrugAlert(int wardId, int drugId) {
String sql = "SELECT * from drugQuantities WHERE wardID = ? AND drugID = ?";
double alert = -1;
try {
Connection connection = DbOp.connect();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, wardId);
statement.setInt(2, drugId);
ResultSet resultSet = statement.executeQuery();
alert = resultSet.getDouble("alert");
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return alert;
}
public static double getWardBatchQuantity(int wardId, int batchId) {
String sql = "SELECT * from batchQuantities WHERE wardID = ? AND batchID = ?";
double quantity = -1;
try {
Connection connection = DbOp.connect();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, wardId);
statement.setInt(2, batchId);
ResultSet resultSet = statement.executeQuery();
quantity = resultSet.getDouble("quantity");
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return quantity;
}
public static void setWardBatchQuantity(int wardId, int batchId, double newQuantity) {
String sql = "UPDATE batchQuantities SET quantity = ? WHERE wardID = ? and batchID = ?";
try {
Connection connection = DbOp.connect();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setDouble(1, newQuantity);
statement.setInt(2, wardId);
statement.setInt(3, batchId);
statement.executeUpdate();
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static ArrayList<Ward> getWardList() {
ArrayList<Ward> wardList = new ArrayList<>();
String sql = "SELECT * from wards";
try {
Connection connection = DbOp.connect();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String wardName = resultSet.getString("name");
int wardId = resultSet.getInt("id");
Ward ward = new Ward(wardName, wardId);
wardList.add(ward);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return wardList;
}
}
|
import Kingfisher
import SwiftUI
protocol LessonSlideViewDelegate {
func lessonSlideViewDidTapContinue(_ view: LessonSlideView)
}
struct LessonSlideView: View {
var lesson: Lesson
var delegate: LessonSlideViewDelegate?
@State var stepValue: Float = 1
var body: some View {
ScrollView {
ProgressBar(value: $stepValue).frame(height: 20)
LessonTitleView(label: lesson.title)
LessonCardView(imageURL: lesson.imageURL,
description: "Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum",
continueAction: continueAction)
}
.padding()
.navigationBarTitleDisplayMode(.inline)
}
func continueAction() {
delegate?.lessonSlideViewDidTapContinue(self)
}
// TEMP testing
func startProgressBar() {
for _ in 0 ... 80 {
stepValue += 0.015
}
}
func resetProgressBar() {
stepValue = 0.0
}
}
|
#!/usr/bin/env python3
#Advent of Code
#2023 Day 12, Part 2
#Solution by James C. (https://github.com/JamesMCo)
import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run
from functools import cache
from itertools import starmap
def solve(puzzle_input: list[str]) -> int:
@cache
def count_arrangements(springs: str, groups: tuple[int, ...]) -> int:
# Based on the implementation described in this reddit comment by /u/damaltor1
# https://www.reddit.com/r/adventofcode/comments/18ghux0/comment/kd0npmi/
if groups:
if not springs:
# No more springs, but still groups
return 0
elif springs:
if "#" in springs:
# At least one broken spring, but no groups for it to be a part of
return 0
else:
# No springs, and no groups
# Only one way to arrange nothing
return 1
match springs[0]:
case ".":
# Step once into the list
return count_arrangements(springs[1:], groups)
case "#":
# n = number of springs in the first group
# If the list starts with n broken springs, and either the group reaches the end of the list or is followed by a non-broken spring,
# then recurse without the broken springs, the separating non-broken spring (i.e. skip n+1 springs), and the group descriptor
# ? can count as # for the group check, and ? can count as . for the separating check
if len(springs) < groups[0]:
# There are not enough springs to make the group valid
return 0
elif all(c in "#?" for c in springs[:groups[0]]):
# There are enough springs to make the group valid
if len(springs) == groups[0]:
# The entire list of springs is this group
if len(groups) == 1:
# And the only group remaining is this group
return 1
else:
# There are more groups that need to be considered, and therefore
# this is invalid
return 0
else:
# There are more springs than just this group
if springs[groups[0]] in ".?":
# The spring after the group can act as a separator
return count_arrangements(springs[groups[0] + 1:], groups[1:])
else:
# The spring after the group is also broken, and cannot act as a separator
# This is invalid
return 0
else:
# There are not only broken springs in the space that should be taken by the group
# This is invalid
return 0
case "?":
# Replace ? with both . and # and sum the total arrangements from both
a = count_arrangements("." + springs[1:], groups)
b = count_arrangements("#" + springs[1:], groups)
return a + b
def parse_line(line: str) -> tuple[str, tuple[int, ...]]:
springs, groups = line.split()
return "?".join([springs] * 5), tuple(map(int, groups.split(","))) * 5
return sum(starmap(count_arrangements, map(parse_line, puzzle_input)))
def main() -> tuple[str, int]:
puzzle_input = util.read.as_lines()
return "The sum of the arrangements for all lines is {}.", solve(puzzle_input)
class AOC_Tests(unittest.TestCase):
def test_ex1(self):
return self.assertEqual(solve(["???.### 1,1,3",
".??..??...?##. 1,1,3",
"?#?#?#?#?#?#?#? 1,3,1,6",
"????.#...#... 4,1,1",
"????.######..#####. 1,6,5",
"?###???????? 3,2,1"]), 525152)
run(main)
|
package com.paulmalland;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* This is where we gonna replace our web.xml content i.e servlet declaration and servlet mapping
* The file is familiar, it's exactly what we use to do in web.xml, but now it's in java and we rejoice and
* all the content assist and the readability of java for us .... java folks
*
* @author paulm
*
*/
public class WebAppInitializer implements WebApplicationInitializer {
/**
*
*/
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher =
servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.html");
dispatcher.addMapping("*.pdf");
dispatcher.addMapping("*.json");
dispatcher.addMapping("*.xml");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
// older version of Spring MVC use context.setConfigLocation("")
// context.setConfigLocation("com.paulmalland.WebConfig");
// recent versions use context.register(WebConfig.class)
context.register(WebConfig.class);
return context;
}
}
|
<script setup>
import PageContainer from "../../components/PageContainer.vue";
import { ref } from 'vue'
import { userUpdateLoginService,userGetAllFrontUserService } from '../../api/user'
import { Edit, Delete } from '@element-plus/icons-vue'
import CategoryEdit from './components/CategoryEdit.vue'
import { formatTime } from '../../utils/format'
//获取前台全部用户数据
const allFrontUserList = ref([])
const getAllFrontUserList = async()=>{
const res = await userGetAllFrontUserService();
allFrontUserList.value = res.data
console.log(res,'全部前台用户数据');
}
getAllFrontUserList()
//按钮操作
//违规操作
const FrontUserModel = ref({
loginState: '',
id: ''
})
const ban = async(row)=>{
FrontUserModel.value.loginState = "违规"
FrontUserModel.value.id = row.id
console.log(row.id);
await ElMessageBox.confirm('你确定要封禁该用户吗', '温馨提示', {
type: 'warning',
confirmButtonText: '确认',
cancelButtonText: '手滑了'
})
await userUpdateLoginService(FrontUserModel.value)
ElMessage.success("操作成功")
getAllFrontUserList()
}
//恢复操作
const recovery = async(row)=>{
FrontUserModel.value.loginState = "正常"
FrontUserModel.value.id = row.id
await ElMessageBox.confirm('你确定要恢复该用户吗', '温馨提示', {
type: 'warning',
confirmButtonText: '确认',
cancelButtonText: '手滑了'
})
await userUpdateLoginService(FrontUserModel.value)
ElMessage.success("操作成功")
getAllFrontUserList()
}
</script>
<template>
<page-container title="用户管理">
<template #extra>
<el-button type="primary">用户管理</el-button>
</template>
<!-- 2. 卡片的主体内容 -->
<el-table v-loading="loading" :data="allFrontUserList" style="width: 100%" stripe>
<el-table-column type="index" label="序号" width="100px"></el-table-column>
<el-table-column prop="username" label="用户名" width="200px"></el-table-column>
<el-table-column prop="nickname" label="用户昵称" width="200px"></el-table-column>
<el-table-column prop="createTime" label="创建时间" width="200px">
<template #default="{ row }">
{{ formatTime(row.createTime) }}
</template>
</el-table-column>
<el-table-column prop="loginState" label="状态" width="100px"></el-table-column>
<el-table-column label="操作">
<!-- row是每一项,$index是下标 -->
<template #default="{ row, $index }">
<el-button
type="primary"
plain
@click="recovery(row, $index)"
>恢复</el-button>
<el-button
type="danger"
plain
@click="ban(row, $index)"
>违规</el-button>
</template>
</el-table-column>
<!-- 空数据时的效果 -->
<template #empty>
<el-empty description="没有数据"></el-empty>
</template>
</el-table>
</page-container>
</template>
|
package com.kortisan.framework.redux.controllers.gates
/** * * * * * * * * *
* Project KoreFrame
* Created by Jacobo G Tamayo on 30/12/22.
* * * * * * * * * * **/
import android.util.Log
import com.kortisan.framework.redux.actions.ReduxAction
import com.kortisan.framework.redux.controllers.ReduxControllerAbstract
import com.kortisan.framework.bloc.ViewModelActionDispatcher
import com.kortisan.framework.redux.ApplicationActionDispatcher
import com.kortisan.framework.redux.actions.ExitGateAction
import com.kortisan.framework.redux.actions.NavigationActions
import com.kortisan.framework.redux.controllers.ControllersProxy
import com.kortisan.framework.redux.controllers.navigation.NavigationController
import com.kortisan.framework.redux.controllers.navigation.strategies.NavigationStrategy
import java.util.Stack
/**
* Esta clase se encarga de controlar la pila de acciones, sus dependencias o requisitos así como
* la salida de esta pila con su respectiva respuestq.
*/
class GatesController: ReduxControllerAbstract() {
/**
* Pila de flujos de navegación (con su pila de estados dentro)
*/
private val actionCourseStack: Stack<ActionCourse> = Stack()
/**
* Entrada a una puerta: Evalua una puerta y determina la acción resultante de forma recursiva
*/
fun evalGate(
gate: BaseGate,
originalAction: ReduxAction,
dispatcher: ViewModelActionDispatcher? = null
): ReduxAction {
var replaceAction = originalAction
// Si todas las dependencias del gate se cumplen, procedemos a evaluar el gate actual
if( gate.enterInGate( originalAction )) {
// Es necesario reemplazar la acción original por la inicial de éste gate
var gateExistsInStack = false
actionCourseStack.forEach {
if( it.gate.name == gate.name )
gateExistsInStack = true
}
replaceAction = gate.startAction
// La acción fue reemplazada y es una acción de navegación
if( replaceAction != originalAction )
// Comprobamos que la configuración del gate permita repetirse en la pila
if( (gate.allowRepeatOnStack && gateExistsInStack) || ! gateExistsInStack )
actionCourseStack.push(
ActionCourse(
originalAction,
gate,
dispatcher,
// Asociamos la actividad al nuevo elemento de la pila de flujos.
getCurrentLaunchActivityName( replaceAction )
)
)
else
// No se permite repetir la entrada a la puerta
replaceAction = ReduxAction.EmptyAction
}
/**
* Evaluamos todas las sub puertas y obtenemos la primera cuya evaluación implique
* un cambio en la acción objetivo.
* No se permite la incepción, o un gate que se llama a sí mismo ni gates ciclicos
* en las dependencias, para eso existe el resultado tipo retry.
*/
gate.subGates.filterNot {
it.name == gate.name && it.subGates.contains( gate )
}.forEach {
// Si es necesario entrar a una sub puerta la evaluamos recursivamente
// Estas son las dependencias de este gate, por tanto se evaluan antes del gate.
if( it.enterInGate( originalAction ))
replaceAction = evalGate(
gate = it,
originalAction = replaceAction,
dispatcher
)
}
return replaceAction
}
/**
* Evaluamos si la acción de reemplazo produce una nueva actividad para abstraer el
* flujo. Esto se utiliza para las salidas de subflujos ya que permite controlar cuando
* una respuesta debe cerrar la actividad actual para continuar con la anterior
*/
private fun getCurrentLaunchActivityName( action: ReduxAction ): String? =
NavigationStrategy.currentActivity?.javaClass?.canonicalName?.let { activityName ->
if( action is NavigationActions ) {
val activityClassNameLaunched: String = action.let {
ControllersProxy.getController<NavigationController>()
?.getClassNameForNavigationAction( it ) ?: ""
}
// Existe una actividad y es diferente de la que se va a lanzar
if( activityName != activityClassNameLaunched )
activityClassNameLaunched
else
activityName
} else
activityName
}
/**
* Salida de una puerta
*
* Extraemos un elemento de la pila de flujos de navegación y navegamos al
* último elemento de la pila
*/
fun <R>exitSubFlow( exitGateResult: ExitGateResult<R> ): ReduxAction {
if( actionCourseStack.isEmpty() )
return ReduxAction.EmptyAction
val currentActionCourse = actionCourseStack.pop()
// Comprobamos que la actividad dònde se encuentra el subflujo no sea necesaria para
// otros subflujos anteriores
Log.d("GATES CONTROLLER stack", actionCourseStack.map { it.activityClassName }.toString() )
Log.d("GATES CONTROLLER", currentActionCourse.toString() )
Log.d("GATES CONTROLLER", "${NavigationStrategy.currentActivity}" )
if ( actionCourseStack.isEmpty() ) {
NavigationStrategy.currentActivity?.run {
// Si la actividad es diferente a la que la lanzó
if( javaClass.canonicalName != currentActionCourse.activityClassName ) {
// TODO: Si la actividad se va a cerrar se debe agregar la respuesta de la
// acción a la respuesta de la actividad, asumiendo que fue iniciada en la
// espera de un resultado.
currentActionCourse.dispatcher = null
}
finish()
}
}
// ¿A dónde se va a mandar la acción al salir del subflujo?
val dispatcher = currentActionCourse.dispatcher
?: ApplicationActionDispatcher.getInstance()
// ¿Qué acción se va a mandar al salir del subflujo?
val resultAction = when( exitGateResult ) {
is ExitGateResult.Retry ->
if( currentActionCourse.gate.retryAllowed )
exitGateResult.customResultRetryAction
?: currentActionCourse.gate.startAction
else
currentActionCourse.gate.onFailAction
is ExitGateResult.Fail ->
exitGateResult.customResultFailAction
?: currentActionCourse.gate.onFailAction
is ExitGateResult.Success -> {
// Si hay una acción personalizada de salida la enviamos al despachador
exitGateResult.customResultSuccessAction?.also {
dispatcher.dispatch( it )
}
currentActionCourse.gate.onSuccessAction
?: currentActionCourse.originalAction
}
}
// Al entrar al subflujo se inició una nueva actividad? Entonces se debe
// terminar la actividad si no hay dependencias en los subflujos de la pila.
// Una salida de error debe poder vaciar la pila de subflujos que lo tienen como
// dependencia.
// En caso de que aplique se lanza la acción de última voluntad
currentActionCourse.gate.lastWillAction?.also { lastWillAction ->
dispatcher.dispatch(
lastWillAction
)
}
// En caso de que el subflujo emita datos, estos se pueden recolectar en el despachador
exitGateResult.rawDataResult?.also { rawDataResult ->
dispatcher.dispatch(
ExitGateAction.SetRawDataResultAction(
currentActionCourse.gate,
currentActionCourse.originalAction,
resultAction,
rawDataResult
)
)
}
return resultAction
}
private data class ActionCourse(
val originalAction: ReduxAction,
val gate: BaseGate,
var dispatcher: ViewModelActionDispatcher? = null,
val activityClassName: String? = null
)
}
|
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark marron-color">
<div class="container">
<a class="navbar-brand" href="#">Website</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#aboutus">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#features">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#Prices">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron text-center">
<h1 class="display-4">Hello, world!</h1>
<p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
<p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
<hr class="my-4">
<a class="btn login-btn btn-lg" href="#" role="button">Sign Up</a>
<a class="btn btn-primary btn-lg" href="#" role="button">Login</a>
</div>
<section id = "aboutus">
<div class="container">
<h2 class="">About Us</h2>
<div class="row">
<div class="col-7 text-justify">Lorem ipsum dolor sit amet, consectetur adipisicing 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. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="col-5">
<img class="image-fluid" src="img/mock_ipad.jpg">
</div>
<div class="row">
<div class="col-7 text-justify">
<img class="image-fluid" src="img/mock_ipad.jpg">
</div>
<div class="col-5 text-justify">
Lorem ipsum dolor sit amet, consectetur adipisicing 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. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
</div>
</div>
</section>
<section class="text-center py-5 my-3" id="features">
<div class="container">
<br>
<br>
<h2>Features</h2>
<p>Features headline message</h2>
<div class="row">
<div class="col-4">Features</div>
<div class="col-4">Features</div>
<div class="col-4">Features</div>
</div>
<br>
<br>
<div class="row">
<div class="col-4">Features</div>
<div class="col-4">Features</div>
<div class="col-4">Features</div>
</div>
<br>
<br>
</section>
<br>
<br>
<section id="Prices">
<div class="container">
<h2 class="text-center">Our Price</h2>
<p class="text-center">Our pricing is among the most competitive in the market</p>
<table class="table text-center">
<thead>
<tr>
<th class="blue-bg">Free Plan </th>
<th class="green-bg">Standard Plan</th>
<th class="red-bg">Premier Plan</th>
</tr>
</thead>
<tbody>
<tr class="price-size">
<td class="blue-bga">RM 0</td>
<td class="green-bga">Rm 99</td>
<td class="red-bga">RM 999</td>
</tr>
<tr>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
</tr>
<tr>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
</tr>
<tr>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
</tr>
<tr>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
</tr>
<tr>
<td><button class=" blue-bg btn btn-block">Subcribe Now</button></td>
<td><button class=" green-bg btn btn-block">Subcribe Now</button></td>
<td><button class=" red-bg btn btn-block">Subcribe Now</button></td>
</tr>
</tbody>
</table>
</div>
</section>
<br>
<br>
<section id="contact">
<div class="container text center py-5 my-3">
<h2 class="text-center">Contact Us</h2>
<p class="text-center">Contact us and we will get to you</p>
<form class="form-inline justify-content-center">
<label class="sr-only" for="inlineFormInputName2">Name</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="Jane Doe">
<label class="sr-only" for="inlineFormInputGroupUsername2">Username</label>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">@</div>
</div>
<input type="text" class="form-control" id="inlineFormInputGroupUsername2" placeholder="Username">
</div>
<button type="submit" class="btn btn-primary mb-2">Submit</button>
</form>
</section>
<br/>
<br/>
<footer class="my-3 py-5">
<div class="row">
<div class="col-2">
<img class="img-fluid" src=img/logo.png >
</div>
<div class="col-3">
<h5>The Company</h5>
<ul class="list-unstyled">
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
</ul>
</div>
<div class="col-2">
<h5>The Company</h5>
<ul class="list-unstyled">
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
</ul>
</div>
<div class="col-2">
<h5>The Company</h5>
<ul class="list-unstyled">
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
</ul>
</div>
<div class="col-3">
<h5>Social</h5>
<ul class="list-unstyled">
<i class="fab fa-facebook-f"></i>
<i class="fab fa-twitter"></i>
<i class="fab fa-instagram"></i
</ul>
</div>
</footer>
</body>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
</html>
|
package at.ac.tuwien.sepr.groupphase.backend.endpoint.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ResetPasswordDto {
@NotBlank(message = "No token provided")
private String token;
@NotBlank(message = "Password must be set")
@Size(min = 8, max = 255, message = "Password must be at least 8 characters")
private String newPassword;
}
|
package bruno.aoc2015;
import bruno.util.AOCReader;
import java.io.IOException;
import java.util.List;
/**
* --- Day 6: Probably a Fire Hazard ---
*
* <p>Because your neighbors keep defeating you in the holiday house decorating contest year after
* year, you've decided to deploy one million lights in a 1000x1000 grid.
*
* <p>Furthermore, because you've been especially nice this year, Santa has mailed you instructions
* on how to display the ideal lighting configuration.
*
* <p>Lights in your grid are numbered from 0 to 999 in each direction; the lights at each corner
* are at 0,0, 0,999, 999,999, and 999,0. The instructions include whether to turn on, turn off, or
* toggle various inclusive ranges given as coordinate pairs. Each coordinate pair represents
* opposite corners of a rectangle, inclusive; a coordinate pair like 0,0 through 2,2 therefore
* refers to 9 lights in a 3x3 square. The lights all start turned off.
*
* <p>To defeat your neighbors this year, all you have to do is set up your lights by doing the
* instructions Santa sent you in order.
*
* <p>For example:
*
* <p>turn on 0,0 through 999,999 would turn on (or leave on) every light. toggle 0,0 through 999,0
* would toggle the first line of 1000 lights, turning off the ones that were on, and turning on the
* ones that were off. turn off 499,499 through 500,500 would turn off (or leave off) the middle
* four lights.
*
* <p>After following the instructions, how many lights are lit?
*
* <p>Your puzzle answer was 569999. --- Part Two ---
*
* <p>You just finish implementing your winning light pattern when you realize you mistranslated
* Santa's message from Ancient Nordic Elvish.
*
* <p>The light grid you bought actually has individual brightness controls; each light can have a
* brightness of zero or more. The lights all start at zero.
*
* <p>The phrase turn on actually means that you should increase the brightness of those lights by
* 1.
*
* <p>The phrase turn off actually means that you should decrease the brightness of those lights by
* 1, to a minimum of zero.
*
* <p>The phrase toggle actually means that you should increase the brightness of those lights by 2.
*
* <p>What is the total brightness of all lights combined after following Santa's instructions?
*
* <p>For example:
*
* <p>turn on 0,0 through 0,0 would increase the total brightness by 1. toggle 0,0 through 999,999
* would increase the total brightness by 2000000.
*
* <p>Your puzzle answer was 17836115.
*/
public class Day06 {
public static void main(String[] args) throws IOException {
String clipboard = AOCReader.readDay(2015, 6);
System.out.println("Clipboard content: " + clipboard);
System.out.println("Part1: " + part1(clipboard));
System.out.println("Part2: " + part2(clipboard));
}
private static int part1(String clipboard) {
List<String> lines = AOCReader.lines(clipboard);
boolean[][] grid = new boolean[1000][1000];
for (String line : lines) {
line = line.replace("turn ", "");
String from = line.split(" ")[1];
String to = line.split(" ")[3];
int x1 = Integer.parseInt(from.substring(0, from.indexOf(',')));
int y1 = Integer.parseInt(from.substring(from.indexOf(',') + 1));
int x2 = Integer.parseInt(to.substring(0, to.indexOf(',')));
int y2 = Integer.parseInt(to.substring(to.indexOf(',') + 1));
for (int x = x1; x <= x2; x++) {
for (int y = y1; y <= y2; y++) {
if (line.startsWith("on")) {
grid[x][y] = true;
} else if (line.startsWith("off")) {
grid[x][y] = false;
} else if (line.startsWith("toggle")) {
grid[x][y] = !grid[x][y];
}
}
}
}
int ans = 0;
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid[0].length; y++) {
if (grid[x][y]) {
ans++;
}
}
}
return ans;
}
private static int part2(String clipboard) {
List<String> lines = AOCReader.lines(clipboard);
int[][] grid = new int[1000][1000];
for (String line : lines) {
line = line.replace("turn ", "");
String from = line.split(" ")[1];
String to = line.split(" ")[3];
int x1 = Integer.parseInt(from.substring(0, from.indexOf(',')));
int y1 = Integer.parseInt(from.substring(from.indexOf(',') + 1));
int x2 = Integer.parseInt(to.substring(0, to.indexOf(',')));
int y2 = Integer.parseInt(to.substring(to.indexOf(',') + 1));
for (int x = x1; x <= x2; x++) {
for (int y = y1; y <= y2; y++) {
if (line.startsWith("on")) {
grid[x][y]++;
} else if (line.startsWith("off")) {
grid[x][y]--;
} else if (line.startsWith("toggle")) {
grid[x][y] += 2;
}
if (grid[x][y] < 0) {
grid[x][y] = 0;
}
}
}
}
int ans = 0;
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid[0].length; y++) {
ans += grid[x][y];
}
}
return ans;
}
}
|
import type { MarkInfo } from '@/app/types'
import type { Module } from 'vuex'
import type { RootState } from '../index'
export interface InformationState {
showState: boolean,
opinionInfo: MarkInfo[],
points: string,
meters: string,
// name: string,
// countryName: string,
secondLength: string
wind: string
}
const initialState = () => ({
showState: false,
opinionInfo: [],
points: '',
meters: '',
// name: '',
// countryName: '',
secondLength: '',
wind: ''
})
const informationState: Module<InformationState, RootState> = {
state: initialState(),
namespaced: true,
getters: {
getInformationState: (moduleState: InformationState) => moduleState,
getShowState: (moduleState: InformationState) => moduleState.showState
},
mutations: {
RESET: (moduleState: InformationState) => {
Object.assign(moduleState, initialState())
},
SET_STATE: (moduleState: InformationState, newState: InformationState) => {
if (newState.showState !== undefined) {
moduleState.showState = newState.showState
}
if (newState.opinionInfo !== undefined) {
moduleState.opinionInfo = newState.opinionInfo
}
if (newState.points !== undefined) {
moduleState.points = newState.points
}
if (newState.meters !== undefined) {
moduleState.meters = newState.meters
}
// if (newState.name) {
// moduleState.name = newState.name
// }
// if (newState.countryName) {
// moduleState.countryName = newState.countryName
// }
if (newState.secondLength) {
moduleState.secondLength = newState.secondLength
}
if (newState.wind !== undefined) {
moduleState.wind = newState.wind
}
}
}
}
export default informationState
|
Hi guys.
## **1. Disclaimer**
**1.1** I would like to contribute to this specific topic: Todo-txt format in Api Baserow. For example, there is a library called [todotxtio](https://epocdotfr.github.io/todotxtio/) which read todotxt files. Initially, I thought I’d respond here instead of the topic, since I’d rather do an initial demo.
**1.2** Add pip install to: requests json todotxtio
**1.3** Create a file called [todo.txt](https://github.com/todotxt/todo.txt) and an file called main.py
**1.4** Use the baserow api to send and receive data: todo.txt. By default, the Baserow API works through get and post http calls.
**1.5** txt format is a simple set of rules that make todo.txt both human and machine-readable . The format supports priorities, creation and completion dates, projects
## **2. Create a file called todo.txt and main.py**
It is important to create these files if you want to do this process automatically with a few clicks.
**2.1 filename: ./todo.txt**
Here we read a txt file with information line by line of txt tasks.
```markdown
(A) Thank Mom for the meatballs @phone
```
**2.2 filename: ./main.py**
Here is a python script that reads the todotxt file locally and imports it in a post request to Baserow.
```python
import requests
import json
import todotxtio
def apiHeader(token):
return {"Authorization": "Token " + token, "Content-Type": "application/json"}
def apiGet(id):
return "https://api.baserow.io/api/database/rows/table/"+id+"/?user_field_names=true"
def getBase(id, token):
return requests.get(apiGet(id), headers=apiHeader(token))
def postBase(id, token, string):
return requests.post(apiGet(id), headers=apiHeader(token), json={"taskName":string})
def listDatabase(id, token, property):
viewList = json.loads(json.dumps(getBase(id, token).json()))
return viewList[property]
def viewGet(idTable, token, property):
taskName = []
for index, item in enumerate(listDatabase(idTable, token, property)):
taskName.append(item['taskName'])
print('taskName: ', taskName)
def listTodos():
list_of_todos = todotxtio.from_file('todo.txt')
return list_of_todos
def listToString(array):
return ' '.join([str(elem) for elem in array])
def viewPost(idTable, token):
return postBase(idTable, token, listToString(listTodos()))
viewGet('id_table', 'add_token', 'add_property')
viewPost('id_table', 'add_token')
```
## **3. Data**
add image
## **4. Final considerations**
**4.1** What do you all think of this idea?
**4.2** This code is in the public domain, use or modify it however you want.
**4.3** The codebase of this code is the same one I developed to generate graphs in Baserow etc
**4.4** This code is something basic for demonstration purposes.
**4.5** I hope to contribute in some way to the Baserow community.
**4.6** If you all have any questions, call me here and I’ll see how I can help
|
import React, { useEffect, useState } from "react";
import { Button, Col, Container, Form, Row } from "react-bootstrap";
import {
MDBInput,
MDBBtn,
MDBCheckbox,
MDBRow,
MDBCol
} from 'mdb-react-ui-kit';
import { UserView } from "../../Model/UserView";
import {useNavigate} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import {Link} from "react-router-dom";
import { ToastUtil } from "../../../Util/ToastUtil";
import {RootUserState, usersFeatureKey} from "../../../Redux/User/user.slice";
import { AppDispatch } from "../../../Redux/Store";
import * as userActions from "../../../Redux/User/user.actions";
import Spinner from "../../../Layouts/Spinner";
interface IProps{}
interface IState{}
let Login:React.FC<IProps> =() =>{
const userState = useSelector((state: RootUserState) => {
return state[usersFeatureKey];
});
let {loading} = userState;
const dispatch: AppDispatch = useDispatch();
const navigate = useNavigate();
const [validated, setValidated] = useState(false);
const [user, setUser] = useState<UserView>({
email: "",
password: "",
isAdmin:false
});
const updateInput = (event: React.ChangeEvent<HTMLInputElement>) => {
setUser((prevState) => {
return {
...prevState,
[event.target.name]: event.target.value
}
})
};
const handleSubmit = (event: any) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === true) {
dispatch(userActions.loginUserAction(user)).then((response:any)=>{
if (response.error) {
ToastUtil.displayErrorToast("Unauthorized! User Name or Password Incorrect");
} else {
ToastUtil.displaySuccessToast('Login is Success!');
navigate('/dashboard');
}
})
}
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
return(
<>
<div className="login d-flex align-items-center justify-content-center">
{
loading && <Spinner/>
}
<Container>
<Row>
<Col></Col>
<Col>
<Row>
<Col>
<h3 className="mt-3 text-success">
<i className="fa fa-sign-in align-items-center"></i> Login</h3>
</Col>
</Row>
<Row>
<Col xs={12}>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group className="mb-3">
<Form.Control
name={'email'}
value={user.email}
onChange={updateInput}
type="email" placeholder="Email" required></Form.Control>
<Form.Control.Feedback>
Looks Good!
</Form.Control.Feedback>
<Form.Control.Feedback type="invalid">
Please choose a valid Email.
</Form.Control.Feedback>
</Form.Group>
<Form.Group className="mb-3">
<Form.Control
name={'password'}
value={user.password}
onChange={updateInput}
pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{5,20}$"
type="password" placeholder="Password" required></Form.Control>
<Form.Control.Feedback>
Looks Good!
</Form.Control.Feedback>
<Form.Control.Feedback type="invalid">
Please choose a Strong Password,
One UpperCase,
One Lower Case,
Min 5 Caharcter,
One Number,
One Special Chanrcter !@#$%^*_=+-
</Form.Control.Feedback>
</Form.Group>
<Button variant="success" type="submit">
Login
</Button>
</Form>
<small className="mt-2">Don't have an Account ?
<Link to={'/users/register'} className="text-decoration-none text-primary fw-bold"> Register</Link>
</small>
<br />
<small className="mt-2">Admin ?
<Link to={'/admin/login'} className="text-decoration-none text-primary fw-bold"> Login</Link>
</small>
</Col>
</Row>
</Col>
<Col></Col>
</Row>
</Container>
</div>
</>
);
}
export default Login;
|
import Toybox.Application;
import Toybox.Lang;
import Toybox.WatchUi;
import State;
// global Controller to manage state
var controller;
// global getApp() helper
(:background)
function getApp() as BeautifulNightscoutWatchfaceApp {
return Application.getApp() as BeautifulNightscoutWatchfaceApp;
}
(:background)
class BeautifulNightscoutWatchfaceApp extends Application.AppBase {
function initialize() {
AppBase.initialize();
controller = new State.Controller();
}
// onStart() is called on application start up
function onStart(state as Dictionary?) as Void {
}
// onStop() is called when your application is exiting
function onStop(state as Dictionary?) as Void {
controller.unregisterBackgroundEvent();
}
// Return the initial view of your application here
function getInitialView() as Array<Views or InputDelegates>? {
controller.validateAndUpdateUrl();
controller.registerBackgroundEvent();
return [ new BeautifulNightscoutWatchfaceView() ] as Array<Views or InputDelegates>;
}
// New app settings have been received so trigger a UI update
function onSettingsChanged() as Void {
controller.validateAndUpdateUrl();
WatchUi.requestUpdate();
}
// This function is called when the temporal event occurrs
function getServiceDelegate(){
controller.setBackground(true);
return [ new RequestBackground() ] as Array<ServiceDelegate>;
}
// This function passes data back to the main process when
// BG process has exited
function onBackgroundData(data) {
controller.onBackgroundData(data);
}
}
|
//
// LoginViewController.swift
// TadaApp
//
// Created by maedi laziman on 29/01/22.
// Copyright © 2022 maedi laziman. All rights reserved.
//
import UIKit
import CoreData
class LoginViewController: UIViewController {
var scrollView: UIScrollView!
var mainContentView = UIView()
var parentView: UIView!
var titlePageLabel: UILabel!
var userName: UITextField!
var password: UITextField!
var btnLogin: UIButton!
var registerLabel: UILabel!
var stackViewLoginField: UIStackView!
var autolayoutScrollView: ScrollViewAutolayoutCreator!
let actMoveToHome: ((LoginModel)->())
let actMoveToRegister: (()->())
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, actionHome: @escaping ((LoginModel)->()), actionRegister: @escaping (()->())) {
self.actMoveToHome = actionHome
self.actMoveToRegister = actionRegister
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
//super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = false
commonInit()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
}
extension LoginViewController {
private func commonInit(){
self.navigationItem.setTitle(
title: Constants.appTitle ,
underline: true,
hideBackBtn: true,
ctr: self,
fontColor: UIColor.black,
bcgColor: UIColor.white,
leftBarButton: nil,
rightBarIcon: UIImage(),
rightBarButton: nil,
customView: nil,
isLeftCustomViewPosition: true)
parentView = UIView()
parentView.setDefaultView();
titlePageLabel = UILabel()
titlePageLabel.setDefaultLabel()
titlePageLabel.setTitlePageFont()
titlePageLabel.textAlignment = .center
titlePageLabel.text = "LOGIN"
userName = UITextField()
userName.setDefaultTextField(strPlaceHolder: "Username")
password = UITextField()
password.setDefaultTextField(strPlaceHolder: "Password")
password.isSecureTextEntry = true
stackViewLoginField = UIStackView()
stackViewLoginField.setDefaultStackView(axis: .vertical)
stackViewLoginField.alignment = .leading
stackViewLoginField.spacing = 16
stackViewLoginField.addArrangedSubview(userName)
stackViewLoginField.addArrangedSubview(password)
btnLogin = UIButton()
btnLogin.setDefaultButton()
btnLogin.setTitle("LOGIN", for: .normal)
btnLogin.titleLabel?.font = Helper.setNormalFont()
btnLogin.backgroundColor = UIColor.darkGray
btnLogin.contentEdgeInsets = UIEdgeInsets.init(top: 8, left: 10, bottom: 7, right: 10)
btnLogin.addTarget(self, action: #selector(didTapLoginBtn(_:)), for: .touchUpInside)
registerLabel = UILabel()
registerLabel.setDefaultLabel()
registerLabel.attributedText = setTextAttribute(firstText: "Don’t have account ?", secondText: " Register")
registerLabel.isUserInteractionEnabled = true
registerLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapRegister)))
autolayoutScrollView = ScrollViewAutolayoutCreator(superView: self.view)
scrollView = autolayoutScrollView.scrollView
mainContentView = autolayoutScrollView.contentView
mainContentView.setDefaultView()
parentView.addSubview(titlePageLabel)
parentView.addSubview(stackViewLoginField)
parentView.addSubview(btnLogin)
parentView.addSubview(registerLabel)
mainContentView.addSubview(parentView)
setConstraint()
autolayoutScrollView.addVerticalConstraints(views: [parentView], verticalPadding: Constants.verticalPaddingContentView)
}
private func setConstraint() {
parentView.translatesAutoresizingMaskIntoConstraints = false
titlePageLabel.translatesAutoresizingMaskIntoConstraints = false
stackViewLoginField.translatesAutoresizingMaskIntoConstraints = false
btnLogin.translatesAutoresizingMaskIntoConstraints = false
registerLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
mainContentView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0),
mainContentView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0),
parentView.topAnchor.constraint(equalTo: mainContentView.topAnchor, constant: 0),
parentView.leadingAnchor.constraint(equalTo: mainContentView.leadingAnchor, constant: Constants.marginFromSide),
parentView.trailingAnchor.constraint(equalTo: mainContentView.trailingAnchor, constant: -Constants.marginFromSide),
parentView.heightAnchor.constraint(greaterThanOrEqualTo: self.view.heightAnchor),
parentView.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor),
titlePageLabel.topAnchor.constraint(equalTo: parentView.topAnchor, constant: 40),
titlePageLabel.leadingAnchor.constraint(equalTo: parentView.leadingAnchor, constant: 0),
titlePageLabel.trailingAnchor.constraint(equalTo: parentView.trailingAnchor, constant: 0),
titlePageLabel.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
stackViewLoginField.topAnchor.constraint(equalTo: titlePageLabel.bottomAnchor, constant: 50),
stackViewLoginField.leadingAnchor.constraint(equalTo: parentView.leadingAnchor, constant: 0),
stackViewLoginField.trailingAnchor.constraint(equalTo: parentView.trailingAnchor, constant: 0),
userName.leadingAnchor.constraint(equalTo: stackViewLoginField.leadingAnchor, constant: 0),
userName.trailingAnchor.constraint(equalTo: stackViewLoginField.trailingAnchor, constant: 0),
password.leadingAnchor.constraint(equalTo: stackViewLoginField.leadingAnchor, constant: 0),
password.trailingAnchor.constraint(equalTo: stackViewLoginField.trailingAnchor, constant: 0),
btnLogin.topAnchor.constraint(equalTo: stackViewLoginField.bottomAnchor, constant: 20),
btnLogin.trailingAnchor.constraint(equalTo: parentView.trailingAnchor, constant: 0),
btnLogin.heightAnchor.constraint(equalToConstant: 30),
btnLogin.widthAnchor.constraint(equalToConstant: 100),
registerLabel.topAnchor.constraint(equalTo: btnLogin.bottomAnchor, constant: 5),
registerLabel.trailingAnchor.constraint(equalTo: parentView.trailingAnchor, constant: 0),
])
}
private func setTextAttribute(firstText: String, secondText: String) -> NSAttributedString {
let font = UIFont.systemFont(ofSize: 14)
let attrs = [NSAttributedString.Key.font : font]
let attributedString = NSMutableAttributedString(string:firstText, attributes:attrs as [NSAttributedString.Key : Any])
let colorTextAttribute: [NSAttributedString.Key: Any] = [.font: font,.foregroundColor: Helper.hexStringToUIColor(hex: "#d84372")]
let colorString = NSMutableAttributedString(string:secondText, attributes:colorTextAttribute)
attributedString.append(colorString)
return attributedString
}
func checkUserIsExistInDB(loginModel: LoginModel) -> Bool{
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return false}
var exist = false
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "username") as! String)
if loginModel.userName == data.value(forKey: "username") as! String {
exist = true
break
}
}
} catch {
print("Failed")
}
return exist
}
func setFlagLogin(){
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "User")
fetchRequest.predicate = NSPredicate(format: "username = %@", userName.text!)
do
{
let test = try managedContext.fetch(fetchRequest)
let objectUpdate = test[0] as! NSManagedObject
objectUpdate.setValue(true, forKey: "login")
do{
try managedContext.save()
}
catch
{
print(error)
}
}
catch
{
print(error)
}
}
@objc func didTapLoginBtn(_ sender: UIButton) {
let usrName = userName.text
let pass = password.text
let loginModel = LoginModel(userName: usrName!, password: pass!)
let validationField = ValidationField(loginModel: loginModel)
if validationField.validationAllLoginField(ctr: self) {
if checkUserIsExistInDB(loginModel: loginModel) {
setFlagLogin()
actMoveToHome(loginModel)
}
else {
let alert = UIAlertController(title: "Error", message: "Username does not exist!, please Register first", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
@objc func didTapRegister(_ sender: UITapGestureRecognizer) {
self.actMoveToRegister()
}
}
|
<template>
<a-layout>
<div class="gx-custom-registration gx-main-content-wrapper">
<div class="gx-login-container">
<div class="gx-login-content">
<div class="gx-login-header gx-text-center">
<h1 class="gx-login-title">Register your club with SubsApp</h1>
</div>
<div v-if="validationMsg && validationMsg.length">
<a-alert
v-for="(item, index) in validationMsg"
:key="index"
type="error"
:message="item"
banner
/>
</div>
<a-form :form="form" class="gx-login-form gx-form-row0">
<a-form-item label="Club Name" class="gx-m-0">
<a-input
v-decorator="fields.club_name"
placeholder="The name of your club"
/>
</a-form-item>
<a-form-item label="First Name" class="gx-m-0">
<a-input
v-decorator="fields.first_name"
placeholder="Your first name"
/>
</a-form-item>
<a-form-item label="Last Name" class="gx-m-0">
<a-input
v-decorator="fields.last_name"
placeholder="Your last name"
/>
</a-form-item>
<a-form-item label="Email" class="gx-m-0">
<a-input v-decorator="fields.email" placeholder="Email">
</a-input>
</a-form-item>
<a-form-item label="Password" class="gx-m-0">
<a-input
v-decorator="fields.password"
placeholder="Password"
type="password"
>
</a-input>
</a-form-item>
<a-form-item label="Confirm Password">
<a-input
v-decorator="fields.c_password"
placeholder="Confirm Password"
type="password"
>
</a-input>
</a-form-item>
<a-form-item class="gx-text-center">
<a-button
type="primary"
block
html-type="submit"
:loading="loginLoading"
@click="handleForm"
>
Register
</a-button>
</a-form-item>
<div class="gx-text-center">
<router-link to="/"></router-link>
</div>
</a-form>
</div>
</div>
</div>
</a-layout>
</template>
<script>
import { authService } from "@/common/api/api.service";
import notifications from "@/common/notifications/notification.service";
import { AUTH_REQUEST } from "@/store/modules/auth/auth-actions";
export default {
name: "ClubRegister",
data() {
return {
loginLoading: false,
message: null,
validationMsg: [],
confirmDirty: false,
form: this.$form.createForm(this),
fields: {
club_name: [
"club_name",
{
rules: [
{
required: true,
message: "The club name is required"
}
]
}
],
first_name: [
"first_name",
{
rules: [
{
required: true,
message: "Your first name is required"
}
]
}
],
last_name: [
"last_name",
{
rules: [
{
required: true,
message: "Your last name is required"
}
]
}
],
email: [
"work_email",
{
rules: [
{
required: true,
validator: this.validateEmail
}
]
}
],
password: [
"password",
{
rules: [
{
required: true,
message: "Please input your password!"
},
{
validator: this.validateToNextPassword
}
]
}
],
c_password: [
"c_password",
{
rules: [
{
required: true,
message: "Please confirm your password!"
},
{
validator: this.compareToFirstPassword
}
]
}
]
}
};
},
methods: {
handleForm() {
this.form.validateFields((err, values) => {
this.message = null;
if (!err) {
if (values.password === values.c_password) {
this.handleFormSubmit({
...values,
teamId: this.teamId
});
} else {
this.message = "Passwords do not match";
}
}
});
},
handleFormSubmit(values) {
this.loginLoading = true;
this.validationMsg = [];
authService
.clubRegister(values)
.then(resp => {
if (resp.data.success) {
notifications.success("Registration complete. Welcome to SubsApp");
this.$store
.dispatch(AUTH_REQUEST, {
username: values.work_email,
password: values.password
})
.then(resp => {
if (resp) {
this.$router.push("/dashboard");
}
this.loginLoading = false;
})
.catch(() => {
this.$router.push("/login");
this.loginLoading = false;
});
} else {
this.loginLoading = false;
if (resp.data.message) {
notifications.warn(resp.data.message);
} else {
notifications.warn(
"Something went wrong, please contact support"
);
}
}
})
.catch(error => {
this.loginLoading = false;
if (error.response.status === 422) {
let errors = Object.values(error.response.data.errors);
this.validationMsg = errors.flat();
console.log(this.validationMsg);
} else {
notifications.warn("Something went wrong, please try again later");
}
});
},
compareToFirstPassword(rule, value, callback) {
const form = this.form;
if (value && value !== form.getFieldValue("password")) {
callback("Passwords do not match");
} else {
callback();
}
},
validateToNextPassword(rule, value, callback) {
const form = this.form;
if (value && this.confirmDirty) {
form.validateFields(["c_password"], { force: true });
}
callback();
},
validateEmail(rule, value, callback) {
const form = this.form;
const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,24}))$/;
if (!emailRegex.test(form.getFieldValue("work_email"))) {
callback("Please enter a valid email");
} else {
callback();
}
}
}
};
</script>
<style lang="scss">
@media screen and (min-width: 0px) and (max-width: 991px) {
.gx-custom-registration {
padding: 0 !important;
& .ant-input {
line-height: 2;
padding: 12px 18px !important;
font-size: 18px;
margin-bottom: 18px;
}
& .ant-form-item-label {
margin-bottom: 8px;
}
& .ant-form-item-label > label {
font-size: 18px;
}
& .ant-btn {
padding: 16px 42px !important;
line-height: 2;
width: 100%;
}
}
}
</style>
|
<div class="container">
<h1>Multi-step Wizard</h1>
<app-wizard>
<app-wizard-step [active]="false">
<h2>Step 1: Personal Information</h2>
<div class="step-content">
<!-- Your personal information form goes here -->
<form>
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required />
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required />
<!-- Other input fields for personal information -->
</form>
</div>
</app-wizard-step>
<app-wizard-step>
<h2>Step 2: Address Details</h2>
<div class="step-content">
<!-- Your address details form goes here -->
<form>
<label for="street">Street:</label>
<input type="text" id="street" name="street" required />
<label for="city">City:</label>
<input type="text" id="city" name="city" required />
<!-- Other input fields for address details -->
</form>
</div></app-wizard-step
>
<app-wizard-step>
<h2>Step 3: Payment Information</h2>
<div class="step-content">
<!-- Your payment information form goes here -->
<form>
<label for="cardNumber">Card Number:</label>
<input type="text" id="cardNumber" name="cardNumber" required />
<label for="expiryDate">Expiry Date:</label>
<input type="text" id="expiryDate" name="expiryDate" required />
<!-- Other input fields for payment information -->
</form>
</div></app-wizard-step
>
<app-wizard-step>
<h2>Step 4: Confirmation</h2>
<div class="step-content">
<!-- Your confirmation details go here -->
<p>Please review your information before submitting:</p>
<ul>
<li>First Name: John</li>
<li>Last Name: Doe</li>
<li>Street: 123 Main St</li>
<li>City: Anytown</li>
<li>Card Number: **** **** **** 1234</li>
<li>Expiry Date: 12/24</li>
</ul>
</div></app-wizard-step
>
</app-wizard>
</div>
|
<?php
use App\Http\Controllers\AdminController;
use App\Http\Controllers\ConfirmAgeController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\MoviesController;
use App\Http\Controllers\MovieReservationController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', [HomeController::class, 'home'])
->name('home');
/*
|--------------------------------------------------------------------------
| Autenticación
|--------------------------------------------------------------------------
*/
Route::get('iniciar-sesion', [AuthController::class, 'formLogin'])
->name('auth.formLogin');
Route::post('iniciar-sesion', [AuthController::class, 'processLogin'])
->name('auth.processLogin');
Route::get('crear-cuenta', [AuthController::class, 'formRegister'])
->name('auth.formRegister');
Route::post('crear-cuenta', [AuthController::class, 'processRegister'])
->name('auth.processRegister');
Route::post('cerrar-sesion', [AuthController::class, 'processLogout'])
->name('auth.processLogout');
/*
|--------------------------------------------------------------------------
| Películas
|--------------------------------------------------------------------------
*/
Route::get('peliculas/listado', [MoviesController::class, 'index'])
->name('movies.index');
Route::get('peliculas/nueva', [MoviesController::class, 'formNew'])
->name('movies.formNew')
->middleware(['auth', 'verificar-rol']);
Route::post('peliculas/nueva', [MoviesController::class, 'processNew'])
->name('movies.processNew')
->middleware(['auth', 'verificar-rol']);
Route::get('peliculas/{id}', [MoviesController::class, 'view'])
->name('movies.view')
->middleware(['mayoria-de-edad']);
Route::get('peliculas/{id}/confirmar-edad', [ConfirmAgeController::class, 'formConfirmation'])
->name('confirm-age.formConfirmation');
Route::post('peliculas/{id}/confirmar-edad', [ConfirmAgeController::class, 'processConfirmation'])
->name('confirm-age.processConfirmation');
Route::get('peliculas/{id}/editar', [MoviesController::class, 'formUpdate'])
->name('movies.formUpdate')
->middleware(['auth', 'verificar-rol']);
Route::post('peliculas/{id}/editar', [MoviesController::class, 'processUpdate'])
->name('movies.processUpdate')
->middleware(['auth', 'verificar-rol']);
Route::get('peliculas/{id}/eliminar', [MoviesController::class, 'confirmDelete'])
->name('movies.confirmDelete')
->middleware(['auth', 'verificar-rol']);
Route::post('peliculas/{id}/eliminar', [MoviesController::class, 'processDelete'])
->name('movies.processDelete')
->middleware(['auth', 'verificar-rol']);
Route::post('peliculas/{id}/reservar', [MovieReservationController::class, 'processReservation'])
->name('movies.processReservation')
->middleware(['auth']);
/*
|--------------------------------------------------------------------------
| Admin
|--------------------------------------------------------------------------
*/
Route::get('admin', [AdminController::class, 'dashboard'])
->name('admin.dashboard')
->middleware(['auth', 'verificar-rol']);
/*
|--------------------------------------------------------------------------
| 404
|--------------------------------------------------------------------------
*/
Route::fallback(function () {
return view('home');
});
|
@model BookReviewer.Models.ViewModels.BookAuthorsPublishers
@using BookReviewer.Models.ViewModels
@{
ViewBag.Title = "Edit Book";
}
<div class="row justify-content-center">
@using (Html.BeginForm("Edit", "Books", FormMethod.Post, htmlAttributes: new { @class = "col-lg-6 col-md-8 col-11 border border-primary border-2 rounded-2 p-4", @enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<h2 class="text-center mb-5">Edit Book</h2>
@Html.HiddenFor(model => model.Book.Id)
<!-- title -->
<div class="form-group mb-4">
@Html.LabelFor(m => m.Book.Title, htmlAttributes: new { @class = "form-label" })
@Html.EditorFor(m => m.Book.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Book.Title, "", new { @class = "text-danger" })
</div>
<!-- isbn -->
<div class="form-group mb-4">
@Html.LabelFor(m => m.Book.Isbn, htmlAttributes: new { @class = "form-label" })
@Html.EditorFor(m => m.Book.Isbn, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Book.Isbn, "", new { @class = "text-danger" })
</div>
<!-- genre -->
<div class="form-group mb-4">
@Html.LabelFor(m => m.Book.Genre, htmlAttributes: new { @class = "form-label" })
@Html.EditorFor(m => m.Book.Genre, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Book.Genre, "", new { @class = "text-danger" })
</div>
<!-- date -->
<div class="form-group mb-4">
@Html.LabelFor(m => m.Book.DatePublished, htmlAttributes: new { @class = "form-label" })
@Html.TextBoxFor(m => m.Book.DatePublished, "{0:yyyy-MM-dd}", new { @class = "form-control", @type = "date" })
@Html.ValidationMessageFor(m => m.Book.DatePublished, "", new { @class = "text-danger" })
</div>
<!-- image -->
<div class="form-group mb-4">
@Html.LabelFor(m => m.ImageFile, htmlAttributes: new { @class = "form-label" })
@Html.TextBoxFor(m => m.ImageFile, new { @class = "form-control", @type = "file" })
@Html.ValidationMessageFor(m => m.ImageFile, "", new { @class = "text-danger" })
</div>
<!-- author -->
<div class="form-group mb-4">
@Html.LabelFor(m => m.Book.AuthorId, htmlAttributes: new { @class = "form-label" })
@Html.DropDownListFor(
m => m.Book.AuthorId,
Model.Authors
.Select(a => new SelectListItem
{
Text = a.FullName(),
Value = $"{a.Id}"
}),
htmlAttributes: new { @class = "form-select" }
)
@Html.ValidationMessageFor(m => m.Book.AuthorId, "", new { @class = "text-danger" })
</div>
<!-- publisher -->
<div class="form-group mb-4">
@Html.LabelFor(m => m.Book.PublisherId, htmlAttributes: new { @class = "form-label" })
@Html.DropDownListFor(
m => m.Book.PublisherId,
Model.Publishers
.Select(p => new SelectListItem
{
Text = p.FullName(),
Value = $"{p.Id}"
}),
htmlAttributes: new { @class = "form-select" }
)
@Html.ValidationMessageFor(m => m.Book.PublisherId, "", new { @class = "text-danger" })
</div>
<!-- description -->
<div class="form-group mb-4">
@Html.LabelFor(m => m.Book.Description, htmlAttributes: new { @class = "form-label" })
@Html.TextAreaFor(m => m.Book.Description, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Book.Description, "", new { @class = "text-danger" })
</div>
<button class="btn btn-primary w-100">Submit</button>
}
</div>
@*@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Book</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Isbn, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Isbn, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Isbn, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Genre, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Genre, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Genre, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DatePublished, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DatePublished, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DatePublished, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Image, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.AuthorId, "AuthorId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("AuthorId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AuthorId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PublisherId, "PublisherId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("PublisherId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.PublisherId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}*@
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
|
import { Request, Response } from 'express'
import { when } from 'jest-when'
import { plainToInstance } from 'class-transformer'
import { validate } from 'class-validator'
import ActivitiesService from '../../../../services/activitiesService'
import NotAttendedReasonRoutes, { NotAttendedForm } from './notAttendedReason'
import { AttendanceReason, AttendanceUpdateRequest, ScheduledActivity } from '../../../../@types/activitiesAPI/types'
import { YesNo } from '../../../../@types/activities'
import AttendanceReasons from '../../../../enum/attendanceReason'
import { associateErrorsWithProperty } from '../../../../utils/utils'
import AttendanceStatus from '../../../../enum/attendanceStatus'
jest.mock('../../../../services/activitiesService')
const activitiesService = new ActivitiesService(null)
describe('Route Handlers - Non Attendance', () => {
const handler = new NotAttendedReasonRoutes(activitiesService)
let req: Request
let res: Response
beforeEach(() => {
res = {
locals: {
user: {
username: 'joebloggs',
activeCaseLoadId: 'MDI',
},
},
render: jest.fn(),
redirectWithSuccess: jest.fn(),
} as unknown as Response
req = {
params: { id: 1 },
session: {
notAttendedJourney: {
activityInstance: {
date: '2023-10-25',
startTime: '09:00',
activitySchedule: { activity: { summary: 'Test activity' }, internalLocation: { description: 'Room 1' } },
},
selectedPrisoners: [{ attendanceId: 1, prisonerNumber: 'ABC123', prisonerName: 'JOE BLOGGS' }],
},
},
body: plainToInstance(NotAttendedForm, {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'JOE BLOGGS',
notAttendedReason: AttendanceReasons.SICK,
moreDetail: '',
caseNote: null,
otherAbsenceReason: null,
sickPay: YesNo.YES,
isPayable: true,
},
],
}),
} as unknown as Request
})
afterEach(() => {
jest.resetAllMocks()
})
describe('GET', () => {
it('should render with the expected view', async () => {
when(activitiesService.getScheduledActivity)
.calledWith(1, res.locals.user)
.mockResolvedValue({
id: 1,
activitySchedule: {
id: 2,
activity: {
id: 2,
paid: true,
},
},
} as ScheduledActivity)
when(activitiesService.getAttendanceReasons)
.calledWith(res.locals.user)
.mockResolvedValue([
{
id: 1,
code: 'SICK',
description: 'Sickness',
attended: false,
capturePay: true,
captureMoreDetail: true,
captureCaseNote: false,
captureIncentiveLevelWarning: false,
captureOtherText: false,
displaySequence: 1,
displayInAbsence: true,
},
{
id: 2,
code: 'ATTENDED',
description: 'Attended',
attended: true,
capturePay: false,
captureMoreDetail: false,
captureCaseNote: false,
captureIncentiveLevelWarning: false,
captureOtherText: false,
displaySequence: 2,
displayInAbsence: false,
},
] as AttendanceReason[])
await handler.GET(req, res)
expect(res.render).toHaveBeenCalledWith('pages/activities/record-attendance/not-attended-reason', {
notAttendedReasons: [
{
id: 1,
code: 'SICK',
description: 'Sickness',
attended: false,
capturePay: true,
captureMoreDetail: true,
captureCaseNote: false,
captureIncentiveLevelWarning: false,
captureOtherText: false,
displaySequence: 1,
displayInAbsence: true,
},
],
selectedPrisoners: [{ attendanceId: 1, prisonerNumber: 'ABC123', prisonerName: 'JOE BLOGGS' }],
isPayable: true,
})
})
})
describe('POST', () => {
const expectedAttendance = {
id: 1,
prisonCode: 'MDI',
status: AttendanceStatus.COMPLETED,
attendanceReason: AttendanceReasons.SICK,
incentiveLevelWarningIssued: false,
issuePayment: true,
comment: '',
caseNote: null,
otherAbsenceReason: null,
} as AttendanceUpdateRequest
it('non attendance should be redirected to the non attendance page', async () => {
when(activitiesService.getScheduledActivity)
.calledWith(1, res.locals.user)
.mockResolvedValue({
id: 1,
activitySchedule: {
id: 2,
activity: {
id: 2,
paid: true,
},
},
} as ScheduledActivity)
await handler.POST(req, res)
expect(activitiesService.updateAttendances).toHaveBeenCalledWith([expectedAttendance], res.locals.user)
expect(res.redirectWithSuccess).toHaveBeenCalledWith(
'attendance-list',
'Attendance recorded',
"You've saved attendance details for Joe Bloggs",
)
})
it('should not issue payment if activity is unpaid', async () => {
when(activitiesService.getScheduledActivity)
.calledWith(1, res.locals.user)
.mockResolvedValue({
id: 1,
activitySchedule: {
id: 2,
activity: {
id: 2,
paid: false,
},
},
} as ScheduledActivity)
await handler.POST(req, res)
const unpaidAttendance = {
...expectedAttendance,
issuePayment: false,
}
expect(activitiesService.updateAttendances).toHaveBeenCalledWith([unpaidAttendance], res.locals.user)
expect(res.redirectWithSuccess).toHaveBeenCalledWith(
'attendance-list',
'Attendance recorded',
"You've saved attendance details for Joe Bloggs",
)
})
})
describe('Validation', () => {
it('should pass validation', async () => {
const requestData = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.SICK,
sickPay: YesNo.YES,
},
{
prisonerNumber: 'ABC234',
prisonerName: 'John Smith',
isPayable: true,
notAttendedReason: AttendanceReasons.SICK,
sickPay: YesNo.NO,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, requestData)
const errors = await validate(requestObject)
expect(errors.length).toEqual(0)
})
it('should fail validation if no attendence reason provided', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'notAttendedReason',
error: 'Select an absence reason for Joe Bloggs',
})
})
it('should fail validation if an invalid reason is provided', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
notAttendedReason: 'INVALID',
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'notAttendedReason',
error: 'Select an absence reason for Joe Bloggs',
})
})
it('should fail validation if attendence reason is "SICK" and pay not selected', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.SICK,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'sickPay',
error: 'Select if Joe Bloggs should be paid',
})
})
it('should fail validation if attendence reason is "REST" and pay not selected', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.REST,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'restPay',
error: 'Select if Joe Bloggs should be paid',
})
})
it('should fail validation if attendence reason is "OTHER" and pay not selected', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.OTHER,
otherAbsenceReason: 'absence reason',
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'otherAbsencePay',
error: 'Select if this is an acceptable absence for Joe Bloggs and they should be paid',
})
})
it('should pass validation and not require pay selection if attendence reason is "SICK" and activity is unpaid', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'false',
notAttendedReason: AttendanceReasons.SICK,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject)
expect(errors.length).toEqual(0)
})
it('should pass validation and not require pay selection if attendence reason is "REST" and activity is unpaid', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'false',
notAttendedReason: AttendanceReasons.REST,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject)
expect(errors.length).toEqual(0)
})
it('should pass validation and not require pay selection if attendence reason is "OTHER" and activity is unpaid', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'false',
notAttendedReason: AttendanceReasons.SICK,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject)
expect(errors.length).toEqual(0)
})
it('should fail validation if attendence reason is "OTHER" and other absence reason not entered', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.OTHER,
otherAbsenceReason: '',
otherAbsencePay: YesNo.YES,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'otherAbsenceReason',
error: 'Enter an absence reason for Joe Bloggs',
})
})
it('should fail validation if attendence reason is "OTHER" and other absence reason exceeds 100 characters', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.OTHER,
otherAbsenceReason: 'a'.repeat(101),
otherAbsencePay: YesNo.YES,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'otherAbsenceReason',
error: 'Absence reason must be 100 characters or less',
})
})
it('should fail validation if attendence reason is "SICK" and more details exceed 100 characters', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.SICK,
sickPay: YesNo.YES,
moreDetail: 'a'.repeat(101),
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'moreDetail',
error: 'Additional details must be 100 characters or less',
})
})
it('should fail validation if attendence reason is "REFUSED" and case note not entered', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.REFUSED,
incentiveLevelWarningIssued: YesNo.YES,
caseNote: '',
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'caseNote',
error: 'Enter a case note for Joe Bloggs',
})
})
it('should fail validation if attendence reason is "REFUSED" and case note exceeds 4000 characters', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.REFUSED,
incentiveLevelWarningIssued: YesNo.YES,
caseNote: 'a'.repeat(4001),
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'caseNote',
error: 'Case note must be 3800 characters or less',
})
})
it('should fail validation if attendence reason is "REFUSED" and incentive level warning not selected', async () => {
const badRequest = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.REFUSED,
caseNote: 'case note',
},
],
}
const requestObject = plainToInstance(NotAttendedForm, badRequest)
const errors = await validate(requestObject).then(errs =>
errs[0]?.children[0]?.children.flatMap(associateErrorsWithProperty),
)
expect(errors.length).toEqual(1)
expect(errors[0]).toEqual({
property: 'incentiveLevelWarningIssued',
error: 'Select if there should be an incentive level warning for Joe Bloggs',
})
})
it('should not set case note when attendance reason not "REFUSED"', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.SICK,
caseNote: 'case note',
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getCaseNote(req.session.notAttendedJourney.activityInstance)).toBeNull()
})
it('should set case note when attendance reason is "REFUSED"', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.REFUSED,
caseNote: 'case note',
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getCaseNote(req.session.notAttendedJourney.activityInstance)).toEqual(
'Refused to attend - Test activity - Room 1 - Wednesday, 25 October 2023 - 09:00 \n\ncase note',
)
})
it('should set case note when attendance reason is "REFUSED" and location is undefined', async () => {
req.session.notAttendedJourney.activityInstance.activitySchedule.internalLocation = undefined
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.REFUSED,
caseNote: 'case note',
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getCaseNote(req.session.notAttendedJourney.activityInstance)).toEqual(
'Refused to attend - Test activity - Wednesday, 25 October 2023 - 09:00 \n\ncase note',
)
})
it('should not issue payment if attendance reason is "REFUSED"', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.REFUSED,
sickPay: YesNo.YES,
restPay: YesNo.YES,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getIssuePayment()).toEqual(false)
})
it('should always issue payment if attendance reason is "CLASH"', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.CLASH,
sickPay: YesNo.NO,
restPay: YesNo.NO,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getIssuePayment()).toEqual(true)
})
it('should always issue payment if attendance reason is "NOT_REQUIRED"', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.NOT_REQUIRED,
sickPay: YesNo.NO,
restPay: YesNo.NO,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getIssuePayment()).toEqual(true)
})
it('should not issue payment if attendance reason is "SICK" and sick pay not selected', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.SICK,
sickPay: YesNo.NO,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getIssuePayment()).toEqual(false)
})
it('should not issue payment if attendance reason is "OTHER" and not acceptable', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.OTHER,
otherAbsencePay: YesNo.NO,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getIssuePayment()).toEqual(false)
})
it('should not issue payment if attendance reason is "OTHER" and acceptable', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.OTHER,
otherAbsencePay: YesNo.YES,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getIssuePayment()).toEqual(true)
})
it('should not issue payment if attendance reason is "REST" and rest pay not selected', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.REST,
restPay: YesNo.NO,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getIssuePayment()).toEqual(false)
})
it('should not issue incentive level warning if attendance reason is not "REFUSED"', async () => {
const request = {
notAttendedData: [
{
prisonerNumber: 'ABC123',
prisonerName: 'Joe Bloggs',
isPayable: 'true',
notAttendedReason: AttendanceReasons.SICK,
incentiveLevelWarningIssued: YesNo.YES,
},
],
}
const requestObject = plainToInstance(NotAttendedForm, request)
expect(requestObject.notAttendedData[0].getIncentiveLevelWarning()).toEqual(false)
})
})
})
|
import { useRef, useState } from 'react'
import { UserAuth } from '../context/app context/AuthContext'
import { Alert } from 'react-bootstrap'
export default function useAddTeacher(refreshData) {
const firstNameRef = useRef()
const lastNameRef = useRef()
const emailRef = useRef()
const passwordRef = useRef()
const passwordConfirmRef = useRef()
const [gender, setGender] = useState('Choose')
const [enabled, setEnabled] = useState('Choose')
const [success, setSuccess] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const { createTeacher } = UserAuth()
const enable = () => {
setEnabled('Enabled')
}
const disable = () => {
setEnabled('Disable')
}
const setMale = () => {
setGender('Male')
}
const setFemale = () => {
setGender('Female')
}
function handleAddTeacher(event) {
event.preventDefault()
setError('')
setSuccess('')
setLoading(true)
const teacher = {
firstName: firstNameRef?.current?.value,
lastName: lastNameRef?.current?.value,
email: emailRef?.current?.value,
password: passwordRef?.current?.value,
passwordConfirm: passwordConfirmRef?.current?.value,
gender: gender.toLowerCase(),
disabled: enabled.toLowerCase()
}
console.table(teacher)
createTeacher(teacher)
.then(response => {
if (response.status === 'success') {
firstNameRef.current.value = ''
lastNameRef.current.value = ''
emailRef.current.value = ''
passwordRef.current.value = ''
passwordConfirmRef.current.value = ''
setGender('Choose')
setSuccess(response.message)
refreshData()
}
else
setError(response.message)
})
.catch(() => {
setError("Couldn't process request due to unresolved issue")
})
.finally(() => {
setLoading(false)
})
}
const ErrorAlert = <>
{error && <Alert variant='danger' onClose={() => setError('')} dismissible>{error}</Alert>}
</>
const SuccessAlert = <>
{success && <Alert variant='success' onClose={() => setSuccess('')} dismissible>{success}</Alert>}
</>
return {
firstNameRef,
lastNameRef,
emailRef,
passwordRef,
passwordConfirmRef,
gender,
setMale,
setFemale,
enabled,
enable,
disable,
loading,
ErrorAlert,
SuccessAlert,
handleAddTeacher
}
}
|
from dataclasses import dataclass
from logging import getLogger
from typing import Any
from fastapi_proj.domain.enteties.component import (
Component,
ComponentCategory,
Ingredient,
)
from fastapi_proj.domain.values.components import CommonTitle
from fastapi_proj.infra.repositories.recipies.base import (
BaseComponentRepository,
)
from fastapi_proj.logic.comands.base import BaseCommand, BaseCommandHandler
logger = getLogger(__name__)
@dataclass(frozen=True)
class CreateComponentCommand(BaseCommand):
title: CommonTitle
category: ComponentCategory
ingredients: list[Ingredient]
@dataclass(frozen=True)
class GetComponentsByCategory(BaseCommand):
category: ComponentCategory
limit: int
offset: int
@dataclass(frozen=True)
class GetComponentByTitleCommand(BaseCommand):
title: CommonTitle
@dataclass(frozen=True)
class GetRandomComponentInCategoryCommand(BaseCommand):
category: ComponentCategory
@dataclass(frozen=True)
class DeleteComponentByTitleCommand(BaseCommand):
title: CommonTitle
@dataclass(frozen=True)
class UpdateComponentByTitleCommand(BaseCommand):
title: CommonTitle
category: ComponentCategory
ingredients: list[Ingredient]
@dataclass
class CreateComponentCommandHandler(BaseCommandHandler[CreateComponentCommand, str]):
component_repository: BaseComponentRepository
async def handle(self, command):
component = Component(command.title, command.category, command.ingredients)
await self.component_repository.add_component(component)
@dataclass
class GetComponentsByCategoryHandler(
BaseCommandHandler[GetComponentsByCategory, list[Component]]
):
component_repository: BaseComponentRepository
async def handle(self, command: GetComponentsByCategory) -> list[dict]:
result = await self.component_repository.get_components_by_category(
command.category.name, command.limit, command.offset
)
return result
@dataclass
class GetComponentByTitleHandler(BaseCommandHandler[GetComponentByTitleCommand, dict]):
component_repository: BaseComponentRepository
async def handle(self, command: GetComponentByTitleCommand) -> dict:
return await self.component_repository.get_component_by_title(command.title)
@dataclass
class GetRandomComponentInCategoryHandler(
BaseCommandHandler[GetRandomComponentInCategoryCommand, dict[str, Any]]
):
component_repository: BaseComponentRepository
async def handle(
self, command: GetRandomComponentInCategoryCommand
) -> dict[str, Any]:
return await self.component_repository.get_random_component_by_category(
command.category
)
@dataclass
class DeleteComponentByTitleHandler(
BaseCommandHandler[DeleteComponentByTitleCommand, None]
):
component_repository: BaseComponentRepository
async def handle(self, command: DeleteComponentByTitleCommand) -> None:
return await self.component_repository.delete_by_title(command.title)
@dataclass
class UpdateComponentByTitleHandler(
BaseCommandHandler[UpdateComponentByTitleCommand, None]
):
component_repository: BaseComponentRepository
async def handle(self, command: UpdateComponentByTitleCommand) -> None:
component = Component(command.title, command.category, command.ingredients)
result = await self.component_repository.update_one_component_ingredients(
component
)
return result
|
package day22
import (
"adventOfGode2023/util"
"slices"
"strconv"
"strings"
)
func Part1(input string) string {
bricks := parse(input)
bricks = applyGravity(bricks)
supports := supporting(bricks)
supporterCount := make([]int, len(supports))
for _, supported := range supports {
for _, supportee := range supported {
supporterCount[supportee]++
}
}
disintegratable := 0
SUPPORTER:
for s := 0; s < len(supports); s++ {
supporting := supports[s]
if len(supporting) == 0 {
disintegratable++
continue
}
for _, supportee := range supporting {
if supporterCount[supportee] < 2 {
continue SUPPORTER
}
}
disintegratable++
}
return strconv.Itoa(disintegratable)
}
func supporting(bricks []Brick) map[int][]int {
var supports = map[int][]int{} // list of bricks that one brick supports
for i := 0; i < len(bricks); i++ {
supports[i] = make([]int, 0)
current := bricks[i]
highestZ := max(current.to.z, current.from.z)
var directlyAbove []C
for x := min(current.from.x, current.to.x); x <= max(current.from.x, current.to.x); x++ {
for y := min(current.from.y, current.to.y); y <= max(current.from.y, current.to.y); y++ {
c := C{x, y, highestZ + 1}
directlyAbove = append(directlyAbove, c)
}
}
for j := 0; j < len(bricks); j++ {
if bricks[j].containsAny(directlyAbove) {
supports[i] = append(supports[i], j)
}
}
}
return supports
}
func applyGravity(bricks []Brick) []Brick {
slices.SortFunc(bricks, func(a, b Brick) int {
return a.from.z - b.from.z
})
FALLING:
for i := 0; i < len(bricks); i++ {
current := bricks[i]
lowestZ := min(current.to.z, current.from.z)
if lowestZ <= 1 {
continue
}
target := current
target.from.z--
target.to.z--
for j := i - 1; j >= 0; j-- {
if bricks[j].to.z != target.from.z {
continue
}
if bricks[j].overlaps(target) {
continue FALLING
}
}
// no collision, let's change the world for a ~~better~~ sandier place
current.to.z -= 1
current.from.z -= 1
bricks[i] = current
// keep pointer at current brick to check if it can fall further
i--
// maintain sort by lowest
if i > 0 {
for bricks[i].from.z < bricks[i-1].from.z {
bricks[i], bricks[i-1] = bricks[i-1], bricks[i]
// keep pointer on current brick, again
i--
}
}
}
return bricks
}
type Brick struct {
from C
to C
}
func (b Brick) contains(c C) bool {
return c.x >= b.from.x &&
c.x <= b.to.x &&
c.y >= b.from.y &&
c.y <= b.to.y &&
c.z >= b.from.z &&
c.z <= b.to.z
}
func (b Brick) containsAny(cs []C) bool {
for _, c := range cs {
if b.contains(c) {
return true
}
}
return false
}
func (b Brick) overlaps(other Brick) bool {
overlapZ := intervalOverlaps(b.from.z, b.to.z, other.from.z, other.to.z)
overlapY := intervalOverlaps(b.from.y, b.to.y, other.from.y, other.to.y)
overlapX := intervalOverlaps(b.from.x, b.to.x, other.from.x, other.to.x)
return overlapX && overlapY && overlapZ
}
// intervalOverlaps interval borders are inclusive
func intervalOverlaps(aStart int, aEnd int, bStart int, bEnd int) bool {
if aStart <= bStart && bStart <= aEnd {
return true
}
if aStart <= bEnd && bEnd <= aEnd {
return true
}
if bStart <= aStart && aStart <= bEnd {
return true
}
if bStart <= aEnd && aEnd <= bEnd {
return true
}
return false
}
type C struct {
x, y, z int
}
func parseC(input string) C {
split := strings.Split(input, ",")
x, _ := strconv.Atoi(split[0])
y, _ := strconv.Atoi(split[1])
z, _ := strconv.Atoi(split[2])
return C{x, y, z}
}
func parse(input string) (result []Brick) {
for _, line := range strings.Split(input, "\n") {
split := strings.Split(line, "~")
result = append(result, Brick{from: parseC(split[0]), to: parseC(split[1])})
}
return
}
func Part2(input string) string {
bricks := parse(input)
bricks = applyGravity(bricks)
supports := supporting(bricks)
supporterCount := make([]int, len(supports))
for _, supported := range supports {
for _, supportee := range supported {
supporterCount[supportee]++
}
}
fallingSum := 0
for supporter := 0; supporter < len(supports); supporter++ {
hits := make([]int, len(supports))
queue := util.Queue[int]{}
falling := 0
for _, supportee := range supports[supporter] {
queue.Enqueue(supportee)
}
for supportee, ok := queue.Dequeue(); ok; supportee, ok = queue.Dequeue() {
hits[supportee]++
if hits[supportee] == supporterCount[supportee] {
falling++
for _, next := range supports[supportee] {
queue.Enqueue(next)
}
}
}
fallingSum += falling
}
return strconv.Itoa(fallingSum)
}
|
{% extends 'home.html' %}
{% load static %}
{% block css %}
<link href="{% static 'visual.css' %}" rel="stylesheet">
{% endblock %}
{% block title %}
<title>StockChart</title>
{% endblock %}
{% block active %}
<div class="navbar-nav">
<a class="nav-item nav-link " href="/">Home <span class="sr-only"></span></a>
<a class="nav-item nav-link active" href="visual">Visualization</a>
<a class="nav-item nav-link" href="contact">Contact Us</a>
</div>
{% endblock %}
{% block content %}
<h1 class="display-3 mx-auto bg-secondary text-white text-center py-2"><strong> Stock Performance Visualization</strong></h1>
<div id="select-form">
{% if message %}
<div class="message bg-primary text-white">
{{ message }}
</div>
{% endif %}
<form method="POST">{% csrf_token %}
<div class="form-group mb-4">
<div class="row">
<div class="col-lg">
<select name="stock_name" class="form-select form-select-lg mb-3" id="stock" aria-label=".form-select-lg example">
<option selected="None">Select Stock</option>
<option value="BAJFINANCE.NS">BAJFINANCE -NSE</option>
<option value="RELIANCE.NS">RELIANCE -NSE</option>
<option value="DIVISLAB.NS">DIVISLAB -NSE</option>
<option value="TATASTEEL.NS">TATASTEEL -NSE</option>
<option value="ONGC.NS">ONGC -NSE</option>
<option value="WIPRO.NS">WIPRO -NSE</option>
<option value="TATAMOTORS.NS">TATAMOTORS -NSE</option>
<option value="CIPLA.NS">CIPLA -NSE</option>
<option value="INDUSINDBK.NS">INDUSINDBK -NSE</option>
<option value="POWERGRID.NS">POWERGRID -NSE</option>
<option value="SHREECEM.NS">SHREECEM -NSE</option>
<option value="BRITANNIA.NS">BRITANNIA -NSE</option>
<option value="INFY.NS">INFY -NSE</option>
<option value="LT.NS">LT -NSE</option>
<option value="HINDUNILVR.NS">HINDUNILVR -NSE</option>
<option value="ULTRACEMCO.NS">ULTRACEMCO -NSE</option>
<option value="HINDALCO.NS">HINDALCO -NSE</option>
<option value="BAJAJFINSV.NS">BAJAJFINSV -NSE</option>
<option value="TATACONSUM.NS">TATACONSUM -NSE</option>
<option value="HCLTECH.NS">HCLTECH -NSE</option>
<option value="DRREDDY.NS">DRREDDY -NSE</option>
<option value="NESTLEIND.NS">NESTLEIND -NSE</option>
<option value="TCS.NS">TCS -NSE</option>
<option value="TITAN.NS">TITAN -NSE</option>
<option value="SBIN.NS">SBIN -NSE</option>
<option value="ADANIGREEN.NS">ADANIGREEN -NSE </option>
<!-- -->
<option value="COLPAL.BO">COLPAL -BSE </option>
<option value="HDFCLIFE.BO">HDFCLIFE -BSE </option>
<option value="TECHM.BO">TECHM -BSE </option>
<option value="KOTAKBANK.BO">KOTAKBANK -BSE </option>
<option value="APOLLOHOSP.BO">APOLLOHOSP -BSE </option>
<option value="SAIL.BO">SAIL -BSE </option>
<option value="INDIGO.BO">INDIGO -BSE </option>
<option value="HAVELLS.BO">HAVELLS -BSE </option>
<option value="BRITANNIA.BO">BRITANNIA -BSE </option>
<option value="ICICIBANK.BO">ICICIBANK -BSE </option>
<option value="JSWSTEEL.BO">JSWSTEEL -BSE </option>
<option value="SHREECEM.BO">SHREECEM -BSE </option>
<option value="DABUR.BO">DABUR -BSE </option>
<option value="MARUTI.BO">MARUTI -BSE </option>
<option value="WIPRO.BO">WIPRO -BSE </option>
<option value="NTPC.BO">NTPC -BSE </option>
<option value="SBIN.BO">SBIN -BSE </option>
<option value="HCLTECH.BO">HCLTECH -BSE </option>
<option value="TCS.BO">TCS -BSE </option>
<option value="ITC.BO">ITC -BSE </option>
<option value="RELIANCE.BO">RELIANCE -BSE </option>
<option value="ASIANPAINT.BO">ASIANPAINT -BSE </option>
<option value="NESTLEIND.BO">NESTLEIND -BSE </option>
<option value="TITAN.BO">TITAN -BSE </option>
</select>
</div>
<div class="col-lg">
<select class="form-select form-select-lg mb-3" id="interval" aria-label=".form-select-lg example" name="interval">
<option selected>Select Interval</option>
<option value="1d">1 Day</option>
<option value="5d">5 Days</option>
<option value="1wk">1 Week</option>
<option value="1mo">1 Month</option>
</select>
</div>
</div>
<div class="row">
<div class="col-lg">
<div class="form-group mb-2">
<label class="col-form-label-lg" for="datepicker_from">From Date:</label>
<input type="date" class="form-control form-control-lg" id="datepicker_from" value="Select Starting Date" name="from">
</div>
</div>
<script>
// Get the current date
var currentDate = new Date();
// Subtract 6 months from the current date
var sixMonthsAgo = new Date(currentDate.getFullYear(), currentDate.getMonth() - 6, currentDate.getDate());
// Format the date as "YYYY-MM-DD"
var formattedDate = sixMonthsAgo.toISOString().split('T')[0];
// Set the default value of the input field
document.getElementById('datepicker_from').value = formattedDate;
</script>
<div class="col-lg">
<div class="form-group mb-2">
<label class="col-form-label-lg" for="datepicker_to">To Date:</label>
<input type="date" class="form-control form-control-lg" id="datepicker_to" value="Select Starting Date" name="to">
</div>
</div>
<script>
// Get the current date
var currentDate = new Date();
// Format the date as "YYYY-MM-DD"
var formattedDate = currentDate.toISOString().split('T')[0];
// Set the default value of the input field
document.getElementById('datepicker_to').value = formattedDate;
</script>
</div>
</div>
<button type="submit" class="btn btn-primary" ><strong>Show Chart</strong></button>
</form>
</div>
<div id="chart" class="pt-5">
<div>
{% if graph %}
<div class ="stock-name bg-secondary text-white">
{{ stock }}
</div>
<div class ="bg-secondary text-white text-center fw-bold"> Symbol : {{symbol}} <br>Interval: {{interval}}</div>
{{ graph|safe }}
{% else %}
<div class="text-center" >
<img class="img-fluid" src="{% static 'favicon.png' %}" alt="Photo not loaded">
</div>
{% endif %}
</div>
</div>
<div>
{% if info %}
<div class="card text-white bg-secondary mx-auto p-3 mt-3">
<div class="card-body mx-auto">
<h3 class="card-title">About {{ stock }} :</h3>
<p class="card-text mx-auto" id="text">
{{info}}
</div>
</div>
{% endif %}
</div>
{% endblock %}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("Usage: dotnet run <start-date> <end-date> <events-path>");
return;
}
string startDateString = args[0];
string endDateString = args[1];
string eventsPath = args[2];
if (!DateTime.TryParse(startDateString, out DateTime startDate) || !DateTime.TryParse(endDateString, out DateTime endDate))
{
Console.WriteLine("Invalid date format. Please use ISO 8601 format (yyyy-MM-dd).");
return;
}
// Tarkista, onko annettu polku kelvollinen
if (!File.Exists(eventsPath))
{
Console.Error.WriteLine($"The specified path '{eventsPath}' does not exist.");
return;
}
// Luo EventManager-instanssi
EventManager eventManager = new EventManager();
// Aseta EventManager-luokan EventsPath-ominaisuus
eventManager.EventsPath = eventsPath;
// Testaa tapahtumien lukemista
bool success = eventManager.ReadEvents();
if (success)
{
Console.WriteLine($"Events between {startDate.ToShortDateString()} and {endDate.ToShortDateString()}:");
var eventsBetweenDates = eventManager.Events?.Where(ev => ev.Date >= startDate && ev.Date <= endDate);
if (eventsBetweenDates != null)
{
foreach (var ev in eventsBetweenDates)
{
Console.WriteLine($"{ev.Date}: {ev.Description}");
}
}
}
else
{
Console.WriteLine("Failed to read events.");
}
}
}
// Luokka tapahtumien käsittelyä varten
public class EventManager
{
// Luettelo tapahtumista
public List<Event>? Events { get; private set; }
// Tiedoston polku, josta tapahtumat luetaan
public string? EventsPath { get; set; }
// Konstruktori
public EventManager()
{
Events = new List<Event>();
}
// Metodi tapahtumien lukemiseksi tiedostosta
public bool ReadEvents()
{
if (string.IsNullOrEmpty(EventsPath))
{
Console.Error.WriteLine("EventsPath is not set.");
return false;
}
if (!File.Exists(EventsPath))
{
Console.Error.WriteLine($"File '{EventsPath}' does not exist.");
return false;
}
// Lue tapahtumatiedosto ja käsittele tapahtumat
try
{
using (StreamReader sr = new StreamReader(EventsPath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// Käsittelee tapahtumatiedoston riviä ja lisää tapahtuma listaan
// Oletetaan tässä, että jokainen rivi sisältää tapahtuman päivämäärän ja kuvauksen eroteltuna esim. pilkulla
string[] parts = line.Split(',');
if (parts.Length >= 2)
{
DateTime date;
if (DateTime.TryParse(parts[0], out date))
{
Events?.Add(new Event(date, parts[1]));
}
}
}
}
return true;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Failed to read events: {ex.Message}");
return false;
}
}
// Luokka tapahtumille
public class Event
{
public DateTime Date { get; set; }
public string Description { get; set; }
public Event(DateTime date, string description)
{
Date = date;
Description = description;
}
}
}
|
/**********
** 105. Construct Binary Tree from Preorder and Inorder Traversal (medium)
******************************************************************************/
/**
* recursive
**/
function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
const inorderIdxMap = {};
let preorderIdx = 0;
inorder.forEach((val, i) => inorderIdxMap[val] = i);
const helper = (left, right) => {
if (left > right) return null;
const root = new TreeNode(preorder[preorderIdx++]);
const i = inorderIdxMap[root.val];
root.left = helper(left, i - 1);
root.right = helper(i + 1, right);
return root;
}
return helper(0, preorder.length - 1);
};
|
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
// constructor
Node(int data)
{
this->data = data;
this->next = NULL;
}
// destructor
~Node()
{
int value = this->data;
if (this->next != NULL)
{
delete next;
this->next = NULL;
}
cout << "Memory is free for data :" << value << endl;
}
};
void insertAtHead(Node *&head, int d)
{
// new node create
Node *temp = new Node(d);
temp->next = head;
head = temp;
}
void insertAtTail(Node *&tail, int d)
{
Node *temp = new Node(d);
tail->next = temp;
tail = tail->next;
}
void insertAtPosition(Node *&head, int position, int d, Node *&tail)
{
if (position == 1)
{
insertAtHead(head, d);
return;
}
Node *temp = head;
int count = 1;
while (count < position - 1)
{
temp = temp->next;
count++;
}
// inserting at last position
if (temp->next == NULL)
{
insertAtTail(tail, d);
return;
}
Node *nodeToInsert = new Node(d);
nodeToInsert->next = temp->next;
temp->next = nodeToInsert;
}
void deleteNode(int position, Node *&head, Node *&tail)
{
if (position == 1)
{
// delete first or start node
Node *temp = head;
head = head->next;
temp->next = NULL;
delete temp;
}
else
{
// deleting any middle or last node
Node *curr = head;
Node *prev = NULL;
int cnt = 1;
while (cnt < position)
{
prev = curr;
curr = curr->next;
cnt++;
}
if (curr->next == NULL)
{
tail = prev;
}
prev->next = curr->next;
curr->next = NULL;
delete curr;
}
}
void print(Node *head)
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
int main()
{
Node *node1 = new Node(1);
Node *head = node1;
Node *tail = node1;
insertAtTail(tail, 2);
insertAtTail(tail, 3);
insertAtTail(tail, 4);
insertAtTail(tail, 5);
insertAtTail(tail, 6);
insertAtPosition(head, 7, 99, tail);
deleteNode(7, head, tail);
cout << "tail: " << tail->data << endl;
print(head);
return 0;
}
|
<script setup>
import Navbar from "../../components/Navbar.vue";
import Footer from "../../components/Footer.vue";
import Modal from "../../components/Modal.vue";
</script>
<template>
<Navbar />
<div class="container d-flex justify-content-center">
<div
v-if="spinner"
class="spinner-border text-warning position-absolute top-50"
role="status"
>
<span class="visually-hidden">Loading...</span>
</div>
</div>
<div
v-if="data.role === 'administrator'"
class="position-absoulte start-0 top-0"
>
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
width="40"
height="40"
fill="currentColor"
class="bi bi-list text-light"
viewBox="0 0 16 16"
data-bs-toggle="offcanvas"
data-bs-target="#offcanvasScrolling"
aria-controls="offcanvasScrolling"
>
<path
fill-rule="evenodd"
d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5"
/>
</svg>
</div>
</div>
<div v-if="data.role === 'administrator'">
<div>
<button
class="btn float-end mt-3 me-3 btn-warning"
data-bs-toggle="modal"
data-bs-target="#exampleModal"
data-bs-whatever="@mdo"
>
Dodaj trenera
</button>
<div
class="modal fade"
id="exampleModal"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-dark">
<h5
class="modal-title text-light"
id="exampleModalLabel"
>
Dodaj trenera
</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div class="modal-body bg-dark">
<form @submit.prevent="addCoach()" method="POST">
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Ime:</label
>
<input
type="text"
class="form-control"
id="recipient-name"
v-model="coach.firstName"
required
/>
</div>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Prezime:</label
>
<input
type="text"
class="form-control"
id="recipient-name"
v-model="coach.lastName"
required
/>
</div>
<div class="mb-3">
<label
for="message-text"
class="col-form-label text-light"
>Description:</label
>
<textarea
class="form-control"
id="message-text"
v-model="coach.description"
required
></textarea>
</div>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Email:</label
>
<input
type="email"
class="form-control"
id="recipient-name"
v-model="coach.email"
required
/>
</div>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Godine</label
>
<input
type="text"
class="form-control"
id="recipient-name"
v-model="coach.age"
required
/>
</div>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Kontakt:</label
>
<input
type="text"
class="form-control"
id="recipient-name"
v-model="coach.phone"
required
/>
</div>
<div class="mb-3">
<label for="formFileSm" class="form-label"
>Dodaj sliku
</label>
<input
class="form-control form-control-sm"
id="formFileSm"
type="file"
@change="imageChange"
required
/>
</div>
<button type="submit" class="btn btn-warning w-100">
Dodaj
</button>
</form>
</div>
<div class="modal-footer bg-dark">
<button
type="button"
class="btn btn-secondary w-100"
data-bs-dismiss="modal"
>
Close
</button>
</div>
</div>
</div>
</div>
<h3 class="text-center mt-5 text-light">Svi treneri</h3>
<div class="container mt-5">
<div class="table-responsive">
<table class="table table-striped table-bordered table-dark table-hover">
<thead>
<tr>
<th scope="col" class="text-center" >ID</th>
<th scope="col" class="text-center">Ime</th>
<th scope="col" class="text-center">Prezime</th>
<th scope="col" class="text-center">Opis</th>
<th scope="col" class="text-center">Email</th>
<th scope="col" class="text-center">Godine</th>
<th scope="col" class="text-center">Kontakt</th>
<th scope="col" class="text-center">Izbrisi</th>
<th scope="col" class="text-center">Uredi</th>
</tr>
</thead>
<tbody>
<tr v-for="coach in coaches">
<th scope="row" class="text-center">{{ coach.id }}</th>
<td class="text-center">{{ coach.firstName }}</td>
<td class="text-center">{{ coach.lastName }}</td>
<td class="text-center">{{ coach.description }}</td>
<td class="text-center">{{ coach.email }}</td>
<td class="text-center">{{ coach.age }}</td>
<td class="text-center">{{ coach.phone }}</td>
<td class="text-center">
<button
class="btn btn-sm"
@click="deleteCoach(coach.id)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="25"
height="25"
fill="currentColor"
class="bi bi-person-dash text-danger"
viewBox="0 0 16 16"
>
<path
d="M12.5 16a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7M11 12h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1 0-1m0-7a3 3 0 1 1-6 0 3 3 0 0 1 6 0M8 7a2 2 0 1 0 0-4 2 2 0 0 0 0 4"
/>
<path
d="M8.256 14a4.5 4.5 0 0 1-.229-1.004H3c.001-.246.154-.986.832-1.664C4.484 10.68 5.711 10 8 10q.39 0 .74.025c.226-.341.496-.65.804-.918Q8.844 9.002 8 9c-5 0-6 3-6 4s1 1 1 1z"
/>
</svg>
</button>
</td>
<td class="text-center">
<button
class="btn btn-sm"
data-bs-toggle="modal"
:data-bs-target="'#exampleModall' + coach.id"
data-bs-whatever="@mdo"
@click="updateCoach(coach)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="25"
height="25"
fill="currentColor"
class="bi bi-person-add text-success"
viewBox="0 0 16 16"
>
<path
d="M12.5 16a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7m.5-5v1h1a.5.5 0 0 1 0 1h-1v1a.5.5 0 0 1-1 0v-1h-1a.5.5 0 0 1 0-1h1v-1a.5.5 0 0 1 1 0m-2-6a3 3 0 1 1-6 0 3 3 0 0 1 6 0M8 7a2 2 0 1 0 0-4 2 2 0 0 0 0 4"
/>
<path
d="M8.256 14a4.5 4.5 0 0 1-.229-1.004H3c.001-.246.154-.986.832-1.664C4.484 10.68 5.711 10 8 10q.39 0 .74.025c.226-.341.496-.65.804-.918Q8.844 9.002 8 9c-5 0-6 3-6 4s1 1 1 1z"
/>
</svg>
</button>
<div
class="modal fade"
:id="'exampleModall' + coach.id"
tabindex="-1"
:aria-labelledby="
'exampleModalLabel' + coach.id
"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-dark">
<h1
class="modal-title fs-5"
:id="'#exampleModall' + coach.id"
>
Uredi trenera
</h1>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div class="modal-body bg-dark">
<form
@submit.prevent="
coachUpdate(coach.id)
"
>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Ime:</label
>
<input
type="text"
class="form-control"
id="recipient-name"
v-model="
update.firstName
"
required
/>
</div>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Prezime:</label
>
<input
type="text"
class="form-control"
id="recipient-name"
v-model="update.lastName"
required
/>
</div>
<div class="mb-3">
<label
for="message-text"
class="col-form-label text-light"
>Description:</label
>
<textarea
class="form-control"
id="message-text"
v-model="
update.description
"
required
></textarea>
</div>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Email:</label
>
<input
type="email"
class="form-control"
id="recipient-name"
v-model="update.email"
required
/>
</div>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Godine</label
>
<input
type="text"
class="form-control"
id="recipient-name"
v-model="update.age"
required
/>
</div>
<div class="mb-3">
<label
for="recipient-name"
class="col-form-label text-light"
>Kontakt:</label
>
<input
type="text"
class="form-control"
id="recipient-name"
v-model="update.phone"
required
/>
</div>
<div class="mb-3">
<label
for="formFileSm"
class="form-label"
>Dodaj sliku
</label>
<input
class="form-control form-control-sm"
id="formFileSm"
type="file"
@change="imageUpdateChange"
required
/>
</div>
<button
type="submit"
class="btn btn-warning w-100"
>
Dodaj
</button>
</form>
</div>
<div class="modal-footer bg-dark">
<button
type="button"
class="btn btn-secondary w-100"
data-bs-dismiss="modal"
>
Close
</button>
</div>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="mt-5 d-flex justify-content-center" v-else>
<div v-if="!spinner" class="alert alert-warning text-dark text-center col-12 col-lg-4 col-md-5 col-sm-5" style="background-color: #ffba00;">Nemate pristupa ovoj stranici!</div>
</div>
<Modal />
<Footer />
</template>
<script>
import axios from "axios";
export default {
data() {
return {
coach: {
firstName: "",
lastName: "",
description: "",
email: "",
age: "",
phone: "",
image: "",
},
message: "",
csrfToken: "",
coaches: [],
users: [],
update: {
firstName: "",
lastName: "",
description: "",
email: "",
age: "",
phone: "",
image: "",
},
coachId:null,
data:[],
spinner:true
};
},
created() {
this.getCoaches();
this.fetchCsrfToken();
this.getUser();
this.getData();
},
methods: {
fetchCsrfToken() {
axios
.get("/sanctum/csrf-cookie")
.then((response) => {
this.csrfToken = response.data.csrf_token;
})
.catch((error) => {
console.error(error);
});
},
imageChange(event) {
this.coach.image = event.target.files[0];
},
imageUpdateChange(event){
this.update.image = event.target.files[0];
},
getCoaches() {
axios
.get("/getCoaches")
.then((response) => {
this.coaches = response.data.coaches;
})
.catch((error) => {
console.log(error);
});
},
deleteCoach(id) {
axios
.post(`/deleteCoach/${id}`)
.then((response) => {
this.message = response.data.message;
this.getCoaches();
})
.catch((error) => {
console.log(error);
});
},
addCoach() {
let coach = new FormData();
coach.append("firstName", this.coach.firstName);
coach.append("lastName", this.coach.lastName);
coach.append("description", this.coach.description);
coach.append("email", this.coach.email);
coach.append("age", this.coach.age);
coach.append("phone", this.coach.phone);
coach.append("image", this.coach.image);
axios.defaults.headers.common["X-CSRF-TOKEN"] = this.csrfToken;
axios
.post("/addCoach", coach)
.then((response) => {
this.message = response.data.message;
this.getCoaches();
$("#exampleModal").modal("hide");
this.coach = {
firstName: "",
lastName: "",
description: "",
email: "",
age: "",
contact: "",
image: null,
};
})
.catch((error) => {
if (error.response && error.response.status === 422) {
this.errors = error.response.data.errors;
} else {
console.log(error);
}
});
},
getUser() {
axios
.get("/getUsers")
.then((response) => {
this.users = response.data.users;
console.log(this.users);
})
.catch((error) => {
console.log(error);
});
},
updateCoach(coach) {
this.coachId = coach.id;
this.update.firstName = coach.firstName;
this.update.lastName = coach.lastName;
this.update.description = coach.description;
this.update.email = coach.email;
this.update.age = coach.age;
this.update.phone = coach.phone;
this.update.image = coach.image;
$("#exampleModall" + coach.id).modal("show");
},
coachUpdate(id) {
let updateCoach = new FormData();
updateCoach.append("firstName", this.update.firstName);
updateCoach.append("lastName", this.update.lastName);
updateCoach.append("description", this.update.description);
updateCoach.append("email", this.update.email);
updateCoach.append("age", this.update.age);
updateCoach.append("phone", this.update.phone);
updateCoach.append("image", this.update.image);
axios.defaults.headers.common["X-CSRF-TOKEN"] = this.csrfToken;
axios
.post(`/updateCoach/${id}`, updateCoach)
.then((response) => {
this.message = response.data.message;
const coach = response.data.coach;
const index = this.coaches.findIndex(
(coach) => coach.id === this.radionicaId
);
if (index !== -1) {
this.coaches[index].firstName = coach.firstName;
this.coaches[index].description = coach.description;
this.coaches[index].email = coach.email;
this.coaches[index].age = coach.age;
this.coaches[index].phone = coach.phone;
this.coaches[index].image = coach.image;
}
this.getCoaches();
});
$("#exampleModall" + this.coachId).modal("hide");
},
getData() {
axios
.get("/getUserData")
.then((response) => {
this.data = response.data.user;
console.log(this.data.role);
})
.catch((error) => {
console.log(error);
}).finally(() => {
this.spinner = false;
});
},
},
};
</script>
<style lang="scss" scoped></style>
|
純LISPで関数作ってみるテスト
eqはシンボル同士の評価しかできない、引数にリストが来るとエラー
(label get-first-nonnil (lambda (x) (cond ((atom x) x) ((car x) (car x)) (T (get-first-nonnil (cdr x))))))
(label or (lambda (x . y) (get-first-nonnil (cons x y))))
;↑全引数を評価してからorするので普通のlispのorと違うわヴォケ
;マクロなら構文解析時に展開する必要があるのだが
;(or a b c) を (cond (a a) (b b) (T c))とかにしてしまうとaが真のときaを2回評価することになって違う
;つまりマクロでcondには展開できない・・・(もしaに副作用があった場合困るわけで)
;(たとえばインクリメント系のしょりだったり (label a (++ a)) とか
(label if (lambda (x y z) (cond (x y) ('T z))))
;↑全引数を評価してからifするのでthen式もelse式も先に同時評価されてしまい普通のlispのifと違うわヴォケ
;(if a b c) を (cond (a b) (T c)) に構文解析時にマクロとして展開しないとアカン
;nilならT nil以外ならnil
(label not (lambda (x) (cond (x nil) (t t))))
;リストとか同じ構造ならT 違うならNIL
(label equal (lambda (x y) (cond ((atom x) (cond ((atom y) (eq x y)) (T nil))) ((atom y) nil) ((equal (car x) (car y)) (equal (cdr x) (cdr y))) (T nil))))
;引数をリストにする
(label list (lambda (x . y) (cons x y)))
;リストの最後の値を取る
(label last (lambda (x) (cond ((atom x) 'nil) ((atom (cdr x)) x) ('t (last (cdr x))))))
;全引数を評価したあと最後の引数を返す
(label progn (lambda (x . y) (car (last (cons x y)))))
;progn テスト
;(progn (label a 'k) (label b 's) (cons a b)) ; -> (K . S)
(label caar (lambda (x) (car (car x))))
(label caaar (lambda (x) (car (car (car x)))))
(label caaaar (lambda (x) (car (car (car (car x))))))
(label caaadr (lambda (x) (car (car (car (cdr x))))))
(label caadr (lambda (x) (car (car (cdr x)))))
(label caadar (lambda (x) (car (car (cdr (car x))))))
(label caaddr (lambda (x) (car (car (cdr (cdr x))))))
(label cadr (lambda (x) (car (cdr x))))
(label cadar (lambda (x) (car (cdr (car x)))))
(label cadaar (lambda (x) (car (cdr (car (car x))))))
(label cadadr (lambda (x) (car (cdr (car (cdr x))))))
(label caddr (lambda (x) (car (cdr (cdr x)))))
(label caddar (lambda (x) (car (cdr (cdr (car x))))))
(label cadddr (lambda (x) (car (cdr (cdr (cdr x))))))
(label cdar (lambda (x) (cdr (car x))))
(label cdaar (lambda (x) (cdr (car (car x)))))
(label cdaaar (lambda (x) (cdr (car (car (car x))))))
(label cdaadr (lambda (x) (cdr (car (car (cdr x))))))
(label cdadr (lambda (x) (cdr (car (cdr x)))))
(label cdadar (lambda (x) (cdr (car (cdr (car x))))))
(label cdaddr (lambda (x) (cdr (car (cdr (cdr x))))))
(label cddr (lambda (x) (cdr (cdr x))))
(label cddar (lambda (x) (cdr (cdr (car x)))))
(label cddaar (lambda (x) (cdr (cdr (car (car x))))))
(label cddadr (lambda (x) (cdr (cdr (car (cdr x))))))
(label cdddr (lambda (x) (cdr (cdr (cdr x)))))
(label cdddar (lambda (x) (cdr (cdr (cdr (car x))))))
(label cddddr (lambda (x) (cdr (cdr (cdr (cdr x))))))
|
import { BaseModel, IBaseModel } from './BaseModel';
import { Book } from './Book';
import { supabase } from '../supabaseClient';
interface IContentTag extends IBaseModel {
name: string;
type: string;
description: string;
author_id: string;
books: { book: Book; position: number }[];
}
export class ContentTag extends BaseModel implements IContentTag {
name: string;
type: string;
description: string;
author_id: string;
books: { book: Book; position: number }[];
constructor(data: IContentTag) {
super(data);
this.name = data.name;
this.type = data.type;
this.description = data.description;
this.author_id = data.author_id;
this.books = data.books || [];
}
static fromJson(json: Record<string, any>): ContentTag {
return new ContentTag({
...BaseModel.fromJson(json),
name: json.name,
type: json.type,
description: json.description,
author_id: json.author_id,
books: json.books?.map((item: any) => ({
book: Book.fromJson(item.book),
position: item.position
}))
});
}
toJson(): Record<string, any> {
return {
...super.toJson(),
name: this.name,
type: this.type,
description: this.description,
author_id: this.author_id,
books: this.books.map((item) => ({
book: item.book.toJson(),
position: item.position
}))
};
}
async create(): Promise<boolean> {
try {
// Insert the content tag into the content_tags table
const { data: contentTagData, error: contentTagError } = await supabase
.from('content_tags')
.insert([
{
...super.toJson(),
name: this.name,
type: this.type,
description: this.description,
author_id: this.author_id
}
])
.select()
.single();
if (contentTagError) {
throw contentTagError;
}
this.id = contentTagData.id;
// Insert books into the book_contenttags table
const bookInsertPromises = this.books.map(async (item) => {
const bookData = {
contenttag_id: this.id,
book_id: item.book.id,
position: item.position
};
const { error } = await supabase
.from('book_contenttags')
.insert([bookData]);
if (error) {
throw error;
}
});
await Promise.all(bookInsertPromises);
return true;
} catch (error) {
console.error(error);
return false;
}
}
async addBook(book: Book, position: number): Promise<boolean> {
try {
this.books.push({ book, position });
// Update the content tag in the database
const bookData = {
contenttag_id: this.id,
book_id: book.id,
position: position
};
const { data, error } = await supabase
.from('book_contenttags')
.insert([bookData])
.single();
if (error) {
throw error;
}
return true;
} catch (error) {
console.error(error);
return false;
}
}
async update(): Promise<boolean> {
try {
// Update the content tag details in the database
const { data, error } = await supabase
.from('content_tags')
.update({
name: this.name,
description: this.description,
// Update other fields as needed
updated_at: new Date().toISOString()
})
.match({ id: this.id });
if (error) {
throw error;
}
// Update or insert new book entries in the book_contenttags table
const bookInsertPromises = this.books.map(async (item) => {
// Check if the book entry already exists in the database
const { data: existingData, error: existingError } = await supabase
.from('book_contenttags')
.select()
.eq('contenttag_id', this.id)
.eq('book_id', item.book.id)
.single();
if (existingData) {
// If the book entry exists, update its position
await supabase
.from('book_contenttags')
.update({ position: item.position })
.match({ contenttag_id: this.id, book_id: item.book.id });
} else {
// If the book entry does not exist, insert a new entry
await supabase.from('book_contenttags').insert([
{
contenttag_id: this.id,
book_id: item.book.id,
position: item.position
}
]);
}
});
await Promise.all(bookInsertPromises);
return true;
} catch (error) {
console.error(error);
return false;
}
}
async delete(): Promise<boolean> {
try {
// Delete associated records from the book_contenttags table
const { error: bookError } = await supabase
.from('book_contenttags')
.delete()
.match({ contenttag_id: this.id });
if (bookError) {
throw bookError;
}
// Delete the content tag from the content_tags table
const { error: contentTagError } = await supabase
.from('content_tags')
.delete()
.match({ id: this.id });
if (contentTagError) {
throw contentTagError;
}
return true;
} catch (error) {
console.error(error);
return false;
}
}
private async getBookById(bookId: string): Promise<Book | null> {
try {
// Fetch the book by its ID from the database
const { data, error } = await supabase
.from('books')
.select()
.eq('id', bookId)
.single();
if (error) {
throw error;
}
return data ? Book.fromJson(data) : null;
} catch (error) {
console.error(error);
return null;
}
}
async getBooksById(): Promise<void> {
try {
// Fetch books associated with the content tag ID from the database
const { data, error } = await supabase
.from('book_contenttags')
.select('book_id, position')
.eq('contenttag_id', this.id);
if (error) {
throw error;
}
// Process the retrieved data and assign it to the books field
const booksData = data ?? [];
this.books = await Promise.all(
booksData.map(async (item: any) => ({
book: (await this.getBookById(item.book_id))!,
position: item.position
}))
);
} catch (error) {
console.error(error);
}
}
}
|
<?xml version="1.0" encoding="UTF-8"?>
<p>We formulated two predictive models to generate estimates of growth for the
<italic>i</italic>th cluster
<italic>C
<sub>i</sub>
</italic>, which we denote respectively as the null model and the weighted model. The null model requires less information by postulating that each cluster is expected to grow in proportion to its current size, prior to the addition of new cases, as a fraction of the entire population of known cases. For example, a cluster that comprises half of all known cases is predicted to accumulate half of new cases that are adjacent to any cluster. Expressed as a Poisson regression model, the expected growth of
<italic>C
<sub>i</sub>
</italic> given total cluster growth
<italic>R</italic> is given by:
<disp-formula id="E1">
<label>(1)</label>
<math id="M1">
<mrow>
<mi mathvariant="bold">E</mi>
<mrow>
<mo>(</mo>
<mrow>
<msub>
<mrow>
<mi>R</mi>
</mrow>
<mn>0</mn>
</msub>
<mo stretchy="false">(</mo>
<msub>
<mrow>
<mi>C</mi>
</mrow>
<mi>i</mi>
</msub>
<mo stretchy="false">)</mo>
</mrow>
<mo>)</mo>
</mrow>
<mo>=</mo>
<mtext>exp</mtext>
<mo> </mo>
<mrow>
<mo>(</mo>
<mrow>
<mfrac>
<mrow>
<mo stretchy="false">|</mo>
<msub>
<mrow>
<mi>C</mi>
</mrow>
<mi>i</mi>
</msub>
<mo stretchy="false">|</mo>
</mrow>
<mrow>
<mo stretchy="false">|</mo>
<msup>
<mrow>
<mi>V</mi>
</mrow>
<mi>c</mi>
</msup>
<mo stretchy="false">|</mo>
</mrow>
</mfrac>
<mi>R</mi>
</mrow>
<mo>)</mo>
</mrow>
<mo>.</mo>
</mrow>
</math>
</disp-formula>where we use boldface
<bold>E</bold> to denote the expectation (and distinguish it from our edge set notation
<italic>E</italic>), and
<italic>R</italic>
<sub>0</sub> is given the subscript 0 to indicate it is the predicted growth under the null model. Thus the null model does not use any individual-level attributes to predict cluster growth—it is a naive model that assumes that the allocation of cluster-adjacent new cases in
<italic>R</italic> is not influenced by any characteristics of those clusters other than the ‘space’ they occupy. In contrast, the weighted model assigns individual-level weights
<italic>w</italic>(
<italic>v</italic>) to every vertex in
<inline-formula id="IE25">
<math id="IM25">
<mrow>
<mi>v</mi>
<mo>∈</mo>
<msub>
<mrow>
<mi>C</mi>
</mrow>
<mi>i</mi>
</msub>
</mrow>
</math>
</inline-formula>. Expressed as a Poisson regression model, the expected growth of cluster
<italic>C
<sub>i</sub>
</italic> under the weighted model is written:
<disp-formula id="E2">
<label>(2)</label>
<math id="M2">
<mrow>
<mi mathvariant="bold">E</mi>
<mo stretchy="false">(</mo>
<mi>R</mi>
<mo stretchy="false">(</mo>
<msub>
<mrow>
<mi>C</mi>
</mrow>
<mi>i</mi>
</msub>
<mo stretchy="false">)</mo>
<mo stretchy="false">)</mo>
<mo>=</mo>
<mtext>exp</mtext>
<mo> </mo>
<mrow>
<mo>(</mo>
<mrow>
<mo>α</mo>
<mo>+</mo>
<mo>β</mo>
<munder>
<mo>∑</mo>
<mrow>
<mi>v</mi>
<mo>∈</mo>
<msub>
<mrow>
<mi>C</mi>
</mrow>
<mi>i</mi>
</msub>
</mrow>
</munder>
<mrow>
<mi>w</mi>
<mo stretchy="false">(</mo>
<mi>v</mi>
<mo stretchy="false">)</mo>
</mrow>
</mrow>
<mo>)</mo>
</mrow>
</mrow>
</math>
</disp-formula>where
<italic>α</italic> and
<italic>β</italic> are parameters to be estimated by regression. Note that
<xref ref-type="disp-formula" rid="E2">Equation (2)</xref> reduces to (1) when
<italic>w</italic>(
<italic>v</italic>) = 1 for all
<inline-formula id="IE26">
<math id="IM26">
<mrow>
<mi>v</mi>
<mo>∈</mo>
<msub>
<mrow>
<mi>C</mi>
</mrow>
<mi>i</mi>
</msub>
</mrow>
</math>
</inline-formula>,
<italic>α</italic> = 0 and
<inline-formula id="IE27">
<math id="IM27">
<mrow>
<mo>β</mo>
<mo>=</mo>
<mi>R</mi>
<mo>/</mo>
<mo stretchy="false">|</mo>
<msup>
<mrow>
<mi>V</mi>
</mrow>
<mi>c</mi>
</msup>
<mo stretchy="false">|</mo>
</mrow>
</math>
</inline-formula>. There are two advantages to using individual-level weights in
<xref ref-type="disp-formula" rid="E2">Equation (2)</xref> rather than cluster-level weights: first, individual-level weights are independent of clustering thresholds, so it is sufficient to calculate weights one time only; second, individual-level weights confer a greater degree of precision for measuring effects on edge densities that would become averaged out in clusters.
</p>
|
// We require the Hardhat Runtime Environment explicitly here. This is optional
// but useful for running the script in a standalone fashion through `node <script>`.
//
// When running the script with `npx hardhat run <script>` you'll find the Hardhat
// Runtime Environment's members available in the global scope.
import { ethers } from "hardhat";
async function main() {
// Hardhat always runs the compile task when running scripts with its command
// line interface.
//
// If this script is run directly using `node` you may want to call compile
// manually to make sure everything is compiled
// await hre.run('compile');
// We get the contract to deploy
const UBIPolygonChildTunnel = await ethers.getContractFactory("UBIPolygonChildTunnel");
const child = await UBIPolygonChildTunnel.attach(process.env.FX_CHILD_TUNNEL!);
console.log("Setting root tunnel...")
await child.setFxRootTunnel(process.env.FX_ROOT_TUNNEL!);
console.log("Setting UBI address...")
await child.setUBI(process.env.UBI_L2!);
console.log("Child Tunnel Setup completed");
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
|
package bot
import (
"fmt"
"log"
"log/slog"
"github.com/diamondburned/arikawa/v3/api"
"github.com/diamondburned/arikawa/v3/discord"
)
// started asynchronously
func (b *Bot) logWriter() {
for {
select {
case logEntry := <-b.l.Consume():
lvl := ""
switch logEntry.Level {
case slog.LevelError:
lvl = " [ERROR]: "
case slog.LevelWarn:
lvl = " [WARN]: "
case slog.LevelInfo:
lvl = " [INFO]: "
case slog.LevelDebug:
lvl = " [DEBUG]: "
}
msg := fmt.Sprintf("%s%s",
lvl,
logEntry.Message,
)
log.Println(msg)
_, err := b.state.SendMessageComplex(b.channelID, api.SendMessageData{
Content: msg,
Embeds: logEntry.Embedding,
Flags: discord.SuppressEmbeds,
Files: logEntry.Files,
})
if err != nil {
b.l.Errorf("failed to send log message to %s: %v", b.channelID, err)
continue
}
case <-b.ctx.Done():
log.Println("closed async goroutine for log writer")
return
}
}
}
|
"use client";
import Image from "next/image";
import { useRouter } from "next/navigation";
import React from "react";
import classes from "./footer.module.css";
const Footer = () => {
const router = useRouter();
return (
<footer className={classes["footer"]}>
<div className={classes["container"]}>
<div className={classes["footer-container"]}>
<div className={classes["footer-container-image"]}>
<Image src="/svg/layout/footer/logo.svg" alt="logo" width={170} height={126}/>
<div className={classes["footer-social"]}>
<div className={classes["footer-social-element"]}>
<Image
src="/svg/layout/social-icons/twitter.svg"
alt="twitter-icon"
width="24"
height="20"
/>
</div>
<div className={classes["footer-social-element"]}>
<Image
src="/svg/layout/social-icons/facebook.svg"
alt="facebook-icon"
width="24"
height="24"
/>
</div>
<div className={classes["footer-social-element"]}>
<Image
src="/svg/layout/social-icons/social.svg"
alt="social-icon"
width="24"
height="20"
/>
</div>
<div className={classes["footer-social-element"]}>
<Image
src="/svg/layout/social-icons/insta.svg"
alt="insta-icon"
width="24"
height="24"
/>
</div>
<div className={classes["footer-social-element"]}>
<Image
src="/svg/layout/social-icons/ticktok.svg"
alt="tiktok-icon"
width="24"
height="24"
/>
</div>
<div className={classes["footer-social-element"]}>
<Image
src="/svg/layout/social-icons/telegram.svg"
alt="telegram-icon"
width="24"
height="24"
/>
</div>
</div>
</div>
<div className={classes["footer-container-disclaimer"]}>
<h3>Disclaimer</h3>
<p>
AJ Sports merely links/embeds content uploaded to popular media
hosting websites such Vimeo.com, Dailymotion.com, Youtube.com,
twitch.tv, reddit.com, etc. AJSports does not host any audiovisual
content itself and has no ability to modify such content. We thus
cannot accept any liability for the content transmitted by others
as we are not affiliated nor endorsed by the external content. All
content is copyright of their respective owners.
</p>
<p className={classes["contact-email"]}>Email: info@ajsports.ch</p>
<div className={classes["footer-actions-mobile"]}>
<button className={classes["protected-button"]}>PROTECTED</button>
<button className={classes["dmca-button"]}>DMCA</button>
</div>
</div>
<div className={classes["footer-container-second"]}>
<div className={classes["footer-container-links"]}>
<h4 className={classes["footer-container-links-heading"]}>
Quick Menus
</h4>
<ul
style={{ listStyle: "none" }}
className={classes["footer-container-links-list"]}
>
<li
onClick={() => {
router.push("/");
}}
className={classes["footer-container-links-list-item"]}
>
About Us
</li>
<li
onClick={() => {
router.push("/contact-us");
}}
className={classes["footer-container-links-list-item"]}
>
Contact Us
</li>
<li
onClick={() => {
router.push("/donate");
}}
className={classes["footer-container-links-list-item"]}
>
Donate
</li>
<li
onClick={() => {
router.push("/give-away");
}}
className={classes["footer-container-links-list-item"]}
>
Giveaways
</li>
</ul>
</div>
<div className={classes["footer-container-links"]}>
<h4
onClick={() => {
router.push("/");
}}
className={classes["footer-container-links-heading"]}
>
Statistics
</h4>
<ul
style={{ listStyle: "none" }}
className={classes["footer-container-links-list"]}
>
<li className={classes["footer-container-links-list-item"]}>
Premier League
</li>
<li className={classes["footer-container-links-list-item"]}>
Champions League
</li>
<li className={classes["footer-container-links-list-item"]}>
Ligue 1
</li>
<li className={classes["footer-container-links-list-item"]}>
La Liga
</li>
</ul>
</div>
<div className={classes["footer-container-links"]}>
<h4
onClick={() => {
router.push("/");
}}
className={classes["footer-container-links-heading"]}
>
Sports
</h4>
<nav className={classes["footer-container-links-list"]}>
<li className={classes["footer-container-links-list-item"]}>
NFL
</li>
<li className={classes["footer-container-links-list-item"]}>
Basketball
</li>
<li className={classes["footer-container-links-list-item"]}>
Football
</li>
<li className={classes["footer-container-links-list-item"]}>
Boxing
</li>
</nav>
</div>
</div>
</div>
<div className={classes["footer-bottom"]}>
<div className={classes["footer-actions"]}>
<p className={classes["protected-button"]}>PROTECTED</p>
<p
onClick={() => {
router.push("/DMCA");
}}
className={classes["dmca-button"]}
>
DMCA
</p>
</div>
<div className={classes["copy-write"]}>
<div className={classes["mobile-news-letter"]}>
<input
className={classes["mobile-news-letter-input"]}
type="text"
placeholder=" Enter email for newsletter"
/>
<button className={classes["mobile-news-letter-button"]}>
Subscribe
</button>
</div>
<p className={classes["copy-write-para"]}>
© 2023 AJ Sports, Inc. All rights reserved
</p>
<div className={classes["copy-write-links"]}>
<p
onClick={() => {
router.push("DMCA");
}}
>
DMCA
</p>
<span>-</span>
<p
onClick={() => {
router.push("privacy-policy");
}}
>
Privacy Policy
</p>
<span>-</span>
<p
onClick={() => {
router.push("FAQ");
}}
>
F.A.Q
</p>
</div>
<div className={classes["copy-write-social"]}>
<Image
src="/svg/layout/footer/facebook.svg"
alt="facebook"
width="18"
height="18"
/>
<Image
src="/svg/layout/footer/twitter.svg"
alt="facebook"
width="18"
height="18"
/>
<Image
src="/svg/layout/footer/insta.svg"
alt="insta"
width="18"
height="18"
/>
<Image
src="/svg/layout/footer/telegram.svg"
alt="telegram"
width="18"
height="18"
/>
</div>
</div>
</div>
</div>
</footer>
);
};
export default Footer;
|
import { configureStore } from "@reduxjs/toolkit";
import { combineReducers } from "redux";
import {
FLUSH,
PAUSE,
PERSIST,
persistReducer,
persistStore,
PURGE,
REGISTER,
REHYDRATE,
} from "redux-persist";
import AsyncStorage from "@react-native-async-storage/async-storage";
// import storage from 'redux-persist/lib/storage'
import childSlice from "./childSlice";
import childrenListSlice from "./childrenListSlice";
import childManageSlice from "./childManageSlice";
const persistConfig = {
key: "root",
version: 1,
storage: AsyncStorage,
whitelist: ['childrenList']
};
const rootReducer = combineReducers({
currentChild: childSlice,
childrenList: childrenListSlice,
childManage: childManageSlice,
});
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});
export const persistor = persistStore(store);
// const store = configureStore({
// reducer: {
// currentChild: childSlice,
// childrenList: childrenListSlice,
// childManage:childManageSlice,
// },
// });
export default store;
|
- Etiquetas HTML
- Se usan para represantar los titulos de la pagina
<h1>Se utiliza una vez</h1>
<h2> sub titulos</h2>
<h3> Para el encabezado</h3>
<p> Para textos genericos</p>
<a href="">Enlaces</a>
<span>Sirve para marcar texto dentro de un p o h</span>
<form action="">Formulario
<fieldset>Etiqueta especial que se utiliza para los campos del Formulario
<legend>Contactonos llenando todos los campos</legend>
<!-- Legend es el titulo del formulario -->
<label>Nombre</label>
<!-- Existen varios tipos de Type.
text/ tel es numeral/ checkbox / radio / email / number placeholder texto de indicaion-->
<input type="text" placeholder="Nombre">
<textarea ">Para rellenar un mensaje</textarea>
<button type="submit"> Un boton</button>
<div>
utlizar solo para separar cotenido dentro
</div>
</fieldset>
</form>
- Estructura del contenido
<head>Contiene el meta, link stylos ccs y js
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diseñeador Freelancer</title>
<link rel="preload" href="css.css" as="style"> Ayuda al performance de la pagina
<link rel="stylesheet" href="css.css">
</head>
<Header>Titulo de presentacion</Header>
<nav>Barra de navegacion</nav>
<main>Cuerpo central de la Informacion</main>
<section>Son bloques de informacion puede ir adentro del main o otro lado mienestra contenga un heading h2345</section>
<article>Son notificias que van de bajol main</article>
<aside>Informacion lateral del main</aside>
<footer>Pie de pagina</footer>
<div>es una forma de agrupar otros bloques dentro de cualquier etiqueta</div>
|
require "time"
require "io"
{% if flag?(:without_openssl) %}
require "crystal/digest/sha1"
require "crystal/digest/md5"
{% else %}
require "digest/sha1"
require "digest/md5"
{% end %}
# Represents a UUID (Universally Unique IDentifier).
#
# NOTE: To use `UUID`, you must explicitly import it with `require "uuid"`
struct UUID
include Comparable(UUID)
# Variants with 16 bytes.
enum Variant
# Unknown (i.e. custom, your own).
Unknown
# Reserved by the NCS for backward compatibility.
NCS
# Reserved for RFC 4122 Specification (default).
RFC4122
# Reserved by Microsoft for backward compatibility.
Microsoft
# Reserved for future expansion.
Future
end
# RFC4122 UUID versions.
enum Version
# Unknown version.
Unknown = 0
# Date-time and NodeID address.
V1 = 1
# DCE security.
V2 = 2
# MD5 hash and namespace.
V3 = 3
# Random.
V4 = 4
# SHA1 hash and namespace.
V5 = 5
end
# A Domain represents a Version 2 domain (DCE security).
enum Domain
Person = 0
Group = 1
Org = 2
end
# MAC address to be used as NodeID.
alias MAC = UInt8[6]
# Namespaces as defined per in the RFC 4122 Appendix C.
#
# They are used with the functions `v3` amd `v5` to generate
# a `UUID` based on a `name`.
module Namespace
# A UUID is generated using the provided `name`, which is assumed to be a fully qualified domain name.
DNS = UUID.new("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
# A UUID is generated using the provided `name`, which is assumed to be a URL.
URL = UUID.new("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
# A UUID is generated using the provided `name`, which is assumed to be an ISO OID.
OID = UUID.new("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
# A UUID is generated using the provided `name`, which is assumed to be a X.500 DN in DER or a text output format.
X500 = UUID.new("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
end
@bytes : StaticArray(UInt8, 16)
# Generates UUID from *bytes*, applying *version* and *variant* to the UUID if
# present.
def initialize(@bytes : StaticArray(UInt8, 16), variant : UUID::Variant? = nil, version : UUID::Version? = nil)
case variant
when nil
# do nothing
when Variant::NCS
@bytes[8] = (@bytes[8] & 0x7f)
when Variant::RFC4122
@bytes[8] = (@bytes[8] & 0x3f) | 0x80
when Variant::Microsoft
@bytes[8] = (@bytes[8] & 0x1f) | 0xc0
when Variant::Future
@bytes[8] = (@bytes[8] & 0x1f) | 0xe0
else
raise ArgumentError.new "Can't set unknown variant"
end
if version
raise ArgumentError.new "Can't set unknown version" if version.unknown?
@bytes[6] = (@bytes[6] & 0xf) | (version.to_u8 << 4)
end
end
# Creates UUID from 16-bytes slice. Raises if *slice* isn't 16 bytes long. See
# `#initialize` for *variant* and *version*.
def self.new(slice : Slice(UInt8), variant : Variant? = nil, version : Version? = nil)
raise ArgumentError.new "Invalid bytes length #{slice.size}, expected 16" unless slice.size == 16
bytes = uninitialized UInt8[16]
slice.copy_to(bytes.to_slice)
new(bytes, variant, version)
end
# Creates another `UUID` which is a copy of *uuid*, but allows overriding
# *variant* or *version*.
def self.new(uuid : UUID, variant : Variant? = nil, version : Version? = nil)
new(uuid.bytes, variant, version)
end
# Creates new UUID by decoding `value` string from hyphenated (ie `ba714f86-cac6-42c7-8956-bcf5105e1b81`),
# hexstring (ie `89370a4ab66440c8add39e06f2bb6af6`) or URN (ie `urn:uuid:3f9eaf9e-cdb0-45cc-8ecb-0e5b2bfb0c20`)
# format, raising an `ArgumentError` if the string does not match any of these formats.
def self.new(value : String, variant : Variant? = nil, version : Version? = nil)
bytes = uninitialized UInt8[16]
case value.size
when 36 # Hyphenated
{8, 13, 18, 23}.each do |offset|
if value[offset] != '-'
raise ArgumentError.new "Invalid UUID string format, expected hyphen at char #{offset}"
end
end
{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34}.each_with_index do |offset, i|
bytes[i] = hex_pair_at value, offset
end
when 32 # Hexstring
16.times do |i|
bytes[i] = hex_pair_at value, i * 2
end
when 45 # URN
raise ArgumentError.new "Invalid URN UUID format, expected string starting with \"urn:uuid:\"" unless value.starts_with? "urn:uuid:"
{9, 11, 13, 15, 18, 20, 23, 25, 28, 30, 33, 35, 37, 39, 41, 43}.each_with_index do |offset, i|
bytes[i] = hex_pair_at value, offset
end
else
raise ArgumentError.new "Invalid string length #{value.size} for UUID, expected 32 (hexstring), 36 (hyphenated) or 45 (urn)"
end
new(bytes, variant, version)
end
# Creates new UUID by decoding `value` string from hyphenated (ie `ba714f86-cac6-42c7-8956-bcf5105e1b81`),
# hexstring (ie `89370a4ab66440c8add39e06f2bb6af6`) or URN (ie `urn:uuid:3f9eaf9e-cdb0-45cc-8ecb-0e5b2bfb0c20`)
# format, returning `nil` if the string does not match any of these formats.
def self.parse?(value : String, variant : Variant? = nil, version : Version? = nil) : UUID?
bytes = uninitialized UInt8[16]
case value.size
when 36 # Hyphenated
{8, 13, 18, 23}.each do |offset|
return if value[offset] != '-'
end
{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34}.each_with_index do |offset, i|
if hex = hex_pair_at? value, offset
bytes[i] = hex
else
return
end
end
when 32 # Hexstring
16.times do |i|
if hex = hex_pair_at? value, i * 2
bytes[i] = hex
else
return
end
end
when 45 # URN
return unless value.starts_with? "urn:uuid:"
{9, 11, 13, 15, 18, 20, 23, 25, 28, 30, 33, 35, 37, 39, 41, 43}.each_with_index do |offset, i|
if hex = hex_pair_at? value, offset
bytes[i] = hex
else
return
end
end
else
return
end
new(bytes, variant, version)
end
# Raises `ArgumentError` if string `value` at index `i` doesn't contain hex
# digit followed by another hex digit.
private def self.hex_pair_at(value : String, i) : UInt8
hex_pair_at?(value, i) || raise ArgumentError.new "Invalid hex character at position #{i * 2} or #{i * 2 + 1}, expected '0' to '9', 'a' to 'f' or 'A' to 'F'"
end
# Parses 2 hex digits from `value` at index `i` and `i + 1`, returning `nil`
# if one or both are not actually hex digits.
private def self.hex_pair_at?(value : String, i) : UInt8?
if (ch1 = value[i].to_u8?(16)) && (ch2 = value[i + 1].to_u8?(16))
ch1 * 16 + ch2
end
end
# Generates RFC 4122 v4 UUID.
#
# It is strongly recommended to use a cryptographically random source for
# *random*, such as `Random::Secure`.
def self.random(random : Random = Random::Secure, variant : Variant = :rfc4122, version : Version = :v4) : self
new_bytes = uninitialized UInt8[16]
random.random_bytes(new_bytes.to_slice)
new(new_bytes, variant, version)
end
# Generates RFC 4122 v1 UUID.
#
# The traditional method for generating a `node_id` involves using the machine’s MAC address.
# However, this approach is only effective if there is only one process running on the machine
# and if privacy is not a concern. In modern languages, the default is to prioritize security
# and privacy. Therefore, a pseudo-random `node_id` is generated as described in section 4.5 of
# the RFC.
#
# The sequence number `clock_seq` is used to generate the UUID. This number should be
# monotonically increasing, with only 14 bits of the clock sequence being used effectively.
# The clock sequence should be stored in a stable location, such as a file. If it is not
# stored, a random value is used by default. If not provided the current time milliseconds
# are used. In case the traditional MAC address based approach should be taken the
# `node_id` can be provided. Otherwise secure random is used.
def self.v1(*, clock_seq : UInt16? = nil, node_id : MAC? = nil) : self
tl = Time.local
now = (tl.to_unix_ns / 100).to_u64 + 122192928000000000
seq = ((clock_seq || (tl.nanosecond/1000000).to_u16) & 0x3fff) | 0x8000
time_low = UInt32.new(now & 0xffffffff)
time_mid = UInt16.new((now >> 32) & 0xffff)
time_hi = UInt16.new((now >> 48) & 0x0fff)
time_hi |= 0x1000 # Version 1
uuid = uninitialized UInt8[16]
IO::ByteFormat::BigEndian.encode(time_low, uuid.to_slice[0..3])
IO::ByteFormat::BigEndian.encode(time_mid, uuid.to_slice[4..5])
IO::ByteFormat::BigEndian.encode(time_hi, uuid.to_slice[6..7])
IO::ByteFormat::BigEndian.encode(seq, uuid.to_slice[8..9])
if node_id
6.times do |i|
uuid.to_slice[10 + i] = node_id[i]
end
else
Random::Secure.random_bytes(uuid.to_slice[10..15])
# set multicast bit as recommended per section 4.5 of the RFC 4122 spec
# to not conflict with real MAC addresses
uuid[10] |= 0x01_u8
end
new(uuid, version: UUID::Version::V1, variant: UUID::Variant::RFC4122)
end
# Generates RFC 4122 v2 UUID.
#
# Version 2 UUIDs are generated using the current time, the local machine’s MAC address,
# and the local user or group ID. However, they are not widely used due to their limitations.
# For a given domain/id pair, the same token may be returned for a duration of up to 7 minutes
# and 10 seconds.
#
# The `id` depends on the `domain`, for the `Domain::Person` usually the local user id (uid) is
# used, for `Domain::Group` usually the local group id (gid) is used. In case the traditional
# MAC address based approach should be taken the `node_id` can be provided. Otherwise secure
# random is used.
def self.v2(domain : Domain, id : UInt32, node_id : MAC? = nil) : self
uuid = v1(node_id: node_id).bytes
uuid[6] = (uuid[6] & 0x0f) | 0x20 # Version 2
uuid[9] = domain.to_u8
IO::ByteFormat::BigEndian.encode(id, uuid.to_slice[0..3])
new(uuid, version: UUID::Version::V2, variant: UUID::Variant::RFC4122)
end
# Generates RFC 4122 v3 UUID using the `name` to generate the UUID, it can be a string of any size.
# The `namespace` specifies the type of the name, usually one of `Namespace`.
def self.v3(name : String, namespace : UUID) : self
klass = {% if flag?(:without_openssl) %}::Crystal::Digest::MD5{% else %}::Digest::MD5{% end %}
hash = klass.digest do |ctx|
ctx.update namespace.bytes
ctx.update name
end
new(hash[0...16], version: UUID::Version::V3, variant: UUID::Variant::RFC4122)
end
# Generates RFC 4122 v4 UUID.
#
# It is strongly recommended to use a cryptographically random source for
# *random*, such as `Random::Secure`.
def self.v4(random r : Random = Random::Secure) : self
random(r)
end
# Generates RFC 4122 v5 UUID using the `name` to generate the UUID, it can be a string of any size.
# The `namespace` specifies the type of the name, usually one of `Namespace`.
def self.v5(name : String, namespace : UUID) : self
klass = {% if flag?(:without_openssl) %}::Crystal::Digest::SHA1{% else %}::Digest::SHA1{% end %}
hash = klass.digest do |ctx|
ctx.update namespace.bytes
ctx.update name
end
new(hash[0...16], version: UUID::Version::V5, variant: UUID::Variant::RFC4122)
end
{% for name in %w(DNS URL OID X500).map(&.id) %}
# Generates RFC 4122 v3 UUID with the `Namespace::{{ name }}`.
#
# * `name`: The name used to generate the UUID, it can be a string of any size.
def self.v3_{{ name.downcase }}(name : String)
v3(name, Namespace::{{ name }})
end
# Generates RFC 4122 v5 UUID with the `Namespace::{{ name }}`.
#
# * `name`: The name used to generate the UUID, it can be a string of any size.
def self.v5_{{ name.downcase }}(name : String)
v5(name, Namespace::{{ name }})
end
{% end %}
# Generates an empty UUID.
#
# ```
# UUID.empty # => UUID(00000000-0000-4000-0000-000000000000)
# ```
def self.empty : self
new(StaticArray(UInt8, 16).new(0_u8), UUID::Variant::NCS, UUID::Version::V4)
end
# Returns UUID variant based on the [RFC4122 format](https://datatracker.ietf.org/doc/html/rfc4122#section-4.1).
# See also `#version`
#
# ```
# require "uuid"
#
# UUID.new(Slice.new(16, 0_u8), variant: UUID::Variant::NCS).variant # => UUID::Variant::NCS
# UUID.new(Slice.new(16, 0_u8), variant: UUID::Variant::RFC4122).variant # => UUID::Variant::RFC4122
# UUID.new(Slice.new(16, 0_u8), variant: UUID::Variant::Microsoft).variant # => UUID::Variant::Microsoft
# UUID.new(Slice.new(16, 0_u8), variant: UUID::Variant::Future).variant # => UUID::Variant::Future
# ```
def variant : UUID::Variant
case
when @bytes[8] & 0x80 == 0x00
Variant::NCS
when @bytes[8] & 0xc0 == 0x80
Variant::RFC4122
when @bytes[8] & 0xe0 == 0xc0
Variant::Microsoft
when @bytes[8] & 0xe0 == 0xe0
Variant::Future
else
Variant::Unknown
end
end
# Returns version based on [RFC4122 format](https://datatracker.ietf.org/doc/html/rfc4122#section-4.1).
# See also `#variant`.
#
# ```
# require "uuid"
#
# UUID.new(Slice.new(16, 0_u8), version: UUID::Version::V1).version # => UUID::Version::V1
# UUID.new(Slice.new(16, 0_u8), version: UUID::Version::V2).version # => UUID::Version::V2
# UUID.new(Slice.new(16, 0_u8), version: UUID::Version::V3).version # => UUID::Version::V3
# UUID.new(Slice.new(16, 0_u8), version: UUID::Version::V4).version # => UUID::Version::V4
# UUID.new(Slice.new(16, 0_u8), version: UUID::Version::V5).version # => UUID::Version::V5
# ```
def version : UUID::Version
case @bytes[6] >> 4
when 1 then Version::V1
when 2 then Version::V2
when 3 then Version::V3
when 4 then Version::V4
when 5 then Version::V5
else Version::Unknown
end
end
# Returns the binary representation of the UUID.
def bytes : StaticArray(UInt8, 16)
@bytes.dup
end
# Returns unsafe pointer to 16-bytes.
def to_unsafe
@bytes.to_unsafe
end
def_equals_and_hash @bytes
# Convert to `String` in literal format.
def inspect(io : IO) : Nil
io << "UUID("
to_s(io)
io << ')'
end
def to_s(io : IO) : Nil
slice = @bytes.to_slice
buffer = uninitialized UInt8[36]
buffer_ptr = buffer.to_unsafe
buffer_ptr[8] = buffer_ptr[13] = buffer_ptr[18] = buffer_ptr[23] = '-'.ord.to_u8
slice[0, 4].hexstring(buffer_ptr + 0)
slice[4, 2].hexstring(buffer_ptr + 9)
slice[6, 2].hexstring(buffer_ptr + 14)
slice[8, 2].hexstring(buffer_ptr + 19)
slice[10, 6].hexstring(buffer_ptr + 24)
io.write_string(buffer.to_slice)
end
def hexstring : String
@bytes.to_slice.hexstring
end
# Returns a `String` that is a valid urn of *self*
#
# ```
# require "uuid"
#
# uuid = UUID.empty
# uuid.urn # => "urn:uuid:00000000-0000-4000-0000-000000000000"
# uuid2 = UUID.new("c49fc136-9362-4414-81a5-9a7e0fcca0f1")
# uuid2.urn # => "urn:uuid:c49fc136-9362-4414-81a5-9a7e0fcca0f1"
# ```
def urn : String
String.build(45) do |str|
str << "urn:uuid:"
to_s(str)
end
end
def <=>(other : UUID) : Int32
@bytes <=> other.bytes
end
class Error < Exception
end
{% for v in %w(1 2 3 4 5) %}
# Returns `true` if UUID is a V{{ v.id }}, `false` otherwise.
def v{{ v.id }}?
variant == Variant::RFC4122 && version == Version::V{{ v.id }}
end
# Returns `true` if UUID is a V{{ v.id }}, raises `Error` otherwise.
def v{{ v.id }}!
unless v{{ v.id }}?
raise Error.new("Invalid UUID variant #{variant} version #{version}, expected RFC 4122 V{{ v.id }}")
else
true
end
end
{% end %}
end
|
@import url("https://fonts.googleapis.com/css2?family=Rubik&display=swap");
/* variables */
$light-blue: #caf0f8;
$dark-blue: #03045e;
$dark-red: #c00;
$dark-yellow: #fc0;
$white: #fff;
$main-font: "Rubik", sans-serif;
/* base */
* {
box-sizing: border-box;
}
body {
font-family: $main-font;
font-size: 16px;
display: flex;
flex-direction: column;
min-height: 100vh;
color: $dark-blue;
background-color: $light-blue;
margin: 0;
padding: 0;
min-width: 300px;
}
.search-section,
.result-section,
.trip-section {
max-width: 960px;
margin: 30px auto;
padding: 0 30px;
}
.trip-section {
display: grid;
grid: auto / 1fr 1fr 1fr;
gap: 30px;
}
#location,
#date {
color: $dark-blue;
background-color: $white;
font-size: 1rem;
width: 100%;
padding: 10px;
border: 2px solid $dark-blue;
border-radius: 3px;
height: 3rem;
font-family: $main-font;
&.error {
border: 2px solid $dark-red;
}
}
.btn {
color: $dark-blue;
background-color: $dark-yellow;
font-size: 1rem;
width: 100%;
padding: 10px;
border: 2px solid $dark-blue;
border-radius: 3px;
transition: all ease 0.25s;
cursor: pointer;
height: 3rem;
}
/* header */
header {
display: flex;
justify-content: center;
align-items: center;
padding: 30px;
}
.logo {
font-size: 1.5rem;
font-weight: bold;
}
/* footer */
footer {
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
color: $light-blue;
background-color: $dark-blue;
}
/* main */
main {
flex: 2;
}
/* hero */
.hero-section {
display: flex;
justify-content: center;
align-items: center;
height: 240px;
position: relative;
background: url("../media/images/hero.jpg") center 35% / cover no-repeat;
& p {
color: $light-blue;
font-size: 2rem;
font-weight: bold;
padding: 0 20px;
}
}
/* form */
.search-form {
display: grid;
grid: auto / 2fr 2fr 1fr;
}
.form-group {
display: inline-block;
flex: 1 1 auto;
padding: 20px;
}
.message {
padding-top: 20px;
color: $dark-red;
}
.search-btn {
margin-top: 24px;
}
label {
display: block;
margin-bottom: 5px;
}
/* card */
.card {
color: $dark-blue;
background-color: $white;
display: grid;
grid-template:
"card-image card-body" auto
"card-image card-footer" 40px / 3fr 2fr;
border-radius: 3px;
overflow: hidden;
&__image {
grid-area: card-image;
height: 400px;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
&__body {
grid-area: card-body;
}
&__text {
padding: 15px;
}
&__weather {
display: flex;
align-items: center;
padding: 15px;
border-top: 1px solid $dark-yellow;
&--icon {
flex: 1 1 40%;
max-width: 40%;
img {
width: 100%;
}
}
&--info {
display: flex;
flex-direction: column;
margin-left: 20px;
flex: 1 1 60%;
max-width: 60%;
p {
margin: 0;
&.temp {
font-size: 1.2rem;
}
}
}
}
&__footer {
grid-area: card-footer;
& .btn {
border: 0;
border-radius: 0;
padding: 10px 15px;
background-color: $dark-yellow;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
& i {
transition: all 0.25s ease;
margin-right: 7px;
}
&:hover {
& i {
&.fa-solid {
color: #c00;
}
}
}
}
}
}
@media (max-width: 768px) {
.search-form {
display: grid;
grid: auto / 1fr 1fr;
}
.trip-section {
display: grid;
grid: auto / 1fr 1fr;
gap: 30px;
}
.card {
grid-template:
"card-image card-body" auto
"card-image card-footer" 40px / 1fr 1fr;
}
}
@media (max-width: 480px) {
.search-form {
display: grid;
grid: auto / 1fr;
}
.trip-section {
display: grid;
grid: auto / 1fr;
gap: 30px;
}
.card {
grid-template:
"card-image card-body" auto
"card-image card-footer" 40px / 1fr 2fr;
}
.hero-section p {
font-size: 1.5rem;
}
}
.card {
&--column {
grid-template:
"card-image" auto
"card-body" auto
"card-footer" 40px/ 1fr;
.card__image {
max-width: 100%;
max-height: 150px;
overflow: hidden;
}
}
}
|
// @vitest-environment jsdom
import { describe, it, expect } from 'vitest';
import { InternalError } from '../Error';
import { Runtime, type PlatformInfo } from './PlatformInfo';
import { PlatformInstanceActivator } from './PlatformInstanceActivator';
class Fake {
constructor(public readonly id: string) {}
}
describe('PlatformInstanceProvider', () => {
describe('Create', () => {
const cases = [
Runtime.Electron,
Runtime.NodeWebkit,
];
it.each(cases)(`Should throw by default`, async (runtime: Runtime) => {
const testee = new PlatformInstanceActivator();
try {
await testee.Create(runtime);
} catch(error) {
expect(error).toBeInstanceOf(InternalError);
expect(error.message).toBe(`Failed to create an instance of type <T> for platform '${runtime}'!`);
}
});
it.each(cases)(`Should create instance for '%p' using platform info`, async (runtime: Runtime) => {
const actual = new PlatformInstanceActivator<Fake>({ Runtime: runtime } as PlatformInfo)
.Configure(runtime, () => new Fake('😎'))
.Create();
expect(actual).toBeInstanceOf(Fake);
expect(actual.id).toBe('😎');
});
it.each(cases)(`Should create instance for '%p' using parameter`, async (runtime: Runtime) => {
const actual = new PlatformInstanceActivator<Fake>({ Runtime: Runtime.Unknown } as PlatformInfo)
.Configure(runtime, () => new Fake('😎'))
.Create(runtime);
expect(actual).toBeInstanceOf(Fake);
expect(actual.id).toBe('😎');
});
});
});
|
#include <stdio.h>
#include <string.h>
int main()
{
char str[16];
int len, i, j, k, num1, num2;
int group_count = 0;
// Input the string
printf("Enter an integer (maximum 15 digits): ");
scanf("%s", str);
// Find the length of the string
len = strlen(str);
// Iterate through all possible groupings of the numbers
for (i = 1; i < len; i++)
{
for (j = 0; j < i; j++)
{
// Extract the first number in the group
num1 = 0;
for (k = 0; k <= j; k++)
{
num1 = num1 * 10 + (str[k] - '0');
}
// Extract the second number in the group
num2 = 0;
for (k = j+1; k <= i; k++)
{
num2 = num2 * 10 + (str[k] - '0');
}
// Check if the numbers are in increasing order
if (num1 < num2)
{
// Print the group
if (group_count > 0)
{
printf(" ");
}
printf("%d%d", num1, num2);
group_count++;
}
}
}
// If no groups were printed, print a message
if (group_count == 0)
{
printf("No groups found.");
}
printf("\n");
return 0;
}
|
use diesel::{associations::{Identifiable, Associations}, deserialize::Queryable, Insertable, Selectable};
use serde::{Deserialize, Serialize};
use crate::models::ranking::Rank;
#[derive(Queryable, Selectable, Serialize, Associations, Identifiable, Deserialize)]
#[diesel(table_name = crate::schema::client)]
#[diesel(belongs_to(Rank))]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct Client {
pub id: uuid::Uuid,
pub username: String,
pub email: String,
pub password: String,
pub salt: String,
pub role_id: i32,
pub rank_id: i32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ClientAuth {
pub username: String,
pub email: String,
pub password: String
}
#[derive(Insertable)]
#[diesel(table_name = crate::schema::client)]
pub struct InsertableClient<'a> {
pub username: &'a str,
pub email: &'a str,
pub password: &'a str,
pub salt: &'a str
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CacheClientDGS {
pub id: uuid::Uuid,
pub username: String,
pub rank_id: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ClientState {
InGame(String),
Online,
Disconnected
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CacheClient {
pub id: uuid::Uuid,
pub username: String,
pub rank: String,
pub state: ClientState
}
|
@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Create New Profile</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('profiles.index') }}"> Back</a>
</div>
</div>
</div>
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
{!! Form::open(array('route' => 'profiles.store','method'=>'POST','enctype'=>'multipart/form-data')) !!}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
{!! Form::hidden('user_id', $id) !!}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>First Name:</strong>
{!! Form::text('first_name', null, array('placeholder' => 'First Name','class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Last Name:</strong>
{!! Form::text('last_name', null, array('placeholder' => 'Last Name','class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Details Name:</strong>
{!! Form::text('details', null, array('placeholder' => 'Details Name','class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>User Image:</strong>
{!! Form::file('image',array('class' => 'form-control','onchange'=>'preview_image(event)')) !!}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
{{-- <button type="submit" class="btn btn-primary">Submit</button> --}}
{!! Form::submit('Submit',array('class' => 'btn btn-primary'))!!}
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<img id="show" src="#" alt="Upload image" style="height: 200px; width: 200px; margin-top: 20px;">
</div>
</div>
{!! Form::close() !!}
<script type="text/javascript">
function preview_image(event)
{
var reader = new FileReader();
reader.onload = function()
{
var output = document.getElementById('show');
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
}
</script>
@endsection
|
import React, { useEffect } from 'react'
import {
Box,
Stack,
Checkbox,
Grid,
TextField,
FormControlLabel,
Paper,
Button,
Container,
useTheme,
useMediaQuery,
Typography
} from '@mui/material'
import { useState } from 'react';
import "../../assets/scss/auth.css"
import { Label, TextFieldsOutlined } from '@mui/icons-material';
import Image from 'mui-image';
import profileImage from "assets/profile.jpg";
import { Link, useNavigate } from 'react-router-dom';
import styled from '@emotion/styled';
import { useSearchParams,useLocation } from 'react-router-dom';
import { useGetValuerInviteDetailsQuery } from 'features/retrieveValuerInviteSlice';
import * as yup from "yup";
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import "../../assets/scss/validation.css"
import { useRegisterUploaderMutation } from 'features/registerUploaderCompanySlice';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import "primereact/resources/themes/bootstrap4-dark-blue/theme.css";
import "primereact/resources/primereact.min.css";
// 👇 Styled React Route Dom Link Component
export const LinkItem = styled(Link)`
text-decoration: none;
color: #3683dc;
&:hover {
text-decoration: underline;
color: #5ea1b6;
}
`;
function AcceptInviteSignup() {
const toastMessage = (message, type) => {
if (type == "success") {
toast.success(message, {
position: toast.POSITION.TOP_RIGHT
});
} else if (type == "error") {
toast.error(message, {
position: toast.POSITION.TOP_RIGHT
});
} else if (type == "warning") {
toast.warning(message, {
position: toast.POSITION.TOP_RIGHT
});
}
}
const [checked, setChecked] = useState(true);
const theme = useTheme();
const isNonMobile = useMediaQuery("(min-width: 600px)");
const location = useLocation();
const params = new URLSearchParams(location.search);
const {data:retrieved,isError,error} = useGetValuerInviteDetailsQuery(params.get("token"));
const [backendValErrors,setBackendValErrors]=useState({});
const [registerValuer,{isLoading:loadingValuer}] = useRegisterUploaderMutation();
const schema = yup.object().shape({
company_name: yup.string().required("Company Name is required"),
full_name: yup.string().required("Your name is required"),
vrb_number: yup.string().required("VRB Number is required"),
isk_number: yup.string().required("ISK Number is required"),
phone_number: yup.string().required("Phone number is required"),
password: yup.string().required("Please provide password").matches(
/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[@#$%^&+=!])(?!.*\s).{6,}$/,
'Password must be at least 8 characters long and contain at least one letter, one number, and one special character'
),
confirm_password: yup.string().oneOf([yup.ref("password"),null],"Passwords do not match.").required("Please confirm the password")
});
const {register: acceptInviteRegister, handleSubmit: handleSubmitRegisterValuer , setValue: setInviteValue ,isLoading: loadingInviteDetails, formState:{ errors: acceptInviteerrors}} = useForm({
resolver: yupResolver(schema)
});
useEffect(() => {
if (!loadingInviteDetails && retrieved) {
setInviteValue("company_name",retrieved?.valauaion_firm_name);
setInviteValue("full_name",retrieved?.director_name);
setInviteValue("email",retrieved?.invite_email);
setInviteValue("vrb_number",retrieved?.vrb_number);
setInviteValue("isk_number",retrieved?.isk_number);
setInviteValue("phone_number",retrieved?.invite_phone);
}
}, [retrieved, loadingInviteDetails, setInviteValue,]);
const navigate = useNavigate();
const submitRegister = async (data)=>{
const formdata= new FormData();
formdata.append("company_name",data.company_name);
formdata.append("email",data.email);
formdata.append("organization_phone",data.phone_number);
formdata.append("vrb_number",data.vrb_number);
formdata.append("directors_vrb",data.vrb_number);
formdata.append("isk_number",data.isk_number);
formdata.append("password",data.password);
formdata.append("password_confirmation",data.confirm_password);
formdata.append("company_email",data.email);
formdata.append("register_as","Report Uploader Admin");
formdata.append("full_name",data.fulls_name);
const result = await registerValuer(formdata);
if ('error' in result) {
toastMessage(result.error.data.message, "error");
if('backendvalerrors' in result.error.data){
setBackendValErrors(result.error.data.backendvalerrors);
}
} else {
toastMessage(result.data.message, "success");
navigate('/login');
}
}
if(!retrieved){
return ( <Box display={'flex'} flexDirection={'column'}
width={isNonMobile ? "50%" : "80%"}
sx={{
justifyContent: 'center',
marginRight: '10%',
marginLeft: '20%',
borderColor: theme.palette.primary,
borderRadius: '10px'
}} >
<Typography variant='h5' sx={{ mb: 2, fontWeight: 'bold' }} align='center' >.</Typography>
</Box>
)
}
if(Object.keys(retrieved).length === 0){
return ( <Box display={'flex'} flexDirection={'column'}
width={isNonMobile ? "50%" : "80%"}
sx={{
justifyContent: 'center',
marginRight: '10%',
marginLeft: '20%',
borderColor: theme.palette.primary,
borderRadius: '10px'
}} >
<Typography variant='h5' sx={{ mb: 2, fontWeight: 'bold' }} align='center' > Invalid / Expired Invite.</Typography>
</Box>)
}else{
return (
<Box display={'flex'} flexDirection={'column'}
width={isNonMobile ? "50%" : "80%"}
sx={{
justifyContent: 'center',
marginRight: '10%',
marginLeft: '20%',
borderColor: theme.palette.primary,
borderRadius: '10px'
}} >
<form onSubmit={handleSubmitRegisterValuer(submitRegister)} >
<Typography variant='h5' sx={{ mb: 2, fontWeight: 'bold' }} align='center' >ACCEPT INVITE BY ACCOUNT CREATION.</Typography>
<Typography variant='p' sx={{ mb: 4 }} align='center'>Creating A Valuation company Account</Typography>
<Typography sx={{ ml: 1 }}>Your Full Names</Typography>
<TextField placeholder='Full Names' sx={{ m: 1 }} id="outlined-basic" fullWidth {...acceptInviteRegister("full_name")} disabled />
<span sx={{ ml: 1 }} className='errorSpan'>{acceptInviteerrors.full_name?.message}</span>
<Typography sx={{ ml: 1 }}>Account Login Email</Typography>
<TextField placeholder='Account Login Email' sx={{ m: 1 }} id="outlined-basic" fullWidth {...acceptInviteRegister("email")} disabled />
<span sx={{ ml: 1 }} className='errorSpan'>{acceptInviteerrors.email?.message}</span>
<span sx={{ ml: 1 }} className='errorSpan'>{backendValErrors?.email}</span>
<Typography sx={{ ml: 1 }}>Company Name</Typography>
<TextField placeholder='Company Name' sx={{ m: 1 }} id="outlined-basic" fullWidth {...acceptInviteRegister("company_name")} disabled />
<span sx={{ ml: 1 }} className='errorSpan'>{acceptInviteerrors.company_name?.message}</span>
<Grid container direction={isNonMobile ? 'row' : 'column'} >
<Grid item md={6} sm={12} sx={{mb:1}}>
<Typography sx={{ ml: 1 }}>Directors VRB Number</Typography>
<TextField placeholder='Directors VRB Number' sx={{ pl:1 }} fullWidth id="outlined-basic" {...acceptInviteRegister("vrb_number")} disabled />
<span sx={{ ml: 1 }} className='errorSpan'>{acceptInviteerrors.vrb_number?.message}</span>
<span sx={{ ml: 1 }} className='errorSpan'>{backendValErrors?.vrb_number}</span>
</Grid>
<Grid item md={6} sm={12} sx={{mb:1}}>
<Typography sx={{ ml: 1 }}>ISK Number</Typography>
<TextField placeholder='ISK Number' sx={{ pl:1 }} fullWidth id="outlined-basic" {...acceptInviteRegister("isk_number")} disabled />
<span sx={{ ml: 1 }} className='errorSpan'>{acceptInviteerrors.isk_number?.message}</span>
<span sx={{ ml: 1 }} className='errorSpan'>{backendValErrors?.isk_number}</span>
</Grid>
</Grid>
<Typography sx={{ ml: 1 }}>Contact Phone Number</Typography>
<TextField placeholder='Contact Phone Number' sx={{ pl:1, mb:1 }} id="outlined-basic" {...acceptInviteRegister("phone_number")} disabled fullWidth/>
<span sx={{ ml: 1 }} className='errorSpan'>{acceptInviteerrors.phone_number?.message}</span>
<Grid container direction={isNonMobile ? 'row' : 'column'} >
<Grid item md={6} sm={12} sx={{mb:1}}>
<Typography sx={{ ml: 1 }} >Password</Typography>
<TextField type='password' placeholder='Password' sx={{ pl: 1}} fullWidth id="outlined-basic" {...acceptInviteRegister("password")} />
<span sx={{ ml: 1 }} className='errorSpan'>{acceptInviteerrors.password?.message}</span>
</Grid>
<Grid item md={6} sm={12} sx={{mb:1}}>
<Typography sx={{ ml: 1 }} >Confirm Password </Typography>
<TextField type='password' placeholder='Confirm Password' sx={{pl:1 }} fullWidth id="outlined-basic" {...acceptInviteRegister("confirm_password")} />
<span sx={{ ml: 1 }} className='errorSpan'>{acceptInviteerrors.confirm_password?.message}</span>
</Grid>
</Grid>
<Button
type='submit'
variant='contained'
fullWidth
sx={{ m: 2, backgroundColor: theme.palette.primary[800] }}
size='large' >Login</Button>
<Grid container direction={isNonMobile ? 'row' : 'column'} sx={{ m: 2 }} >
<Grid item md={6} sm={12}>
<Link to={'/login'} >Have an Account? Login</Link>
</Grid>
<Grid item md={6} sm={12}>
<Link to={'/forgot-password'}>Forgot password</Link>
</Grid>
</Grid>
</form>
</Box>
)
}
}
export default AcceptInviteSignup;
|
import { toUnit } from '@utils/bn';
import { DeployFunction } from 'hardhat-deploy/types';
import { HardhatRuntimeEnvironment } from 'hardhat/types';
const deployFunction: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
const { deployer, kp3rV1 } = await hre.getNamedAccounts();
const kp3RForTest = await hre.deployments.get('KP3Rv1');
const keep3rV2 = await hre.deployments.get('Keep3rForTestnet');
const pairManager = await hre.deployments.get('UniV3PairManager');
const jobForTest = await hre.deployments.deploy('BasicJob', {
from: deployer,
contract: 'solidity/for-test/JobForTest.sol:JobForTest',
args: [keep3rV2.address],
log: true,
});
// register job
if (jobForTest.newlyDeployed) {
await hre.deployments.execute('Keep3rForTestnet', { from: deployer, log: true }, 'addJob', jobForTest.address);
}
const LIQUIDITY = await hre.deployments.read('Keep3rForTestnet', 'liquidityAmount', jobForTest.address, pairManager.address);
if (LIQUIDITY == 0) {
// deployer needs to have KP3R and WETH balance
let klpBalance = await hre.deployments.read('UniV3PairManager', 'balanceOf', deployer);
if (klpBalance == 0) {
const wethBalance = await hre.deployments.read('WETH', 'balanceOf', deployer);
if (wethBalance < toUnit(1)) {
await hre.deployments.execute('WETH', { from: deployer, log: true, value: toUnit(0.1) }, 'deposit');
}
const kp3rBalance = await hre.deployments.read('KP3Rv1', 'balanceOf', deployer);
if (kp3rBalance < toUnit(100)) {
await hre.deployments.execute('KP3Rv1', { from: deployer, log: true }, 'mint(uint256)', toUnit(1));
}
await hre.deployments.execute('KP3Rv1', { from: deployer, log: true }, 'approve', pairManager.address, toUnit(100));
await hre.deployments.execute('WETH', { from: deployer, log: true }, 'approve', pairManager.address, toUnit(100));
const mintArguments: any[] = [toUnit(1), toUnit(0.1), 0, 0, deployer];
await hre.deployments.execute('UniV3PairManager', { from: deployer, log: true }, 'mint', ...mintArguments);
klpBalance = await hre.deployments.read('UniV3PairManager', 'balanceOf', deployer);
}
// add liquidity to job
await hre.deployments.execute('UniV3PairManager', { from: deployer, log: true }, 'approve', keep3rV2.address, klpBalance);
await hre.deployments.execute(
'Keep3rForTestnet',
{ from: deployer, log: true },
'addLiquidityToJob',
jobForTest.address,
pairManager.address,
klpBalance
);
}
const IS_KEEPER = await hre.deployments.read('Keep3rForTestnet', 'isKeeper', deployer);
if (!IS_KEEPER) {
// register deployer as keeper
await hre.deployments.execute('Keep3rForTestnet', { from: deployer, log: true }, 'bond', kp3RForTest.address, 0);
await hre.deployments.execute('Keep3rForTestnet', { from: deployer, log: true }, 'activate', kp3RForTest.address);
}
await hre.deployments.execute('BasicJob', { from: deployer, log: true, gasLimit: 1e6 }, 'work');
};
deployFunction.dependencies = ['testnet-keep3r'];
deployFunction.tags = ['job-for-test'];
export default deployFunction;
|
export interface ITextEditorState {
textAlign: 'right' | 'left';
listType: 'bulleted' | 'numbered' | undefined;
bold: boolean;
italic: boolean;
underline: boolean;
fontSize: number;
color: string;
}
export class TextEditorState implements ITextEditorState {
constructor(
public textAlign: 'right' | 'left' = 'right',
// tslint:disable-next-line:no-unnecessary-initializer
public listType: 'bulleted' | 'numbered' | undefined = undefined,
public bold: boolean = false,
public italic: boolean = false,
public underline: boolean = false,
public fontSize: number = 13,
public color: string = ''
) {
}
}
export class TextEditorContent {
private TEXT: string;
public states: ITextEditorState[];
constructor(
text?: string
) {
this.TEXT = text || '';
this.states = [];
}
public get linedText(): { index: number, text: string, state: ITextEditorState }[] {
return this.TEXT.split(/\n/).map((value, idx) => {
return { index: idx, text: value, state: this.states[idx] };
}) || [];
}
public set text(value: string) {
this.TEXT = value;
const state = new Array<ITextEditorState>();
value.split(/\n/)
.forEach((val, idx) => {
state.push(this.states[idx] || new TextEditorState());
});
}
}
|
<?php
function generateProfessorHTML($id) {
$profPost = new WP_Query(array(
'post_type' => 'professor',
'p' => $id
));
while ($profPost->have_posts()) {
$profPost->the_post();
ob_start(); ?>
<div class="professor-callout">
<div class="professor-callout__photo"
style="background-image: url(<?php the_post_thumbnail_url('professorPortrait'); ?>);">
</div>
<div class="professor-callout__text">
<h5><?php the_title() ?></h5>
<p><?php echo wp_trim_words(get_the_content(), 30) ?></p>
<?php
$relatedPrograms = get_field('related_program');
if ($relatedPrograms) { ?>
<p> teaches:
<?php foreach ($relatedPrograms as $key => $program) {
echo get_the_title($program);
if ($key != array_key_last($relatedPrograms) && count($relatedPrograms) > 1)
echo ', ';
}
}
?>.
</p>
<?php }
?>
<p>
<strong>
<a href="<?php the_permalink(); ?>">Learn more about <?php the_title() ?> »</a>
</strong>
</p>
</div>
</div>
<?php
wp_reset_postdata();
return ob_get_clean();
}
|
package negocio.cliente;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import negocio.factoria.FactoriaNegocio;
public class Create {
private static TCliente correct = new TCliente(-1, "09128355G", "Miguel", "Gonzalez Romero", true, true);
private static TCliente incorrect = new TCliente(-1, "0912835G", "Miguel", "Gonzalez Romero", true, true);
private static SACliente saCliente;
@BeforeClass
public static void initializeClass() {
saCliente = FactoriaNegocio.getInstance().createSACliente();
}
@Test
public void testCorrecto() {
int resultado = saCliente.create(correct);
correct.setId(resultado);
try {
assertTrue(resultado > 0);
}
catch (Exception exception) {
fail(exception.getMessage());
}
}
@Test
public void testRepetido() {
saCliente.create(correct);
int repetido = saCliente.create(correct);
try {
assertTrue(repetido == -1);
}
catch (Exception exception) {
fail(exception.getMessage());
}
}
@Test
public void testIncorrecto() {
int resultado = saCliente.create(incorrect);
try {
assertTrue(resultado == -1);
}
catch (Exception exception) {
fail(exception.getMessage());
}
}
@AfterClass
public static void destroyClass() {
saCliente.deleteFisico(correct.getId());
saCliente.deleteFisico(incorrect.getId());
}
}
|
package com.example.xpenses.mainModule.viewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.example.xpenses.R
import com.example.xpenses.common.entities.FirebaseUser
import com.example.xpenses.mainModule.model.MainRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(private val repository: MainRepository) : ViewModel() {
val initialSetupEvent = liveData {
emit(repository.fetchInitialPreferences())
}
private val _snackbarMsg = MutableLiveData<Int>()
val snackbarMsg: LiveData<Int> = _snackbarMsg
private val _user = MutableLiveData<FirebaseUser>()
val user: LiveData<FirebaseUser> = _user
init {
getUser()
}
private fun getUser() {
repository.getUser { result ->
_user.value = result
if (result != null) _snackbarMsg.value = R.string.main_auth_success
}
}
fun resume() {
repository.resume()
}
fun pause() {
repository.pause()
}
fun updateLastDestination(lastDestination:String){
viewModelScope.launch(Dispatchers.IO) {
repository.updateLastDestination(lastDestination)
}
}
}
|
<?php
namespace common\models\forms;
use Yii;
use yii\base\Model;
use common\models\entities\User;
/**
* Login form
*
* @property-read $user User
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user;
/**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
*/
public function validatePassword($attribute) {
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Такого сочетания Email/Логина и Пароля не зарегистрировано');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate() && $this->getUser()->status > User::STATUS_GUEST) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} elseif ($this->getUser()->status <= User::STATUS_GUEST) {
$this->addError('password', 'Такого сочетания Email/Логина и Пароля не зарегистрировано');
}
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
if (strpos($this->username, '@') > 0) {
$this->_user = User::findByEmail($this->username);
} else {
$this->_user = User::findByUsername($this->username);
}
}
return $this->_user;
}
}
|
package com.github.yurinevenchenov1970.marvelworld.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.yurinevenchenov1970.marvelworld.R;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* @author Yuri Nevenchenov on 9/11/2017.
*/
public class CharacterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private CharacterClickListener mClickListener;
@BindView(R.id.character_image_view)
ImageView mImageView;
@BindView(R.id.character_name_text_view)
TextView mNameTextView;
@BindView(R.id.description_text_view)
TextView mDescriptionTextView;
public CharacterViewHolder(View itemView, CharacterClickListener clickListener) {
super(itemView);
mClickListener = clickListener;
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
mClickListener.onItemClick(getLayoutPosition());
}
}
|
import React, { useState } from "react";
import { View, Text, SafeAreaView } from "react-native";
import COLORS from "../colors/colors";
import Button from "../components/Button";
import DetailInput from "../components/DetailInput";
const Registration = ({ navigation }) => {
const [inputFields, setInputFields] = useState({
firstName: "",
lastName: "",
address: "",
phoneNumber: "",
bloodGroup: "",
});
return (
<SafeAreaView
style={{ backgroundColor: COLORS.white, flex: 1, paddingHorizontal: 10 }}
>
<Text style={{ color: COLORS.black, fontSize: 40, fontWeight: "bold" }}>
Registration
</Text>
<Text style={{ color: COLORS.grey, fontSize: 18, marginVertical: 10 }}>
Enter your details to register.
</Text>
<View style={{ marginVertical: 20 }}>
<DetailInput
placeHolder="Enter your full name"
inputType="firstName"
inputFields={inputFields}
setInputFields={setInputFields}
/>
<DetailInput
placeHolder="Enter your phone number"
inputType="lastName"
inputFields={inputFields}
setInputFields={setInputFields}
/>
<DetailInput
placeHolder="Enter your email address"
inputType="address"
inputFields={inputFields}
setInputFields={setInputFields}
/>
<DetailInput
placeHolder="Enter your email password"
inputType="phoneNumber"
inputFields={inputFields}
setInputFields={setInputFields}
/>
<DetailInput
placeHolder="Enter your blood group"
inputType="bloodGroup"
inputFields={inputFields}
setInputFields={setInputFields}
/>
<Button
title={"Register"}
onPress={() => navigation.navigate("Main")}
/>
<Text
// to return to login screen on press
onPress={() => navigation.navigate("Register")}
style={{
color: COLORS.black,
textAlign: "center",
fontSize: 16,
paddingTop: 5,
}}
>
Already have an account? Log in
</Text>
</View>
</SafeAreaView>
);
};
// const style = StyleSheet.create({
// image: {
// flex: 1,
// height: 200,
// },
// });
export default Registration;
|
# library('readxl')
# library('clusterProfiler') # 基因 ID 转换、富集
library("enrichplot")
library('org.Hs.eg.db') # 人数据库 hsa
library('org.Mm.eg.db') # 鼠数据库 mmu
library('org.Rn.eg.db') # 鼠数据库 rat
# library('R.utils')
R.utils::setOption("clusterProfiler.download.method",'auto')
gseakeggServer <- function(id) {
moduleServer(
id,
function(input, output, session) {
output$plot_gsea0 <- renderPlot({
return(NULL)
})
observeEvent(input$show,{
DEG <- reactive({
file1 <- input$file1
if(is.null(file1) ){
DEG <- readRDS('www/DEG.RDS')
}
else{
d <- tail( unlist(strsplit(file1$datapath,'[.]') ), 1)
if(d=='csv'){
DEG <- data.frame( read.csv(file1$datapath, fileEncoding = "GB18030") )
} else{
DEG <- data.frame( readxl::read_excel(file1$datapath,1) )
}
}
# lis <- strsplit(DEG$ID,'[.]')
# for (i in 1:length(lis) ) {
# DEG$ID[i] <- lis[[i]][1]
# } ; rm(i)
return( DEG )
})
if(!is.null(DEG() )){
observe({
DEG <- DEG()
updateSelectInput(session ,inputId = 'ID', choices = colnames(DEG),
selected = colnames(DEG)[1] )
if(!input$ID==''){
output$DEG <- renderDataTable({ return(DEG()) })
}
updateSelectInput(session,inputId='logFC_col',choices=colnames(DEG),selected = '')
# gseKEGG 富集
observeEvent(input$submit1,{
# 加载界面
output$plot_gsea0 <- renderPlot({
if(!input$logFC_col==''){
OrgDb.db <- reactive({
if(input$species == 'hsa'){ OrgDb.db <- org.Hs.eg.db }
else if(input$species == 'mmu'){ OrgDb.db <- org.Mm.eg.db }
else if(input$species == 'rat'){ OrgDb.db <- org.Rn.eg.db }
return(OrgDb.db)
})
observe({
DEG <- DEG()
DEG <- dplyr::rename(DEG, c('ID'=input$ID))
# 自动判断输入基因名类型
name <- reactive({
if(input$geneid=='unknown'){
dat1 <- DEG
dat2 <- dat1[1:500,]
dfName <- data.frame()
for (i in geneName){
n <- try(clusterProfiler::bitr(unique(dat2$ID), fromType <- i, toType <- "MAP", OrgDb <- OrgDb.db() ),silent=T)
logi <- 'try-error' %in% class( n )
if(logi== F ){
if(nrow(dfName) < nrow(n)){
dfName <- n
name <- colnames(dfName)[1]
}
}
}
}
else{ name <- input$geneid }
return(name)
})
# 选择 "ENTREZID" 基因
geneList <- reactive({
if(is.null(DEG )){return(NULL)}
dat1 <- DEG
name <- name()
if(name=="ENTREZID"){
dat1$ENTREZID <- dat1$ID
DEG <- dat1
}
else if(!name=="ENTREZID"){
dfName <- clusterProfiler::bitr(unique(dat1$ID), fromType <- name, toType <- "ENTREZID" , OrgDb <- OrgDb.db())
DEG <- merge(dat1, dfName, by.x='ID', by.y= name())
}
# 3.4 geneList: LogFC
geneList <- eval(parse(text = paste0("DEG$",input$logFC_col) ) ) # 把 DEG 数据logFC列值赋值给数据geneList
names(geneList) <- DEG$ENTREZID # 把ID赋值给geneList数据的名字
geneList <- sort(geneList, decreasing = T) # 把数据进行排序
return(geneList)
})
kk_gse <- reactive({
if(is.null(geneList() )){return(NULL)}
geneList <- geneList()
# 2.1 差异基因富集
kk_gse <- clusterProfiler::gseKEGG(geneList = geneList,
organism = input$species,
minGSSize = input$gsea_min,
keyType = "kegg",
maxGSSize = input$gsea_max,
pAdjustMethod = 'BH',
pvalueCutoff = input$pvalue_gsea,
verbose = TRUE)
kk_gse <- clusterProfiler::setReadable(kk_gse, OrgDb = OrgDb.db(), keyType = "ENTREZID")
})
observe({
if(is.null(kk_gse() ) ) {return(NULL) }
kk_gse <- kk_gse()
if(input$plot_gsea_id1 == "p_eamp"){
kk_gse_emap <- enrichplot::pairwise_termsim(kk_gse)
updateSelectInput(session, "gsea_num1",label = '通路选择',
choices = kk_gse_emap@result[["Description"]],
selected = kk_gse_emap@result[["Description"]][1:10] )
}
else if(!input$plot_gsea_id1 == "p_eamp" ){
updateSelectInput(session, "gsea_num1",label = '通路选择',
choices = kk_gse@result[["Description"]],
selected = kk_gse@result[["Description"]][1:10] )
}
updateSelectInput(session, "gsea_kk_gse",label = '通路选择',
choices = kk_gse@result[["Description"]],
selected = kk_gse@result[["Description"]][1] )
} )
# GSEA 富集、网页展示
observeEvent(input$submit1,{
plot_gsea0 <- reactive({
if(is.null(kk_gse() )){return(NULL)}
kk_gse <- kk_gse()
if(input$plot_gsea_id1 == "p_dot"){
p <- dotplot( kk_gse, showCategory= input$gsea_num0 ,split=".sign") +
facet_grid(.~.sign)
}
else if(input$plot_gsea_id1 == "p_bar"){
p <- ggplot(kk_gse, aes(NES, fct_reorder(Description, NES),
fill= qvalue),
showCategory= input$gsea_num0) +
geom_bar(stat='identity') +
scale_fill_continuous(low='red', high='blue', guide=guide_colorbar(reverse=TRUE)) +
theme_minimal() + ylab(NULL)
}
else {
p<- emapplot(enrichplot::pairwise_termsim(kk_gse),
showCategory = input$gsea_num0,
layout.params = list(layout = 'kk'),
edge.params = list(min = 0.1), color = "NES",
cex.params = list(category_node = 1.5),max.overlaps =10 )
}
return(p)
})
# 3.1 展示GSEA 1
output$plot_gsea0 <- renderPlot({
if (is.null( plot_gsea0() ) ){ return() }
return( plot_gsea0() )
})
if(T){
output$pdf0 <- downloadHandler(
filename="gsea0.pdf",
content = function(file){
pdf(file,width=input$w0,height=input$h0)
print( plot_gsea0() )
dev.off()
}
)
output$png0 <- downloadHandler(
filename="gsea0.png",
content = function(file){
png(file,width=input$w0,height=input$h0,units="in",res=input$ppi0)
print( plot_gsea0() )
dev.off()
}
)
output$jpeg0 <- downloadHandler(
filename="gsea0.jpeg",
content = function(file){
jpeg(file,width=input$w0,height=input$h0,units="in",res=input$ppi0)
print(plot_gsea0() )
dev.off()
}
)
output$tiff0 <- downloadHandler(
filename="gsea0.tiff",
content = function(file){
tiff(file,width=input$w0,height=input$h0,units="in",res=input$ppi0)
print(plot_gsea0() )
dev.off()
} )
output$rdata0 <- downloadHandler(
filename="gseaKEGG.rdata",
content = function(file){
gseaKEGG <- plot_gsea0()
save(gseaKEGG,file = file)
} )
}
})
# GSEA 富集、网页展示
observeEvent(input$submit_gsea1,{
plot_gsea1 <- reactive({
if(is.null(kk_gse() )){return(NULL)}
kk_gse <- kk_gse()
if(input$plot_gsea_id1 == "p_dot"){
p <- dotplot( kk_gse, showCategory= input$gsea_num1 , split=".sign") +
facet_grid(.~.sign)
}
else if(input$plot_gsea_id1 == "p_bar"){
p <- ggplot(kk_gse, aes(NES, fct_reorder(Description, NES), fill= qvalue), showCategory= input$gsea_num1) +
geom_bar(stat='identity') +
scale_fill_continuous(low='red', high='blue', guide=guide_colorbar(reverse=TRUE)) +
theme_minimal() + ylab(NULL)
}
else {
p<- emapplot(enrichplot::pairwise_termsim(kk_gse), showCategory = input$gsea_num1,
layout.params = list(layout = 'kk'),
edge.params = list(min = 0.1), color = "NES",
cex.params = list(category_node = 1.5),max.overlaps =10 )
}
return(p)
})
# 3.1 展示GSEA 1
output$plot_gsea1 <- renderPlot({
if (is.null( kk_gse() ) ){ return() }
return( plot_gsea1() )
})
if(T){
output$pdf1 <- downloadHandler(
filename="gsea1.pdf",
content = function(file){
pdf(file,width = input$w1,height=input$h1)
print( plot_gsea1() )
dev.off()
}
)
output$png1 <- downloadHandler(
filename="gsea1.png",
content = function(file){
png(file,width=input$w1,height=input$h1,units="in",res=input$ppi1)
print( plot_gsea1() )
dev.off()
}
)
output$jpeg1 <- downloadHandler(
filename="gsea1.jpeg",
content = function(file){
jpeg(file,width=input$w1,height=input$h1,units="in",res=input$ppi1)
print(plot_gsea1() )
dev.off()
}
)
output$tiff1 <- downloadHandler(
filename="gsea1.tiff",
content = function(file){
tiff(file,width=input$w1,height=input$h1,units="in",res=input$ppi1)
print(plot_gsea1() )
dev.off()
} )
output$rdata1 <- downloadHandler(
filename="gseaKEGG.rdata",
content = function(file){
gseaKEGG1 <- plot_gsea1()
save(gseaKEGG1,file = file)
} )
}
})
# 3.1 展示GSEA 2
observeEvent(input$submit_gsea2, {
plot_gsea2 <-reactive({
if (is.null( kk_gse() ) ){ return() }
kk_gse <- kk_gse()
if(input$plot_gsea_id2 == "p_gsea"){
y3 <- match(input$gsea_kk_gse , kk_gse@result[["Description"]] )
p <- gseaplot2(kk_gse, geneSetID = y3, pvalue_table = T)
}
else if(input$plot_gsea_id2 == "p1"){
y2 <- input$gsea_kk_gse
p = cnetplot(kk_gse,
color.params = list(foldChange = geneList(), edge = T ),
showCategory = y2, layout = "gem", node_label="gene")
}
else if(input$plot_gsea_id2 == "p2"){
y2 <- input$gsea_kk_gse
p <- cnetplot(kk_gse, circular = T,
color.params = list(foldChange = geneList(), edge = T ),
showCategory = y2, layout = "gem", node_label="gene")
}
return(p)
})
output$plot_gsea2 <- renderPlot({
if (is.null( kk_gse() ) ){ return() }
return( plot_gsea2() )
})
if(T){
output$pdf2 <- downloadHandler(
filename="gsea2.pdf",
content = function(file){
pdf(file,width=input$w2,height=input$h2)
print( plot_gsea2() )
dev.off()
}
)
output$png2 <- downloadHandler(
filename="gsea2.png",
content = function(file){
png(file,width=input$w2,height=input$h2,units="in",res=input$ppi2)
print( plot_gsea2() )
dev.off()
}
)
output$jpeg2 <- downloadHandler(
filename="gsea2.jpeg",
content = function(file){
jpeg(file,width=input$w2,height=input$h2,units="in",res=input$ppi2)
print(plot_gsea2() )
dev.off()
}
)
output$tiff2 <- downloadHandler(
filename="gsea2.tiff",
content = function(file){
tiff(file,width=input$w2,height=input$h2,units="in",res=input$ppi2)
print(plot_gsea2() )
dev.off()
} )
output$rdata2 <- downloadHandler(
filename="gseaKEGG.rdata",
content = function(file){
gseaKEGG2 <- plot_gsea2()
save(gseaKEGG2,file = file)
} )
} # if
})
})
}
})
} ) # observeEvent(input$submit1,{
})
}
}) # show
# 5.3 下载参考数据 DEseq2 Excel
output$downloadSampleData <- downloadHandler(
filename = function() {
paste('DEG.csv')
},
content = function(file) {
write.csv(readRDS('www/DEG.RDS'), file, row.names = F, fileEncoding = "GB18030")
} )
} # function(input, output, session)
) # moduleServer
} # function(id)
|
package ch06.sec05.exam01;
public class Car {
// 필드
String model;
int speed;
// 생성자
public Car(String model) {
// 왼쪽은 멤버필드의 model
// 오른쪽은 매개변수로 넘어온 model
this.model = model;
}
// 메소드
// 왼쪽은 멤버필드의 speed
// 오른쪽은 매개벼수로 넘어온 speed
void setSpeed(int speed) {
this.speed = speed;
}
// 멤버필드 speed의 값을 리턴하라
int getSpeed() {
// return speed; // 이것도 괜찮지만
// 가시성을 높이기 위해
return this.speed; // 이렇게 해도 됨
}
// 10에서 50까지 속도를 점진적으로 증가시킨다.
// this를 붙이면 코드량이 많이 증가하지만 개념적 이해가 확실히 되어서 오류가 덜 발생
// 따라서 유지보수가 더 쉬워짐
public void run() {
for (int i = 10; i <= 50; i += 10) {
this.setSpeed(i);
System.out.println(model + "가 달립니다. (시속 : " + speed + "km/h)");
}
}
}
|
# More visualization ideas: https://lmudge13.github.io/sample_code/mixed_effects.html
#Install package, if needed, and load
if (!require(lmerTest)) install.packages('lmerTest')
library('lmerTest')
if (!require(sjPlot)) install.packages('sjPlot')
library(sjPlot)
#
if (!require(lme4)) install.packages('lme4')
library(lme4)
if (!require(nlme)) install.packages('nlme')
library(nlme)
if (!require(tidyverse)) install.packages('tidyverse')
library(tidyverse)
if (!require(MuMIn)) install.packages('MuMIn')
library(MuMIn)
# use MuMIn::r.squaredGLMM() to calculate R2 values from mixed effects models
# full data set
fdat = read_csv("ghg-model-dataset.csv")
# CO2 FLUX #
#=====GETTING STARTED
#Read in the data
# data for this model
mdat = fdat %>%
mutate(np_ratio = (tn/14.001) / ((tp/1000)/30.97)) %>%
select(pond_id:period, co2_lake, NEP, np_ratio, tp, srp, tn, nox, bottom_do_sat, temp, chla, buoy_freq) %>%
# only keep rows that have values for all variables
filter(!(if_any(co2_lake:buoy_freq, is.na))) %>%
# force the reference treatment to be first (so model results show effect of the pulse treatment)
mutate(treatment = as.factor(treatment),
period = as.factor(period),
treatment = fct_relevel(treatment, "reference"))
#=====STEP 1: MIXED EFFECTS MODEL
# mod_mixed<-lmerTest::lmer(co2_flux ~ buoy_freq + (1|pond_id), data=flux, na.action="na.fail", REML=F)
# summary(mod_mixed)
# mod1 = lmer(co2_lake ~ treatment + buoy_freq + chla + NEP + np_ratio + (1|pond_id) + (0+period|treatment), data = mdat, REML=F)
# summary(mod1)
# mod2 = lmer(co2_lake ~ treatment + buoy_freq + chla + NEP + np_ratio + (1|pond_id), data = mdat, REML=F)
# summary(mod2)
# mod3 = lmer(co2_lake ~ treatment + buoy_freq + chla + NEP + log(tp) + (1|pond_id) + (0+period|treatment), data = mdat, REML=F)
# summary(mod3)
# mod4 = lmer(co2_lake ~ period + buoy_freq + log(tp) + (1|pond_id), data = mdat, REML=F)
# summary(mod4)
# mod5 = lmer(co2_lake ~ period + buoy_freq + log(tp) + (1|pond_id) + (0+period|treatment), data = mdat, REML=F)
# summary(mod5)
# mod6 = lmer(co2_lake ~ treatment + period + buoy_freq + log(tp) + (1|pond_id), data = mdat, REML=F)
# summary(mod6)
mod7 = lmer(co2_lake ~ treatment * period + buoy_freq + log(tp) + (1|pond_id), data = mdat, REML=F)
summary(mod7)
# mod8 = lmer(co2_lake ~ treatment + buoy_freq + log(tp) + (1|pond_id) + (0+treatment|period), data = mdat, REML=F)
# summary(mod8)
# mod9 = lmer(co2_lake ~ treatment + buoy_freq + log(tp) + (1|pond_id), data = mdat, REML=F)
# summary(mod9)
# mod10 = lmer(co2_lake ~ treatment * period + buoy_freq + log(tp) + (1|pond_id) + (0+treatment|pond_id), data = mdat, REML=F)
# summary(mod10)
# remove "Period" as a fixed effect
mod11 = lmer(co2_lake ~ treatment * log(tp) + buoy_freq + (1|pond_id), data = mdat, REML=F)
summary(mod11)
mod12 = lmer(co2_lake ~ treatment + log(tp) + buoy_freq + treatment:log(tp) + NEP + (1|pond_id), data = mdat, REML=F)
summary(mod12)
# mod13 = lmer(co2_lake ~ treatment + log(tp) + chla + buoy_freq + NEP + treatment:log(tp) + treatment:chla + treatment:NEP + (1|pond_id), data = mdat, REML=F)
# summary(mod13)
#Calculate the variance explained by the model (R-squared)
# rsq(mdat$co2_lake, predict(mod7))
r.squaredGLMM(mod7)
#Plot the Effect Sizes
sjPlot::plot_model(mod7,
# axis.labels=c("Treatment * Period \n(Pulse2)", "Treatment * Period \n(Pulse1)", "log(TP)",
# "Buoyancy \nFrequency", "Period \n(Pulse2)", "Period \n(Pulse1)", "Treatment"),
show.values=TRUE, show.p=TRUE,
title = expression(Effect~on~CO[2]~Flux))
#Make a pretty table
sjPlot::tab_model(mod7,
# pred.labels = c("(Intercept)", "Treatment", "Period (Pulse1)", "Period (Pulse2)", "Buoyancy Frequency",
# "log(TP)", "Treatment * Period (Pulse1)", "Treatment * Period (Pulse2)"),
show.re.var= TRUE,
dv.labels= "Effects on CO2 Flux")
#=====STEP 2: COMPARE TO NULL MODEL
# Null model does NOT allow intercept to vary by lake
mod_null<-lm(co2_lake ~ treatment * period + buoy_freq + log(tp), data = mdat)
summary(mod_null)
#Compare the mixed model to the null model
anova(mod7, mod_null)
#A p<0.05 means that the two models are different from each other
# output model results for plotting
mod_co2 = summary(mod7)$coefficients %>% as.data.frame() %>% rownames_to_column(var="fixed.effect") %>% as_tibble()
# CH4 FLUX #
#=====GETTING STARTED
#Read in the data
# data for this model
mdat = fdat %>%
mutate(np_ratio = (tn/14.001) / ((tp/1000)/30.97)) %>%
select(pond_id:period, ch4_lake, tp, tn, np_ratio, bottom_do, temp, chla, wind_speed, buoy_freq) %>%
# only keep rows that have values for all variables
filter(!(if_any(ch4_lake:buoy_freq, is.na))) %>%
# force the reference treatment to be first (so model results show effect of the pulse treatment)
mutate(treatment = as.factor(treatment),
period = as.factor(period),
treatment = fct_relevel(treatment, "reference"))
#=====STEP 1: MIXED EFFECTS MODEL
# mod_mixed<-lmerTest::lmer(ch4_flux ~ bottom_do + period + (1|pond_id), data=flux, na.action="na.fail", REML=F)
# summary(mod_mixed)
# mod1 = lmer(ch4_lake ~ treatment + bottom_do + buoy_freq + np_ratio + (1|pond_id) + (0+period|treatment), data = mdat, REML=F)
# summary(mod1)
# mod2 = lmer(ch4_lake ~ treatment + bottom_do + buoy_freq + np_ratio + (1|pond_id), data = mdat, REML=F)
# summary(mod2)
# mod3 = lmer(ch4_lake ~ treatment + bottom_do + buoy_freq + log(tp) + (1|pond_id) + (0+period|treatment), data = mdat, REML=F)
# summary(mod3)
# mod4 = lmer(ch4_lake ~ treatment + bottom_do + buoy_freq + log(tp) + (1|pond_id), data = mdat, REML=F)
# summary(mod4)
# mod5 = lmer(ch4_lake ~ period + bottom_do + buoy_freq + (1|pond_id) + (0+period|treatment), data = mdat, REML=F)
# summary(mod5)
# mod6 = lmer(ch4_lake ~ period + bottom_do + buoy_freq + (1|pond_id), data = mdat, REML=F)
# summary(mod6)
# mod7 = lmer(ch4_lake ~ period + bottom_do + (1|pond_id), data = mdat, REML=F)
# summary(mod7)
# mod8 = lmer(ch4_lake ~ period + bottom_do + doy + (1|pond_id) + (0+doy|pond_id), data = mdat, REML=F)
# summary(mod8)
# mod9 = lmer(ch4_lake ~ period + bottom_do + doy + (1|pond_id), data = mdat, REML=F)
# summary(mod9)
# mod10 = lmer(ch4_lake ~ treatment + period + bottom_do + (1|pond_id), data = mdat, REML=F)
# summary(mod10)
mod11 = lmer(ch4_lake ~ treatment * period + bottom_do + (1|pond_id), data = mdat, REML=F)
summary(mod11)
# mod12 = lmer(ch4_lake ~ treatment + bottom_do + (1|pond_id) + (0+treatment|period), data = mdat, REML=F)
# summary(mod12)
# mod13 = lmer(ch4_lake ~ treatment * period + bottom_do + wind_speed + (1|pond_id), data = mdat, REML=F)
# summary(mod13)
# mod14 = lmer(ch4_lake ~ treatment * period + bottom_do + buoy_freq + (1|pond_id), data = mdat, REML=F)
# summary(mod14)
# remove "Period" as a fixed effect
mod15 = lmer(ch4_lake ~ treatment * bottom_do + (1|pond_id), data = mdat, REML=F)
summary(mod15)
#Calculate the variance explained by the model (R-squared)
# rsq(mdat$ch4_lake, predict(mod11))
r.squaredGLMM(mod11)
#Plot the Effect Sizes
sjPlot::plot_model(mod11,
# axis.labels = c("Treatment * Period \n(Pulse2)", "Treatment * Period \n(Pulse1)", "Bottom \nWater DO",
# "Period \n(Pulse2)", "Period \n(Pulse1)", "Treatment"),
show.values=TRUE, show.p=TRUE,
title=expression(Effect~on~CH[4]~Flux))
#Make a pretty table
sjPlot::tab_model(mod11,
# pred.labels = c("(Intercept)", "Treatment", "Period (Pulse1)", "Period (Pulse2)", "Bottom Water DO",
# "Treatment * Period (Pulse1)", "Treatment * Period (Pulse2)"),
show.re.var= TRUE,
dv.labels= "Effects on CH4 Flux")
#=====STEP 2: COMPARE TO NULL MODEL
# Null model does NOT allow intercept to vary by lake
mod_null<-lm(ch4_lake ~ treatment * period + bottom_do, data=mdat)
summary(mod_null)
#Compare the mixed model to the null model
anova(mod11, mod_null)
#A p<0.05 means that the two models are different from each other
# output model results for plotting
mod_ch4 = summary(mod11)$coefficients %>% as.data.frame() %>% rownames_to_column(var="fixed.effect") %>% as_tibble()
# N2O FLUX #
#=====GETTING STARTED
#Read in the data
# data for this model
mdat = fdat %>%
mutate(np_ratio = (tn/14.001) / ((tp/1000)/30.97),
n2o_lake = n2o_lake * 1000) %>%
select(pond_id:period, n2o_lake, tp, tn, np_ratio, nox, bottom_do, temp, wind_speed, buoy_freq) %>%
# only keep rows that have values for all variables
filter(!(if_any(n2o_lake:buoy_freq, is.na))) %>%
# force the reference treatment to be first (so model results show effect of the pulse treatment)
mutate(treatment = as.factor(treatment),
period = as.factor(period),
treatment = fct_relevel(treatment, "reference"))
# mean weekly values to include DEA
wdat = fdat %>%
filter(!(doy<146 | doy>240)) %>%
fill(week) %>%
mutate(period = as_factor(period),
np_ratio = (tn/14.001) / ((tp/1000)/30.97),
n2o_lake = n2o_lake * 1000,
DEA = DEA * 1000) %>%
select(pond_id:week, n2o_lake, tp, tn, nox, bottom_do, temp, wind_speed, buoy_freq, DEA) %>%
group_by(pond_id, week) %>%
summarize(across(n2o_lake:DEA, ~mean(., na.rm=T))) %>%
ungroup() %>%
mutate(period = case_when(.$week %in% c(1,2,3,4) ~ "BASE",
.$week %in% c(5,6,7,8,9) ~ "PULSE1",
.$week %in% c(10,11,12,13,14) ~ "PULSE2"))
#=====STEP 1: MIXED EFFECTS MODEL
# mod_mixed<-lmerTest::lmer(n2o_flux ~ doy + (1|pond_id), data=flux, na.action="na.fail", REML=F)
# summary(mod_mixed)
# mod1 = lmer(n2o_lake ~ treatment + nox + bottom_do + buoy_freq + (1|pond_id), data = mdat, REML=F)
# summary(mod1)
# mod2 = lmer(n2o_lake ~ period + nox + bottom_do + buoy_freq + (1|pond_id) + (0+period|treatment), data = mdat, REML=F)
# summary(mod2)
# mod3 = lmer(n2o_lake ~ period + nox + bottom_do + buoy_freq + (1|pond_id), data = mdat, REML=F)
# summary(mod3)
# mod4 = lmer(n2o_lake ~ period + nox + bottom_do + (1|pond_id) + (0+period|treatment), data = mdat, REML=F)
# summary(mod4)
# mod5 = lmer(n2o_lake ~ period + nox + bottom_do + (1|pond_id), data = mdat, REML=F)
# summary(mod5)
# mod6 = lmer(n2o_lake ~ period + nox + bottom_do + DEA + (1|pond_id), data = wdat, REML=F)
# summary(mod6)
# mod7 = lmer(n2o_lake ~ treatment + period + nox + bottom_do + (1|pond_id), data = mdat, REML=F)
# summary(mod7)
mod8 = lmer(n2o_lake ~ treatment * period + nox + bottom_do + (1|pond_id), data = mdat, REML=F)
summary(mod8)
# mod11 = lmer(n2o_lake ~ treatment + nox + bottom_do + (1|pond_id) + (0+treatment|period), data = mdat, REML=F)
# summary(mod11)
# mod9 = lmer(n2o_lake ~ treatment * period + np_ratio + bottom_do + (1|pond_id), data = mdat, REML=F)
# summary(mod9)
# mod10 = lmer(n2o_lake ~ treatment * period + tn + bottom_do + (1|pond_id), data = mdat, REML=F)
# summary(mod10)
#Calculate the variance explained by the model (R-squared)
# rsq(mdat$n2o_lake, predict(mod8))
r.squaredGLMM(mod8)
#Plot the Effect Sizes
sjPlot::plot_model(mod8,
# axis.labels=c("Treatment * Period \n(Pulse2)", "Treatment * Period \n(Pulse1)", "Bottom \nWater DO",
# "NOx", "Period \n(Pulse2)", "Period \n(Pulse1)", "Treatment"),
show.values=TRUE, show.p=TRUE,
title=expression(Effect~on~N[2]*O~Flux))
#Make a pretty table
sjPlot::tab_model(mod8,
pred.labels = c("(Intercept)", "Treatment", "Period (Pulse1)", "Period (Pulse2)", "NOx",
"Bottom Water DO", "Treatment * Period (Pulse1)", "Treatment * Period (Pulse2)"),
show.re.var= TRUE,
dv.labels= "Effects on N2O Flux")
#=====STEP 2: COMPARE TO NULL MODEL
# Null model does NOT allow intercept to vary by lake
mod_null<-lm(n2o_lake ~ treatment * period + nox + bottom_do, data=mdat)
summary(mod_null)
#Compare the mixed model to the null model
anova(mod8, mod_null)
#A p<0.05 means that the two models are different from each other
# output model results for plotting
mod_n2o = summary(mod8)$coefficients %>% as.data.frame() %>% rownames_to_column(var="fixed.effect") %>% as_tibble()
|
# 第一个 DApp
本篇教程主要介绍如何使用 Rooch 提供的 DApp 前端模板工具来创建一个计数器程序。
## 创建项目
```bash
pnpm create @roochnetwork/create-rooch
```
## 初始化项目
安装 DApp 所需依赖:
```bash
pnpm install
```
运行 DApp:
```bash
pnpm dev
```
当一切顺利后,在浏览器中能看到如下:

到这一步说明,前端已经能够正常工作了,接下来需要部署合约,使得 DApp 能够与合约进行交互。
## 切换网络
当前在本地网络演示创建 Counter DApp 应用,使用 `rooch env switch` 来切换网络:
```bash
rooch env switch --alias local
The active environment was successfully switched to `local`
```
## 启动 Rooch 本地节点
```bash
rooch server start
```
## 部署合约
我们使用 `examples/counter` 这个合约来部署。
```bash
rooch move publish --named-addresses rooch_examples=default
```
## 修改前端配置
找到前端项目中的 `src/App.tsx` 文件,修改 `devCounterAddress` 这个常量:
```tsx
// Your publish counter contract address
const devCounterAddress = ""
const devCounterModule = `${devCounterAddress}::counter`
```
添加部署 Counter 合约的地址:
```bash
const devCounterAddress = "0x634e4b692ac7873bb937af3f0ac9bc63c4c6ead3f857c5bbc92e3ff41f756651"
```
> 注意:根据实际部署地址修改!
## 调用合约
连接上钱包,就会提示创建会话密钥:

一切就绪后,就可以在 DApp 调用 Counter 合约了,点击 `Increment` 按钮,增加计数器的值:

## 总结
至此,你已经掌握了如何创建 DApp,并且如何在前端与合约端完成初始化工作,进行基本的交互。
|
#pragma once
#include <json/value.h>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
#include "config.h"
#include "events.h"
#include "http.h"
#include "model.h"
namespace taranis {
struct Version {
int major;
int minor;
int patch;
std::string pre_release_identifiers;
};
bool operator==(const Version &lhs, const Version &rhs);
bool operator<(const Version &lhs, const Version &rhs);
bool operator<=(const Version &lhs, const Version &rhs);
bool operator>(const Version &lhs, const Version &rhs);
bool operator>=(const Version &lhs, const Version &rhs);
struct ReleaseDescription {
std::string name;
std::string tag_name;
bool pre_release;
std::string browser_url;
std::string archive_url;
std::string news_url;
};
class VersionChecker {
public:
VersionChecker(std::shared_ptr<Config> config,
std::shared_ptr<HttpClient> client,
std::shared_ptr<Model> model);
void check(CallContext context);
private:
enum Action { browse = 1, skip = 2 };
static constexpr int message_delay{5000};
const std::string current_version_extended;
std::shared_ptr<Config> config;
std::shared_ptr<HttpClient> client;
std::shared_ptr<Model> model;
void do_check(bool interactive) const;
void notify_user(const ReleaseDescription &release) const;
Json::Value fetch_releases() const;
std::vector<ReleaseDescription>
extract_newer_releases(const Json::Value &value) const;
std::string
generate_new_version_question(const ReleaseDescription &release) const;
std::string shorten_current_version_extended() const;
static Version parse_possible_version_string(const std::string &target);
};
} // namespace taranis
|
def main():
matrix_P = [
[0, 0.5, 0.3, 0.2],
[0.1, 0.2, 0.55, 0.15],
[0.4, 0.3, 0.2, 0.1],
[0, 0.25, 0.35, 0.4]
]
start_state = int(input("Trạng thái bắt đầu: ")) - 1
des_state = int(input("Trạng thái đích: ")) - 1
n = int(input("Nhập số giai đoạn: "))
result_matrix = matrix_power(matrix_P, n)
if result_matrix:
rounded_result_matrix = round_matrix(result_matrix)
print(f"Ma trận P^{n} (làm tròn đến 3 chữ số hàng thập phân):")
for row in rounded_result_matrix:
print(row)
print(f"Xác suất lớn nhất hệ thống bắt đầu từ trạng thái {start_state+1} sang trạng thái {des_state+1} sau {n} giai đoạn: {rounded_result_matrix[start_state][des_state]}")
def matrix_power(matrix, n):
result = matrix.copy()
for _ in range(n - 1):
result = multiply_matrices(result, matrix)
return result
def multiply_matrices(matrix1, matrix2):
result = []
if len(matrix1[0]) != len(matrix2):
print("Không thể nhân hai ma trận này.")
return None
for i in range(len(matrix1)):
result.append([0] * len(matrix2[0]))
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
def round_matrix(matrix):
rounded_matrix = []
for row in matrix:
rounded_row = [round(num, 3) for num in row]
rounded_matrix.append(rounded_row)
return rounded_matrix
if __name__ == "__main__":
main()
|
<form #loginForm="ngForm" id="login-form" (ngSubmit)="submitLogin()">
<div class="container">
<div class="row">
<div class="login-form-div col-sm-12">
<div class="text-center">
<label class="block-label" for="signin-login-input">{{'login.username.label' | translate}}</label>
<input type="text" name="login" id="signin-login-input"
class="form-control form-control-sm" aria-label="Small" aria-describedby="inputGroup-sizing-sm"
[(ngModel)]="loginData.login" placeholder="{{'login.username.placeholder' | translate}}"
#login="ngModel" pattern="^[a-zA-Z0-9]{4,15}$" required>
<div *ngIf="login.touched && login.invalid"
class="alert alert-danger">
{{'login.common.error' | translate}}
</div>
</div>
</div>
<div class="login-form-div col-sm-12">
<div class="text-center">
<label class="block-label" for="signin-pass-input">{{'login.password.label' | translate}}</label>
<input type="password" name="password" id="signin-pass-input"
class="form-control form-control-sm" aria-label="Small" aria-describedby="inputGroup-sizing-sm"
[(ngModel)]="loginData.password" placeholder="{{'login.password.placeholder' | translate}}"
#password="ngModel" pattern="^[a-zA-Z0-9]{6,15}$" required>
<div *ngIf="password.touched && password.invalid"
class="alert alert-danger">
{{'login.common.error' | translate}}
</div>
</div>
</div>
</div>
<div class="row login-form-div">
<div class="col-12">
<div class="text-center">
<input type="submit" class="btn btn-success login-button" value="Login" [disabled]="!loginForm.form.valid">
<h6 id="login-form-title"><a>{{'login.other.forgotten-password' | translate}}</a></h6>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="login-form-div text-center">
<h4>{{'login.other.registration' | translate}}
<a routerLink="/register">{{'login.other.registration-label' | translate}} </a>
</h4>
</div>
</div>
</div>
</form>
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title th:text="${titulo}">Insert title here</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/
bootstrap.min.css">
</head>
<header th:replace="fragments/header :: header"></header>
<body>
<div class="container" center>
<div th:object="${clase}" th:remove="tag">
<ul th:if="${#fields.hasErrors('*')}" class="alert alert-danger">
<li th:each="err: ${#fields.errors('*')}" th:text="${err}"></li>
</ul>
</div>
<form th:action="@{/formCla}" th:object="${clase}" method="post" enctype="multipart/form-data">
<div class="form-group row">
<label class="col-sm-2 col-form-label">Nombre</label>
<div class="col-sm-6">
<input type="text" th:field="*{nombre}" class="form-control" th:errorclass="'form-control alert-danger'" /> <small
class="form-text text-danger" th:if="${#fields.hasErrors('nombre')}" th:errors="*{nombre}"></small>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Descripcion</label>
<div class="col-sm-6">
<input type="text" th:field="*{descripcion}" class="form-control" th:errorclass="'form-control alert-danger'" /> <small
class="form-text text-danger" th:if="${#fields.hasErrors('descripcion')}" th:errors="*{descripcion}"></small>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<input type="submit" value="Crear clase" class="btn btn-secondary" />
</div>
</div>
</form>
</div>
</body>
</html>
|
import React from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm, useWatch } from 'react-hook-form';
import {
DEFAULT_VALUE_FORGOT_PASSWORD,
IDefaultValueForgotPassword,
handleSubmitForgotPasswordForm,
schema_forgot_password,
} from './data';
import {
ForgotPasswordForm,
ForgotPasswordVerifyMail,
ResetYourPassword,
} from './components';
import { Box } from '@chakra-ui/react';
export function ForgotPassword() {
const form = useForm({
resolver: yupResolver(schema_forgot_password),
defaultValues: DEFAULT_VALUE_FORGOT_PASSWORD,
mode: 'all',
});
const { handleSubmit, control } = form;
const step = useWatch({
control,
name: 'step',
});
const onSubmit = async (values: IDefaultValueForgotPassword) => {
handleSubmitForgotPasswordForm({ values, form });
};
const renderStep = () => {
switch (step) {
case 'forgotPasswordForm': {
return <ForgotPasswordForm form={form} />;
}
case 'forgotPasswordVerifyMail': {
return <ForgotPasswordVerifyMail form={form} />;
}
case 'resetPassword': {
return <ResetYourPassword form={form} />;
}
}
};
return (
<Box
as="form"
onSubmit={handleSubmit(onSubmit)}
id="form-forgot-password"
h="100%"
>
{renderStep()}
</Box>
);
}
|
<template>
<div class="card mt-4">
<table class="table m-0">
<thead>
<tr>
<th scope="col">Student Name</th>
<!-- <th scope="col">Project Title</th>
<th scope="col">Project Type</th> -->
<th scope="col">Proposal Status</th>
<th scope="col">Proposal Comments</th>
<th scope="col">Proposal Details</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr v-for="proposal in proposalList" :key="proposal.key">
<td width="15%">{{ proposal.student.name }}</td>
<!-- <td width="15%">{{ proposal.title }}</td>
<td width="15%">{{ proposal.project }}</td> -->
<td width="15%">{{ proposal.evaluationStatus }}</td>
<td width="15%" v-if="proposal.evaluator1Id == currentUID">
{{ proposal.evaluationComment1 }}
</td>
<td width="15%" v-if="proposal.evaluator2Id == currentUID">
{{ proposal.evaluationComment2 }}
</td>
<td width="4%">
<div class="w-100 btn-group" role="group">
<router-link :to="`/ProposalDetail/${proposal.key}`">
<!-- <router-link to="/Evaluate"> -->
<button class="btn btn-success mx-1">
Project
</button>
</router-link>
</div>
</td>
<td width="1%">
<div class="w-100 btn-group" role="group">
<router-link :to="`/Evaluate/${proposal.key}`">
<!-- <router-link to="/Evaluate"> -->
<button class="btn btn-primary mx-1">
Evaluate
</button>
</router-link>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { useLoadProject, deleteProject } from "@/firebase";
import { db } from "@/firebase";
import firebase from "firebase";
export default {
data() {
return {
proposalList: [],
currentUID: "",
};
},
created() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.currentUID = user.uid;
const eva1 = new Promise((resolve) => {
db.collection("project")
.where("evaluator1Id", "==", user.uid)
.onSnapshot((snapshotChange) => {
let tmp = [];
snapshotChange.forEach((doc) => {
tmp.push({
key: doc.id,
...doc.data(),
});
});
resolve(tmp);
});
});
const eva2 = new Promise((resolve) => {
db.collection("project")
.where("evaluator2Id", "==", user.uid)
.onSnapshot((snapshotChange) => {
let tmp = [];
snapshotChange.forEach((doc) => {
tmp.push({
key: doc.id,
...doc.data(),
});
});
resolve(tmp);
});
});
Promise.all([eva1, eva2]).then((data) => {
this.proposalList = data[0].concat(data[1]);
});
}
});
},
methods: {
download(url) {
window.open(url, "_blank");
},
},
setup() {
const users = useLoadProject();
return { users, deleteProject };
},
};
</script>
|
import java.util.*;
public class Main {
private static long solve(int N, int W, int[] w, int[] v) {
return solveRec(N, W, w, v, new HashMap[N+1]);
}
private static long solveRec(int k, int maxWeight, int[] w, int[] v, HashMap<Integer, Long>[] cache) {
if (maxWeight < 0) return Long.MIN_VALUE;
if (k == 0) return 0;
if (cache[k] == null) cache[k] = new HashMap<Integer, Long>();
if (cache[k].containsKey(maxWeight)) return cache[k].get(maxWeight);
long without = solveRec(k-1, maxWeight, w, v, cache);
long with = v[k-1] + solveRec(k-1, maxWeight - w[k-1], w, v, cache);
long result = Math.max(with, without);
cache[k].put(maxWeight, result);
return result;
}
public static void main(String[] args) {
int N, W;
int[] w;
int[] v;
try (Scanner scanner = new Scanner(System.in)) {
N = scanner.nextInt();
W = scanner.nextInt();
w = new int[N];
v = new int[N];
for (int i = 0; i < N; i++) {
w[i] = scanner.nextInt();
v[i] = scanner.nextInt();
}
}
long result = solve(N, W, w, v);
System.out.println(result);
//test();
}
private static void test() {
testCase(3, 8, new int[] {3, 4, 5}, new int[] {30, 50, 60}, 90);
testCase(5, 5, new int[] { 1, 1, 1, 1, 1}, new int[] {1000000000,1000000000,1000000000,1000000000,1000000000}, 5000000000L);
testCase(6, 15, new int[] {6,5,6,6,3,7}, new int[] {5,6,4,6,5,2}, 17);
int[] w = new int[100];
int[] v = new int[100];
for (int i=0; i < 100; i++) {
w[i] = 1;
v[i] = 1;
}
long start = System.currentTimeMillis();
testCase(100, 100, w, v, 100);
long elapsed = System.currentTimeMillis() - start;
System.out.println("large test case: " + elapsed);
System.out.println("DONE");
}
private static void testCase(int N, int W, int[] w, int[] v, long expected) {
long result = solve(N, W, w, v);
if (result != expected) {
System.out.println("FAILED N=" + N + " W=" + W + " w=" + Arrays.toString(w) + " v=" + Arrays.toString(v)
+ ", was " + result + " expected " + expected);
}
}
}
|
@file:JsModule("@zowe/imperative")
package zowe.imperative.imperative.auth.builders
import js.objects.Record
import zowe.imperative.cmd.doc.ICommandDefinition
import zowe.imperative.cmd.doc.profiles.definition.ICommandProfileAuthConfig
import zowe.imperative.imperative.doc.IImperativeAuthGroupConfig
import zowe.imperative.logger.Logger
/**
* Generate a complete group of commands for logging in and out of services based on provided auth definitions.
*/
external class CompleteAuthGroupBuilder {
companion object {
/**
* Get the complete auth group of commands
*
* @param authConfigs mapping of profile types to auth configs
* @param logger logger to use in the builder classes
* @param authGroupConfig config that allows command definitions to be overridden
* @return the complete profile group of commands
*/
fun getAuthGroup(
authConfigs: Record<String, Array<ICommandProfileAuthConfig>>,
logger: Logger,
authGroupConfig: IImperativeAuthGroupConfig = definedExternally,
): ICommandDefinition
}
}
|
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Feedback>
*/
class FeedbackFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'title' => fake()->sentence(3,6),
'content' => fake()->sentence(5,15),
'type' => fake()->randomElement(['complaint', 'suggestion']),
'status' => fake()->randomElement(['approved', 'declined', 'on progress']),
'date_submitted' => fake()->date(),
'date_resolved' => fake()->date(),
'user_id' => mt_rand(1,10),
];
}
}
|
/*
GAME FUNCTION:
-Player must guess a number between a min and a max
-Player gets a certain amount of guesses
-Notify player of guesses remaining
-Notify player of correct answer if he looses
-Let player choose to play again
*/
// Game Values
let min=1,
max=10,
winningNum = getRandomNum(min, max),
guessesLeft = 3;
// UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessBtn = document.querySelector('#guess-btn'),
guessInput = document.querySelector('#guess-input'),
message = document.querySelector('.message');
// Assign to UI min and max
minNum.textContent = min;
maxNum.textContent = max;
// Play again Event listener
game.addEventListener('mousedown', function(e){
if(e.target.className === 'play-again'){
window.location.reload();
}
});
// Listen for guess
guessBtn.addEventListener('click', function(){
let guess = parseInt(guessInput.value);
// Validate Input
if( isNaN(guess) || guess < min || guess > max ){
setMessage(`Please enter a number between ${min} and ${max}`, 'red');
}
// Check if won
if( guess === winningNum){
// Game over -Won
// // Disable Input
// guessInput.disabled = true;
// // Change border color
// guessInput.style.borderColor = 'green';
// // Set Message
// setMessage(`${winningNum} is correct, YOU WIN!`, 'green');
gameOver(true, `${winningNum} is correct, YOU WIN!`);
} else{
// Wrong Number
guessesLeft -=1;
// teh above is same as guessesLeft = guessesLeft - 1
if( guessesLeft === 0){
// Game over- Lost
// // Disable Input
// guessInput.disabled = true;
// // Change border color
// guessInput.style.borderColor = 'red';
// // Set Message
// setMessage(`Game Over, you Lost. The correct number was ${winningNum}.`, 'red');
gameOver(false, `Game Over, you Lost. The correct number was ${winningNum}.`)
} else{
// Game continues - answer wrong
// Change border color
guessInput.style.borderColor = 'red';
// Clear the input
guessInput.value = '';
// Tell user it's the wrong number
setMessage(`${guess} is not correct, ${guessesLeft} guesses left`, 'red');
}
}
});
// Game Over
function gameOver(won, msg){
let color;
won === true ? color = 'green' : color = 'red' ;
// Disable Input
guessInput.disabled = true;
// Change border color
guessInput.style.borderColor = color;
// Set Text Color
message.style.color = color;
// Set Message
setMessage(msg);
// Play Again?
guessBtn.value = 'Play Again';
guessBtn.className += 'play-again';
}
// Get winning number
function getRandomNum(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
// Set message
function setMessage(msg , color){
message.style.color = color;
message.textContent = msg;
}
|
import { useVariableValue } from './useVariableValue'
import { render, screen } from '@testing-library/react'
import nock from 'nock'
import {
useDevCycleClient,
useIsDevCycleInitialized,
withDevCycleProvider,
} from '.'
import { mockConfig } from '../mockData/mockConfig'
jest.unmock('@devcycle/js-client-sdk')
describe('useVariableValue', () => {
const Component = () => {
const variableValue = useVariableValue('string-var', 'Hello')
return <div>Variable Value: {variableValue}</div>
}
const TestApp = () => {
const isReady = useIsDevCycleInitialized()
const dvcClient = useDevCycleClient()
const identifyUser = () => {
dvcClient.identifyUser({ user_id: 'identified_user' })
}
if (!isReady) {
return <div>Loading...</div>
}
return (
<>
<button onClick={identifyUser}>Identify User</button>
<Component />
<Component />
<Component />
</>
)
}
it(
'should re-render all components that call useVariableValue with ' +
'the same variable key when an update occurs',
async () => {
const scope = nock('https://sdk-api.devcycle.com/v1')
scope
.defaultReplyHeaders({
'access-control-allow-origin': '*',
})
.get('/sdkConfig')
.query((query) => query.user_id === 'test_user')
.reply(200, mockConfig)
.persist()
const updatedConfig = {
...mockConfig,
variables: {
'string-var': {
_id: '63633c566cf0fcb7e2123456',
key: 'string-var',
type: 'String',
value: 'Hola',
},
},
}
scope
.defaultReplyHeaders({
'access-control-allow-origin': '*',
})
.get('/sdkConfig')
.query((query) => query.user_id === 'identified_user')
.reply(200, updatedConfig)
.persist()
const App = withDevCycleProvider({
user: { user_id: 'test_user' },
sdkKey: 'dvc_test_key',
})(TestApp)
render(<App />)
expect(
await screen.findAllByText('Variable Value: Bonjour'),
).toHaveLength(3)
screen.getByText('Identify User').click()
expect(
await screen.findAllByText('Variable Value: Hola'),
).toHaveLength(3)
},
)
})
|
import axios from "axios";
import { useEffect, useState } from "react";
import './style.css'
import { Link ,useNavigate } from "react-router-dom";
function Signup() {
const [email, setEmail] = useState("");
const [password, setPass] = useState("");
const [name, setName] = useState("");
const [surname, setSurname] = useState("");
const [phonenumber, setPhone] = useState("");
const navigation=useNavigate()
async function register(event) {
event.preventDefault();
await axios.post("https://localhost:7030/api/UserAuth/register", {
email: email,
password: password,
name: name,
surname: surname,
phonenumber:phonenumber
}).then((result)=>{
if (result.data == 'Failed') {
//
alert("Kayıt başarısız Tekrar deneyin");
setEmail("");
setPass("");
setName("");
setSurname("");
setPhone("");
}
else if(result.data=="Email"){
alert("Bu email kullanılmakta başka bir mail giriniz");
}
else{
alert("Kayıt Başarılı");
navigation('/')
}
});
}
return(
<div className="login template d-flex justify-content-center align-items-center vh-100 bg-primary">
<div className="form_container p-5 rounded bg-white">
<form>
<h3 className="text-center">Kaydol</h3>
<div>
<label htmlFor="email">Email</label>
<input type="email" placeholder="E-mail Giriniz" className="form-control"
value={email}
onChange={(event) => {
setEmail(event.target.value);
}}></input>
</div>
<div>
<label htmlFor="password">Password</label>
<input type="password" placeholder="Şifreyi Giriniz" className="form-control"
value={password}
onChange={(event) => {
setPass(event.target.value);
}}></input>
</div>
<div>
<label htmlFor="name">İsim</label>
<input type="name" placeholder="İsim Giriniz" className="form-control"
value={name}
onChange={(event) => {
setName(event.target.value);
}}></input>
</div>
<div>
<label htmlFor="surname">Soyisim</label>
<input type="surname" placeholder="Soyisim Giriniz" className="form-control"
value={surname}
onChange={(event) => {
setSurname(event.target.value);
}}></input>
</div>
<div>
<label htmlFor="phonenumber">Telefon Numarası</label>
<input type="phonenumber" placeholder="Telefon No Giriniz" className="form-control"
value={phonenumber}
onChange={(event) => {
setPhone(event.target.value);
}}></input>
</div>
<div className="d-grid">
<button className="btn btn-primary"onClick={register}>Kaydol</button>
</div>
<p className="text-end mt-2">
<Link to="/" className="ms-2">Giriş Yap</Link>
</p>
</form>
</div>
</div>
)
}
export default Signup
|
<?xml version="1.0" encoding="utf-8"?>
<fig:template xmlns:fig="http://figdice.org/">
<!-- Open the output file and locate where this <ul> is:
You can see that it has 3 <li> items. This is because
we loop over the 3 top-level elements of the "indexed" array.
-->
<ul>
<!-- The loop is realized by the fig:walk directive.
The value of this attribute is an expression evaluating
to the data you mounted into the view.
The data is an indexed array whose items are
associative arrays, all of them having the "name" and "link"
keys.
Here we use the "link" value inside an inline HTML attribute,
with the { } notation (because it is an HTML attribute, the
string it contains is unparsed, apart from the sections within { }
which are treated as normal FigDice Expressions).
The "name" key is used as the inner content of a <a> inner tag.
-->
<li fig:walk="/indexed"><a href="{link}" fig:text="name"></a></li>
</ul>
<!-- We have seen that, from within a fig:walk loop,
the engine gives you direct access to the property of the current
item, in each iteration. This is similar to a
foreach($collection as $item) statement,
where the $item is understated and does not have to be explicity
mentioned inside the loop, in order to access its properties.
In FigDice, this is called the "Context".
We will see in further tutorials how to access properties that are
outside your context anyway.
-->
<!-- In the following section, we perform a nested loop:
our data structure is a collection of rows, and each row has
three cells.
It is perfectly valid to operate a fig:walk INSIDE an outer fig:walk,
so as to loop over the inner collection (the cells).
-->
<table>
<tr fig:walk="/nested">
<!-- First loop: the context is a row. We can access the properties of
the row (its name, and its collection of cells (the "values" array). -->
<td fig:text="name"></td>
<!-- Here we use a special built-in function: "position()".
This function is meaningful solely from withing a fig:walk iteration,
and it returns the 1-based number of the current iteration. -->
<td>Row #<span fig:mute="true" fig:text="position()" /></td>
<!-- Let's go for the inner loop: we will iterate on the "values" array
of each row item, thus changing the Context, from the row to
individual cell. -->
<!-- Each cell is, in turn, a scalar value! In order to display it,
we use the dot symbol, which means "the current item", whatever it is. -->
<td fig:walk="values" fig:text="."></td>
</tr>
</table>
</fig:template>
|
// 观察者,等待被触发
interface ObserverInterface {
update(msg: string): void;
}
// 主题,接收状态变化,触发每个观察者
interface SubjectInterface {
observers: ObserverInterface[];
addObserver(observer: ObserverInterface): void;
removeObserver(observer: ObserverInterface): void;
notifyObservers(msg: string): void;
}
// 主题,接收状态变化,触发每个观察者
class ConcreteSubject implements SubjectInterface {
observers: ObserverInterface[] = [];
state: object = {};
addObserver(observer: ObserverInterface): void {
this.observers.push(observer);
}
removeObserver(observer: ObserverInterface): void {
const index = this.observers.findIndex((val) => val === observer);
if (index > -1) {
this.observers.splice(index, 1);
}
}
notifyObservers(msg: string): void {
this.observers.forEach((observer) => observer.update(msg));
}
change(name: string, value: string): void {
this.state[name] = value;
console.log(`${name}状态更新为:${value}`);
console.log("通知所有观察者");
this.notifyObservers("状态更新");
}
}
// 观察者,等待被触发
class ConcreteObserver implements ObserverInterface {
name: string;
constructor(name: string) {
this.name = name;
}
update(msg: string): void {
console.log(`${this.name} update ${msg}`);
}
}
// 使用
const subject = new ConcreteSubject();
const ob1 = new ConcreteObserver("ob1");
const ob2 = new ConcreteObserver("ob2");
subject.addObserver(ob1);
subject.addObserver(ob2);
subject.change("天气", "多云");
subject.removeObserver(ob2);
subject.change("天气", "晴");
|
interface ComplexBeanDependency {
dependencyName: string;
beanClass: any;
}
type BeanDependency = string | ComplexBeanDependency;
interface BeanDefinition {
beanName: string;
beanClass: any;
dependencies: BeanDependency[];
}
interface ResolvedDependency {
name: string;
value: any;
}
export class ApplicationContext {
private context = new Map<string, any>();
private beanDefinitions = new Map<string, BeanDefinition>();
addBeanDefinition(beanName: string, beanClass: any, dependencies: BeanDependency[]) {
this.beanDefinitions.set(beanName, {
beanName,
beanClass,
dependencies
});
}
getBeanByName<T>(beanName: string): T {
if (this.context.has(beanName)) {
return this.context.get(beanName);
} else {
const bean = this.createBean<T>(beanName);
if (bean !== null) {
this.context.set(beanName, bean);
return bean;
} else {
throw Error(`No bean with name '${beanName}'`);
}
}
}
private resolveDependency(dependency: BeanDependency): ResolvedDependency {
if (typeof dependency === "string") {
return {name: dependency, value: this.getBeanByName(dependency as string)};
} else {
return {name: dependency.dependencyName, value: this.getBeansByClass(dependency.beanClass)};
}
}
getBeansByClass(type: any): any[] {
const beans: any[] = [];
for (const [name, definition] of this.beanDefinitions) {
if (type.isPrototypeOf(definition.beanClass)) {
beans.push(this.getBeanByName(name));
}
}
return beans;
}
private createBean<T>(beanName: string): T {
if (!this.beanDefinitions.has(beanName)) {
throw new Error(`No bean definition found for '${beanName}'`);
}
const {beanClass, dependencies} = this.beanDefinitions.get(beanName) as BeanDefinition;
const dependenciesArg = dependencies.map(dependency => this.resolveDependency(dependency))
.reduce((accumulator, currentValue) => ({
...accumulator,
[currentValue.name]: currentValue.value
}), {} as any);
return new beanClass(dependenciesArg);
}
}
|
import React from 'react';
import { Row, Col, Dropdown, Button } from 'react-bootstrap';
import { Routes } from 'constants/Routes';
import { Rating } from '@material-ui/lab';
import { toast } from 'react-toastify';
import noBranchImg from 'images/noBranchImg.png';
import { CallAPI } from 'utils/API/APIConfig';
import { SP_GET_OWNER_BRANCHES } from 'utils/API/EndPoints/BranchManager';
import { useHistory } from 'react-router-dom';
import { useIntl } from 'react-intl';
import TableLoader from 'components/shared/TableLoader';
export default function BranchesAll() {
const history = useHistory();
const { messages } = useIntl();
const { isLoading, data } = CallAPI({
name: 'getbranchInfoAll',
url: SP_GET_OWNER_BRANCHES,
refetchOnWindowFocus: true,
enabled: true,
select: (res) => res?.data?.data,
onError: (err) => toast.error(err?.response?.data?.error?.message),
});
return (
<>
<Row className="branch-header">
<Col className="components">
<div>
<p className="title">{messages['branches.all']}</p>
<p className="title-info">{messages['branches.all.info']}</p>
</div>
<div className="actionsDiv">
<button
type="button"
className="btn btn-grey"
onClick={() => {
history.push(Routes.changeOwnerPhone);
}}
>
{messages['branches.display.branches.change.owner']}
</button>
<button
onClick={() => history.push(Routes.settingAllBrsanchesAdd)}
type="button"
className="btn btn-primary"
>
{messages['branches.add.new']}
</button>
</div>
</Col>
</Row>
<Row className="branch-body">
{!isLoading &&
data?.list?.length > 0 &&
data?.list?.map((branch) => (
<Col lg={4} md={12} key={branch.branchId}>
<div className="card branch-body__card">
{branch?.bannerImage ? (
<img
className="branch-body__card--salonImg"
src={branch.bannerImage}
alt={branch.name}
/>
) : (
<img
src={noBranchImg}
className="branch-body__card--salonImg"
alt={branch.name}
/>
)}
<div className="card-body branch-body__card--bodyCard">
<div className="d-flex justify-content-between showActionsDiv">
<div className="d-flex">
<Rating
name="read-only"
className="branch-body__card--bodyCard__rating"
value={branch.rating}
precision={0.5}
readOnly
/>
<span className="px-2">{branch.rating || 0}</span>
</div>
<Dropdown
id="dropdown-menu-align-end"
className="showMore"
drop="start"
>
<Dropdown.Toggle
className="showMore--btn"
id="dropdown-autoclose-true"
>
<i className="flaticon-more" />
</Dropdown.Toggle>
<Dropdown.Menu className="showMore--dropdown">
<Dropdown.Item
as={Button}
eventKey="1"
onClick={() => {
history.push(Routes.changeManager);
localStorage.setItem(
'selectedBranches',
JSON.stringify([branch.branchId]),
);
}}
>
{messages['branches.add.branch.change.manager.title']}
</Dropdown.Item>
{/* <Dropdown.Item as={Button} eventKey="2">
{messages['branches.display.branches.delete.branch']}
</Dropdown.Item> */}
</Dropdown.Menu>
</Dropdown>
</div>
<h5 className="branch-body__card--bodyCard__name">{branch.name}</h5>
<p className="branch-body__card--bodyCard__address">
{branch.address || messages['branches.display.branches.address']}
</p>
<h6 className="branch-body__card--bodyCard__name">
{messages['branches.branch.manager']}
</h6>
<div className="d-flex justify-content-between">
<p className="branch-body__card--bodyCard__address">
{branch.managerName}
</p>
<p className="branch-body__card--bodyCard__address">
{branch.mobileNumber}
</p>
</div>
</div>
</div>
</Col>
))}
<Col className="d-flex justify-content-center">
{(data?.list?.length === 0 || isLoading) && (
<TableLoader colSpan="2" noData={!isLoading} />
)}
</Col>
</Row>
</>
);
}
|
#include <Python.h>
#include <Windows.h>
PyDoc_STRVAR(winDocs, "Shutdown(condition) - Shut down the device, condition is logged by the system\nRestart(condition) - Restart the device, condition is logged by the system\nLogOut(condition) - Logs out the user from the device, condition is logged by the system\n\nMajor flags:\n\nSHTDN_REASON_MAJOR_APPLICATION: Application issue\nSHTDN_REASON_MAJOR_HARDWARE: Hardware issue\nSHTDN_REASON_MAJOR_OPERATINGSYSTEM: Operating system issue\nSHTDN_REASON_MAJOR_OTHER: Other issue\nSHTDN_REASON_MAJOR_POWER: Power failure\nSHTDN_REASON_MAJOR_SOFTWARE: Software issue\nSHTDN_REASON_MAJOR_SYSTEM: System failure\n\nMinor flags:\n\nSHTDN_REASON_MINOR_BLUESCREEN: Blue screen crash event.\nSHTDN_REASON_MINOR_CORDUNPLUGGED: Unplugged\nSHTDN_REASON_MINOR_DISK: Disk\nSHTDN_REASON_MINOR_ENVIRONMENT: Environment\nSHTDN_REASON_MINOR_HARDWARE_DRIVER: Driver\nSHTDN_REASON_MINOR_HOTFIX: Hot Fix\nSHTDN_REASON_MINOR_HOTFIX_UNINSTALL: Hot fix uninstallation\nSHTDN_REASON_MINOR_HUNG: Unresponsive\nSHTDN_REASON_MINOR_INSTALLATION: Installation\nSHTDN_REASON_MINOR_MAINTENANCE: Maintenance\nSHTDN_REASON_MINOR_MMC: MMC issue\nSHTDN_REASON_MINOR_NETWORK_CONNECTIVITY: Network connectivity.\nSHTDN_REASON_MINOR_NETWORKCARD: Network card\nSHTDN_REASON_MINOR_OTHER: Other issue\nSHTDN_REASON_MINOR_OTHERDRIVER: Other driver event\nSHTDN_REASON_MINOR_POWER_SUPPLY: Power supply\nSHTDN_REASON_MINOR_PROCESSOR: Processor\nSHTDN_REASON_MINOR_RECONFIG: Reconfigure\nSHTDN_REASON_MINOR_SECURITY: Secuity issue\nSHTDN_REASON_MINOR_SECURITYFIX: Security patch\nSHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL: Security patch uninstallation\nSHTDN_REASON_MINOR_SERVICEPACK: Service pack\nSHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL: Service pack uninstallation\nSHTDN_REASON_MINOR_TERMSRV: Terminal services\nSHTDN_REASON_MINOR_UNSTABLE: Unstable\nSHTDN_REASON_MINOR_UPGRADE: Upgrade\nSHTDN_REASON_MINOR_WMI: WMI issue\n\nAdditional flags (optional):\n\nSHTDN_REASON_FLAG_USER_DEFINED: The reason code is defined by the user. If this flag is not present, the reason code is defined by the system\nSHTDN_REASON_FLAG_PLANNED:The shutdown was planned. The system generates a System State Data (SSD) file. This file contains system state information such as the processes, threads, memory usage, and configuration.If this flag is not present, the shutdown was unplanned.Notification and reporting options are controlled by a set of policies.For example, after logging in, the system displays a dialog box reporting the unplanned shutdown if the policy has been enabled.An SSD file is created only if the SSD policy is enabled on the system\n\n See https://msdn.microsoft.com/en-us/library/aa376885(v=vs.85).aspx");
static PyObject * sys_shutdown(PyObject *self, PyObject *args) {
int val;
if (!PyArg_ParseTuple(args, "i", &val))
return NULL;
ExitWindowsEx(EWX_POWEROFF, val); // Shutdown
return Py_BuildValue(""); // Return nothing
}
static PyObject * sys_restart(PyObject *self, PyObject *args) {
int val;
if (!PyArg_ParseTuple(args, "i", &val))
return NULL;
ExitWindowsEx(EWX_REBOOT, val); // Restart
return Py_BuildValue(""); // Return nothing
}
static PyObject * sys_log_out(PyObject *self, PyObject *args) {
int val;
if (!PyArg_ParseTuple(args, "i", &val))
return NULL;
ExitWindowsEx(EWX_LOGOFF, val); // Log out
return Py_BuildValue(""); // Return nothing
}
static PyMethodDef localMethods[] = {
{ "Shutdown", (PyCFunction)sys_shutdown, METH_VARARGS, "Shuts down the device. Requires one argument to be logged by the system"}, // Shutdown
{ "Restart", (PyCFunction)sys_restart, METH_VARARGS, "Restarts the device. Requires one argument to be logged by the system"}, // Restart
{ "LogOut", (PyCFunction)sys_log_out, METH_VARARGS, "Logs the user out of the device. Requires one argument to be logged by the system" }, // Log out
{ NULL, NULL, 0, NULL }
};
static struct PyModuleDef func = {
PyModuleDef_HEAD_INIT,
"WinUtils",
winDocs,
-1,
localMethods,
};
PyMODINIT_FUNC PyInit_WinUtils(void) {
PyObject *module = PyModule_Create(&func); // Create module
// Major flags:
PyModule_AddIntMacro(module, SHTDN_REASON_MAJOR_APPLICATION);
PyModule_AddIntMacro(module, SHTDN_REASON_MAJOR_HARDWARE);
PyModule_AddIntMacro(module, SHTDN_REASON_MAJOR_OPERATINGSYSTEM);
PyModule_AddIntMacro(module, SHTDN_REASON_MAJOR_OTHER);
PyModule_AddIntMacro(module, SHTDN_REASON_MAJOR_POWER);
PyModule_AddIntMacro(module, SHTDN_REASON_MAJOR_SOFTWARE);
PyModule_AddIntMacro(module, SHTDN_REASON_MAJOR_SYSTEM);
// Minor flags:
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_BLUESCREEN);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_CORDUNPLUGGED);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_DISK);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_ENVIRONMENT);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_HARDWARE_DRIVER);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_HOTFIX);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_HOTFIX_UNINSTALL);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_HUNG);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_INSTALLATION);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_MAINTENANCE);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_MMC);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_NETWORKCARD);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_OTHER);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_OTHERDRIVER);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_POWER_SUPPLY);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_PROCESSOR);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_RECONFIG);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_SECURITY);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_SECURITYFIX);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_SERVICEPACK);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_TERMSRV);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_UNSTABLE);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_UPGRADE);
PyModule_AddIntMacro(module, SHTDN_REASON_MINOR_WMI);
// Optional flags
PyModule_AddIntMacro(module, SHTDN_REASON_FLAG_USER_DEFINED);
PyModule_AddIntMacro(module, SHTDN_REASON_FLAG_PLANNED);
return module;
}
|
## Copyright (C) 2016 Hani Andreas Ibrahim
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see <http://www.gnu.org/licenses/>.
% SampleStatDemo is a demo script for the samplestat.m functions
%
% - strayarea.m
% - trustarea.m
%
% Core functions as mean(), std(), min() and max() are also used.
% Author: Hani Andreas Ibrahim <hani.ibrahim@gmx.de>
% License: GPL 3.0
% Sample data
v = [ ...
9.999; ...
9.998; ...
10.002; ...
10.000; ...
10.001; ...
10.000 ...
];
% Statistical confidence level
p = "95%";
% Calculate statistical results
n = length(v); % Number of values
x = mean(v); % Arithmetic mean
s = std (v); % Standard deviation
sa = strayarea(v, p); % Range of dispersion of the values (stray area)
ta = trustarea(v, p); % Range of dispersion of the mean (trust area)
mi = min(v); % Minimal value
ma = max(v); % Maximal value
% Output
fprintf("SampleStatDemo - Demo script 'Statistics for Sampling Distributions'\n\n");
fprintf("Values:\n");
disp(v); % Display data
fprintf("\n"); % blank line
fprintf("\
Number of Values : %i\n\
Arithmetic Mean : %g\n\
Standard Deviation (S.D.) : %g\n\
Confidence Level : %s\n\
Range of Dispersion (values): %g\n\
Range of Dispersion (mean) : %g\n\
Minimum : %g\n\
Maximum : %g\n\
", n, x, s, p, sa, ta, mi, ma);
fprintf("\n"); % blank line
fprintf("\
68 percent of the values will stray arount %g +- %g (S.D.). %s of the values \
will be expected around %g +/- %g (Range of disp. of the values, stray area). \
With a propability of %s the mean of %g will stray around %g +/- %g (Rage of \
dispersion of the mean, trust area).\n", x, s, p, x, sa, p, x, x, ta);
clear;
|
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include "lists.h"
/**
* add_node - Adds a new node at the
* beginning of a list_t list.
* @head: A pointer to a pointer to
* the head of the list.
* @str: The string to be added as the data
* of the new node.
* Return: The address of the new element,
* or NULL if it fails.
*/
list_t *add_node(list_t **head, const char *str)
{
list_t *new_node;
if (str == NULL)
{
return (NULL);
}
new_node = malloc(sizeof(list_t));
if (new_node == NULL)
{
return (NULL);
}
new_node->str = strdup(str);
if (new_node->str == NULL)
{
free(new_node);
return (NULL);
}
new_node->len = strlen(str);
new_node->next = *head;
*head = new_node;
return (new_node);
}
|
package com.example.btlmobile.adapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.btlmobile.R;
import com.example.btlmobile.model.Vocabulary;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class LearnWordAdapter extends RecyclerView.Adapter<LearnWordAdapter.LearnWordViewHolder> {
private List<Vocabulary> listVocab,practiceWord;
private ItemPracticeWordListener itemPracticeWordListener;
private boolean isOnTextChange = false;
public void setItemPracticeWordListener(ItemPracticeWordListener itemPracticeWordListener) {
this.itemPracticeWordListener = itemPracticeWordListener;
}
public List<Vocabulary> getListVocab() {
return listVocab;
}
public List<Vocabulary> getPracticeWord() {
return practiceWord;
}
public String checkSubmit(){
int cnt = 0;
for(int i = 0 ; i < listVocab.size();i++){
System.out.println(listVocab.get(i).toString());
System.out.println(practiceWord.get(i).toString());
if(listVocab.get(i).equals(practiceWord.get(i))){
cnt ++;
}
}
return String.valueOf(cnt);
}
public void setListVoca(List<Vocabulary> list) {
listVocab = new ArrayList<>();
practiceWord = new ArrayList<>();
for(Vocabulary v : list){
listVocab.add(v);
}
for(Vocabulary v : list){
Vocabulary vocabulary = new Vocabulary(v.getId(),v.getWord(),v.getMeaning(),v.getType(),v.getAccent(),v.getImage(),v.getSentence());
practiceWord.add(vocabulary);
}
System.out.println(listVocab.size());
notifyDataSetChanged();
}
public void setVocabPractiveWordType(String type,int position){
practiceWord.get(position).setType(type);
}
public void setVocabPractiveWordMeaning(String meaning,int id){
for(Vocabulary v : practiceWord){
if(v.getId() == id){
v.setMeaning(meaning);
break;
}
}
}
@NonNull
@Override
public LearnWordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.learnword_item,parent,false);
return new LearnWordViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull LearnWordViewHolder holder, int position) {
Vocabulary vocabulary = listVocab.get(position);
holder.text_view_word.setText(vocabulary.getWord());
holder.edit_text_meaning.setText("");
holder.sp.setSelection(0);
holder.edit_text_meaning.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
isOnTextChange = true;
}
@Override
public void afterTextChanged(Editable editable) {
if(isOnTextChange){
isOnTextChange = false;
setVocabPractiveWordMeaning(editable.toString(),vocabulary.getId());
}
}
});
// int p = 0;
// for(int i = 0 ; i < holder.sp.getCount(); i++){
// if(holder.sp.getItemAtPosition(i).toString().equalsIgnoreCase(vocabulary.getType())){
// p = i;
// break;
// }
// }
holder.sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
setVocabPractiveWordType(adapterView.getItemAtPosition(i).toString(),position);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public int getItemCount() {
return listVocab.size();
}
public class LearnWordViewHolder extends RecyclerView.ViewHolder{
private TextView text_view_word;
private EditText edit_text_meaning;
private Spinner sp;
public LearnWordViewHolder(@NonNull View itemView) {
super(itemView);
text_view_word = itemView.findViewById(R.id.word);
edit_text_meaning = itemView.findViewById(R.id.meaning);
sp = itemView.findViewById(R.id.spinner_learnword);
sp.setAdapter(new ArrayAdapter<String>(itemView.getContext(), R.layout.item_spinner,itemView.getResources().getStringArray(R.array.type)));
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(itemPracticeWordListener != null){
itemPracticeWordListener.onItemPracticeWordClick(view,getAdapterPosition());
}
}
});
}
}
public interface ItemPracticeWordListener{
void onItemPracticeWordClick(View view, int position);
}
}
|
<?php
/**
* Created by PhpStorm.
* User: Vincent Shu
* Date: 1/31/2019
* Time: 5:27 PM
*/
namespace Wumpus;
class WumpusView
{
/**
* Constructor
* @param Wumpus $wumpus The Wumpus object
*/
public function __construct(Wumpus $wumpus) {
$this->wumpus = $wumpus;
}
/**
* Generate the HTML for the number of arrows remaining
* @return string HTML
*/
public function presentArrows() {
$a = $this->wumpus->numArrows();
return "<p>You have $a arrows remaining.</p>";
}
public function presentStatus() {
$room = $this->wumpus->getCurrent()->getNum();
$html = <<<HTML
<p id="first">You are in room $room</p>
HTML;
if($this->wumpus->hearBirds()) {
$html .= '<p>You hear birds!</p>';
}
if($this->wumpus->feelDraft()) {
$html .= '<p>You feel a draft!</p>';
}
if($this->wumpus->smellWumpus()) {
$html .= '<p>You smell a wumpus!</p>';
}
if($this->wumpus->wasCarried()) {
$html .= "<p>You were carried by the birds to room $room!</p>";
}
return $html;
}
/**
* Present the links for a room
* @param int $ndx An index 0 to 2 for the three rooms
* @return string HTML
*/
public function presentRoom($ndx) {
$room = $this->wumpus->getCurrent()->getNeighbors()[$ndx];
$roomnum = $room->getNum();
$roomndx = $room->getNdx();
$roomurl = "game-post.php?m=$roomndx";
$shooturl = "game-post.php?s=$roomndx";
$html = <<<HTML
<div class="room">
<figure><img src="cave2.jpg" width="180" height="135" alt=""/></figure>
<p class="number"><a href="$roomurl">$roomnum</a></p>
<p><a href="$shooturl">Shoot Arrow</a></p>
</div>
HTML;
return $html;
}
public function newGame(){
$newgame = "game-post.php?n";
$html = <<<HTML
<p class="operation"><a href="$newgame">Start Game</a></p>
HTML;
}
private $wumpus; // The Wumpus object
}
|
import React from "react";
import styled from "@emotion/styled";
import { useTheme } from "next-themes";
const TopBar: React.FC = () => {
const { theme, setTheme } = useTheme();
return (
<Container>
<Avatar
onClick={() => {
setTheme(theme === "light" ? "dark" : "light");
}}
/>
</Container>
);
};
export default TopBar;
const Container = styled.div`
display: flex;
justify-content: flex-end;
padding: 0.5rem;
align-items: center;
background-color: #333333;
height: 4rem;
`;
const Avatar = styled.div`
max-height: 3rem;
height: 100%;
aspect-ratio: 1;
border-radius: 200px;
//opacity: 0.2;
transition: opacity;
transition-duration: 150ms;
// ${({ theme }) => theme.md} {
// opacity: 1;
// }
background-color: ${(props) => props.theme.colors.text.primary.enabled};
`;
|
import { Component, ViewChild } from '@angular/core';
import { SpreadsheetComponent } from '@syncfusion/ej2-angular-spreadsheet';
import { enableRipple } from '@syncfusion/ej2-base';
import { dataSource } from './datasource';
enableRipple(true);
@Component({
selector: 'app-container',
template: `<ejs-spreadsheet #spreadsheet (created)="created()" [showFormulaBar]="false"
[showSheetTabs]="false">
<e-sheets>
<!-- Hiding the headers and gridlines in 'Price Details' sheet -->
<e-sheet [showGridLines]="false" [showHeaders]="false">
<e-ranges>
<e-range [dataSource]="data"></e-range>
</e-ranges>
<e-columns>
<e-column [width]=150></e-column>
<e-column [width]=110></e-column>
<e-column [width]=110></e-column>
<e-column [width]=85></e-column>
<e-column [width]=85></e-column>
<e-column [width]=85></e-column>
<e-column [width]=85></e-column>
<e-column [width]=85></e-column>
</e-columns>
</e-sheet>
</e-sheets>
</ejs-spreadsheet>`
})
export class AppComponent {
@ViewChild('spreadsheet')
spreadsheetObj: SpreadsheetComponent | undefined;
data: object[] = dataSource;
created() {
this.spreadsheetObj!.cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'A1:H1');
this.spreadsheetObj!.cellFormat({ textAlign: 'center' }, 'D2:H11');
// The gridlines have been removed to set border for the range of cells
this.spreadsheetObj!.setBorder({ border: '1px solid #e0e0e0' }, 'A1:H11');
}
}
|
#' ELATUS workflow
#' This workflow loads the Kallisto and CellRanger raw count matrices, performs emptydrops, then doublet removal, a quality control filtering. Next it gets the highly expressed lncRNAs only detected by Kallisto and the ratio of their expression between Kallisto/CellRanger and finally, after normalization and clustering it calculates the Specificity Index of each of them. The last step is generating the list of biologically relevant lncRNAs. In addition it identifies highly-expressed lncRNAs exclusively detected by Kallisto whose functionality has been proven by external biobliography (CRISPR screenings...) and those highly-expressed lncRNAs robustly detected by both Cell Ranger and Kallisto.
#' @param kallisto_path Path to the Kallisto raw count matrix (As an example: kallisto_path=system.file("extdata", "kallisto_example_raw_matrix", package = "ELATUS"))
#' @param kallisto_name Name of the Kallisto raw count matrix (As an example kallisto_name="cells_genes_NO_multimapping")
#' @param cellRanger_path Path to the CellRanger raw count matrix (As an example :cellRanger_path=system.file("extdata", "cellRanger_example_raw_matrix", package = "ELATUS"))
#' @param organism Human or Mouse dataset (for the example "Mouse")
#' @param lower_emptydrops A numeric scalar specifying the lower bound on the total UMI count, at or below which all barcodes are assumed to correspond to empty droplets. For the example, 1000
#' @param EmptyDrops_FDR_thres FDR threshold to classifly empty droplets (For the example, 0.01)
#' @param cells_mito_threshold Mitochondrial content (%) threshold. Keep cells with less mitocondrial content than the defined threshold (For the example = 15)
#' @param cells_max_threshold Keep cells with less counts than the defined threshold (For the example = 30000)
#' @param cells_min_genes_detected_threshold Keep cells with counts in more genes than the defined threhold (For the example = 500)
#' @param threshold_minumun_gene_counts Select genes with more than this total counts (For the paper = 250 counts)
#' @param threshold_cells_detected Select genes present in at least a number of cells higher than this threshold (For the paper = 25)
#' @param dimred_clustering dimensionality reduction (For the example "PCA")
#' @param k_neighbors the number of nearest neighbors used to construct the graph. Choose a smaller k to more but smaller clusters as lncRNAs tend to be expressed in small subpopulations. (in this example, k=5)
#' @param ratio_threshold Threshold to remove lncRNAs whose ratio of expression between Kallisto and CellRanger is smaller than this defined threshold (For the paper = 40)
#' @param CR_threshold Threshold to remove lncRNAs that have a CellRanger expression higher than this defined threshold (For the paper = 10)
#' @param SI_threshold Threshold to remove lncRNAs whose SI is smaller than this defined threshold (For the paper = 0.15)
#' @return A list with most biologically relevant lncRNAs
#' @export
ELATUS <- function(kallisto_path, kallisto_name, cellRanger_path, organism, lower_emptydrops, EmptyDrops_FDR_thres, cells_mito_threshold, cells_max_threshold, cells_min_genes_detected_threshold, threshold_minumun_gene_counts, threshold_cells_detected, dimred_clustering, k_neighbors, ratio_threshold, CR_threshold, SI_threshold)
{
if (organism == "Human")
{
gencode_path <- system.file("extdata", "hg38_v37.rds", package = "ELATUS")
}
if (organism == "Mouse")
{
gencode_path <- system.file("extdata", "mm10_vM27.rds", package = "ELATUS")
}
crispr_data <- readRDS(system.file("extdata", "hits_info_Liu_science_2015_ensids.rds", package = "ELATUS"))
gtf <- readRDS(gencode_path)
gtf$gene_id <- gsub("_","-",gtf$gene_id)
mitochondrial_ens_ids <- unique(gtf$gene_id[grep("^MT-",gtf$gene_name)])
lncrna_ens_ids <- unique(c(gtf$gene_id[grep("lncRNA",gtf$gene_type)]))
protein_coding_ens_ids <- unique(c(gtf$gene_id[gtf$gene_type=="protein_coding"]))
lncrna_names <- unique(gtf$gene_name[gtf$gene_id %in% lncrna_ens_ids])
protein_coding_names <- unique(gtf$gene_name[gtf$gene_id %in% protein_coding_ens_ids])
kallisto <- import_kallisto_sc(kallisto_path, kallisto_name)
kallisto <- Seurat::as.SingleCellExperiment(kallisto)
kallisto_sce <- qc_metrics(kallisto, mitochondrial_ens_ids)
cellRanger <- import_CellRanger_sc(cellRanger_path)
cellRanger <- Seurat::as.SingleCellExperiment(cellRanger)
cellRanger_sce <- qc_metrics(cellRanger, mitochondrial_ens_ids)
#EmptyDrops filtering
#for the example given (human PBMCs) the parameters are lower_emptydrops=1000 & EmptyDrops_FDR_thres = 0.01
kallisto_filt_sce_ed <- emptydrops_filt(kallisto_sce, lower = lower_emptydrops, EmptyDrops_FDR_thres = EmptyDrops_FDR_thres)
cellRanger_filt_sce_ed <- emptydrops_filt(cellRanger_sce, lower = lower_emptydrops, EmptyDrops_FDR_thres = EmptyDrops_FDR_thres)
# Remove doublets
kallisto_filt_sce_ed_nodoubs <- remove_doublets(kallisto_filt_sce_ed)
kallisto_filt_sce_ed_nodoubs <- kallisto_filt_sce_ed_nodoubs[,kallisto_filt_sce_ed_nodoubs$isDoublet == F]
cellRanger_filt_sce_ed_nodoubs <- remove_doublets(cellRanger_filt_sce_ed)
cellRanger_filt_sce_ed_nodoubs <- cellRanger_filt_sce_ed_nodoubs[,cellRanger_filt_sce_ed_nodoubs$isDoublet == F]
# Filtering (The following thresholds have been used. cells_mito_threshold=15, cells_max_threshold= 50000, cells_min_genes_detected_threshold = 500)cells_mito_threshold, cells_max_threshold, cells_min_genes_detected_threshold
kallisto_filt_sce <- Filtering(kallisto_filt_sce_ed_nodoubs, cells_mito_threshold=cells_mito_threshold, cells_max_threshold= cells_max_threshold, cells_min_genes_detected_threshold = cells_min_genes_detected_threshold)
kallisto_filt_sce <- scuttle::logNormCounts(kallisto_filt_sce)
cellRanger_filt_sce <- Filtering(cellRanger_filt_sce_ed_nodoubs, cells_mito_threshold=cells_mito_threshold, cells_max_threshold= cells_max_threshold, cells_min_genes_detected_threshold = cells_min_genes_detected_threshold)
cellRanger_filt_sce <- scuttle::logNormCounts(cellRanger_filt_sce)
# Now get the highly expressed lncRNAs only detected by Kallisto and the ratio of their expression between Kallisto/CellRanger. Also get the highly-expressedcommonly detected by Cell Ranger and Kallisto
# uniquifyFeatures
gene_name <- gtf$gene_name[match(rownames(kallisto_filt_sce),gtf$gene_id)]
rownames(kallisto_filt_sce) <- scuttle::uniquifyFeatureNames(rownames(kallisto_filt_sce), gene_name)
gene_name <- gtf$gene_name[match(rownames(cellRanger_filt_sce),gtf$gene_id)]
rownames(cellRanger_filt_sce) <- scuttle::uniquifyFeatureNames(rownames(cellRanger_filt_sce), gene_name)
# We considered highly expressed lncRNAs as those with at least 250 counts in at least 25 cells
top_genes(kallisto_filt_sce,threshold_minumun_gene_counts,threshold_cells_detected)
candidate_lncRNAs_exclusive <- get_candidates(kallisto_filt_sce, cellRanger_filt_sce , threshold_minumun_gene_counts = threshold_minumun_gene_counts, threshold_cells_detected = threshold_cells_detected,lncrna_names = lncrna_names,gtf=gtf)
candidate_lncRNAs_common <- get_candidates(kallisto_filt_sce, cellRanger_filt_sce, threshold_minumun_gene_counts = threshold_minumun_gene_counts, threshold_cells_detected = threshold_cells_detected,lncrna_names = lncrna_names,gtf=gtf, exclusive = F)
# clustering
set.seed(100100100)
kallisto_filt_sce <- scater::runPCA(kallisto_filt_sce)
g <- scran::buildSNNGraph(kallisto_filt_sce, use.dimred = dimred_clustering, k = k_neighbors ) # k is the number of nearest neighbors used to construct the graph. Choose a smaller k to more but smaller clusters as lncRNAs tend to be expressed in small subpopulations. (in this example, k=5). dimred_clustering is the dimensionality reduction (PCA here, but could be the corrected space after integrating samples)
clust <- igraph::cluster_louvain(g)$membership
print(table(clust))
kallisto_filt_sce$louvain_clusters <- factor(clust)
# Calculate the Specificity Index for each gene
SI <- SI(kallisto_filt_sce,group_by="louvain_clusters", average_by="mean")
cell_type_specific_score <- SI[["cell_type_specificity_score"]]
counts_cell_specificity_index <- SI[["counts_cell_specificity_index"]]
candidate_lncRNAs_exclusive$SI <- cell_type_specific_score[rownames(candidate_lncRNAs_exclusive)]
candidate_lncRNAs_common$SI <- cell_type_specific_score[rownames(candidate_lncRNAs_common)]
# To know in which cluster the SI is the highest
candidate_lncRNAs_exclusive$cell_type_SI <- colnames(counts_cell_specificity_index[rownames(candidate_lncRNAs_exclusive),])[apply(counts_cell_specificity_index[rownames(candidate_lncRNAs_exclusive),],1,which.max)]
candidate_lncRNAs_exclusive <- crispr_info(crispr_data, candidate_lncRNAs_exclusive)
candidate_lncRNAs_common$cell_type_SI <- candidate_lncRNAs_common$cell_type_SI <- colnames(counts_cell_specificity_index[rownames(candidate_lncRNAs_common),])[apply(counts_cell_specificity_index[rownames(candidate_lncRNAs_common),],1,which.max)]
# Get the biologically relevant lncRNAs from these candidates (In the paper we used the following parameters: ratio_threshold = 40, CR_threshold = 10, SI_threshold = 0.15)
ratio_threshold = 40
CR_threshold = 10
SI_threshold = 0.15
exclusive_lncRNAs_CRISPRi <- candidate_lncRNAs_exclusive[candidate_lncRNAs_exclusive$crispr_intersection == T,]
exclusive_biologically_relevant_lncRNAs <- biologically_relevant_lncRNAs(candidate_lncRNAs_exclusive, ratio_threshold,CR_threshold,SI_threshold)
candidate_lncRNAs_common$crispr_intersection = "NA"
if (nrow(exclusive_lncRNAs_CRISPRi)>0)
{
exclusive_lncRNAs_CRISPRi$category = "Exclusive_lncRNA_CRISPRi"
}
exclusive_biologically_relevant_lncRNAs$category = "Exclusive_lncRNA"
candidate_lncRNAs_common$category = "Common_lncRNA"
biologically_relevant_lncRNAs <- rbind(exclusive_biologically_relevant_lncRNAs, candidate_lncRNAs_common,exclusive_lncRNAs_CRISPRi)
biologically_relevant_lncRNAs
}
|
<div class="container">
<h2>Update Task</h2>
<form [formGroup]="updateTaskForm">
<mat-form-field appearance="outline" class="form-field">
<mat-label>Title</mat-label>
<input matInput type="text" formControlName="title" placeholder="Title">
<mat-error *ngIf="updateTaskForm.get('title')?.invalid && updateTaskForm.get('title')?.touched">
This input is Required!
</mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="form-field">
<mat-label>Description</mat-label>
<textarea matInput formControlName="description" placeholder="Description" required></textarea>
<mat-error *ngIf="updateTaskForm.get('description')?.invalid && updateTaskForm.get('description')?.touched">
Please enter a valid description.
</mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="form-field">
<mat-label>Due Date</mat-label>
<input matInput [matDatepicker]="dueDatePicker" formControlName="dueDate" placeholder="Choose a due date" required>
<mat-datepicker-toggle matSuffix [for]="dueDatePicker"></mat-datepicker-toggle>
<mat-datepicker #dueDatePicker></mat-datepicker>
<mat-error *ngIf="updateTaskForm.get('dueDate')?.invalid && updateTaskForm.get('dueDate')?.touched">
This input is Required!
</mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="form-field">
<mat-label>Select the Priority</mat-label>
<mat-select formControlName="priority" name="Priority">
<mat-option *ngFor="let priority of listOfPriorities" [value]="priority">{{priority}}</mat-option>
</mat-select>
<mat-error *ngIf="updateTaskForm.get('priority')?.invalid && updateTaskForm.get('priority')?.touched">
This input is Required!
</mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="form-field">
<mat-label>Select the Task Status</mat-label>
<mat-select formControlName="taskStatus" name="taskStatus">
<mat-option *ngFor="let status of tasStatus" [value]="status">{{status}}</mat-option>
</mat-select>
<mat-error *ngIf="updateTaskForm.get('taskStatus')?.invalid && updateTaskForm.get('taskStatus')?.touched">
This input is Required!
</mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="form-field">
<mat-label>Select the Employee</mat-label>
<mat-select formControlName="employeeId" name="employeeId">
<mat-option *ngFor="let employee of listOfEmployees" [value]="employee.id">{{employee.name}}</mat-option>
</mat-select>
<mat-error *ngIf="updateTaskForm.get('employeeId')?.invalid && updateTaskForm.get('employeeId')?.touched">
This input is Required!
</mat-error>
</mat-form-field>
<button mat-raised-button color="primary" type="submit" [disabled]="updateTaskForm.invalid" (click)="updateTask()">Update Task</button>
</form>
</div>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.