text
stringlengths 184
4.48M
|
---|
<!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> University website design -Easy Tutorial </title>
<link rel="stylesheet" href="style.css">
<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=Poppins:wght@100;200;300;400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/fontawesome.min.css">
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.1.0-7/css/all.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<section class="sub-header">
<nav>
<a href="index.html"> <img src="image/logo.png" alt=""></a>
<div class="nav-links" id="navLinks">
<i class="fa fa-times" onclick="hideMenu() "></i>
<ul>
<li> <a href="index.html"> HOME </a></li>
<li> <a href="about.html"> ABOUT </a></li>
<li> <a href="course.html"> COURSE </a></li>
<li> <a href="blog.html"> BLOG </a></li>
<li> <a href="contact.html"> CONTACT </a></li>
</ul>
</div>
<i class="fa fa-bars" onclick="showMenu()"></i>
</nav>
<h1> Our Certificate & Online Programs For 2022 </h1>
</section>
<!-- blog page content -->
<section class="blog-content">
<div class="row">
<div class="blog-left">
<img src="image/certificate.jpg" >
<h2>Our Certificate & Online Programs For 2022 </h2>
<p>Northern University Bangladesh or NUB is a private university in Dhaka, Bangladesh. It was established in 2002. The university was sponsored
and funded by International Business Agriculture & Technology Trust.</p> <br>
<p>Northern University Bangladesh or NUB is a private university in Dhaka, Bangladesh. It was established in 2002. The university was sponsored
and funded by International Business Agriculture & Technology Trust.</p> <br>
<p>Northern University Bangladesh or NUB is a private university in Dhaka, Bangladesh. It was established in 2002. The university was sponsored
and funded by International Business Agriculture & Technology Trust.</p> <br>
<p>Northern University Bangladesh or NUB is a private university in Dhaka, Bangladesh. It was established in 2002. The university was sponsored
and funded by International Business Agriculture & Technology Trust.</p>
<div class="comment-box">
<h3> Leave a Comment</h3>
<form class="comment-form" >
<input type="text" placeholder="Enter Name">
<input type="email" placeholder="Enter Email">
<textarea rows="5" placeholder="your comment"></textarea>
<button type="submit" class="hero-btn red-btn"> POST COMMENT </button>
</form>
</div>
</div>
<div class="blog-right">
<h3> Post Categories </h3>
<div>
<span> Business Analyties </span>
<span> 19</span>
</div>
<div>
<span> Data Science </span>
<span> 33</span>
</div>
<div>
<span> Machine Learning </span>
<span> 55</span>
</div>
<div>
<span> Computer Science </span>
<span> 12</span>
</div>
<div>
<span> Business Analyties </span>
<span>43</span>
</div>
<div>
<span> Business Analyties </span>
<span> 16</span>
</div>
</div>
</div>
</section>
<!-- footer -->
<section class="footer">
<h4> About US</h4>
<p> Discover your God-given purpose. In these 20-teaching videos you'll discover - <br> - the importance of living from your heart, your gifts and where you fit into God's
plan and how to align with the Lord's
destiny on your life as you serve Him with joy.</p>
<div class="icon">
<i class="fa fa-facebook" ></i>
<i class="fa fa-whatsapp" ></i>
<i class="fa fa-youtube" ></i>
<i class="fa fa-linkedin" ></i>
<i class="fa fa-instagram" ></i>
</div>
<p> made with <i class="fa fa-heart-o" > </i> by easin bin yousuf </p>
</section>
<!-- java script for toggle menu -->
<script>
var navLinks = document.getElementById("navLinks");
function showMenu(){
navLinks.style.right = "0";
}
function hideMenu(){
navLinks.style.right = "-200px";
}
</script>
</body>
</html> |
Project Instructions
1) Set up the environment
i. Download and install VirtualBox
ii. Download OVM and sample project files
https://www.dropbox.com/sh/j7f7pog3sw3rbq7/AABX72ga7A0g0lLY9vRHv4Voa
iii. Install OVM appliance. The username and password are both "test".
Instructions for installing an OVM are here:
http://grok.lsu.edu/article.aspx?articleid=13838
iv. Move the sample files to the VM (or download them inside the VM)
v. Make sure the sample test runs inside the VM
a. Open the terminal and navigate to your sample files directory
b. Run the test in the way described below
c. It should run but one of the tests should fail
2) Fix the sample test so that it passes. The test is just a sample and not
meant to be a complete test of the feature it covers. There's no need to
change what it tests - just find the cause of the failure and fix it.
3) Write a new test for login. You can use the same user as the sample test
(username: justa_tester, password: testing1).
i. Be as comprehensive as you can. Attempt to cover all functionality
related to login.
ii. Implement the most important things first and stub out things you
don't have time to implement.
iii. Document your assumptions and the pros and cons of the decisions you
made.
iv. Document things you would do differently or additionally if you hit a
wall somewhere.
4) When you're done, zip up the directory that you downloaded (containing your
new test) and email it to the interview team.
Code Overview
The selenium browser object is also known as WebDriver. For info on its native
methods and capabilities, read the WebDriver API documentation
<http://selenium-python.readthedocs.org/en/latest/api.html#module-selenium.webdriver.remote.webelement>.
We use a wrapper around the selenium browser object that's defined in
utils.Browser. You can call any method defined in that class and also any of
the WebDriver class that it wraps. There are methods defined in our Browser
class to do things like register, log in, log out, and various other commonly
used things.
Running tests in a shell
This is the best way to run/debug tests when you're working on them. Here's how
you would run test_spotlight_hireme.py
$ ipython
In [1]: import utils
In [2]: import test_spotlight_hireme
In [3]: b = utils.run_numbered_tests(test_spotlight_hireme)
That should run the tests contained in test_spotlight_hireme.py until they all
pass or until an exception happens or an assert fails.
You can also drive a browser from the shell to help you write your tests.
Here's an example of creating a browser, login and clicking the Account
Settings link::
In [4]: b = utils.get_browser()
In [5]: b.login('justa_tester')
In [6]: b('.accountlinks .accountmenu .menu-toggle').click()
In [7]: b('a[href="/account/"]').click()
In [8]: b.contains('Account Settings', 'a').click()
Online Instructions: https://gist.github.com/NigelKibodeaux/2326cd66c1c5a946501a |
(%ex "2.7")
; exercise 2.7, page 94
(define (make-interval a b) (cons a b))
(define (upper-bound a)
(let ((x (car a))
(y (cdr a)))
(if (> x y) x y)))
(define (lower-bound a)
(let ((x (car a))
(y (cdr a)))
(if (< x y) x y)))
(let((bound-test1 (make-interval 4 6))
(bound-test2 (make-interval 4 -6))
(bound-test3 (make-interval -14 -6))
(test-bounds (lambda (interval)
(display "interval: ")(display interval)(newline)
(display " Upper bound: ")(display (upper-bound interval))(newline)
(display " Lower bound: ")(display (lower-bound interval))(newline)
(newline))))
(test-bounds bound-test1)
(test-bounds bound-test2)
(test-bounds bound-test3)) |
<%--
Document : CheckOut
Created on : Oct 18, 2023, 9:17:50 PM
Author : Dac Dat
--%>
<%@page import="model.User"%>
<%
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
User user = (User) session.getAttribute("account");
if(user == null) {
response.sendRedirect("/login");
return;
}
%>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style>
.dropdown-toggle::after {
content: none;
}
.dropdown-toggle {
background-color: transparent;
}
</style>
</head>
<body style="background-color: #e8e8e8">
<%@include file="Header.jsp" %>
<c:set var="user" value="${sessionScope.account}"></c:set>
<c:set var="listCart" value="${requestScope.listCart}"></c:set>
<c:set var="listProduct" value="${requestScope.listProduct}"></c:set>
<c:set var="listProductColor" value="${requestScope.listProductColor}"></c:set>
<c:set var="listShipping" value="${requestScope.listShipping}"></c:set>
<div class="container">
<div class="row cart-body p-5 bg-white mt-3" >
<form class="d-flex row w-100" id="checkOutForm">
<div class="col-lg-6">
<!-- SHIPPING METHOD -->
<div class="card">
<div class="card-header" style="font-size: 22px;color: chocolate;font-weight: bold">Information Customer</div>
<div class="card-body">
<div class="form-group col-md-12">
<label for="Name" style="font-weight: bold">Full Name:</label>
<input type="text" class="form-control fullName" id="Name" placeholder="Full name" value="${user.fullname}" name="name" required="">
</div>
<div class="form-group col-md-12">
<label for="Phone" style="font-weight: bold">Phone:</label>
<input type="text" class="form-control phone" id="Phone" placeholder="Phone" value="${user.phone}" name="phone" required="">
</div>
<div class="form-group col-md-12">
<label for="city" style="font-weight: bold">City:</label>
<select class="form-select form-control" id="city" aria-label=".form-select-sm" required="" name="city">
<option value="" selected>Select city</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="district" style="font-weight: bold">District: </label>
<select class="form-select form-control" id="district" aria-label=".form-select-sm" required="" name="district">
<option value="" selected >Select district</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="ward" style="font-weight: bold">Ward:</label>
<select class="form-select form-control" id="ward" aria-label=".form-select-sm" required=""name="ward">
<option value="" selected>Select ward</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="Address" style="font-weight: bold">Specific Address:</label>
<input type="text" required="" class="form-control specificAddress" id="Address" placeholder="Specific Address" value="${user.address}" name="address">
</div>
<div class="form-group col-md-12">
<label for="shipping" style="font-weight: bold">Shipping</label>
<select id="shipping" class="form-control" name="shipping">
<c:forEach var="shipping" items="${listShipping}">
<option value="${shipping.shipping_id}" class="${shipping.price}">${shipping.type}</option>
</c:forEach>
</select>
</div>
<div class="form-group col-md-12">
<label for="Message" style="font-weight: bold">Message:</label>
<input type="text" class="form-control" id="Message" placeholder="Message" value="" name="message">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<!-- REVIEW ORDER -->
<div class="card">
<div class="card-header d-flex align-items-center justify-content-between" >
<div style="font-size: 22px;color: chocolate;font-weight: bold"">Review Order</div>
<a href="cart" style="font-size: 14px;text-align: center;text-decoration: none;color: green;font-weight: bold">Edit Cart</a>
</div>
<div class="card-body">
<c:forEach var="cartItem" items="${listCart}">
<div class="form-group row">
<c:forEach var="prodColor" items="${listProductColor}">
<c:if test="${prodColor.product_color_id == cartItem.product_color_id}">
<div class="col-sm-3 col-3">
<img class="img-fluid" src="images/${prodColor.image}" />
</div>
</c:if>
</c:forEach>
<c:forEach var="prodColor" items="${listProductColor}">
<c:if test="${prodColor.product_color_id == cartItem.product_color_id}">
<c:forEach var="prod" items="${listProduct}">
<c:if test="${prodColor.product_id == prod.product_id}">
<div class="col-sm-6 col-6">
<div class="col-12" style="font-weight: bold;font-size: 18px">${prod.name}</div>
<div class="col-12"><small style="font-weight: bold ;font-style: italic;font-size: 14px">Quantity: <span style="font-weight: lighter ;font-style: normal">${cartItem.quantity}</span></small></div>
<div class="col-12"><small style="font-weight: bold ;font-style: italic;font-size: 14px">Color: <span style="font-weight: lighter ;font-style: normal">${prodColor.color}</span></small></div>
<div class="col-12"><small style="font-weight: bold ;font-style: italic;font-size: 14px">Price: <span style="font-weight: lighter ;font-style: normal">$${prodColor.price}</span></small></div>
</div>
</c:if>
</c:forEach>
</c:if>
</c:forEach>
<c:forEach var="prodColor" items="${listProductColor}">
<c:if test="${prodColor.product_color_id == cartItem.product_color_id}">
<div class="col-sm-3 col-3 text-right">
<h6><span>$</span><span class="price">${prodColor.price * cartItem.quantity}</span></h6>
</div>
</c:if>
</c:forEach>
</div>
</c:forEach>
<hr />
<hr />
<div class="form-group row">
<div class="col-12">
<strong>Order</strong>
<span class="float-right" style="font-weight: bold"><span>$</span><span class="totalPrice"></span></span>
<input type="text" class="form-control" id="createat" name="creatat" hidden="" value="<%= java.time.LocalDate.now()%>">
</div>
<div class="col-12">
<strong>Shipping</strong>
<span class="float-right" style="font-weight: bold"><span>$</span><span class="shipvalue"></span></span>
</div>
<div class="col-12">
<strong>Order Total</strong>
<span class="float-right" style="font-weight: bold"><span>$</span><span class="totalPriceAndShip"></span></span>
<input type="text" class="totalOrder" value="" name="total" hidden="">
</div>
</div>
</div>
</div>
<button type="button" style="background-color: #ee4d2d; color: white; padding: 13px 26px" class="btn float-right mt-5 submitBtn">Purchase</button>
</div>
</form>
</div>
</div>
</div>
<%@include file="Footer.jsp" %>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
const totalPrice = document.querySelector('.totalPrice');
const prices = document.querySelectorAll('.price');
const totalInput = document.querySelector('input[name="total"]');
const shipping = document.querySelector("#shipping");
const totalOrder = document.querySelector(".totalOrder");
const totalPriceAndShip = document.querySelector(".totalPriceAndShip");
let total = 0;
prices.forEach((value) => {
let price = +(value.innerHTML);
total += +(value.innerHTML);
});
totalPrice.innerHTML = total;
var selectedOption = shipping.querySelector(`option[value="\${1}"]`);
var selectedOptionClassName = selectedOption.className;
console.log(selectedOptionClassName);
const shipvalue = document.querySelector(".shipvalue");
shipvalue.innerHTML = selectedOptionClassName;
totalPriceAndShip.innerHTML = total + (+selectedOptionClassName);
totalInput.value = total + (+selectedOptionClassName);
shipping.addEventListener("change", function () {
var selectedValue = shipping.value;
var selectedOption = shipping.querySelector(`option[value="\${selectedValue}"]`);
var selectedOptionClassName = selectedOption.className;
shipvalue.innerHTML = selectedOptionClassName;
totalPriceAndShip.innerHTML = total + (+selectedOptionClassName);
totalInput.value = total + (+selectedOptionClassName);
});
var citis = document.getElementById("city");
var districts = document.getElementById("district");
var wards = document.getElementById("ward");
var Parameter = {
url: "https://raw.githubusercontent.com/kenzouno1/DiaGioiHanhChinhVN/master/data.json",
method: "GET",
responseType: "application/json",
};
var promise = axios(Parameter);
promise.then(function (result) {
console.log(result);
renderCity(result.data);
});
let cityName = "";
let districtName = "";
let wardName = "";
let dataWards;
function normalizeText(text) {
text = text.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
return text.replace(/Đ/g, "D").replace(/đ/g, "d");
}
function renderCity(data) {
for (const x of data) {
citis.options[citis.options.length] = new Option(x.Name, x.Id);
}
citis.onchange = function () {
district.length = 1;
ward.length = 1;
if (this.value != "") {
const result = data.filter(n => n.Id === this.value);
cityName = normalizeText(result[0].Name);
for (const k of result[0].Districts) {
district.options[district.options.length] = new Option(k.Name, k.Id);
}
}
};
district.onchange = function (value) {
ward.length = 1;
const dataCity = data.filter((n) => n.Id === citis.value);
dataCity[0].Districts.forEach((item) => {
if (item.Id === value.target.value) {
districtName = normalizeText(item.Name);
}
});
if (this.value != "") {
dataWards = dataCity[0].Districts.filter(n => n.Id === this.value)[0].Wards;
for (const w of dataWards) {
wards.options[wards.options.length] = new Option(w.Name, w.Id);
}
}
};
wards.onchange = function (event) {
dataWards.forEach((value) => {
if (value.Id === event.target.value) {
wardName = normalizeText(value.Name);
}
})
}
}
const submitBtn = document.querySelector(".submitBtn");
submitBtn.onclick = () => {
const city = document.querySelector("#city");
let idCity = city.options[city.selectedIndex].value;
city.options[city.selectedIndex].value = cityName;
const district = document.querySelector("#district");
let idDistrict = district.options[district.selectedIndex].value;
district.options[district.selectedIndex].value = districtName;
const ward = document.querySelector("#ward");
let idWard = ward.options[ward.selectedIndex].value;
ward.options[ward.selectedIndex].value = wardName;
const checkOutForm = document.querySelector("#checkOutForm");
const data = new FormData(checkOutForm);
$.ajax({
type: "post",
url: "/PhoneStore/check-out",
processData: false,
contentType: false,
enctype: "multipart/form-data",
data: data,
cache: false,
success: function (response)
{
console.log(response);
switch (response) {
case 'Invalid input':
Swal.fire({
title: 'Invalid Input',
icon: 'error',
confirmButtonText: 'OK',
})
break;
case 'OK':
city.options[city.selectedIndex].value = idCity;
district.options[district.selectedIndex].value = idDistrict;
ward.options[ward.selectedIndex].value = idWard;
Swal.fire({
title: 'Cancel successfully',
icon: 'success',
showCancelButton: true,
confirmButtonText: 'Go to history purchase',
}).then((result) => {
sendToastNotificationInfo();
if (result.isConfirmed) {
window.open("history-purchase", "_self");
}
})
break;
}
}
});
};
</script>
</body>
</html> |
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Results;
using AutoMapper;
using StaffManagement.Dtos;
using StaffManagement.Models;
namespace StaffManagement.Controllers.Api
{
public class SkillsController : ApiController
{
private ApplicationDbContext m_context;
public SkillsController()
{
m_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
m_context.Dispose();
}
//GET /api/skills
[HttpGet]
public IHttpActionResult GetSkills()
{
return Ok(m_context.Skills.Select(Mapper.Map<Skill, SkillDto>));
}
//GET /api/skills/1
public IHttpActionResult GetSkill(int id)
{
var skill = m_context.Skills.SingleOrDefault(x=>x.id == id);
if (skill == null)
return NotFound();
return Ok(Mapper.Map<Skill, SkillDto>(skill));
}
//POST /api/skills
[HttpPost]
public IHttpActionResult CreateSkill(SkillDto skillDto)
{
if (!ModelState.IsValid)
return BadRequest();
var skill = Mapper.Map<SkillDto, Skill>(skillDto);
m_context.Skills.Add(skill);
m_context.SaveChanges();
skillDto.id = skill.id;
return Created(new Uri(Request.RequestUri + "/"+skill.id), skillDto);
}
//PUT /api/skills/1
[HttpPut]
public IHttpActionResult UpdateSkill(int id, SkillDto skillDto)
{
if (!ModelState.IsValid)
return BadRequest();
var dbSkill = m_context.Skills.SingleOrDefault(x=>x.id == id);
if (dbSkill == null)
return NotFound();
Mapper.Map<SkillDto, Skill>(skillDto, dbSkill);
m_context.SaveChanges();
return Ok();
}
//DELETE /api/skills/1
[HttpDelete]
public IHttpActionResult DeleteSkill(int id)
{
var skill = m_context.Skills.SingleOrDefault(x=>x.id == id);
if (skill == null)
return NotFound();
m_context.Skills.Remove(skill);
m_context.SaveChanges();
return Ok();
}
}
} |
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Runtime, Function, Code } from 'aws-cdk-lib/aws-lambda';
import * as sns from 'aws-cdk-lib/aws-sns';
import { Stack, RemovalPolicy } from 'aws-cdk-lib';
import { Rule, Schedule } from 'aws-cdk-lib/aws-events';
import { LambdaFunction } from 'aws-cdk-lib/aws-events-targets';
import { RetentionDays } from 'aws-cdk-lib/aws-logs';
import { LambdaIntegration, RestApi, Cors } from 'aws-cdk-lib/aws-apigateway';
import { AttributeType, Table } from 'aws-cdk-lib/aws-dynamodb';
import { Duration } from 'aws-cdk-lib';
import * as dotenv from 'dotenv';
import path = require('path');
export class BackendStack extends Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
dotenv.config({ path: path.resolve(__dirname, '.env') });
const plaidApiKey = process.env.PLAID_API_KEY || 'NO API KEY SET';
const plaidClientKey = process.env.PLAID_CLIENT_ID || 'NO CLIENT ID SET';
const tableName = 'PlaidAccessKeys';
const TOPIC_NAME = "WeeklyReportTopic";
// Setup our dynamo db table
const dynamoTable = new Table(this, tableName, {
partitionKey: {
name: 'uuid',
type: AttributeType.STRING
},
readCapacity: 1,
writeCapacity: 1,
tableName: tableName,
removalPolicy: RemovalPolicy.RETAIN,
});
/**
* Get Link Lambda needs API Gateway integration
*/
const getLink = new Function(this, 'getLink', {
description: "Get Temporary Access Token Link from Plaid",
code: Code.fromAsset('lib/lambdas/getLink/target/x86_64-unknown-linux-musl/release/lambda'),
runtime: Runtime.PROVIDED_AL2,
handler: 'not.required',
timeout: Duration.minutes(5),
environment: {
RUST_BACKTRACE: '1',
PLAID_API_KEY: plaidApiKey,
PLAID_CLIENT_ID: plaidClientKey
},
logRetention: RetentionDays.ONE_WEEK,
});
/**
* Create Access Token needs API Gateway and Dynamo DB Permission
*/
const createAccessToken = new Function(this, 'createAccessToken', {
description: "Add recipes worker",
code: Code.fromAsset('lib/lambdas/createAccessToken/target/x86_64-unknown-linux-musl/release/lambda'),
runtime: Runtime.PROVIDED_AL2,
handler: 'not.required',
timeout: Duration.minutes(5),
environment: {
RUST_BACKTRACE: '1',
TABLE_NAME: tableName,
PLAID_API_KEY: plaidApiKey,
PLAID_CLIENT_ID: plaidClientKey
},
logRetention: RetentionDays.ONE_WEEK,
});
/**
* Send Weekly Report needs Event Bridge and SNS Topic and Dynamo DB Read Access
*/
const sendWeeklyReport = new Function(this, 'sendWeeklyReport', {
description: "Add recipes worker",
code: Code.fromAsset('lib/lambdas/sendWeeklyReport/target/x86_64-unknown-linux-musl/release/lambda'),
runtime: Runtime.PROVIDED_AL2,
handler: 'not.required',
timeout: Duration.minutes(5),
environment: {
RUST_BACKTRACE: '1',
TABLE_NAME: tableName,
PLAID_API_KEY: plaidApiKey,
PLAID_CLIENT_ID: plaidClientKey,
TOPIC: TOPIC_NAME
},
logRetention: RetentionDays.ONE_WEEK,
});
const reportTopic = new sns.Topic(this, TOPIC_NAME);
reportTopic.grantPublish(sendWeeklyReport);
dynamoTable.grantFullAccess(createAccessToken);
dynamoTable.grantFullAccess(sendWeeklyReport);
// Create an API Gateway resource for each of the CRUD operations
const link = new RestApi(this, 'GetLink', {
restApiName: 'Get Link API',
defaultCorsPreflightOptions: {
allowOrigins: Cors.ALL_ORIGINS,
allowMethods: Cors.ALL_METHODS,
allowHeaders: Cors.DEFAULT_HEADERS,
}
});
const accToken = new RestApi(this, 'CreateAccessToken', {
restApiName: "Create Access Token API",
defaultCorsPreflightOptions: {
allowOrigins: Cors.ALL_ORIGINS,
allowMethods: Cors.ALL_METHODS,
allowHeaders: Cors.DEFAULT_HEADERS
}
});
// Integrate lambda functions with an API gateway
const linkApi = new LambdaIntegration(getLink);
const accTokenApi = new LambdaIntegration(createAccessToken);
const links = link.root.addResource('api');
links.addMethod('GET', linkApi);
const tokens = accToken.root.addResource('api');
tokens.addMethod('POST', accTokenApi);
const eventRule = new Rule(this, 'scheduleRule', {
schedule: Schedule.expression('rate(7 days)'),
});
eventRule.addTarget(new LambdaFunction(sendWeeklyReport));
}
} |
import React, { useContext } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { logout } from '../services/localStorage';
import myContext from '../context/myContext';
function HeaderSeller() {
const navigate = useNavigate();
const { userData } = useContext(myContext);
return (
<header className="flex justify-between bg-teal-900 h-16">
<nav className="flex">
<Link
to="/seller/orders"
className="hover:bg-teal-600 hover:rounded-md m-4 ml-20 px-4 text-white"
data-testid="customer_products__element-navbar-link-orders"
>
Pedidos
</Link>
</nav>
<section className="flex">
<p
className="bg-teal-500 py-5 px-4 text-white"
data-testid="customer_products__element-navbar-user-full-name"
>
{ userData.name }
</p>
<button
type="button"
onClick={ () => {
navigate('/');
logout();
} }
className="bg-red-800 text-white w-20"
data-testid="customer_products__element-navbar-link-logout"
>
Sair
</button>
</section>
</header>
);
}
export default HeaderSeller; |
package com.zeyadgasser.core
import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zeyadgasser.core.Outcome.EmptyOutcome
import com.zeyadgasser.core.Outcome.EmptyOutcome.emptyOutcomeFlow
import com.zeyadgasser.core.Outcome.EmptyOutcome.input
import com.zeyadgasser.core.Outcome.ErrorOutcome
import com.zeyadgasser.core.Outcome.ProgressOutcome
import com.zeyadgasser.core.api.AsyncOutcomeFlow
import com.zeyadgasser.core.api.CancelInput
import com.zeyadgasser.core.api.Debounce
import com.zeyadgasser.core.api.Effect
import com.zeyadgasser.core.api.EmptyInput
import com.zeyadgasser.core.api.Input
import com.zeyadgasser.core.api.NONE
import com.zeyadgasser.core.api.Output
import com.zeyadgasser.core.api.Reducer
import com.zeyadgasser.core.api.Result
import com.zeyadgasser.core.api.State
import com.zeyadgasser.core.api.Throttle
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted.Companion.Lazily
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.reflect.KClass
/**
* A base viewModel class that implements a UnidirectionalDataFlow (UDF) pattern using [Flow]s.
*/
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
abstract class FluxViewModel<I : Input, R : Result, S : State, E : Effect>(
val initialState: S,
initialInput: I? = null,
private val savedStateHandle: SavedStateHandle? = null,
private val reducer: Reducer<S, R>? = null,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO,
) : ViewModel() {
companion object {
const val ARG_STATE_KEY = "arg_state_key"
private const val DELAY = 100L
}
data class EffectOutcome<E>(val effect: E) : Outcome()
data class ResultOutcome<R>(val result: R) : Outcome()
data class StateOutcome<S>(val state: S, override var input: Input = EmptyInput, ) : Outcome(input)
private lateinit var job: Job
private var currentState: S = initialState
private val cancellableInputsMap: MutableMap<KClass<out I>, AtomicBoolean> = mutableMapOf()
private val tag: String = this::class.simpleName.orEmpty()
private val inputs: MutableSharedFlow<Input> = MutableSharedFlow()
private val throttledInputs: MutableSharedFlow<Input> = MutableSharedFlow()
private val debouncedInputs: MutableSharedFlow<Input> = MutableSharedFlow()
private val viewModelListener: MutableStateFlow<Output> = MutableStateFlow(currentState)
init {
activate()
initialInput?.let { process(it) }
}
/**
* Call observe from view to listen to state and effect updates.
*
* @return a [StateFlow] of [Output] representing the state and effect updates.
*/
fun observe(): StateFlow<Output> = viewModelListener.asStateFlow()
/**
* Send inputs: I to be processed by ViewModel.
*
* @param input the input to be processed.
*/
fun process(input: Input): Unit = viewModelScope.launch {
when (input.inputStrategy) {
NONE -> inputs
is Throttle -> throttledInputs
is Debounce -> debouncedInputs
}.emit(input)
}.let {}
/**
* Returns a new Flow that is cancellable by the [input].
* Make sure to cancel while the other action is in progress.
*
* @param [inputClass] The input that can be used to cancel the flow.
* @return A new Flow that is cancellable by [input] I.
*/
fun Flow<Outcome>.makeCancellable(inputClass: KClass<out I>): Flow<Outcome> =
onStart { cancellableInputsMap[inputClass] = AtomicBoolean(false) }
.takeWhile { cancellableInputsMap[inputClass]?.get() == false }
.onCompletion { cancellableInputsMap.remove(inputClass) }
/**
* Map inputs: I with current state: S to a [Flow] of [Outcome]s.
*
* @param input the input to be handled.
* @param state the current state of the ViewModel.
* @return a [Flow] of [Outcome] representing the outcomes of handling the input.
*/
abstract fun handleInputs(input: I, state: S): Flow<Outcome>
/**
* Override to implement with your preferred logger.
*/
protected open fun log(loggable: Loggable): Unit = Log.d(tag, "$loggable").let { }
/**
* Activates the UnidirectionalDataFlow (UDF) by creating the stream that connects the inputs streams to
* the [viewModelListener]
*/
private fun activate(): Unit = createOutcomes().shareIn(viewModelScope, Lazily).let { outcomeFlow ->
val states = createStates(outcomeFlow, reducer)
val nonStates = outcomeFlow.filter { it !is StateOutcome<*> && it !is ResultOutcome<*> }
job = viewModelScope.launch(dispatcher) { merge(nonStates, states).collect { it.handleOutcome() } }
}
/**
* Merges the input [Flow]s, log each emission, then calls [handleInputs] to map the inputs to actions
* that can be executed in ([flatMapConcat]) or out([flatMapMerge]) of order. Also calls
* [processInputOutcomeStream] to apply the Loading, Success & Error (LSE) pattern.
*/
private fun createOutcomes(): Flow<Outcome> = merge(
inputs,
throttledInputs.onEach { delay(it.inputStrategy.interval) },
debouncedInputs.debounce { it.inputStrategy.interval }
).map { input ->
log(input)
InputOutcomeStream(input, processInput(input))
}.flowOn(dispatcher).shareIn(viewModelScope, Lazily).run {
// create two streams one for sync and one for async processing
val asyncOutcomes = filter { it.outcomes is AsyncOutcomeFlow }
.map { it.copy(outcomes = (it.outcomes as AsyncOutcomeFlow).flow) }
.flatMapMerge { processInputOutcomeStream(it) }
val sequentialOutcomes = filter { it.outcomes !is AsyncOutcomeFlow }
.flatMapConcat { processInputOutcomeStream(it) }
merge(asyncOutcomes, sequentialOutcomes).flowOn(dispatcher)// merge them back into a single stream
}
@Suppress("UNCHECKED_CAST")
private fun processInput(input: Input) = if (input is CancelInput<*>) emptyOutcomeFlow()
.also { cancellableInputsMap[input.clazz as KClass<I>] = AtomicBoolean(true) }
else handleInputs(input as I, currentState)
/**
* Applies the Loading, Success & Error (LSE) pattern to every [Outcome]
*/
private fun processInputOutcomeStream(stream: InputOutcomeStream): Flow<Outcome> {
val fluxOutcomeFlow = stream.outcomes
.map { fluxOutcome -> fluxOutcome.apply { input = stream.input } } // attribute outcomes to inputs
.catch { cause -> emit(ErrorOutcome(cause, input = stream.input)) } // wrap uncaught exceptions
return if (stream.input.showProgress) { // emit Progress true and false around the outcome
fluxOutcomeFlow.flatMapConcat {
flowOf(it, ProgressOutcome(false, it.input)).onEach { delay(DELAY) }
}.onStart { emit(ProgressOutcome(true, stream.input)) }
} else fluxOutcomeFlow
}
/**
* Given a [Flow] of [Outcome]s return a [Flow] of [StateOutcome]s by filtering and applying the [reducer]
* if exists (MVI vs MVVM).
*/
@Suppress("UNCHECKED_CAST")
private fun createStates(outcome: Flow<Outcome>, reducer: Reducer<S, R>?): Flow<StateOutcome<S>> =
if (reducer == null)
outcome.mapNotNull { if (it is StateOutcome<*>) it as StateOutcome<S> else null } // MVVM
else
outcome.mapNotNull { if (it is ResultOutcome<*>) it as ResultOutcome<R> else null } // MVI
.scan(StateOutcome(currentState)) { state: StateOutcome<S>, result: ResultOutcome<R> ->
StateOutcome(reducer.reduce(state.state, result.result), result.input).also { log(result) }
}
/**
* Passes and logs [Outcome]s to [viewModelListener] to be observed by the view
*/
@Suppress("UNCHECKED_CAST")
private suspend fun Outcome.handleOutcome(): Unit = when (this) {
is ResultOutcome<*>, EmptyOutcome -> Unit
is ErrorOutcome -> viewModelListener.emit(error)
is EffectOutcome<*> -> viewModelListener.emit(effect as Output)
is ProgressOutcome -> viewModelListener.emit(progress)
is StateOutcome<*> -> (state as S).takeIf { it != currentState }?.let { state ->
savedStateHandle?.set(ARG_STATE_KEY, state)
currentState = state
viewModelListener.emit(state)
} ?: Unit
}.also { log(this) }
/**
* Cancels the UDF when the ViewModel is destroyed.
*/
final override fun onCleared(): Unit = job.cancel()
} |
package com.ew.gerocomium.controller;
import com.ew.gerocomium.common.constant.Constant;
import com.ew.gerocomium.dao.base.Result;
import com.ew.gerocomium.dao.query.*;
import com.ew.gerocomium.service.OutwardService;
import com.ew.gerocomium.service.RetreatApplyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@Api(tags = "外出登记")
@RestController
@RequestMapping("/outward")
@PreAuthorize("@AuthorityAssert.hasAuthority('/check-in/leave')")
public class OutwardController {
@Resource
private OutwardService outwardService;
@GetMapping("/pageOutwardByKey")
@ApiOperation(value = "分页查询外出登记", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result pageOutwardByKey(@ApiParam(value = "分页查询外出登记请求实体", required = true) PageOutwardByKeyQuery pageOutwardByKeyQuery,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.pageOutwardByKey(pageOutwardByKeyQuery);
}
@GetMapping("/pageSearchElderByKey")
@ApiOperation(value = "分页搜索老人", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result pageSearchElderByKey(@ApiParam(value = "分页搜索老人请求实体", required = true) PageSearchElderByKeyQuery pageSearchElderByKeyQuery,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.pageSearchElderByKey(pageSearchElderByKeyQuery);
}
@GetMapping("/pageSearchStaffByKey")
@ApiOperation(value = "分页搜索护工", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result pageSearchStaffByKey(@ApiParam(value = "分页搜索护工请求实体", required = true) PageSearchStaffByKeyQuery pageSearchStaffByKeyQuery,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.pageSearchStaffByKey(pageSearchStaffByKeyQuery);
}
@GetMapping("/listOutwardStaff")
@ApiOperation(value = "获取护工列表", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result listOutwardStaff(@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.listOutwardStaff();
}
@GetMapping("/pageEmergencyContact")
@ApiOperation(value = "分页获取紧急联系人", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result pageEmergencyContact(@ApiParam(value = "分页获取紧急联系人请求实体", required = true) PageSearchEmergencyContactQuery pageSearchEmergencyContactQuery,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.pageEmergencyContact(pageSearchEmergencyContactQuery);
}
@GetMapping("/listContactByElderId")
@ApiOperation(value = "获取紧急联系人列表", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result listContact(@ApiParam(value = "根据编号获取外出登记请求参数", required = true) @RequestParam Long elderId,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.listContactByElderId(elderId);
}
@PostMapping("/addOutward")
@ApiOperation(value = "新增外出登记", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result addOutward(@ApiParam(value = "新增外出登记请求实体", required = true) @RequestBody AddOutwardQuery addOutwardQuery,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.addOutward(addOutwardQuery);
}
@GetMapping("/getOutwardById")
@ApiOperation(value = "根据编号获取外出登记", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result getOutwardById(@ApiParam(value = "根据编号获取外出登记请求参数", required = true) @RequestParam Long outwardId,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.getOutwardById(outwardId);
}
@PutMapping("/delayReturn")
@ApiOperation(value = "延期返回", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result delayReturn(@ApiParam(value = "延期返回请求实体", required = true) @RequestBody DelayReturnQuery delayReturnQuery,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.delayReturn(delayReturnQuery);
}
@PutMapping("/recordReturn")
@ApiOperation(value = "登记返回", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result recordReturn(@ApiParam(value = "登记返回请求实体", required = true) @RequestBody RecordReturnQuery recordReturnQuery,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.recordReturn(recordReturnQuery);
}
@DeleteMapping("/deleteOutward")
@ApiOperation(value = "删除外出登记", notes = Constant.DEVELOPER + Constant.EMPEROR_WEN)
public Result deleteOutward(@ApiParam(value = "删除外出登记请求参数", required = true) @RequestParam Long outwardId,
@ApiParam(value = "接口访问请求头", required = true) @RequestHeader String token) {
return outwardService.deleteOutward(outwardId);
}
} |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';
import { KhoDetailComponent } from './kho-detail.component';
describe('Kho Management Detail Component', () => {
let comp: KhoDetailComponent;
let fixture: ComponentFixture<KhoDetailComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [KhoDetailComponent],
providers: [
{
provide: ActivatedRoute,
useValue: { data: of({ kho: { id: 123 } }) },
},
],
})
.overrideTemplate(KhoDetailComponent, '')
.compileComponents();
fixture = TestBed.createComponent(KhoDetailComponent);
comp = fixture.componentInstance;
});
describe('OnInit', () => {
it('Should load kho on init', () => {
// WHEN
comp.ngOnInit();
// THEN
expect(comp.kho).toEqual(expect.objectContaining({ id: 123 }));
});
});
}); |
1. Kiểu dữ liệu
- bool
- int/uint: (int8–int256/uint8–uint256) (step by 8 bit)
- address: ~20 byte. Mỗi address có một lượng Ether nhất định, là số cryptocurrency được dùng trên blockchain, và có thể cho và nhận Ether từ các address khác
- byte
- enum
- function type
- struct
- mapping: tương tự hashtable. Cấu trúc mapping(_KeyType => _ValueType) với _KeyType có thể là bất kì kiểu gì ngoại trừ mapping, dynamic-sized array, contract, enum, struct. _ValueType có thể là bất kì kiểu dữ liệu nào
- array
2. Contract
- Tương tự như class trong OOP với các thuộc tính (state variables) và phương thức (functions). Các khái niệm abstract contract (contract với ít nhất 1 phương thức chưa được thực thi), interface (chỉ gồm chữ ký thao tác) cũng tương tự OOP.
- Hỗ trợ đa kế thừa (sử dụng thuật toán C3 Linearzation tương tự python)
3.Function
- Có 2 cách gọi 1 phương thức:
+ internal calling: con trỏ instruction nhảy đến vị trí function trong bộ nhớ để thực thi
+ external calling: EVM thực hiện lệnh call
- Với internal calling:
+ private: chỉ có thể truy cập từ các phương thức bên trong contract
+ internal: chỉ có thể truy cập từ các phương thức bên trong contract hoặc từ contract con (kế thừa)
- Với external calling:
+ public: tất cả đều access
+ external: Access bỏi bên ngoài nhưng không thể access bởi chính các function bên trong cùng 1 contract
4.Memory and Storage
- State variables và Local Variables of structs, array mặc định lưu trữ stored.
- Function arguments mặc định lưu trữ ở memory.
- Keyword "memory" là bắt buộc nếu muốn pass by value cho các kiểu dữ liệu reference như arrays, structs, mappings, and strings.
5.If statement and Required()
pragma solidity 0.6.0;
contract Example {
address owner;
event SomeEvent();
event OtherEvent();
function doSomething(address _someowner) public {
transfer2(_someowner);
emit SomeEvent();
transfer1(_someowner);
emit OtherEvent();
}
function transfer1(address _newOwner) public {
require(msg.sender == owner);
// Do the actual transfer
}
function transfer2(address _newOwner) public {
if (msg.sender != owner) return;
// Do the actual transfer
}
}
*) _someowner equals to owner:
- transfer2 performs the transfer
- event SomeEvent is emitted
- transfer1 performs the transfer
- event OtherEvent is emitted
*) _someowner does not equal to owner:
- transfer2 does not perform the transfer but returns execution to previous function (doSomething)
- event SomeEvent is emitted
- transfer1 does not perform the transfer and halts the transaction execution with an error
- event OtherEvent is not emitted as the execution never reaches this far |
package common
import (
"github.com/toffguy77/statusPage/internal/countries"
"github.com/toffguy77/statusPage/internal/models"
"github.com/toffguy77/statusPage/middleware/prepare"
)
func GetResultData() models.ResultSetT {
var result models.ResultSetT
countriesList := countries.GetCountries()
chanSMS := make(chan [][]models.SMSData)
chanMMS := make(chan [][]models.MMSData)
chanVoiceCall := make(chan []models.VoiceCallData)
chanEmail := make(chan map[string][][]models.EmailData)
chanBilling := make(chan models.BillingData)
chanSupport := make(chan []int)
chanIncidents := make(chan []models.IncidentData)
for {
go prepare.GetSmsData(chanSMS, countriesList)
go prepare.GetMmsData(chanMMS, countriesList)
go prepare.GetVoiceCallData(chanVoiceCall, countriesList)
go prepare.GetEmailData(chanEmail, countriesList)
go prepare.GetBillingData(chanBilling)
go prepare.GetSupportData(chanSupport)
go prepare.GetIncidentsData(chanIncidents)
break
}
result.SMS = <-chanSMS
result.MMS = <-chanMMS
result.VoiceCall = <-chanVoiceCall
result.Email = <-chanEmail
result.Billing = <-chanBilling
result.Support = <-chanSupport
result.Incidents = <-chanIncidents
return result
}
func CheckResults(results models.ResultSetT) bool {
if results.MMS == nil {
return false
}
emptyBilling := models.BillingData{
CreateCustomer: false,
Purchase: false,
Payout: false,
Recurring: false,
FraudControl: false,
CheckoutPage: false,
}
if results.Billing == emptyBilling {
return false
}
if results.Email == nil {
return false
}
if results.SMS == nil {
return false
}
if results.Incidents == nil {
return false
}
if results.Support == nil {
return false
}
if results.VoiceCall == nil {
return false
}
return true
} |
import {
Box,
Center,
chakra,
Container,
Flex,
HStack,
Text,
VStack,
} from "@chakra-ui/react";
import { ComponentMeta } from "@storybook/react";
import { Card } from ".";
import { StoryRoot } from "../../../.storybook/StoryRoot";
import todoDone from "./todo-done.svg";
import todoOpen from "./todo-open.svg";
export default {
title: "component/Card",
component: Card,
} as ComponentMeta<typeof Card>;
export const EmptyCard = () => {
return (
<StoryRoot>
<Center width="100%">
<Flex width="300px" height="200px">
<Card />
</Flex>
</Center>
</StoryRoot>
);
};
export const TodoCard = () => {
return (
<StoryRoot>
<Center width="100%">
<Flex width="300px" height="200px">
<Card>
<VStack align="start">
<VStack align="start" spacing={0}>
<Text fontSize="lg" color="white" fontWeight="semibold">
Create figma mock
</Text>
<Text fontSize="sm" color="whiteAlpha.800">
Tracker app
</Text>
</VStack>
<VStack align="start" spacing={3}>
<HStack>
<img src={todoDone} alt="todo-done" />{" "}
<Center>
<Text
fontSize="md"
color="white"
lineHeight="15px"
h="11px"
textDecoration="line-through"
>
Design layout
</Text>
</Center>
</HStack>
<HStack>
<img src={todoOpen} alt="todo-open" />{" "}
<Center>
<Text
fontSize="md"
color="white"
lineHeight="15px"
h="11px"
>
Design home page
</Text>
</Center>
</HStack>
</VStack>
</VStack>
</Card>
</Flex>
</Center>
</StoryRoot>
);
}; |
// ignore_for_file: unused_local_variable, prefer_const_constructors, use_build_context_synchronously
import 'dart:io';
import 'package:chat_app/UI/auth%20screens/otp_screen.dart';
import 'package:chat_app/UI/auth%20screens/user_information.dart';
import 'package:chat_app/UI/home%20screen/home_screen.dart';
import 'package:chat_app/commons/common_firebase_method.dart';
import 'package:chat_app/custom%20widgets/snakbar%20widget/snakbar.dart';
import 'package:chat_app/models/user_model.dart';
import 'package:chat_app/shared%20prefrence/shared_prefrence.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class AuthProvider extends ChangeNotifier {
signINwhitPhone(BuildContext context, String phoneNumber) async {
try {
final auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: phoneNumber,
verificationCompleted: (PhoneAuthCredential credential) async {
await auth.signInWithCredential(credential);
},
verificationFailed: (e) {
throw Exception(e.message);
},
codeSent: ((String verficationId, int? resendToken) async {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => OtpScreen(
verficationId: verficationId,
)));
}),
codeAutoRetrievalTimeout: (String verficationId) {});
} on FirebaseAuthException catch (e) {
snakBarWidget(context: context, content: e.message!);
}
}
void verfiyOtp({
required BuildContext context,
required String verificationId,
required String userOtp,
}) async {
try {
final auth = FirebaseAuth.instance;
PhoneAuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: userOtp,
);
await auth.signInWithCredential(credential);
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (_) => UserInformationScreen(),
),
(route) => false);
} on FirebaseAuthException catch (e) {
snakBarWidget(context: context, content: e.message!);
}
}
void saveUserDataToFirebase({
required BuildContext context,
required String name,
required File? profilePic,
}) async {
try {
///(firebase firestore الجزء دا عشان نرفع صوره علي )
String photoUrl =
'https://png.pngitem.com/pimgs/s/649-6490124_katie-notopoulos-katienotopoulos-i-write-about-tech-round.png';
if (profilePic != null) {
photoUrl = await storeFileToFirebase(
"profilePic/${UserData.getUserphoneNumber()}",
profilePic,
);
///(firebase firestore الجزء دا خاص بتسجيل المستخدم علي )
final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
String uid = UserData.getUserphoneNumber() ?? "";
var user = UserModel(
name: name,
uid: uid,
profilePic: photoUrl,
isOnline: false,
phoneNumber: UserData.getUserphoneNumber() ?? "",
groupId: [],
);
await firebaseFirestore.collection("Users").doc(uid).set(user.toMap());
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (_) => HomeScreen(),
),
(route) => false);
UserData.setUserModel(user);
UserData.setIsFrist(true);
}
} catch (e) {
snakBarWidget(context: context, content: e.toString());
}
}
Stream<UserModel> userData(String uid) {
final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
return firebaseFirestore
.collection("Users")
.doc(uid)
.snapshots()
.map((event) => UserModel.fromMap(event.data()!));
}
void setUserState(bool isOnline) async {
final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
await firebaseFirestore
.collection("Users")
.doc(UserData.getUserphoneNumber())
.update({
"isOnline": isOnline,
});
}
} |
# Go API client for taikuncore
This Api will be responsible for overall data distribution and authorization.
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client.
- API version: v1
- Package version: 1.0.0
- Build package: org.openapitools.codegen.languages.GoClientCodegen
For more information, please visit [http://taikun.cloud/](http://taikun.cloud/)
## Installation
Install the following dependencies:
```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/net/context
```
Put the package under your project folder and add the following in import:
```golang
import taikuncore "github.com/itera-io/taikungoclient/client"
```
To use a proxy, set the environment variable `HTTP_PROXY`:
```golang
os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port")
```
## Configuration of Server URL
Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification.
### Select Server Configuration
For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`.
```golang
ctx := context.WithValue(context.Background(), taikuncore.ContextServerIndex, 1)
```
### Templated Server URL
Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`.
```golang
ctx := context.WithValue(context.Background(), taikuncore.ContextServerVariables, map[string]string{
"basePath": "v2",
})
```
Note, enum values are always validated and all unused variables are silently ignored.
### URLs Configuration per Operation
Each operation can use different server URL defined using `OperationServers` map in the `Configuration`.
An operation is uniquely identified by `"{classname}Service.{nickname}"` string.
Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps.
```golang
ctx := context.WithValue(context.Background(), taikuncore.ContextOperationServerIndices, map[string]int{
"{classname}Service.{nickname}": 2,
})
ctx = context.WithValue(context.Background(), taikuncore.ContextOperationServerVariables, map[string]map[string]string{
"{classname}Service.{nickname}": {
"port": "8443",
},
})
```
## Documentation for API Endpoints
All URIs are relative to *http://localhost*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AWSCloudCredentialAPI* | [**AwsCreate**](docs/AWSCloudCredentialAPI.md#awscreate) | **Post** /api/v1/aws/create | Add Aws credentials
*AWSCloudCredentialAPI* | [**AwsDeviceNames**](docs/AWSCloudCredentialAPI.md#awsdevicenames) | **Post** /api/v1/aws/device-names | Aws device name list
*AWSCloudCredentialAPI* | [**AwsList**](docs/AWSCloudCredentialAPI.md#awslist) | **Get** /api/v1/aws/list | Retrieve list of aws cloud credentials
*AWSCloudCredentialAPI* | [**AwsOwners**](docs/AWSCloudCredentialAPI.md#awsowners) | **Get** /api/v1/aws/owners | Retrieve aws verified owner list
*AWSCloudCredentialAPI* | [**AwsRegionlist**](docs/AWSCloudCredentialAPI.md#awsregionlist) | **Post** /api/v1/aws/regions | Retrieve aws regions list
*AWSCloudCredentialAPI* | [**AwsUpdate**](docs/AWSCloudCredentialAPI.md#awsupdate) | **Post** /api/v1/aws/update | Update AWS credentials
*AWSCloudCredentialAPI* | [**AwsValidateOwners**](docs/AWSCloudCredentialAPI.md#awsvalidateowners) | **Post** /api/v1/aws/validate-owners | Aws validate owners
*AWSCloudCredentialAPI* | [**AwsZones**](docs/AWSCloudCredentialAPI.md#awszones) | **Post** /api/v1/aws/zones | Fetch Aws zones
*AccessProfilesAPI* | [**AccessprofilesCreate**](docs/AccessProfilesAPI.md#accessprofilescreate) | **Post** /api/v1/accessprofiles/create | Create access profile
*AccessProfilesAPI* | [**AccessprofilesDelete**](docs/AccessProfilesAPI.md#accessprofilesdelete) | **Delete** /api/v1/accessprofiles/{id} | Delete access profile by Id
*AccessProfilesAPI* | [**AccessprofilesDropdown**](docs/AccessProfilesAPI.md#accessprofilesdropdown) | **Get** /api/v1/accessprofiles/list | Retrieve access profiles by organization Id
*AccessProfilesAPI* | [**AccessprofilesList**](docs/AccessProfilesAPI.md#accessprofileslist) | **Get** /api/v1/accessprofiles | Retrieve all access profiles
*AccessProfilesAPI* | [**AccessprofilesLockManager**](docs/AccessProfilesAPI.md#accessprofileslockmanager) | **Post** /api/v1/accessprofiles/lockmanager | Lock/unlock access profiles
*AccessProfilesAPI* | [**AccessprofilesUpdate**](docs/AccessProfilesAPI.md#accessprofilesupdate) | **Put** /api/v1/accessprofiles/update/{id} | Update access profile
*AdminAPI* | [**AdminAddBalance**](docs/AdminAPI.md#adminaddbalance) | **Post** /api/v1/admin/organizations/add/balance | Add balance for organization
*AdminAPI* | [**AdminBillingOperations**](docs/AdminAPI.md#adminbillingoperations) | **Post** /api/v1/admin/cloudcredentials/billing | Billing operations: enable/disable billing
*AdminAPI* | [**AdminCreateUser**](docs/AdminAPI.md#admincreateuser) | **Post** /api/v1/admin/users/create | User creation for admin
*AdminAPI* | [**AdminDeleteOrg**](docs/AdminAPI.md#admindeleteorg) | **Post** /api/v1/admin/organizations/delete | Delete organization
*AdminAPI* | [**AdminKeycloakList**](docs/AdminAPI.md#adminkeycloaklist) | **Get** /api/v1/admin/keycloak/list | Keycloak list for admin
*AdminAPI* | [**AdminMakeCsm**](docs/AdminAPI.md#adminmakecsm) | **Post** /api/v1/admin/users/make/csm | User csm update for admin
*AdminAPI* | [**AdminMakeOwner**](docs/AdminAPI.md#adminmakeowner) | **Post** /api/v1/admin/users/make/owner | User choose owner for admin
*AdminAPI* | [**AdminOrganizations**](docs/AdminAPI.md#adminorganizations) | **Get** /api/v1/admin/organizations/list | Organizations for admin
*AdminAPI* | [**AdminProjectList**](docs/AdminAPI.md#adminprojectlist) | **Get** /api/v1/admin/projects/list | Projects for admin
*AdminAPI* | [**AdminUpdateProject**](docs/AdminAPI.md#adminupdateproject) | **Post** /api/v1/admin/projects/update/version | Projects update for admin
*AdminAPI* | [**AdminUpdateProjectKube**](docs/AdminAPI.md#adminupdateprojectkube) | **Post** /api/v1/admin/projects/update/kubeconfig | Projects update kube for admin
*AdminAPI* | [**AdminUpdateUser**](docs/AdminAPI.md#adminupdateuser) | **Post** /api/v1/admin/users/update/password | User password update for admin
*AdminAPI* | [**AdminUpdateUserKube**](docs/AdminAPI.md#adminupdateuserkube) | **Post** /api/v1/admin/projects/update/userkube | Projects update kube for admin
*AdminAPI* | [**AdminUpdateUsers**](docs/AdminAPI.md#adminupdateusers) | **Post** /api/v1/admin/users/update/email | User email update for admin
*AdminAPI* | [**AdminUsersList**](docs/AdminAPI.md#adminuserslist) | **Get** /api/v1/admin/users/list | Users for admin
*AiCredentialsAPI* | [**AiCredentialCreate**](docs/AiCredentialsAPI.md#aicredentialcreate) | **Post** /api/v1/ai-credential/create | Create ai credential
*AiCredentialsAPI* | [**AiCredentialDelete**](docs/AiCredentialsAPI.md#aicredentialdelete) | **Delete** /api/v1/ai-credential/{id} | Remove ai credential
*AiCredentialsAPI* | [**AiCredentialDropdown**](docs/AiCredentialsAPI.md#aicredentialdropdown) | **Get** /api/v1/ai-credential | Retrieve all AI credentials for organization
*AiCredentialsAPI* | [**AiCredentialList**](docs/AiCredentialsAPI.md#aicredentiallist) | **Get** /api/v1/ai-credential/list | Retrieve all AI credentials
*AiManagementAPI* | [**AiManagementDisable**](docs/AiManagementAPI.md#aimanagementdisable) | **Post** /api/v1/ai-management/disable | Disable ai
*AiManagementAPI* | [**AiManagementEnable**](docs/AiManagementAPI.md#aimanagementenable) | **Post** /api/v1/ai-management/enable | Enable ai
*AlertingIntegrationsAPI* | [**AlertingintegrationsCreate**](docs/AlertingIntegrationsAPI.md#alertingintegrationscreate) | **Post** /api/v1/alertingintegrations/create | Create alerting profile alerting integration
*AlertingIntegrationsAPI* | [**AlertingintegrationsDelete**](docs/AlertingIntegrationsAPI.md#alertingintegrationsdelete) | **Delete** /api/v1/alertingintegrations/{id} | Delete alerting profile alerting integration
*AlertingIntegrationsAPI* | [**AlertingintegrationsEdit**](docs/AlertingIntegrationsAPI.md#alertingintegrationsedit) | **Put** /api/v1/alertingintegrations/edit | Edit alerting profile alerting integration
*AlertingIntegrationsAPI* | [**AlertingintegrationsList**](docs/AlertingIntegrationsAPI.md#alertingintegrationslist) | **Get** /api/v1/alertingintegrations/{alertingProfileId} | List alerting integrations by profile id
*AlertingIntegrationsAPI* | [**DocumentationList**](docs/AlertingIntegrationsAPI.md#documentationlist) | **Get** /api/v1/documentation | Retrieve all documentation links
*AlertingProfilesAPI* | [**AlertingprofilesAssignEmail**](docs/AlertingProfilesAPI.md#alertingprofilesassignemail) | **Put** /api/v1/alertingprofiles/assignemails/{id} | Assign Alerting emails
*AlertingProfilesAPI* | [**AlertingprofilesAssignWebhooks**](docs/AlertingProfilesAPI.md#alertingprofilesassignwebhooks) | **Put** /api/v1/alertingprofiles/assignwebhooks/{id} | Assign Alerting webhooks
*AlertingProfilesAPI* | [**AlertingprofilesAttach**](docs/AlertingProfilesAPI.md#alertingprofilesattach) | **Post** /api/v1/alertingprofiles/attach | Attach alerting profile to project
*AlertingProfilesAPI* | [**AlertingprofilesCreate**](docs/AlertingProfilesAPI.md#alertingprofilescreate) | **Post** /api/v1/alertingprofiles/create | Add Alerting profile
*AlertingProfilesAPI* | [**AlertingprofilesDelete**](docs/AlertingProfilesAPI.md#alertingprofilesdelete) | **Delete** /api/v1/alertingprofiles/{id} | Remove Alerting profiles by Id
*AlertingProfilesAPI* | [**AlertingprofilesDetach**](docs/AlertingProfilesAPI.md#alertingprofilesdetach) | **Post** /api/v1/alertingprofiles/detach | Detach alerting profile from project
*AlertingProfilesAPI* | [**AlertingprofilesDropdown**](docs/AlertingProfilesAPI.md#alertingprofilesdropdown) | **Get** /api/v1/alertingprofiles/list | Retrieve all Alerting profiles for organization
*AlertingProfilesAPI* | [**AlertingprofilesEdit**](docs/AlertingProfilesAPI.md#alertingprofilesedit) | **Post** /api/v1/alertingprofiles/edit | Update Alerting profile
*AlertingProfilesAPI* | [**AlertingprofilesList**](docs/AlertingProfilesAPI.md#alertingprofileslist) | **Get** /api/v1/alertingprofiles | Retrieve all Alerting profiles
*AlertingProfilesAPI* | [**AlertingprofilesLockManager**](docs/AlertingProfilesAPI.md#alertingprofileslockmanager) | **Post** /api/v1/alertingprofiles/lockmanager | Lock/Unlock Alerting profiles
*AlertingProfilesAPI* | [**AlertingprofilesVerify**](docs/AlertingProfilesAPI.md#alertingprofilesverify) | **Post** /api/v1/alertingprofiles/verifywebhook | Verify webhook endpoint
*AllowedHostAPI* | [**AllowedhostCreate**](docs/AllowedHostAPI.md#allowedhostcreate) | **Post** /api/v1/allowedhost/create | Create access profile allowed host
*AllowedHostAPI* | [**AllowedhostDelete**](docs/AllowedHostAPI.md#allowedhostdelete) | **Delete** /api/v1/allowedhost/{id} | Delete access profile allowed host
*AllowedHostAPI* | [**AllowedhostEdit**](docs/AllowedHostAPI.md#allowedhostedit) | **Put** /api/v1/allowedhost/edit/{id} | Edit access profile allowed host
*AllowedHostAPI* | [**AllowedhostList**](docs/AllowedHostAPI.md#allowedhostlist) | **Get** /api/v1/allowedhost/list/{accessProfileId} | List allowed hosts by access profile id
*AppRepositoriesAPI* | [**RepositoryAvailableList**](docs/AppRepositoriesAPI.md#repositoryavailablelist) | **Get** /api/v1/repository/available | Retrieve available repositories
*AppRepositoriesAPI* | [**RepositoryBind**](docs/AppRepositoriesAPI.md#repositorybind) | **Post** /api/v1/repository/bind | Bind repo to organization
*AppRepositoriesAPI* | [**RepositoryDelete**](docs/AppRepositoriesAPI.md#repositorydelete) | **Post** /api/v1/repository/delete | Delete repo from organization
*AppRepositoriesAPI* | [**RepositoryDisable**](docs/AppRepositoriesAPI.md#repositorydisable) | **Post** /api/v1/repository/disable | Disable repo from organization
*AppRepositoriesAPI* | [**RepositoryImport**](docs/AppRepositoriesAPI.md#repositoryimport) | **Post** /api/v1/repository/import | Import repo to artifact
*AppRepositoriesAPI* | [**RepositoryRecommendedList**](docs/AppRepositoriesAPI.md#repositoryrecommendedlist) | **Get** /api/v1/repository/recommended | Retrieve taikun recommended repositories
*AppRepositoriesAPI* | [**RepositoryUnbind**](docs/AppRepositoriesAPI.md#repositoryunbind) | **Post** /api/v1/repository/unbind | Unbind repo from organization
*AuthManagementAPI* | [**AuthForgotPassword**](docs/AuthManagementAPI.md#authforgotpassword) | **Post** /api/v1/auth/forgotpassword | Generate reset password token if you forgot password
*AuthManagementAPI* | [**AuthLogin**](docs/AuthManagementAPI.md#authlogin) | **Post** /api/v1/auth/login | Login to API
*AuthManagementAPI* | [**AuthRefresh**](docs/AuthManagementAPI.md#authrefresh) | **Post** /api/v1/auth/refresh | Refresh bearer token that generated automatically by API
*AuthManagementAPI* | [**AuthResetPassword**](docs/AuthManagementAPI.md#authresetpassword) | **Post** /api/v1/auth/resetpassword | Reset password
*AuthManagementAPI* | [**AuthTrial**](docs/AuthManagementAPI.md#authtrial) | **Post** /api/v1/auth/trial | Try free
*AutoscalingAPI* | [**AutoscalingDisable**](docs/AutoscalingAPI.md#autoscalingdisable) | **Post** /api/v1/autoscaling/disable | Disable autoscaling
*AutoscalingAPI* | [**AutoscalingEdit**](docs/AutoscalingAPI.md#autoscalingedit) | **Post** /api/v1/autoscaling/edit | Edit autoscaling
*AutoscalingAPI* | [**AutoscalingEnable**](docs/AutoscalingAPI.md#autoscalingenable) | **Post** /api/v1/autoscaling/enable | Enable autoscaling
*AutoscalingAPI* | [**AutoscalingSync**](docs/AutoscalingAPI.md#autoscalingsync) | **Post** /api/v1/autoscaling/sync | Sync autoscaling
*AzureCloudCredentialAPI* | [**AzureCreate**](docs/AzureCloudCredentialAPI.md#azurecreate) | **Post** /api/v1/azure/create | Add Azure credentials
*AzureCloudCredentialAPI* | [**AzureDashboard**](docs/AzureCloudCredentialAPI.md#azuredashboard) | **Post** /api/v1/azure/quota/list | Fetch Azure quota list
*AzureCloudCredentialAPI* | [**AzureList**](docs/AzureCloudCredentialAPI.md#azurelist) | **Get** /api/v1/azure/list | Retrieve list of azure cloud credentials
*AzureCloudCredentialAPI* | [**AzureLocations**](docs/AzureCloudCredentialAPI.md#azurelocations) | **Post** /api/v1/azure/locations | Fetch Azure location list
*AzureCloudCredentialAPI* | [**AzureOffers**](docs/AzureCloudCredentialAPI.md#azureoffers) | **Get** /api/v1/azure/offers/{cloudId}/{publisher} |
*AzureCloudCredentialAPI* | [**AzurePublishers**](docs/AzureCloudCredentialAPI.md#azurepublishers) | **Get** /api/v1/azure/publishers/{cloudId} | List Azure publishers list
*AzureCloudCredentialAPI* | [**AzureSkus**](docs/AzureCloudCredentialAPI.md#azureskus) | **Get** /api/v1/azure/skus/{cloudId}/{publisher}/{offer} |
*AzureCloudCredentialAPI* | [**AzureSubscriptions**](docs/AzureCloudCredentialAPI.md#azuresubscriptions) | **Post** /api/v1/azure/subscriptions | Azure subscriptions list
*AzureCloudCredentialAPI* | [**AzureUpdate**](docs/AzureCloudCredentialAPI.md#azureupdate) | **Post** /api/v1/azure/update | Update Azure credentials
*AzureCloudCredentialAPI* | [**AzureZones**](docs/AzureCloudCredentialAPI.md#azurezones) | **Post** /api/v1/azure/zones | Fetch Azure zone list
*BackupPolicyAPI* | [**BackupByName**](docs/BackupPolicyAPI.md#backupbyname) | **Get** /api/v1/backup/{projectId}/{name} |
*BackupPolicyAPI* | [**BackupClearProject**](docs/BackupPolicyAPI.md#backupclearproject) | **Post** /api/v1/backup/clear/project | Delete unfinished backup for project
*BackupPolicyAPI* | [**BackupCreate**](docs/BackupPolicyAPI.md#backupcreate) | **Post** /api/v1/backup/create | Add backup policy
*BackupPolicyAPI* | [**BackupDeleteBackup**](docs/BackupPolicyAPI.md#backupdeletebackup) | **Post** /api/v1/backup/delete/backup | Remove policy backup
*BackupPolicyAPI* | [**BackupDeleteBackupLocation**](docs/BackupPolicyAPI.md#backupdeletebackuplocation) | **Post** /api/v1/backup/delete/location | Remove backup location from project
*BackupPolicyAPI* | [**BackupDeleteRestore**](docs/BackupPolicyAPI.md#backupdeleterestore) | **Post** /api/v1/backup/delete/restore | Remove policy restore
*BackupPolicyAPI* | [**BackupDeleteSchedule**](docs/BackupPolicyAPI.md#backupdeleteschedule) | **Post** /api/v1/backup/delete/schedule | Remove policy schedule
*BackupPolicyAPI* | [**BackupDescribeBackup**](docs/BackupPolicyAPI.md#backupdescribebackup) | **Get** /api/v1/backup/describe/backup/{projectId}/{name} |
*BackupPolicyAPI* | [**BackupDescribeRestore**](docs/BackupPolicyAPI.md#backupdescriberestore) | **Get** /api/v1/backup/describe/restore/{projectId}/{name} |
*BackupPolicyAPI* | [**BackupDescribeSchedule**](docs/BackupPolicyAPI.md#backupdescribeschedule) | **Get** /api/v1/backup/describe/schedule/{projectId}/{name} |
*BackupPolicyAPI* | [**BackupDisableBackup**](docs/BackupPolicyAPI.md#backupdisablebackup) | **Post** /api/v1/backup/disablebackup | Disable backup by the projectId
*BackupPolicyAPI* | [**BackupEnableBackup**](docs/BackupPolicyAPI.md#backupenablebackup) | **Post** /api/v1/backup/enablebackup | Enable backup by the projectId
*BackupPolicyAPI* | [**BackupImportBackupStorage**](docs/BackupPolicyAPI.md#backupimportbackupstorage) | **Post** /api/v1/backup/location | Import backup storage from source project to target project
*BackupPolicyAPI* | [**BackupListAllBackupStorages**](docs/BackupPolicyAPI.md#backuplistallbackupstorages) | **Get** /api/v1/backup/location/{projectId} | List all backup locations
*BackupPolicyAPI* | [**BackupListAllBackups**](docs/BackupPolicyAPI.md#backuplistallbackups) | **Get** /api/v1/backup/backups/{projectId} | List all backups
*BackupPolicyAPI* | [**BackupListAllDeleteBackupRequests**](docs/BackupPolicyAPI.md#backuplistalldeletebackuprequests) | **Get** /api/v1/backup/delete-requests/{projectId} | List all delete backup requests
*BackupPolicyAPI* | [**BackupListAllRestores**](docs/BackupPolicyAPI.md#backuplistallrestores) | **Get** /api/v1/backup/restores/{projectId} | List all restores
*BackupPolicyAPI* | [**BackupListAllSchedules**](docs/BackupPolicyAPI.md#backuplistallschedules) | **Get** /api/v1/backup/schedules/{projectId} | List all schedules
*BackupPolicyAPI* | [**BackupRestoreBackup**](docs/BackupPolicyAPI.md#backuprestorebackup) | **Post** /api/v1/backup/restore | Restore backup
*BillingAPI* | [**BillingCreate**](docs/BillingAPI.md#billingcreate) | **Post** /api/v1/billing/create | Add billing summary
*BillingAPI* | [**BillingExportCsv**](docs/BillingAPI.md#billingexportcsv) | **Get** /api/v1/billing/export | Export Csv
*BillingAPI* | [**BillingGroupedList**](docs/BillingAPI.md#billinggroupedlist) | **Get** /api/v1/billing/grouped | Retrieve a grouped list of billing summaries
*BillingAPI* | [**BillingList**](docs/BillingAPI.md#billinglist) | **Get** /api/v1/billing | Retrieve billing info
*CatalogAPI* | [**CatalogBindProject**](docs/CatalogAPI.md#catalogbindproject) | **Post** /api/v1/catalog/bind-project | Bind projects to catalog
*CatalogAPI* | [**CatalogCreate**](docs/CatalogAPI.md#catalogcreate) | **Post** /api/v1/catalog/create | Create catalog
*CatalogAPI* | [**CatalogDelete**](docs/CatalogAPI.md#catalogdelete) | **Delete** /api/v1/catalog/{id} | Delete catalog
*CatalogAPI* | [**CatalogDropdown**](docs/CatalogAPI.md#catalogdropdown) | **Get** /api/v1/catalog/list | Catalog dropdown list for organization
*CatalogAPI* | [**CatalogEdit**](docs/CatalogAPI.md#catalogedit) | **Put** /api/v1/catalog/edit | Edit catalog
*CatalogAPI* | [**CatalogList**](docs/CatalogAPI.md#cataloglist) | **Get** /api/v1/catalog | Catalog list for organization
*CatalogAPI* | [**CatalogLock**](docs/CatalogAPI.md#cataloglock) | **Post** /api/v1/catalog/lockmanager | Lock catalog
*CatalogAppAPI* | [**CatalogAppCreate**](docs/CatalogAppAPI.md#catalogappcreate) | **Post** /api/v1/catalog-app/create | Create catalog app
*CatalogAppAPI* | [**CatalogAppDelete**](docs/CatalogAppAPI.md#catalogappdelete) | **Delete** /api/v1/catalog-app/{id} | Delete catalog app
*CatalogAppAPI* | [**CatalogAppDetails**](docs/CatalogAppAPI.md#catalogappdetails) | **Get** /api/v1/catalog-app/{catalogAppId} | Catalog App details
*CatalogAppAPI* | [**CatalogAppEditParams**](docs/CatalogAppAPI.md#catalogappeditparams) | **Put** /api/v1/catalog-app/edit/params | Edit catalog app params
*CatalogAppAPI* | [**CatalogAppEditVersion**](docs/CatalogAppAPI.md#catalogappeditversion) | **Put** /api/v1/catalog-app/edit/version | Edit catalog app version
*CatalogAppAPI* | [**CatalogAppLockManager**](docs/CatalogAppAPI.md#catalogapplockmanager) | **Post** /api/v1/catalog-app/lockmanager | Lock catalog app
*CatalogAppAPI* | [**CatalogAppParamDetails**](docs/CatalogAppAPI.md#catalogappparamdetails) | **Get** /api/v1/catalog-app/params/{catalogAppId} | Catalog App param details
*CheckerAPI* | [**CheckerArtifact**](docs/CheckerAPI.md#checkerartifact) | **Post** /api/v1/checker/artifact | Check artifact url
*CheckerAPI* | [**CheckerAws**](docs/CheckerAPI.md#checkeraws) | **Post** /api/v1/checker/aws | Check aws credential
*CheckerAPI* | [**CheckerAzure**](docs/CheckerAPI.md#checkerazure) | **Post** /api/v1/checker/azure | Check azure credentials
*CheckerAPI* | [**CheckerAzureQuota**](docs/CheckerAPI.md#checkerazurequota) | **Post** /api/v1/checker/azure/quota/cpu | Check azure cpu quota
*CheckerAPI* | [**CheckerCidr**](docs/CheckerAPI.md#checkercidr) | **Post** /api/v1/checker/cidr | Check valid cidr format
*CheckerAPI* | [**CheckerCron**](docs/CheckerAPI.md#checkercron) | **Post** /api/v1/checker/cron | Check valid cron job format
*CheckerAPI* | [**CheckerDns**](docs/CheckerAPI.md#checkerdns) | **Post** /api/v1/checker/dns | Check valid dns format
*CheckerAPI* | [**CheckerDuplicateName**](docs/CheckerAPI.md#checkerduplicatename) | **Post** /api/v1/checker/duplicate | Duplicate name
*CheckerAPI* | [**CheckerGoogle**](docs/CheckerAPI.md#checkergoogle) | **Post** /api/v1/checker/google |
*CheckerAPI* | [**CheckerKeycloak**](docs/CheckerAPI.md#checkerkeycloak) | **Post** /api/v1/checker/keycloak | Check keycloak credential
*CheckerAPI* | [**CheckerKubeConfig**](docs/CheckerAPI.md#checkerkubeconfig) | **Post** /api/v1/checker/kube-config |
*CheckerAPI* | [**CheckerNode**](docs/CheckerAPI.md#checkernode) | **Post** /api/v1/checker/node | Duplicate server name checker
*CheckerAPI* | [**CheckerNtp**](docs/CheckerAPI.md#checkerntp) | **Post** /api/v1/checker/ntp | Check valid ntp format
*CheckerAPI* | [**CheckerOpenAi**](docs/CheckerAPI.md#checkeropenai) | **Post** /api/v1/checker/openai | Check open-ai token
*CheckerAPI* | [**CheckerOpenstack**](docs/CheckerAPI.md#checkeropenstack) | **Post** /api/v1/checker/openstack | Check openstack credential
*CheckerAPI* | [**CheckerOpenstackTaikunImage**](docs/CheckerAPI.md#checkeropenstacktaikunimage) | **Post** /api/v1/checker/openstack-image/{id} | Check openstack taikun image
*CheckerAPI* | [**CheckerOpenstackTaikunLbImage**](docs/CheckerAPI.md#checkeropenstacktaikunlbimage) | **Post** /api/v1/checker/taikun-lb-image/{id} | Check openstack taikun lb image
*CheckerAPI* | [**CheckerOrganization**](docs/CheckerAPI.md#checkerorganization) | **Post** /api/v1/checker/organization | Check duplicate org name
*CheckerAPI* | [**CheckerPrometheus**](docs/CheckerAPI.md#checkerprometheus) | **Post** /api/v1/checker/prometheus | Check prometheus credentials
*CheckerAPI* | [**CheckerProxmox**](docs/CheckerAPI.md#checkerproxmox) | **Post** /api/v1/checker/proxmox | Check proxmox credential
*CheckerAPI* | [**CheckerS3**](docs/CheckerAPI.md#checkers3) | **Post** /api/v1/checker/s3 | Check s3 credential
*CheckerAPI* | [**CheckerSsh**](docs/CheckerAPI.md#checkerssh) | **Post** /api/v1/checker/ssh | Check valid ssh key format
*CheckerAPI* | [**CheckerTanzu**](docs/CheckerAPI.md#checkertanzu) | **Post** /api/v1/checker/tanzu | Check tanzu credential
*CheckerAPI* | [**CheckerUser**](docs/CheckerAPI.md#checkeruser) | **Post** /api/v1/checker/user | Check duplicate username
*CheckerAPI* | [**CheckerYaml**](docs/CheckerAPI.md#checkeryaml) | **Post** /api/v1/checker/yaml | Check yaml file
*CloudCredentialAPI* | [**CloudcredentialsAllFlavors**](docs/CloudCredentialAPI.md#cloudcredentialsallflavors) | **Get** /api/v1/cloudcredentials/flavors/{cloudId} |
*CloudCredentialAPI* | [**CloudcredentialsDashboardList**](docs/CloudCredentialAPI.md#cloudcredentialsdashboardlist) | **Get** /api/v1/cloudcredentials/list | Retrieve all cloud credentials
*CloudCredentialAPI* | [**CloudcredentialsDelete**](docs/CloudCredentialAPI.md#cloudcredentialsdelete) | **Delete** /api/v1/cloudcredentials/{cloudId} | Remove cloud credential by cloud Id
*CloudCredentialAPI* | [**CloudcredentialsExceeded**](docs/CloudCredentialAPI.md#cloudcredentialsexceeded) | **Get** /api/v1/cloudcredentials/exceeded-quotas | Retrieve cloud credentials exceeded quotas
*CloudCredentialAPI* | [**CloudcredentialsForCli**](docs/CloudCredentialAPI.md#cloudcredentialsforcli) | **Get** /api/v1/cloudcredentials/cli | Retrieve cloud credentials for CLI
*CloudCredentialAPI* | [**CloudcredentialsForProject**](docs/CloudCredentialAPI.md#cloudcredentialsforproject) | **Get** /api/v1/cloudcredentials/details | Retrieve cloud credential details by cloud Id
*CloudCredentialAPI* | [**CloudcredentialsLockManager**](docs/CloudCredentialAPI.md#cloudcredentialslockmanager) | **Post** /api/v1/cloudcredentials/lockmanager | Lock/Unlock cloud credential
*CloudCredentialAPI* | [**CloudcredentialsMakeDefault**](docs/CloudCredentialAPI.md#cloudcredentialsmakedefault) | **Post** /api/v1/cloudcredentials/makedefault | Make cloud credentials default
*CloudCredentialAPI* | [**CloudcredentialsOrgList**](docs/CloudCredentialAPI.md#cloudcredentialsorglist) | **Get** /api/v1/cloudcredentials | Retrieve a list of cloud credentials by organization Id
*CommonAPI* | [**CommonCountries**](docs/CommonAPI.md#commoncountries) | **Get** /api/v1/common/countries | Retrieve country list
*CommonAPI* | [**CommonEnumValues**](docs/CommonAPI.md#commonenumvalues) | **Get** /api/v1/common/enumvalues | Retrieve enum values
*CommonAPI* | [**CommonIpRangeCount**](docs/CommonAPI.md#commoniprangecount) | **Post** /api/v1/common/ip-range-count | Retrieve ip address range count
*CommonAPI* | [**CommonIpRangeList**](docs/CommonAPI.md#commoniprangelist) | **Post** /api/v1/common/ip-range-list | Retrieve ip address range list
*CommonAPI* | [**CommonSortingElements**](docs/CommonAPI.md#commonsortingelements) | **Get** /api/v1/common/sorting-elements/{type} |
*CronJobServiceAPI* | [**CronjobAutoUpgradeProjects**](docs/CronJobServiceAPI.md#cronjobautoupgradeprojects) | **Post** /api/v1/cronjob/auto-upgrade-projects | Upgrade projects that auto-upgrade option enabled
*CronJobServiceAPI* | [**CronjobBlockOrganization**](docs/CronJobServiceAPI.md#cronjobblockorganization) | **Post** /api/v1/cronjob/block-organization | Block organization
*CronJobServiceAPI* | [**CronjobCancelExpiredSubscriptions**](docs/CronJobServiceAPI.md#cronjobcancelexpiredsubscriptions) | **Post** /api/v1/cronjob/cancel-expired-subscriptions | Cancel expired subscriptions
*CronJobServiceAPI* | [**CronjobCreateKeyPool**](docs/CronJobServiceAPI.md#cronjobcreatekeypool) | **Post** /api/v1/cronjob/create-key-pool | Create key pool
*CronJobServiceAPI* | [**CronjobDeleteExpiredAlerts**](docs/CronJobServiceAPI.md#cronjobdeleteexpiredalerts) | **Post** /api/v1/cronjob/alerts | Delete expired alerts
*CronJobServiceAPI* | [**CronjobDeleteExpiredEvents**](docs/CronJobServiceAPI.md#cronjobdeleteexpiredevents) | **Post** /api/v1/cronjob/events | Delete expired events
*CronJobServiceAPI* | [**CronjobDeleteExpiredHistoryLogs**](docs/CronJobServiceAPI.md#cronjobdeleteexpiredhistorylogs) | **Post** /api/v1/cronjob/history-logs | Delete expired history logs
*CronJobServiceAPI* | [**CronjobDeleteExpiredOrgs**](docs/CronJobServiceAPI.md#cronjobdeleteexpiredorgs) | **Post** /api/v1/cronjob/delete-expired-organizations | Delete registration expired organizations
*CronJobServiceAPI* | [**CronjobDeleteExpiredRefreshTokens**](docs/CronJobServiceAPI.md#cronjobdeleteexpiredrefreshtokens) | **Post** /api/v1/cronjob/refresh-tokens | Delete expired refresh tokens
*CronJobServiceAPI* | [**CronjobDeleteExpiredRequests**](docs/CronJobServiceAPI.md#cronjobdeleteexpiredrequests) | **Post** /api/v1/cronjob/taikun-requests | Delete expired requests
*CronJobServiceAPI* | [**CronjobDeleteExpiredServers**](docs/CronJobServiceAPI.md#cronjobdeleteexpiredservers) | **Post** /api/v1/cronjob/delete-expired-servers | Delete expired servers
*CronJobServiceAPI* | [**CronjobDeleteImportedBackupLocation**](docs/CronJobServiceAPI.md#cronjobdeleteimportedbackuplocation) | **Post** /api/v1/cronjob/backup-locations | Delete imported backup locations
*CronJobServiceAPI* | [**CronjobDeleteKubeConfigs**](docs/CronJobServiceAPI.md#cronjobdeletekubeconfigs) | **Post** /api/v1/cronjob/delete-kube-configs | Remove deleted user's kube config
*CronJobServiceAPI* | [**CronjobDeleteRemovedSpotInstances**](docs/CronJobServiceAPI.md#cronjobdeleteremovedspotinstances) | **Post** /api/v1/cronjob/delete-removed-spot-instances | Delete removed spot instances
*CronJobServiceAPI* | [**CronjobDeleteUselessProjectActions**](docs/CronJobServiceAPI.md#cronjobdeleteuselessprojectactions) | **Post** /api/v1/cronjob/project-actions | Delete useless project actions
*CronJobServiceAPI* | [**CronjobEmailForProjectExpiration**](docs/CronJobServiceAPI.md#cronjobemailforprojectexpiration) | **Post** /api/v1/cronjob/project-expiration | Send email to the users about project expiration
*CronJobServiceAPI* | [**CronjobFetchArtifactOrganizations**](docs/CronJobServiceAPI.md#cronjobfetchartifactorganizations) | **Post** /api/v1/cronjob/fetch-artifact-organizations | Fetch artifact hub organizations
*CronJobServiceAPI* | [**CronjobFetchAzureFlavorPrices**](docs/CronJobServiceAPI.md#cronjobfetchazureflavorprices) | **Post** /api/v1/cronjob/fetch-azure-flavor-prices | Fetch azure flavor prices
*CronJobServiceAPI* | [**CronjobFetchAzureFlavorPricesWithEuro**](docs/CronJobServiceAPI.md#cronjobfetchazureflavorpriceswitheuro) | **Post** /api/v1/cronjob/fetch-azure-flavor-prices-with-euro | Fetch azure flavor prices with euro
*CronJobServiceAPI* | [**CronjobFetchK8sAlertData**](docs/CronJobServiceAPI.md#cronjobfetchk8salertdata) | **Post** /api/v1/cronjob/fetch-k8s-alert-data | Fetch k8s alert data
*CronJobServiceAPI* | [**CronjobFetchK8sOverviewData**](docs/CronJobServiceAPI.md#cronjobfetchk8soverviewdata) | **Post** /api/v1/cronjob/fetch-k8s-overview-data | Fetch k8s overview data
*CronJobServiceAPI* | [**CronjobFetchOrganizationDetails**](docs/CronJobServiceAPI.md#cronjobfetchorganizationdetails) | **Post** /api/v1/cronjob/fetch-organization-details | Fetch organization details
*CronJobServiceAPI* | [**CronjobKubeConfigCleaner**](docs/CronJobServiceAPI.md#cronjobkubeconfigcleaner) | **Post** /api/v1/cronjob/kube-config-cleaner | Clean kube config
*CronJobServiceAPI* | [**CronjobPurgeExpiredProjects**](docs/CronJobServiceAPI.md#cronjobpurgeexpiredprojects) | **Post** /api/v1/cronjob/purge-expired-projects | Purge expired projects
*CronJobServiceAPI* | [**CronjobRemindUsersByAlertingProfile**](docs/CronJobServiceAPI.md#cronjobremindusersbyalertingprofile) | **Post** /api/v1/cronjob/remind-users-by-alerting-profile | Remind users by alerting profile
*CronJobServiceAPI* | [**CronjobSyncAppProxy**](docs/CronJobServiceAPI.md#cronjobsyncappproxy) | **Post** /api/v1/cronjob/sync-app-proxy | Sync app proxy command
*CronJobServiceAPI* | [**CronjobSyncBackupCredentials**](docs/CronJobServiceAPI.md#cronjobsyncbackupcredentials) | **Post** /api/v1/cronjob/sync-backup-credentials | Sync backup credentials
*CronJobServiceAPI* | [**CronjobSyncOpaProfiles**](docs/CronJobServiceAPI.md#cronjobsyncopaprofiles) | **Post** /api/v1/cronjob/sync-opa-profiles | Sync opa profiles
*CronJobServiceAPI* | [**CronjobSyncOrganizations**](docs/CronJobServiceAPI.md#cronjobsyncorganizations) | **Post** /api/v1/cronjob/sync-organizations | Sync organizations
*CronJobServiceAPI* | [**CronjobSyncProjectApps**](docs/CronJobServiceAPI.md#cronjobsyncprojectapps) | **Post** /api/v1/cronjob/sync-project-apps | Sync project apps
*CronJobServiceAPI* | [**CronjobSyncProjects**](docs/CronJobServiceAPI.md#cronjobsyncprojects) | **Post** /api/v1/cronjob/sync-projects | Sync projects
*CronJobServiceAPI* | [**CronjobTriggerTemplates**](docs/CronJobServiceAPI.md#cronjobtriggertemplates) | **Post** /api/v1/cronjob/trigger-templates | Trigger scheduled templates
*CronJobServiceAPI* | [**CronjobUpdateProjectAppStatus**](docs/CronJobServiceAPI.md#cronjobupdateprojectappstatus) | **Post** /api/v1/cronjob/update-project-app-status | Update project app status
*CronJobServiceAPI* | [**CronjobUpdateProjectQuotaMessage**](docs/CronJobServiceAPI.md#cronjobupdateprojectquotamessage) | **Post** /api/v1/cronjob/update-project-quota-message | Update project quota message
*DnsServersAPI* | [**DnsserversCreate**](docs/DnsServersAPI.md#dnsserverscreate) | **Post** /api/v1/dnsservers/create | Create dns servers for access profile
*DnsServersAPI* | [**DnsserversDelete**](docs/DnsServersAPI.md#dnsserversdelete) | **Delete** /api/v1/dnsservers/{id} | Delete dns server
*DnsServersAPI* | [**DnsserversEdit**](docs/DnsServersAPI.md#dnsserversedit) | **Put** /api/v1/dnsservers/edit/{id} | Edit dns server
*DnsServersAPI* | [**DnsserversList**](docs/DnsServersAPI.md#dnsserverslist) | **Get** /api/v1/dnsservers/{accessProfileId} | List dn servers by profile id
*FlavorsAPI* | [**FlavorsAwsInstanceTypes**](docs/FlavorsAPI.md#flavorsawsinstancetypes) | **Get** /api/v1/flavors/aws/{cloudId} |
*FlavorsAPI* | [**FlavorsAzureVmSizes**](docs/FlavorsAPI.md#flavorsazurevmsizes) | **Get** /api/v1/flavors/azure/{cloudId} |
*FlavorsAPI* | [**FlavorsBindToProject**](docs/FlavorsAPI.md#flavorsbindtoproject) | **Post** /api/v1/flavors/bind | Bind flavors to project
*FlavorsAPI* | [**FlavorsDropdownFlavors**](docs/FlavorsAPI.md#flavorsdropdownflavors) | **Get** /api/v1/flavors/credentials/dropdown/list | Retrieve cloud credentials dropdown list
*FlavorsAPI* | [**FlavorsGoogleMachineTypes**](docs/FlavorsAPI.md#flavorsgooglemachinetypes) | **Get** /api/v1/flavors/google/{cloudId} |
*FlavorsAPI* | [**FlavorsOpenshiftFlavors**](docs/FlavorsAPI.md#flavorsopenshiftflavors) | **Get** /api/v1/flavors/openshift/{cloudId} | Retrieve openshift flavors
*FlavorsAPI* | [**FlavorsOpenstackFlavors**](docs/FlavorsAPI.md#flavorsopenstackflavors) | **Get** /api/v1/flavors/openstack/{cloudId} |
*FlavorsAPI* | [**FlavorsProxmoxFlavors**](docs/FlavorsAPI.md#flavorsproxmoxflavors) | **Get** /api/v1/flavors/proxmox/{cloudId} | Retrieve proxmox flavors
*FlavorsAPI* | [**FlavorsSelectedFlavorsForProject**](docs/FlavorsAPI.md#flavorsselectedflavorsforproject) | **Get** /api/v1/flavors/projects/list | Retrieve selected flavors for project
*FlavorsAPI* | [**FlavorsTanzuFlavors**](docs/FlavorsAPI.md#flavorstanzuflavors) | **Get** /api/v1/flavors/tanzu/{cloudId} | Retrieve tanzu flavors
*FlavorsAPI* | [**FlavorsUnbindFromProject**](docs/FlavorsAPI.md#flavorsunbindfromproject) | **Post** /api/v1/flavors/unbind | Unbind flavors from project
*GoogleAPI* | [**GooglecloudBillingAccountList**](docs/GoogleAPI.md#googlecloudbillingaccountlist) | **Post** /api/v1/googlecloud/billing-accounts |
*GoogleAPI* | [**GooglecloudCreate**](docs/GoogleAPI.md#googlecloudcreate) | **Post** /api/v1/googlecloud/create |
*GoogleAPI* | [**GooglecloudList**](docs/GoogleAPI.md#googlecloudlist) | **Get** /api/v1/googlecloud/list | Retrieve list of google cloud credentials
*GoogleAPI* | [**GooglecloudRegionList**](docs/GoogleAPI.md#googlecloudregionlist) | **Post** /api/v1/googlecloud/regions |
*GoogleAPI* | [**GooglecloudZoneList**](docs/GoogleAPI.md#googlecloudzonelist) | **Post** /api/v1/googlecloud/zones/{region} |
*ImagesAPI* | [**ImagesAwsCommonImages**](docs/ImagesAPI.md#imagesawscommonimages) | **Get** /api/v1/images/aws/common/{cloudId} | Commonly used aws images
*ImagesAPI* | [**ImagesAwsImagesList**](docs/ImagesAPI.md#imagesawsimageslist) | **Post** /api/v1/images/aws | Retrieve aws images
*ImagesAPI* | [**ImagesAwsPersonalImages**](docs/ImagesAPI.md#imagesawspersonalimages) | **Get** /api/v1/images/aws/personal/{cloudId} | Aws personal images
*ImagesAPI* | [**ImagesAzureCommonImages**](docs/ImagesAPI.md#imagesazurecommonimages) | **Get** /api/v1/images/azure/common/{cloudId} | Commonly used azure images
*ImagesAPI* | [**ImagesAzureImages**](docs/ImagesAPI.md#imagesazureimages) | **Get** /api/v1/images/azure/{cloudId}/{publisherName}/{offer}/{sku} |
*ImagesAPI* | [**ImagesAzurePersonalImages**](docs/ImagesAPI.md#imagesazurepersonalimages) | **Get** /api/v1/images/azure/personal/{cloudId} | Azure personal images
*ImagesAPI* | [**ImagesBindImagesToProject**](docs/ImagesAPI.md#imagesbindimagestoproject) | **Post** /api/v1/images/bind | Bind images to project
*ImagesAPI* | [**ImagesCommonGoogleImages**](docs/ImagesAPI.md#imagescommongoogleimages) | **Get** /api/v1/images/google/common/{cloudId} | Commonly used google images
*ImagesAPI* | [**ImagesGoogleImages**](docs/ImagesAPI.md#imagesgoogleimages) | **Get** /api/v1/images/google/{cloudId}/{type} |
*ImagesAPI* | [**ImagesImageDetails**](docs/ImagesAPI.md#imagesimagedetails) | **Post** /api/v1/images/details | Get image details
*ImagesAPI* | [**ImagesOpenstackImages**](docs/ImagesAPI.md#imagesopenstackimages) | **Get** /api/v1/images/openstack/{cloudId} | Retrieve openstack images
*ImagesAPI* | [**ImagesProxmoxImages**](docs/ImagesAPI.md#imagesproxmoximages) | **Get** /api/v1/images/proxmox/{cloudId} | Retrieve proxmox images
*ImagesAPI* | [**ImagesSelectedImagesForProject**](docs/ImagesAPI.md#imagesselectedimagesforproject) | **Get** /api/v1/images/projects/list | Retrieve selected images for projects
*ImagesAPI* | [**ImagesTanzuImages**](docs/ImagesAPI.md#imagestanzuimages) | **Get** /api/v1/images/tanzu/{cloudId} | Retrieve tanzu images
*ImagesAPI* | [**ImagesUnbindImagesFromProject**](docs/ImagesAPI.md#imagesunbindimagesfromproject) | **Post** /api/v1/images/unbind | Unbind images from project
*InfraAPI* | [**InfraCreate**](docs/InfraAPI.md#infracreate) | **Post** /api/v1/infra/create | Create infra product
*InfraAPI* | [**InfraDetails**](docs/InfraAPI.md#infradetails) | **Get** /api/v1/infra/details | Retrieve infra details
*InfraAPI* | [**InfraOrganizationsList**](docs/InfraAPI.md#infraorganizationslist) | **Get** /api/v1/infra/organizations-list | Retrieve infra products list
*InfraAPI* | [**InfraProductList**](docs/InfraAPI.md#infraproductlist) | **Get** /api/v1/infra/list | Retrieve infra products list
*InfraBillingSummaryAPI* | [**InfraBillingSummaryCreate**](docs/InfraBillingSummaryAPI.md#infrabillingsummarycreate) | **Post** /api/v1/infra-billing-summary/create | Add infra billing summary
*InfraBillingSummaryAPI* | [**InfraBillingSummaryList**](docs/InfraBillingSummaryAPI.md#infrabillingsummarylist) | **Post** /api/v1/infra-billing-summary/list | Retrieve infra billing info
*InvoicesAPI* | [**InvoicesCreate**](docs/InvoicesAPI.md#invoicescreate) | **Post** /api/v1/invoices/create | Create invoice
*InvoicesAPI* | [**InvoicesDownload**](docs/InvoicesAPI.md#invoicesdownload) | **Post** /api/v1/invoices/download | Download invoice
*InvoicesAPI* | [**InvoicesList**](docs/InvoicesAPI.md#invoiceslist) | **Get** /api/v1/invoices/list | Invoices list
*InvoicesAPI* | [**InvoicesUpdate**](docs/InvoicesAPI.md#invoicesupdate) | **Put** /api/v1/invoices/update/{invoiceId} | Update invoice
*KeycloakAPI* | [**KeycloakCreate**](docs/KeycloakAPI.md#keycloakcreate) | **Post** /api/v1/keycloak/create | Create keycloak configuration for organization
*KeycloakAPI* | [**KeycloakDelete**](docs/KeycloakAPI.md#keycloakdelete) | **Post** /api/v1/keycloak/delete | Delete keycloak configuration
*KeycloakAPI* | [**KeycloakEdit**](docs/KeycloakAPI.md#keycloakedit) | **Post** /api/v1/keycloak/edit | Edit keycloak configuration for organization
*KeycloakAPI* | [**KeycloakList**](docs/KeycloakAPI.md#keycloaklist) | **Get** /api/v1/keycloak | Get keycloak configuration
*KubeConfigAPI* | [**KubeconfigCreate**](docs/KubeConfigAPI.md#kubeconfigcreate) | **Post** /api/v1/kubeconfig | Create kube config
*KubeConfigAPI* | [**KubeconfigDelete**](docs/KubeConfigAPI.md#kubeconfigdelete) | **Post** /api/v1/kubeconfig/delete | Delete kube config
*KubeConfigAPI* | [**KubeconfigDeleteByProjectId**](docs/KubeConfigAPI.md#kubeconfigdeletebyprojectid) | **Post** /api/v1/kubeconfig/delete-by-project-id | Delete kube config by project id
*KubeConfigAPI* | [**KubeconfigDownload**](docs/KubeConfigAPI.md#kubeconfigdownload) | **Post** /api/v1/kubeconfig/download | Download kube config file for user by project Id
*KubeConfigAPI* | [**KubeconfigExport**](docs/KubeConfigAPI.md#kubeconfigexport) | **Post** /api/v1/kubeconfig/export | Export
*KubeConfigAPI* | [**KubeconfigInteractiveShell**](docs/KubeConfigAPI.md#kubeconfiginteractiveshell) | **Post** /api/v1/kubeconfig/interactive-shell | Interactive shell for user kube config
*KubeConfigAPI* | [**KubeconfigList**](docs/KubeConfigAPI.md#kubeconfiglist) | **Get** /api/v1/kubeconfig | Retrieve a list of kube configs for project
*KubeConfigRoleAPI* | [**KubeconfigroleList**](docs/KubeConfigRoleAPI.md#kubeconfigrolelist) | **Get** /api/v1/kubeconfigrole | Retrieve list of kube config role
*KubernetesAPI* | [**KubernetesAddK8sAlert**](docs/KubernetesAPI.md#kubernetesaddk8salert) | **Post** /api/v1/kubernetes/alert/{projectId} | Add k8s alert
*KubernetesAPI* | [**KubernetesAddK8sEvents**](docs/KubernetesAPI.md#kubernetesaddk8sevents) | **Post** /api/v1/kubernetes/event/{projectId} | Add k8s event
*KubernetesAPI* | [**KubernetesAlertList**](docs/KubernetesAPI.md#kubernetesalertlist) | **Get** /api/v1/kubernetes/{projectId}/alerts | Retrieve a list of alerts for project
*KubernetesAPI* | [**KubernetesCli**](docs/KubernetesAPI.md#kubernetescli) | **Post** /api/v1/kubernetes/cli | Execute k8s web socket namespaced pod
*KubernetesAPI* | [**KubernetesConfigMapList**](docs/KubernetesAPI.md#kubernetesconfigmaplist) | **Get** /api/v1/kubernetes/{projectId}/configmap | Retrieve a list of k8s config map for all namespaces
*KubernetesAPI* | [**KubernetesCrdList**](docs/KubernetesAPI.md#kubernetescrdlist) | **Get** /api/v1/kubernetes/{projectId}/crd | Retrieve a list of crd
*KubernetesAPI* | [**KubernetesCronJobList**](docs/KubernetesAPI.md#kubernetescronjoblist) | **Get** /api/v1/kubernetes/{projectId}/cronjobs | Retrieve a list of k8s cron jobs for all namespaces
*KubernetesAPI* | [**KubernetesDaemonSetList**](docs/KubernetesAPI.md#kubernetesdaemonsetlist) | **Get** /api/v1/kubernetes/{projectId}/daemonset | Retrieve list of k8s daemonset
*KubernetesAPI* | [**KubernetesDashboardList**](docs/KubernetesAPI.md#kubernetesdashboardlist) | **Get** /api/v1/kubernetes/{projectId}/dashboard | Retrieve a list of crd
*KubernetesAPI* | [**KubernetesDeploymentList**](docs/KubernetesAPI.md#kubernetesdeploymentlist) | **Get** /api/v1/kubernetes/{projectId}/deployment | Retrieve a list of k8s deployment for all namespaces
*KubernetesAPI* | [**KubernetesDescribeConfigMap**](docs/KubernetesAPI.md#kubernetesdescribeconfigmap) | **Post** /api/v1/kubernetes/describe/configmap | Describe configmap
*KubernetesAPI* | [**KubernetesDescribeCrd**](docs/KubernetesAPI.md#kubernetesdescribecrd) | **Post** /api/v1/kubernetes/describe/crd | Describe crd
*KubernetesAPI* | [**KubernetesDescribeCronjob**](docs/KubernetesAPI.md#kubernetesdescribecronjob) | **Post** /api/v1/kubernetes/describe/cronjob | Describe cronjob
*KubernetesAPI* | [**KubernetesDescribeDaemonSet**](docs/KubernetesAPI.md#kubernetesdescribedaemonset) | **Post** /api/v1/kubernetes/describe/daemonset | Describe daemonset
*KubernetesAPI* | [**KubernetesDescribeDeployment**](docs/KubernetesAPI.md#kubernetesdescribedeployment) | **Post** /api/v1/kubernetes/describe/deployment | Describe deployment
*KubernetesAPI* | [**KubernetesDescribeIngress**](docs/KubernetesAPI.md#kubernetesdescribeingress) | **Post** /api/v1/kubernetes/describe/ingress | Describe ingress
*KubernetesAPI* | [**KubernetesDescribeJob**](docs/KubernetesAPI.md#kubernetesdescribejob) | **Post** /api/v1/kubernetes/describe/job | Describe job
*KubernetesAPI* | [**KubernetesDescribeNetworkPolicy**](docs/KubernetesAPI.md#kubernetesdescribenetworkpolicy) | **Post** /api/v1/kubernetes/describe/network-policy | Describe network policy
*KubernetesAPI* | [**KubernetesDescribeNode**](docs/KubernetesAPI.md#kubernetesdescribenode) | **Post** /api/v1/kubernetes/describe/node | Describe node
*KubernetesAPI* | [**KubernetesDescribePdb**](docs/KubernetesAPI.md#kubernetesdescribepdb) | **Post** /api/v1/kubernetes/describe/pdb | Describe pdb
*KubernetesAPI* | [**KubernetesDescribePod**](docs/KubernetesAPI.md#kubernetesdescribepod) | **Post** /api/v1/kubernetes/describe/pod | Describe pod
*KubernetesAPI* | [**KubernetesDescribePvc**](docs/KubernetesAPI.md#kubernetesdescribepvc) | **Post** /api/v1/kubernetes/describe/pvc | Describe pvc
*KubernetesAPI* | [**KubernetesDescribeSecret**](docs/KubernetesAPI.md#kubernetesdescribesecret) | **Post** /api/v1/kubernetes/describe/secret | Describe secret
*KubernetesAPI* | [**KubernetesDescribeService**](docs/KubernetesAPI.md#kubernetesdescribeservice) | **Post** /api/v1/kubernetes/describe/service | Describe service
*KubernetesAPI* | [**KubernetesDescribeStorageClass**](docs/KubernetesAPI.md#kubernetesdescribestorageclass) | **Post** /api/v1/kubernetes/describe/storageclass | Describe storage class
*KubernetesAPI* | [**KubernetesDescribeSts**](docs/KubernetesAPI.md#kubernetesdescribests) | **Post** /api/v1/kubernetes/describe/sts | Describe stateful set
*KubernetesAPI* | [**KubernetesDownload**](docs/KubernetesAPI.md#kubernetesdownload) | **Get** /api/v1/kubernetes/{projectId}/download | Download kube config file
*KubernetesAPI* | [**KubernetesExport**](docs/KubernetesAPI.md#kubernetesexport) | **Get** /api/v1/kubernetes/export | Export
*KubernetesAPI* | [**KubernetesGetSupportedList**](docs/KubernetesAPI.md#kubernetesgetsupportedlist) | **Get** /api/v1/kubernetes/supported/list | Retrieve Taikun supported kubernetes versions
*KubernetesAPI* | [**KubernetesHelmReleaseList**](docs/KubernetesAPI.md#kuberneteshelmreleaselist) | **Get** /api/v1/kubernetes/{projectId}/helmreleases | Retrieve a list of k8s helm releases for all namespaces
*KubernetesAPI* | [**KubernetesIngressList**](docs/KubernetesAPI.md#kubernetesingresslist) | **Get** /api/v1/kubernetes/{projectId}/ingress | Retrieve a list of k8s ingress for all namespaces
*KubernetesAPI* | [**KubernetesInteractiveShell**](docs/KubernetesAPI.md#kubernetesinteractiveshell) | **Post** /api/v1/kubernetes/interactive-shell | Produce interactive shell command
*KubernetesAPI* | [**KubernetesJobsList**](docs/KubernetesAPI.md#kubernetesjobslist) | **Get** /api/v1/kubernetes/{projectId}/jobs | Retrieve a list of k8s jobs for all namespaces
*KubernetesAPI* | [**KubernetesKillPod**](docs/KubernetesAPI.md#kuberneteskillpod) | **Post** /api/v1/kubernetes/{projectId}/deletepod/{metadataName}/{namespace} |
*KubernetesAPI* | [**KubernetesKubeConfig**](docs/KubernetesAPI.md#kuberneteskubeconfig) | **Get** /api/v1/kubernetes/{projectId}/kubeconfig | Retrieve kube config file
*KubernetesAPI* | [**KubernetesNamespaceList**](docs/KubernetesAPI.md#kubernetesnamespacelist) | **Get** /api/v1/kubernetes/{projectId}/namespaces | Retrieve kube config file
*KubernetesAPI* | [**KubernetesNetworkPolicyList**](docs/KubernetesAPI.md#kubernetesnetworkpolicylist) | **Get** /api/v1/kubernetes/{projectId}/network-policies | Retrieve a list of k8s network-policies for all namespaces
*KubernetesAPI* | [**KubernetesNodeList**](docs/KubernetesAPI.md#kubernetesnodelist) | **Get** /api/v1/kubernetes/{projectId}/node | Retrieve a list of k8s node
*KubernetesAPI* | [**KubernetesOverview**](docs/KubernetesAPI.md#kubernetesoverview) | **Get** /api/v1/kubernetes/overview | Overview kubernetes nodes and pods by organization id
*KubernetesAPI* | [**KubernetesPatchCrd**](docs/KubernetesAPI.md#kubernetespatchcrd) | **Post** /api/v1/kubernetes/patch/crd | Patch crd
*KubernetesAPI* | [**KubernetesPatchCronJob**](docs/KubernetesAPI.md#kubernetespatchcronjob) | **Post** /api/v1/kubernetes/patch/cronjob | Patch cron-job
*KubernetesAPI* | [**KubernetesPatchIngress**](docs/KubernetesAPI.md#kubernetespatchingress) | **Post** /api/v1/kubernetes/patch/ingress | Patch ingress
*KubernetesAPI* | [**KubernetesPatchJob**](docs/KubernetesAPI.md#kubernetespatchjob) | **Post** /api/v1/kubernetes/patch/job | Patch job
*KubernetesAPI* | [**KubernetesPatchNode**](docs/KubernetesAPI.md#kubernetespatchnode) | **Post** /api/v1/kubernetes/patch/node | Patch node
*KubernetesAPI* | [**KubernetesPatchPdb**](docs/KubernetesAPI.md#kubernetespatchpdb) | **Post** /api/v1/kubernetes/patch/pdb | Patch pdb
*KubernetesAPI* | [**KubernetesPatchPod**](docs/KubernetesAPI.md#kubernetespatchpod) | **Post** /api/v1/kubernetes/patch/pod | Patch pod
*KubernetesAPI* | [**KubernetesPatchPvc**](docs/KubernetesAPI.md#kubernetespatchpvc) | **Post** /api/v1/kubernetes/patch/pvc | Patch pvc
*KubernetesAPI* | [**KubernetesPatchSecret**](docs/KubernetesAPI.md#kubernetespatchsecret) | **Post** /api/v1/kubernetes/patch/secret | Patch secret
*KubernetesAPI* | [**KubernetesPatchSts**](docs/KubernetesAPI.md#kubernetespatchsts) | **Post** /api/v1/kubernetes/patch/sts | Patch sts
*KubernetesAPI* | [**KubernetesPdbList**](docs/KubernetesAPI.md#kubernetespdblist) | **Get** /api/v1/kubernetes/{projectId}/pdb | Retrieve a list of k8s pdb for all namespaces
*KubernetesAPI* | [**KubernetesPodList**](docs/KubernetesAPI.md#kubernetespodlist) | **Get** /api/v1/kubernetes/{projectId}/pod | Retrieve a list of k8s pod for all namespaces
*KubernetesAPI* | [**KubernetesPodLogs**](docs/KubernetesAPI.md#kubernetespodlogs) | **Post** /api/v1/kubernetes/podLogs | Retrieve k8s pod logs
*KubernetesAPI* | [**KubernetesPvcList**](docs/KubernetesAPI.md#kubernetespvclist) | **Get** /api/v1/kubernetes/{projectId}/pvc | Retrieve a list of k8s pvc for all namespaces
*KubernetesAPI* | [**KubernetesQuota**](docs/KubernetesAPI.md#kubernetesquota) | **Get** /api/v1/kubernetes/{projectId}/quota | K8s quota usage
*KubernetesAPI* | [**KubernetesRemovealerts**](docs/KubernetesAPI.md#kubernetesremovealerts) | **Post** /api/v1/kubernetes/removealerts | Remove k8s alerts
*KubernetesAPI* | [**KubernetesRestartDaemonSet**](docs/KubernetesAPI.md#kubernetesrestartdaemonset) | **Post** /api/v1/kubernetes/restart/daemonset | Restart daemon set
*KubernetesAPI* | [**KubernetesRestartDeployment**](docs/KubernetesAPI.md#kubernetesrestartdeployment) | **Post** /api/v1/kubernetes/restart/deployment | Restart deployment
*KubernetesAPI* | [**KubernetesRestartSts**](docs/KubernetesAPI.md#kubernetesrestartsts) | **Post** /api/v1/kubernetes/restart/sts | Restart stateful set
*KubernetesAPI* | [**KubernetesSecretList**](docs/KubernetesAPI.md#kubernetessecretlist) | **Get** /api/v1/kubernetes/{projectId}/secret | Retrieve a list of k8s secret for all namespaces
*KubernetesAPI* | [**KubernetesServiceList**](docs/KubernetesAPI.md#kubernetesservicelist) | **Get** /api/v1/kubernetes/{projectId}/service | Retrieve a list of k8s service for all namespaces
*KubernetesAPI* | [**KubernetesSilenceManager**](docs/KubernetesAPI.md#kubernetessilencemanager) | **Post** /api/v1/kubernetes/silencemanager | Silence management for k8s alerts
*KubernetesAPI* | [**KubernetesStorageClassList**](docs/KubernetesAPI.md#kubernetesstorageclasslist) | **Get** /api/v1/kubernetes/{projectId}/storageclass | Retrieve a list of k8s storageclass for all namespaces
*KubernetesAPI* | [**KubernetesStsList**](docs/KubernetesAPI.md#kubernetesstslist) | **Get** /api/v1/kubernetes/{projectId}/sts | Retrieve a list of k8s sts for all namespaces
*KubernetesAPI* | [**KubernetesUpdateAlert**](docs/KubernetesAPI.md#kubernetesupdatealert) | **Put** /api/v1/kubernetes/updatealert/{alertId} | Update k8s alert
*KubernetesProfilesAPI* | [**KubernetesprofilesCreate**](docs/KubernetesProfilesAPI.md#kubernetesprofilescreate) | **Post** /api/v1/kubernetesprofiles | Add kubernetes profile
*KubernetesProfilesAPI* | [**KubernetesprofilesDelete**](docs/KubernetesProfilesAPI.md#kubernetesprofilesdelete) | **Delete** /api/v1/kubernetesprofiles/{id} | Delete kubernetes profile
*KubernetesProfilesAPI* | [**KubernetesprofilesDropdown**](docs/KubernetesProfilesAPI.md#kubernetesprofilesdropdown) | **Get** /api/v1/kubernetesprofiles | Retrieve all kubernetes profiles for organization
*KubernetesProfilesAPI* | [**KubernetesprofilesList**](docs/KubernetesProfilesAPI.md#kubernetesprofileslist) | **Get** /api/v1/kubernetesprofiles/list | Retrieve all kubernetes profiles
*KubernetesProfilesAPI* | [**KubernetesprofilesLockManager**](docs/KubernetesProfilesAPI.md#kubernetesprofileslockmanager) | **Post** /api/v1/kubernetesprofiles/lockmanager | Kubernetes profile lock/unlock
*KubesprayAPI* | [**KubesprayCreate**](docs/KubesprayAPI.md#kubespraycreate) | **Post** /api/v1/kubespray | Add kubespray
*KubesprayAPI* | [**KubesprayDelete**](docs/KubesprayAPI.md#kubespraydelete) | **Delete** /api/v1/kubespray/{id} | Delete kubespray
*KubesprayAPI* | [**KubesprayList**](docs/KubesprayAPI.md#kubespraylist) | **Get** /api/v1/kubespray/list | Retrieve all kubespray versions
*NotificationsAPI* | [**NotificationsCreate**](docs/NotificationsAPI.md#notificationscreate) | **Post** /api/v1/notifications/add | Create notification
*NotificationsAPI* | [**NotificationsExportCsv**](docs/NotificationsAPI.md#notificationsexportcsv) | **Get** /api/v1/notifications/download | Export Csv
*NotificationsAPI* | [**NotificationsList**](docs/NotificationsAPI.md#notificationslist) | **Get** /api/v1/notifications/list | Retrieve all notifications
*NotificationsAPI* | [**NotificationsNotifyOwner**](docs/NotificationsAPI.md#notificationsnotifyowner) | **Post** /api/v1/notifications/notifyowner | Notify owner
*NotificationsAPI* | [**NotificationsOperationMessages**](docs/NotificationsAPI.md#notificationsoperationmessages) | **Post** /api/v1/notifications/operations | Get project operations
*NtpServersAPI* | [**NtpserversCreate**](docs/NtpServersAPI.md#ntpserverscreate) | **Post** /api/v1/ntpservers/create | Create access profile ntp server
*NtpServersAPI* | [**NtpserversDelete**](docs/NtpServersAPI.md#ntpserversdelete) | **Delete** /api/v1/ntpservers/{id} | Delete access profile ntp server
*NtpServersAPI* | [**NtpserversEdit**](docs/NtpServersAPI.md#ntpserversedit) | **Put** /api/v1/ntpservers/edit/{id} | Edit access profile ntp server
*NtpServersAPI* | [**NtpserversList**](docs/NtpServersAPI.md#ntpserverslist) | **Get** /api/v1/ntpservers/list/{accessProfileId} | List ntp server by access profile id
*OpaProfilesAPI* | [**OpaprofilesCreate**](docs/OpaProfilesAPI.md#opaprofilescreate) | **Post** /api/v1/opaprofiles/create | Add policy profile
*OpaProfilesAPI* | [**OpaprofilesDelete**](docs/OpaProfilesAPI.md#opaprofilesdelete) | **Delete** /api/v1/opaprofiles/{id} | Remove Opa profile by Id
*OpaProfilesAPI* | [**OpaprofilesDisableGatekeeper**](docs/OpaProfilesAPI.md#opaprofilesdisablegatekeeper) | **Post** /api/v1/opaprofiles/disablegatekeeper | Disable Gatekeeper by the projectId
*OpaProfilesAPI* | [**OpaprofilesDropdown**](docs/OpaProfilesAPI.md#opaprofilesdropdown) | **Get** /api/v1/opaprofiles/list | Retrieve policy profiles for organization
*OpaProfilesAPI* | [**OpaprofilesEnableGatekeeper**](docs/OpaProfilesAPI.md#opaprofilesenablegatekeeper) | **Post** /api/v1/opaprofiles/enablegatekeeper | Enable Gatekeeper by the projectId
*OpaProfilesAPI* | [**OpaprofilesList**](docs/OpaProfilesAPI.md#opaprofileslist) | **Get** /api/v1/opaprofiles | Retrieve all policy profiles
*OpaProfilesAPI* | [**OpaprofilesLockManager**](docs/OpaProfilesAPI.md#opaprofileslockmanager) | **Post** /api/v1/opaprofiles/lockmanager | Lock/Unlock policy profile
*OpaProfilesAPI* | [**OpaprofilesMakeDefault**](docs/OpaProfilesAPI.md#opaprofilesmakedefault) | **Post** /api/v1/opaprofiles/make-default | Choose default policy profile
*OpaProfilesAPI* | [**OpaprofilesSync**](docs/OpaProfilesAPI.md#opaprofilessync) | **Post** /api/v1/opaprofiles/sync | Sync policy profile
*OpaProfilesAPI* | [**OpaprofilesUpdate**](docs/OpaProfilesAPI.md#opaprofilesupdate) | **Put** /api/v1/opaprofiles | Update policy profile
*OpenshiftAPI* | [**OpenshiftCreate**](docs/OpenshiftAPI.md#openshiftcreate) | **Post** /api/v1/openshift/create | Add Openshift cloud credential
*OpenshiftAPI* | [**OpenshiftList**](docs/OpenshiftAPI.md#openshiftlist) | **Get** /api/v1/openshift/list | Retrieve all operation credentials
*OpenshiftAPI* | [**OpenshiftPullSecret**](docs/OpenshiftAPI.md#openshiftpullsecret) | **Post** /api/v1/openshift/pull-secret |
*OpenshiftAPI* | [**OpenshiftStorageClass**](docs/OpenshiftAPI.md#openshiftstorageclass) | **Post** /api/v1/openshift/storage-class |
*OpenshiftAPI* | [**OpenshiftValidate**](docs/OpenshiftAPI.md#openshiftvalidate) | **Post** /api/v1/openshift/validate |
*OpenstackCloudCredentialAPI* | [**OpenstackCreate**](docs/OpenstackCloudCredentialAPI.md#openstackcreate) | **Post** /api/v1/openstack/create | Add Openstack credentials
*OpenstackCloudCredentialAPI* | [**OpenstackList**](docs/OpenstackCloudCredentialAPI.md#openstacklist) | **Get** /api/v1/openstack/list | Retrieve list of openstack cloud credentials
*OpenstackCloudCredentialAPI* | [**OpenstackNetworks**](docs/OpenstackCloudCredentialAPI.md#openstacknetworks) | **Post** /api/v1/openstack/networks | Openstack network list
*OpenstackCloudCredentialAPI* | [**OpenstackProjects**](docs/OpenstackCloudCredentialAPI.md#openstackprojects) | **Post** /api/v1/openstack/projects | Openstack project list
*OpenstackCloudCredentialAPI* | [**OpenstackQuotas**](docs/OpenstackCloudCredentialAPI.md#openstackquotas) | **Post** /api/v1/openstack/quotas | Openstack quota list
*OpenstackCloudCredentialAPI* | [**OpenstackRegionList**](docs/OpenstackCloudCredentialAPI.md#openstackregionlist) | **Post** /api/v1/openstack/regions | Retrieve Openstack regions
*OpenstackCloudCredentialAPI* | [**OpenstackSubnet**](docs/OpenstackCloudCredentialAPI.md#openstacksubnet) | **Post** /api/v1/openstack/subnets | Retrieve Openstack subnets
*OpenstackCloudCredentialAPI* | [**OpenstackUpdate**](docs/OpenstackCloudCredentialAPI.md#openstackupdate) | **Post** /api/v1/openstack/update | Update Openstack credentials
*OpenstackCloudCredentialAPI* | [**OpenstackVolumes**](docs/OpenstackCloudCredentialAPI.md#openstackvolumes) | **Post** /api/v1/openstack/volumes | Openstack volume list
*OpenstackCloudCredentialAPI* | [**OpenstackZones**](docs/OpenstackCloudCredentialAPI.md#openstackzones) | **Post** /api/v1/openstack/zones | Fetch Openstack zones
*OperationCredentialsAPI* | [**OpscredentialsCreate**](docs/OperationCredentialsAPI.md#opscredentialscreate) | **Post** /api/v1/opscredentials | Add Operation credentials
*OperationCredentialsAPI* | [**OpscredentialsDelete**](docs/OperationCredentialsAPI.md#opscredentialsdelete) | **Delete** /api/v1/opscredentials/{id} | Remove Operation credential by Id
*OperationCredentialsAPI* | [**OpscredentialsList**](docs/OperationCredentialsAPI.md#opscredentialslist) | **Get** /api/v1/opscredentials/list | Retrieve all operation credentials
*OperationCredentialsAPI* | [**OpscredentialsListByOrganizationId**](docs/OperationCredentialsAPI.md#opscredentialslistbyorganizationid) | **Get** /api/v1/opscredentials | Retrieve operation credentials by organization Id
*OperationCredentialsAPI* | [**OpscredentialsLockManager**](docs/OperationCredentialsAPI.md#opscredentialslockmanager) | **Post** /api/v1/opscredentials/lockmanager | Lock/Unlock operation credential
*OperationCredentialsAPI* | [**OpscredentialsMakeDefault**](docs/OperationCredentialsAPI.md#opscredentialsmakedefault) | **Post** /api/v1/opscredentials/makedefault | Choose default operation credential
*OperationCredentialsAPI* | [**OpscredentialsMetricNames**](docs/OperationCredentialsAPI.md#opscredentialsmetricnames) | **Get** /api/v1/opscredentials/{id}/metric/names | Fetch prometheus metric names
*OrganizationSubscriptionsAPI* | [**OrganizationsubcriptionsList**](docs/OrganizationSubscriptionsAPI.md#organizationsubcriptionslist) | **Get** /api/v1/organizationsubcriptions | Retrieve all organization subscriptions
*OrganizationSubscriptionsAPI* | [**OrganizationsubcriptionsUpdate**](docs/OrganizationSubscriptionsAPI.md#organizationsubcriptionsupdate) | **Post** /api/v1/organizationsubcriptions/update | Update subscription
*OrganizationsAPI* | [**OrganizationsAcceptOffer**](docs/OrganizationsAPI.md#organizationsacceptoffer) | **Post** /api/v1/organizations/accept-offer | Accept discount offer
*OrganizationsAPI* | [**OrganizationsAccessForPartner**](docs/OrganizationsAPI.md#organizationsaccessforpartner) | **Post** /api/v1/organizations/access-for partner | Give access to partner
*OrganizationsAPI* | [**OrganizationsCreate**](docs/OrganizationsAPI.md#organizationscreate) | **Post** /api/v1/organizations | Add a new organization. Only available for admins.
*OrganizationsAPI* | [**OrganizationsDelete**](docs/OrganizationsAPI.md#organizationsdelete) | **Delete** /api/v1/organizations/{id} | Delete the specified organization. Only available for admins.
*OrganizationsAPI* | [**OrganizationsDetawils**](docs/OrganizationsAPI.md#organizationsdetawils) | **Get** /api/v1/organizations/details | Retrieve all data about current organization by Id
*OrganizationsAPI* | [**OrganizationsExportCsv**](docs/OrganizationsAPI.md#organizationsexportcsv) | **Get** /api/v1/organizations/export | Export Csv file
*OrganizationsAPI* | [**OrganizationsLeave**](docs/OrganizationsAPI.md#organizationsleave) | **Post** /api/v1/organizations/leave | Leave taikun
*OrganizationsAPI* | [**OrganizationsList**](docs/OrganizationsAPI.md#organizationslist) | **Get** /api/v1/organizations | Retrieve all organizations
*OrganizationsAPI* | [**OrganizationsOrganizationList**](docs/OrganizationsAPI.md#organizationsorganizationlist) | **Get** /api/v1/organizations/list | Retrieve organizations
*OrganizationsAPI* | [**OrganizationsToggle**](docs/OrganizationsAPI.md#organizationstoggle) | **Post** /api/v1/organizations/toggle/keycloak | Toggle keycloak login option
*OrganizationsAPI* | [**OrganizationsUpdate**](docs/OrganizationsAPI.md#organizationsupdate) | **Post** /api/v1/organizations/update | Update organization by Id
*OrganizationsAPI* | [**OrganizationsUpdatePayment**](docs/OrganizationsAPI.md#organizationsupdatepayment) | **Post** /api/v1/organizations/updatepaymentmethod | Update organization payment Id
*PackageAPI* | [**PackageDetails**](docs/PackageAPI.md#packagedetails) | **Get** /api/v1/package/{repoName}/{packageName} |
*PackageAPI* | [**PackageList**](docs/PackageAPI.md#packagelist) | **Get** /api/v1/package/list | Retrieve all available packages
*PackageAPI* | [**PackageValue**](docs/PackageAPI.md#packagevalue) | **Post** /api/v1/package/value | Get yaml based value
*PackageAPI* | [**PackageValueAutocomplete**](docs/PackageAPI.md#packagevalueautocomplete) | **Post** /api/v1/package/value-autocomplete | Get autocomplete dictionary
*PackageAPI* | [**PackageVersions**](docs/PackageAPI.md#packageversions) | **Post** /api/v1/package/versions | Get available versions
*PartnersAPI* | [**PartnerAddWhitelistDomain**](docs/PartnersAPI.md#partneraddwhitelistdomain) | **Post** /api/v1/partner/add/whitelist/domain | Add white list domain
*PartnersAPI* | [**PartnerBecomeAPartner**](docs/PartnersAPI.md#partnerbecomeapartner) | **Post** /api/v1/partner/become-a-partner | Become a partner
*PartnersAPI* | [**PartnerBindOrganizations**](docs/PartnersAPI.md#partnerbindorganizations) | **Post** /api/v1/partner/bindorganizations | Bind organizations to a partner
*PartnersAPI* | [**PartnerContactUs**](docs/PartnersAPI.md#partnercontactus) | **Post** /api/v1/partner/contact-us | Contact with us
*PartnersAPI* | [**PartnerCreate**](docs/PartnersAPI.md#partnercreate) | **Post** /api/v1/partner/create |
*PartnersAPI* | [**PartnerDeleteWhitelistDomain**](docs/PartnersAPI.md#partnerdeletewhitelistdomain) | **Post** /api/v1/partner/delete/whitelist/domain | Delete white list domain
*PartnersAPI* | [**PartnerDetails**](docs/PartnersAPI.md#partnerdetails) | **Get** /api/v1/partner/details | Details of partners
*PartnersAPI* | [**PartnerDropdown**](docs/PartnersAPI.md#partnerdropdown) | **Get** /api/v1/partner/list | Get partners dropdown
*PartnersAPI* | [**PartnerInfo**](docs/PartnersAPI.md#partnerinfo) | **Get** /api/v1/partner/info | Get partner's registration info
*PartnersAPI* | [**PartnerList**](docs/PartnersAPI.md#partnerlist) | **Get** /api/v1/partner | Get partners
*PartnersAPI* | [**PartnerUpdate**](docs/PartnersAPI.md#partnerupdate) | **Put** /api/v1/partner/update/{id} |
*PaymentsAPI* | [**PaymentBillingInfo**](docs/PaymentsAPI.md#paymentbillinginfo) | **Get** /api/v1/payment/billing-info | Get billing info for organization
*PaymentsAPI* | [**PaymentCardinfo**](docs/PaymentsAPI.md#paymentcardinfo) | **Get** /api/v1/payment/cardinfo | Get card information
*PaymentsAPI* | [**PaymentClear**](docs/PaymentsAPI.md#paymentclear) | **Post** /api/v1/payment/clear | Clear payment
*PaymentsAPI* | [**PaymentCreateCustomer**](docs/PaymentsAPI.md#paymentcreatecustomer) | **Post** /api/v1/payment/createcustomer | Create customer
*PaymentsAPI* | [**PaymentFinalPrice**](docs/PaymentsAPI.md#paymentfinalprice) | **Post** /api/v1/payment/finalprice | Fetch final price
*PaymentsAPI* | [**PaymentGetStripeInvoices**](docs/PaymentsAPI.md#paymentgetstripeinvoices) | **Get** /api/v1/payment/stripeinvoices/{subscriptionId} |
*PaymentsAPI* | [**PaymentPay**](docs/PaymentsAPI.md#paymentpay) | **Post** /api/v1/payment/pay | Pay invoice
*PaymentsAPI* | [**PaymentUpdateCard**](docs/PaymentsAPI.md#paymentupdatecard) | **Post** /api/v1/payment/updatecard | Update payment card
*PaymentsAPI* | [**PaymentWebhook**](docs/PaymentsAPI.md#paymentwebhook) | **Post** /api/v1/payment/webhook | Listen to payment webhook
*PreDefinedQueriesAPI* | [**PredefinedqueriesCreate**](docs/PreDefinedQueriesAPI.md#predefinedqueriescreate) | **Post** /api/v1/predefinedqueries/prometheus/dashboard/create | Create prometheus dashboard pre defined query
*PreDefinedQueriesAPI* | [**PredefinedqueriesDelete**](docs/PreDefinedQueriesAPI.md#predefinedqueriesdelete) | **Delete** /api/v1/predefinedqueries/prometheus/dashboard/delete/{id} | Delete prometheus dashboard pre defined query
*PreDefinedQueriesAPI* | [**PredefinedqueriesList**](docs/PreDefinedQueriesAPI.md#predefinedquerieslist) | **Get** /api/v1/predefinedqueries/prometheus/dashboard/list/{projectId} | Get list of pre defined organization prometheus dashboard elements
*PreDefinedQueriesAPI* | [**PredefinedqueriesPrometheusDashboardCommon**](docs/PreDefinedQueriesAPI.md#predefinedqueriesprometheusdashboardcommon) | **Get** /api/v1/predefinedqueries/prometheus/dashboard/common/{projectId} | et list of pre defined common prometheus dashboard elements
*PreDefinedQueriesAPI* | [**PredefinedqueriesUpdate**](docs/PreDefinedQueriesAPI.md#predefinedqueriesupdate) | **Post** /api/v1/predefinedqueries/prometheus/dashboard/update | Update prometheus dashboard pre defined query
*ProjectActionsAPI* | [**ProjectactionsDelete**](docs/ProjectActionsAPI.md#projectactionsdelete) | **Delete** /api/v1/projectactions/{projectId} | Delete the project action
*ProjectActionsAPI* | [**ProjectactionsEdit**](docs/ProjectActionsAPI.md#projectactionsedit) | **Put** /api/v1/projectactions/edit/{projectId} | Update project action by projectId
*ProjectAppParamsAPI* | [**ProjectappparamEdit**](docs/ProjectAppParamsAPI.md#projectappparamedit) | **Put** /api/v1/projectappparam/edit/{projectAppId} | Edit project app params
*ProjectAppsAPI* | [**ProjectappAutosync**](docs/ProjectAppsAPI.md#projectappautosync) | **Post** /api/v1/projectapp/autosync | AutoSync management
*ProjectAppsAPI* | [**ProjectappDelete**](docs/ProjectAppsAPI.md#projectappdelete) | **Delete** /api/v1/projectapp/uninstall/{projectAppId} | Uninstall application
*ProjectAppsAPI* | [**ProjectappDetails**](docs/ProjectAppsAPI.md#projectappdetails) | **Get** /api/v1/projectapp/{id} | Retrieve project app's details
*ProjectAppsAPI* | [**ProjectappInstall**](docs/ProjectAppsAPI.md#projectappinstall) | **Post** /api/v1/projectapp/install | Install an application
*ProjectAppsAPI* | [**ProjectappList**](docs/ProjectAppsAPI.md#projectapplist) | **Get** /api/v1/projectapp/list | Retrieve all project apps according to current organization
*ProjectAppsAPI* | [**ProjectappLockManager**](docs/ProjectAppsAPI.md#projectapplockmanager) | **Post** /api/v1/projectapp/lockmanager | Lock/Unlock project app
*ProjectAppsAPI* | [**ProjectappSync**](docs/ProjectAppsAPI.md#projectappsync) | **Post** /api/v1/projectapp/sync | Sync an application
*ProjectGroupsAPI* | [**ProjectgroupsBind**](docs/ProjectGroupsAPI.md#projectgroupsbind) | **Post** /api/v1/projectgroups/bind | Bind User groups
*ProjectGroupsAPI* | [**ProjectgroupsCreate**](docs/ProjectGroupsAPI.md#projectgroupscreate) | **Post** /api/v1/projectgroups/create | Add Project groups
*ProjectGroupsAPI* | [**ProjectgroupsDelete**](docs/ProjectGroupsAPI.md#projectgroupsdelete) | **Delete** /api/v1/projectgroups | Remove Project group(s)
*ProjectGroupsAPI* | [**ProjectgroupsEdit**](docs/ProjectGroupsAPI.md#projectgroupsedit) | **Put** /api/v1/projectgroups/update/{projectGroupId} | Update project groups
*ProjectGroupsAPI* | [**ProjectgroupsList**](docs/ProjectGroupsAPI.md#projectgroupslist) | **Get** /api/v1/projectgroups/list | Retrieve list of Project groups
*ProjectGroupsAPI* | [**ProjectgroupsListByUserId**](docs/ProjectGroupsAPI.md#projectgroupslistbyuserid) | **Get** /api/v1/projectgroups/list/{userGroupId} | Retrieve list of Project groups by user group id for dropdown
*ProjectGroupsAPI* | [**ProjectgroupsProjectList**](docs/ProjectGroupsAPI.md#projectgroupsprojectlist) | **Get** /api/v1/projectgroups/{projectGroupId}/projects | Retrieve list of projects by project group id
*ProjectInfracostsAPI* | [**ProjectinfracostsDelete**](docs/ProjectInfracostsAPI.md#projectinfracostsdelete) | **Delete** /api/v1/projectinfracosts/{projectId} | Delete the project infracost
*ProjectInfracostsAPI* | [**ProjectinfracostsDetails**](docs/ProjectInfracostsAPI.md#projectinfracostsdetails) | **Get** /api/v1/projectinfracosts/{projectId} | Project Infracost details
*ProjectInfracostsAPI* | [**ProjectinfracostsUpsert**](docs/ProjectInfracostsAPI.md#projectinfracostsupsert) | **Post** /api/v1/projectinfracosts/upsert/{projectId} | Upsert project infracost by ProjectId
*ProjectQuotasAPI* | [**ProjectquotasList**](docs/ProjectQuotasAPI.md#projectquotaslist) | **Get** /api/v1/projectquotas | Retrieve all project quotas
*ProjectQuotasAPI* | [**ProjectquotasUpdate**](docs/ProjectQuotasAPI.md#projectquotasupdate) | **Post** /api/v1/projectquotas/update | Edit project quota
*ProjectRevisionsAPI* | [**ProjectrevisionsEdit**](docs/ProjectRevisionsAPI.md#projectrevisionsedit) | **Put** /api/v1/projectrevisions/edit/{projectId} | Update project revision by ProjectId for poller
*ProjectTemplatesAPI* | [**ProjecttemplateCreate**](docs/ProjectTemplatesAPI.md#projecttemplatecreate) | **Post** /api/v1/projecttemplate/create | Create project from template
*ProjectTemplatesAPI* | [**ProjecttemplateDelete**](docs/ProjectTemplatesAPI.md#projecttemplatedelete) | **Delete** /api/v1/projecttemplate/{id} | Delete project template by Id
*ProjectTemplatesAPI* | [**ProjecttemplateDropdown**](docs/ProjectTemplatesAPI.md#projecttemplatedropdown) | **Get** /api/v1/projecttemplate/list | Retrieve project template by organization Id
*ProjectTemplatesAPI* | [**ProjecttemplateList**](docs/ProjectTemplatesAPI.md#projecttemplatelist) | **Get** /api/v1/projecttemplate | Retrieve all project templates
*ProjectsAPI* | [**ProjectsAiAnalyzer**](docs/ProjectsAPI.md#projectsaianalyzer) | **Get** /api/v1/projects/ai-analyze/{projectId} | Analyze cluster by AI model
*ProjectsAPI* | [**ProjectsAlerts**](docs/ProjectsAPI.md#projectsalerts) | **Get** /api/v1/projects/alerts/{projectId} | Project alerts
*ProjectsAPI* | [**ProjectsChatCompletions**](docs/ProjectsAPI.md#projectschatcompletions) | **Post** /api/v1/projects/chat/completions | AI Chat completions
*ProjectsAPI* | [**ProjectsCommit**](docs/ProjectsAPI.md#projectscommit) | **Post** /api/v1/projects/commit/{projectId} | Commit changes for the given project. The changes will then be applied and the project will be updated. The project must be in the READY state.
*ProjectsAPI* | [**ProjectsCreate**](docs/ProjectsAPI.md#projectscreate) | **Post** /api/v1/projects | Create a new project
*ProjectsAPI* | [**ProjectsDelete**](docs/ProjectsAPI.md#projectsdelete) | **Post** /api/v1/projects/delete | Delete the project. The project must be empty (no server) and in READY state
*ProjectsAPI* | [**ProjectsDeleteWholeProject**](docs/ProjectsAPI.md#projectsdeletewholeproject) | **Post** /api/v1/projects/deletewholeproject | Delete whole project by project Id
*ProjectsAPI* | [**ProjectsDescribe**](docs/ProjectsAPI.md#projectsdescribe) | **Get** /api/v1/projects/describe/{projectId} | Describe project by Id
*ProjectsAPI* | [**ProjectsDetails**](docs/ProjectsAPI.md#projectsdetails) | **Get** /api/v1/projects/{projectId} | Retrieve details of the project by Id
*ProjectsAPI* | [**ProjectsDropdown**](docs/ProjectsAPI.md#projectsdropdown) | **Get** /api/v1/projects/list | Retrieve list of projects for dropdown
*ProjectsAPI* | [**ProjectsEdit**](docs/ProjectsAPI.md#projectsedit) | **Put** /api/v1/projects/edit/{projectId} | Update project by Id for poller
*ProjectsAPI* | [**ProjectsEditHealth**](docs/ProjectsAPI.md#projectsedithealth) | **Put** /api/v1/projects/edit/health | Update health status of the project by Id
*ProjectsAPI* | [**ProjectsEditStatus**](docs/ProjectsAPI.md#projectseditstatus) | **Put** /api/v1/projects/edit/status | Change the project status for the given project. Only available for admin.
*ProjectsAPI* | [**ProjectsExtendLifetime**](docs/ProjectsAPI.md#projectsextendlifetime) | **Post** /api/v1/projects/extend/lifetime | Extend life time of project
*ProjectsAPI* | [**ProjectsForAlerting**](docs/ProjectsAPI.md#projectsforalerting) | **Get** /api/v1/projects/foralerting | Retrieve a list of projects for alert poller. Only available for admins.
*ProjectsAPI* | [**ProjectsForBilling**](docs/ProjectsAPI.md#projectsforbilling) | **Get** /api/v1/projects/forbilling | Retrieve a list of projects for billing
*ProjectsAPI* | [**ProjectsForPoller**](docs/ProjectsAPI.md#projectsforpoller) | **Get** /api/v1/projects/forpoller | Retrieve a list of projects for poller. Only available for admins.
*ProjectsAPI* | [**ProjectsList**](docs/ProjectsAPI.md#projectslist) | **Get** /api/v1/projects | Retrieve all projects
*ProjectsAPI* | [**ProjectsLockManager**](docs/ProjectsAPI.md#projectslockmanager) | **Post** /api/v1/projects/lockmanager | Lock/Unlock project
*ProjectsAPI* | [**ProjectsLokiLogs**](docs/ProjectsAPI.md#projectslokilogs) | **Post** /api/v1/projects/lokilogs | Retrieve loki logs
*ProjectsAPI* | [**ProjectsMonitoring**](docs/ProjectsAPI.md#projectsmonitoring) | **Post** /api/v1/projects/monitoring | Monitoring operations enable/disable
*ProjectsAPI* | [**ProjectsMonitoringAlerts**](docs/ProjectsAPI.md#projectsmonitoringalerts) | **Post** /api/v1/projects/monitoringalerts | Monitoring alerts for project
*ProjectsAPI* | [**ProjectsPrometheusMetrics**](docs/ProjectsAPI.md#projectsprometheusmetrics) | **Post** /api/v1/projects/prometheusmetrics | Prometheus metrics data project
*ProjectsAPI* | [**ProjectsPurge**](docs/ProjectsAPI.md#projectspurge) | **Post** /api/v1/projects/purge | Purge a list of servers from project by project Id
*ProjectsAPI* | [**ProjectsPurgeWholeProject**](docs/ProjectsAPI.md#projectspurgewholeproject) | **Post** /api/v1/projects/purgewholeproject | Purge a whole project by project Id
*ProjectsAPI* | [**ProjectsRepair**](docs/ProjectsAPI.md#projectsrepair) | **Post** /api/v1/projects/repair/{projectId} | Repair project by Id
*ProjectsAPI* | [**ProjectsToggleFullSpot**](docs/ProjectsAPI.md#projectstogglefullspot) | **Post** /api/v1/projects/toggle-full-spot | Full spot operations enable/disable
*ProjectsAPI* | [**ProjectsToggleSpotVms**](docs/ProjectsAPI.md#projectstogglespotvms) | **Post** /api/v1/projects/toggle-spot-vms | Spot vm(s) operations enable/disable
*ProjectsAPI* | [**ProjectsToggleSpotWorkers**](docs/ProjectsAPI.md#projectstogglespotworkers) | **Post** /api/v1/projects/toggle-spot-workers | Spot worker(s) operations enable/disable
*ProjectsAPI* | [**ProjectsUpgrade**](docs/ProjectsAPI.md#projectsupgrade) | **Post** /api/v1/projects/upgrade/{projectId} | Upgrade the project's Kubernetes to the next available version. Project must be READY.
*ProjectsAPI* | [**ProjectsVisibility**](docs/ProjectsAPI.md#projectsvisibility) | **Get** /api/v1/projects/visibility/{projectId} | Visibility of project actions
*PrometheusBillingsAPI* | [**PrometheusbillingsCreate**](docs/PrometheusBillingsAPI.md#prometheusbillingscreate) | **Post** /api/v1/prometheusbillings | Add prometheus billing
*PrometheusBillingsAPI* | [**PrometheusbillingsExportCsv**](docs/PrometheusBillingsAPI.md#prometheusbillingsexportcsv) | **Get** /api/v1/prometheusbillings/export | Export Csv
*PrometheusBillingsAPI* | [**PrometheusbillingsGroupedList**](docs/PrometheusBillingsAPI.md#prometheusbillingsgroupedlist) | **Get** /api/v1/prometheusbillings/grouped | Retrieve a list of grouped prometheus billing
*PrometheusBillingsAPI* | [**PrometheusbillingsList**](docs/PrometheusBillingsAPI.md#prometheusbillingslist) | **Get** /api/v1/prometheusbillings | Retrieve all prometheus billing
*PrometheusOrganizationsAPI* | [**PrometheusorganizationsBindRules**](docs/PrometheusOrganizationsAPI.md#prometheusorganizationsbindrules) | **Post** /api/v1/prometheusorganizations/bind/rules | Bind rules to organizations
*PrometheusRulesAPI* | [**PrometheusrulesBindOrganizations**](docs/PrometheusRulesAPI.md#prometheusrulesbindorganizations) | **Post** /api/v1/prometheusrules/bind/organizations | Bind organizations to prometheus rule
*PrometheusRulesAPI* | [**PrometheusrulesCreate**](docs/PrometheusRulesAPI.md#prometheusrulescreate) | **Post** /api/v1/prometheusrules | Add prometheus rule
*PrometheusRulesAPI* | [**PrometheusrulesDelete**](docs/PrometheusRulesAPI.md#prometheusrulesdelete) | **Delete** /api/v1/prometheusrules/{id} | Remove prometheus rule
*PrometheusRulesAPI* | [**PrometheusrulesDetails**](docs/PrometheusRulesAPI.md#prometheusrulesdetails) | **Get** /api/v1/prometheusrules/details | Retrieve all prometheus rules with detailed info
*PrometheusRulesAPI* | [**PrometheusrulesList**](docs/PrometheusRulesAPI.md#prometheusruleslist) | **Get** /api/v1/prometheusrules | Retrieve a list of prometheus rules
*PrometheusRulesAPI* | [**PrometheusrulesUpdate**](docs/PrometheusRulesAPI.md#prometheusrulesupdate) | **Put** /api/v1/prometheusrules/edit/{id} | Edit prometheus rule
*ProxmoxCloudCredentialAPI* | [**ProxmoxBridgeList**](docs/ProxmoxCloudCredentialAPI.md#proxmoxbridgelist) | **Post** /api/v1/proxmox/bridge-list | Fetch proxmox bridge list
*ProxmoxCloudCredentialAPI* | [**ProxmoxCreate**](docs/ProxmoxCloudCredentialAPI.md#proxmoxcreate) | **Post** /api/v1/proxmox/create | Add Proxmox credentials
*ProxmoxCloudCredentialAPI* | [**ProxmoxHypervisorList**](docs/ProxmoxCloudCredentialAPI.md#proxmoxhypervisorlist) | **Post** /api/v1/proxmox/hypervisor-list | Fetch proxmox hypervisor list
*ProxmoxCloudCredentialAPI* | [**ProxmoxList**](docs/ProxmoxCloudCredentialAPI.md#proxmoxlist) | **Get** /api/v1/proxmox/list | Retrieve list of proxmox cloud credentials
*ProxmoxCloudCredentialAPI* | [**ProxmoxStorageList**](docs/ProxmoxCloudCredentialAPI.md#proxmoxstoragelist) | **Post** /api/v1/proxmox/storage-list | Fetch proxmox storage list
*ProxmoxCloudCredentialAPI* | [**ProxmoxUpdate**](docs/ProxmoxCloudCredentialAPI.md#proxmoxupdate) | **Post** /api/v1/proxmox/update | Update proxmox credentials
*ProxmoxCloudCredentialAPI* | [**ProxmoxUpdateHypervisors**](docs/ProxmoxCloudCredentialAPI.md#proxmoxupdatehypervisors) | **Post** /api/v1/proxmox/update/hypervisors | Update proxmox credentials
*ProxmoxCloudCredentialAPI* | [**ProxmoxUpdateIpAddresses**](docs/ProxmoxCloudCredentialAPI.md#proxmoxupdateipaddresses) | **Post** /api/v1/proxmox/update/ip-addresses | Update proxmox network used ip addresses
*ProxmoxCloudCredentialAPI* | [**ProxmoxVmTemplateList**](docs/ProxmoxCloudCredentialAPI.md#proxmoxvmtemplatelist) | **Post** /api/v1/proxmox/vm-template-list | Fetch proxmox vm template list
*S3CredentialsAPI* | [**S3credentialsCreate**](docs/S3CredentialsAPI.md#s3credentialscreate) | **Post** /api/v1/s3credentials | Add s3 credential
*S3CredentialsAPI* | [**S3credentialsDelete**](docs/S3CredentialsAPI.md#s3credentialsdelete) | **Delete** /api/v1/s3credentials/{id} | Delete s3 credential
*S3CredentialsAPI* | [**S3credentialsDropdown**](docs/S3CredentialsAPI.md#s3credentialsdropdown) | **Get** /api/v1/s3credentials | Retrieve all S3 credentials for organization
*S3CredentialsAPI* | [**S3credentialsList**](docs/S3CredentialsAPI.md#s3credentialslist) | **Get** /api/v1/s3credentials/list | Retrieve all S3 credentials
*S3CredentialsAPI* | [**S3credentialsLockManagement**](docs/S3CredentialsAPI.md#s3credentialslockmanagement) | **Post** /api/v1/s3credentials/lockmanager | Lock/unlock s3 credential
*S3CredentialsAPI* | [**S3credentialsMakeDeafult**](docs/S3CredentialsAPI.md#s3credentialsmakedeafult) | **Post** /api/v1/s3credentials/makedefault | Make default s3 credential
*S3CredentialsAPI* | [**S3credentialsUpdate**](docs/S3CredentialsAPI.md#s3credentialsupdate) | **Put** /api/v1/s3credentials | Update s3 credential
*SearchAPI* | [**SearchAccessProfiles**](docs/SearchAPI.md#searchaccessprofiles) | **Post** /api/v1/search/access-profiles | Global search for access-profiles
*SearchAPI* | [**SearchBackupCredentials**](docs/SearchAPI.md#searchbackupcredentials) | **Post** /api/v1/search/backup-credentials | Global search for backup-credentials
*SearchAPI* | [**SearchBillingCredentials**](docs/SearchAPI.md#searchbillingcredentials) | **Post** /api/v1/search/billing-credentials | Global search for billing-credentials
*SearchAPI* | [**SearchCloudCredentials**](docs/SearchAPI.md#searchcloudcredentials) | **Post** /api/v1/search/cloud-credentials | Global search for cloud-credentials
*SearchAPI* | [**SearchConfigMaps**](docs/SearchAPI.md#searchconfigmaps) | **Post** /api/v1/search/config-maps | Global search for config-maps
*SearchAPI* | [**SearchDaemonSets**](docs/SearchAPI.md#searchdaemonsets) | **Post** /api/v1/search/daemon-sets | Global search for daemon-sets
*SearchAPI* | [**SearchDeployments**](docs/SearchAPI.md#searchdeployments) | **Post** /api/v1/search/deployments | Global search for deployments
*SearchAPI* | [**SearchIngress**](docs/SearchAPI.md#searchingress) | **Post** /api/v1/search/ingress | Global search for ingress
*SearchAPI* | [**SearchKubernetesProfiles**](docs/SearchAPI.md#searchkubernetesprofiles) | **Post** /api/v1/search/kubernetes-profiles | Global search for kubernetes-profiles
*SearchAPI* | [**SearchNodes**](docs/SearchAPI.md#searchnodes) | **Post** /api/v1/search/nodes | Global search for nodes
*SearchAPI* | [**SearchOrganizations**](docs/SearchAPI.md#searchorganizations) | **Post** /api/v1/search/organizations | Global search for organizations
*SearchAPI* | [**SearchPartners**](docs/SearchAPI.md#searchpartners) | **Post** /api/v1/search/partners | Global search for partners
*SearchAPI* | [**SearchPods**](docs/SearchAPI.md#searchpods) | **Post** /api/v1/search/pods | Global search for pods
*SearchAPI* | [**SearchProjects**](docs/SearchAPI.md#searchprojects) | **Post** /api/v1/search/projects | Global search for projects
*SearchAPI* | [**SearchPrometheusRules**](docs/SearchAPI.md#searchprometheusrules) | **Post** /api/v1/search/prometheus-rules | Global search for prometheus-rules
*SearchAPI* | [**SearchPvcs**](docs/SearchAPI.md#searchpvcs) | **Post** /api/v1/search/pvcs | Global search for pvcs
*SearchAPI* | [**SearchSecrets**](docs/SearchAPI.md#searchsecrets) | **Post** /api/v1/search/secrets | Global search for secrets
*SearchAPI* | [**SearchServers**](docs/SearchAPI.md#searchservers) | **Post** /api/v1/search/servers | Global search for servers
*SearchAPI* | [**SearchServices**](docs/SearchAPI.md#searchservices) | **Post** /api/v1/search/services | Global search for services
*SearchAPI* | [**SearchStandAloneProfiles**](docs/SearchAPI.md#searchstandaloneprofiles) | **Post** /api/v1/search/stand-alone-profiles | Global search for stand-alone-profiles
*SearchAPI* | [**SearchSts**](docs/SearchAPI.md#searchsts) | **Post** /api/v1/search/sts | Global search for sts
*SearchAPI* | [**SearchUsers**](docs/SearchAPI.md#searchusers) | **Post** /api/v1/search/users | Global search for users
*SecurityGroupAPI* | [**SecuritygroupCreate**](docs/SecurityGroupAPI.md#securitygroupcreate) | **Post** /api/v1/securitygroup/create | Create standalonealone profile security group
*SecurityGroupAPI* | [**SecuritygroupDelete**](docs/SecurityGroupAPI.md#securitygroupdelete) | **Delete** /api/v1/securitygroup/{id} | Delete standalone profile security group
*SecurityGroupAPI* | [**SecuritygroupEdit**](docs/SecurityGroupAPI.md#securitygroupedit) | **Put** /api/v1/securitygroup/edit | Edit standalone profile security group
*SecurityGroupAPI* | [**SecuritygroupList**](docs/SecurityGroupAPI.md#securitygrouplist) | **Get** /api/v1/securitygroup/list/{standAloneProfileId} | List stand alone security group by profile id
*ServersAPI* | [**ServersConsole**](docs/ServersAPI.md#serversconsole) | **Post** /api/v1/servers/console | Console screenshot or terminal access for server
*ServersAPI* | [**ServersCreate**](docs/ServersAPI.md#serverscreate) | **Post** /api/v1/servers/create | Create a new server in the given project.
*ServersAPI* | [**ServersDelete**](docs/ServersAPI.md#serversdelete) | **Post** /api/v1/servers/delete | Delete server by project id
*ServersAPI* | [**ServersDetails**](docs/ServersAPI.md#serversdetails) | **Get** /api/v1/servers/{projectId} | Retrieve all servers by given project
*ServersAPI* | [**ServersList**](docs/ServersAPI.md#serverslist) | **Get** /api/v1/servers |
*ServersAPI* | [**ServersReboot**](docs/ServersAPI.md#serversreboot) | **Post** /api/v1/servers/reboot | Reboot server
*ServersAPI* | [**ServersReset**](docs/ServersAPI.md#serversreset) | **Post** /api/v1/servers/reset | Update server(s) status(es)
*ServersAPI* | [**ServersStatus**](docs/ServersAPI.md#serversstatus) | **Get** /api/v1/servers/status/{serverId} | Show server status
*ServersAPI* | [**ServersUpdate**](docs/ServersAPI.md#serversupdate) | **Post** /api/v1/servers/update | Update server
*ServersAPI* | [**ServersUpdateByProjectId**](docs/ServersAPI.md#serversupdatebyprojectid) | **Put** /api/v1/servers/update/{projectId} | Update server by projectId
*SlackAPI* | [**SlackCreate**](docs/SlackAPI.md#slackcreate) | **Post** /api/v1/slack/create | Create slack configuration
*SlackAPI* | [**SlackDeleteMultiple**](docs/SlackAPI.md#slackdeletemultiple) | **Post** /api/v1/slack/delete-multiple | Delete slack configuration(s)
*SlackAPI* | [**SlackDropdown**](docs/SlackAPI.md#slackdropdown) | **Get** /api/v1/slack/list | Retrieve all slack configs for organization
*SlackAPI* | [**SlackList**](docs/SlackAPI.md#slacklist) | **Get** /api/v1/slack | Retrieve all slack configs
*SlackAPI* | [**SlackUpdate**](docs/SlackAPI.md#slackupdate) | **Put** /api/v1/slack/update/{id} | Update slack configuration
*SlackAPI* | [**SlackVerify**](docs/SlackAPI.md#slackverify) | **Post** /api/v1/slack/verify | Verify slack configuration
*SshUsersAPI* | [**SshusersCreate**](docs/SshUsersAPI.md#sshuserscreate) | **Post** /api/v1/sshusers/create | Create access profile ssh user
*SshUsersAPI* | [**SshusersDelete**](docs/SshUsersAPI.md#sshusersdelete) | **Post** /api/v1/sshusers/delete | Delete access profile ssh user
*SshUsersAPI* | [**SshusersEdit**](docs/SshUsersAPI.md#sshusersedit) | **Post** /api/v1/sshusers/edit | Edit access profile ssh user
*SshUsersAPI* | [**SshusersList**](docs/SshUsersAPI.md#sshuserslist) | **Get** /api/v1/sshusers/list/{accessProfileId} | List ssh user by access profile id
*StandaloneAPI* | [**StandaloneCommit**](docs/StandaloneAPI.md#standalonecommit) | **Post** /api/v1/standalone/commit | Commit vm
*StandaloneAPI* | [**StandaloneCreate**](docs/StandaloneAPI.md#standalonecreate) | **Post** /api/v1/standalone/create | Create a new vm in the given project.
*StandaloneAPI* | [**StandaloneDelete**](docs/StandaloneAPI.md#standalonedelete) | **Post** /api/v1/standalone/delete | Delete vm
*StandaloneAPI* | [**StandaloneDetails**](docs/StandaloneAPI.md#standalonedetails) | **Get** /api/v1/standalone/{projectId} | Retrieve a list of standalone vm with detailed info
*StandaloneAPI* | [**StandaloneForPoller**](docs/StandaloneAPI.md#standaloneforpoller) | **Get** /api/v1/standalone/forpoller | List all StandaloneVms for poller
*StandaloneAPI* | [**StandaloneIpManagement**](docs/StandaloneAPI.md#standaloneipmanagement) | **Post** /api/v1/standalone/ip/management | Enable/Disable stand alone public ip
*StandaloneAPI* | [**StandaloneList**](docs/StandaloneAPI.md#standalonelist) | **Get** /api/v1/standalone |
*StandaloneAPI* | [**StandaloneProjectDetails**](docs/StandaloneAPI.md#standaloneprojectdetails) | **Get** /api/v1/standalone/project/{projectId} | Retrieve details of the project by Id
*StandaloneAPI* | [**StandalonePurge**](docs/StandaloneAPI.md#standalonepurge) | **Post** /api/v1/standalone/purge | Purge vm
*StandaloneAPI* | [**StandaloneRepair**](docs/StandaloneAPI.md#standalonerepair) | **Post** /api/v1/standalone/repair | Repair vm
*StandaloneAPI* | [**StandaloneReset**](docs/StandaloneAPI.md#standalonereset) | **Post** /api/v1/standalone/reset | Reset vm status
*StandaloneAPI* | [**StandaloneUpdate**](docs/StandaloneAPI.md#standaloneupdate) | **Post** /api/v1/standalone/update | Update vm
*StandaloneAPI* | [**StandaloneUpdateFlavor**](docs/StandaloneAPI.md#standaloneupdateflavor) | **Post** /api/v1/standalone/update/flavor | Update standalone vm flavor
*StandaloneActionsAPI* | [**StandaloneactionsConsole**](docs/StandaloneActionsAPI.md#standaloneactionsconsole) | **Post** /api/v1/standaloneactions/console | Console screenshot or terminal for vm
*StandaloneActionsAPI* | [**StandaloneactionsDownloadRdp**](docs/StandaloneActionsAPI.md#standaloneactionsdownloadrdp) | **Get** /api/v1/standaloneactions/download/rdp/{id} | Download RDP file
*StandaloneActionsAPI* | [**StandaloneactionsReboot**](docs/StandaloneActionsAPI.md#standaloneactionsreboot) | **Post** /api/v1/standaloneactions/reboot | Reboot standalone vm
*StandaloneActionsAPI* | [**StandaloneactionsShelve**](docs/StandaloneActionsAPI.md#standaloneactionsshelve) | **Post** /api/v1/standaloneactions/shelve | Shelve standalone vm
*StandaloneActionsAPI* | [**StandaloneactionsStart**](docs/StandaloneActionsAPI.md#standaloneactionsstart) | **Post** /api/v1/standaloneactions/start | Start standalone vm
*StandaloneActionsAPI* | [**StandaloneactionsStatus**](docs/StandaloneActionsAPI.md#standaloneactionsstatus) | **Get** /api/v1/standaloneactions/status/{id} | Show standalone vm status
*StandaloneActionsAPI* | [**StandaloneactionsStop**](docs/StandaloneActionsAPI.md#standaloneactionsstop) | **Post** /api/v1/standaloneactions/stop | Stop standalone vm
*StandaloneActionsAPI* | [**StandaloneactionsUnshelve**](docs/StandaloneActionsAPI.md#standaloneactionsunshelve) | **Post** /api/v1/standaloneactions/unshelve | Unshelve standalone vm
*StandaloneActionsAPI* | [**StandaloneactionsWindowsInstancePassword**](docs/StandaloneActionsAPI.md#standaloneactionswindowsinstancepassword) | **Post** /api/v1/standaloneactions/password | Retrieve aws windows admin instance password
*StandaloneProfileAPI* | [**StandaloneprofileCreate**](docs/StandaloneProfileAPI.md#standaloneprofilecreate) | **Post** /api/v1/standaloneprofile/create | Create standalone profile.
*StandaloneProfileAPI* | [**StandaloneprofileDelete**](docs/StandaloneProfileAPI.md#standaloneprofiledelete) | **Post** /api/v1/standaloneprofile/delete | Delete standalone profile.
*StandaloneProfileAPI* | [**StandaloneprofileDropdown**](docs/StandaloneProfileAPI.md#standaloneprofiledropdown) | **Get** /api/v1/standaloneprofile/list | Retrieve all standalone profiles for organization
*StandaloneProfileAPI* | [**StandaloneprofileEdit**](docs/StandaloneProfileAPI.md#standaloneprofileedit) | **Post** /api/v1/standaloneprofile/edit | Edit standalone profile.
*StandaloneProfileAPI* | [**StandaloneprofileList**](docs/StandaloneProfileAPI.md#standaloneprofilelist) | **Get** /api/v1/standaloneprofile | Retrieve all standalone profiles
*StandaloneProfileAPI* | [**StandaloneprofileLockManagement**](docs/StandaloneProfileAPI.md#standaloneprofilelockmanagement) | **Post** /api/v1/standaloneprofile/lockmanager | Lock/unlock standalone profile.
*StandaloneVMDisksAPI* | [**StandalonevmdisksCreate**](docs/StandaloneVMDisksAPI.md#standalonevmdiskscreate) | **Post** /api/v1/standalonevmdisks/create | Add disk for standalone vm
*StandaloneVMDisksAPI* | [**StandalonevmdisksDelete**](docs/StandaloneVMDisksAPI.md#standalonevmdisksdelete) | **Post** /api/v1/standalonevmdisks/delete | Remove disk from standalone vm
*StandaloneVMDisksAPI* | [**StandalonevmdisksPurge**](docs/StandaloneVMDisksAPI.md#standalonevmdiskspurge) | **Post** /api/v1/standalonevmdisks/purge | Purge vm disks
*StandaloneVMDisksAPI* | [**StandalonevmdisksReset**](docs/StandaloneVMDisksAPI.md#standalonevmdisksreset) | **Post** /api/v1/standalonevmdisks/reset | Update status of disk
*StandaloneVMDisksAPI* | [**StandalonevmdisksUpdate**](docs/StandaloneVMDisksAPI.md#standalonevmdisksupdate) | **Post** /api/v1/standalonevmdisks/update | Update disk
*StandaloneVMDisksAPI* | [**StandalonevmdisksUpdateSize**](docs/StandaloneVMDisksAPI.md#standalonevmdisksupdatesize) | **Post** /api/v1/standalonevmdisks/update-size | Update disk size
*StripeAPI* | [**StripeSubscriptionItemList**](docs/StripeAPI.md#stripesubscriptionitemlist) | **Get** /api/v1/stripe/{subscriptionId} |
*SubscriptionAPI* | [**SubscriptionBind**](docs/SubscriptionAPI.md#subscriptionbind) | **Post** /api/v1/subscription/bind | Bind subscription
*SubscriptionAPI* | [**SubscriptionBoundList**](docs/SubscriptionAPI.md#subscriptionboundlist) | **Get** /api/v1/subscription/boundlist | Retrieve subscription for organization bound
*SubscriptionAPI* | [**SubscriptionDelete**](docs/SubscriptionAPI.md#subscriptiondelete) | **Post** /api/v1/subscription/delete | Delete subscription package
*SubscriptionAPI* | [**SubscriptionList**](docs/SubscriptionAPI.md#subscriptionlist) | **Get** /api/v1/subscription | Retrieve private subscription list for partners
*SubscriptionAPI* | [**SubscriptionPublic**](docs/SubscriptionAPI.md#subscriptionpublic) | **Get** /api/v1/subscription/public | Retrieve subscription for organization bound
*SubscriptionAPI* | [**SubscriptionSubscription**](docs/SubscriptionAPI.md#subscriptionsubscription) | **Post** /api/v1/subscription/create | Add new subscription package
*SubscriptionAPI* | [**SubscriptionUpdate**](docs/SubscriptionAPI.md#subscriptionupdate) | **Post** /api/v1/subscription/update | Update subscription
*TanzuAPI* | [**TanzuCreate**](docs/TanzuAPI.md#tanzucreate) | **Post** /api/v1/tanzu/create | Create tanzu credentials
*TanzuAPI* | [**TanzuKubernetesVersions**](docs/TanzuAPI.md#tanzukubernetesversions) | **Get** /api/v1/tanzu/kubernetes-versions/{cloudId} | Tanzu available k8s version list
*TanzuAPI* | [**TanzuList**](docs/TanzuAPI.md#tanzulist) | **Get** /api/v1/tanzu/list | Retrieve list of tanzu cloud credentials
*TanzuAPI* | [**TanzuStorageList**](docs/TanzuAPI.md#tanzustoragelist) | **Post** /api/v1/tanzu/storage-list | Tanzu storage list
*TanzuAPI* | [**TanzuUpdate**](docs/TanzuAPI.md#tanzuupdate) | **Post** /api/v1/tanzu/update | Update tanzu credentials
*TicketAPI* | [**TicketArchive**](docs/TicketAPI.md#ticketarchive) | **Post** /api/v1/ticket/archive | Archive ticket
*TicketAPI* | [**TicketClose**](docs/TicketAPI.md#ticketclose) | **Post** /api/v1/ticket/close | Close ticket
*TicketAPI* | [**TicketCreate**](docs/TicketAPI.md#ticketcreate) | **Post** /api/v1/ticket/create | Create ticket
*TicketAPI* | [**TicketDelete**](docs/TicketAPI.md#ticketdelete) | **Delete** /api/v1/ticket/delete/{ticketId} |
*TicketAPI* | [**TicketDeleteMessage**](docs/TicketAPI.md#ticketdeletemessage) | **Delete** /api/v1/ticket/delete/message/{messageId} |
*TicketAPI* | [**TicketEdit**](docs/TicketAPI.md#ticketedit) | **Post** /api/v1/ticket/edit | Edit ticket
*TicketAPI* | [**TicketEditMessage**](docs/TicketAPI.md#ticketeditmessage) | **Post** /api/v1/ticket/edit/message | Edit ticket message
*TicketAPI* | [**TicketList**](docs/TicketAPI.md#ticketlist) | **Get** /api/v1/ticket/list | Retrieve list of tickets
*TicketAPI* | [**TicketMessages**](docs/TicketAPI.md#ticketmessages) | **Get** /api/v1/ticket/{ticketId}/messages |
*TicketAPI* | [**TicketOpen**](docs/TicketAPI.md#ticketopen) | **Post** /api/v1/ticket/open | Open ticket
*TicketAPI* | [**TicketReply**](docs/TicketAPI.md#ticketreply) | **Post** /api/v1/ticket/reply | Reply message
*TicketAPI* | [**TicketSetPriority**](docs/TicketAPI.md#ticketsetpriority) | **Post** /api/v1/ticket/set-priority | Set priority
*TicketAPI* | [**TicketTransfer**](docs/TicketAPI.md#tickettransfer) | **Post** /api/v1/ticket/transfer | Transfer ticket
*TicketAPI* | [**TicketTransferList**](docs/TicketAPI.md#tickettransferlist) | **Get** /api/v1/ticket/transfer/list | Retrieve organization managers
*UserGroupAPI* | [**UsergroupsBindProjectsGroup**](docs/UserGroupAPI.md#usergroupsbindprojectsgroup) | **Post** /api/v1/usergroups/bind-project-groups | Bind project groups
*UserGroupAPI* | [**UsergroupsCreate**](docs/UserGroupAPI.md#usergroupscreate) | **Post** /api/v1/usergroups/create | Add user groups
*UserGroupAPI* | [**UsergroupsDelete**](docs/UserGroupAPI.md#usergroupsdelete) | **Delete** /api/v1/usergroups | Remove user group(s)
*UserGroupAPI* | [**UsergroupsList**](docs/UserGroupAPI.md#usergroupslist) | **Get** /api/v1/usergroups/list | Retrieve list of user groups
*UserGroupAPI* | [**UsergroupsListByProjectGroupId**](docs/UserGroupAPI.md#usergroupslistbyprojectgroupid) | **Get** /api/v1/usergroups/list-by-project-group-id/{projectGroupId} | Dropdown list
*UserGroupAPI* | [**UsergroupsUpdate**](docs/UserGroupAPI.md#usergroupsupdate) | **Put** /api/v1/usergroups/update/{userGroupId} | Update user groups
*UserGroupAPI* | [**UsergroupsUserGroupUsers**](docs/UserGroupAPI.md#usergroupsusergroupusers) | **Get** /api/v1/usergroups/users/{userGroupId} | Dropdown list
*UserProjectsAPI* | [**UserprojectsBindProjects**](docs/UserProjectsAPI.md#userprojectsbindprojects) | **Post** /api/v1/userprojects/bindprojects | Bind projects to user
*UserProjectsAPI* | [**UserprojectsBindUsers**](docs/UserProjectsAPI.md#userprojectsbindusers) | **Post** /api/v1/userprojects/bindusers | Bind users to project
*UserProjectsAPI* | [**UserprojectsProjectListByUser**](docs/UserProjectsAPI.md#userprojectsprojectlistbyuser) | **Get** /api/v1/userprojects/projects/list | Projects list for user
*UserProjectsAPI* | [**UserprojectsUserListByProject**](docs/UserProjectsAPI.md#userprojectsuserlistbyproject) | **Get** /api/v1/userprojects/users/list/{projectId} | Users list by project id
*UserTokenAPI* | [**UsertokenAvailableEndpoints**](docs/UserTokenAPI.md#usertokenavailableendpoints) | **Get** /api/v1/usertoken/available-endpoints | Get available endpoint list
*UserTokenAPI* | [**UsertokenBindUnbind**](docs/UserTokenAPI.md#usertokenbindunbind) | **Post** /api/v1/usertoken/bind-unbind | Bind and unbind endpoints
*UserTokenAPI* | [**UsertokenCreate**](docs/UserTokenAPI.md#usertokencreate) | **Post** /api/v1/usertoken/create | Create a new user token
*UserTokenAPI* | [**UsertokenDelete**](docs/UserTokenAPI.md#usertokendelete) | **Delete** /api/v1/usertoken/delete/{id} |
*UserTokenAPI* | [**UsertokenList**](docs/UserTokenAPI.md#usertokenlist) | **Get** /api/v1/usertoken/list | Get user token list
*UsersAPI* | [**UsersChangePassword**](docs/UsersAPI.md#userschangepassword) | **Post** /api/v1/users/changepassword | Change user password
*UsersAPI* | [**UsersConfirmEmail**](docs/UsersAPI.md#usersconfirmemail) | **Post** /api/v1/users/confirmemail | Confirm user email
*UsersAPI* | [**UsersCreate**](docs/UsersAPI.md#userscreate) | **Post** /api/v1/users/create | Create user
*UsersAPI* | [**UsersDelete**](docs/UsersAPI.md#usersdelete) | **Delete** /api/v1/users/{id} |
*UsersAPI* | [**UsersDeleteMyAccount**](docs/UsersAPI.md#usersdeletemyaccount) | **Post** /api/v1/users/delete | Delete my account
*UsersAPI* | [**UsersDisable**](docs/UsersAPI.md#usersdisable) | **Post** /api/v1/users/disable | Disable user
*UsersAPI* | [**UsersDropdown**](docs/UsersAPI.md#usersdropdown) | **Get** /api/v1/users/list | Retrieve users as dropdown
*UsersAPI* | [**UsersExportCsv**](docs/UsersAPI.md#usersexportcsv) | **Get** /api/v1/users/export | Export Csv
*UsersAPI* | [**UsersForceToResetPassword**](docs/UsersAPI.md#usersforcetoresetpassword) | **Post** /api/v1/users/force-to-reset | Force to reset password
*UsersAPI* | [**UsersList**](docs/UsersAPI.md#userslist) | **Get** /api/v1/users | Retrieve all users
*UsersAPI* | [**UsersToggleDemoMode**](docs/UsersAPI.md#userstoggledemomode) | **Post** /api/v1/users/toggle-demo-mode | Toggle demo mode
*UsersAPI* | [**UsersToggleMaintenanceMode**](docs/UsersAPI.md#userstogglemaintenancemode) | **Post** /api/v1/users/togglemaintenancemode | Toggle maintenance mode
*UsersAPI* | [**UsersToggleNotificationMode**](docs/UsersAPI.md#userstogglenotificationmode) | **Post** /api/v1/users/togglenotificationmode | Toggle notification mode
*UsersAPI* | [**UsersUpdateUser**](docs/UsersAPI.md#usersupdateuser) | **Post** /api/v1/users/update | Update user
*UsersAPI* | [**UsersUserInfo**](docs/UsersAPI.md#usersuserinfo) | **Get** /api/v1/users/userinfo | Retrieve user info
*UsersAPI* | [**UsersVerifyEmail**](docs/UsersAPI.md#usersverifyemail) | **Post** /api/v1/users/verifyemail | Verify user email
## Documentation For Models
- [AccessProfilesForProjectListDto](docs/AccessProfilesForProjectListDto.md)
- [AccessProfilesList](docs/AccessProfilesList.md)
- [AccessProfilesListDto](docs/AccessProfilesListDto.md)
- [AccessProfilesLockManagementCommand](docs/AccessProfilesLockManagementCommand.md)
- [AccessProfilesSearchCommand](docs/AccessProfilesSearchCommand.md)
- [AccessProfilesSearchList](docs/AccessProfilesSearchList.md)
- [ActionStatus](docs/ActionStatus.md)
- [ActionType](docs/ActionType.md)
- [AdminAddBalanceCommand](docs/AdminAddBalanceCommand.md)
- [AdminBillingOperationCommand](docs/AdminBillingOperationCommand.md)
- [AdminOrganizationsDeleteCommand](docs/AdminOrganizationsDeleteCommand.md)
- [AdminOrganizationsList](docs/AdminOrganizationsList.md)
- [AdminOrganizationsListDto](docs/AdminOrganizationsListDto.md)
- [AdminProjectUpdateCommand](docs/AdminProjectUpdateCommand.md)
- [AdminProjectsList](docs/AdminProjectsList.md)
- [AdminProjectsResponseData](docs/AdminProjectsResponseData.md)
- [AdminUpdateProjectKubeConfigCommand](docs/AdminUpdateProjectKubeConfigCommand.md)
- [AdminUpdateUserKubeConfigCommand](docs/AdminUpdateUserKubeConfigCommand.md)
- [AdminUserCreateCommand](docs/AdminUserCreateCommand.md)
- [AdminUsersList](docs/AdminUsersList.md)
- [AdminUsersResponseData](docs/AdminUsersResponseData.md)
- [AdminUsersUpdateEmailCommand](docs/AdminUsersUpdateEmailCommand.md)
- [AdminUsersUpdatePasswordCommand](docs/AdminUsersUpdatePasswordCommand.md)
- [AiCredentialDto](docs/AiCredentialDto.md)
- [AiCredentials](docs/AiCredentials.md)
- [AiCredentialsForOrganizationEntity](docs/AiCredentialsForOrganizationEntity.md)
- [AiCredentialsListDto](docs/AiCredentialsListDto.md)
- [AiType](docs/AiType.md)
- [AlertingEmailDto](docs/AlertingEmailDto.md)
- [AlertingIntegrationDto](docs/AlertingIntegrationDto.md)
- [AlertingIntegrationType](docs/AlertingIntegrationType.md)
- [AlertingIntegrationsListDto](docs/AlertingIntegrationsListDto.md)
- [AlertingProfilesList](docs/AlertingProfilesList.md)
- [AlertingProfilesListDto](docs/AlertingProfilesListDto.md)
- [AlertingProfilesLockManagerCommand](docs/AlertingProfilesLockManagerCommand.md)
- [AlertingReminder](docs/AlertingReminder.md)
- [AlertingWebhookDto](docs/AlertingWebhookDto.md)
- [AllFlavorsList](docs/AllFlavorsList.md)
- [AllTicketsDto](docs/AllTicketsDto.md)
- [AllTicketsList](docs/AllTicketsList.md)
- [AllowedHostCreateDto](docs/AllowedHostCreateDto.md)
- [AllowedHostList](docs/AllowedHostList.md)
- [AllowedHostListDto](docs/AllowedHostListDto.md)
- [AmazonAvailabilityZonesCommand](docs/AmazonAvailabilityZonesCommand.md)
- [AmazonCredentialsListDto](docs/AmazonCredentialsListDto.md)
- [Annotations](docs/Annotations.md)
- [ApiResponse](docs/ApiResponse.md)
- [AppRepositoryList](docs/AppRepositoryList.md)
- [ArchiveTicketCommand](docs/ArchiveTicketCommand.md)
- [ArticleList](docs/ArticleList.md)
- [ArticlesListDto](docs/ArticlesListDto.md)
- [ArtifactRepositoryDto](docs/ArtifactRepositoryDto.md)
- [ArtifactUrlCheckerCommand](docs/ArtifactUrlCheckerCommand.md)
- [AttachDetachAlertingProfileCommand](docs/AttachDetachAlertingProfileCommand.md)
- [AutoSyncManagementCommand](docs/AutoSyncManagementCommand.md)
- [AutoscalingSyncCommand](docs/AutoscalingSyncCommand.md)
- [AvailableEndpointData](docs/AvailableEndpointData.md)
- [AvailableEndpointsList](docs/AvailableEndpointsList.md)
- [AvailablePackageDetailsDto](docs/AvailablePackageDetailsDto.md)
- [AvailablePackagesDto](docs/AvailablePackagesDto.md)
- [AvailablePackagesList](docs/AvailablePackagesList.md)
- [AwsBlockDeviceMappingsCommand](docs/AwsBlockDeviceMappingsCommand.md)
- [AwsCommonImages](docs/AwsCommonImages.md)
- [AwsCredentialList](docs/AwsCredentialList.md)
- [AwsCredentialsForProjectDto](docs/AwsCredentialsForProjectDto.md)
- [AwsExtendedImagesListDto](docs/AwsExtendedImagesListDto.md)
- [AwsFlavorList](docs/AwsFlavorList.md)
- [AwsFlavorListDto](docs/AwsFlavorListDto.md)
- [AwsImagesPostList](docs/AwsImagesPostList.md)
- [AwsImagesPostListCommand](docs/AwsImagesPostListCommand.md)
- [AwsOwnerDetails](docs/AwsOwnerDetails.md)
- [AwsProjectAZSubnetDto](docs/AwsProjectAZSubnetDto.md)
- [AwsRegionDto](docs/AwsRegionDto.md)
- [AwsValidateOwnerCommand](docs/AwsValidateOwnerCommand.md)
- [AzResult](docs/AzResult.md)
- [AzureCommonImages](docs/AzureCommonImages.md)
- [AzureCredentialList](docs/AzureCredentialList.md)
- [AzureCredentialsForProjectDto](docs/AzureCredentialsForProjectDto.md)
- [AzureCredentialsListDto](docs/AzureCredentialsListDto.md)
- [AzureDashboardCommand](docs/AzureDashboardCommand.md)
- [AzureFlavorList](docs/AzureFlavorList.md)
- [AzureFlavorsWithPriceDto](docs/AzureFlavorsWithPriceDto.md)
- [AzureImageList](docs/AzureImageList.md)
- [AzureLocationsCommand](docs/AzureLocationsCommand.md)
- [AzureOffersList](docs/AzureOffersList.md)
- [AzurePublisherDetails](docs/AzurePublisherDetails.md)
- [AzurePublishersList](docs/AzurePublishersList.md)
- [AzureQuotaListRecordDto](docs/AzureQuotaListRecordDto.md)
- [AzureSkusList](docs/AzureSkusList.md)
- [AzureSubscriptionListCommand](docs/AzureSubscriptionListCommand.md)
- [AzureZonesCommand](docs/AzureZonesCommand.md)
- [BackupCredentials](docs/BackupCredentials.md)
- [BackupCredentialsCreateCommand](docs/BackupCredentialsCreateCommand.md)
- [BackupCredentialsForOrganizationEntity](docs/BackupCredentialsForOrganizationEntity.md)
- [BackupCredentialsListDto](docs/BackupCredentialsListDto.md)
- [BackupCredentialsSearchCommand](docs/BackupCredentialsSearchCommand.md)
- [BackupCredentialsSearchList](docs/BackupCredentialsSearchList.md)
- [BackupCredentialsUpdateCommand](docs/BackupCredentialsUpdateCommand.md)
- [BackupDto](docs/BackupDto.md)
- [BackupLockManagerCommand](docs/BackupLockManagerCommand.md)
- [BackupMakeDefaultCommand](docs/BackupMakeDefaultCommand.md)
- [BackupStorageLocationDto](docs/BackupStorageLocationDto.md)
- [BecomePartnerCommand](docs/BecomePartnerCommand.md)
- [BillingCredentialsSearchCommand](docs/BillingCredentialsSearchCommand.md)
- [BillingCredentialsSearchList](docs/BillingCredentialsSearchList.md)
- [BillingInfo](docs/BillingInfo.md)
- [BillingInfoDto](docs/BillingInfoDto.md)
- [BillingSummaryDto](docs/BillingSummaryDto.md)
- [BindAppRepositoryCommand](docs/BindAppRepositoryCommand.md)
- [BindFlavorToProjectCommand](docs/BindFlavorToProjectCommand.md)
- [BindImageToProjectCommand](docs/BindImageToProjectCommand.md)
- [BindOrganizationsCommand](docs/BindOrganizationsCommand.md)
- [BindOrganizationsToRuleDto](docs/BindOrganizationsToRuleDto.md)
- [BindProjectGroupsToUserGroupCommand](docs/BindProjectGroupsToUserGroupCommand.md)
- [BindProjectsCommand](docs/BindProjectsCommand.md)
- [BindProjectsToCatalogCommand](docs/BindProjectsToCatalogCommand.md)
- [BindPrometheusOrganizationsCommand](docs/BindPrometheusOrganizationsCommand.md)
- [BindRulesCommand](docs/BindRulesCommand.md)
- [BindRulesToOrganizationDto](docs/BindRulesToOrganizationDto.md)
- [BindSubscriptionCommand](docs/BindSubscriptionCommand.md)
- [BindSubscriptionResponseDto](docs/BindSubscriptionResponseDto.md)
- [BindUnbindEndpointToTokenCommand](docs/BindUnbindEndpointToTokenCommand.md)
- [BindUserGroupsToProjectGroupCommand](docs/BindUserGroupsToProjectGroupCommand.md)
- [BindUsersCommand](docs/BindUsersCommand.md)
- [BoundFlavorsForProjectsList](docs/BoundFlavorsForProjectsList.md)
- [BoundFlavorsForProjectsListDto](docs/BoundFlavorsForProjectsListDto.md)
- [BoundImagesForProjectsList](docs/BoundImagesForProjectsList.md)
- [BoundImagesForProjectsListDto](docs/BoundImagesForProjectsListDto.md)
- [BridgeListCommand](docs/BridgeListCommand.md)
- [CBackupDto](docs/CBackupDto.md)
- [CDeleteBackupRequestDto](docs/CDeleteBackupRequestDto.md)
- [CRestoreDto](docs/CRestoreDto.md)
- [CScheduleDto](docs/CScheduleDto.md)
- [CardInformationDto](docs/CardInformationDto.md)
- [CatalogAppDetailsDto](docs/CatalogAppDetailsDto.md)
- [CatalogAppLockManagement](docs/CatalogAppLockManagement.md)
- [CatalogAppParamsDetailsDto](docs/CatalogAppParamsDetailsDto.md)
- [CatalogAppParamsDto](docs/CatalogAppParamsDto.md)
- [CatalogDropdownDto](docs/CatalogDropdownDto.md)
- [CatalogList](docs/CatalogList.md)
- [CatalogListDto](docs/CatalogListDto.md)
- [CatalogLockManagementCommand](docs/CatalogLockManagementCommand.md)
- [ChangeCardCommand](docs/ChangeCardCommand.md)
- [ChangePasswordCommand](docs/ChangePasswordCommand.md)
- [Chart](docs/Chart.md)
- [ChartSpec](docs/ChartSpec.md)
- [ChatCompletionsCommand](docs/ChatCompletionsCommand.md)
- [CheckAwsCommand](docs/CheckAwsCommand.md)
- [CheckAzureCommand](docs/CheckAzureCommand.md)
- [CheckAzureCpuQuotaCommand](docs/CheckAzureCpuQuotaCommand.md)
- [CheckOpenstackCommand](docs/CheckOpenstackCommand.md)
- [CheckPrometheusCommand](docs/CheckPrometheusCommand.md)
- [CheckS3Command](docs/CheckS3Command.md)
- [CheckTanzuCommand](docs/CheckTanzuCommand.md)
- [CidrCommand](docs/CidrCommand.md)
- [ClearProjectBackupCommand](docs/ClearProjectBackupCommand.md)
- [CloseTicketCommand](docs/CloseTicketCommand.md)
- [CloudCredentialsDropdownRecordDto](docs/CloudCredentialsDropdownRecordDto.md)
- [CloudCredentialsForOrganizationEntity](docs/CloudCredentialsForOrganizationEntity.md)
- [CloudCredentialsResponseData](docs/CloudCredentialsResponseData.md)
- [CloudCredentialsSearchCommand](docs/CloudCredentialsSearchCommand.md)
- [CloudCredentialsSearchList](docs/CloudCredentialsSearchList.md)
- [CloudLockManagerCommand](docs/CloudLockManagerCommand.md)
- [CloudRole](docs/CloudRole.md)
- [CloudStatus](docs/CloudStatus.md)
- [CloudType](docs/CloudType.md)
- [CommitStandAloneVmCommand](docs/CommitStandAloneVmCommand.md)
- [CommonAvailabilityDto](docs/CommonAvailabilityDto.md)
- [CommonDropdownDto](docs/CommonDropdownDto.md)
- [CommonDropdownIsBoundDto](docs/CommonDropdownIsBoundDto.md)
- [CommonDropdownIsBoundDtoForProject](docs/CommonDropdownIsBoundDtoForProject.md)
- [CommonExtendedDropdownDto](docs/CommonExtendedDropdownDto.md)
- [CommonSearchKubernetesResponseData](docs/CommonSearchKubernetesResponseData.md)
- [CommonSearchResponseData](docs/CommonSearchResponseData.md)
- [CommonStringBasedDropdownDto](docs/CommonStringBasedDropdownDto.md)
- [CommonStringDropdownIsBoundDto](docs/CommonStringDropdownIsBoundDto.md)
- [Condition](docs/Condition.md)
- [ConfigMapDto](docs/ConfigMapDto.md)
- [ConfigMapSearchCommand](docs/ConfigMapSearchCommand.md)
- [ConfigMapSearchList](docs/ConfigMapSearchList.md)
- [ConfigMaps](docs/ConfigMaps.md)
- [ConfirmEmailCommand](docs/ConfirmEmailCommand.md)
- [ConsoleScreenshotCommand](docs/ConsoleScreenshotCommand.md)
- [ContactUsCommand](docs/ContactUsCommand.md)
- [CostComponent](docs/CostComponent.md)
- [CountryListDto](docs/CountryListDto.md)
- [CreateAccessProfileCommand](docs/CreateAccessProfileCommand.md)
- [CreateAiCredentialCommand](docs/CreateAiCredentialCommand.md)
- [CreateAlertDto](docs/CreateAlertDto.md)
- [CreateAlertingIntegrationCommand](docs/CreateAlertingIntegrationCommand.md)
- [CreateAlertingProfileCommand](docs/CreateAlertingProfileCommand.md)
- [CreateAllowedHostCommand](docs/CreateAllowedHostCommand.md)
- [CreateAwsCloudCommand](docs/CreateAwsCloudCommand.md)
- [CreateAzureCloudCommand](docs/CreateAzureCloudCommand.md)
- [CreateBackupPolicyCommand](docs/CreateBackupPolicyCommand.md)
- [CreateBillingSummaryCommand](docs/CreateBillingSummaryCommand.md)
- [CreateCatalogAppCommand](docs/CreateCatalogAppCommand.md)
- [CreateCatalogCommand](docs/CreateCatalogCommand.md)
- [CreateDnsServerCommand](docs/CreateDnsServerCommand.md)
- [CreateInfraProductCommand](docs/CreateInfraProductCommand.md)
- [CreateInvoiceCommand](docs/CreateInvoiceCommand.md)
- [CreateKubeConfigCommand](docs/CreateKubeConfigCommand.md)
- [CreateKubernetesProfileCommand](docs/CreateKubernetesProfileCommand.md)
- [CreateNtpServerCommand](docs/CreateNtpServerCommand.md)
- [CreateOpaProfileCommand](docs/CreateOpaProfileCommand.md)
- [CreateOpenstackCloudCommand](docs/CreateOpenstackCloudCommand.md)
- [CreateProjectAppCommand](docs/CreateProjectAppCommand.md)
- [CreateProjectCommand](docs/CreateProjectCommand.md)
- [CreateProjectFromTemplateCommand](docs/CreateProjectFromTemplateCommand.md)
- [CreateProjectGroupCommand](docs/CreateProjectGroupCommand.md)
- [CreateProxmoxCommand](docs/CreateProxmoxCommand.md)
- [CreateProxmoxNetworkDto](docs/CreateProxmoxNetworkDto.md)
- [CreateSecurityGroupCommand](docs/CreateSecurityGroupCommand.md)
- [CreateSlackConfigurationCommand](docs/CreateSlackConfigurationCommand.md)
- [CreateSshUserCommand](docs/CreateSshUserCommand.md)
- [CreateStandAloneDiskCommand](docs/CreateStandAloneDiskCommand.md)
- [CreateStandAloneVmCommand](docs/CreateStandAloneVmCommand.md)
- [CreateStripeCustomerCommand](docs/CreateStripeCustomerCommand.md)
- [CreateSubscriptionCommand](docs/CreateSubscriptionCommand.md)
- [CreateTanzuCommand](docs/CreateTanzuCommand.md)
- [CreateTicketCommand](docs/CreateTicketCommand.md)
- [CreateUserCommand](docs/CreateUserCommand.md)
- [CreateUserGroupCommand](docs/CreateUserGroupCommand.md)
- [CredentialChartDto](docs/CredentialChartDto.md)
- [CredentialMakeDefaultCommand](docs/CredentialMakeDefaultCommand.md)
- [CredentialsChart](docs/CredentialsChart.md)
- [CredentialsForCli](docs/CredentialsForCli.md)
- [CredentialsForCliDto](docs/CredentialsForCliDto.md)
- [CredentialsForProjectList](docs/CredentialsForProjectList.md)
- [CronJobCommand](docs/CronJobCommand.md)
- [CsvExporter](docs/CsvExporter.md)
- [DaemonSetDto](docs/DaemonSetDto.md)
- [DaemonSetSearchCommand](docs/DaemonSetSearchCommand.md)
- [DaemonSetSearchList](docs/DaemonSetSearchList.md)
- [DaemonSets](docs/DaemonSets.md)
- [DashboardChart](docs/DashboardChart.md)
- [DateFilter](docs/DateFilter.md)
- [DateInterval](docs/DateInterval.md)
- [DeleteAlertCommand](docs/DeleteAlertCommand.md)
- [DeleteBackupCommand](docs/DeleteBackupCommand.md)
- [DeleteBackupStorageLocationCommand](docs/DeleteBackupStorageLocationCommand.md)
- [DeleteImageFromProjectCommand](docs/DeleteImageFromProjectCommand.md)
- [DeleteKubeConfigByProjectIdCommand](docs/DeleteKubeConfigByProjectIdCommand.md)
- [DeleteKubeConfigCommand](docs/DeleteKubeConfigCommand.md)
- [DeleteProjectCommand](docs/DeleteProjectCommand.md)
- [DeleteRepositoryCommand](docs/DeleteRepositoryCommand.md)
- [DeleteRestoreCommand](docs/DeleteRestoreCommand.md)
- [DeleteScheduleCommand](docs/DeleteScheduleCommand.md)
- [DeleteServerCommand](docs/DeleteServerCommand.md)
- [DeleteSlackConfigCommand](docs/DeleteSlackConfigCommand.md)
- [DeleteSshUserCommand](docs/DeleteSshUserCommand.md)
- [DeleteStandAloneProfileCommand](docs/DeleteStandAloneProfileCommand.md)
- [DeleteStandAloneVmCommand](docs/DeleteStandAloneVmCommand.md)
- [DeleteStandAloneVmDiskCommand](docs/DeleteStandAloneVmDiskCommand.md)
- [DeleteSubscriptionCommand](docs/DeleteSubscriptionCommand.md)
- [DeleteUserGroupCommand](docs/DeleteUserGroupCommand.md)
- [DeleteWholeProjectCommand](docs/DeleteWholeProjectCommand.md)
- [DeploymentDto](docs/DeploymentDto.md)
- [DeploymentSearchCommand](docs/DeploymentSearchCommand.md)
- [DeploymentSearchList](docs/DeploymentSearchList.md)
- [Deployments](docs/Deployments.md)
- [DescribeConfigMapCommand](docs/DescribeConfigMapCommand.md)
- [DescribeCrdCommand](docs/DescribeCrdCommand.md)
- [DescribeCronJobCommand](docs/DescribeCronJobCommand.md)
- [DescribeDaemonSetCommand](docs/DescribeDaemonSetCommand.md)
- [DescribeDeploymentCommand](docs/DescribeDeploymentCommand.md)
- [DescribeIngressCommand](docs/DescribeIngressCommand.md)
- [DescribeJobCommand](docs/DescribeJobCommand.md)
- [DescribeNetworkPolicyCommand](docs/DescribeNetworkPolicyCommand.md)
- [DescribeNodeCommand](docs/DescribeNodeCommand.md)
- [DescribePodCommand](docs/DescribePodCommand.md)
- [DescribePodDisruptionCommand](docs/DescribePodDisruptionCommand.md)
- [DescribePvcCommand](docs/DescribePvcCommand.md)
- [DescribeSecretCommand](docs/DescribeSecretCommand.md)
- [DescribeServiceCommand](docs/DescribeServiceCommand.md)
- [DescribeStorageClassCommand](docs/DescribeStorageClassCommand.md)
- [DescribeStsCommand](docs/DescribeStsCommand.md)
- [DisableAiCommand](docs/DisableAiCommand.md)
- [DisableAutoscalingCommand](docs/DisableAutoscalingCommand.md)
- [DisableBackupCommand](docs/DisableBackupCommand.md)
- [DisableGatekeeperCommand](docs/DisableGatekeeperCommand.md)
- [DisableRepoCommand](docs/DisableRepoCommand.md)
- [DisableUserCommand](docs/DisableUserCommand.md)
- [DnsCommand](docs/DnsCommand.md)
- [DnsNtpAddressEditDto](docs/DnsNtpAddressEditDto.md)
- [DnsServerCreateDto](docs/DnsServerCreateDto.md)
- [DnsServerListDto](docs/DnsServerListDto.md)
- [DnsServersListDto](docs/DnsServersListDto.md)
- [DocumentationData](docs/DocumentationData.md)
- [DocumentationsList](docs/DocumentationsList.md)
- [DownloadInvoiceCommand](docs/DownloadInvoiceCommand.md)
- [DownloadKubeConfigCommand](docs/DownloadKubeConfigCommand.md)
- [DuplicateNameCheckerCommand](docs/DuplicateNameCheckerCommand.md)
- [EditAlertingIntegrationCommand](docs/EditAlertingIntegrationCommand.md)
- [EditAllowedHostDto](docs/EditAllowedHostDto.md)
- [EditArticleCommand](docs/EditArticleCommand.md)
- [EditAutoscalingCommand](docs/EditAutoscalingCommand.md)
- [EditCatalogAppParamCommand](docs/EditCatalogAppParamCommand.md)
- [EditCatalogAppVersionCommand](docs/EditCatalogAppVersionCommand.md)
- [EditCatalogCommand](docs/EditCatalogCommand.md)
- [EditProjectAppParamsDto](docs/EditProjectAppParamsDto.md)
- [EditSecurityGroupCommand](docs/EditSecurityGroupCommand.md)
- [EditSshUserCommand](docs/EditSshUserCommand.md)
- [EditTicketCommand](docs/EditTicketCommand.md)
- [EmailMode](docs/EmailMode.md)
- [EnableAiCommand](docs/EnableAiCommand.md)
- [EnableAutoscalingCommand](docs/EnableAutoscalingCommand.md)
- [EnableBackupCommand](docs/EnableBackupCommand.md)
- [EnableGatekeeperCommand](docs/EnableGatekeeperCommand.md)
- [EndpointElements](docs/EndpointElements.md)
- [EnumList](docs/EnumList.md)
- [EstimatedInfracost](docs/EstimatedInfracost.md)
- [ExceededQuotaList](docs/ExceededQuotaList.md)
- [ExportKubeConfigCommand](docs/ExportKubeConfigCommand.md)
- [Filter](docs/Filter.md)
- [FilteringElementDto](docs/FilteringElementDto.md)
- [FinalPriceCommand](docs/FinalPriceCommand.md)
- [FinalPriceDto](docs/FinalPriceDto.md)
- [FlavorsListDto](docs/FlavorsListDto.md)
- [ForceToResetPasswordCommand](docs/ForceToResetPasswordCommand.md)
- [ForgotPasswordCommand](docs/ForgotPasswordCommand.md)
- [FromTemplateDto](docs/FromTemplateDto.md)
- [FullSpotOperationCommand](docs/FullSpotOperationCommand.md)
- [GetCatalogAppValueAutocompleteCommand](docs/GetCatalogAppValueAutocompleteCommand.md)
- [GetCatalogAppValueCommand](docs/GetCatalogAppValueCommand.md)
- [GetProjectOperationCommand](docs/GetProjectOperationCommand.md)
- [GetToken](docs/GetToken.md)
- [GiveAccessToPartnerCommand](docs/GiveAccessToPartnerCommand.md)
- [GoogleCommonImages](docs/GoogleCommonImages.md)
- [GoogleCredentialForProjectDto](docs/GoogleCredentialForProjectDto.md)
- [GoogleCredentialList](docs/GoogleCredentialList.md)
- [GoogleCredentialsListDto](docs/GoogleCredentialsListDto.md)
- [GoogleFlavorDto](docs/GoogleFlavorDto.md)
- [GoogleFlavorList](docs/GoogleFlavorList.md)
- [GoogleImageList](docs/GoogleImageList.md)
- [GoogleOwnerDetails](docs/GoogleOwnerDetails.md)
- [GroupedBillingInfo](docs/GroupedBillingInfo.md)
- [GroupedBillings](docs/GroupedBillings.md)
- [HelmMetadata](docs/HelmMetadata.md)
- [HelmReleaseDto](docs/HelmReleaseDto.md)
- [HelmReleasesList](docs/HelmReleasesList.md)
- [HelmSpec](docs/HelmSpec.md)
- [HelmStatus](docs/HelmStatus.md)
- [HypervisorListCommand](docs/HypervisorListCommand.md)
- [ImageByIdCommand](docs/ImageByIdCommand.md)
- [ImportBackupStorageLocationCommand](docs/ImportBackupStorageLocationCommand.md)
- [ImportRepoCommand](docs/ImportRepoCommand.md)
- [InfraBillingListCommand](docs/InfraBillingListCommand.md)
- [InfraBillingSummariesCreateCommand](docs/InfraBillingSummariesCreateCommand.md)
- [InfraBillingSummaryDto](docs/InfraBillingSummaryDto.md)
- [InfraOrganizationsListDto](docs/InfraOrganizationsListDto.md)
- [InfraProductDto](docs/InfraProductDto.md)
- [IngressDto](docs/IngressDto.md)
- [IngressSearchCommand](docs/IngressSearchCommand.md)
- [IngressSearchList](docs/IngressSearchList.md)
- [Ingresses](docs/Ingresses.md)
- [InteractiveShellSendCommand](docs/InteractiveShellSendCommand.md)
- [InvoiceDto](docs/InvoiceDto.md)
- [InvoiceListDto](docs/InvoiceListDto.md)
- [Invoices](docs/Invoices.md)
- [IpAddressRangeCountCommand](docs/IpAddressRangeCountCommand.md)
- [IpAddressRangeListCommand](docs/IpAddressRangeListCommand.md)
- [JsonNode](docs/JsonNode.md)
- [JsonNodeOptions](docs/JsonNodeOptions.md)
- [KeycloakCheckerCommand](docs/KeycloakCheckerCommand.md)
- [KeycloakCreateCommand](docs/KeycloakCreateCommand.md)
- [KeycloakDeleteCommand](docs/KeycloakDeleteCommand.md)
- [KeycloakEditCommand](docs/KeycloakEditCommand.md)
- [KeycloakListDto](docs/KeycloakListDto.md)
- [KubeConfigForUserDto](docs/KubeConfigForUserDto.md)
- [KubeConfigForUserList](docs/KubeConfigForUserList.md)
- [KubeConfigInteractiveShellCommand](docs/KubeConfigInteractiveShellCommand.md)
- [KubeConfigResponse](docs/KubeConfigResponse.md)
- [KubeConfigRoleDto](docs/KubeConfigRoleDto.md)
- [KubeConfigRoleResponse](docs/KubeConfigRoleResponse.md)
- [KubernetesAlertCreateDto](docs/KubernetesAlertCreateDto.md)
- [KubernetesAlertDto](docs/KubernetesAlertDto.md)
- [KubernetesAlertList](docs/KubernetesAlertList.md)
- [KubernetesCliCommand](docs/KubernetesCliCommand.md)
- [KubernetesCronJobDto](docs/KubernetesCronJobDto.md)
- [KubernetesCronJobsList](docs/KubernetesCronJobsList.md)
- [KubernetesDashboardDto](docs/KubernetesDashboardDto.md)
- [KubernetesEventCreateDto](docs/KubernetesEventCreateDto.md)
- [KubernetesJobDto](docs/KubernetesJobDto.md)
- [KubernetesJobList](docs/KubernetesJobList.md)
- [KubernetesNodeLabelsDto](docs/KubernetesNodeLabelsDto.md)
- [KubernetesOverviewDto](docs/KubernetesOverviewDto.md)
- [KubernetesPodLogsCommand](docs/KubernetesPodLogsCommand.md)
- [KubernetesProfilesEntity](docs/KubernetesProfilesEntity.md)
- [KubernetesProfilesLisForPollerDto](docs/KubernetesProfilesLisForPollerDto.md)
- [KubernetesProfilesList](docs/KubernetesProfilesList.md)
- [KubernetesProfilesListDto](docs/KubernetesProfilesListDto.md)
- [KubernetesProfilesLockManagerCommand](docs/KubernetesProfilesLockManagerCommand.md)
- [KubernetesProfilesSearchCommand](docs/KubernetesProfilesSearchCommand.md)
- [KubernetesProfilesSearchList](docs/KubernetesProfilesSearchList.md)
- [KubernetesQuotaListDto](docs/KubernetesQuotaListDto.md)
- [KubernetesVersionListDto](docs/KubernetesVersionListDto.md)
- [KubesprayCreateCommand](docs/KubesprayCreateCommand.md)
- [KubesprayListDto](docs/KubesprayListDto.md)
- [Kubesprays](docs/Kubesprays.md)
- [LeaveTaikunCommand](docs/LeaveTaikunCommand.md)
- [LeaveTaikunDto](docs/LeaveTaikunDto.md)
- [ListAllBackupStorageLocations](docs/ListAllBackupStorageLocations.md)
- [ListAllBackups](docs/ListAllBackups.md)
- [ListAllDeleteBackupRequests](docs/ListAllDeleteBackupRequests.md)
- [ListAllRestores](docs/ListAllRestores.md)
- [ListAllSchedules](docs/ListAllSchedules.md)
- [ListCatalogAppAvailableVersionsCommand](docs/ListCatalogAppAvailableVersionsCommand.md)
- [ListForLandingPageDto](docs/ListForLandingPageDto.md)
- [ListForOrganizationEditDto](docs/ListForOrganizationEditDto.md)
- [LockProjectAppCommand](docs/LockProjectAppCommand.md)
- [LoginCommand](docs/LoginCommand.md)
- [LokiResponseDto](docs/LokiResponseDto.md)
- [MakeCsmCommand](docs/MakeCsmCommand.md)
- [MakeOwnerCommand](docs/MakeOwnerCommand.md)
- [Metadata](docs/Metadata.md)
- [MonitoringCredentialsListDto](docs/MonitoringCredentialsListDto.md)
- [MonitoringOperationsCommand](docs/MonitoringOperationsCommand.md)
- [NetworkPolicies](docs/NetworkPolicies.md)
- [NetworkPolicyDto](docs/NetworkPolicyDto.md)
- [NodeCommand](docs/NodeCommand.md)
- [NodeDto](docs/NodeDto.md)
- [NodeSearchResponseData](docs/NodeSearchResponseData.md)
- [NodesSearchCommand](docs/NodesSearchCommand.md)
- [NodesSearchList](docs/NodesSearchList.md)
- [NotificationHistory](docs/NotificationHistory.md)
- [NotificationListDto](docs/NotificationListDto.md)
- [NotificationSendCommand](docs/NotificationSendCommand.md)
- [NotifyOwnersCommand](docs/NotifyOwnersCommand.md)
- [NtpCommand](docs/NtpCommand.md)
- [NtpServerCreateDto](docs/NtpServerCreateDto.md)
- [NtpServerListDto](docs/NtpServerListDto.md)
- [NtpServersListDto](docs/NtpServersListDto.md)
- [OpaMakeDefaultCommand](docs/OpaMakeDefaultCommand.md)
- [OpaProfileList](docs/OpaProfileList.md)
- [OpaProfileListDto](docs/OpaProfileListDto.md)
- [OpaProfileLockManagerCommand](docs/OpaProfileLockManagerCommand.md)
- [OpaProfileSyncCommand](docs/OpaProfileSyncCommand.md)
- [OpaProfileUpdateCommand](docs/OpaProfileUpdateCommand.md)
- [OpenAiCheckerCommand](docs/OpenAiCheckerCommand.md)
- [OpenStackNetworkListQuery](docs/OpenStackNetworkListQuery.md)
- [OpenStackProjectListQuery](docs/OpenStackProjectListQuery.md)
- [OpenStackRegionListQuery](docs/OpenStackRegionListQuery.md)
- [OpenStackZoneListQuery](docs/OpenStackZoneListQuery.md)
- [OpenTicketCommand](docs/OpenTicketCommand.md)
- [OpenshiftCreateCommand](docs/OpenshiftCreateCommand.md)
- [OpenshiftCredentialForProjectDto](docs/OpenshiftCredentialForProjectDto.md)
- [OpenshiftFlavorData](docs/OpenshiftFlavorData.md)
- [OpenshiftFlavorList](docs/OpenshiftFlavorList.md)
- [OpenshiftList](docs/OpenshiftList.md)
- [OpenshiftListDto](docs/OpenshiftListDto.md)
- [OpenstackComputeQuotaDto](docs/OpenstackComputeQuotaDto.md)
- [OpenstackCredentialList](docs/OpenstackCredentialList.md)
- [OpenstackCredentialsForProjectDto](docs/OpenstackCredentialsForProjectDto.md)
- [OpenstackCredentialsListDto](docs/OpenstackCredentialsListDto.md)
- [OpenstackFlavorList](docs/OpenstackFlavorList.md)
- [OpenstackFlavorListDto](docs/OpenstackFlavorListDto.md)
- [OpenstackImageList](docs/OpenstackImageList.md)
- [OpenstackNetworkDto](docs/OpenstackNetworkDto.md)
- [OpenstackQuotaList](docs/OpenstackQuotaList.md)
- [OpenstackQuotasCommand](docs/OpenstackQuotasCommand.md)
- [OpenstackSubnetListQuery](docs/OpenstackSubnetListQuery.md)
- [OpenstackVolumeQuotaDto](docs/OpenstackVolumeQuotaDto.md)
- [OpenstackVolumeTypeListQuery](docs/OpenstackVolumeTypeListQuery.md)
- [OperationCredentialLockManagerCommand](docs/OperationCredentialLockManagerCommand.md)
- [OperationCredentials](docs/OperationCredentials.md)
- [OperationCredentialsCreateCommand](docs/OperationCredentialsCreateCommand.md)
- [OperationCredentialsForOrganizationEntity](docs/OperationCredentialsForOrganizationEntity.md)
- [OperationCredentialsListDto](docs/OperationCredentialsListDto.md)
- [OperationCredentialsMakeDefaultCommand](docs/OperationCredentialsMakeDefaultCommand.md)
- [OrganizationCreateCommand](docs/OrganizationCreateCommand.md)
- [OrganizationDetailsDto](docs/OrganizationDetailsDto.md)
- [OrganizationDropdownDto](docs/OrganizationDropdownDto.md)
- [OrganizationDto](docs/OrganizationDto.md)
- [OrganizationEntityForDashboard](docs/OrganizationEntityForDashboard.md)
- [OrganizationNameCheckerCommand](docs/OrganizationNameCheckerCommand.md)
- [OrganizationSearchCommand](docs/OrganizationSearchCommand.md)
- [OrganizationSearchList](docs/OrganizationSearchList.md)
- [OrganizationSubscriptionDto](docs/OrganizationSubscriptionDto.md)
- [OrganizationsList](docs/OrganizationsList.md)
- [PackageAutocompleteDto](docs/PackageAutocompleteDto.md)
- [Parameter](docs/Parameter.md)
- [PartnerDetailsDto](docs/PartnerDetailsDto.md)
- [PartnerDetailsForOrganizationsDto](docs/PartnerDetailsForOrganizationsDto.md)
- [PartnerDetailsForUserDto](docs/PartnerDetailsForUserDto.md)
- [PartnerEntity](docs/PartnerEntity.md)
- [PartnerRecordDto](docs/PartnerRecordDto.md)
- [PartnersList](docs/PartnersList.md)
- [PartnersSearchCommand](docs/PartnersSearchCommand.md)
- [PartnersSearchList](docs/PartnersSearchList.md)
- [PartnersSearchResponseData](docs/PartnersSearchResponseData.md)
- [PatchCrdCommand](docs/PatchCrdCommand.md)
- [PatchCronJobCommand](docs/PatchCronJobCommand.md)
- [PatchIngressCommand](docs/PatchIngressCommand.md)
- [PatchJobCommand](docs/PatchJobCommand.md)
- [PatchNodeCommand](docs/PatchNodeCommand.md)
- [PatchNodeLabelsDto](docs/PatchNodeLabelsDto.md)
- [PatchPdbCommand](docs/PatchPdbCommand.md)
- [PatchPodCommand](docs/PatchPodCommand.md)
- [PatchPvcCommand](docs/PatchPvcCommand.md)
- [PatchSecretCommand](docs/PatchSecretCommand.md)
- [PatchStsCommand](docs/PatchStsCommand.md)
- [PayInvoiceCommand](docs/PayInvoiceCommand.md)
- [PodDisruptionDto](docs/PodDisruptionDto.md)
- [PodDisruptions](docs/PodDisruptions.md)
- [PodDto](docs/PodDto.md)
- [PodListDto](docs/PodListDto.md)
- [Pods](docs/Pods.md)
- [PodsSearchCommand](docs/PodsSearchCommand.md)
- [PodsSearchList](docs/PodsSearchList.md)
- [ProblemDetails](docs/ProblemDetails.md)
- [ProjectActionDto](docs/ProjectActionDto.md)
- [ProjectActionUpdateDto](docs/ProjectActionUpdateDto.md)
- [ProjectActionVisibilityDto](docs/ProjectActionVisibilityDto.md)
- [ProjectAppDetailsDto](docs/ProjectAppDetailsDto.md)
- [ProjectAppDto](docs/ProjectAppDto.md)
- [ProjectAppList](docs/ProjectAppList.md)
- [ProjectAppListDto](docs/ProjectAppListDto.md)
- [ProjectAppParamDto](docs/ProjectAppParamDto.md)
- [ProjectAppParamsDto](docs/ProjectAppParamsDto.md)
- [ProjectButtonStatusDto](docs/ProjectButtonStatusDto.md)
- [ProjectChartDto](docs/ProjectChartDto.md)
- [ProjectCommonRecordDto](docs/ProjectCommonRecordDto.md)
- [ProjectDetailsErrorListDto](docs/ProjectDetailsErrorListDto.md)
- [ProjectDetailsErrorType](docs/ProjectDetailsErrorType.md)
- [ProjectDetailsForServersDto](docs/ProjectDetailsForServersDto.md)
- [ProjectDetailsForVmsDto](docs/ProjectDetailsForVmsDto.md)
- [ProjectDto](docs/ProjectDto.md)
- [ProjectExtendLifeTimeCommand](docs/ProjectExtendLifeTimeCommand.md)
- [ProjectForListDto](docs/ProjectForListDto.md)
- [ProjectForUpdateDto](docs/ProjectForUpdateDto.md)
- [ProjectFullListDto](docs/ProjectFullListDto.md)
- [ProjectGroupDetailsListDto](docs/ProjectGroupDetailsListDto.md)
- [ProjectGroupEntityListDto](docs/ProjectGroupEntityListDto.md)
- [ProjectGroupList](docs/ProjectGroupList.md)
- [ProjectHealth](docs/ProjectHealth.md)
- [ProjectInfracostUpsertDto](docs/ProjectInfracostUpsertDto.md)
- [ProjectListDetailDto](docs/ProjectListDetailDto.md)
- [ProjectListDto](docs/ProjectListDto.md)
- [ProjectListForAlert](docs/ProjectListForAlert.md)
- [ProjectListForPoller](docs/ProjectListForPoller.md)
- [ProjectListForProjectGroupDto](docs/ProjectListForProjectGroupDto.md)
- [ProjectLockManagerCommand](docs/ProjectLockManagerCommand.md)
- [ProjectQuotaList](docs/ProjectQuotaList.md)
- [ProjectQuotaListDto](docs/ProjectQuotaListDto.md)
- [ProjectRevisionDto](docs/ProjectRevisionDto.md)
- [ProjectRevisionUpdateDto](docs/ProjectRevisionUpdateDto.md)
- [ProjectStatus](docs/ProjectStatus.md)
- [ProjectTemplateDropdownListDto](docs/ProjectTemplateDropdownListDto.md)
- [ProjectTemplateList](docs/ProjectTemplateList.md)
- [ProjectTemplateListDto](docs/ProjectTemplateListDto.md)
- [ProjectType](docs/ProjectType.md)
- [ProjectWithFlavorsAndImagesDto](docs/ProjectWithFlavorsAndImagesDto.md)
- [ProjectsForBillingDto](docs/ProjectsForBillingDto.md)
- [ProjectsList](docs/ProjectsList.md)
- [ProjectsMonitoringAlertsCommand](docs/ProjectsMonitoringAlertsCommand.md)
- [ProjectsSearchCommand](docs/ProjectsSearchCommand.md)
- [ProjectsSearchList](docs/ProjectsSearchList.md)
- [PrometheusBillingCreateCommand](docs/PrometheusBillingCreateCommand.md)
- [PrometheusBillingInfo](docs/PrometheusBillingInfo.md)
- [PrometheusBillingSummaryDto](docs/PrometheusBillingSummaryDto.md)
- [PrometheusDashboardCreateCommand](docs/PrometheusDashboardCreateCommand.md)
- [PrometheusDashboardDto](docs/PrometheusDashboardDto.md)
- [PrometheusDashboardListDto](docs/PrometheusDashboardListDto.md)
- [PrometheusDashboardUpdateCommand](docs/PrometheusDashboardUpdateCommand.md)
- [PrometheusEntity](docs/PrometheusEntity.md)
- [PrometheusLabelDeleteDto](docs/PrometheusLabelDeleteDto.md)
- [PrometheusLabelListDto](docs/PrometheusLabelListDto.md)
- [PrometheusLabelUpdateDto](docs/PrometheusLabelUpdateDto.md)
- [PrometheusMetricsCommand](docs/PrometheusMetricsCommand.md)
- [PrometheusOrganizationDiscountDto](docs/PrometheusOrganizationDiscountDto.md)
- [PrometheusRuleListDto](docs/PrometheusRuleListDto.md)
- [PrometheusRulesList](docs/PrometheusRulesList.md)
- [PrometheusRulesSearchCommand](docs/PrometheusRulesSearchCommand.md)
- [PrometheusRulesSearchList](docs/PrometheusRulesSearchList.md)
- [PrometheusRulesSearchResponseData](docs/PrometheusRulesSearchResponseData.md)
- [PrometheusType](docs/PrometheusType.md)
- [ProxmoxCheckerCommand](docs/ProxmoxCheckerCommand.md)
- [ProxmoxCredentialsForProjectDto](docs/ProxmoxCredentialsForProjectDto.md)
- [ProxmoxFlavorData](docs/ProxmoxFlavorData.md)
- [ProxmoxFlavorList](docs/ProxmoxFlavorList.md)
- [ProxmoxHypervisorDto](docs/ProxmoxHypervisorDto.md)
- [ProxmoxImageList](docs/ProxmoxImageList.md)
- [ProxmoxList](docs/ProxmoxList.md)
- [ProxmoxListDto](docs/ProxmoxListDto.md)
- [ProxmoxNetworkListDto](docs/ProxmoxNetworkListDto.md)
- [ProxmoxRole](docs/ProxmoxRole.md)
- [ProxmoxStorage](docs/ProxmoxStorage.md)
- [PurgeCommand](docs/PurgeCommand.md)
- [PurgeStandAloneCommand](docs/PurgeStandAloneCommand.md)
- [PurgeStandAloneVmDiskCommand](docs/PurgeStandAloneVmDiskCommand.md)
- [PurgeWholeProjectCommand](docs/PurgeWholeProjectCommand.md)
- [PvcDto](docs/PvcDto.md)
- [PvcSearchCommand](docs/PvcSearchCommand.md)
- [PvcSearchList](docs/PvcSearchList.md)
- [Pvcs](docs/Pvcs.md)
- [RebootServerCommand](docs/RebootServerCommand.md)
- [RebootStandAloneVmCommand](docs/RebootStandAloneVmCommand.md)
- [RefreshTokenCommand](docs/RefreshTokenCommand.md)
- [RegionListCommand](docs/RegionListCommand.md)
- [RemindUsersByAlertingProfileCommand](docs/RemindUsersByAlertingProfileCommand.md)
- [RepairStandAloneVmCommand](docs/RepairStandAloneVmCommand.md)
- [ReplyTicketCommand](docs/ReplyTicketCommand.md)
- [Repository](docs/Repository.md)
- [ResetPasswordCommand](docs/ResetPasswordCommand.md)
- [ResetProjectStatusCommand](docs/ResetProjectStatusCommand.md)
- [ResetServerStatusCommand](docs/ResetServerStatusCommand.md)
- [ResetStandAloneVmDiskStatusCommand](docs/ResetStandAloneVmDiskStatusCommand.md)
- [ResetStandAloneVmStatusCommand](docs/ResetStandAloneVmStatusCommand.md)
- [Resource](docs/Resource.md)
- [RestartDaemonSetCommand](docs/RestartDaemonSetCommand.md)
- [RestartDeploymentCommand](docs/RestartDeploymentCommand.md)
- [RestartStsCommand](docs/RestartStsCommand.md)
- [RestoreBackupCommand](docs/RestoreBackupCommand.md)
- [RuleCreateCommand](docs/RuleCreateCommand.md)
- [RuleForUpdateDto](docs/RuleForUpdateDto.md)
- [S3CredentialForProjectDto](docs/S3CredentialForProjectDto.md)
- [SecretDto](docs/SecretDto.md)
- [SecretSearchCommand](docs/SecretSearchCommand.md)
- [SecretSearchList](docs/SecretSearchList.md)
- [Secrets](docs/Secrets.md)
- [SecurityGroupListDto](docs/SecurityGroupListDto.md)
- [SecurityGroupProtocol](docs/SecurityGroupProtocol.md)
- [SecurityReportSummary](docs/SecurityReportSummary.md)
- [SecurityReportSummaryDto](docs/SecurityReportSummaryDto.md)
- [ServerActionButtonVisibilityDto](docs/ServerActionButtonVisibilityDto.md)
- [ServerChartDto](docs/ServerChartDto.md)
- [ServerCommonRecordDto](docs/ServerCommonRecordDto.md)
- [ServerForCreateDto](docs/ServerForCreateDto.md)
- [ServerListDto](docs/ServerListDto.md)
- [ServerTemplateDto](docs/ServerTemplateDto.md)
- [ServerUpdateDto](docs/ServerUpdateDto.md)
- [ServersForBillingDto](docs/ServersForBillingDto.md)
- [ServersList](docs/ServersList.md)
- [ServersListForDetails](docs/ServersListForDetails.md)
- [ServersSearchCommand](docs/ServersSearchCommand.md)
- [ServersSearchList](docs/ServersSearchList.md)
- [ServersSearchResponseData](docs/ServersSearchResponseData.md)
- [ServiceDto](docs/ServiceDto.md)
- [ServiceSearchCommand](docs/ServiceSearchCommand.md)
- [ServiceSearchList](docs/ServiceSearchList.md)
- [Services](docs/Services.md)
- [SetTicketPriorityCommand](docs/SetTicketPriorityCommand.md)
- [ShelveStandAloneVmCommand](docs/ShelveStandAloneVmCommand.md)
- [SilenceOperationsCommand](docs/SilenceOperationsCommand.md)
- [SimplePrometheusEntity](docs/SimplePrometheusEntity.md)
- [SlackConfigurationDto](docs/SlackConfigurationDto.md)
- [SlackConfigurationList](docs/SlackConfigurationList.md)
- [SlackType](docs/SlackType.md)
- [SourceRef](docs/SourceRef.md)
- [SpotVmOperationCommand](docs/SpotVmOperationCommand.md)
- [SpotWorkerOperationCommand](docs/SpotWorkerOperationCommand.md)
- [SshKeyCommand](docs/SshKeyCommand.md)
- [SshUserCreateDto](docs/SshUserCreateDto.md)
- [SshUserListDto](docs/SshUserListDto.md)
- [SshUsersListDto](docs/SshUsersListDto.md)
- [StandAloneMetaDataDto](docs/StandAloneMetaDataDto.md)
- [StandAloneMetaDataDtoForVm](docs/StandAloneMetaDataDtoForVm.md)
- [StandAloneProfileCreateCommand](docs/StandAloneProfileCreateCommand.md)
- [StandAloneProfileForDetailsDto](docs/StandAloneProfileForDetailsDto.md)
- [StandAloneProfileFullDto](docs/StandAloneProfileFullDto.md)
- [StandAloneProfileLockManagementCommand](docs/StandAloneProfileLockManagementCommand.md)
- [StandAloneProfileSecurityGroupDto](docs/StandAloneProfileSecurityGroupDto.md)
- [StandAloneProfileSecurityGroupForDetailsDto](docs/StandAloneProfileSecurityGroupForDetailsDto.md)
- [StandAloneProfileSecurityGroupFullDto](docs/StandAloneProfileSecurityGroupFullDto.md)
- [StandAloneProfileUpdateCommand](docs/StandAloneProfileUpdateCommand.md)
- [StandAloneProfiles](docs/StandAloneProfiles.md)
- [StandAloneProfilesListDto](docs/StandAloneProfilesListDto.md)
- [StandAloneProfilesSearchCommand](docs/StandAloneProfilesSearchCommand.md)
- [StandAloneProfilesSearchList](docs/StandAloneProfilesSearchList.md)
- [StandAloneVmDiskDto](docs/StandAloneVmDiskDto.md)
- [StandAloneVmDiskForDetailsDto](docs/StandAloneVmDiskForDetailsDto.md)
- [StandAloneVmDiskFullDto](docs/StandAloneVmDiskFullDto.md)
- [StandAloneVmDiskStatus](docs/StandAloneVmDiskStatus.md)
- [StandAloneVmFullDto](docs/StandAloneVmFullDto.md)
- [StandAloneVmIpManagementCommand](docs/StandAloneVmIpManagementCommand.md)
- [StandAloneVmListForDetails](docs/StandAloneVmListForDetails.md)
- [StandAloneVmSmallDetailDto](docs/StandAloneVmSmallDetailDto.md)
- [StandAloneVmStatus](docs/StandAloneVmStatus.md)
- [StandaloneProfileListDto](docs/StandaloneProfileListDto.md)
- [StandaloneProfileSecurityGroupListDto](docs/StandaloneProfileSecurityGroupListDto.md)
- [StandaloneVisibilityDto](docs/StandaloneVisibilityDto.md)
- [StandaloneVmListDto](docs/StandaloneVmListDto.md)
- [StandaloneVmsForBillingDto](docs/StandaloneVmsForBillingDto.md)
- [StandaloneVmsList](docs/StandaloneVmsList.md)
- [StandaloneVmsListForDetailsDto](docs/StandaloneVmsListForDetailsDto.md)
- [StandaloneVmsListForPoller](docs/StandaloneVmsListForPoller.md)
- [StartStandaloneVmCommand](docs/StartStandaloneVmCommand.md)
- [Status](docs/Status.md)
- [StopStandaloneVmCommand](docs/StopStandaloneVmCommand.md)
- [StorageClassDto](docs/StorageClassDto.md)
- [StorageClasses](docs/StorageClasses.md)
- [StorageListCommand](docs/StorageListCommand.md)
- [StripeInvoiceListDto](docs/StripeInvoiceListDto.md)
- [StripeInvoices](docs/StripeInvoices.md)
- [StripeSubscriptionItemDto](docs/StripeSubscriptionItemDto.md)
- [StsDto](docs/StsDto.md)
- [StsList](docs/StsList.md)
- [StsSearchCommand](docs/StsSearchCommand.md)
- [StsSearchList](docs/StsSearchList.md)
- [Subnet](docs/Subnet.md)
- [Subresource](docs/Subresource.md)
- [SyncProjectAppCommand](docs/SyncProjectAppCommand.md)
- [TaikunLbDto](docs/TaikunLbDto.md)
- [TanzuCredentialsForProjectDto](docs/TanzuCredentialsForProjectDto.md)
- [TanzuCredentialsList](docs/TanzuCredentialsList.md)
- [TanzuCredentialsListDto](docs/TanzuCredentialsListDto.md)
- [TanzuFlavorList](docs/TanzuFlavorList.md)
- [TanzuFlavorsListDto](docs/TanzuFlavorsListDto.md)
- [TanzuImageList](docs/TanzuImageList.md)
- [TanzuImagesListDto](docs/TanzuImagesListDto.md)
- [TanzuStorageListCommand](docs/TanzuStorageListCommand.md)
- [TicketPriority](docs/TicketPriority.md)
- [ToggleDemoModeCommand](docs/ToggleDemoModeCommand.md)
- [ToggleKeycloakCommand](docs/ToggleKeycloakCommand.md)
- [ToggleMaintenanceModeCommand](docs/ToggleMaintenanceModeCommand.md)
- [ToggleNotificationModeCommand](docs/ToggleNotificationModeCommand.md)
- [TransferList](docs/TransferList.md)
- [TransferTicketCommand](docs/TransferTicketCommand.md)
- [TryForFreeCommand](docs/TryForFreeCommand.md)
- [UnbindAppRepositoryCommand](docs/UnbindAppRepositoryCommand.md)
- [UnbindFlavorFromProjectCommand](docs/UnbindFlavorFromProjectCommand.md)
- [UnshelveStandaloneVmCommand](docs/UnshelveStandaloneVmCommand.md)
- [UpdateAccessProfileDto](docs/UpdateAccessProfileDto.md)
- [UpdateAlertingProfileCommand](docs/UpdateAlertingProfileCommand.md)
- [UpdateAwsCommand](docs/UpdateAwsCommand.md)
- [UpdateAzureCommand](docs/UpdateAzureCommand.md)
- [UpdateCatalogDto](docs/UpdateCatalogDto.md)
- [UpdateHealthStatusCommand](docs/UpdateHealthStatusCommand.md)
- [UpdateHypervisorsCommand](docs/UpdateHypervisorsCommand.md)
- [UpdateInvoiceDto](docs/UpdateInvoiceDto.md)
- [UpdateKubernetesAlertDto](docs/UpdateKubernetesAlertDto.md)
- [UpdateOpenStackCommand](docs/UpdateOpenStackCommand.md)
- [UpdateOrganizationCommand](docs/UpdateOrganizationCommand.md)
- [UpdateOrganizationSubscriptionCommand](docs/UpdateOrganizationSubscriptionCommand.md)
- [UpdatePaymentIdCommand](docs/UpdatePaymentIdCommand.md)
- [UpdateProjectGroupDto](docs/UpdateProjectGroupDto.md)
- [UpdateProjectUserDto](docs/UpdateProjectUserDto.md)
- [UpdateProjectUserGroupDto](docs/UpdateProjectUserGroupDto.md)
- [UpdateProxmoxCommand](docs/UpdateProxmoxCommand.md)
- [UpdateQuotaCommand](docs/UpdateQuotaCommand.md)
- [UpdateServerCommand](docs/UpdateServerCommand.md)
- [UpdateServerHealthDto](docs/UpdateServerHealthDto.md)
- [UpdateSlackConfigurationDto](docs/UpdateSlackConfigurationDto.md)
- [UpdateStandAloneVmCommand](docs/UpdateStandAloneVmCommand.md)
- [UpdateStandAloneVmDiskDto](docs/UpdateStandAloneVmDiskDto.md)
- [UpdateStandAloneVmFlavorCommand](docs/UpdateStandAloneVmFlavorCommand.md)
- [UpdateStandaloneVmDiskCommand](docs/UpdateStandaloneVmDiskCommand.md)
- [UpdateStandaloneVmDiskSizeCommand](docs/UpdateStandaloneVmDiskSizeCommand.md)
- [UpdateSubscriptionCommand](docs/UpdateSubscriptionCommand.md)
- [UpdateTanzuCommand](docs/UpdateTanzuCommand.md)
- [UpdateUsedIpAddressesCommand](docs/UpdateUsedIpAddressesCommand.md)
- [UpdateUserCommand](docs/UpdateUserCommand.md)
- [UpdateUserGroupDto](docs/UpdateUserGroupDto.md)
- [UpdateUserProjectDto](docs/UpdateUserProjectDto.md)
- [UpdateUserProjectGroupDto](docs/UpdateUserProjectGroupDto.md)
- [UserDetails](docs/UserDetails.md)
- [UserDto](docs/UserDto.md)
- [UserExistCommand](docs/UserExistCommand.md)
- [UserForListDto](docs/UserForListDto.md)
- [UserGroupDetailsListDto](docs/UserGroupDetailsListDto.md)
- [UserGroupEntityListDto](docs/UserGroupEntityListDto.md)
- [UserGroupList](docs/UserGroupList.md)
- [UserListDto](docs/UserListDto.md)
- [UserListForUserGroupDto](docs/UserListForUserGroupDto.md)
- [UserResourceChartDto](docs/UserResourceChartDto.md)
- [UserRole](docs/UserRole.md)
- [UserTokenCreateCommand](docs/UserTokenCreateCommand.md)
- [UserTokenCreateDto](docs/UserTokenCreateDto.md)
- [UserTokensListDto](docs/UserTokensListDto.md)
- [UsersList](docs/UsersList.md)
- [UsersSearchCommand](docs/UsersSearchCommand.md)
- [UsersSearchList](docs/UsersSearchList.md)
- [UsersSearchResponseData](docs/UsersSearchResponseData.md)
- [VerifyEmailCommand](docs/VerifyEmailCommand.md)
- [VerifySlackCredentialsCommand](docs/VerifySlackCredentialsCommand.md)
- [VerifyWebhookCommand](docs/VerifyWebhookCommand.md)
- [VmConsoleScreenshotCommand](docs/VmConsoleScreenshotCommand.md)
- [VmTemplateListCommand](docs/VmTemplateListCommand.md)
- [WebhookHeaderDto](docs/WebhookHeaderDto.md)
- [WhiteListDomainCreateCommand](docs/WhiteListDomainCreateCommand.md)
- [WhiteListDomainCreateDto](docs/WhiteListDomainCreateDto.md)
- [WhiteListDomainDeleteCommand](docs/WhiteListDomainDeleteCommand.md)
- [WhiteListDomainDto](docs/WhiteListDomainDto.md)
- [YamlValidatorCommand](docs/YamlValidatorCommand.md)
## Documentation For Authorization
Authentication schemes defined for the API:
### Bearer
- **Type**: API key
- **API key parameter name**: Authorization
- **Location**: HTTP header
Note, each API key must be added to a map of `map[string]APIKey` where the key is: Authorization and passed in as the auth context for each request.
Example
```golang
auth := context.WithValue(
context.Background(),
sw.ContextAPIKeys,
map[string]sw.APIKey{
"Authorization": {Key: "API_KEY_STRING"},
},
)
r, err := client.Service.Operation(auth, args)
```
## Documentation for Utility Methods
Due to the fact that model structure members are all pointers, this package contains
a number of utility functions to easily obtain pointers to values of basic types.
Each of these functions takes a value of the given basic type and returns a pointer to it:
* `PtrBool`
* `PtrInt`
* `PtrInt32`
* `PtrInt64`
* `PtrFloat`
* `PtrFloat32`
* `PtrFloat64`
* `PtrString`
* `PtrTime`
## Author
[email protected] |
import { Component, Input, OnInit } from '@angular/core';
import { Platform } from '@ionic/angular';
import { MetaMedia } from '../../models/meta-media/meta-media';
/**
* Composant d'affichage des slides "3d" de l'écran d'accueil
* J'ai pris l'effet 3d livré avec sur le site d'ionic
* Je l'ai modifié pour rajouté l'effet de halo sous les carte (voir scss)
* et c'est presque tout
*/
@Component({
selector: 'ath-slides3d',
templateUrl: './slides3d.component.html',
styleUrls: ['./slides3d.component.scss'],
})
export class Slides3dComponent implements OnInit {
@Input() metaMedias!: MetaMedia[];
simpleSlide = false;
isVisible = false;
constructor(private platform: Platform) {
this.simpleSlide = (platform.is('ios') && screen.width <= 375 && screen.height <= 700);
}
slidesOpts: any = {
slidesPerView: 3,
coverflowEffect: {
rotate: 50,
stretch: 0,
depth: 150,
modifier: 1,
slideShadows: false,
}
};
ngOnInit() {
if (!this.simpleSlide) {
this.slidesOpts.on = {
beforeInit() {
const swiper = this;
swiper.classNames.push(`${swiper.params.containerModifierClass}coverflow`);
swiper.classNames.push(`${swiper.params.containerModifierClass}3d`);
swiper.params.watchSlidesProgress = true;
swiper.originalParams.watchSlidesProgress = true;
},
setTranslate() {
const swiper = this;
const {
width: swiperWidth, height: swiperHeight, slides, $wrapperEl, slidesSizesGrid, $
} = swiper;
const params = swiper.params.coverflowEffect;
const isHorizontal = swiper.isHorizontal();
const transform$$1 = swiper.translate;
const center = isHorizontal ? -transform$$1 + (swiperWidth / 2) : -transform$$1 + (swiperHeight / 2);
const rotate = isHorizontal ? params.rotate : -params.rotate;
const translate = params.depth;
// Each slide offset from center
for (let i = 0, length = slides.length; i < length; i += 1) {
const $slideEl = slides.eq(i);
const slideSize = slidesSizesGrid[i];
const slideOffset = $slideEl[0].swiperSlideOffset;
const offsetMultiplier = ((center - slideOffset - (slideSize / 2)) / slideSize) * params.modifier;
let rotateY = isHorizontal ? rotate * offsetMultiplier : 0;
let rotateX = isHorizontal ? 0 : rotate * offsetMultiplier;
// var rotateZ = 0
let translateZ = -translate * Math.abs(offsetMultiplier);
let translateY = isHorizontal ? 0 : params.stretch * (offsetMultiplier);
let translateX = isHorizontal ? params.stretch * (offsetMultiplier) : 0;
// Fix for ultra small values
if (Math.abs(translateX) < 0.001) { translateX = 0; }
if (Math.abs(translateY) < 0.001) { translateY = 0; }
if (Math.abs(translateZ) < 0.001) { translateZ = 0; }
if (Math.abs(rotateY) < 0.001) { rotateY = 0; }
if (Math.abs(rotateX) < 0.001) { rotateX = 0; }
const slideTransform = `translate3d(${translateX}px,${translateY}px,${translateZ}px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
$slideEl.transform(slideTransform);
$slideEl[0].style.zIndex = -Math.abs(Math.round(offsetMultiplier)) + 1;
if (params.slideShadows) {
// Set shadows
let $shadowBeforeEl = isHorizontal ? $slideEl.find('.swiper-slide-shadow-left') : $slideEl.find('.swiper-slide-shadow-top');
let $shadowAfterEl = isHorizontal ? $slideEl.find('.swiper-slide-shadow-right') : $slideEl.find('.swiper-slide-shadow-bottom');
if ($shadowBeforeEl.length === 0) {
$shadowBeforeEl = swiper.$(`<div class="swiper-slide-shadow-${isHorizontal ? 'left' : 'top'}"></div>`);
$slideEl.append($shadowBeforeEl);
}
if ($shadowAfterEl.length === 0) {
$shadowAfterEl = swiper.$(`<div class="swiper-slide-shadow-${isHorizontal ? 'right' : 'bottom'}"></div>`);
$slideEl.append($shadowAfterEl);
}
if ($shadowBeforeEl.length) { $shadowBeforeEl[0].style.opacity = offsetMultiplier > 0 ? offsetMultiplier : 0; }
if ($shadowAfterEl.length) { $shadowAfterEl[0].style.opacity = (-offsetMultiplier) > 0 ? -offsetMultiplier : 0; }
}
}
// Set correct perspective for IE10
if (swiper.support.pointerEvents || swiper.support.prefixedPointerEvents) {
const ws = $wrapperEl[0].style;
ws.perspectiveOrigin = `${center}px 50%`;
}
},
setTransition(duration: number) {
const swiper = this;
swiper.slides
.transition(duration)
.find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left')
.transition(duration);
}
};
}
setTimeout(() => {
this.isVisible = true;
}, 200);
}
} |
data = read.csv2("/Users/maxfilling/Desktop/WBDA2023/wellbeing_data_v3new2.csv")
df_input = data
df_input$date = as.Date(df_input$date)
summary(df_input)
str(df_input)
for(i in 7:23){ #7 is the first column with numbers
df_input[,i] = as.numeric(df_input[,i])
}
for(i in 28:123){ #123 is the last column with numbers
df_input[,i] = as.numeric(df_input[,i])
}
df_input$BS_week = as.factor(df_input$BS_week)
df_input$WS_week = as.factor(df_input$WS_week)
df_input$MO_type_of_Activity_planned_Morning = as.factor(df_input$MO_type_of_Activity_planned_Morning)
df_input$MO_Activity_planned_todo_Morning = as.factor(df_input$MO_Activity_planned_todo_Morning)
df_input$MO_Time_to_get_asleep[is.na(df_input$MO_Time_to_get_asleep) | df_input$MO_Time_to_get_asleep >= 300] = NA #Replace all entries higher than 5 hours with NA
summary(df_input$MO_Time_to_get_asleep)
df_input = df_input #The main Dataset including all data
df_weekly = aggregate(x = df_input[,91:123],na.action=na.omit, na.rm = TRUE, FUN = mean, by = list(Group.id = df_input$ID, WS_week = df_input$WS_week)) #Weekly Survey data for each week
df_base = aggregate(x = df_input[,63:90],na.action=na.omit, na.rm = TRUE, FUN = mean, by = list(Group.id = df_input$ID, BS_week = df_input$BS_week)) #Base survey data for basiseline, break and endline
df_single = df_input[df_input$ID == "ojdoychl", ] #Here you should use your own ID. This ID was randomly picked for demonstration purposes
df_overall = aggregate(x = df_input[,7:120],na.action=na.omit, na.rm = TRUE, FUN = mean, by = list(Group.date = df_input$date)) #representation of the complete course overall without differentation between IDs
df_base = aggregate(x = df_input[,c("Entertainment", "BS_Cognitive_Well_Being")],na.action=na.omit, na.rm = TRUE, FUN = mean, by = list(Group.id = df_input$ID, BS_week = df_input$BS_week))
df_weekly = aggregate(x = df_input[,c("WS_Performance", "WS_Cognitive_Well_Being")],na.action=na.omit, na.rm = TRUE, FUN = mean, by = list(Group.id = df_input$ID, WS_week = df_input$WS_week))
install.packages("ggplot2")
install.packages("dplyr")
#Fall 1
# Laden der benötigten Bibliotheken
library(ggplot2)
# Ihr Datensatz
df_weekly <- aggregate(x = df_input[, c("WS_Performance", "WS_Cognitive_Well_Being")],
na.action = na.omit, na.rm = TRUE, FUN = mean,
by = list(Group.id = df_input$ID, WS_week = df_input$WS_week))
# Erstellen der Grafik
ggplot(df_weekly, aes(x = WS_week)) +
geom_line(aes(y = WS_Performance, color = "Performance"), size = 1) +
geom_line(aes(y = WS_Cognitive_Well_Being, color = "Cognitive Well-Being"), linetype = "dashed", size = 1) +
geom_point(aes(y = WS_Performance, color = "Performance"), size = 3, shape = 21, fill = "white") +
geom_point(aes(y = WS_Cognitive_Well_Being, color = "Cognitive Well-Being"), size = 3, shape = 23, fill = "white") +
labs(x = "Woche", y = "Durchschnittliche Bewertung") +
scale_y_continuous(limits = c(0, 10)) +
scale_color_manual(name = "Bewertung",
values = c("Performance" = "blue", "Cognitive Well-Being" = "red"),
labels = c("Performance", "Cognitive Well-Being")) +
scale_linetype_manual(name = "Wohlbefinden", values = c("dashed"), guide = guide_legend(override.aes = list(color = c("red")))) +
theme_minimal()
#Fall2
# Laden der benötigten Bibliotheken
library(ggplot2)
# Ihr Datensatz
df_weekly <- aggregate(x = df_input[, c("WS_Performance", "WS_Cognitive_Well_Being")],
na.action = na.omit, na.rm = TRUE, FUN = mean,
by = list(Group.id = df_input$ID, WS_week = df_input$WS_week))
# Erstellen der Grafik
ggplot(df_weekly, aes(x = WS_week, y = WS_Performance, size = WS_Cognitive_Well_Being)) +
geom_point(color = "blue", alpha = 0.8) +
labs(x = "Woche", y = "Performance", size = "Cognitive Well-Being") +
scale_y_continuous(limits = c(0, 10)) +
scale_size_continuous(range = c(3, 10)) +
theme_minimal() |
package com.example.wellness.mappers;
import com.example.wellness.dto.training.TrainingBody;
import com.example.wellness.dto.training.TrainingResponse;
import com.example.wellness.dto.training.TrainingResponseWithOrderCount;
import com.example.wellness.dto.training.TrainingWithOrderCount;
import com.example.wellness.mappers.template.DtoMapper;
import com.example.wellness.models.Training;
import com.example.wellness.utils.EntitiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
@Mapper(componentModel = "spring")
@Slf4j
public abstract class TrainingMapper extends DtoMapper<Training, TrainingBody, TrainingResponse> {
@Autowired
private EntitiesUtils entitiesUtils;
@Override
public Mono<Training> updateModelFromBody(TrainingBody body, Training training) {
return entitiesUtils.verifyMappingExercises(body.getExercises())
.then(Mono.fromCallable(
() -> {
training.setBody(body.getBody());
training.setTitle(body.getTitle());
training.setExercises(
body.getExercises()
.stream().distinct().toList()
);
training.setPrice(body.getPrice());
training.setApproved(false);
training.setUserDislikes(new ArrayList<>());
training.setUserLikes(new ArrayList<>());
training.setImages(body.getImages());
return training;
}
));
}
public abstract TrainingResponseWithOrderCount fromModelToResponseWithOrderCount(TrainingWithOrderCount trainingWithOrderCount);
} |
# RoomOS Integrations Explained
<img src="/doc/images/meetingroom4.jpeg" />
An integration is a third party extension that can be developed by customers, partners and third party software developers to extend, automate and add value to the Cisco devices, using the public APIs, SDKs and open platform tools.
RoomOS supports many alternative types of integrations, and it can initially be difficult to know which one to choose. This guide describes the main alternatives for connecting to a Cisco device, how they differ from each other, and suggests when to use and not use each one.
All the integrations use the xAPI, and often an integration can be implemented with any of the alternatives. The difference is the way they connect, the network requirements, how they can be deployed, and the security model.
## Short summary
A short summary of the integration types are:
* **Macros:** JavaScript snippets that run on the device itself.
* **Cloud xAPI / Workspace integrations**: Integration that can run outside of the collab device network and talks to the devices via the cloud using Webex APIs.
* **JSXAPI / Web sockets:** A web-socket based Node.js integration on a machine in the same network as the collab devices, using the same SDK to access the xAPI as the macros (JSXAPI).
* **HTTP API**: Similar to the JSXAPI integration, but uses standard HTTP requests and a web hook like mechanism for feedback.
* **RS232 / SSH**: Cable-based connection (serial cable or USB), typically for legacy room controllers such as Crestron and Extron, often placed in the same room as the collab device.
All the solutions presented here support [UI extensions](/doc/TechDocs/UiExtensions).
## Quick sheet
<table style="font-size: 14px">
<tr>
<th></th>
<th>Macros</th>
<th>Cloud xAPI</th>
<th>JSXAPI</th>
<th>HTTP</th>
<th>RS-232/SSH</th>
</tr>
<tr>
<td>⚙️ Programming language / SDK</td>
<td>JavaScript</td>
<td>Any</td>
<td>JavaScript</td>
<td>Any</td>
<td>Any</td>
</tr>
<tr>
<td>🚚 On-prem / cloud</td>
<td>Both</td>
<td>Cloud only</td>
<td>Both</td>
<td>Both</td>
<td>Both</td>
</tr>
<tr>
<td>🏎️ Latency</td>
<td>Instantaneous</td>
<td>~1s</td>
<td>Very low</td>
<td>Low</td>
<td>Low</td>
</tr>
<tr>
<td>🔐 Access control</td>
<td>User based</td>
<td>Token based</td>
<td>User based</td>
<td>User based</td>
<td>Optional</td>
</tr>
<tr>
<td>👮♀️ API access</td>
<td>Full</td>
<td>Reduced*</td>
<td>Full</td>
<td>Full</td>
<td>Full</td>
</tr>
</table>
\**Cloud xAPI can only subscribe to a subset of events and status changes, and is not allowed to use xAPIs marked as **privacy-impacting** on personal-registered devices.*
## Macros
Macros are JavaScripts that run on the collab device itself. The scripts can use an xAPI library to talk to the device and receive feedback from it. This is similar to Node.js rather than a browser, the JavaScript macro does not have access to any HTML or CSS.
<img src="/doc/images/integrations/macros.png" />
Macros are typically created in the macro editor on a specific device, then copied to other devices. Macros are heavily sandboxed and cannot access the file system, setup socket connections etc, but they can talk to other web services using the xAPI [HTTP Client apis](/xapi/search?search=http+client).
<img src="/doc/images/macroeditor.png" style="border: 1px solid #333" />
Common use cases for macros are providing support for custom UI actions such as quick dials, custom layouts, controlling lights, blinds, climate controls, and creating automated workflows like unbooking a room when nobody shows up. Since they run on the device itself, there is no network involved, and the response to device events, user interactions etc are instantaneous.
Macros can run as either admin or integrator / room control user, but in general there is no fine grained way to set which APIs a particular macro can and cannot access. In practise, a third party macro designed to eg just provide light control will typically also have access to call logs, network settings, user management etc.
### Use macros when:
- You want to create something quick, or start learning the xAPI.
- You want to create solutions for a few, big complex rooms (like auditoriums).
- You have access to limited programming skills and resources.
- You need fast response to events on the device, or user interactions.
- You don't want or don't have the ability to host code elsewhere.
Macros are also a great way to learn working with the Cisco devices and the xAPI. You can create a Hello World application in a matter of minutes from deciding to start, without needing to download or setup any developer environment.
You can provision macros from the device itself or from Control Hub. There are no offical support for bulk provisioning, so if you need to deploy to many devices, you need to use other tools such as [CE Deploy](https://cs.co/ce-deplo) or write your own scripts.
### Don't use macros when:
- You need to respond to external events, such as a fire alarm. Macros cannot receive web hooks, or set up websockets to external end points.
- You need co-operation between devices.
- You don't trust the integration and need fine grained control over which APIs the integration is allowed to use.
- You need centralized integration logic that you need to update often.
### Typical use cases
* Modern in-room controls for lights, shades, climate controls supporting HTTP REST APIs
* Custom ui panels on the device to control custom layout
For an intro to macros, start with: [Macro Tutorial](/doc/TechDocs/MacroTutorial). For dozens of examples, see [extensions on this site](/macros).
## Cloud xAPI / Workspace integrations
Cloud xAPI talks to the device using modern REST APIs. These calls are made from the integration not to the Cisco device itself, but to the Webex cloud, so the integration does not need to be on the same network as the devices.
<img src="/doc/images/integrations/cloud.png" />
The access model is more advanced than the macros and on-prem solutions, and does not use local user access. Instead, access is granted as tokens, either by:
- Using a token on behalf of an authorised org admin.
- Giving bots access to the devices specifically (a bot in this case just means a machine account generated in the Webex cloud, not necessarily a chat bot).
The cloud xAPI itself does not provide any feedback mechanisms such as notifying the integration when a status has changed on the device, or a user interatction has occured. It can still be useful as a way to invoke device commands in bulk based on specific business requirements.
<img src="/doc/images/integrations/workspace-integrations.png" />
Workspace integrations build on top of the cloud xAPI to improve this: It allows you to create integrations in the cloud that receive notifications and events that you specify in the manifest. Furthermore, unlike all the other integrations, it allows you to specify exactly which xAPIs the integration is allowed to access, giving you fine grained access control over what an integration can and cannot do.
Workspace integrations can be created for your own org, but it can also be created as a public integration that any Webex customer can use. This creates a unique business opportunity for developers to create solutions that can be offered to any Webex customer and installed almost as a one-click operation on Control Hub.
Not all events and statuses are supported by a workspace integration. You can see a full list when adding a new integration on Control Hub.
See also the [Device developer guide](https://developer.webex.com/docs/api/guides/device-developers-guide#devices-api) on developer.webex.com.
### Use cloud xAPI and workspace integrations when:
* You have a publicly accessible web service
* You want to create solutions that you can sell to customers that they can start using simply by enabling it in Control Hub
* You want to provide integrations to hundreds or thousands of devices in your org, with small maintenance efforts
### Don't use when:
- You need data to stay strictly within your own network
- You need access to more APIs than the cloud xAPIs allow
- You need the integration to work with devices in personal mode, and your integration requires privacy-impacting APIs
- You need fast respons to events (eg adjusting a light as the user moves a slider)
- You have an on-prem device deployment (without the possibility of Webex Edge for devices)
To get started with cloud xAPI and workspace integrations, see [the device guide](https://developer.webex.com/docs/api/guides/device-developers-guide) and the [Workspace Integrations guide](https://developer.webex.com/docs/api/guides/workspace-integrations-guide) on developer.webex.com.
### Typical use cases
* Automatically unbook a scheduled meeting room if no-one arrives after a few minutes.
* Collecting usage metrics from large number of devices in an organisation to a central analytics tool.
* Providing a "Report Issue" form on all devices in the meeting rooms thar forwards the issue to eg ServiceNow.
## JSXAPI / Node.js
JSXAPI is a web-socket based SDK for Node.js that let's you talk to devices from eg virtual machines or Raspberry Pis that are on the same network as the collab devices. The syntax for the SDK is exactly the same as the macros use, so it's easy to move code from a macro to a more centralized integration.
Since the integration is running on your own platform of choice, you can now use any other tool such as crypto, databases, sockets, machine learning etc. You can also listen to external events and update the collab devices based on that, or make integrations that synchronizes devices.
<img src="/doc/images/integrations/onprem.png" />
This solution requires that you use a local user to connect to the devices, so you need to maintain an up-to-date list of ip addresses, usernames and passwords. You also need to handle re-connects for the web-sockets, for example if the network is temporarily down.
Since the integration is hosted in one centralized place, maintenance is done by simply upgrading your integration and restarting it.
Both secure web sockets (wss) and unsecure (ws) is supported.
### Use this integration when:
- You need to combine data from multiple devices
- You need to respond to external events
- You need to use external libraries not supported by macros
- You need to use the APIs directly from a browser (not via a web server)
### Do not use this integration when
- Maintaining device IP addresses, local users and passwords is not an option.
- You don't have access to the device network (isolated network).
### Typical use case
* A building management server that controls lights, climate control etc in the building by listening to UI events from the Cisco devices and forwards the requests to the appropriate smart building controllers.
* Showing important company alerts on all screens in the office, such as fire alarm and evacuation maps.
For an introduction, see [JSXAPI / Node.js](/doc/TechDocs/JSXAPIIntro).
## HTTP(S) API
You can also talk to the collab device with HTTP(S) API. The format of this API is not a REST API, but rather a proprietary XML over HTTP API. An integration using this is connection-less (fire and forget), so it doesn't need to maintain a connection like the web socket. Conceptually this solution is otherwise very similar to the JSXAPI approach.
<img src="/doc/images/integrations/http.png" />
There is also a web-hook like mechanism that can instruct the device to post HTTP messages back to a web server (HTTP Feedback), based on status changes or events that you specify.
It's recommended to use this approach in the same situations as the JSXAPI situation above, but where:
* You cannot use web socket, perhaps your integration platform does not support web sockets
* You dont need feedback, and prefer a simple fire and forget HTTP solution
### Don't use when:
* You need to access directly the API directly from a browser / web app (no CORS: the devices don't HTTP requests from different origins)
See the [Postman collection](/doc/UsefulLinks/Resources) at DevNET for many good examples.
## RS-232 / SSH connection
RS-232 or SSH connections are command-line based integrations. This also allows you to plug a cable directly into the Cisco devices that support these inputs. These kind of integrations are usually set up for external room controllers such as Crestron and Extron located in the same room as the Cisco device, with USB or serial cables.
This integration form supports various formats, such as command line, XML or JSON.
<img src="/doc/images/integrations/rs232.png" />
For more technical details, see the the [API reference guide (PDF)](https://www.cisco.com/c/en/us/support/collaboration-endpoints/spark-room-kit-series/products-command-reference-list.html) and the drivers for Creston / Extron etc on the [useful links](/doc/UsefulLinks/Resources) page.
### Use this integration when
* You need to use a legacy control system that doesn't support HTTP or web sockets.
* You require a direct cabled connection for security reasons.
### Typical use case
* Legacy room control (lights, shades, climate control) or advanced AV control with proprietary drivers
* Legacy ontrol systems that don't support HTTP, web socket or SSH connections
## Combined solutions
There is of course nothing stopping you from creating solutions that combine several of the solutions mentioned above. Just make sure you understand the strengths and pain points of each integration type first and make sure it's worth the extra complexity and maintenance effort.
## Browser based solutions
Connecting directly from a web browser on a laptop or a mobile phone to a Cisco device is also possible. This can be done using the JSXAPI solution or HTTP solution mentioned above. A couple of security considerations are worth noting:
* The Cisco devices use self signed SSL certificates, which most browser don't like. A user will need to approve the certifciate before using the integration the first time.
* Username and password for the collab device should not be made freely available on a publicly accessible web page.
The best practise would typically be that the browser talks to a web server, that then talks to the collab device, which basically means the JSXAPI or HTTP based solution mentioned earlier.
See [this guide ](/doc/TechDocs/JSXAPIBrowser) for more details.
## Web apps on the device?
As of 2022, the web apps (and other web based features such as digital signage, embedded apps and web views opened from API) do not have any access to the device xAPI, for security reasons.
<!--
Combination of methods
There are a few more specific topics on accessing the xAPI. For those interested, these are:
* Accessing the xAPI directly from a browser (eg a smart phone)
* Accessing the xAPI from a web app running ont the collab device
--> |
import os.path
from tkinter import *
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from playsound import playsound
MOVE_INCREMENT = 20 # SPACE TO MOVE AFTER FIRST HEAD
MOVES_PER_SECOND = 15 # MOVES PER SEC, AFFECTS GAME SPEED DIRECTLY, CHANGE THIS TO ALTER THE GAME SPEED
GAME_SPEED = 1000 // MOVES_PER_SECOND # DEFINES THE GAME SPEED
class Game(ttk.Frame):
def __init__(self, parent, controller, show_welcome, background):
super().__init__(parent)
labelframe = LabelFrame(self, background=background)
labelframe.pack(fill="x", expand="yes", pady=(5, 800), padx=5)
button_container = ttk.Frame(labelframe,
padding=10,
style="Background.TFrame")
button_container.pack(expand=True, fill="both")
# welcome button calling show_timer function in app.py (lambda function)
welcome_button = ttk.Button(button_container,
text="Welcome",
command=show_welcome,
style="PomodoroButton.TButton",
cursor="hand2")
welcome_button.pack(expand="True", fill="both", padx=50, pady=(0, 0))
class Snake(tk.Canvas): # canvas class
def __init__(self):
super().__init__(width=600, height=620, background="black",
highlightthickness=0) # super class contain canvas
self.snake_positions = [(100, 100), (80, 100),
(60, 100)] # assign position to snake_body as each box of 20 pixels
self.food_position = (200, 100)
self.score = 0
self.direction = "Right" # default snake moves in right
self.bind_all("<Key>",
self.on_key_press) # <Key> means any key pressed on the keyboard, on key press we call the function specified
self.load_assets()
self.create_objects()
self.after(GAME_SPEED, self.perform_actions)
def load_assets(self):
try:
self.snake_body_image = Image.open("./assets/snake.png") # opens image
self.snake_body = ImageTk.PhotoImage(self.snake_body_image) # assigns image to snake_body
self.food_image = Image.open("./assets/food.png") # opens image
self.food = ImageTk.PhotoImage(self.food_image) # assigns image to food
except IOError as error:
print(error)
# Snake.destroy(self)
def create_objects(self): # place the assets into the window
self.create_text(
45, 12, text=f"Score {self.score}", tag="score", fill="#fff", font=("TkDefaultFont", 14)
) # allows to create text and add updating info like score
for x_position, y_position in self.snake_positions:
self.create_image(x_position, y_position, image=self.snake_body,
tag="snake") # method within the canvas which create image assets
self.create_image(*self.food_position, image=self.food,
tag="food") # create food image and place it in the window
self.create_rectangle(7, 27, 593, 613, outline="#525d69") # creates a boundary
def move_snake(self):
head_x_position, head_y_position = self.snake_positions[0] # extract the initial head values
if self.direction == "Left":
new_head_position = (head_x_position - MOVE_INCREMENT, head_y_position) # new head position
elif self.direction == "Right":
new_head_position = (head_x_position + MOVE_INCREMENT, head_y_position)
elif self.direction == "Down":
new_head_position = (head_x_position, head_y_position + MOVE_INCREMENT)
elif self.direction == "Up":
new_head_position = (head_x_position, head_y_position - MOVE_INCREMENT)
self.snake_positions = [new_head_position] + self.snake_positions[
:-1] # when head move we chop off the last element of the tail
for segement, position in zip(self.find_withtag("snake"),
self.snake_positions): # we get all the snake images with their positions, zip creates tuple of first element with its position and so on
self.coords(segement,
position) # we fetch the image and position and use this function to change the position of that image
def perform_actions(self): # function to perform actions
if self.check_collisions():
return # this means the game stops as we return here, perform_actions is not called again
self.move_snake()
self.after(GAME_SPEED,
self.perform_actions) # calls function perform_action agter 75 milliseconds, not the value that function returns
def check_collisions(self):
head_x_position, head_y_position = self.snake_positions[0] # extract the initial head values
return (
head_x_position in (0, 600) # check wether snake collides with the side walls
or head_y_position in (20, 620) # checks wether snake collides with the top/bottom walls
or (head_x_position, head_y_position) in self.snake_positions[1:]
# check wether the snake collides with itself
)
def on_key_press(self, e):
new_direction = e.keysym
all_directions = ("Up", "Down", "Left", "Right") # tuple of given directions
opposites = ({"Up", "Down"}, {"Left", "Right"}) # tuple with set of opposite directions
if (
new_direction in all_directions # check new direction in given directions
and {new_direction, self.direction} not in opposites
# check new direction not opposite i.e up/down, left/right
):
self.direction = new_direction
#
# root = tk.Tk()
# root.title("Application") # title
# root.resizable(False, False) # window size
#
# board = Snake() # instance for App class
# board.grid() # put everything into the App Window
#
# root.mainloop() |
package com.javabrains;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class Triangle extends ShapeService implements ApplicationContextAware{
private String type;
private int height;
ApplicationContext context=null;
public Triangle() {
}
public Triangle(String type) {
super();
this.type = type;
}
public Triangle(int height) {
super();
this.height = height;
}
public Triangle(String type, int height) {
super();
this.type = type;
this.height = height;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public void draw(String name){
System.out.println(getType() + " Triangle with height "+getHeight()+" with name "+name);
}
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context=context;
System.out.println("context set here "+context);
}
} |
export type CompressImgProps = {
maxW?: number;
maxH?: number;
maxSize?: number;
};
export const compressBase64Img = ({
base64Img,
maxW = 1080,
maxH = 1080,
maxSize = 1024 * 500 // 500kb
}: CompressImgProps & {
base64Img: string;
}) => {
return new Promise<string>((resolve, reject) => {
const fileType =
/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/.exec(base64Img)?.[1] || 'image/jpeg';
const img = new Image();
img.src = base64Img;
img.onload = async () => {
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxW) {
height *= maxW / width;
width = maxW;
}
} else {
if (height > maxH) {
width *= maxH / height;
height = maxH;
}
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
return reject('压缩图片异常');
}
ctx.drawImage(img, 0, 0, width, height);
const compressedDataUrl = canvas.toDataURL(fileType, 1);
// 移除 canvas 元素
canvas.remove();
if (compressedDataUrl.length > maxSize) {
return reject('图片太大了');
}
resolve(compressedDataUrl);
};
img.onerror = reject;
});
}; |
#pragma warning disable CS0649
#pragma warning disable CS8618
public class NullabilitySamples
{
#region NullabilityUsage
[Test]
public void Test()
{
var type = typeof(NullabilityTarget);
var arrayField = type.GetField("ArrayField")!;
var genericField = type.GetField("GenericField")!;
var context = new NullabilityInfoContext();
var arrayInfo = context.Create(arrayField);
Assert.AreEqual(NullabilityState.NotNull, arrayInfo.ReadState);
Assert.AreEqual(NullabilityState.Nullable, arrayInfo.ElementType!.ReadState);
var genericInfo = context.Create(genericField);
Assert.AreEqual(NullabilityState.NotNull, genericInfo.ReadState);
Assert.AreEqual(NullabilityState.NotNull, genericInfo.GenericTypeArguments[0].ReadState);
Assert.AreEqual(NullabilityState.Nullable, genericInfo.GenericTypeArguments[1].ReadState);
}
#endregion
#region NullabilityExtension
[Test]
public void ExtensionTests()
{
var type = typeof(NullabilityTarget);
var field = type.GetField("StringField")!;
Assert.True(field.IsNullable());
Assert.AreEqual(NullabilityState.Nullable, field.GetNullability());
Assert.AreEqual(NullabilityState.Nullable, field.GetNullabilityInfo().ReadState);
}
#endregion
// ReSharper disable UnusedMember.Local
// ReSharper disable NotAccessedField.Local
class PropertyTarget
{
string? write;
public string? ReadWrite { get; set; }
public string? Read { get; }
public string? Write
{
set => write = value;
}
}
// ReSharper restore NotAccessedField.Local
// ReSharper restore UnusedMember.Local
[Test]
public void Property()
{
var type = typeof(PropertyTarget);
var readWrite = type.GetProperty("ReadWrite")!;
var write = type.GetProperty("Write")!;
var read = type.GetProperty("Read")!;
Assert.True(readWrite.IsNullable());
Assert.True(write.IsNullable());
Assert.True(read.IsNullable());
}
} |
import React from 'react'
import axios from 'axios'
class Dashboard extends React.Component {
constructor(props) {
super(props)
this.state = {
admins: [],
articles: [],
categories: [],
commentaries: [],
messages: [],
contacts: [],
}
this.getInfos = this.getInfos.bind(this)
}
componentDidMount() {
this.getInfos()
}
countInfos(el) {
let count = 0
for(let i = 0; i < el.length; i++) {
count ++
}
return count
}
// Récupère toutes les données
getInfos() {
const url = this.props.url
const api = this.props.api
function getAdmins() {
return axios.get(`${url}/api/admin?api_token=${api}`)
}
function getArticles() {
return axios.get(`${url}/api/article?api_token=${api}`)
}
function getCategories() {
return axios.get(`${url}/api/category?api_token=${api}`)
}
function getCommentaries() {
return axios.get(`${url}/api/commentary?api_token=${api}`)
}
function getMessages() {
return axios.get(`${url}/api/message?api_token=${api}`)
}
function getContacts() {
return axios.get(`${url}/api/contact?api_token=${api}`)
}
Promise.all([
getAdmins(),
getArticles(),
getCategories(),
getCommentaries(),
getContacts(),
getMessages(),
])
.then(results => {
const admins = results[0]
const articles = results[1]
const categories = results[2]
const commentaries = results[3]
const contacts = results[4]
const messages = results[5]
this.setState({
admins: admins.data,
articles: articles.data,
categories: categories.data,
commentaries: commentaries.data,
contacts: contacts.data,
messages: messages.data,
})
})
}
render() {
// Rendu du nombre total de chaque tables
const admins = this.state.admins
const articles = this.state.articles
const categories = this.state.categories
const commentaries = this.state.commentaries
const messages = this.state.messages
const contacts = this.state.contacts
let adminsNum = this.countInfos(admins)
let articlesNum = this.countInfos(articles)
let categoriesNum = this.countInfos(categories)
let commentariesNum = this.countInfos(commentaries)
let messagesNum = this.countInfos(messages)
let contactsNum = this.countInfos(contacts)
return(
<div className="admin-dashboard">
<h2 className="dash-title">Tableau de bord</h2>
<p className="dash-admin">Nombre d'admins <br/> <span>{adminsNum}</span></p>
<p className="dash-art">Nombre d'articles <br/> <span>{articlesNum}</span></p>
<p className="dash-cat">Nombre de catégories <br/> <span>{categoriesNum}</span></p>
<p className="dash-com">Nombre de commentaires <br/> <span>{commentariesNum}</span></p>
<p className="dash-mes">Nombre de messages <br/> <span>{messagesNum}</span></p>
<p className="dash-con">Nombre de contacts <br/> <span>{contactsNum}</span></p>
</div>
)
}
}
export default Dashboard |
<?php
namespace App\Form;
use App\Entity\WebProject;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class WebProjectType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class, [
'required' => true
])
->add('description', TextareaType::class, [
'required' => false
])
->add('link', UrlType::class, [
'required' => true
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => WebProject::class,
]);
}
} |
/*
* Copyright (C) 2016 Sree Harsha Totakura <[email protected]>
*
* 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 auth.api;
import java.nio.ByteBuffer;
import java.util.Arrays;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import protocol.Message;
import protocol.MessageParserException;
import protocol.MessageSizeExceededException;
import protocol.Protocol;
/**
*
* @author Sree Harsha Totakura <[email protected]>
*/
@EqualsAndHashCode(callSuper = true)
public class OnionAuthEncrypt extends OnionAuthApiMessage {
@Getter private long requestID;
@Getter private int[] sessions;
@Getter private byte[] payload;
/**
* Create a message to encrypt given data using layered encryption.
*
* @param sessions the sessions of the layer. The session should have
* previously been created.
* @param requestID the request ID. This is used to match responses to
* requests.
* @param payload the data to be encrypted.
* @throws MessageSizeExceededException
*/
public OnionAuthEncrypt(long requestID, int[] sessions, byte[] payload)
throws MessageSizeExceededException {
this.addHeader(Protocol.MessageType.API_AUTH_LAYER_ENCRYPT);
if (sessions.length > 255) {
throw new MessageSizeExceededException(
"Number of sessions cannot be more that 255");
}
assert (requestID <= Message.UINT32_MAX);
for (int session : sessions) {
assert (session <= Message.UINT16_MAX);
}
this.size += 4; //2 reserved + 1 layer count byte + 1 reserved byte
this.requestID = requestID;
this.size += 4;
this.sessions = sessions;
this.size += sessions.length * 2; // 4 bytes for each session
this.payload = payload;
this.size += payload.length;
if (this.size > Protocol.MAX_MESSAGE_SIZE) {
throw new MessageSizeExceededException();
}
}
@Override
public void send(ByteBuffer out) {
super.send(out);
super.sendEmptyBytes(out, 2);
out.put((byte) sessions.length);
super.sendEmptyBytes(out, 1);
out.putInt((int) requestID);
for (int session : sessions) {
out.putShort((short) session);
}
out.put(payload);
}
public static OnionAuthEncrypt parse(ByteBuffer buf)
throws MessageParserException {
OnionAuthEncrypt message;
short layerCount;
long requestID;
int[] sessions;
byte[] payload;
if (buf.remaining() < 11) //1 added header + 1 session + 1 byte payload
{
throw new MessageParserException("Message is too small");
}
buf.getShort(); //read out reserved portion
layerCount = Message.unsignedShortFromByte(buf.get());
buf.get(); //skip reserved
requestID = Message.unsignedLongFromInt(buf.getInt());
assert (layerCount <= 255);
sessions = new int[layerCount];
for (int index = 0; index < sessions.length; index++) {
sessions[index] = Message.unsignedIntFromShort(buf.getShort());
}
payload = new byte[buf.remaining()];
buf.get(payload);
try {
message = new OnionAuthEncrypt(requestID, sessions, payload);
} catch (MessageSizeExceededException ex) {
throw new MessageParserException("Message size exceeded");
}
return message;
}
} |
'use strict';
//игроки
const player0 = document.querySelector('.player--0');
const player1 = document.querySelector('.player--1');
//общий счёт игроков
const score0 = document.querySelector('#score--0');
const score1 = document.querySelector('#score--1');
const current0 = document.getElementById('current--0');
const current1 = document.getElementById('current--1');
//игральная кость
const dice = document.querySelector('.dice');
//кнопки
const btnRollDice = document.querySelector('.btn--roll');
const btnHold = document.querySelector('.btn--hold');
const btnNewGame = document.querySelector('.btn--new');
//текущий счёт игроков
const actualScore0 = document.querySelector('#current--0');
const actualScore1 = document.querySelector('#current--1');
score0.textContent = 0;
score1.textContent = 0;
let activePlayer;
let score;
let scores;
let playing;
let numberDice;
const init = function () {
playing = true;
numberDice = 0;
activePlayer = 0;
scores = [0, 0];
score = 0;
player0.classList.add('player--active');
player1.classList.remove('player--active');
player1.classList.remove('player--winner');
player0.classList.remove('player--winner');
current0.textContent = 0;
current1.textContent = 0;
score0.textContent = 0;
score1.textContent = 0;
dice.classList.add('hidden');
};
init();
let changePlayer = function () {
document.querySelector(`#current--${activePlayer}`).textContent = 0;
activePlayer = activePlayer === 0 ? 1 : 0;
player0.classList.toggle('player--active');
player1.classList.toggle('player--active');
score = 0;
};
btnRollDice.addEventListener('click', function () {
if (playing) {
dice.classList.remove('hidden');
numberDice = Math.trunc(Math.random() * 6) + 1;
dice.src = `dice-${numberDice}.png`;
if (numberDice !== 1) {
score += numberDice;
document.querySelector(`#current--${activePlayer}`).textContent = score;
} else {
changePlayer();
score = 0;
}
}
});
btnHold.addEventListener('click', function () {
if (playing) {
scores[activePlayer] += score;
document.querySelector(`#score--${activePlayer}`).textContent =
scores[activePlayer];
}
if (scores[activePlayer] >= 100) {
document
.querySelector(`.player--${activePlayer}`)
.classList.add('player--winner');
playing = false;
dice.classList.add('hidden');
} else {
changePlayer();
}
});
btnNewGame.addEventListener('click', init); |
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef RY_PDS_UTILS_H
#define RY_PDS_UTILS_H
/*
* NeL Includes
*/
#include <nel/misc/types_nl.h>
#include <nel/misc/common.h>
#include <nel/misc/time_nl.h>
#include <nel/misc/stream.h>
#include <nel/misc/entity_id.h>
#include <nel/misc/sheet_id.h>
#include <nel/misc/variable.h>
namespace RY_PDS
{
/**
* Definition of streamable persistent data.
* Used to fetch data from PDS to service classes
*/
typedef NLMISC::IStream CPData;
/**
* PD System Verbosity control
*/
extern NLMISC::CVariable<bool> PDVerbose;
/**
* PD System Verbosity level
*/
extern NLMISC::CVariable<sint> PDVerboseLevel;
/**
* PDS Resolve Unmapped rows
* If true, PDS continue loading when it finds a row not mapped in a mapped table,
* and keeps it unmapped.
* Otherwise, loading fails.
*/
extern NLMISC::CVariable<bool> ResolveUnmappedRows;
/**
* PDS Resolve Double Mapped Rows
* If true, PDS continue loading when it finds a row already mapped, and keeps it unmapped.
* Otherwise, loading fails.
* See also ResolveDoubleMappedKeepOlder
*/
extern NLMISC::CVariable<bool> ResolveDoubleMappedRows;
/**
* PDS Resolve Double Mapped Keep Older
* If true, when finds a doubly mapped row at loading, keep only older row as mapped (lesser row index)
* See also ResolveDoubleMappedRows.
*/
extern NLMISC::CVariable<bool> ResolveDoubleMappedKeepOlder;
/**
* PDS Resolve Unallocated rows
* If true, when finds a reference to an unallocated row or an invalid row, force reference to null.
*/
extern NLMISC::CVariable<bool> ResolveInvalidRow;
/**
* Definition of Table indices
*/
typedef uint16 TTableIndex;
/**
* Definition of Row indices
*/
typedef uint32 TRowIndex;
/**
* Definition of Column indices
*/
typedef uint16 TColumnIndex;
/**
* Definition of index Checksum validator
*/
typedef uint16 TIndexChecksum;
/**
* Table & Row indices constants
*/
const TTableIndex INVALID_TABLE_INDEX = 0xffff;
const TRowIndex INVALID_ROW_INDEX = 0xffffffff;
const TColumnIndex INVALID_COLUMN_INDEX = 0xffff;
/**
* Checksum
*/
const TIndexChecksum VALID_INDEX_CHECKSUM = 0xdead;
/**
* Default Hashing Function
*/
/*template<typename T>
class CDefaultHash
{
public:
size_t operator() (const T& value) const { return (uint32)value; }
};*/
/**
* Table Container Interface
*/
class ITableContainer
{
public:
/// Get Table Index
virtual TTableIndex getTableIndex(const std::string& tableName) const = 0;
/// Get Table Name
virtual std::string getTableName(TTableIndex tableIndex) const = 0;
};
/**
* Definition of Object indices
* An object is pointed by a table index and a row index
* \author Benjamin Legros
* \author Nevrax France
* \date 2004
*/
class CObjectIndex
{
public:
/// Constructor of invalid index
explicit CObjectIndex(bool validateChecksum = false) : _Row(INVALID_ROW_INDEX), _Table(INVALID_TABLE_INDEX), _Checksum((TIndexChecksum)~VALID_INDEX_CHECKSUM)
{
if (validateChecksum)
validate();
else
invalidate();
}
/// Constructor
CObjectIndex(TTableIndex table, TRowIndex row) : _Row(row), _Table(table) { validate(); }
/// Constructor
CObjectIndex(const CObjectIndex &index) { *this = index; }
/// Cast operator
operator uint64 () const { return _FullIndex; }
/// Get Table index
TTableIndex table() const { return _Table; }
/// Get Row index
TRowIndex row() const { return _Row; }
/// Copy
CObjectIndex & operator = (const CObjectIndex &index) { _FullIndex = index._FullIndex; return *this; }
/// Equal?
bool operator == (const CObjectIndex &index) const { return _FullIndex == index._FullIndex; }
/// Not equal?
bool operator != (const CObjectIndex &index) const { return !(*this == index); }
/// Return null
static CObjectIndex null()
{
return CObjectIndex(true);
}
/// Checksum valid?
bool isChecksumValid() const
{
return getChecksum() == VALID_INDEX_CHECKSUM;
}
/// Is it Null Ptr?
bool isNull() const
{
return _Table == INVALID_TABLE_INDEX && _Row == INVALID_ROW_INDEX && isChecksumValid();
}
/// Validity check
bool isValid() const
{
return _Table != INVALID_TABLE_INDEX && _Row != INVALID_ROW_INDEX && isChecksumValid();
}
/// transform to string
std::string toString(const ITableContainer* container = NULL) const
{
if (isValid())
{
if (container != NULL)
{
return NLMISC::toString("(%s:%u)", container->getTableName(_Table).c_str(), _Row);
}
else
{
return NLMISC::toString("(%u:%u)", _Table, _Row);
}
}
else if (isNull())
{
return "<Null>";
}
else
{
return NLMISC::toString("(%u:%u <invalid>)", _Table, _Row);
}
}
/// get from string
void fromString(const char* str, const ITableContainer* container = NULL)
{
uint table;
uint row;
uint valid;
if (sscanf(str, "(%d:%d:%d)", &table, &row, &valid) == 3)
{
_Table = (TTableIndex)table;
_Row = (TRowIndex)row;
if (valid != 0)
validate();
else
invalidate();
return;
}
else if (sscanf(str, "(%d:%d)", &table, &row) == 2)
{
_Table = (TTableIndex)table;
_Row = (TRowIndex)row;
validate();
return;
}
else if (container != NULL && parseIndexWithName(str, container))
{
validate();
return;
}
*this = CObjectIndex::null();
return;
}
void serial(NLMISC::IStream& f)
{
f.serial(_FullIndex);
}
private:
bool parseIndexWithName(const char* str, const ITableContainer* container)
{
TRowIndex row;
TTableIndex table;
if (*(str++) != '(')
return false;
std::string tableName;
while (*str != '\0' && *str != ':')
tableName += *(str++);
if (*(str++) != ':')
return false;
table = container->getTableIndex(tableName);
if (table == INVALID_TABLE_INDEX)
return false;
NLMISC::fromString(std::string(str), row);
while (*str >= '0' && *str <= '9')
++str;
if (*str != ')')
return false;
_Row = row;
_Table = table;
return true;
}
#ifdef NL_OS_WINDOWS
#define PDS_ROW_LO_WORD 0
#define PDS_ROW_HI_WORD 1
#define PDS_TABLE_WORD 2
#define PDS_CHECKSUM_WORD 3
#else
#define PDS_ROW_LO_WORD 0
#define PDS_ROW_HI_WORD 1
#define PDS_TABLE_WORD 2
#define PDS_CHECKSUM_WORD 3
#endif
union
{
struct
{
TRowIndex _Row;
TTableIndex _Table;
TIndexChecksum _Checksum;
};
uint64 _FullIndex;
uint16 _Words[4];
};
/// Compute partial checksum of the index
TIndexChecksum getPartialChecksum() const
{
return _Words[PDS_ROW_LO_WORD] ^ _Words[PDS_ROW_HI_WORD] ^ _Words[PDS_TABLE_WORD];
}
/// Get checksum of the index
TIndexChecksum getChecksum() const
{
return getPartialChecksum() ^ _Words[PDS_CHECKSUM_WORD];
}
/// Force validation of an index
void validate()
{
_Checksum = getPartialChecksum() ^ VALID_INDEX_CHECKSUM;
}
/// Force invalidation of an index
void invalidate()
{
_Checksum = getPartialChecksum() ^ (~VALID_INDEX_CHECKSUM);
}
};
/**
* Definition of column index
* \author Benjamin Legros
* \author Nevrax France
* \date 2004
*/
class CColumnIndex
{
public:
/// Constructor
explicit CColumnIndex(TTableIndex table = INVALID_TABLE_INDEX, TRowIndex row = INVALID_ROW_INDEX, TColumnIndex column = INVALID_COLUMN_INDEX)
: _Table(table), _Column(column), _Row(row)
{
}
/// Constructor
explicit CColumnIndex(const CObjectIndex& object, TColumnIndex column)
: _Table(INVALID_TABLE_INDEX), _Column(INVALID_COLUMN_INDEX), _Row(INVALID_ROW_INDEX)
{
if (!object.isValid())
return;
_Table = object.table();
_Row = object.row();
_Column = column;
}
/// Get Table Index
TTableIndex table() const { return _Table; }
/// Get Row Index
TRowIndex row() const { return _Row; }
/// Get Column Index
TColumnIndex column() const { return _Column; }
/// Test if is null
bool isNull() const { return _Table == INVALID_TABLE_INDEX && _Row == INVALID_ROW_INDEX && _Column == INVALID_COLUMN_INDEX; }
/// Cast to 64 bits
operator uint64() const { return _FullIndex; }
/// 32 bits hash key
uint32 hash() const { return (uint32) ((_Table<<2) ^ (_Row<<1) ^ _Column); }
/// Operator <
bool operator < (const CColumnIndex& b) const { return _FullIndex < b._FullIndex; }
/// transform to string
std::string toString(const ITableContainer* container = NULL) const
{
if (isNull())
{
return "<Null>";
}
else if (container != NULL)
{
return NLMISC::toString("(%s:%u:%u)", container->getTableName(_Table).c_str(), _Row, _Column);
}
else
{
return NLMISC::toString("(%u:%u:%u)", _Table, _Row, _Column);
}
}
private:
union
{
struct
{
/// Table Index
TTableIndex _Table;
/// Column Index in row
TColumnIndex _Column;
/// Row Index in table
TRowIndex _Row;
};
/// Full 64 bits index
uint64 _FullIndex;
};
};
/**
* Definition of set of object indexes
* This is actually a index on the first element of a list contained in each database
*/
typedef std::vector<CObjectIndex> TIndexList;
/**
* A container of index lists
* \author Benjamin Legros
* \author Nevrax France
* \date 2004
*/
//#define DEBUG_SETMAP_ACCESSOR
struct CColumnIndexHashMapTraits
{
enum { bucket_size = 4, min_buckets = 8 };
CColumnIndexHashMapTraits() { }
size_t operator() (const CColumnIndex &id) const
{
return id.hash();
}
bool operator()(const CColumnIndex &left, const CColumnIndex &right)
{
return left < right;
}
};
class CSetMap
{
public:
/// Hash Key
/*class CKeyHash
{
public:
size_t operator() (const CColumnIndex& key) const { return (uint32)(key.hash()); }
};*/
/// Map of lists
typedef CHashMap<CColumnIndex, TIndexList, CColumnIndexHashMapTraits> TListMap;
/// An Accessor on a list
class CAccessor
{
public:
/// Constructor, only builds invalid accessor
CAccessor() : _Valid(false) { }
/// Is Valid
bool isValid() const { return _Valid; }
/// Get whole list
const TIndexList& get() const { nlassert(isValid()); return (*_It).second; }
/// Test if object belongs to list
bool belongsTo(const CObjectIndex& test) const
{
nlassert(isValid());
return std::find((*_It).second.begin(), (*_It).second.end(), test) != (*_It).second.end();
}
/// Add index to list
void add(const CObjectIndex& index)
{
nlassert(isValid());
if (!belongsTo(index))
{
(*_It).second.push_back(index);
}
}
/// Remove index from list
void erase(const CObjectIndex& index)
{
nlassert(isValid());
TIndexList& iList = (*_It).second;
TIndexList::iterator itr;
for (itr=iList.begin(); itr!=iList.end(); )
itr = ((*itr == index) ? iList.erase(itr) : (itr+1));
// gcc can't resolve this:
//(*_It).second.erase(std::remove((*_It).second.begin(), (*_It).second.end(), index), (*_It).second.end());
}
/// Dump list
void display() const
{
if (!isValid())
{
nlinfo("<can't display set>");
return;
}
#ifdef DEBUG_SETMAP_ACCESSOR
nlinfo("Set '%s' content:", _Debug.toString().c_str());
#else
nlinfo("Set content:");
#endif
TIndexList::const_iterator it;
for (it=(*_It).second.begin(); it!=(*_It).second.end(); ++it)
nlinfo("%s", (*it).toString().c_str());
}
private:
friend class CSetMap;
/// Internal pointer to list
TListMap::iterator _It;
/// Is Valid
bool _Valid;
#ifdef DEBUG_SETMAP_ACCESSOR
CColumnIndex _Debug;
/// constructor for CIndexListMap
CAccessor(TListMap::iterator it, const CColumnIndex& index) : _It(it), _Valid(true), _Debug(index) { }
#else
/// constructor for CIndexListMap
CAccessor(TListMap::iterator it, const CColumnIndex& index) : _It(it), _Valid(true) { }
#endif
};
/// Get the list associated to this column
CAccessor get(const CColumnIndex& index)
{
TListMap::iterator it = _Map.find(index);
if (it == _Map.end())
{
it = _Map.insert(TListMap::value_type(index, TIndexList())).first;
}
return CAccessor(it, index);
}
/// Clear up whole map
void clear() { _Map.clear(); }
private:
friend class CAccessor;
TListMap _Map;
};
/**
* Base class for Row accessible objects.
* Contains a Row index, used to represent the object in the database
* Classes that derive from this class are assumed to know their own Table index.
* \author Benjamin Legros
* \author Nevrax France
* \date 2004
*/
class IPDBaseData
{
public:
/// Constructor
IPDBaseData() : __BaseRow(INVALID_ROW_INDEX), __BaseTable(INVALID_TABLE_INDEX) {}
/// Get Row index
TRowIndex getRow() const { return __BaseRow; }
/// Get Table index
TTableIndex getTable() const { return __BaseTable; }
protected:
TRowIndex __BaseRow;
TTableIndex __BaseTable;
friend class CPDSLib;
};
/**
* A class that allocates and deallocate indices in PDS database.
* The allocator is able to init itself from a PDS command
* \author Benjamin Legros
* \author Nevrax France
* \date 2004
*/
class CIndexAllocator
{
public:
CIndexAllocator() : _NextIndex(0) { }
TRowIndex allocate()
{
// no index in stack, get next
if (_FreeIndices.empty())
return _NextIndex++;
// pop a free index
TRowIndex index = _FreeIndices.front();
_FreeIndices.pop_front();
return index;
}
void deallocate(TRowIndex index)
{
// push index on stack
_FreeIndices.push_back(index);
}
void forceAllocated(TRowIndex index)
{
for (; _NextIndex<index; ++_NextIndex)
_FreeIndices.push_back(_NextIndex);
// remove index from free if was there
std::deque<TRowIndex>::iterator it = std::find(_FreeIndices.begin(), _FreeIndices.end(), index);
if (it != _FreeIndices.end())
_FreeIndices.erase(it);
if (_NextIndex < index+1)
_NextIndex = index+1;
}
void clear()
{
_NextIndex = 0;
_FreeIndices.clear();
}
void serial(NLMISC::IStream& f)
{
f.serialCheck(NELID("IALC"));
f.serialVersion(0);
f.serial(_NextIndex);
f.serialCont(_FreeIndices);
}
private:
/// Next free index
TRowIndex _NextIndex;
/// Free items
std::deque<TRowIndex> _FreeIndices;
};
typedef IPDBaseData* (*TPDFactory)();
typedef void (*TPDFetch)(IPDBaseData*, CPData&);
typedef void (*TPDFetchFailure)(uint64 key);
/**
* Get Value as String
*/
template<typename T>
std::string pdsToString(const T& value) { return NLMISC::toString(value); }
inline std::string pdsToString(const bool& value) { return value ? std::string("true") : std::string("false"); }
inline std::string pdsToString(const CObjectIndex& value) { return value.toString(); }
inline std::string pdsToString(const CColumnIndex& value) { return value.toString(); }
inline std::string pdsToString(const NLMISC::CSheetId& value) { return value.toString(); }
inline std::string pdsToString(const NLMISC::CEntityId& value) { return value.toString(); }
}; // RY_PDS
#endif //RY_PDS_UTILS_H |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe UserDetail, feature_category: :system_access do
it { is_expected.to belong_to(:user) }
specify do
values = [:basics, :move_repository, :code_storage, :exploring, :ci, :other, :joining_team]
is_expected.to define_enum_for(:registration_objective).with_values(values).with_suffix
end
describe 'validations' do
context 'for onboarding_status json schema' do
let(:step_url) { '_some_string_' }
let(:email_opt_in) { true }
let(:onboarding_status) do
{
step_url: step_url,
email_opt_in: email_opt_in
}
end
it { is_expected.to allow_value(onboarding_status).for(:onboarding_status) }
context 'for step_url' do
let(:onboarding_status) do
{
step_url: step_url
}
end
it { is_expected.to allow_value(onboarding_status).for(:onboarding_status) }
context "when 'step_url' is invalid" do
let(:step_url) { [] }
it { is_expected.not_to allow_value(onboarding_status).for(:onboarding_status) }
end
end
context 'for email_opt_in' do
let(:onboarding_status) do
{
email_opt_in: email_opt_in
}
end
it { is_expected.to allow_value(onboarding_status).for(:onboarding_status) }
context "when 'email_opt_in' is invalid" do
let(:email_opt_in) { 'true' }
it { is_expected.not_to allow_value(onboarding_status).for(:onboarding_status) }
end
end
context 'when there is no data' do
let(:onboarding_status) { {} }
it { is_expected.to allow_value(onboarding_status).for(:onboarding_status) }
end
context 'when trying to store an unsupported key' do
let(:onboarding_status) do
{
unsupported_key: '_some_value_'
}
end
it { is_expected.not_to allow_value(onboarding_status).for(:onboarding_status) }
end
end
describe '#job_title' do
it { is_expected.not_to validate_presence_of(:job_title) }
it { is_expected.to validate_length_of(:job_title).is_at_most(200) }
end
describe '#pronouns' do
it { is_expected.not_to validate_presence_of(:pronouns) }
it { is_expected.to validate_length_of(:pronouns).is_at_most(50) }
end
describe '#pronunciation' do
it { is_expected.not_to validate_presence_of(:pronunciation) }
it { is_expected.to validate_length_of(:pronunciation).is_at_most(255) }
end
describe '#bio' do
it { is_expected.to validate_length_of(:bio).is_at_most(255) }
end
describe '#linkedin' do
it { is_expected.to validate_length_of(:linkedin).is_at_most(500) }
end
describe '#twitter' do
it { is_expected.to validate_length_of(:twitter).is_at_most(500) }
end
describe '#skype' do
it { is_expected.to validate_length_of(:skype).is_at_most(500) }
end
describe '#discord' do
it { is_expected.to validate_length_of(:discord).is_at_most(500) }
context 'when discord is set' do
let_it_be(:user_detail) { create(:user_detail) }
it 'accepts a valid discord user id' do
user_detail.discord = '1234567890123456789'
expect(user_detail).to be_valid
end
it 'throws an error when other url format is wrong' do
user_detail.discord = '123456789'
expect(user_detail).not_to be_valid
expect(user_detail.errors.full_messages).to match_array([_('Discord must contain only a discord user ID.')])
end
end
end
describe '#mastodon' do
it { is_expected.to validate_length_of(:mastodon).is_at_most(500) }
context 'when mastodon is set' do
let_it_be(:user_detail) { create(:user_detail) }
it 'accepts a valid mastodon username' do
user_detail.mastodon = '@[email protected]'
expect(user_detail).to be_valid
end
it 'throws an error when mastodon username format is wrong' do
user_detail.mastodon = '@robin'
expect(user_detail).not_to be_valid
expect(user_detail.errors.full_messages)
.to match_array([_('Mastodon must contain only a mastodon username.')])
end
end
end
describe '#location' do
it { is_expected.to validate_length_of(:location).is_at_most(500) }
end
describe '#organization' do
it { is_expected.to validate_length_of(:organization).is_at_most(500) }
end
describe '#website_url' do
it { is_expected.to validate_length_of(:website_url).is_at_most(500) }
it 'only validates the website_url if it is changed' do
user_detail = create(:user_detail)
# `update_attribute` required to bypass current validations
# Validations on `User#website_url` were added after
# there was already data in the database and `UserDetail#website_url` is
# derived from `User#website_url` so this reproduces the state of some of
# our production data
user_detail.update_attribute(:website_url, 'NotAUrl')
expect(user_detail).to be_valid
user_detail.website_url = 'AlsoNotAUrl'
expect(user_detail).not_to be_valid
expect(user_detail.errors.full_messages).to match_array(["Website url is not a valid URL"])
end
end
end
describe '#save' do
let(:user_detail) do
create(
:user_detail,
bio: 'bio',
discord: '1234567890123456789',
linkedin: 'linkedin',
location: 'location',
mastodon: '@[email protected]',
organization: 'organization',
skype: 'skype',
twitter: 'twitter',
website_url: 'https://example.com'
)
end
shared_examples 'prevents `nil` value' do |attr|
it 'converts `nil` to the empty string' do
user_detail[attr] = nil
expect { user_detail.save! }
.to change { user_detail[attr] }.to('')
.and not_change { user_detail.attributes.except(attr.to_s) }
end
end
it_behaves_like 'prevents `nil` value', :bio
it_behaves_like 'prevents `nil` value', :discord
it_behaves_like 'prevents `nil` value', :linkedin
it_behaves_like 'prevents `nil` value', :location
it_behaves_like 'prevents `nil` value', :mastodon
it_behaves_like 'prevents `nil` value', :organization
it_behaves_like 'prevents `nil` value', :skype
it_behaves_like 'prevents `nil` value', :twitter
it_behaves_like 'prevents `nil` value', :website_url
end
describe '#sanitize_attrs' do
shared_examples 'sanitizes html' do |attr|
it 'sanitizes html tags' do
details = build_stubbed(:user_detail, attr => '<a href="//evil.com">https://example.com<a>')
expect { details.sanitize_attrs }.to change { details[attr] }.to('https://example.com')
end
it 'sanitizes iframe scripts' do
details = build_stubbed(:user_detail, attr => '<iframe src=javascript:alert()><iframe>')
expect { details.sanitize_attrs }.to change { details[attr] }.to('')
end
it 'sanitizes js scripts' do
details = build_stubbed(:user_detail, attr => '<script>alert("Test")</script>')
expect { details.sanitize_attrs }.to change { details[attr] }.to('')
end
end
%i[linkedin skype twitter website_url].each do |attr|
it_behaves_like 'sanitizes html', attr
it 'encodes HTML entities' do
details = build_stubbed(:user_detail, attr => 'test&attr')
expect { details.sanitize_attrs }.to change { details[attr] }.to('test&attr')
end
end
%i[location organization].each do |attr|
it_behaves_like 'sanitizes html', attr
it 'does not encode HTML entities' do
details = build_stubbed(:user_detail, attr => 'test&attr')
expect { details.sanitize_attrs }.not_to change { details[attr] }
end
end
it 'sanitizes on validation' do
details = build(:user_detail)
expect(details)
.to receive(:sanitize_attrs)
.at_least(:once)
.and_call_original
details.save!
end
end
end |
class OceanFloor
def initialize
@map = {}
@map.default = 0
end
def accept(p1, p2)
dir_x = -1 * (p1[0] <=> p2[0])
dir_y = -1 * (p1[1] <=> p2[1])
len_x = (p1[0] - p2[0]).abs
len_y = (p1[1] - p2[1]).abs
length = [len_x, len_y].max
(length + 1).times do |i|
x = p1[0] + (dir_x * i)
y = p1[1] + (dir_y * i)
@map[[x,y]] += 1
end
end
def get_iterator(n1, n2)
return n1.method(:upto) if n1 <= n2
n1.method(:downto)
end
def count_greater_than(n)
p @map.values.filter {|v| v > n}
@map.values.filter {|v| v > n}.size
end
end
lines = File.open('5-input').readlines.collect {|l| l.strip }
# split each line on the ->, then each pair on the comma, then convert the str to int
# so 0,9 -> 5,9 becomes [[0, 9], [5, 9]]
data = lines.map {|l| l.split(' -> ').map{|i| i.split(',').map{|n| n.to_i}}}
ocean_floor = OceanFloor.new
data.each do |line|
p line
ocean_floor.accept(line[0], line[1])
end
p ocean_floor
p ocean_floor.count_greater_than 1 |
---
title: 'Top Linux commands that commonly used in DevOps'
description: '🐧 Top 79 Linux commands that are commonly used in DevOps ♾'
pubDate: '2024-04-01'
heroImage: '../../assets/images/linux_poster.jpg'
category: 'DevOps'
tags:
- DevOps
- Linux
- LearningResources
---
## 🚀 **_As a DevOps engineer, ideally you should have proficiency in the Linux._**
_As a DevOps professional, mastering the Linux command line is crucial for efficient server management, automation, and troubleshooting. In this comprehensive guide, we’ll explore top **79 essential Linux commands that every DevOps user** should know. Each command is accompanied by a clear explanation and practical examples to help you deepen your Linux proficiency._
### This article will help in understanding most of the important and majorly used Linux commands that would be required for a DevOps Engineer
To execute these commands one can either use any Linux machine / virtual machine / online Linux terminal to quickly start working with the commands
### What is Linux?
- Linux is an operating system, the same as Windows, iOS, and Mac OS.
In fact, Linux is the operating system that powers one of the most well-known platforms, Android.
- All of the hardware resources connected to your desktop or laptop are managed by an operating system, which is a piece of software.
- The operating system, in a nutshell, controls how your software and hardware communicate with one another.
- The operating system (OS) is necessary for the software to run.
### Why is Linux used for DevOps?
- One of the main practices carried out by the majority of IT companies is infrastructure automation.
- In the area of automating infrastructure, Linux is widely used.
The creation of instances takes less time with Linux’s assistance, and operations run more quickly.
- 47% of businesses will choose Linux by 2021 for major infrastructure versioning and infrastructure automation.
So, Is there any ideal Linux for DevOps?
**Some of the DevOps-friendly Linux distributions are**:
- **Ubuntu**: For good reason, Ubuntu is frequently ranked first when this subject is brought up.
- **Fedora**: For developers who prefer RHEL, Fedora is a good option to be explored.
1. **`ls`**: List directory contents
2. **`cd`**: Change directory
3. **`pwd`**: Print working directory
4. **`mkdir`**: Create a directory
5. **`touch`**: Create a file
6. **`cp`**: Copy files and directories
7. **`mv`**: Move or rename files and directories
8. **`rm`**: Remove files and directories
9. **`find`**: Search for files and directories
10. **`grep`**: Search for patterns in files
11. **`cat`**: Concatenate and display files
12. **`less`**: View file contents page by page
13. **`head`**: Display the first lines of a file
14. **`tail`**: Display the last lines of a file
15. **`vi/vim`**: Text editor
16. **`nano`**: Text editor
17. **`tar`**: Archive and compress files
18. **`gzip`**: Compress files
19. **`gunzip`**: Decompress files
20. **`wget`**: Download files from the web
21. **`curl`**: Transfer data to or from a server
22. **`ssh`**: Secure shell remote login
23. **`scp`**: Securely copy files between hosts
24. **`chmod`**: Change file permissions
25. **`chown`**: Change file ownership
26. **`chgrp`**: Change group ownership
27. **`ps`**: Display running processes
28. **`top`**: Monitor system resources and processes
29. **`kill`**: Terminate processes
30. **`df`**: Display disk space usage
31. **`du`**: Estimate file and directory space usage
32. **`free`**: Display memory usage
33. **`uname`**: Print system information
34. **`ifconfig`**: Configure network interfaces
35. **`ping`**: Test network connectivity
36. **`netstat`**: Network statistics
37. **`iptables`**: Firewall administration
38. **`systemctl`**: Manage system services
39. **`journalctl`**: Query the system journal
40. **`crontab`**: Schedule cron jobs
41. **`useradd`**: Create a user account
42. **`passwd`**: Change user password
43. **`su`**: Switch user
44. **`sudo`**: Execute a command as another user
45. **`usermod`**: Modify user account
46. **`groupadd`**: Create a group
47. **`groupmod`**: Modify a group
48. **`id`**: Print user and group information
49. **`ssh-keygen`**: Generate SSH key pairs
50. **`rsync`**: Synchronize files and directories
51. **`diff`**: Compare files line by line
52. **`patch`**: Apply a patch to files
53. **`tar`**: Extract files from an archive
54. **`curl`**: Perform HTTP requests
55. **`nc`**: Netcat - networking utility
56. **`wget`**: Download files from the web
57. **`whois`**: Lookup domain registration details
58. **`dig`**: DNS lookup utility
59. **`sed`**: Stream editor for text manipulation
60. **`awk`**: Pattern scanning and processing language
61. **`sort`**: Sort lines in a text file
62. **`cut`**: Extract sections from lines of files
63. **`wc`**: Word, line, character, and byte count
64. **`tee`**: Redirect output to multiple files or commands
65. **`history`**: Command history
66. **`source`**: Execute commands from a file in the current shell
67. **`alias`**: Create command aliases
68. **`ln`**: Create links between files
69. **`uname`**: Print system information
70. **`lsof`**: List open files and processes
71. **`mkfs`**: Create a file system
72. **`mount`**: Mount a file system
73. **`umount`**: Unmount a file system
74. **`ssh-agent`**: Manage SSH keys in memory
75. **`grep`**: Search for patterns in files
76. **`tr`**: Translate characters
77. **`cut`**: Select portions of lines from files
78. **`paste`**: Merge lines of files
79. **`uniq`**: Report or omit repeated lines
### ⚡ Conclusion
\_These are some of the **top and most popular Linux commands for DevOps** that our experts have selected to aid you in your **DevOps journey**. You can start to feel the pressure of becoming an expert Linux user by inventively integrating these commands into your work processes.\*
## Support 🫶
- Help spread the word about ProDevOpsGuy by sharing it on social media and recommending it to your friends. 🗣️
- You can also sponsor 🏅 on [Github Sponsors](https://github.com/sponsors/NotHarshhaa) |
<p-confirmDialog [style]="{ width: '450px' }"></p-confirmDialog>
<div *ngIf="vm$ | async as vm" fxLayout="column" fxLayout.gt-sm="row" fxLayoutGap="24px">
<form class="container" [formGroup]="form" (ngSubmit)="submitForm(vm.mode)">
<app-text-input
[placeholder]="'Wprowadź tytuł ogłoszenia'"
[formControlName]="'title'"
[label]="'Tytuł ogłoszenia'"
[errorMessage]="titleErrorMessage">
</app-text-input>
<app-text-area-input
[formControlName]="'description'"
[placeholder]="'Wprowadź opis ogłoszenia'"
[rows]="5"
[label]="'Opis ogłoszenia'"
[errorMessage]="descriptionErrorMessage">
</app-text-area-input>
<div fxLayout="column" fxLayout.gt-sm="row" fxLayoutGap="18px" fxLayoutAlign="center end">
<app-select-input
fxFlex="50"
[formControlName]="'definition'"
[options]="vm.definitions ?? []"
[errorMessage]="definitionErrorMessage"
[label]="'Definicja'"
optionLabel="name"
filterMatchMode="contains"
filterBy="name"
placeholder="Wybierz definicję">
<ng-template appSelectInputSelectedTemplate let-definition>
<div>
<div>{{ form.value['definition'].name }}</div>
</div>
</ng-template>
<ng-template appSelectInputItemTemplate let-definition>
<div>
<div>{{ definition.name }}</div>
</div>
</ng-template>
</app-select-input>
<app-select-input
fxFlex="50"
[formControlName]="'category'"
[options]="vm.categories ?? []"
[errorMessage]="categoryErrorMessage"
[label]="'Kategoria'"
optionLabel="name"
filterMatchMode="contains"
filterBy="name"
placeholder="Wybierz kategorię">
<ng-template appSelectInputSelectedTemplate let-definition>
<div>
<div>{{ form.value['category'].name }}</div>
</div>
</ng-template>
<ng-template appSelectInputItemTemplate let-category>
<div>
<div>{{ category.name }}</div>
</div>
</ng-template>
</app-select-input>
</div>
<div fxLayout="column" fxLayout.gt-sm="row" fxLayoutGap="18px" fxLayoutAlign="center end">
<app-overlay-select-input
fxFlex="50"
[label]="'Lokalizacja'"
[placeholder]="'Wybierz lokalizację'"
[formControlName]="'localization'"
[data]="vm.localizations ?? []">
<ng-template appOverlaySelectInputSelectedTemplate let-localization>
{{ localization.city }}
</ng-template>
<ng-template appOverlaySelectInputHeaderTemplate>
<th>Ulica</th>
<th>Miasto</th>
</ng-template>
<ng-template appOverlaySelectInputRowTemplate let-localization>
<td>{{ localization.street }}</td>
<td>{{ localization.city }}</td>
</ng-template>
</app-overlay-select-input>
<app-button
fxFlex="50"
[type]="'submit'"
[buttonLoading]="vm.status === 'loading'"
[disabled]="!form.valid"
label="Zapisz"
[buttonIcon]="'pi pi-check'"
[buttonStyle]="'raised'"></app-button>
</div>
</form>
<p-fileUpload
#fileUpload
fxFlex="480px"
ngClass.lt-md="p-fileupload-content-lt-md"
name="images[]"
accept="image/*"
[uploadLabel]="'Wgraj'"
[chooseLabel]="'Wybierz'"
[showCancelButton]="false"
[customUpload]="true"
(uploadHandler)="customUploadHandler($event, fileUpload)"
[multiple]="true"
[maxFileSize]="1000000">
<ng-template let-file let-index="index" pTemplate="file">
<div fxLayout="row" fxLayoutGap="16px" [ngStyle]="{ 'margin-bottom': '8px' }">
<img fxFlex="80px" [src]="file.objectURL" />
<div fxFlex>
{{ file.name }}
</div>
<app-button
fxFlexAlign="start"
[buttonIcon]="'pi pi-times'"
(click)="fileUpload.remove($event, index)"></app-button>
</div>
</ng-template>
<ng-template pTemplate="content">
<ng-container *ngIf="vm.advertisement && vm.advertisement.images && vm.advertisement.images.length > 0">
<p-divider [align]="'center'">
<b>Aktualne zdjęcia</b>
</p-divider>
<div fxLayout="column" fxLayoutGap="8px">
<div *ngFor="let file of vm.advertisement.images" fxLayout="row" fxLayoutGap="16px">
<img fxFlex="80px" [src]="file.bytes | base64ToDataUri" />
<div fxFlex>
{{ file.description }}
</div>
<div>
<app-button
[buttonIcon]="file.main ? 'pi pi-star-fill' : 'pi pi-star'"
[buttonStyle]="'flat'"
[buttonRounded]="true"
[buttonColor]="'warning'"
(click)="setMainImage(file.id)"></app-button>
<app-button
[buttonIcon]="'pi pi-trash'"
[buttonStyle]="'flat'"
[buttonRounded]="true"
[buttonColor]="'danger'"
(click)="deleteImage(file.id)"></app-button>
</div>
</div>
</div>
</ng-container>
</ng-template>
</p-fileUpload>
</div> |
import React from 'react';
import { useTranslation } from 'react-i18next';
const useSwitchLang = () => {
const { i18n, t } = useTranslation();
const changeLang = () => {
i18n.changeLanguage(i18n.language === 'en' ? 'de' : 'en');
localStorage.setItem('transzug-lang', JSON.stringify(i18n.language));
};
React.useEffect(() => {
changeHTML(i18n.language);
}, [i18n.language]);
const changeHTML = (lang: string) => {
document.documentElement.lang = lang;
document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
};
return {
changeLang,
};
};
export default useSwitchLang; |
export default interface Cart {
type: string;
id: string;
version: number;
versionModifiedAt: string;
lastMessageSequenceNumber: number;
createdAt: string;
lastModifiedAt: string;
lastModifiedBy: {
clientId: string;
isPlatformClient: boolean;
customer: {
typeId: string;
id: string;
};
};
createdBy: {
clientId: string;
isPlatformClient: boolean;
customer: {
typeId: string;
id: string;
};
};
customerId: string;
lineItems: LineItem[];
cartState: string;
totalPrice: {
type: string;
currencyCode: string;
centAmount: number;
fractionDigits: number;
};
shippingMode: string;
shipping: [];
customLineItems: [];
discountCodes: [];
directDiscounts: [];
inventoryMode: string;
taxMode: string;
taxRoundingMode: string;
taxCalculationMode: string;
deleteDaysAfterLastModification: number;
refusedGifts: [];
origin: string;
itemShippingAddresses: [];
totalLineItemQuantity: number;
}
interface LineItem {
id: string;
productId: string;
name: {
[key: string]: string;
};
productType: {
typeId: string;
id: string;
version: number;
};
productSlug: {
[key: string]: string;
};
variant: {
id: number;
prices: Price[];
images: Image[];
attributes: Attribute[];
assets: [];
};
price: Price;
quantity: number;
discountedPricePerQuantity: [];
perMethodTaxRate: [];
addedAt: string;
lastModifiedAt: string;
state: {
quantity: number;
state: {
typeId: string;
id: string;
};
}[];
priceMode: string;
lineItemMode: string;
totalPrice: {
type: string;
currencyCode: string;
centAmount: number;
fractionDigits: number;
};
taxedPricePortions: [];
}
interface Price {
id: string;
value: {
type: string;
currencyCode: string;
centAmount: number;
fractionDigits: number;
};
discounted: {
value: {
type: string;
currencyCode: string;
centAmount: number;
fractionDigits: number;
};
discount: {
typeId: string;
id: string;
};
};
}
interface Image {
url: string;
dimensions: {
w: number;
h: number;
};
}
interface Attribute {
name: string;
value: string;
}
export interface MeCartsResp {
count: number;
limit: number;
offset: number;
results: Cart[];
} |
from djongo import models
# Create your models here.
class Category(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, created from name.', null=True)
description = models.TextField(null=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Author(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
address = models.CharField(max_length=255, null=True)
email = models.EmailField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Publisher(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
address = models.CharField(max_length=255, null=True)
email = models.EmailField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Book(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, created from name.', null=True)
author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
publisher = models.ForeignKey(Publisher, on_delete=models.SET_NULL, null=True)
price = models.IntegerField(default=0)
old_price = models.IntegerField(default=0)
image = models.TextField()
# thumbnail = models.ImageField(upload_to='images/products/thumbnails')
is_active = models.BooleanField(default=True)
is_bestseller = models.BooleanField(default=False)
description = models.TextField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# categories = models.ArrayReferenceField(to=Category, on_delete=models.CASCADE, null=True)
categories = models.ManyToManyField(to=Category)
def __str__(self):
return self.name
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None |
import { createAsyncThunk } from "@reduxjs/toolkit"
import {
getAllProducts,
addProducts,
updateProducts,
deleteProduct,
getCategory,
} from "../../../services/productServices"
export const fetchProductsByCategory = createAsyncThunk(
"products/fetchProductsByCategory",
async (category: any) => {
const response = await getCategory(category)
return response.data
}
)
// Tüm ürünleri getiren thunk
export const fetchAllProducts = createAsyncThunk(
"products/fetchAllProducts",
async () => {
const response = await getAllProducts()
return response.data
}
)
// Ürün ekleyen thunk
export const addProduct = createAsyncThunk(
"products/addProduct",
async (data: any) => {
const response = await addProducts(data)
return response.data
}
)
// Ürün güncelleyen thunk
export const updateProduct = createAsyncThunk(
"products/updateProduct",
async ({ productId, data }: any) => {
const response = await updateProducts(productId, data)
return response.data
}
)
// Ürünü silen thunk
export const deleteProductById = createAsyncThunk(
"products/deleteProductById",
async (productId: any) => {
const response = await deleteProduct(productId)
return response.data
}
) |
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LiveFile</title>
<link href="https://unpkg.com/[email protected]/css/basscss.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<body class="single">
<div class="hero clearfix">
<header class="clearfix">
<div class="max-width-4 mx-auto">
<div class="md-flex lg-flex items-center">
<a href="/" class="logo">LiveFile</a>
<nav class="flex-auto">
<a href="/">Features</a>
<a href="/">Use Cases</a>
<a href="/blog" class="last">Blog</a>
</nav>
<a href="#" class="join medium xs-hide sm-hide">Join the Waitlist</a>
<a href="#" class="join medium button md-hide lg-hide">Waitlist</a>
<a href="#" class="toggle"><img src="https://icon.now.sh/more_vert/24/1F0166" class="md-hide lg-hide" alt=""></a>
</div>
</div>
</header>
<div class="max-width-3 mx-auto center">
<svg class="art" width="1274" height="1195" viewBox="0 0 1274 1195" xmlns="http://www.w3.org/2000/svg">
<path d="M822.728 34c-216.078 9.134-437.544 67.983-601.236 209.326C112.902 337.09 32.067 472.152 34.035 615.607c1.403 102.251 44.881 201.352 110.357 279.902 65.476 78.55 151.87 137.704 244.04 181.998 126.991 61.028 269.37 95.452 409.443 80.262 140.073-15.191 277.107-83.626 359.56-197.875 84.347-116.875 104.736-275.457 59.182-412.202-45.556-136.745-154.004-249.661-286.134-307.246-132.13-57.585-285.703-60.813-422.576-15.646" stroke="#F4F6FA" stroke-width="67" fill="none" fill-rule="evenodd" stroke-linecap="round"/>
</svg>
</div>
</div>
<div class="max-width-2 mx-auto">
<div class="post py2">
<h1 class="mb1">Welcome to Jekyll!</h1>
<p class="meta mt0 mb3">Posted by <a href="https://github.com/">@</a> on Oct 1, 2018</p>
<div class="mb4">
<p>You’ll find this post in your <code class="highlighter-rouge">_posts</code> directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run <code class="highlighter-rouge">jekyll serve</code>, which launches a web server and auto-regenerates your site when a file is updated.</p>
<p>To add new posts, simply add a file in the <code class="highlighter-rouge">_posts</code> directory that follows the convention <code class="highlighter-rouge">YYYY-MM-DD-name-of-post.ext</code> and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.</p>
<p>Jekyll also offers powerful support for code snippets:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">print_hi</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
<span class="nb">puts</span> <span class="s2">"Hi, </span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">"</span>
<span class="k">end</span>
<span class="n">print_hi</span><span class="p">(</span><span class="s1">'Tom'</span><span class="p">)</span>
<span class="c1">#=> prints 'Hi, Tom' to STDOUT.</span></code></pre></figure>
<p>Check out the <a href="https://jekyllrb.com/docs/home">Jekyll docs</a> for more info on how to get the most out of Jekyll. File all bugs/feature requests at <a href="https://github.com/jekyll/jekyll">Jekyll’s GitHub repo</a>. If you have questions, you can ask them on <a href="https://talk.jekyllrb.com/">Jekyll Talk</a>.</p>
</div>
</div>
</div>
<div class="subscribe clearfix bg-dark py4">
<div class="max-width-1 mx-auto px3">
<p class="h1 center bold">Join the Waitlist</p>
<p class="center mb3">We are so excited to get you access to what we’re building. We think this will change your life.</p>
<form action="">
<input type="text" placeholder="Your Name" class="text">
<input type="text" placeholder="Your Email" class="text mb3">
<div class="center">
<button class="medium">Join the Waitlist</button>
</div>
</form>
</div>
</div>
<footer class="clearfix">
<div class="max-width-4 mx-auto">
<div class="md-flex lg-flex items-center">
<a href="/" class="logo">LiveFile</a>
<nav class="flex-auto">
<a href="/" class="full">Features</a>
<a href="/" class="full">Use Cases</a>
<a href="/blog" class="full last">Blog</a>
<a href=""><img src="https://icon.now.sh/twitter/16/1F0166" alt="" class="icon"></a>
<a href=""><img src="https://icon.now.sh/facebook/16/1F0166" alt="" class="icon"></a>
<a href=""><img src="https://icon.now.sh/linkedin/16/1F0166" alt="" class="icon"></a>
</nav>
<p>© 2018 LiveFile, All Rights Reserved. <br class="sm-hide md-hide lg-hide"><a href="#">We're hiring.</a></p>
</div>
</div>
</footer>
<script type="text/javascript" src='https://code.jquery.com/jquery-3.3.1.min.js'></script>
<script>
$( document ).ready(function() {
$(".join").click(function() {
$('html, body').animate({
scrollTop: $(".subscribe").offset().top
}, 500);
return false;
});
function handler1() {
$("nav").addClass("open");
$('.toggle img').attr('src','https://icon.now.sh/close/24/1F0166');
$(this).one("click", handler2);
return false;
}
function handler2() {
$("nav").removeClass("open");
$('.toggle img').attr('src','https://icon.now.sh/more_vert/24/1F0166');
$(this).one("click", handler1);
return false;
}
$(".toggle").one("click", handler1);
});
</script>
</body>
</html> |
<?php
namespace App\Http\Controllers;
use App\Models\App;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class HomeController extends Controller
{
public function home()
{
return view('home');
}
public function index()
{
$app = App::all();
$users = User::all();
return view('index', compact('app', 'users'));
}
public function create()
{
$user = User::all();
return view('create',[
'user' =>$user
]);
}
public function store(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:5048',
'name' => 'required',
'id_users' => 'required',
// Add more validation rul es as needed
]);
$generatedImageName = $request->image->storeAs('images',
time() . '-' . $request->name . '.'
. $request->image->extension(), 'public');
// dd($generatedImageName) ;
$app = App::create([
'app_name' => $request->input('name'),
'stamp_images' => $generatedImageName,
'status' => $request->input('status'),
'id_users' => $request->input('id_users'),
]);
$app->save();
return redirect('/');
}
public function edit($id)
{
$user = User::all();
$app = App::find($id);
return view('edit',compact('app','user'));
}
public function update(Request $request, $id)
{
$generatedImageName = $request->image->storeAs('images',
time() . '-' . $request->name . '.'
. $request->image->extension(), 'public');
App::where('id', $id)
->update([
'app_name' => $request->input('name'),
'stamp_images' => $generatedImageName,
'status' => $request->input('status'),
'id_users' => $request->input('id_users')
]);
return redirect('/');
}
//save to database
} |
import logo from './logo.svg';
import './App.css';
import Button from './component/Button';
import Box from './cssmodule/Box';
import CheckBox from './cssmodule/component/CheckBox';
import { useState } from 'react';
function App() {
const [check, setCheck] = useState(false);
const onChange = e => {
setCheck(e.target.checked);
}
return (
<div className="App">
{/* Sass 테스트 */}
{/* <div className='button'>
<Button size="large" onClick={() => alert('클릭했어요')}>Button</Button>
<Button>Button</Button>
<Button size={"small"}>Button</Button>
</div>
<div className='button'>
<Button size="large" color={"gray"}>Button</Button>
<Button color={"gray"}>Button</Button>
<Button size={"small"} color={"gray"}>Button</Button>
</div>
<div className='button'>
<Button size="large" color={"pink"}>Button</Button>
<Button color={"pink"}>Button</Button>
<Button size={"small"} color={"pink"}>Button</Button>
</div>
<div className='button'>
<Button size="large" color={"blue"} fullWidth>Button</Button>
<Button color={"gray"} fullWidth>Button</Button>
<Button size={"small"} color={"pink"} fullWidth>Button</Button>
</div> */}
{/* CSS Module 테스트 */}
{/* <Box/>
<Box/> */}
<CheckBox onChange={onChange} checked={check}>
다음 약관에 모두 동의
</CheckBox>
<p>
<b>check : </b>
{ check ? 'true':'false'}
</p>
</div>
);
}
export default App; |
<template>
<div>
<v-tabs>
<v-tab @click="introClick">
<span class="d-md-flex d-none">Intro</span>
<v-tooltip bottom>
<template v-slot:activator="{ on, attrs }">
<v-icon class="d-md-none d-flex" v-bind="attrs" v-on="on">mdi-domain</v-icon>
</template>
<span>Intro</span>
</v-tooltip>
</v-tab>
<v-tab @click="webappClick">
<span class="d-md-flex d-none">Web Application</span>
<v-tooltip bottom>
<template v-slot:activator="{ on, attrs }">
<v-icon class="d-md-none d-flex" v-bind="attrs" v-on="on">mdi-web</v-icon>
</template>
<span>Web App</span>
</v-tooltip>
</v-tab>
<v-tab @click="mobileClick">
<span class="d-md-flex d-none">Simple Mobile App</span>
<v-tooltip bottom>
<template v-slot:activator="{ on, attrs }">
<v-icon class="d-md-none d-flex" v-bind="attrs" v-on="on">mdi-tablet-cellphone</v-icon>
</template>
<span>Simple Mobile App</span>
</v-tooltip>
</v-tab>
</v-tabs>
<v-spacer></v-spacer>
<WebAppComponent v-if="webApp"/>
<IntroComponent v-if="intro"/>
<MobileAppComponent v-if="mobile"/>
</div>
</template>
<script>
import IntroComponent from '../components/IntroComponent.vue'
import WebAppComponent from '../components/WebAppComponent.vue'
import MobileAppComponent from '../components/MobileAppComponent.vue'
export default {
data: () => ({
intro: true,
webApp: false,
mobile: false,
}),
components: {
WebAppComponent,
IntroComponent,
MobileAppComponent
},
methods: {
introClick() {
this.intro = true
this.webApp = false
this.mobile = false
},
webappClick() {
this.intro = false
this.webApp = true
this.mobile = false
},
mobileClick() {
this.intro = false
this.webApp = false
this.mobile = true
}
}
}
</script> |
import { BaseMigration } from './base';
import { MigrationStrategy } from './contracts/migrationContract';
import Logger from '../logger';
import { LumError } from '../../utilities/models/LumError';
export class StatesLookupStrategy extends BaseMigration implements MigrationStrategy {
public async run() {
try {
// const result
const alreadyInDb = await this.targetDb.statesLookup.findOne({});
if (alreadyInDb) {
Logger.info(`states already exists in db...`);
return;
}
const defaultStates = [
{ name: 'Alabama', abbreviation: 'AL', supported: false },
{ name: 'Alaska', abbreviation: 'AK', supported: false },
{ name: 'Arizona', abbreviation: 'AZ', supported: false },
{ name: 'Arkansas', abbreviation: 'AR', supported: true },
{ name: 'California', abbreviation: 'CA', supported: false },
{ name: 'Colorado', abbreviation: 'CO', supported: false },
{ name: 'Connecticut', abbreviation: 'CT', supported: false },
{ name: 'Delaware', abbreviation: 'DE', supported: false },
{ name: 'Florida', abbreviation: 'FL', supported: true },
{ name: 'Georgia', abbreviation: 'GA', supported: false },
{ name: 'Hawaii', abbreviation: 'HI', supported: false },
{ name: 'Idaho', abbreviation: 'ID', supported: false },
{ name: 'Illinois', abbreviation: 'IL', supported: false },
{ name: 'Indiana', abbreviation: 'IN', supported: false },
{ name: 'Iowa', abbreviation: 'IA', supported: false },
{ name: 'Kansas', abbreviation: 'KS', supported: true },
{ name: 'Kentucky', abbreviation: 'KY', supported: false },
{ name: 'Louisiana', abbreviation: 'LA', supported: false },
{ name: 'Maine', abbreviation: 'ME', supported: false },
{ name: 'Maryland', abbreviation: 'MD', supported: false },
{ name: 'Massachusetts', abbreviation: 'MA', supported: false },
{ name: 'Michigan', abbreviation: 'MI', supported: false },
{ name: 'Minnesota', abbreviation: 'MN', supported: false },
{ name: 'Mississippi', abbreviation: 'MS', supported: true },
{ name: 'Missouri', abbreviation: 'MO', supported: true },
{ name: 'Montana', abbreviation: 'MT', supported: false },
{ name: 'Nebraska', abbreviation: 'NE', supported: false },
{ name: 'Nevada', abbreviation: 'NV', supported: false },
{ name: 'New Hampshire', abbreviation: 'NH', supported: false },
{ name: 'New Jersey', abbreviation: 'NJ', supported: false },
{ name: 'New Mexico', abbreviation: 'NM', supported: false },
{ name: 'New York', abbreviation: 'NY', supported: false },
{ name: 'North Carolina', abbreviation: 'NC', supported: false },
{ name: 'North Dakota', abbreviation: 'ND', supported: false },
{ name: 'Ohio', abbreviation: 'OH', supported: false },
{ name: 'Oklahoma', abbreviation: 'OK', supported: true },
{ name: 'Oregon', abbreviation: 'OR', supported: false },
{ name: 'Pennsylvania', abbreviation: 'PA', supported: false },
{ name: 'Rhode Island', abbreviation: 'RI', supported: false },
{ name: 'South Carolina', abbreviation: 'SC', supported: false },
{ name: 'South Dakota', abbreviation: 'SD', supported: false },
{ name: 'Tennessee', abbreviation: 'TN', supported: true },
{ name: 'Texas', abbreviation: 'TX', supported: true },
{ name: 'Utah', abbreviation: 'UT', supported: false },
{ name: 'Vermont', abbreviation: 'VT', supported: false },
{ name: 'Virginia', abbreviation: 'VA', supported: false },
{ name: 'Washington', abbreviation: 'WA', supported: false },
{ name: 'West Virginia', abbreviation: 'WV', supported: false },
{ name: 'Wisconsin', abbreviation: 'WI', supported: false },
{ name: 'Wyoming', abbreviation: 'WY', supported: false },
];
const result = await this.targetDb.statesLookup.bulkCreate(defaultStates);
if (result) Logger.info(`Migrated states table`);
} catch (error: any) {
console.log('error:', error);
Logger.error(`Code 500: ${error}`);
throw new LumError(500, error?.errorMessage || 'Error while migrating states');
}
}
} |
#Objective : Write a program in python for any searching techniques.
#Code :
def binary_search(arr, low, high, a):
if high >= low:
mid = (high + low) // 2
if arr[mid] == a:
return mid
elif arr[mid] > a: # If element is smaller than mid, then it can only present in left subarray
return binary_search(arr, low, mid - 1, a)
else: # Else the element can only be present in right subarray
return binary_search(arr, mid + 1, high, a)
else: # Element is not present in the array
return -1
arr = [ 20, 23, 40, 60, 90 ]
a = 23
# Function call
result = binary_search(arr, 0, len(arr)-1, a)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array") |
#Chuong trinh BTL2.D6: Selection sort 10 so nguyen
#-----------------------------------
#Data segment
.data
#Cac cau nhac nhap du lieu
str1: .asciiz "Cac buoc sap xep: \n"
str2: .asciiz "Mang can sap xep: "
str3: .asciiz "Mang sau khi sap xep: "
str4: .asciiz "\n"
str5: .asciiz " "
str6: .asciiz "\n Thoi gian chay: "
str7: .asciiz "ms"
filename: .asciiz "INT10.BIN" # Tên tệp nhị phân
#-----------------------------------
#Code segment
.text
.globl main
#-----------------------------------
#Chuong trinh chinh
#-----------------------------------
main:
# Do thoi gian cua chuong trinh luu vao $a3
li $v0, 30
syscall
add $a3, $zero, $a0
li $s2, 10 # $s2=10
sll $s0, $s2, 2 # $s0=n*4
sub $sp, $sp, $s0 # Lenh nay tao mot khung ngan xep du lon de chua mang
# Mo tep nhi phan
la $a0, filename # Dia chi cua ten tep
li $a1, 0 # Che do doc
li $v0, 13 # Ma he thong cho open
syscall
move $s3, $v0 # Luu giu file descriptor
# Doc du lieu tu tep nhi phan
move $s1, $zero # i=0
for_get:
bge $s1, $s2, exit_get # neu i>=n di den exit_for_get
sll $t0, $s1, 2 # $t0=i*4
add $t1, $t0, $sp # $t1=$sp+i*4
move $a0, $s3 # File descriptor
move $a1, $t1 # Buffer
li $a2, 4 # Kich thuoc
li $v0, 14 # Ma he thong cho read
syscall
addi $s1, $s1, 1 # i=i+1
j for_get
exit_get:
# Dong tep nhi phan
move $a0, $s3 # File descriptor
li $v0, 16 # Ma he thong cho close
syscall
la $a0, str2 # In chuoi str2
li $v0, 4
syscall
move $a0, $sp # $a0=dia chi co so cua mang
move $a1, $s2 # $a1=kich thuoc cua mang
jal isort # isort(a,n)
# Tai thoi diem nay, mang da duoc sap xep va nam trong khung ngan xep
la $a0, str3 # In chuoi str3
li $v0, 4
syscall
move $s1, $zero # i=0
for_print:
bge $s1, $s2, exit_print # neu i>=n di den exit_print
sll $t0, $s1, 2 # $t0=i*4
add $t1, $sp, $t0 # $t1=dia chi cua a[i]
lw $a0, 0($t1) #
li $v0, 1 # in phan tu a[i]
syscall #
la $a0, str5 # In chuoi str5
li $v0, 4
syscall
addi $s1, $s1, 1 # i=i+1
j for_print
exit_print:
add $sp, $sp, $s0 # loai bo khung ngan xep
#tinh thoi gian chay cua chuong trinh
la $a0, str6 # In "\n Thoi gian chay: "
li $v0, 4
syscall
li $v0, 30
syscall
sub $a0, $a0, $a3 # Tinh thoi gian chay $a0 = $a0 - $a3
li $v0, 1
syscall
la $a0, str7 # In "ms"
li $v0, 4
syscall
li $v0, 10 # THOAT
syscall
# selection_sort
isort:
addi $sp, $sp, -20 # luu giu gia tri vao ngan xep
sw $ra, 0($sp)
sw $s0, 4($sp)
sw $s1, 8($sp)
sw $s2, 12($sp)
sw $s3, 16($sp)
move $s0, $a0 # dia chi co so cua mang
move $s1, $zero # i=0
subi $s2, $s2, 1
jal print_array # in mang can sap xep
addi $s2, $s2, 1
la $a0, str1 # In chuoi str1
li $v0, 4
syscall
subi $s2, $a1, 1 # do dai -1
isort_for:
bge $s1, $s2, isort_exit # neu i >= do dai-1 -> thoat vong lap
move $a0, $s0 # dia chi co so
move $a1, $s1 # i
move $a2, $s2 # do dai - 1
jal mini
move $s3, $v0 # gia tri tra ve cua mini
bne $s1, $s3, do_swap # neu i != mini -> thuc hien swap
j isort_continue # nguoc lai, tiep tuc vong lap
do_swap:
move $a0, $s0 # mang
move $a1, $s1 # i
move $a2, $s3 # mini
jal swap
jal print_array
isort_continue:
addi $s1, $s1, 1 # i += 1
j isort_for # quay lai dau vong lap
isort_exit:
lw $ra, 0($sp) # khoi phuc gia tri tu ngan xep
lw $s0, 4($sp)
lw $s1, 8($sp)
lw $s2, 12($sp)
lw $s3, 16($sp)
addi $sp, $sp, 20 # khoi phuc con tro ngan xep
jr $ra # tra ve
#-----------------------------------
#Cac chuong trinh con khac
#-----------------------------------
# Tim index_minimum
mini:
move $t0, $a0 # co so cua mang
move $t1, $a1 # mini = dau tien = i
move $t2, $a2 # cuoi cung
sll $t3, $t1, 2 # dau tien * 4
add $t3, $t3, $t0 # index = mang co so + dau tien * 4
lw $t4, 0($t3) # min = v[dau tien]
addi $t5, $t1, 1 # i = 0
mini_for:
bgt $t5, $t2, mini_end # di den mini_end
sll $t6, $t5, 2 # i * 4
add $t6, $t6, $t0 # index = mang co so + i * 4
lw $t7, 0($t6) # v[index]
bge $t7, $t4, mini_if_exit # bo qua if khi v[i] >= min
move $t1, $t5 # mini = i
move $t4, $t7 # min = v[i]
mini_if_exit:
addi $t5, $t5, 1 # i += 1
j mini_for
mini_end:
move $v0, $t1 # tra ve mini
jr $ra
# Swap
swap:
sll $t1, $a1, 2 # i * 4
add $t1, $a0, $t1 # v + i * 4
sll $t2, $a2, 2 # j * 4
add $t2, $a0, $t2 # v + j * 4
lw $t0, 0($t1) # v[i]
lw $t3, 0($t2) # v[j]
sw $t3, 0($t1) # v[i] = v[j]
sw $t0, 0($t2) # v[j] = $t0
jr $ra
# In mang
print_array:
move $s4, $zero # j=0
print_loop:
bgt $s4, $s2, end_print_array # neu j > do dai-1 -> thoat vong lap
sll $t0, $s4, 2 # $t0=j*4
add $t1, $t0, $s0 # $t1=$s0+j*4
lw $a0, 0($t1)
li $v0, 1 # in phan tu a[j]
syscall
la $a0, str5
li $v0, 4
syscall
addi $s4, $s4, 1 # j=j+1
j print_loop
end_print_array:
la $a0, str4
li $v0, 4
syscall
jr $ra
#----------------------------------- |
import {
Typography,
Button,
Dialog,
DialogHeader,
DialogBody,
DialogFooter,
Input,
Select,
Option,
Alert,
} from '@material-tailwind/react';
import React, { useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import UserItem from './UserItem';
import { object, string } from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import toast from 'react-hot-toast';
import { deleteUserAPI, updateUserAPI } from '../../../../apis/userAPI';
const validationSchema = object({
taiKhoan: string().required('Tài khoản không được trống'),
matKhau: string().required('Mật khẩu không được trống'),
hoTen: string().required('Họ tên không được trống'),
email: string()
.email('Email không đúng định dạng')
.required('Email không được trống'),
soDt: string().required('Số điện thoại không được trống'),
maLoaiNguoiDung: string().required('Loại không được trống'),
});
export default function ListUser({ TABLE_HEAD, users, getUsers }) {
const [open, setOpen] = useState(false);
const [selectedUser, setSelectedUser] = useState(null);
const [error, setError] = useState(null);
const submitBtn = useRef();
const {
register,
handleSubmit,
setValue,
watch,
trigger,
formState: { errors },
} = useForm({
defaultValues: {
taiKhoan: '',
hoTen: '',
matKhau: '',
email: '',
soDt: '',
maLoaiNguoiDung: '',
maNhom: 'GP00',
},
mode: 'onTouched',
resolver: yupResolver(validationSchema),
});
const handleOpen = () => {
setOpen(!open);
};
const handleSelectedUser = (user) => {
setSelectedUser(user);
setTimeout(() => trigger(), 0); //buộc setState trước sau đó mới run trigger
setError(null);
handleOpen();
};
const handleDeleteUser = async (user) => {
try {
await deleteUserAPI(user.taiKhoan);
getUsers();
toast.success('Xóa thành công');
} catch (error) {
toast.error(error);
}
};
const handleEditUser = async (values) => {
try {
await updateUserAPI({ ...values, maNhom: 'GP00' });
getUsers();
handleOpen();
setError(null);
toast.success('Cập nhật người dùng thành công');
} catch (error) {
setError(error);
console.log(error);
}
};
const handleErrors = (errors) => {
console.log(errors);
};
useEffect(() => {
for (let key in selectedUser) {
if (key === 'soDT') {
setValue('soDt', selectedUser[key]);
}
setValue(key, selectedUser[key]);
}
}, [selectedUser]);
return (
<>
<table className="mt-4 w-full min-w-max table-auto text-left">
<thead>
<tr>
{TABLE_HEAD.map((head) => (
<th
key={head}
className="border-y border-blue-gray-100 bg-blue-gray-50/50 p-4"
>
<Typography
variant="small"
color="blue-gray"
className="font-normal leading-none opacity-70"
>
{head}
</Typography>
</th>
))}
</tr>
</thead>
<tbody>
{users.map((user, index) => {
const isLast = index === users.length - 1;
const classes = isLast ? 'p-4' : 'p-4 border-b border-blue-gray-50';
return (
<UserItem
user={user}
classes={classes}
onOpen={handleSelectedUser}
onDeleteUser={handleDeleteUser}
key={user.taiKhoan}
/>
);
})}
</tbody>
</table>
<Dialog open={open} handler={handleOpen}>
<DialogHeader>Edit User</DialogHeader>
<DialogBody>
<form
onSubmit={handleSubmit(handleEditUser, handleErrors)}
className="flex flex-col gap-4"
>
<div className="w-full">
<Input
label="Username"
{...register('taiKhoan')}
disabled={true}
success={!errors.taiKhoan && watch('taiKhoan') !== ''}
error={errors.taiKhoan}
/>
</div>
<div className="w-full">
<Input
label="Email"
{...register('email')}
success={!errors.email && watch('email') !== ''}
error={errors.email}
/>
</div>
<div className="w-full">
<Input
label="Họ Tên"
{...register('hoTen')}
success={!errors.hoTen && watch('hoTen') !== ''}
error={errors.hoTen}
/>
</div>
<div className="w-full">
<Input
label="Số điện thoại"
{...register('soDt')}
success={!errors.soDt && watch('soDt') !== ''}
error={errors.soDt}
/>
</div>
<div className="w-full">
<Input
label="Password"
{...register('matKhau')}
success={!errors.matKhau && watch('matKhau') !== ''}
error={errors.matKhau}
/>
</div>
<div className="w-full">
<Select
label="Loại Người Dùng"
onChange={(value) => {
setValue('maLoaiNguoiDung', value);
}}
value={watch('maLoaiNguoiDung')}
success={
!errors.maLoaiNguoiDung && watch('maLoaiNguoiDung') !== ''
}
>
<Option value="KhachHang">Khách Hàng</Option>
<Option value="QuanTri">Quản Trị</Option>
</Select>
<select className="hidden" {...register('maLoaiNguoiDung')}>
<option value="KhachHang">Khách Hàng</option>
<option value="QuanTri">Quản Trị</option>
</select>
</div>
<input ref={submitBtn} type="submit" hidden />
</form>
{error && (
<Alert color="red" className="mt-2">
{error}
</Alert>
)}
</DialogBody>
<DialogFooter>
<Button
variant="text"
color="red"
onClick={handleOpen}
className="mr-1"
>
<span>Cancel</span>
</Button>
<Button
variant="gradient"
color="green"
onClick={() => {
submitBtn.current.click();
}}
>
<span>Confirm</span>
</Button>
</DialogFooter>
</Dialog>
</>
);
} |
import React from 'react'
import { useEffect, useState } from 'react'
import { creations } from '../utils/data'
import { FaQuoteRight } from 'react-icons/fa'
import { FiChevronRight, FiChevronLeft } from 'react-icons/fi'
import '../creations/Creations.css'
const Creations = () => {
// const [project, setProject] = useState(creations)
const [currentPerson, setCurrentPerson] = useState(0)
const prevSlide = () => {
setCurrentPerson((oldPerson) => {
const result = (oldPerson - 1 + creations.length) % creations.length
return result
})
}
const nextSlide = () => {
setCurrentPerson((oldPerson) => {
const result = (oldPerson + 1) % creations.length
return result
})
}
useEffect(() => {
let sliderId = setInterval(() => {
nextSlide()
}, 5000)
return () => {
clearInterval(sliderId)
}
})
return (
<section className='slider-container'>
{creations.map((project, index) => {
const { id, image, title, subtitle } = project
return (
<article
className='slide'
style={{
transform: `translateX(${100 * (index - currentPerson)}%)`,
}}
key={id}
>
<img src={image} alt={title} className='person-img' />
<h5 className='name'>{title}</h5>
<p className='text'>{subtitle}</p>
<FaQuoteRight className='icon' />
</article>
)
})}
<button type='button' className='prev' onClick={prevSlide}>
<FiChevronLeft />
</button>
<button type='button' className='next' onClick={nextSlide}>
<FiChevronRight />
</button>
</section>
)
}
export default Creations |
package com.example.hibernate.ormapping.onetoone.bidirectional;
import com.example.hibernate.ormapping.onetoone.unidirectional.StudentGfgDetail;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Fetch;
@Entity
@Data
@NoArgsConstructor
@Table(name = "student")
public class Student extends BaseEntity {
private String firstName;
private String lastName;
private String email;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "student_gfg_detail_id")
private StudentGfgDetail studentGfgDetail;
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
@Override
public String toString() {
return "Student{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", studentGfgDetail=" + studentGfgDetail +
'}';
}
} |
import {
AppBar,
Button,
IconButton,
Menu,
MenuItem,
Stack,
Toolbar,
Typography,
} from "@mui/material";
import CatchingPokemonIcon from "@mui/icons-material/CatchingPokemon";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import { useState } from "react";
const MuiNavbar = () => {
const [anchorElement, setAnchorElement] = useState(null);
const open = Boolean(anchorElement);
const handleClick = (e) => {
setAnchorElement(e.currentTarget);
};
const handleClose = () => {
setAnchorElement(null);
};
return (
<AppBar position="static">
<Toolbar>
<IconButton size="large" edge="start" color="inherit" aria-label="logo">
<CatchingPokemonIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
POKEMONAPP
</Typography>
<Stack direction="row" spacing={2}>
<Button color="inherit">Features</Button>
<Button color="inherit">Pricing</Button>
<Button color="inherit">About</Button>
<Button
color="inherit"
id="resources-button"
onClick={handleClick}
aria-controls={open ? "resources-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
endIcon={<KeyboardArrowDownIcon />}
>
Resources
</Button>
<Button color="inherit">Login</Button>
</Stack>
<Menu
id="resources-menu"
anchorEl={anchorElement}
open={open}
MenuListProps={{
"aria-labelledby": "resources-button",
}}
onClose={handleClose}
anchorOrigin={{
vertical: "bottom",
horizontal: "right",
}}
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
>
<MenuItem onClick={handleClose}>Blog</MenuItem>
<MenuItem onClick={handleClose}>Podcast</MenuItem>
</Menu>
</Toolbar>
</AppBar>
);
};
export default MuiNavbar; |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import sys
from oslo_config import cfg
ALL_OPTS = [
cfg.StrOpt('pybasedir',
default=os.path.abspath(os.path.join(os.path.dirname(__file__),
'../../')),
sample_default='<Path>',
help="""
The directory where the Nova python modules are installed.
This directory is used to store template files for networking and remote
console access. It is also the default path for other config options which
need to persist Nova internal data. It is very unlikely that you need to
change this option from its default value.
Possible values:
* The full path to a directory.
Related options:
* ``state_path``
"""),
cfg.StrOpt('bindir',
default=os.path.join(sys.prefix, 'local', 'bin'),
help="""
The directory where the Nova binaries are installed.
This option is only relevant if the networking capabilities from Nova are
used (see services below). Nova's networking capabilities are targeted to
be fully replaced by Neutron in the future. It is very unlikely that you need
to change this option from its default value.
Possible values:
* The full path to a directory.
"""),
cfg.StrOpt('state_path',
default='$pybasedir',
help="""
The top-level directory for maintaining Nova's state.
This directory is used to store Nova's internal state. It is used by a
variety of other config options which derive from this. In some scenarios
(for example migrations) it makes sense to use a storage location which is
shared between multiple compute hosts (for example via NFS). Unless the
option ``instances_path`` gets overwritten, this directory can grow very
large.
Possible values:
* The full path to a directory. Defaults to value provided in ``pybasedir``.
"""),
]
def basedir_def(*args):
"""Return an uninterpolated path relative to $pybasedir."""
return os.path.join('$pybasedir', *args)
def bindir_def(*args):
"""Return an uninterpolated path relative to $bindir."""
return os.path.join('$bindir', *args)
def state_path_def(*args):
"""Return an uninterpolated path relative to $state_path."""
return os.path.join('$state_path', *args)
def register_opts(conf):
conf.register_opts(ALL_OPTS)
def list_opts():
return {"DEFAULT": ALL_OPTS} |
import numpy as np
import imageio
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
MAX_PIXEL_VALUE=255
RGB_DIM = 3
GRAYSCALE = 1
RGB = 2
RGB_YIQ_TRANSFORMATION_MATRIX = np.array([[0.299, 0.587, 0.114],
[0.596, -0.275, -0.321],
[0.212, -0.523, 0.311]])
def read_image(filename, representation):
"""
Reads an image and converts it into a given representation
:param filename: filename of image on disk
:param representation: 1 for greyscale and 2 for RGB
:return: Returns the image as an np.float64 matrix normalized to [0,1]
"""
im = imageio.imread(filename)
if np.ndim(im) == RGB_DIM and representation == GRAYSCALE:
im = rgb2gray(im)
im_float = im.astype(np.float64)
if np.amax(im_float) > 1:
im_float /= MAX_PIXEL_VALUE
return im_float
def imdisplay(filename, representation):
"""
Reads an image and displays it into a given representation
:param filename: filename of image on disk
:param representation: 1 for greyscale and 2 for RGB
"""
im = read_image(filename, representation)
plt.imshow(im, cmap=plt.cm.gray)
plt.show()
def rgb2yiq(imRGB):
"""
Transform an RGB image into the YIQ color space
:param imRGB: height X width X 3 np.float64 matrix in the [0,1] range
:return: the image in the YIQ space
"""
r = imRGB[:, :, 0]
g = imRGB[:, :, 1]
b = imRGB[:, :, 2]
y = r * RGB_YIQ_TRANSFORMATION_MATRIX[0, 0] + g * RGB_YIQ_TRANSFORMATION_MATRIX[0, 1] + b * \
RGB_YIQ_TRANSFORMATION_MATRIX[0, 2]
i = r * RGB_YIQ_TRANSFORMATION_MATRIX[1, 0] + g * RGB_YIQ_TRANSFORMATION_MATRIX[1, 1] + b * \
RGB_YIQ_TRANSFORMATION_MATRIX[1, 2]
q = r * RGB_YIQ_TRANSFORMATION_MATRIX[2, 0] + g * RGB_YIQ_TRANSFORMATION_MATRIX[2, 1] + b * \
RGB_YIQ_TRANSFORMATION_MATRIX[2, 2]
imYIQ = imRGB.copy()
imYIQ[:, :, 0] = y
imYIQ[:, :, 1] = i
imYIQ[:, :, 2] = q
return imYIQ
def yiq2rgb(imYIQ):
"""
Transform a YIQ image into the RGB color space
:param imYIQ: height X width X 3 np.float64 matrix in the [0,1] range for
the Y channel and in the range of [-1,1] for the I,Q channels
:return: the image in the RGB space
"""
yiq_rgb_transformation_matrix = np.linalg.inv(RGB_YIQ_TRANSFORMATION_MATRIX)
y = imYIQ[:, :, 0]
i = imYIQ[:, :, 1]
q = imYIQ[:, :, 2]
r = y * yiq_rgb_transformation_matrix[0, 0] + i * yiq_rgb_transformation_matrix[0, 1] + q * \
yiq_rgb_transformation_matrix[0, 2]
g = y * yiq_rgb_transformation_matrix[1, 0] + i * yiq_rgb_transformation_matrix[1, 1] + q * \
yiq_rgb_transformation_matrix[1, 2]
b = y * yiq_rgb_transformation_matrix[2, 0] + i * yiq_rgb_transformation_matrix[2, 1] + q * \
yiq_rgb_transformation_matrix[2, 2]
imRGB = imYIQ.copy()
imRGB[:, :, 0] = r
imRGB[:, :, 1] = g
imRGB[:, :, 2] = b
return imRGB
def histogram_equalize(im_orig):
"""
Perform histogram equalization on the given image
:param im_orig: Input float64 [0,1] image
:return: [im_eq, hist_orig, hist_eq]
"""
im_tmp = im_orig
im_tmp_3_channels = im_orig
if np.ndim(im_orig) == 3:
im_tmp_3_channels = rgb2yiq(im_orig) # converting the RGB image to YIQ.
im_tmp = im_tmp_3_channels[:, :, 0] # taking only the Y channel of the converted image.
# performing histogram equalization algorithm as seen in class
hist_orig = np.histogram(im_tmp, bins=256, range=(0, 1))[0]
hist_sum = np.cumsum(hist_orig)
sum_pixels = np.sum(hist_orig)
first_none_zero_index = (hist_sum != 0).argmax(axis=0)
first_none_zero_value = hist_sum[first_none_zero_index]
if hist_sum[MAX_PIXEL_VALUE] - first_none_zero_value == 0:
return [im_orig, hist_orig, hist_orig]
hist_new_indexes = (MAX_PIXEL_VALUE * (
(hist_sum - first_none_zero_value) / (sum_pixels - first_none_zero_value))).round()
hist_new_indexes = hist_new_indexes.astype("int64")
hist_eq = np.zeros(256, dtype=np.float64)
np.put(hist_eq, hist_new_indexes, hist_orig)
# replace value in im_orig with hist_new_indexes[value]
mapping = np.zeros(256, dtype=np.float64)
mapping[np.arange(256)] = hist_new_indexes
im_tmp *= MAX_PIXEL_VALUE
im_tmp = im_tmp.astype("int64")
im_eq = mapping[im_tmp]
im_eq = im_eq.astype(np.float64)
im_eq /= MAX_PIXEL_VALUE
if np.ndim(im_orig) == 3:
im_tmp_3_channels[:, :, 0] = im_eq
im_eq = yiq2rgb(im_tmp_3_channels)
return [im_eq, hist_orig, hist_eq]
def quantize(im_orig, n_quant, n_iter):
"""
Performs optimal quantization of a given greyscale or RGB image
:param im_orig: Input float64 [0,1] image
:param n_quant: Number of intensities im_quant image will have
:param n_iter: Maximum number of iterations of the optimization
:return: im_quant - is the quantized output image
error - is an array with shape (n_iter,) (or less) of
the total intensities error for each iteration of the
quantization procedure
"""
im_tmp = im_orig
im_tmp_3_channels = im_orig
if np.ndim(im_orig) == 3:
im_tmp_3_channels = rgb2yiq(im_orig) # converting the RGB image to YIQ.
im_tmp = im_tmp_3_channels[:, :, 0] # taking only the Y channel of the converted image.
hist = np.histogram(im_tmp, bins=256, range=(0, 1))[0] # create image histogram
hist_cum = np.cumsum(hist) # create cumulative histogram
z_arr = np.zeros(n_quant + 1, dtype=np.int64) # computing z of size shape (n_quant+1,)
z_arr[0] = -1
z_arr[-1] = MAX_PIXEL_VALUE
sum_pixels = hist_cum[-1]
bin_pixels_avg = sum_pixels / n_quant # initial amount of pixels in each bin of z
q_arr = np.zeros(n_quant, dtype=np.int64)
for i in range(1, n_quant):
z_arr[i] = np.argmax(hist_cum >= (bin_pixels_avg * i))
# initialize q
for i in range(n_quant):
q_arr[i] = (z_arr[i + 1] + z_arr[i]) // 2
z_error = []
error = []
iter_runner = 0
convergence = False
indx_arr = np.arange(256)
while (iter_runner < n_iter) and (not convergence):
error_count = 0
for q_index in range(n_quant):
# computing z_i
if q_index != 0:
new_z = (q_arr[q_index - 1] + q_arr[q_index]) // 2
if z_arr[q_index] != new_z:
z_arr[q_index] = int(new_z)
error_count += 1
# calculating qi according to formula shown in class
for q_index in range(n_quant):
start = int(z_arr[q_index]) + 1
end = int(z_arr[q_index + 1])
new_qi_sum_top = np.sum(indx_arr[start:end + 1] * hist[start:end + 1])
new_qi_sum_bottom = np.sum(hist[start:end + 1])
if new_qi_sum_bottom != 0:
q_arr[q_index] = int(new_qi_sum_top / new_qi_sum_bottom)
# calculatin the new error according to formuale shown in class
new_error = 0
for q_index in range(n_quant):
start = int(z_arr[q_index]) + 1
end = int(z_arr[q_index + 1])
new_error += np.sum(((q_arr[q_index] - indx_arr[start:end + 1]) ** 2) * hist[start:end + 1])
iter_runner += 1
error.append(new_error)
z_error.append(error_count)
if error_count == 0:
convergence = True # exit loop
im_quant = np.zeros(im_tmp.shape, dtype=np.float64)
im_tmp *= MAX_PIXEL_VALUE
im_tmp = im_tmp.astype(np.int64)
new_idx_arr = np.zeros(256, dtype=np.int64)
for q_index in range(n_quant):
new_idx_arr[z_arr[q_index] + 1:z_arr[q_index + 1] + 1] = q_arr[q_index]
new_idx_arr[z_arr[-2]:z_arr[-1] + 1] = q_arr[-1]
im_quant = new_idx_arr[im_tmp].astype(np.float64)
im_quant /= MAX_PIXEL_VALUE
if np.ndim(im_orig) == 3:
im_tmp_3_channels[:, :, 0] = im_quant
im_quant = yiq2rgb(im_tmp_3_channels)
return [im_quant, error] |
<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>8-bit Sound and Music Engine</title>
<meta charset="utf-8">
<meta name="description" content="8-bit sound and music engine">
<meta name="keywords" content="ZZT, 8-bit sound, 8-bit music, JavaScript">
<meta name="author" content="Jesse Wiesenborn">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.musicbox {
font-family: monospace;
font-size: 9pt;
/*color: blue;
background-color: cornsilk;*/
width: 70%;
border: 1px;
}
</style>
</head>
<body>
<center>
<br>8-bit Sound and Music Engine<br><br>
by Jesse Wiesenborn
<br><br>In 1991, Epic Megagames made PC gaming history with <i>ZZT</i>, a DOS-based adventure with a built-in programming language called <i>ZZT-OOP</i>. This allowed players to create, among other things, their own musical sequences. Now you can create <i>ZZT-OOP</i> sounds and musical sequences in your own web browser with this JavaScript applet.<br/><br/>
Because sound and music are composed of waves, this program uses trigonometric functions (and one or two derivatives) to compute audio waveforms based on user-specified input and parameters. Typing a musical note sequence into the box below, for example, 'ICDEFGAB+CH.CQX' will play an ascending C scale in eighth notes, followed by a dotted half-note C and a quarter note rest. For variations on "Twinkle, Twinkle, Little Star," you can copy-paste the sequence from <a href='twinkle.txt'>this textfile</a> into the box and click 'Play sequence'.<br/><br/>
To hear sound, you'll need computer speakers or headphones. You can also export to WAV format for playback on an external audio application. <br/><br/>
<!--
<br>Software Requirements Specification
<br>
<br>The goal of this project is to make a platform for users to create and perform their own 8-bit computer music. The idea for this program comes from the 1991 computer game "ZZT" by Epic Megagames. With ZZT, players could build their own game boards, code their own objects, and write their own computer music. The scope of this project is to build an interface for the creation of 8-bit computer music such as that which players could make with ZZT.
<br>
<br>The objective of this branch is to add a user interface to our existing code from the 'Javawave' Javascript audio synthesizer (https://github.com/jwiesenborn/javawave). This user interface (UI) may be a single textbox for typing in alphanumeric codes correlating with musical notes and a button for the user to play the sequence. Then users can write their own 8-bit musical sequences and play them back on the computer without the trouble of emulating the DOS-era game on their modern machine. The advantage of using Javascript is that it lowers the technical barrier for users to access the platform, as there is no downloading or installation required to run the music engine. In contrast with classic ZZT, this project also may be expanded to include additional functions and has an outlook of integration with online services such as social networking.
<br>
<br>This program closely mirrors the original ZZT-OOP syntax for musical sequences, with some additional note durations and frequencies. A syntactical guide is included. Future iterations could further extend the program such as adding support for multiple channels, sequences of greater complexity, and chords or arpeggiations to study applications in musical theory.
<br>-->
Bit depth: <input type="radio" id="8-bit" value="8-bit" name="bitdepth" checked><label for="8-bit">8-bit</label> | <input type="radio" id="16-bit" value="16-bit" name="bitdepth"><label for="16-bit">16-bit</label><br>
<br>
Sample rate: <input type="text" id="samplerate" value="44100"></input> samples per second (e.g., 44100)
<br><br>
Tempo: Q = <input type="text" id="tempo" value="160"></input> beats per minute
<br><br>
Volume: 1 / <input type="text" id="volume" value="1"></input> (This fraction reduces the volume of the sound output by the denominator entered here. You can use this if you are exporting multiple voices to combine in an external application such as Audacity. Typically this value is the total number of voices in your composition, i.e., if your composition has three voices, type 3 here. If you have four, type 4 etc.)
<br><br>
#Play:<br>
<textarea id="musicbox" rows="15" cols="75" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
<br><br><!--
<button type="button" id="savetext">Save code</button>--> <button type="button" id="play" onClick="play('play');">Play sequence</button> <button type="button" id="Export to WAV" onClick="play('export');">Export to WAV</button>
<br>
<br>The following syntactical codes will run in this application. It plays original <i>ZZT</i> syntax with the exception of scientific notation (which defines octaves as C to B instead of A to G) and no drums (yet!) but does add some new features such as 64th notes and extended range. This table is courtesy of <a href="https://museumofzzt.com/article/view/747/zzt-oop-101/#play">Museum of ZZT</a>:<br>
<br>
<table border=1>
<tr>
<th>-</th>
<th>Symbol</th><th>Effect</th>
</tr>
<tr>
<th>Basic Notes</th>
<td class="c">C<br>D<br>E<br>F<br>G<br>A<br>B<br></td>
<td>Plays note</td>
</tr>
<tr>
<th>Rest</th><td class="c">X</td>
<td>Rests</td>
</tr>
<tr>
<th rowspan="3">Accidentals<br>(Placed after a basic note)</th>
<tr><td class="c">#</td><td>Sharp</td></tr>
<tr><td class="c">!</td><td>Flat</td></tr>
</tr>
<tr>
<th rowspan="17">Basic Durations</th>
</tr>
<tr><td class="c">W</td><td>Whole Note</td></tr>
<tr><td class="c">H</td><td>Half Note</td></tr>
<tr><td class="c">Q</td><td>Quarter note</td></tr>
<tr><td class="c">I</td><td>Eighth note</td></tr>
<tr><td class="c">S</td><td>Sixteenth note</td></tr>
<tr><td class="c">T</td><td>Thirty-second note</td></tr>
<tr><td class="c">Y</td><td>64th note (new!)</td></tr>
<tr><td class="c">N</td><td>128th note (new!)</td></tr>
<tr><td class="c">U</td><td>256th note (new!)</td></tr>
<tr><td class="c">V</td><td>512th note (new!)</td></tr>
<tr><td class="c">O</td><td>1,024th note (experimental)</td></tr>
<tr><td class="c">R</td><td>2,048th note (experimental)</td></tr>
<tr><td class="c">P</td><td>4,096th note (experimental)</td></tr>
<tr><td class="c">J</td><td>8,192nd note (experimental)</td></tr>
<tr><td class="c">K</td><td>16,384th note (experimental)</td></tr>
<tr><td class="c">L</td><td>32,768th note (experimental)</td></tr>
<!--<tr><td class="c">Z</td><td>65,536th note (experimental)</td></tr>-->
<tr>
<th rowspan="2">Advanced Durations</th>
<td class="c">3</td>
<td>Triplet: Cuts the previous duration into thirds. (Ex: Q3CDE would play the C, D, and E notes totaling the time of a quarter note.)</td>
</tr>
<tr>
<td class="c">.</td>
<td>Time-and-a-half: Extends the current duration by 50%. (Ex: H.C would play a C-note with a duration equal to three quarter notes.)</td>
</tr>
<tr>
<tr><th rowspan="3">Octaves<br>(Default: <s>3</s> 4)</th></tr>
<tr><td class="c">+</td><td>Increases the octave by 1 up to a maximum of <s>6</s> 9.</td></tr>
<tr><td class="c">-</td><td>Decreases the octave by 1 down to a minimum of <s>1</s> -2.</td></tr>
</tr>
<!--
<tr><th rowspan="10">Drums</th></tr>
<tr><td class="c">1</td><td>Tick</td></tr>
<tr><td class="c">2</td><td>Tweet</td></tr>
<tr><td class="c">4</td><td>Cowbell</td></tr>
<tr><td class="c">5</td><td>Hi snare</td></tr>
<tr><td class="c">6</td><td>High woodblock</td></tr>
<tr><td class="c">7</td><td>Low snare</td></tr>
<tr><td class="c">8</td><td>Low tom</td></tr>
<tr><td class="c">9</td><td>Low woodblock</td></tr>
<tr><td class="c">0</td><td>Bass drum</td></tr>
-->
</table>
<br/><br/>For more examples, try playing the sound effects listed at <a href="https://wiki.zzt.org/wiki/Sound_effects">https://wiki.zzt.org/wiki/Sound_effects</a>
<br/><br/>Thank you to <a href="http://soundfile.sapp.org/doc/WaveFormat/">soundfile++</a> for providing the Microsoft WAV file format specification.<br/><br/>
</center>
<script>
// title: 8-bit Sound and Music Engine
// author: Jesse Wiesenborn
// date: 9/13/2023
// version: 0.17
// git: https://github.com/jwiesenborn/javawave
// Global constants and objects
var bitsPerSample = 0; //
var bitDepth = 0; //((2 ^ bitsPerSample) - 1) / 2;
var eightBit = false;
var sixteenBit = false;
var numchannel = 1;
var global_y_Offset = 0.000000; //vertical offset between notes
var global_direction = ""; //plus-or-minus semaphore
var xCursor = 0; //xCursor is the offset in bytes
var defaultDuration = 1; //quarter note
var defaultOctave = 4; //default octave
var musicText = ''; //needs global scope for some reason
var sampleRate = 0;
var tempo = 0;
var quarterNoteDuration = 0;
var action = "";
var frequency = 0;
var actualDuration = 0;
var note = "";
var compareOutput = "";
var volumeMultiplier = 1.0; //new
// This ArrayBuffer default may seem large at 26 MB, but this is necessary because JavaScript can't dynamically change the size of the array itself
// (or maybe I just don't know how to do it yet.) It shouldn't be too slow because the Dataview doesn't need to access all of it at once.
// I initially tried resizing the buffer on-the-fly with buffer.resize() but it's not supported.
const buffer = new ArrayBuffer(26460000); //26460000 is 5 minutes of 44,100 16-bit samples per second
var view = new DataView(buffer, 0);
// Get user-defined bit depth from radio button(s) and assign to global variable
function getBitDepth(){
//console.log(document.getElementById('8-bit').checked + ", " + document.getElementById('16-bit').checked); //for debugging
if (document.getElementById('8-bit').checked == true) {
bitsPerSample = 8;
bitDepth = 255 / 2;
eightBit = true;
console.log("Bit depth: 8bit");
}
if (document.getElementById('16-bit').checked == true) {
bitsPerSample = 16;
bitDepth = 65535 / 2;
sixteenBit = true;
console.log("Bit depth: 16bit");
}
}
// Get user-defined sample rate from textbox and assign to variable.
function getSampleRate(){
sampleRate = parseInt(document.getElementById('samplerate').value);
document.getElementById('samplerate').value = sampleRate;
console.log("Sample rate = " + sampleRate);
//console.log("Buffer resizeable? " + buffer.resizable); //for debugging
}
// Get tempo from textbox and assign to global variable.
function getTempo(){
tempo = parseInt(document.getElementById('tempo').value);
document.getElementById('tempo').value = tempo;
console.log("Tempo = " + tempo);
}
// Get volume denominator from textbox and assign multiplier to global variable.
function getVolume(){
var volumeDenominator = parseFloat(document.getElementById('volume').value);
if (volumeDenominator < 1) {
volumeDenominator = 1;
}
document.getElementById('volume').value = volumeDenominator;
volumeMultiplier = 1 / volumeDenominator;
console.log("Volume = " + volumeMultiplier);
}
// Reset variables so you can change the code text and play a new sequence
// (this is faster than clearing the whole array buffer)
function resetVars(){
bitsPerSample = 0; //
bitDepth = 0; //((2 ^ bitsPerSample) - 1) / 2;
eightBit = false;
sixteenBit = false;
numchannel = 1;
global_y_Offset = 0.000000; //vertical offset between notes
global_direction = ""; //plus-or-minus semaphore
xCursor = 0;
defaultDuration = 1; //quarter note
defaultOctave = 4; //default octave
musicText = ''; //needs global scope for some reason
sampleRate = 0;
tempo = 0;
quarterNoteDuration = 0.000000;
action = "";
frequency = 0;
actualDuration = 0;
note = "";
global_y_Offset = 0.000000; //vertical offset between notes
global_direction = ""; //plus-or-minus semaphore
xCursor = 0;
compareOutput = "";
volumeMultiplier = 1.0;
console.clear();
}
// User clicks the Play button.
function play(action1) {
//reset cache
resetVars();
action = action1;
console.log("Initialized buffer to " + buffer.byteLength + " bytes");
//get user-defined parameters
getBitDepth();
getSampleRate();
getTempo();
getVolume();
quarterNoteDuration = (sampleRate / tempo) * 60;
musicText = document.getElementById("musicbox").value;
//In the future, it would be nice to send this data to the server (with the user's permission) to save their compositions.
if ((sampleRate > 0) && (tempo > 0)) {
//alert(textToDuration(musicText)); //for debugging
// Parse the user-defined text
parseText();
} else{
alert("Sample rate and tempo must be non-negative integers.")
}
}
// Parse the user-defined text.
// This is a little bit tricky because notes are more than one character if a flat or a sharp is added.
// So we keep each note in memory until we are sure the user has finished coding that note, i.e.,
// when another note is begun and there are no more sharps and flats, such as when a new octave is defined,
// a drum, a new note, new duration is defined, an unknown character etc
function parseText() {
//alert(musicText); //for debugging
note = "";
var duration = defaultDuration;
var octave = defaultOctave;
var drum = -1;
var result = "";
var unknown = "";
for (var i = 0; i < musicText.length; i++) {
var c = musicText.charAt(i);
//run tryNote() when the note (or rest) is finished coding
//IF note !='' (note is not blank)
//AND (a new note is being started, a new duration is being defined, a new octave is being defined,
// a drum is played, an invalid character is entered, or the end of the sequence is reached)
//BUT NOT when a sharp# or a flat(!) is being added,
//THEN tryNote/append to buffer, and clear note variable
switch(c.toUpperCase()) {
case "C":
note=tryNote(note, octave, duration);
note = "C";
break;
case "D":
note=tryNote(note, octave, duration);
note = "D";
break;
case "E":
note=tryNote(note, octave, duration);
note = "E";
break;
case "F":
note=tryNote(note, octave, duration);
note = "F";
break;
case "G":
note=tryNote(note, octave, duration);
note = "G";
break;
case "A":
note=tryNote(note, octave, duration);
note = "A";
break;
case "B":
note=tryNote(note, octave, duration);
note = "B";
break;
case "Q":
note=tryNote(note, octave, duration);
duration = 1;
break;
case "H":
note=tryNote(note, octave, duration);
duration = 2;
break;
case "W":
note=tryNote(note, octave, duration);
duration = 4;
break;
case "I":
note=tryNote(note, octave, duration);
duration = 0.5;
break;
case "S":
note=tryNote(note, octave, duration);
duration = 0.25;
break;
case "T":
note=tryNote(note, octave, duration);
duration = 0.125;
break;
case "Y": //sixty-fourth note
note=tryNote(note, octave, duration);
duration = 0.0625;
break;
case "N": //128th-note
note=tryNote(note, octave, duration);
duration = 0.03125;
break;
case "U": //256th-note
note=tryNote(note, octave, duration);
duration = 0.015625;
break;
case "V": //512th-note
note=tryNote(note, octave, duration);
duration = 0.0078125;
break;
case "O": //1,024th-note
note=tryNote(note, octave, duration);
duration = 0.00390625;
break;
case "R": //2,048th-note
note=tryNote(note, octave, duration);
duration = 0.001953125;
break;
case "P": //4,096th-note
note=tryNote(note, octave, duration);
duration = 0.0009765625;
break;
case "J": //8,192nd-note
note=tryNote(note, octave, duration);
duration = 0.00048828125;
break;
case "K": //16,384th-note
note=tryNote(note, octave, duration);
duration = 0.000244140625;
break;
case "L": //32,768th-note
note=tryNote(note, octave, duration);
duration = 0.0001220703125;
break;
//case "Z": //approx one sample at t=160 (didn't work)
// note=tryNote(note, octave, duration);
// duration = 0.00006103515625;
// break;
case "3":
note=tryNote(note, octave, duration);
duration = duration / 3;
break;
case ".":
note=tryNote(note, octave, duration);
duration = duration * 1.5;
break;
case "X":
note=tryNote(note, octave, duration);
note = "X";
break;
case "#":
note = note + "#";
break;
case "!":
note = note + "!";
break;
case "+":
note=tryNote(note, octave, duration);
octave = octave + 1;
break;
case "-":
note=tryNote(note, octave, duration);
octave = octave - 1;
break;
case "1":
note=tryNote(note, octave, duration);
drum = 1;
break;
case "2":
note=tryNote(note, octave, duration);
drum = 2;
break;
case "4":
note=tryNote(note, octave, duration);
drum = 4;
break;
case "5":
note=tryNote(note, octave, duration);
drum = 5;
break;
case "6":
note=tryNote(note, octave, duration);
drum = 6;
break;
case "7":
note=tryNote(note, octave, duration);
drum = 7;
break;
case "8":
note=tryNote(note, octave, duration);
drum = 8;
break;
case "9":
note=tryNote(note, octave, duration);
drum = 9;
break;
case "0":
note=tryNote(note, octave, duration);
drum = 0;
break;
case "\\":
note=tryNote(note, octave, duration);
result = "";
break;
case "&":
note=tryNote(note, octave, duration);
result = "";
break;
case "<":
note=tryNote(note, octave, duration);
result = "";
break;
case ">":
note=tryNote(note, octave, duration);
result = "";
break;
default:
note=tryNote(note, octave, duration);
unknown = unknown + c;
break;
} //end of switch case
//alert(str.charAt(i)); //for debugging
} //end of musicText iterator
note=tryNote(note, octave, duration);
//Encode sequence of notes to data stream.
var outputFile = wavChunk() + fmtChunk() + dataChunk();
//console.log(compareOutput); //for debugging
//Export to file option
if (action == 'export') {
download('file.wav', outputFile);
}
else if (action == 'play') {
//Send to audio output
wavStream(outputFile);
}
//alert("view.byteLength = " + view.byteLength); //for debugging
}
// Convert each user-defined note into terms of frequency, octave, and duration.
// Assume A4 = 440 hz
// Remember, in terms of parsing the text, tryNote executes the "previous" note instead of the "current" note.
function tryNote(note, octave, duration){
if (note!='') {
//console.log("Trying note " + note + ", octave " + octave + ", duration " + duration); //for debugging
for (var i = 0; i < note.length; i++) {
var c = note.charAt(i);
switch(c){ //}.toUpperCase()) {
case "C":
frequency = 261.6255653;
break;
case "D":
frequency = 293.6647679;
break;
case "E":
frequency = 329.6275569;
break;
case "F":
frequency = 349.2282314;
break;
case "G":
frequency = 391.995436;
break;
case "A":
frequency = 440;
break;
case "B":
frequency = 493.8833013;
break;
case "#":
frequency = frequency * 1.059463094;
break;
case "!":
frequency = frequency * 0.9438743127;
break;
case "X":
frequency = 0;
break;
}
}
switch(octave){
case 9:
frequency = frequency * 32;
break;
case 8:
frequency = frequency * 16;
break;
case 7:
frequency = frequency * 8;
break;
case 6:
frequency = frequency * 4;
break;
case 5:
frequency = frequency * 2;
break;
case 4:
frequency = frequency;
break;
case 3:
frequency = frequency / 2;
break;
case 2:
frequency = frequency / 4;
break;
case 1:
frequency = frequency / 8;
break;
case 0:
frequency = frequency / 16;
break;
case -1:
frequency = frequency / 32;
break;
case -2:
frequency = frequency / 64;
break;
default:
console.log("Octave " + octave + " is out of scope. Defaulting to silence.");
frequency = 0;
break;
}
actualDuration = parseInt(quarterNoteDuration * duration); // the actual number of samples this note will occupy.
//console.log("Computing note frequency, actualDuration) //incomplete
// Compute note given frequency and exact duration.
computeNote();
}
return '';
}
// The purpose of this function is to append notes of a sequence together in such a way as to avoid gaps or jumps (discontinuities) in the data signal.
// If you put all the notes together without "stitching" them together to make one continuous wave, you'll hear clicks and pops between each note.
// To create a smooth sound, we start each new note at the same point the previous note left off.
// It was very useful to view the waveforms with Audacity (audacityteam.org) when putting this together.
function computeNote(){
//console.log("Computing frequency " + frequency + ", actual duration " + actualDuration + " samples"); //for debugging
//Make a data view from the buffer.
//8-bit samples are stored as unsigned bytes, ranging from 0 to 255. 16-bit samples are stored as 2's-complement signed integers, ranging from -32768 to 32767.
//source: http://soundfile.sapp.org/doc/WaveFormat/
//8bit ==> uInt8 (unsigned) 16bit ==> Int16 (signed)
//Syntax: DataView.prototype.getUint8() or .setUint8()
//Syntax: DataView.prototype.getInt16() or .setInt16()
//The duration of the array will equal the number of bytes if 8-bit, otherwise it will be times two if 16-bit.
//var durationInBytes = 0;
//if (eightBit == true){
// durationInBytes = actualDuration;
// } else if (sixteenBit == true){
// durationInBytes = actualDuration * 2;
// }
//view = new DataView(buffer, xCursor); //xCursor is the offset in bytes
//var noteArray = new Int16Array(noteDuration); // deprecated
// As part of the process of "stitching" the waves of two different notes together,
// the program has to discern whether the curve is sloping up or down at the point one note-wave ends and a new one begins.
// We use xOffset in the trigonometric computation to determine the starting point of each consecutive wave/note.
var yOffset = global_y_Offset;
var xOffset = 0;
if (global_direction == "+") {
xOffset = 1;
}
else if (global_direction == "-") {
xOffset = -1;
}
else {
xOffset = 1;
}
//console.log(frequency, xOffset, yOffset); //for debugging
//var tmpCursor = xCursor; //deprecated
//var tmpLoop = xCursor + actualDuration; //deprecated
//console.log("xCursor = " + xCursor); //for debugging
// Compute the wave (y) at each sample given (x).
for (x = 0; x < actualDuration; x++) {
var c = computeWave(x, frequency, xOffset, yOffset);
//console.log(c + " = parseInt(computeWave(" + x + ", " + frequency + ", " + xOffset + ", " + yOffset + "))"); //for debugging
//noteArray[x] = c; // * v; //deprecated
//Write each value to its byte in the array buffer.
//View has not been advanced to xCursor, so this needs to be added to each (x).
//8-bit samples are stored as unsigned bytes, ranging from 0 to 255. 16-bit samples are stored as 2's-complement signed integers, ranging from -32768 to 32767.
//source: http://soundfile.sapp.org/doc/WaveFormat/
if (eightBit == true){
d = parseInt(Math.round(c + 127.5)); //unsigned (0,255)
//console.log("Writing integer " + d + " to index " + (xCursor + x) + " in 8 bits."); //for debugging
view.setUint8(xCursor + x, d);
//console.log("Reading value at index " + (xCursor + x) + " in 8 bits = " + view.getUint8(xCursor + x)); //for debugging
//xCursor = xCursor + 1;
} else if (sixteenBit == true){
d = parseInt(Math.round(c)); //signed (-32768, 327767)
//console.log("Writing integer " + d + " to index " + (xCursor + (x * 2)) + " in 16 bits."); //for debugging
view.setInt16(xCursor + (x * 2), d); // Remember 16-bit arrays need two bytes per sample.
//console.log("Reading value at index " + (xCursor + (x * 2)) + " in 16 bits = " + view.getInt16(xCursor + (x * 2))); //for debugging
//xCursor = xCursor + 2; // Remember 16-bit arrays need two bytes per sample.
}
}
//Increment the buffer cursor to the end of the note that has been computed.
if (eightBit == true){
xCursor = xCursor + actualDuration;
xCursor = xCursor - 1; // Correct a discontinuity in the signal
} else if (sixteenBit == true){
xCursor = xCursor + (actualDuration * 2); // Remember 16-bit arrays need two bytes per sample.
xCursor = xCursor - 2; // Correct a discontinuity in the signal
}
//console.log("xCursor = " + xCursor); //for debugging
// Derive computeWave(x) to determine whether the slope is positive or negative.
// Set global semaphores to start the consecutive note at the same point the previous note ended.
if (eightBit == true){
// global_direction = determineUpOrDown(view.getUint8(xCursor-1),view.getUint8(xCursor)); //noteArray[x-2], noteArray[x-1]); //deprecated
global_direction = deriveSlope(x, frequency, xOffset, yOffset);
//global_y_Offset = view.getUint8(xCursor-1) / bitDepth; //noteArray[x-1] / bitDepth; //deprecated
global_y_Offset = c / bitDepth;
//console.log("value at xCursor-2=" + (xCursor -2) + " is " + view.getUint8(xCursor-2));
//console.log("value at xCursor-1=" + (xCursor -1) + " is " + view.getUint8(xCursor-1));
} else if (sixteenBit == true){
// global_direction = determineUpOrDown(view.getInt16(xCursor-2),view.getInt16(xCursor)); //noteArray[x-4], noteArray[x-2]); //deprecated
global_direction = deriveSlope(x, frequency, xOffset, yOffset);
//global_y_Offset = view.getInt16(xCursor-2) / bitDepth; //noteArray[x-2] / bitDepth; //deprecated
global_y_Offset = c / bitDepth;
//console.log("value at xCursor-5=" + (xCursor -5) + " is " + view.getInt16(xCursor-5));
//console.log("value at xCursor-4=" + (xCursor -4) + " is " + view.getInt16(xCursor-4)); //these are the correct values.
//console.log("value at xCursor-3=" + (xCursor -3) + " is " + view.getInt16(xCursor-3));
//console.log("value at xCursor-2=" + (xCursor -2) + " is " + view.getInt16(xCursor-2)); //these are correct
//console.log("value at xCursor-1=" + (xCursor -1) + " is " + view.getInt16(xCursor-1));
}
//console.log('slope ' + global_direction); //debugging
//console.log('offset=' + global_y_Offset + '; asin(offset)=' + Math.asin(global_y_Offset)); //debugging
//return noteArray; //deprecated
}
// Compute the waveform at x=i given frequency, bit depth, and curve-connecting offsets.
function computeWave(i, frequency, xOffset, yOffset) {
//var a = (Math.sin(((Math.PI * 2 * i * frequency) + (Math.asin(yOffset) * samplingRate) ) / samplingRate) ) * bitDepth; //deprecated
var a = (Math.sin(((Math.PI * 2 * i * frequency) + (xOffset * (Math.asin(yOffset) * sampleRate))) / sampleRate) ) * xOffset * bitDepth;
//console.log(a + " = (Math.sin(((Math.PI * 2 * " + i + " * " + frequency + ") + (" + xOffset + "* (Math.asin(" + yOffset + ") * " + sampleRate + "))) / " + sampleRate + ") ) * " + xOffset + " * " + bitDepth + "; )"); //for debugging
return a * volumeMultiplier;
}
// I had a bone-headed realization when I was trying to figure out the slope of the curve at X:
// "Oh yeah, that thing I studied for four years in math class!"
// This function replaces determineUpOrDown(), taking the derivative of our wave synthesis computeWave() function, which is the cosine of the same function.
// If it's positive, then the slope is positive;
// if it's negative, then the slope is negative;
// and if it equals zero, then we take the derivative of the derivative, which is -sin of computeWave.
function deriveSlope(i, frequency, xOffset, yOffset) {
var d = (Math.cos(((Math.PI * 2 * i * frequency) + (xOffset * (Math.asin(yOffset) * sampleRate))) / sampleRate) ) * xOffset * bitDepth;
var dir = "";
if (d > 0) {
dir = "+";
}
else if (d < 0) {
dir = "-";
}
else if (d == 0) {
var e = -1 * ((Math.sin(((Math.PI * 2 * i * frequency) + (xOffset * (Math.asin(yOffset) * sampleRate))) / sampleRate) ) * xOffset * bitDepth);
if (e > 0) {
dir = "+";
}
else if (e < 0) {
dir = "-";
}
}
return dir;
}
// Deprecated. Keeping for posterity, but don't show this to my calculus teacher!
// Find whether a curve is sloping upwards or downwards given two samples.
// Sometimes with 8-bit waves, there are two adjacent samples with equal values,
// causing the wave to "flip" to the other direction
// (or if both samples equal zero.)
// This could be fixed by comparing three or more samples, or by using 16-bit samples instead.
//function determineUpOrDown(a, b) {
// var dir = "";
// if (b > a) { // if the last two samples in the note are increasing, then the curve is going up.
// dir = "+";
// }
// else if (b < a) { // if the last two samples in the note are decreasing, then the curve is going down.
// dir = "-";
// }
// else if (a == b) { //If there is no curve, chances are the point is at the top or bottom of a curve,
// if (a > 0) { // so if it's above zero then the curve is probably going downward
// dir = "-";
// }
// else if (a < 0) { // and if it's below zero then the curve is probably going upward
// dir = "+";
// }
// }
// //console.log("a=" + a + ", b=" + b + ", dir=" + dir); //debugging
// //console.log("Comparing curve slope: (" + a + ", " + b + "), result = " + dir); //debugging
//
// return dir;
//}
// Preliminary volume-shaping function
//
//function volumeShape(i, duration) {
// var v = (Math.cos(Math.PI * i / duration * .5));
// return v;
//}
//
// Deprecated
//
//function Wave(i, frequency, xOffset, yOffset) {
// //var a = (Math.sin(((Math.PI * 2 * i * frequency) + (Math.asin(yOffset) * samplingRate) ) / samplingRate) ) * bitDepth;
// var a = (Math.sin(((Math.PI * 2 * i * frequency) + (xOffset * (Math.asin(yOffset) * samplingRate))) / samplingRate) ) * xOffset * bitDepth;
// return a;
//}
// Stream to computer audio
function wavStream(data) {
var pom = document.createElement('audio');
pom.setAttribute('autoplay', 'autoplay');
pom.setAttribute('src', 'data:audio/wav;charset=utf-8,' + data);
//Deprecated
//if (document.createEvent) {
// var event = document.createEvent('MouseEvents');
// event.initEvent('click', true, true);
// pom.dispatchEvent(event); }
//else {
// pom.click(); }
}
// WAVE chunk
// This function is part of what encodes the audio wave signal to streaming/file format.
// integerToByte_LittleEndian returns a 2-Byte little-endian integer.
// integerTo4Byte_LittleEndian returns 4 bytes etc.
function wavChunk() {
var ChunkID = textTo4Byte_BigEndian("RIFF");
//if 8bit, byte length is xCursor.
//if 16bit, byte length is xCursor * 2.
if (eightBit == true){
var byteLength = xCursor;
} else if (sixteenBit == true){
var byteLength = xCursor * 2;
}
var ChunkSize = integerTo4Byte_LittleEndian(36 + byteLength);
var Format = textTo4Byte_BigEndian("WAVE");
return (ChunkID + ChunkSize + Format);
}
// FORMAT chunk
// This function is part of what encodes the audio wave signal to streaming/file format.
function fmtChunk() {
var Subchunk1ID = textTo4Byte_BigEndian("fmt ");
var Subchunk1Size = integerTo4Byte_LittleEndian(16); //PCM
var AudioFormat = integerToByte_LittleEndian(1); //Uncompressed
var NumChannels = integerToByte_LittleEndian(numchannel); //Mono
var SampleRate = integerTo4Byte_LittleEndian(sampleRate); // samplingRate
var ByteRate = integerTo4Byte_LittleEndian(sampleRate * numchannel * (bitsPerSample/8)); //SamplingRate * NumChannels
var BlockAlign = integerToByte_LittleEndian(numchannel * (bitsPerSample/8));
var bitsPerSampleEncoded = integerToByte_LittleEndian(bitsPerSample);
return(Subchunk1ID + Subchunk1Size + AudioFormat + NumChannels + SampleRate + ByteRate + BlockAlign + bitsPerSampleEncoded);
}
// DATA chunk
// This function is part of what encodes the audio wave signal to streaming/file format.
function dataChunk() {
var Subchunk2ID = textTo4Byte_BigEndian("data");
if (eightBit == true){
var byteLength = xCursor;
} else if (sixteenBit == true){
var byteLength = xCursor * 2;
}
var Subchunk2Size = integerTo4Byte_LittleEndian(byteLength * numchannel * (bitsPerSample/8)); //# of bytes in the array
//alert("DT length=" + dt.length);
//var Data = signedInt16ArrayToUnsigned(dt);
//var returnStr = '';
if (eightBit == true){
var Data = new Uint8Array(buffer, 0, xCursor);
var Data2 = Uint8ArrayToHex(Data);
} else if (sixteenBit == true){
//var Data = new Int16Array(buffer, 0, (xCursor * 2));
var Data2 = Int16ArrayToHex(view);
}
return(Subchunk2ID + Subchunk2Size + Data2);
}
// A Memo on Format Conversion and Byte Endianness in JavaScript
// It is inefficient to convert the data buffer into a URI-encoded hexadecimal string,
// but browsers do not seem to allow direct streaming of the data buffer to output.
// This appears to be a tradeoff of writing a music synthesizer in JavaScript instead of C/C++ or .NET.
// If you know a way to send the data view directly to the output stream without re-encoding it, I would certainly love to hear about it!
// According to MDN, "with a DataView you are able to control the byte-order.
// It is big-endian by default and can be set to little-endian in the getter/setter methods."
// I have yet to get this built-in functionality to work, so I wrote functions to do it manually instead.
// I am sure there is a better way to convert byte arrays to hexadecimal format,
// but at the time I was writing this program I couldn't find any,
// so here are the manual conversion functions.
// Convert a signed 16-bit array to unsigned 16-bit integers,
// then to hexadecimal byte format.
//
function signedInt16ArrayToUnsigned(arr) {
var returnString = "";
for (i = 0; i < arr.length; i++) {
sample = arr[i];
if (sample >= 0) {
var r = integerToByte_LittleEndian(sample); }
else if (sample < 0) {
sample = sample + 65536; // (16^4)
var r = integerToByte_LittleEndian(sample); }
returnString = returnString.concat(r); }
return returnString; }
//
// Convert a signed 16-bit array to hexadecimal byte format.
//
function Int16ArrayToHex() {
//console.log("Int16ArrayToHex");
var returnString = "";
for (i = 0; i < xCursor; i=i+2) {
sample = view.getInt16(i);
if (sample >= 0) {
//var r = integerToByte_LittleEndian(sample); }
}
else if (sample < 0) {
sample = sample + 65536; // (16^4) // Two's Complement
//var r = integerToByte_LittleEndian(sample); }
}
var r = int16ToBytes_LittleEndian(sample);
returnString = returnString.concat(r);
//compareOutput = compareOutput.concat("[" + i + "," + view.getInt16(i) + "]");
}
return returnString;
}
//
function Uint8ArrayToHex(arr) {
//console.log("Uint8ArrayToHex");
var returnString = "";
for (i = 0; i < arr.length; i++) {
sample = arr[i];
var r = Uint8ToByte_LittleEndian(sample);
returnString = returnString.concat(r);
//compareOutput = compareOutput.concat("[" + i + "," + arr[i] + "]");
}
return returnString;
}
// Convert one 16-bit integer to hexadecimal bytes, big-endian,
// and append leading %s for the URI stream encoding.
function integerToByte_BigEndian(s) {
var doubleCheck = s;
var int4 = s % 16;
s = parseInt(s / 16);
var int3 = s % 16;
s = parseInt(s / 16);
var int2 = s % 16;
s = parseInt(s / 16);
var int1 = s % 16;
s = parseInt(s / 16);
//
// Make sure the hexadecimal-converted value equals the original value.
//if (doubleCheck != validate(int1, int2, int3, int4)) {
// alert("Failure: integerToByte_BigEndian(" + s + ") != " + validate(int1, int2, int3, int4) + "."); }
//
return "%" + intToHex(int1) + intToHex(int2) + "%" + intToHex(int3) + intToHex(int4); }
//
// Convert one 16-bit integer to hexadecimal bytes, little-endian,
// and append leading %s for the URI stream encoding.
function integerToByte_LittleEndian(s) {
var doubleCheck = s;
var int1 = s % 16;
s = parseInt(s / 16);
var int2 = s % 16;
s = parseInt(s / 16);
var int3 = s % 16;
s = parseInt(s / 16);
var int4 = s % 16;
s = parseInt(s / 16);
return "%" + intToHex(int2) + intToHex(int1) + "%" + intToHex(int4) + intToHex(int3); }
function Uint8ToByte_LittleEndian(s) {
var doubleCheck = s;
var int1 = s % 16;
s = parseInt(s / 16);
var int2 = s % 16;
s = parseInt(s / 16);
//console.log(":" + doubleCheck + " --> " + int2 + ", " + int1);
return "%" + intToHex(int2) + intToHex(int1); }
function int16ToBytes_LittleEndian(s) {
var doubleCheck = s;
var int1 = s % 16;
s = parseInt(s / 16);
var int2 = s % 16;
s = parseInt(s / 16);
var int3 = s % 16;
s = parseInt(s / 16);
var int4 = s % 16;
s = parseInt(s / 16);
//console.log(":" + doubleCheck + " --> " + int2 + ", " + int1 + ", " + int4 + ", " + int3);
return "%" + intToHex(int2) + intToHex(int1) + "%" + intToHex(int4) + intToHex(int3); }
// Data chunks are 4 bytes
// Convert one 16-bit integer to hexadecimal bytes, little-endian,
// and append leading %s for the URI stream encoding.
function integerTo4Byte_LittleEndian(s) {
//var doubleCheck = s;
var int1 = s % 16;
s = parseInt(s / 16);
var int2 = s % 16;
s = parseInt(s / 16);
var int3 = s % 16;
s = parseInt(s / 16);
var int4 = s % 16;
s = parseInt(s / 16);
var int5 = s % 16;
s = parseInt(s / 16);
var int6 = s % 16;
s = parseInt(s / 16);
var int7 = s % 16;
s = parseInt(s / 16);
var int8 = s % 16;
s = parseInt(s / 16);
return "%" + intToHex(int2) + intToHex(int1) + "%" + intToHex(int4) + intToHex(int3)
+ "%" + intToHex(int6) + intToHex(int5) + "%" + intToHex(int8) + intToHex(int7);
}
// Convert an integer in the range [0,15] to hexadecimal.
function intToHex(n) {
if (n < 10) {
if (n >= 0) {
return n.toString(); }
else { console.log("Error: intToHex(" + n + ")"); } }
switch (n) {
case 10:
var r = "a";
break;
case 11:
var r = "b";
break;
case 12:
var r = "c";
break;
case 13:
var r = "d";
break;
case 14:
var r = "e";
break;
case 15:
var r = "f";
break;
default:
console.log("Error: intToHex(" + n + ")");
break; }
return r; }
//
// Send the data in a URI stream to a downloadable file.
// Source: https://stackoverflow.com/questions/2897619/using-html5-javascript-to-generate-and-save-a-file
//
function download(filename, data) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:audio/wav;charset=utf-8,' + data);
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event); }
else {
pom.click(); } }
//File format blocks are two to four bytes.
//Convert a 4-character string to 4 bytes, big-endian
//Insert % sign for URI encoding.
function textTo4Byte_BigEndian(t) {
t3 = t.charCodeAt(3);
t2 = t.charCodeAt(2);
t1 = t.charCodeAt(1);
t0 = t.charCodeAt(0);
//console.log(t3 + ';' + t2 + ';' + t1 + ';' + t0);
var int8 = t3 % 16;
t3 = parseInt(t3 / 16);
var int7 = t3 % 16;
t3 = parseInt(t3 / 16);
var int6 = t2 % 16;
t2 = parseInt(t2 / 16);
var int5 = t2 % 16;
t2 = parseInt(t2 / 16);
var int4 = t1 % 16;
t1 = parseInt(t1 / 16);
var int3 = t1 % 16;
t1 = parseInt(t1 / 16);
var int2 = t0 % 16;
t0 = parseInt(t0 / 16);
var int1 = t0 % 16;
t0 = parseInt(t0 / 16);
return "%" + intToHex(int1) + intToHex(int2) + "%" + intToHex(int3) + intToHex(int4)
+ "%" + intToHex(int5) + intToHex(int6) + "%" + intToHex(int7) + intToHex(int8);
}
//Verify an unsigned byte computes back to the correct integer (for debugging)
//function validate(w,x,y,z) {
// var w = w * 16 * 16 * 16;
// var x = x * 16 * 16;
// var y = y * 16;
// return w + x + y + z; }
// A function that draws the waveform onto an HTML5 canvas (Needs to be updated)
//function drawWave() {
// brush.beginPath();
// brush.lineWidth = '1';
// var lineLength = lpcm16.length;
// var delta = lineLength / canWidth;
// brush.moveTo(0, canHeight + lpcm16[0]);
// for (x = 0; x < canWidth; x++) {
// var dx = parseInt(x * delta);
// var drawX = x;
// var drawY = parseInt((lpcm16[dx] / bitDepth) * canHeight) + canHeight;
// brush.lineTo(drawX, drawY);
// //alert(x + ':' + dx + ': (' + drawX + ', ' + drawY + ')');
// }
// brush.stroke();
//}
</script>
</footer>
</body>
</html> |
package types
import "encoding/json"
type JSONSchema struct {
Property
ID string `json:"$id,omitempty"`
Title string `json:"title,omitempty"`
Properties map[string]Property `json:"properties"`
Required []string `json:"required,omitempty"`
Defs map[string]JSONSchema `json:"defs,omitempty"`
AdditionalProperties bool `json:"additionalProperties,omitempty"`
}
func ObjectSchema(kv ...string) *JSONSchema {
s := &JSONSchema{
Property: Property{
Type: "object",
},
Properties: map[string]Property{},
}
for i, v := range kv {
if i%2 == 1 {
s.Properties[kv[i-1]] = Property{
Description: v,
Type: "string",
}
}
}
return s
}
type Property struct {
Description string `json:"description,omitempty"`
Type string `json:"type,omitempty"`
Ref string `json:"$ref,omitempty"`
Items []JSONSchema `json:"items,omitempty"`
}
type Type []string
func (t *Type) UnmarshalJSON(data []byte) error {
switch data[0] {
case '[':
return json.Unmarshal(data, (*[]string)(t))
case 'n':
return json.Unmarshal(data, (*[]string)(t))
default:
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
*t = []string{s}
}
return nil
}
func (t *Type) MarshalJSON() ([]byte, error) {
switch len(*t) {
case 0:
return json.Marshal(nil)
case 1:
return json.Marshal((*t)[0])
default:
return json.Marshal(*t)
}
} |
_English | [中文](./README.zh.md)_
---
# Overview
Agora Chat UIKit for React-Native is a development kit with an user interface that enables an easy and fast integration of standard chat features into new or existing client apps. Agora Chat CallKit for React-Native is a development kit with an user interface that enables an easy and fast integration of RTC video/audio calling into new or existing client app.
The general structure of the repository is as follows:
.
├── UIKit SDK
├── CallKit SDK
├── UIKit Demo
└── CallKit Demo
- `example`: This is a demo example of a relatively complete UIKit. Including user login, logout, session management, contact management, group management, chat management, basic settings, etc.
- `examples/callkit-example`: This is a demonstration example of audio and video calls. Including single-person and multi-person audio and video call functions.
- `packages/react-native-chat-UIKit`: UIKit SDK project
- `packages/react-native-chat-callkit`: CallKit SDK project
## Requirements
- operating system:
- MacOS 10.15.7 or above
- Tools collection:
- Xcode 13.4 or above (if developing iOS platform reference)
- Android studio 2021.3.1 or above (if developing Android platform applications) (as for short)
- Visual Studio Code latest (vscode for short)
- Compile and run environment:
- Java JDK 1.8.0 or above (it is recommended to use Android studio's own)
- Objective-C 2.0 or above (recommended to use Xcode comes with it)
- Typescript 4.0 or above
- Nodejs 16.18.0 or above (brew installation is recommended)
- yarn 1.22.19 or above (brew installation is recommended)
- React-Native 0.63.5 or above
- npm and related tools (**not recommended**, please solve related problems by yourself)
- expo 6.0.0 or above
⚑ More details, please see https://reactnative.dev/docs/environment-setup
⚑ we strongly recommend installing yarn using corepack
## Try the example app
**Download repository [from here](https://github.com/AgoraIO-Usecase/AgoraChat-rn).**
**Project initialization.**
```sh
yarn && yarn run example-env && yarn run sdk-version
```
**Configure the necessary parameters.**
In the `example` project, add `appKey` and other information to the `example/src/env.ts`. In the `examples/callkit-example` project, add `appKey` and other information to the `examples/callkit-example/src/env.ts` file.
**Configure FCM file.**
In the `example` project, for the Android platform, please put `google-services.json` under the `examples/android/app` folder, and for the iOS platform, please put `GoogleService-Info.plist` under the `example/iOS/ChatUikitExample` folder.
In the `examples/callkit-example` project, for the Android platform, please put `google-services.json` under the `examples/callkit-example/android/app` folder, for the iOS platform, please put `GoogleService-Info.plist` under the `examples/callkit-example/iOS/ChatCallkitExample` folder.
**Compile and Run example app.**
```sh
cd example && yarn run Android
# or
cd example && yarn run pods && yarn run iOS
```
## Development Note
We tried development on macOS systems. You might encounter problems in running sample or scripts like yarn build in Windows machines.
More detailed development help can be found here.
[detail development helper](./docs/dev.md)
## UIKit Detail
Find out more about Agora Chat UIKit for React-Native please see the link below. If you need any help in resolving any issues or have questions, [visit our community](https://github.com/AgoraIO-Usecase/AgoraChat-rn).
- [UIKit detail](./packages/react-native-chat-uikit/README.md)
- [UIKit example detail](./example/README.md)
If you want to experience the fastest and easiest integration, please take a look at this project.
- [Quick Start for UIKit](https://github.com/AgoraIO-Usecase/AgoraChat-UIKit-rn)
## CallKit Detail
Find out more about Agora Chat Callkit for React-Native please see the link below. If you need any help in resolving any issues or have questions, [visit our community](https://github.com/AgoraIO-Usecase/AgoraChat-rn).
- [callkit detail](./packages/react-native-chat-callkit/README.md)
- [callkit example detail](./examples/callkit-example/README.md)
If you want to experience the fastest and easiest integration, please take a look at this project.
- [Quick Start for CallKit](https://github.com/AgoraIO-Usecase/AgoraChat-Callkit-rn)
---
# Q & A
If you have more questions, please check here, and if you have more suggestions, please contribute here.
[skip to here](./QA.md)
---
# mind Mapping
The description of this dimension may increase your understanding of the project.
[skip to here](./swdt.md) |
package com.api.book.bootrestbook.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.api.book.bootrestbook.entities.Book;
import com.api.book.bootrestbook.services.BookService;
@RestController
public class BookController {
@Autowired
private BookService bookService;
// get all BOoks
@GetMapping("/books")
public ResponseEntity<List<Book>> getBooks() {
List<Book> list = bookService.getAllBooks();
if (list.size() <= 0) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
return ResponseEntity.status(HttpStatus.CREATED).body(list);
}
// get single Book by id handler
@GetMapping("/books/{id}")
public ResponseEntity<Book> getBook(@PathVariable("id") int id) {
Book book = bookService.getBookById(id);
if (book == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
return ResponseEntity.of(Optional.of(book));
}
// put new Book
@PostMapping("/books")
public ResponseEntity<Book> addBook(@RequestBody Book book) {
Book b = null;
try {
b = this.bookService.addBook(book);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
return ResponseEntity.of(Optional.of(b));
}
// delete existing Book handler
@DeleteMapping("/books/{bookId}")
public void deleteBook(@PathVariable("bookId") int bookId) {
try {
this.bookService.deleteBook(bookId);
} catch (Exception e) {
e.printStackTrace();
}
}
// Update book Handler
@PutMapping("/books/{bookId}")
public ResponseEntity<Book> updateBook(@RequestBody Book book, @PathVariable("bookId") int bookId) {
try {
this.bookService.updateBook(book, bookId);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
return ResponseEntity.ok().body(book);
}
} |
package arep.taller;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* The main function for the Java program, which sets up a server socket and handles incoming client requests.
*
* @throws IOException if an I/O error occurs
* @throws URISyntaxException if a string could not be parsed as a URI reference
*/
public class HttpServer {
private final NetworkWrapper networkWrapper;
public HttpServer(NetworkWrapper networkWrapper) {
this.networkWrapper = networkWrapper;
}
public static void main(String[] args) throws IOException, URISyntaxException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(35000);
} catch (IOException e) {
System.err.println("Could not listen on port: 35000.");
System.exit(1);
}
boolean running = true;
while (running) {
Socket clientSocket = null;
try {
System.out.println("Listo para recibir ...");
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
OutputStream outputStream = clientSocket.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
boolean firstLine = true;
String uriStr = "";
while (true) {
String inputLine = in.readLine();
if (inputLine == null || inputLine.isEmpty()) {
break;
}
if (firstLine) {
uriStr = inputLine.split(" ")[1];
firstLine = false;
}
System.out.println("Received: " + inputLine);
}
URI requestUri = new URI(uriStr);
try {
byte[] outputBytes = htttpResponse(requestUri);
outputStream.write(outputBytes);
} catch (Exception e) {
byte[] errorBytes = httpError();
outputStream.write(errorBytes);
}
outputStream.close();
in.close();
clientSocket.close();
}
serverSocket.close();
}
/**
* Generates an HTTP response based on the requested URI.
*
* @param requestedURI the URI that was requested
* @return the HTTP response as a byte array
*/
public static byte[] htttpResponse(URI requestedURI) throws IOException {
Path file = Paths.get("target/classes/public" + requestedURI.getPath());
if (Files.isRegularFile(file)) {
String mimeType = Files.probeContentType(file);
byte[] fileBytes = Files.readAllBytes(file);
ByteArrayOutputStream response = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(response);
dos.writeBytes("HTTP/1.1 200 OK\r\n");
dos.writeBytes("Content-Type: " + mimeType + "\r\n");
dos.writeBytes("Content-Length: " + fileBytes.length + "\r\n");
dos.writeBytes("\r\n");
dos.write(fileBytes, 0, fileBytes.length);
return response.toByteArray();
} else {
return httpError();
}
}
/**
* Generates an HTTP error response with status code 404 Not Found
*
* @return the HTTP error response as a byte array
*/
private static byte[] httpError() {
String errorResponse = "HTTP/1.1 404 Not Found\r\n" +
"Content-Type: text/html\r\n" +
"\r\n" +
"<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <title>Error Not found</title>\n" +
" <meta charset=\"UTF-8\">\n" +
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
" </head>\n" +
" <body>\n" +
" <h1>Error</h1>\n" +
" </body>\n" +
"</html>";
return errorResponse.getBytes(StandardCharsets.UTF_8);
}
/**
* Extracts the movie title from the given URI.
*
* @param uri the URI containing the movie title
* @return the extracted movie title, or null if it cannot be extracted
*/
public static String extractMovieTitleFromUri(String uri) {
String[] params = uri.split("\\?");
if (params.length == 2) {
String[] keyValue = params[1].split("=");
if (keyValue.length == 2 && keyValue[0].equals("title")) {
return keyValue[1];
}
}
return "";
}
} |
import {AppDispatch, dispatchType} from "./redux-store";
import {authAPI} from "../api/api";
import {stopSubmit} from "redux-form";
export type AuthPageType = {
userId: number | null,
email: string | null,
login: string | null,
isAuth: boolean
}
type SetUserDataAcType = {
type: 'SET_USER_DATA',
payload: {
userId: number | null,
email: string | null,
login: string | null,
isAuth: boolean
}
}
export type AuthActionCreatorType = SetUserDataAcType
let InitialState = {
userId: 0,
email: '',
login: '',
isAuth: false
}
export const authReducer = (state: AuthPageType = InitialState, action: AuthActionCreatorType): AuthPageType => {
switch (action.type) {
case "SET_USER_DATA": {
return {...state, ...action.payload, isAuth: action.payload.isAuth}
}
default: {
return state
}
}
}
export const SetAuthUserDataAC = (userId: number | null, email: string | null, login: string | null, isAuth: boolean): SetUserDataAcType => {
return {
type: 'SET_USER_DATA' as const,
payload: {
userId,
login,
email,
isAuth
}
}
}
export const getAuthUserData = () => (dispatch: dispatchType) => {
return authAPI.me().then(response => {
if (response.data.resultCode === 0) {
dispatch(SetAuthUserDataAC(response.data.data.id, response.data.data.email, response.data.data.login, true))
}
})
}
export const login = (email: string, password: string, rememberMe: boolean) => (dispatch: AppDispatch) => {
authAPI.login(email, password, rememberMe).then(res => {
if (res.data.resultCode === 0) {
dispatch(getAuthUserData())
}
else {
dispatch(stopSubmit('login', {_error: res.data.messages.length > 0 ? res.data.messages[0] : 'Wrong email or password'}))
}
})
}
export const logout = () => (dispatch: AppDispatch) => {
authAPI.logout().then(res => {
if (res.data.resultCode === 0) {
dispatch(SetAuthUserDataAC(null, null, null, false))
}
})
}
export default authReducer |
import fs from "fs";
import { v4 as uuid } from "uuid";
const DB_FILE_PATH = "./core/db";
type UUID = string;
interface Todo {
id: UUID;
date: string;
content: string;
done: boolean;
}
/**
* Cria uma nova todo com o conteúdo fornecido e a adiciona ao banco de dados.
* @param {string} content - O conteúdo da nova todo.
* @returns {Todo} A todo recém-criada.
*/
export function create(content: string): Todo {
const todo: Todo = {
id: uuid(),
date: new Date().toISOString(),
content: content,
done: false,
};
const todos: Array<Todo> = [...read(), todo];
fs.writeFileSync(
DB_FILE_PATH,
JSON.stringify(
{
todos,
dogs: [],
},
null,
2
)
);
return todo;
}
/**
* Lê as todos do banco de dados e retorna um array de objetos Todo.
* @returns {Array<Todo>} Um array contendo as todos armazenadas no banco de dados.
*/
export function read(): Array<Todo> {
const dbString = fs.readFileSync(DB_FILE_PATH, "utf-8");
const db = JSON.parse(dbString || "{}");
if (!db.todos) {
return [];
}
return db.todos;
}
/**
* Atualiza uma todo existente com base no ID fornecido e nas informações parciais fornecidas.
* @param {UUID} id - O ID da todo a ser atualizada.
* @param {Partial<Todo>} partialTodo - As informações parciais a serem atualizadas na todo.
* @returns {Todo} A todo atualizada.
*/
export function update(id: UUID, partialTodo: Partial<Todo>): Todo {
let updatedTodo;
const todos = read();
todos.forEach((currentTodo) => {
const isToUpdate = currentTodo.id === id;
if (isToUpdate) {
updatedTodo = Object.assign(currentTodo, partialTodo);
}
});
fs.writeFileSync(
DB_FILE_PATH,
JSON.stringify(
{
todos,
},
null,
2
)
);
if (!updatedTodo) {
throw new Error("Please, provide another ID!");
}
return updatedTodo;
}
/**
* Atualiza o conteúdo de uma todo com base no ID fornecido.
* @param {UUID} id - O ID da todo a ser atualizada.
* @param {string} content - O novo conteúdo da todo.
* @returns {Todo} A todo com o conteúdo atualizado.
*/
export function updateContentById(id: UUID, content: string): Todo {
return update(id, {
content,
});
}
/**
* Exclui uma todo com base no ID fornecido.
* @param {UUID} id - O ID da todo a ser excluída.
*/
export function dbDeleteById(id: UUID) {
const todos = read();
const todosWithoutOne = todos.filter((todo) => {
if (id === todo.id) {
return false;
}
return true;
});
fs.writeFileSync(
DB_FILE_PATH,
JSON.stringify(
{
todos: todosWithoutOne,
},
null,
2
)
);
}
/**
* Limpa completamente o banco de dados, apagando todo o seu conteúdo.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function CLEAR_DB() {
fs.writeFileSync(DB_FILE_PATH, "");
} |
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="assets/dmt errand.png">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<title>DMT Errand</title>
<style>
section{
padding: 60px 0;
}
.text-orange{
color: #FF914D;
}
.card{
height: 80vh;
}
.card-footer:hover{
background-color: #FF914D;
color: #fff;
}
.accordion-button:not(.collapsed){
background-color: #FF914D;
color: #fff;
}
::-webkit-scrollbar-track {
background-color: white;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
background-color: #FF914D;
}
body{
overflow-x: hidden;
}
</style>
</head>
<body class="bg-dark">
<!-- navbar -->
<nav class="navbar navbar-expand-md navbar-light">
<div class="container-xxl">
<a href="#intro" class="navbar-brand px-2">
<span class="fw-bold text-white">
DMT
</span>
<span class="fw-bold text-orange">
Errand
</span>
</a>
<!-- Toogle button for mobile nav -->
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main-nav" aria-controls="main-nav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse justify-content-end align-center" id="main-nav">
<ul class="navbar-nav">
<li class="nav-item">
<a href="#topics" class="nav-link text-light">About DMT Errand</a>
</li>
<li class="nav-item">
<a href="#reviews" class="nav-link text-light">Reviews</a>
</li>
<li class="nav-item">
<a href="#contact" class="nav-link text-light">Get in Touch</a>
</li>
<li class="nav-item d-md-none">
<a href="#pricing" class="nav-link text-light">Pricing</a>
</li>
<li class="nav-item ms-2 d-none d-md-inline">
<a href="#pricing" class="btn" style="background-color: #FF914D; color: #fff;" >Avail Now</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- main image & intro text -->
<section id="intro">
<div class="container-lg">
<div class="row justify-content-center align-items-center">
<div class="col-md-5 text-center text md-start">
<h1>
<div class="display-7 text-white">Your Personal Assistant for Everyday Tasks</div>
</h1>
<p class="lead my-4 text-light">Let us take care of your everyday tasks so that you can focus on the things that matter most.
</p>
<a href="#pricing" class="btn btn-secondary btn-lg" style="background-color: #FF914D; color: #fff;">Avail Now</a>
</div>
<div class="col-md-5 text-center d-none d-md-block">
<span class="tt" data-bs-placement="bottom" title="DMT Errand Logo">
<img src="assets/dmt errand.png" alt="DMT Errand" class="img-fluid">
</span>
</div>
</div>
</div>
</section>
<!-- pricing plans -->
<section id="pricing" class="mt-5">
<div class="container-lg">
<div class="text-center text-white">
<h2><i class="bi bi-cash text-orange"></i> Pricing Plans</h2>
<p class="lead text-light">Services</p>
</div>
<div class="row my-3 align-items-center justify-content-center g-3">
<div class="col-8 col-lg-4">
<div class="card border-0 bg-light">
<div class="card-body text-center bg-light py-4">
<h4 class="card-title mb-3">Errand Services</h4>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Grocery Shopping</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Show, game, and movie tickets</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Merchandise purchases, returns and exchanges</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Prescription drop off/pick-up</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Post office services</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Balloon/Flower delivery</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Gift wrapping and delivery</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Bank services</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Food pick up and delivery</p>
</div>
<a href="#" class="card-footer btn btn-outline-orange btn-lg text-orange">
Learn More
</a>
</div>
</div>
<div class="col-8 col-lg-4">
<div class="card border-0">
<div class="card-body text-center bg-light py-4">
<h4 class="card-title mb-3">Business Services</h4>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Bill payment</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Document delivery</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Purchase & delivery of office supplies</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Purchase & delivery of food, beverages and office supplies</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Corporate gifts delivery & distribution</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Bulk mailings</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Package delivery</p>
</div>
<a href="#" class="card-footer btn btn-outline-orange btn-lg text-orange">
Learn More
</a>
</div>
</div>
<div class="col-8 col-lg-4">
<div class="card border-0">
<div class="card-body text-center bg-light py-4">
<h4 class="card-title mb-3">Waiting Services</h4>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>DMV</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Utilities</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Repair person appointments</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Restaurants</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Movies</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Concerts</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>Clubs</p>
<p class="card-text mx-5 my-2 text-orange text-start"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill mx-1" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>New products release</p>
</div>
<a href="#" class="card-footer btn btn-outline-orange btn-lg text-orange">
Learn More
</a>
</div>
</div>
</div>
</div>
</section>
<!-- topics at a glance -->
<section id="topics">
<div class="container-md">
<div class="text-center text-white">
<h2><i class="bi bi-question-lg text-orange"></i> Frequently Answered Questions (FAQ)</h2>
</div>
<div class="row my-3 g-5 justify-content-around align-items-center">
<div class="col-6 col-lg-4 d-none d-md-block">
<img id="imgFAQ" src="assets/FAQ.svg" alt="FAQ" class="img-fluid mx-auto">
</div>
<div class="col-lg-6">
<!-- accordion -->
<div class="accordion" id="accordions">
<div class="accordion-item">
<h2 class="accordion-header" id="heading-1">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-1" aria-expanded="true" aria-controls="accordion-1">
What services do you offer?
</button>
</h2>
<div id="accordion-1" class="accordion-collapse collapse show" aria-labelledby="heading-1" data-bs-parent="#accordions">
<div class="accordion-body">
<p>We offer a variety of errand services such as grocery shopping, food pick up and delivery, bill payment, package delivery, repair person appointments, and more.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-2">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-2" aria-expanded="true" aria-controls="accordion-2">
How do I place an order?
</button>
</h2>
<div id="accordion-2" class="accordion-collapse collapse" aria-labelledby="heading-2" data-bs-parent="#accordions">
<div class="accordion-body">
<p>You can place an order on our website or by calling us directly.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-3">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-3" aria-expanded="true" aria-controls="accordion-3">
What is the cost of your services?
</button>
</h2>
<div id="accordion-3" class="accordion-collapse collapse" aria-labelledby="heading-3" data-bs-parent="#accordions">
<div class="accordion-body">
<p>Our prices vary depending on the service requested. You can find the prices for each service on our website.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-4">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-4" aria-expanded="true" aria-controls="accordion-4">
What forms of payment do you accept?
</button>
</h2>
<div id="accordion-4" class="accordion-collapse collapse" aria-labelledby="heading-4" data-bs-parent="#accordions">
<div class="accordion-body">
<p>We accept most major credit cards and also offer other forms of payment such as PayPal or Gcash.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-5">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-5" aria-expanded="true" aria-controls="accordion-5">
How do I know my order has been received?
</button>
</h2>
<div id="accordion-5" class="accordion-collapse collapse" aria-labelledby="heading-5" data-bs-parent="#accordions">
<div class="accordion-body">
<p>You will receive an email confirmation once your order has been received.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-6">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-6" aria-expanded="true" aria-controls="accordion-6">
What are your service hours?
</button>
</h2>
<div id="accordion-6" class="accordion-collapse collapse" aria-labelledby="heading-6" data-bs-parent="#accordions">
<div class="accordion-body">
<p>Our service hours vary depending on the day and service requested. You can find our service hours on our website.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-7">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-7" aria-expanded="true" aria-controls="accordion-7">
What is your service area?
</button>
</h2>
<div id="accordion-7" class="accordion-collapse collapse" aria-labelledby="heading-7" data-bs-parent="#accordions">
<div class="accordion-body">
<p>Our service area includes specific neighborhoods and cities. You can find our service area on our website.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-8">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-8" aria-expanded="true" aria-controls="accordion-8">
How do I cancel or reschedule an appointment?
</button>
</h2>
<div id="accordion-8" class="accordion-collapse collapse" aria-labelledby="heading-8" data-bs-parent="#accordions">
<div class="accordion-body">
<p>You can cancel or reschedule an appointment by contacting us directly via phone or email.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-9">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-9" aria-expanded="true" aria-controls="accordion-9">
What is your refund policy?
</button>
</h2>
<div id="accordion-9" class="accordion-collapse collapse" aria-labelledby="heading-9" data-bs-parent="#accordions">
<div class="accordion-body">
<p>Our refund policy varies depending on the service requested. You can find our refund policy on our website.</p>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="heading-10">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion-10" aria-expanded="true" aria-controls="accordion-10">
Can I provide specific instructions for my order?
</button>
</h2>
<div id="accordion-10" class="accordion-collapse collapse" aria-labelledby="heading-10" data-bs-parent="#accordions">
<div class="accordion-body">
<p>Yes, you can provide specific instructions for your order either online or by contacting us directly.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- reviews list -->
<section id="reviews" class="bg-dark text-white">
<div class="container-lg">
<div class="text-center">
<h2><i class="bi bi-stars text-orange"></i> What Our Clients Say About Us</h2>
<p class="lead">See why our clients trust us to handle their errands.</p>
</div>
<div class="row justify-content-center my-5">
<div class="col-lg-8">
<div class="list-group">
<div class="list-group-item py-3">
<div class="pb-2">
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
</div>
<h5 class="mb-1">Excellent service and timely delivery</h5>
<p class="mb-1">I used this errand service for the first time and was extremely impressed with the level of service provided. The delivery was on time and the person who handled my errand was very polite and professional. I highly recommend this service to anyone looking for a reliable errand service.</p>
<small>Sarah T.</small>
</div>
<div class="list-group-item py-3">
<div class="pb-2">
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-half text-orange"></i>
</div>
<h5 class="mb-1">Great communication and service</h5>
<p class="mb-1">The errand service I used was great at communicating with me throughout the process. They kept me updated on the status of my errand and were very responsive to any questions I had. The service itself was good, but there was a slight delay in the delivery. Overall, I would recommend this service for its communication and reliability.</p>
<small>Sarah T.</small>
</div>
<div class="list-group-item py-3">
<div class="pb-2">
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
<i class="bi bi-star-fill text-orange"></i>
</div>
<h5 class="mb-1">Lifesaver during a busy week</h5>
<p class="mb-1">I used this errand service during a very busy week and it was a lifesaver. The person who handled my errand was very efficient and took care of everything I needed, from grocery shopping to picking up my dry cleaning. It saved me a lot of time and stress, and I would definitely use this service again.</p>
<small>David S.</small>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Contact Form -->
<section id="contact">
<div class="container-lg">
<div class="text-center text-white">
<h2><i class="bi bi-headset text-orange"></i> Get in Touch</h2>
<p class="lead">Have a task you need help with? Get in touch with us!</p>
</div>
<div class="row justify-content-center my-5">
<div class="col-lg-6">
<form>
<label for="name" class="form-label text-white">Name:</label>
<div class="input-group mb-4">
<span class="input-group-text">
<i class="bi bi-person-circle"></i>
</span>
<input type="text" class="form-control" id="name" placeholder="e.g. John Doe">
<span class="input-group-text">
<span class="tt" data-bs-placement="bottom" title="Enter your name.">
<i class="bi bi-question-circle text-muted"></i>
</span>
</span>
</div>
<label for="emailAddress" class="form-label text-white">Email Address:</label>
<div class="input-group mb-4">
<span class="input-group-text">
<i class="bi bi-envelope-fill"></i>
</span>
<input type="email" class="form-control" id="emailAddress" placeholder="e.g. [email protected]">
<span class="input-group-text">
<span class="tt" data-bs-placement="bottom" title="Enter an email address we can reply to.">
<i class="bi bi-question-circle text-muted"></i>
</span>
</span>
</div>
<label for="phoneNumber" class="form-label text-white">Phone Number:</label>
<div class="input-group mb-4">
<span class="input-group-text">
<i class="bi bi-telephone-fill"></i>
</span>
<input type="number" class="form-control" id="phoneNumber" placeholder="e.g. 09123456789">
<span class="input-group-text">
<span class="tt" data-bs-placement="bottom" title="Enter a phone number we can contact.">
<i class="bi bi-question-circle text-muted"></i>
</span>
</span>
</div>
<label for="typeOfErrand" class="form-label text-white">Type of Errand:</label>
<div class="input-group mb-4">
<span class="input-group-text">
<i class="bi bi-file-ruled-fill"></i>
</span>
<select id="typeOfErrand" class="form-select">
<option value="grocery shopping" selected>Grocery shopping</option>
<option value="prescription pick-up">Prescription pick-up</option>
<option value="dry cleaning">Dry cleaning</option>
<option value="meal delivery">Meal delivery</option>
<option value="pet care">Pet care</option>
<option value="house cleaning">House cleaning</option>
<option value="home repairs">Home repairs</option>
<option value="gift delivery">Gift delivery</option>
<option value="event planning">Event planning</option>
<option value="transportation services">Transportation services</option>
<option value="yard work">Yard work</option>
<option value="childcare">Childcare</option>
<option value="elderly care">Elderly care</option>
<option value="personal shopping">Personal shopping</option>
<option value="errand running">Errand running</option>
<option value="office assistance">Office assistance</option>
<option value="technology support">Technology support</option>
<option value="personal assistant services">Personal assistant services</option>
</select>
</div>
<label for="location" class="form-label text-white">Location:</label>
<div class="input-group mb-4">
<span class="input-group-text">
<i class="bi bi-geo-alt-fill"></i>
</span>
<input type="text" class="form-control" id="location" placeholder="e.g. 123 Main St, Anytown, Philippines">
<span class="input-group-text">
<span class="tt" data-bs-placement="bottom" title="Enter your location to know if our service is avaible at your location.">
<i class="bi bi-question-circle text-muted"></i>
</span>
</span>
</div>
<div class="form-floating mb-4 mt-5 ">
<textarea id="message" class="form-control" style="height: 140px;"></textarea>
<label for="message">Your message...</label>
</div>
<div class="mb-4 text-center">
<button class="btn" style="background-color: #FF914D; color: #fff;">Submit</button>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- get updates / modal trigger -->
<section class="bg-dark">
<div class="contain">
<div class="text-center text-white">
<h2><i class="bi bi-arrow-clockwise text-orange"></i> Stay in the Loop</h2>
<p class="lead">Get the latest updates as they happen.</p>
</div>
<div class="row justify-content-center">
<div class="col-md-8 text-center">
<p class="my-4 text-white">
At DMT Errand, we understand how busy life can get. That's why we created a platform that connects people who need help running errands with local, trusted helpers. Our platform is easy to use, and you can quickly find someone to help you with anything from grocery shopping to pet care. Sign up for our updates to stay in the loop on new features and special promotions.
</p>
<button class="btn" style="background-color: #FF914D; color: #fff;" data-bs-toggle="modal" data-bs-target="#reg-modal">
Register for Updates
</button>
</div>
</div>
</div>
</section>
<!-- modal itself -->
<div class="modal fade" id="reg-modal" tabindex="-1" aria-labelledby="modal-title" aria-hidden="true">
<div class="modal-dialog ">
<div class="modal-content bg-dark">
<div class="modal-header text-white">
<h5 class="modal-title" id="modal-title">Get the Latest Updates</h5>
<button class="btn-close" type="button" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body text-white">
<p>Thanks for your interest in DMT Errand updates. We'll keep you informed about new features, promotions, and other important news related to our platform.</p>
<label for="modal-email" class="form-label">Your email address: </label>
<input type="email" class="form-control" id="modal-email" placeholder="e.g. [email protected]">
</div>
<div class="modal-footer">
<button class="btn" style="background-color: #FF914D; color: #fff;">Submit</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<script>
const tooltips = document.querySelectorAll(".tt");
tooltips.forEach(t => {
new bootstrap.Tooltip(t);
});
</script>
</body>
</html> |
import { useEffect } from "react";
import { fetchAllProductForHomeAsync, selectAllProduct } from "../vendor/AddProductSlice";
import { useDispatch, useSelector } from "react-redux";
import { selectLoggedInUser } from "../auth/AuthSlice";
import { addToCartAsync } from "../cart/CartSlice";
import { Link } from "react-router-dom";
import { CustomerNavbar } from "../navbar/CustomerNavbar";
import'../style/customer/home.css'
export default function Decoration() {
const dispatch = useDispatch();
const products = useSelector(selectAllProduct);
const user = useSelector(selectLoggedInUser);
const productsByCategory = products.filter(product => product.itemType === 'music')
useEffect(() => {
if(user ){
dispatch(fetchAllProductForHomeAsync())
}
}, [dispatch]);
function handleAddToCart(e, _id) {
dispatch(addToCartAsync({ product: _id }))
.catch((error) => {
console.error("Error adding to cart:", error);
});
}
return (
<div className="container-fluid home-whole ">
<div className="row">
<CustomerNavbar />
</div>
<div className="row justify-content-center pt-4 text-center category-heading">
<div className="col-md-8">
<h1>Explore Music Options for Your Event</h1>
</div>
</div>
<div className="row px-5 py-5">
<div className="row justify-content-center">
<div className="col-md-3 text-center bg-warning py-2 "><Link to='/User/venue' className="text-decoration-none text-dark">Venue</Link></div>
<div className="col-md-1"></div>
<div className="col-md-3 text-center bg-success py-2 "><Link to='/User/catering' className="text-decoration-none text-dark">Catering</Link></div>
<div className="col-md-1"></div>
<div className="col-md-3 text-center bg-primary py-2 "><Link to='/User/decoration' className="text-decoration-none text-dark">Decoration</Link></div>
</div>
<div className="row pt-4 justify-content-center">
<div className="col-md-4 text-center bg-danger py-2"><Link to='/User/music' className="text-decoration-none text-dark">Music</Link></div>
</div>
</div>
<div className="row py-5">
{products && products.length > 0 ? (
<div >
<div className="container py-1 mb-3">
<div className="row row-cols-1 row-cols-md-4 g-4">
{productsByCategory.map((product) => (
<div className="col " key={product._id}>
<div id="card1" className="card h-100 ">
<img src={product.itemImage} className="card-img-top" id="cardimgtop1" alt="image" />
<div className="card-body row text-center" id="cardbody1">
<div className="col-md-5">
<h5 id="cardtitle1" className="card-title ">{product.itemName}</h5>
</div>
<div className="col-md-2"></div>
<div className="col-md-5">
<span><h4 id="cardprice1"><i className="fa-solid fa-indian-rupee-sign"></i>{product.itemPrice}</h4></span>
</div>
</div>
<div className="mb-4 d-flex justify-content-around ">
<button className="btn btn-primary " id="addcartbtn1" onClick={(e) => handleAddToCart(e, product._id)}>Add To Cart</button>
</div>
</div>
</div>
))}
</div>
</div>
</div>
) : (
<p>No Product Found</p>
)}
</div>
</div>
);
} |
<?php
/*
* Your installation or use of this SugarCRM file is subject to the applicable
* terms available at
* http://support.sugarcrm.com/Resources/Master_Subscription_Agreements/.
* If you do not agree to all of the applicable terms or do not have the
* authority to bind the entity as an authorized representative, then do not
* install or use this SugarCRM file.
*
* Copyright (C) SugarCRM Inc. All rights reserved.
*/
namespace Sugarcrm\SugarcrmTestsUnit\IdentityProvider\Authentication\ServiceAccount;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Sugarcrm\Sugarcrm\IdentityProvider\Authentication\ServiceAccount\ServiceAccount;
use Sugarcrm\Sugarcrm\IdentityProvider\Authentication\User;
/**
* @coversDefaultClass \Sugarcrm\Sugarcrm\IdentityProvider\Authentication\ServiceAccount\ServiceAccount
*/
class ServiceAccountTest extends TestCase
{
/**
* @var ServiceAccount|MockObject
*/
protected $serviceAccount;
/**
* @var \User|MockObject
*/
protected $userBean;
/**
* @var \User|MockObject
*/
protected $systemUser;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->serviceAccount = $this->getMockBuilder(ServiceAccount::class)
->setMethods(['getUserBean'])
->getMock();
$this->userBean = $this->createMock(\User::class);
$this->serviceAccount->method('getUserBean')->willReturn($this->userBean);
$this->systemUser = $this->createMock(\User::class);
$this->systemUser->id = 'systemId';
}
/**
* @covers ::isServiceAccount
*/
public function testIsServiceAccount(): void
{
$this->assertTrue($this->serviceAccount->isServiceAccount());
}
/**
* @covers ::getSugarUser
*/
public function testGetSugarUserSystemUser(): void
{
$this->serviceAccount->setDataSourceSRN('');
$this->userBean->expects($this->once())->method('getSystemUser')->willReturn($this->systemUser);
$sugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('systemId', $sugarUser->id);
$repeatedSugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('systemId', $repeatedSugarUser->id);
}
/**
* @covers ::getSugarUser
*/
public function testGetSugarUserDataSourceUserWrongSRN(): void
{
$this->serviceAccount->setDataSourceSRN('wrong-srn');
$this->userBean->expects($this->once())->method('getSystemUser')->willReturn($this->systemUser);
$sugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('systemId', $sugarUser->id);
}
/**
* @covers ::getSugarUser
*/
public function testGetSugarUserDataSourceEmptyResourceType(): void
{
$this->serviceAccount->setDataSourceSRN('srn:dev:iam:na:1225636081::');
$this->userBean->expects($this->once())->method('getSystemUser')->willReturn($this->systemUser);
$sugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('systemId', $sugarUser->id);
}
/**
* @covers ::getSugarUser
*/
public function testGetSugarUserDataSourceResourceTypeIsNotUser(): void
{
$this->serviceAccount->setDataSourceSRN('srn:dev:iam:na:1225636081:sa:');
$this->userBean->expects($this->once())->method('getSystemUser')->willReturn($this->systemUser);
$sugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('systemId', $sugarUser->id);
}
/**
* @covers ::getSugarUser
*/
public function testGetSugarUserDataSourceEmptyUserId(): void
{
$this->serviceAccount->setDataSourceSRN('srn:dev:iam:na:1225636081:user:');
$this->userBean->expects($this->once())->method('getSystemUser')->willReturn($this->systemUser);
$sugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('systemId', $sugarUser->id);
}
/**
* @covers ::getSugarUser
*/
public function testGetSugarUserDataSourceUserDoesNotExist(): void
{
$this->userBean->id = null;
$this->serviceAccount->setDataSourceSRN('srn:dev:iam:na:1225636081:user:12345');
$this->userBean->expects($this->once())->method('retrieve')->with('12345', true, false);
$this->userBean->expects($this->once())->method('getSystemUser')->willReturn($this->systemUser);
$sugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('systemId', $sugarUser->id);
}
/**
* @covers ::getSugarUser
*/
public function testGetSugarUserDataSourceUserIsNotDeveloperForAnyModule(): void
{
$this->userBean->id = '12345';
$this->serviceAccount->setDataSourceSRN('srn:dev:iam:na:1225636081:user:12345');
$this->userBean->expects($this->once())->method('retrieve')->with('12345', true, false);
$this->userBean->expects($this->once())->method('isDeveloperForAnyModule')->willReturn(false);
$this->userBean->expects($this->once())->method('getSystemUser')->willReturn($this->systemUser);
$sugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('systemId', $sugarUser->id);
}
/**
* @covers ::getSugarUser
*/
public function testGetSugarUserDataSourceUser(): void
{
$this->userBean->id = '12345';
$this->serviceAccount->setDataSourceSRN('srn:dev:iam:na:1225636081:user:12345');
$this->userBean->expects($this->once())->method('retrieve')->with('12345', true, false);
$this->userBean->expects($this->once())->method('isDeveloperForAnyModule')->willReturn(true);
$this->userBean->expects($this->never())->method('getSystemUser');
$sugarUser = $this->serviceAccount->getSugarUser();
$this->assertEquals('12345', $sugarUser->id);
}
/**
* @covers ::setDataSourceSRN
* @covers ::getDataSourceSRN
*/
public function testDataSourceSRN(): void
{
$srn = 'srn:dev:iam:na:1225636081:user:12345';
$this->serviceAccount->setDataSourceSRN($srn);
$this->assertEquals($srn, $this->serviceAccount->getDataSourceSRN());
}
/**
* @covers ::setDataSourceName
* @covers ::getDataSourceName
*/
public function testDataSourceName(): void
{
$name = 'data source name';
$this->serviceAccount->setDataSourceName($name);
$this->assertEquals($name, $this->serviceAccount->getDataSourceName());
}
} |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
class F2(object):
def __init__(self, lmbda: float):
super(F2, self).__init__()
self.lmbda = lmbda
def penalty(self, x, factors): #TODO: remove x
norm, raw = 0, 0
for f in factors:
raw += torch.sum(f ** 2)
norm += self.lmbda * torch.sum(f ** 2)
return norm / factors[0].shape[0], raw / factors[0].shape[0], self.lmbda
def checkpoint(self, regularizer_cache_path, epoch_id):
if regularizer_cache_path is not None:
print('Save the regularizer at epoch {}'.format(epoch_id))
path = regularizer_cache_path + '{}.reg'.format(epoch_id)
torch.save(self.state_dict(), path)
print('Regularizer Checkpoint:{}'.format(path))
class N3(object):
def __init__(self, lmbda: float):
super(N3, self).__init__()
self.lmbda = lmbda
def penalty(self, x, factors):
"""
:param factors: tuple, (s, p, o), batch_size * rank
:return:
"""
norm, raw = 0, 0
for f in factors:
raw += torch.sum(
torch.abs(f) ** 3
)
norm += self.lmbda * torch.sum(
torch.abs(f) ** 3
)
return norm / factors[0].shape[0], raw / factors[0].shape[0], self.lmbda
def checkpoint(self, regularizer_cache_path, epoch_id):
if regularizer_cache_path is not None:
print('Save the regularizer at epoch {}'.format(epoch_id))
path = regularizer_cache_path + '{}.reg'.format(epoch_id)
torch.save(self.state_dict(), path)
print('Regularizer Checkpoint:{}'.format(path))
class DURA_UniBi_2(object):
def __init__(self, lmbda: float):
super(DURA_UniBi_2, self).__init__()
self.lmbda = lmbda
def givens_rotations(self, r, x, transpose=False):
"""Givens rotations.
Args:
r: torch.Tensor of shape (N x d), rotation parameters
x: torch.Tensor of shape (N x d), points to rotate
transpose: whether to transpose the rotation matrix
Returns:
torch.Tensor os shape (N x d) representing rotation of x by r
"""
givens = r.view((r.shape[0], -1, 2))
givens = givens / torch.norm(givens, p=2, dim=-1, keepdim=True).clamp_min(1e-15)
x = x.view((r.shape[0], -1, 2))
if transpose:
x_rot = givens[:, :, 0:1] * x - givens[:, :, 1:] * torch.cat((-x[:, :, 1:], x[:, :, 0:1]), dim=-1)
else:
x_rot = givens[:, :, 0:1] * x + givens[:, :, 1:] * torch.cat((-x[:, :, 1:], x[:, :, 0:1]), dim=-1)
return x_rot.view((r.shape[0], -1))
def penalty(self, x, factors):
norm, raw = 0, 0
h, Rot_u, Rot_v, rel, t = factors
uh = self.givens_rotations(Rot_u, h)
suh = rel * uh
vt = self.givens_rotations(Rot_v, t, transpose=True)
svt = rel * vt
norm += torch.sum(suh ** 2 + svt ** 2 + h ** 2 + t ** 2)
return self.lmbda * norm / h.shape[0], norm / h.shape[0], self.lmbda
def checkpoint(self, regularizer_cache_path, epoch_id):
if regularizer_cache_path is not None:
print('Save the regularizer at epoch {}'.format(epoch_id))
path = regularizer_cache_path + '{}.reg'.format(epoch_id)
torch.save(self.state_dict(), path)
print('Regularizer Checkpoint:{}'.format(path))
class DURA_UniBi_3(object):
def __init__(self, lmbda: float):
super(DURA_UniBi_3, self).__init__()
self.lmbda = lmbda
def quaternion_rotation(self, rotation, x, right = False, transpose = False):
"""rotate a batch of quaterions with by orthogonal rotation matrices
Args:
rotation (torch.Tensor): parameters that used to rotate other vectors [batch_size, rank]
x (torch.Tensor): vectors that need to be rotated [batch_size, rank]
right (bool): whether to rotate left or right
transpose (bool): whether to transpose the rotation matrix
Returns:
rotated_vectors(torch.Tensor): rotated_results [batch_size, rank]
"""
# ! it seems like calculate in this way will slow down the speed
# turn to quaterion
rotation = rotation.view(rotation.shape[0], -1, 4)
rotation = rotation / torch.norm(rotation, dim=-1, keepdim=True).clamp_min(1e-15) # unify each quaterion of the rotation part
p, q, r, s = rotation[:, :, 0], rotation[:, :, 1], rotation[:, :, 2], rotation[:, :, 3]
if transpose:
q, r, s = -q, -r ,-s # the transpose of this quaterion rotation matrix can be achieved by negating the q, r, s
s_a, x_a, y_a, z_a = x.chunk(dim=1, chunks=4)
if right:
# right rotation
# the original version used in QuatE is actually the right rotation
rotated_s = s_a * p - x_a * q - y_a * r - z_a * s
rotated_x = s_a * q + p * x_a + y_a * s - r * z_a
rotated_y = s_a * r + p * y_a + z_a * q - s * x_a
rotated_z = s_a * s + p * z_a + x_a * r - q * y_a
else:
# left rotation
rotated_s = s_a * p - x_a * q - y_a * r - z_a * s
rotated_x = s_a * q + x_a * p - y_a * s + z_a * r
rotated_y = s_a * r + x_a * s + y_a * p - z_a * q
rotated_z = s_a * s - x_a * r + y_a * q + z_a * p
rotated_vectors = torch.cat([rotated_s, rotated_x, rotated_y, rotated_z], dim=-1)
return rotated_vectors
def penalty(self, x, factors):
norm, raw = 0, 0
h, Rot_u, Rot_v, rel, t = factors
uh = self.quaternion_rotation(Rot_u, h)
suh = rel * uh
vt = self.quaternion_rotation(Rot_v, t, transpose=True)
svt = rel * vt
norm += torch.sum(suh ** 2 + svt ** 2 + h ** 2 + t ** 2)
return self.lmbda * norm / h.shape[0], norm / h.shape[0], self.lmbda
def checkpoint(self, regularizer_cache_path, epoch_id):
if regularizer_cache_path is not None:
print('Save the regularizer at epoch {}'.format(epoch_id))
path = regularizer_cache_path + '{}.reg'.format(epoch_id)
torch.save(self.state_dict(), path)
print('Regularizer Checkpoint:{}'.format(path)) |
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" version = "1.0" >
<xsl:template match="/">
<xsl:text>
</xsl:text>
<html>
<body>
<h2>Drig Dávid Kurzusfelvétel – 2023/24. I. félév.</h2>
<table border = "4">
<tr bgcolor = "#90EE90">
<th>ID</th>
<th>Tipus</th>
<th>Targy</th>
<th colspan="2">Idopont</th>
<th>Helyszin</th>
<th>Oktato</th>
<th>Szak</th>
</tr>
<xsl:for-each select="/EZ3YRC_kurzusfelvetel/kurzusok/kurzus">
<tr>
<td><xsl:value-of select = "@id"/></td>
<td><xsl:value-of select = "@tipus"/></td>
<td><xsl:value-of select = "targy"/></td>
<td><xsl:value-of select = "idopont/nap"/></td>
<td><xsl:value-of select = "idopont/tol"/>h - <xsl:value-of select = "idopont/ig"/>h</td>
<td><xsl:value-of select = "helyszin"/></td>
<td><xsl:value-of select = "oktato"/></td>
<td><xsl:value-of select = "szak"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
<xsl:output method="xml" encoding="utf-8" indent="yes"></xsl:output>
</xsl:stylesheet> |
---
title: Authorization with Identity--Part 2
description: Use Delamater and Murach (2022) as a guide to finish adding authorization to a web app: Restrict the admin controller. Add Admin to our navigation menu, but only for admin users. Seed users and an admin role. Re-publish to Azure
keywords: Identity, Authorization, UserManager, Authorize attribute
---
<h1>Authorization with Identity Part 2</h1>
| Weekly topics | |
| ------------------------------- | ----------------------------- |
| 1. Intro to Identity | 6. Complex domain models |
| 2. Authentication | 7. More complex domain models |
| <mark>3. Authorization</mark> | 8. Validation |
| 4. Async/Await | 9. Web Security |
| 5. Load testing and performance | 10. Term project |
| 11. Project Presentations | |
[TOC]
## Introduction
- Q and A
## Review - Last Class' Demo (2024)
We added this code:
- An `[Authorize]` attribute to the controller method for posting a message.
Note that if a user isn't authenticated, they will be redirected to *login*.
- Do you know how the framework knows where to redirect the user to log in?
- How does the return URL get sent to the login controller method?
- The `UserController`, some supporting code and two views:
- `Index` for managing users and roles
- `Add` for adding new users
This is redundant to our register view! We should refacotr this.
## Overview of Today's Demo
We will use Delamater and Murach (2022) as a guide to finish adding authorization to our web app.
- Seed a user and an admin role.
- Restrict the admin controller.
- Add Admin to our navigation menu, but only for admin users.
- Re-publish to Azure.
## Restricting Access
We will use the following C# attributes to restrict access classes or methods:
- `[Authorize]`
- Limits access to logged in users.
- If a user tries to access a method that requires authorization, they will automatically be redirected to Account/Login[^1].
- `[Authorize(Roles = "Admin")]`
- Limits access to users in the Admin role.
- If a user not in this role tries to access a method with this restriction, they will be automatically redirected to Account/AccessDenied[^2].
## Demo—Finishing the Authorization Code
1. Restrict access to authorized users
- Add the `[Authorize]` attribute to the `Review` methods (for posting a review) in the `ReviewController`.
- Add `[Authorize(Roles = "Admin")]` to the `AdminController`
2. Provide notification and redirection to unauthorized users
- Add an HTTP GET `AccessDenied()` action method to the `AcccountController`. This will notify unauthorized users that they either need to log in or don't have Admin priveleges.
- Add the `AccessDenied` view to the Views / Account folder
3. Seed an admin user
We will follow the approach used in the textbook and use the code from the section of ch. 16 titled "How to seed roles and users".
- Copy the `ConfigureIdentity` class (I renamed it to `SeedUsers` in my example code) which contains a static method named `CreateAdminUserAsync`. I put the file in the `Data` folder of my project.
- Add a call to the `CreateAdminUserAsync` method to `Program.cs`. It goes in the `using` statement at the bottom where we are already calling the `SeedData.Seed` method. Here's what the `using` statement looks like after adding the call to `CreateAdminUserAsync`:
```c#
using (var scope = app.Services.CreateScope())
{
await SeedUsers.CreateAdminUserAsync(scope.ServiceProvider);
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
SeedData.Seed(context, scope.ServiceProvider);
}
```
4. Add an *Admin* link to the navbar menu.
This code isn't in the textbook. Add the code below to the shared _Layout.cshtml file, inside the @if statement that checks to see if a user is logged in.
```c#
@if (User.IsInRole("Admin"))
{
<li class="nav-item">
<a class="nav-link" asp-controller="User" asp-action="Index">
<span class="fas fa-cog"></span> Admin</a>
</li>
}
```
## Conclusion
- Look at the lab instructions
- Reminder to publish to Azure
- Don't delete your migrations, add to them so your migration will run smoothly on the Azure database.
- Reminder to keep your unit tests working
- Reminder to keep checking your Azure credit balance!
- Review due dates on Moodle
## Examples
[BookReivews, Authorization branch](https://github.com/LCC-CIT/CS296N-Example-BookReviews-DotNet6/tree/04-Authorization)—2023 example using .NET 6.0 and MySQL
[BookReivews, Authorization branch](https://github.com/LCC-CIT/CS296N-Example-BookReviews/tree/4-Authorization)—2022 example using .NET 3.1 and SQL Server
## References
*Murach’s ASP.NET Core MVC*, Mary Delamater and Joel Murach, 2022
- Ch. 16, "How to Authenticate and Authorize Users"
- [Authorization in ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/)—Microsoft ASP.NET Core MVC Tutorial
- [Asp.net Core Redirect To Login Page With Return Url](https://vectorlinux.com/asp-net-core-redirect-to-login-page-with-return-url/), Vector Linux: tech help tutorials, 2023.
------
## Conclusion
- Review due dates on Moodle.
- There is reading, but no reading quiz for next week.
## Footnotes
[^1]: Account/Login is the default path that unauthorized (not logged in) users will be redirected to when they try to access an action method restricted with the [Authorize] attribute.
[^2]: Account/AccessDenied is the default path that unauthorized (not in the required role) users will be redirected to when they try to access an action method restricted with the [Authorize(Roles = "SomeRole")] attribute.
[^3]: The users I seeded before adding authentication don't have a password--but this isn't necessarily a problem. They work for the Reviews in the seed data.
------
[ ](http://creativecommons.org/licenses/by-sa/4.0/)
ASP.NET Core MVC Lecture Notes, written winter 2021, revised winter <time>2022</time>, by [Brian Bird](https://profbird.dev) are licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). |
import { renderHook, waitFor } from '@testing-library/react';
import { usePatientQuery } from './usePatientQuery';
jest.mock('node-fetch');
const fetch = require('node-fetch');
describe('usePatientQuery', () => {
beforeEach(() => {
fetch.mockClear();
});
it('should fetch patient data when id is provided', async () => {
fetch.mockResolvedValueOnce({
json: async () => ({
data: {
patient: {
patient_id: 1,
first_name: 'John',
last_name: 'Doe',
email: '[email protected]',
gender: 'Male',
age: 30,
avatar: 'avatar-url'
}
}
})
});
const { result } = renderHook(() =>
usePatientQuery({ id: 1 })
);
await waitFor(() => {
expect(result.current.patient).toEqual({
patient_id: 1,
first_name: 'John',
last_name: 'Doe',
email: '[email protected]',
gender: 'Male',
age: 30,
avatar: 'avatar-url'
});
});
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(null);
});
it('should handle an error response', async () => {
fetch.mockRejectedValueOnce(new Error('Network Error'));
const { result } = renderHook(() =>
usePatientQuery({ id: 2 })
);
await waitFor(() => {
expect(result.current.patient).toBe(undefined);
});
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeInstanceOf(Error);
});
}); |
// Copyright 2023 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use cstr::cstr;
use fuchsia_criterion::{criterion, FuchsiaCriterion};
use fuchsia_trace as trace;
use fuchsia_trace::Scope;
use std::time::Duration;
macro_rules! bench_trace_record_fn {
($bench:ident, $name:ident $(, $arg:expr)? $(, args: $key:expr => $val:expr)?) => {
let name = cstr!(stringify!($name));
$bench = $bench
.with_function(
concat!(stringify!($name), "/0Args"),
|b| {
b.iter(|| {trace::$name!(c"benchmark", name $(, $arg)? $(, $key => $val)?);});
}
)
.with_function(
concat!(stringify!($name), "/15Args"),
|b| {
b.iter(|| {trace::$name!(c"benchmark", name $(, $arg)?,
"a"=>1,
"b"=>2,
"c"=>3,
"d"=>4,
"e"=>5,
"f"=>6,
"g"=>7,
"h"=>8,
"i"=>9,
"j"=>10,
"k"=>11,
"l"=>12,
"m"=>13,
"n"=>14,
"o"=>15);});
}
);
};
}
macro_rules! bench_async_trace_record_fn {
($bench:ident, $name:ident) => {
let name = cstr!(stringify!($name));
$bench = $bench
.with_function(
concat!(stringify!($name), "/0Args"),
|b| {
b.iter(|| trace::$name!(fuchsia_trace::Id::new(), c"benchmark", name));
}
)
.with_function(
concat!(stringify!($name), "/15Args"),
|b| {
b.iter(|| trace::$name!(fuchsia_trace::Id::new(), c"benchmark", name,
"a"=>1,
"b"=>2,
"c"=>3,
"d"=>4,
"e"=>5,
"f"=>6,
"g"=>7,
"h"=>8,
"i"=>9,
"j"=>10,
"k"=>11,
"l"=>12,
"m"=>13,
"n"=>14,
"o"=>15));
}
);
};
}
fn main() {
fuchsia_trace_provider::trace_provider_create_with_fdio();
fuchsia_trace_provider::trace_provider_wait_for_init();
let mut c = FuchsiaCriterion::default();
let internal_c: &mut criterion::Criterion = &mut c;
*internal_c = std::mem::take(internal_c)
.warm_up_time(Duration::from_millis(1))
.measurement_time(Duration::from_millis(100))
.sample_size(10);
let mut bench = criterion::Benchmark::new("TraceEventRust/Empty", |b| {
b.iter(|| 1);
});
bench_trace_record_fn!(bench, instant, Scope::Process);
bench_trace_record_fn!(bench, counter, 0, args: "a" => 0);
bench_trace_record_fn!(bench, duration);
bench_trace_record_fn!(bench, duration_begin);
bench_trace_record_fn!(bench, duration_end);
bench_trace_record_fn!(bench, flow_begin, 1.into());
bench_trace_record_fn!(bench, flow_step, 1.into());
bench_trace_record_fn!(bench, flow_end, 1.into());
bench_trace_record_fn!(bench, blob, &[1, 2, 3, 4, 5, 6]);
bench_async_trace_record_fn!(bench, async_enter);
bench_async_trace_record_fn!(bench, async_instant);
c.bench("fuchsia.trace_records.rust", bench);
} |
<template>
<div class="card" style="width: 18rem; margin: auto">
<img
v-bind:src="srcUrl"
class="card-img-top"
width="70"
height="200"
alt="..."
/>
<div class="card-body">
<h5 class="card-title">{{ name }}</h5>
<p class="card-text">{{ food }}</p>
<button class="btn btn-primary" @click="handleClick">OK</button>
</div>
</div>
</template>
<script setup>
import { defineProps, defineEmits } from "vue";
const p = defineProps({
name: String,
food: {
type: String,
default: "떡볶이",
},
srcUrl: String,
teamNum: Number,
});
const emit = defineEmits(["card-disappear"]);
function handleClick() {
alert(`${p.teamNum}팀 입니다~~~!!`);
emit('card-disappear'); // 이벤트 발생
}
</script> |
import 'dart:math' as math;
import 'package:flutter/material.dart';
class TickerPro extends StatefulWidget {
const TickerPro({Key? key}) : super(key: key);
@override
State<TickerPro> createState() => _TickerProState();
}
class _TickerProState extends State<TickerPro> with TickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 10),
)..repeat();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
appBar: AppBar(
title: const Text('Ticker Pro'),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Transform.rotate(
angle: _controller.value * 2.0 * math.pi,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12.0),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 3,
blurRadius: 7,
offset: const Offset(0, 3),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(12.0),
child: Image.asset(
'assets/wallpaper.jpeg',
height: 150.0,
width: 150.0,
),
),
),
);
},
),
const SizedBox(height: 20.0),
const Text(
'Rotating Image',
style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
),
],
),
),
);
}
} |
import { ref } from 'vue'
import { defineStore } from 'pinia'
import idCreation from '@/helpers/idCreation'
import type { IContacts } from '@/models/ObjectModels'
import type { IClient } from '@/models/ClientModel'
export const useClientsStore = defineStore('client', () => {
const clientJson: string | null = localStorage.getItem('clients')
const searchValueStore = ref<string>('')
const clientsData = ref<IClient[]>([])
clientsData.value = clientJson !== null ? JSON.parse(clientJson) : []
function saveClients(): void {
localStorage.setItem('clients', JSON.stringify(clientsData.value))
}
function addClient(
firstName: string,
secondName: string,
thirdName: string,
contacts: IContacts[]
): void {
clientsData.value.push({
id: idCreation(clientsData.value),
firstName,
secondName,
thirdName,
fullName: `${secondName} ${firstName} ${thirdName}`,
date: {
newDate: new Date(),
nowDate: Date.now()
},
edit: {
newEdit: new Date(),
nowEdit: Date.now()
},
contacts
})
saveClients()
}
function initialContacts(id: number, contacts: IContacts[]) {
clientsData.value.forEach((client: IClient) => {
if (client.id === id && typeof contacts !== 'undefined') {
client.contacts = contacts
saveClients()
}
})
}
function changeClient(
id: number,
firstName: string,
secondName: string,
thirdName: string,
contacts: IContacts[]
): void {
clientsData.value.forEach((client: any) => {
if (client.id === id) {
client.firstName = firstName
client.secondName = secondName
client.thirdName = thirdName
client.fullName = `${secondName} ${firstName} ${thirdName}`
client.edit.newEdit = new Date()
client.edit.nowEdit = Date.now()
client.contacts = contacts
saveClients()
}
})
}
function deleteClient(id: number): void {
clientsData.value.forEach((client: IClient, i: number) => {
if (client.id === id) {
clientsData.value.splice(i, 1)
saveClients()
}
})
}
return {
clientsData,
searchValueStore,
saveClients,
addClient,
initialContacts,
changeClient,
deleteClient
}
}) |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import com.ctre.phoenix.sensors.PigeonIMU;
import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveDriveOdometry;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.math.kinematics.SwerveModuleState;
import edu.wpi.first.wpilibj.smartdashboard.Field2d;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import frc.robot.Constants.DriveConstants;
import frc.robot.Constants.SwerveConstants;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
public class DriveSubsystem extends SubsystemBase {
// Robot swerve modules
private final SwerveModuleOffboard m_frontLeft =
new SwerveModuleOffboard(
SwerveConstants.kFrontLeftDriveMotorPort,
SwerveConstants.kFrontLeftTurningMotorPort,
SwerveConstants.kFrontLeftMagEncoderPort,
SwerveConstants.kFrontLeftMagEncoderOffsetDegrees);
private final SwerveModuleOffboard m_rearLeft =
new SwerveModuleOffboard(
SwerveConstants.kRearLeftDriveMotorPort,
SwerveConstants.kRearLeftTurningMotorPort,
SwerveConstants.kRearLeftMagEncoderPort,
SwerveConstants.kRearLeftMagEncoderOffsetDegrees);
private final SwerveModuleOffboard m_frontRight =
new SwerveModuleOffboard(
SwerveConstants.kFrontRightDriveMotorPort,
SwerveConstants.kFrontRightTurningMotorPort,
SwerveConstants.kFrontRightMagEncoderPort,
SwerveConstants.kFrontRightMagEncoderOffsetDegrees);
private final SwerveModuleOffboard m_rearRight =
new SwerveModuleOffboard(
SwerveConstants.kRearRightDriveMotorPort,
SwerveConstants.kRearRightTurningMotorPort,
SwerveConstants.kRearRightMagEncoderPort,
SwerveConstants.kRearRightMagEncoderOffsetDegrees);
// The imu sensor
private final PigeonIMU m_imu = new PigeonIMU(SwerveConstants.kIMU_ID);
// Odometry class for tracking robot pose
SwerveDriveOdometry m_odometry =
new SwerveDriveOdometry(
DriveConstants.kDriveKinematics,
Rotation2d.fromDegrees(m_imu.getYaw()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
});
// Create Field2d for robot and trajectory visualizations.
private Field2d m_field;
/** Creates a new DriveSubsystem. */
public DriveSubsystem() {
// Create and push Field2d to SmartDashboard.
m_field = new Field2d();
SmartDashboard.putData(m_field);
}
@Override
public void periodic() {
// Update the odometry in the periodic block
m_odometry.update(
Rotation2d.fromDegrees(m_imu.getYaw()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
});
// Update robot position on Field2d.
m_field.setRobotPose(getPose());
// Diagnostics
SmartDashboard.putNumber("FL Mag Enc", m_frontLeft.getCanCoder());
SmartDashboard.putNumber("FR Mag Enc", m_frontRight.getCanCoder());
SmartDashboard.putNumber("RL Mag Enc", m_rearLeft.getCanCoder());
SmartDashboard.putNumber("RR Mag Enc", m_rearRight.getCanCoder());
SmartDashboard.putNumber("FL Drive Enc", m_frontLeft.getPosition().distanceMeters);
SmartDashboard.putNumber("FR Drive Enc", m_frontRight.getPosition().distanceMeters);
SmartDashboard.putNumber("RL Drive Enc", m_rearLeft.getPosition().distanceMeters);
SmartDashboard.putNumber("RR Drive Enc", m_rearRight.getPosition().distanceMeters);
SmartDashboard.putNumber("FL Turn Enc", m_frontLeft.getPosition().angle.getDegrees());
SmartDashboard.putNumber("FR Turn Enc", m_frontRight.getPosition().angle.getDegrees());
SmartDashboard.putNumber("RL Turn Enc", m_rearLeft.getPosition().angle.getDegrees());
SmartDashboard.putNumber("RR Turn Enc", m_rearRight.getPosition().angle.getDegrees());
}
/**
* Returns the currently-estimated pose of the robot.
*
* @return The pose.
*/
public Pose2d getPose() {
return m_odometry.getPoseMeters();
}
/**
* Resets the odometry to the specified pose.
*
* @param pose The pose to which to set the odometry.
*/
public void resetOdometry(Pose2d pose) {
m_odometry.resetPosition(
Rotation2d.fromDegrees(m_imu.getYaw()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
},
pose);
}
/**
* Method to drive the robot using joystick info.
*
* @param xSpeed Speed of the robot in the x direction (forward).
* @param ySpeed Speed of the robot in the y direction (sideways).
* @param rot Angular rate of the robot.
* @param fieldRelative Whether the provided x and y speeds are relative to the field.
*/
public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative) {
SmartDashboard.putNumber("xSpeed", xSpeed);
SmartDashboard.putNumber("ySpeed", ySpeed);
SmartDashboard.putNumber("rot", rot);
// Apply joystick deadband
xSpeed = MathUtil.applyDeadband(xSpeed, 0.1, 1.0);
ySpeed = MathUtil.applyDeadband(ySpeed, 0.1, 1.0);
rot = MathUtil.applyDeadband(rot, 0.1, 1.0);
var swerveModuleStates =
DriveConstants.kDriveKinematics.toSwerveModuleStates(
fieldRelative
? ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, rot, Rotation2d.fromDegrees(m_imu.getYaw()))
: new ChassisSpeeds(xSpeed, ySpeed, rot));
SwerveDriveKinematics.desaturateWheelSpeeds(
swerveModuleStates, DriveConstants.kMaxSpeedMetersPerSecond);
m_frontLeft.setDesiredState(swerveModuleStates[SwerveConstants.kSwerveFL_enum]);
m_frontRight.setDesiredState(swerveModuleStates[SwerveConstants.kSwerveFR_enum]);
m_rearLeft.setDesiredState(swerveModuleStates[SwerveConstants.kSwerveRL_enum]);
m_rearRight.setDesiredState(swerveModuleStates[SwerveConstants.kSwerveRR_enum]);
}
/**
* Sets the swerve ModuleStates.
*
* @param desiredStates The desired SwerveModule states.
*/
public void setModuleStates(SwerveModuleState[] desiredStates) {
SwerveDriveKinematics.desaturateWheelSpeeds(
desiredStates, DriveConstants.kMaxSpeedMetersPerSecond);
m_frontLeft.setDesiredState(desiredStates[SwerveConstants.kSwerveFL_enum]);
m_frontRight.setDesiredState(desiredStates[SwerveConstants.kSwerveFR_enum]);
m_rearLeft.setDesiredState(desiredStates[SwerveConstants.kSwerveRL_enum]);
m_rearRight.setDesiredState(desiredStates[SwerveConstants.kSwerveRR_enum]);
}
/** Resets the drive encoders to currently read a position of 0. */
public void resetEncoders() {
m_frontLeft.resetEncoders();
m_rearLeft.resetEncoders();
m_frontRight.resetEncoders();
m_rearRight.resetEncoders();
}
/** Zeroes the heading of the robot. */
public void zeroHeading() {
m_imu.setYaw(0);
}
/**
* Returns the heading of the robot.
*
* @return the robot's heading in degrees, from -180 to 180
*/
public double getHeading() {
return m_imu.getYaw();
}
} |
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012-Today Serpent Consulting Services PVT. LTD.
# (<http://www.serpentcs.com>)
#
# 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/>
#
# ---------------------------------------------------------------------------
from openerp.exceptions import except_orm, UserError, ValidationError
from openerp.tools import misc, DEFAULT_SERVER_DATETIME_FORMAT
from openerp import models, fields, api, _
from openerp import workflow
from decimal import Decimal
import datetime
import urllib2
import time
import openerp.addons.decimal_precision as dp
def _offset_format_timestamp1(src_tstamp_str, src_format, dst_format,
ignore_unparsable_time=True, context=None):
"""
Convert a source timeStamp string into a destination timeStamp string,
attempting to apply the
correct offset if both the server and local timeZone are recognized,or no
offset at all if they aren't or if tz_offset is false (i.e. assuming they
are both in the same TZ).
@param src_tstamp_str: the STR value containing the timeStamp.
@param src_format: the format to use when parsing the local timeStamp.
@param dst_format: the format to use when formatting the resulting
timeStamp.
@param server_to_client: specify timeZone offset direction (server=src
and client=dest if True, or client=src and
server=dest if False)
@param ignore_unparsable_time: if True, return False if src_tstamp_str
cannot be parsed using src_format or
formatted using dst_format.
@return: destination formatted timestamp, expressed in the destination
timezone if possible and if tz_offset is true, or src_tstamp_str
if timezone offset could not be determined.
"""
if not src_tstamp_str:
return False
res = src_tstamp_str
if src_format and dst_format:
try:
# dt_value needs to be a datetime.datetime object\
# (so notime.struct_time or mx.DateTime.DateTime here!)
dt_value = datetime.datetime.strptime(src_tstamp_str, src_format)
if context.get('tz', False):
try:
import pytz
src_tz = pytz.timezone(context['tz'])
dst_tz = pytz.timezone('UTC')
src_dt = src_tz.localize(dt_value, is_dst=True)
dt_value = src_dt.astimezone(dst_tz)
except Exception:
pass
res = dt_value.strftime(dst_format)
except Exception:
# Normal ways to end up here are if strptime or strftime failed
if not ignore_unparsable_time:
return False
pass
return res
class HotelFloor(models.Model):
_name = "hotel.floor"
_description = "Floor"
name = fields.Char('Floor Name', size=64, required=True, select=True)
sequence = fields.Integer('Sequence', size=64)
class ProductCategory(models.Model):
_inherit = "product.category"
isroomtype = fields.Boolean('Is Room Type')
isamenitytype = fields.Boolean('Is Amenities Type')
isservicetype = fields.Boolean('Is Service Type')
rtype_ids = fields.One2many('hotel.room.type', 'cat_id',
string='Room Type')
class HotelRoomType(models.Model):
_name = "hotel.room.type"
_description = "Room Type"
cat_id = fields.Many2one('product.category', 'category', required=True,
delegate=True, select=True, ondelete='cascade')
capacity = fields.Integer('PAX')
list_price = fields.Float('Precio', digits_compute=dp.get_precision('Product Price'))
class ProductProduct(models.Model):
_inherit = "product.product"
isroom = fields.Boolean('Is Room')
iscategid = fields.Boolean('Is categ id')
isservice = fields.Boolean('Is Service id')
class HotelRoomAmenitiesType(models.Model):
_name = 'hotel.room.amenities.type'
_description = 'amenities Type'
cat_id = fields.Many2one('product.category', 'category', required=True,
delegate=True, ondelete='cascade')
class HotelRoomAmenities(models.Model):
_name = 'hotel.room.amenities'
_description = 'Room amenities'
room_categ_id = fields.Many2one('product.product', 'Product Category',
required=True, delegate=True,
ondelete='cascade')
rcateg_id = fields.Many2one('hotel.room.amenities.type',
'Amenity Catagory')
class FolioRoomLine(models.Model):
_name = 'folio.room.line'
_description = 'Hotel Room Reservation'
_rec_name = 'room_id'
room_id = fields.Many2one(comodel_name='hotel.room', string='Room id')
check_in = fields.Datetime('Check In Date', required=True)
check_out = fields.Datetime('Check Out Date', required=True)
folio_id = fields.Many2one('hotel.folio', string='Folio Number')
status = fields.Selection(string='Estado de Factura', related='folio_id.state')
class HotelRoom(models.Model):
_name = 'hotel.room'
_description = 'Hotel Room'
_order = 'sequence'
@api.one
def _get_price(self):
room_type = self.env['hotel.room.type']
r_type_id = room_type.search([('cat_id','=',self.product_id.categ_id.id)])
self.price = r_type_id.list_price
product_id = fields.Many2one('product.product', 'Product_id',
required=True, delegate=True,
ondelete='cascade')
floor_id = fields.Many2one('hotel.floor', 'Floor No',
help='At which floor the room is located.')
max_adult = fields.Integer('Max Adult')
max_child = fields.Integer('Max Child')
room_amenities = fields.Many2many('hotel.room.amenities', 'temp_tab',
'room_amenities', 'rcateg_id',
string='Room Amenities',
help='List of room amenities. ')
status = fields.Selection([('available', 'Available'),
('occupied', 'Occupied')],
'Status', default='available')
capacity = fields.Integer('Capacity')
room_line_ids = fields.One2many('folio.room.line', 'room_id',
string='Room Reservation Line')
state = fields.Selection([('clean', 'Limpia'),
('dirty', 'Sucia'),
],
'Limpieza', default='clean')
# list_price = fields.Float(related='product_id.list_price', string="Precio", readonly=True)
price = fields.Float(string='Precio',
store=False, readonly=True, compute='_get_price')
sequence = fields.Integer('Sequence')
# @api.onchange('isroom')
# def isroom_change(self):
# '''
# Based on isroom, status will be updated.
# ----------------------------------------
# @param self: object pointer
# '''
# if self.isroom is False:
# self.status = 'occupied'
# if self.isroom is True:
# self.status = 'available'
# @api.multi
# def write(self, vals):
# """
# Overrides orm write method.
# @param self: The object pointer
# @param vals: dictionary of fields value.
# """
# if 'isroom' in vals and vals['isroom'] is False:
# vals.update({'color': 2, 'status': 'occupied'})
# if 'isroom'in vals and vals['isroom'] is True:
# vals.update({'color': 5, 'status': 'available'})
# ret_val = super(HotelRoom, self).write(vals)
# return ret_val
@api.multi
def set_room_status_occupied(self):
"""
This method is used to change the state
to occupied of the hotel room.
---------------------------------------
@param self: object pointer
"""
return self.write({'isroom': False, 'color': 2})
@api.multi
def set_room_status_available(self):
"""
This method is used to change the state
to available of the hotel room.
---------------------------------------
@param self: object pointer
"""
return self.write({'isroom': True, 'color': 5})
class HotelFolio(models.Model):
@api.depends('payment_lines.amount','room_lines.price_unit','room_lines.discount','room_lines.tax_id','room_lines.checkin_date','room_lines.checkout_date','amount_total')
def _amount_all(self):
"""
Compute the total amounts of the SO.
"""
for order in self:
amount_payment = residual = 0.0
for line in order.payment_lines:
amount_payment += line.amount
order.update({
'amount_payment': amount_payment,
'residual': order.amount_total - amount_payment,
})
@api.depends('folio_service_ids.product_id','folio_service_ids.quantity','folio_service_ids.list_price','folio_service_ids.cobrado')
def _amount_all_service(self):
"""
Compute the total amounts of the SO.
"""
for order in self:
service_total = service_paid = service_residual = 0.0
for line in order.folio_service_ids:
service_total += line.price_subtotal
if line.cobrado=='si':
service_paid += line.price_subtotal
order.update({
'service_total': service_total,
'service_paid': service_paid,
'service_residual': service_total - service_paid,
})
@api.multi
def action_view_folio(self):
invoice_ids = self
imd = self.env['ir.model.data']
action = imd.xmlid_to_object('hotel.open_hotel_folio1_form_tree_all')
list_view_id = imd.xmlid_to_res_id('hotel.view_hotel_folio1_tree')
form_view_id = imd.xmlid_to_res_id('hotel.view_hotel_folio1_form')
result = {
'name': action.name,
'help': action.help,
'type': action.type,
'views': [[list_view_id, 'tree'], [form_view_id, 'form'], [False, 'graph'], [False, 'kanban'], [False, 'calendar'], [False, 'pivot']],
'target': action.target,
'context': action.context,
'res_model': action.res_model,
}
if len(invoice_ids) > 1:
result['domain'] = "[('id','in',%s)]" % invoice_ids.ids
elif len(invoice_ids) == 1:
result['views'] = [(form_view_id, 'form')]
result['res_id'] = invoice_ids.ids[0]
else:
result = {'type': 'ir.actions.act_window_close'}
return result
@api.multi
def name_get(self):
res = []
disp = ''
for rec in self:
if rec.order_id:
disp = str(rec.name)
res.append((rec.id, disp))
return res
@api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
if args is None:
args = []
args += ([('name', operator, name)])
mids = self.search(args, limit=100)
return mids.name_get()
@api.model
def _needaction_count(self, domain=None):
"""
Show a count of draft state folio on the menu badge.
@param self: object pointer
"""
return self.search_count([('state', '=', 'draft')])
@api.model
def _get_checkin_date(self):
if self._context.get('tz'):
to_zone = self._context.get('tz')
else:
to_zone = 'UTC'
return _offset_format_timestamp1(time.strftime("%Y-%m-%d 12:00:00"),
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S',
ignore_unparsable_time=True,
context={'tz': to_zone})
@api.model
def _get_checkout_date(self):
if self._context.get('tz'):
to_zone = self._context.get('tz')
else:
to_zone = 'UTC'
tm_delta = datetime.timedelta(days=1)
return datetime.datetime.strptime(_offset_format_timestamp1
(time.strftime("%Y-%m-%d 10:00:00"),
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S',
ignore_unparsable_time=True,
context={'tz': to_zone}),
'%Y-%m-%d %H:%M:%S') + tm_delta
@api.multi
def copy(self, default=None):
'''
@param self: object pointer
@param default: dict of default values to be set
'''
return super(HotelFolio, self).copy(default=default)
@api.multi
def _invoiced(self, name, arg):
'''
@param self: object pointer
@param name: Names of fields.
@param arg: User defined arguments
'''
return self.env['sale.order']._invoiced(name, arg)
@api.multi
def _invoiced_search(self, obj, name, args):
'''
@param self: object pointer
@param name: Names of fields.
@param arg: User defined arguments
'''
return self.env['sale.order']._invoiced_search(obj, name, args)
@api.multi
def recibo(self):
datas = {
'ids': [],
'model': 'hotel.folio',
'form': self.id,
'context': {'active_id': self.id},
}
return {
'type': 'ir.actions.report.xml',
'report_name': 'recibo_x',
'datas': datas,
}
_name = 'hotel.folio'
_description = 'hotel folio new'
_rec_name = 'order_id'
_order = 'name desc'
_inherit = ['ir.needaction_mixin']
name = fields.Char('Folio Number', readonly=True, index=True,
default='Nuevo')
order_id = fields.Many2one('sale.order', 'Order', delegate=True,
required=True, ondelete='cascade')
checkin_date = fields.Datetime('Check In', required=True, readonly=True,
states={'draft': [('readonly', False)]},
default=_get_checkin_date)
checkout_date = fields.Datetime('Check Out', required=True, readonly=True,
states={'draft': [('readonly', False)]},
default=_get_checkout_date)
room_lines = fields.One2many('hotel.folio.line', 'folio_id',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)]},
help="Hotel room reservation detail.")
service_lines = fields.One2many('hotel.service.line', 'folio_id',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)],
'sale': [('readonly', False)]},
help="Hotel services detail provide to"
"customer and it will include in "
"main Invoice.")
payment_lines = fields.One2many('hotel.payment', 'folio_id','Linea de Pagos')
folio_service_ids = fields.One2many('hotel.folio.service', 'folio_id',)
hotel_policy = fields.Selection([('prepaid', 'On Booking'),
('manual', 'On Check In'),
('picking', 'On Checkout')],
'Hotel Policy', default='manual',
help="Hotel policy for payment that "
"either the guest has to payment at "
"booking time or check-in "
"check-out time.")
duration = fields.Float('Duration in Days', readonly=True,
states={'draft': [('readonly', False)]},
help="Number of days which will automatically "
"count from the check-in and check-out date. ")
currrency_ids = fields.One2many('currency.exchange', 'folio_no',
readonly=True)
hotel_invoice_id = fields.Many2one('account.invoice', 'Invoice')
identification_id = fields.Char(related='partner_id.main_id_number', string="Núm. Documento", required=True)
type_doc = fields.Many2one('res.partner.id_category', 'Tipo Documento' , related='partner_id.main_id_category_id', required=True)
adress_partner = fields.Char(related='partner_id.street', string='Dirección', required=False)
city_partner = fields.Char(related='partner_id.city', string='Ciudad', required=False)
state_partner = fields.Many2one('res.country.state', 'Provincia' , related='partner_id.state_id', required=True)
country_partner = fields.Many2one('res.country', 'País' , related='partner_id.country_id', required=True)
phone_partner = fields.Char(related='partner_id.phone', string='Teléfono')
email_partner = fields.Char(related='partner_id.email', string='Email')
observations = fields.Text('Observaciones')
amount_payment = fields.Monetary(string='Monto pagado', store=True, readonly=True, compute='_amount_all', track_visibility='always')
residual = fields.Monetary(string='Importe adeudado', store=True, readonly=True, compute='_amount_all', track_visibility='always')
service_total = fields.Monetary(string='Total', store=True, readonly=True, compute='_amount_all_service', track_visibility='always')
service_paid = fields.Monetary(string='Monto Cobrado', store=True, readonly=True, compute='_amount_all_service', track_visibility='always')
service_residual = fields.Monetary(string='Monto a Cobrar', store=True, readonly=True, compute='_amount_all_service', track_visibility='always')
@api.multi
def go_to_currency_exchange(self):
'''
when Money Exchange button is clicked then this method is called.
-------------------------------------------------------------------
@param self: object pointer
'''
cr, uid, context = self.env.args
context = dict(context)
for rec in self:
if rec.partner_id.id and len(rec.room_lines) != 0:
context.update({'folioid': rec.id, 'guest': rec.partner_id.id,
'room_no': rec.room_lines[0].product_id.name,
'hotel': rec.warehouse_id.id})
self.env.args = cr, uid, misc.frozendict(context)
else:
raise except_orm(_('Warning'), _('Please Reserve Any Room.'))
return {'name': _('Currency Exchange'),
'res_model': 'currency.exchange',
'type': 'ir.actions.act_window',
'view_id': False,
'view_mode': 'form,tree',
'view_type': 'form',
'context': {'default_folio_no': context.get('folioid'),
'default_hotel_id': context.get('hotel'),
'default_guest_name': context.get('guest'),
'default_room_number': context.get('room_no')
},
}
@api.constrains('room_lines')
def folio_room_lines(self):
'''
This method is used to validate the room_lines.
------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation
'''
folio_rooms = []
for room in self[0].room_lines:
if room.product_id.id in folio_rooms:
raise ValidationError(_('You Cannot Take Same Room Twice'))
folio_rooms.append(room.product_id.id)
@api.constrains('checkin_date', 'checkout_date')
def check_dates(self):
'''
This method is used to validate the checkin_date and checkout_date.
-------------------------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation
'''
if self.checkin_date >= self.checkout_date:
raise ValidationError(_('Check in Date Should be \
less than the Check Out Date!'))
# if self.date_order and self.checkin_date:
# if self.checkin_date < self.date_order:
# raise ValidationError(_('Check in date should be \
# greater than the current date.'))
@api.onchange('checkout_date', 'checkin_date')
def onchange_dates(self):
'''
This mathod gives the duration between check in and checkout
if customer will leave only for some hour it would be considers
as a whole day.If customer will check in checkout for more or equal
hours, which configured in company as additional hours than it would
be consider as full days
--------------------------------------------------------------------
@param self: object pointer
@return: Duration and checkout_date
'''
# import pdb;pdb.set_trace()
company_obj = self.env['res.company']
configured_addition_hours = 0
company_ids = company_obj.search([])
if company_ids.ids:
configured_addition_hours = company_ids[0].additional_hours
myduration = 0
chckin = self.checkin_date
chckout = self.checkout_date
if chckin and chckout:
server_dt = DEFAULT_SERVER_DATETIME_FORMAT
chkin_dt = datetime.datetime.strptime(chckin, server_dt)
chkout_dt = datetime.datetime.strptime(chckout, server_dt)
dur = chkout_dt - chkin_dt
sec_dur = dur.seconds
additional_hours = abs((dur.seconds / 60) / 60)
if additional_hours <= 12:
myduration = dur.days
else:
myduration = dur.days + 1
if configured_addition_hours > 0:
additional_hours = abs((dur.seconds / 60) / 60)
if additional_hours >= configured_addition_hours:
myduration += 1
for line in self.room_lines:
line.checkin_date = chckin
line.checkout_date = chckout
line.on_change_checkout()
self.duration = myduration
def update_partner(self, vals, partner):
partner_obj = self.env['res.partner']
partner = partner_obj.browse(partner)
if 'phone_partner' in vals:
partner.write({'phone': vals['phone_partner']})
if 'email_partner' in vals:
partner.write({'email': vals['email_partner']})
if 'city_partner' in vals:
partner.write({'city': vals['city_partner']})
if 'adress_partner' in vals:
partner.write({'street': vals['adress_partner']})
if 'state_partner' in vals:
partner.write({'state_id': vals['state_partner']})
if 'country_partner' in vals:
partner.write({'country_id': vals['country_partner']})
if 'type_doc' in vals:
partner.write({'main_id_category_id': vals['type_doc']})
if 'identification_id' in vals:
partner.write({'main_id_number': vals['identification_id']})
@api.multi
def check_reservation_exists(self):
for folio in self:
self._cr.execute("""select hr.reservation_no
from hotel_reservation as hr
inner join hotel_reservation_line as hrl on hrl.line_id = hr.id
inner join hotel_reservation_line_room_rel as hrlrr on hrlrr.room_id = hrl.id
where (checkin,checkout) overlaps
( timestamp %s, timestamp %s )
and hr.partner_id <> cast(%s as integer)
and hr.state = 'confirm'
and hrlrr.hotel_reservation_line_id in (
select id from hotel_room where product_id in (select product_id
from hotel_folio as hf
inner join hotel_folio_line hfl on (hf.id=hfl.folio_id)
join sale_order_line sol on (hfl.order_line_id=sol.id)
where hf.id = cast(%s as integer) ) )""",
(folio.checkin_date, folio.checkout_date,
str(folio.partner_id.id), str(folio.id)))
res = self._cr.fetchone()
# print self._cr.query
roomcount = res and res[0] or 0.0
# print roomcount
if roomcount:
raise ValidationError(_('Ha tratado de crear/modificar un folio con habitaciones que ya están reservadas en este periodo de reserva. %s'%res))
return True
@api.multi
def check_folio_exists(self):
for folio in self:
self._cr.execute("""select hf.name
from hotel_folio as hf
inner join sale_order so on (hf.order_id=so.id)
inner join hotel_folio_line hfl on (hf.id=hfl.folio_id)
join sale_order_line sol on (hfl.order_line_id=sol.id)
inner join folio_room_line frl on (frl.folio_id=hf.id)
join hotel_room hr on (frl.room_id=hr.id)
where (check_in,check_out) overlaps
( timestamp %s, timestamp %s )
and hf.id <> cast(%s as integer)
and so.state not in ('cancel','done')
and hr.product_id=sol.product_id
and sol.product_id in (select product_id
from hotel_folio as hf
inner join hotel_folio_line hfl on (hf.id=hfl.folio_id)
join sale_order_line sol on (hfl.order_line_id=sol.id)
where hf.id = cast(%s as integer) )
""",
(folio.checkin_date, folio.checkout_date,
str(folio.id), str(folio.id)))
res = self._cr.fetchone()
# print self._cr.query
roomcount = res and res[0] or 0.0
if roomcount:
raise ValidationError(_('Ha tratado de crear/modificar un folio con una habitacion que ya ha sido registrada en este período. %s'%res))
return True
@api.model
def create(self, vals, check=True):
"""
Overrides orm create method.
@param self: The object pointer
@param vals: dictionary of fields value.
@return: new record set for hotel folio.
"""
self.update_partner(vals,vals['partner_id'])
if not 'service_lines' and 'folio_id' in vals:
tmp_room_lines = vals.get('room_lines', [])
vals['order_policy'] = vals.get('hotel_policy', 'manual')
vals.update({'room_lines': []})
folio_id = super(HotelFolio, self).create(vals)
for line in (tmp_room_lines):
line[2].update({'folio_id': folio_id})
vals.update({'room_lines': tmp_room_lines})
folio_id.write(vals)
else:
if not vals:
vals = {}
vals['name'] = self.env['ir.sequence'].next_by_code('hotel.folio')
folio_id = super(HotelFolio, self).create(vals)
folio_room_line_obj = self.env['folio.room.line']
h_room_obj = self.env['hotel.room']
try:
for rec in folio_id:
for room_rec in rec.room_lines:
prod = room_rec.product_id.name
room_obj = h_room_obj.search([('name', '=',
prod)])
room_obj.write({'isroom': False, 'status': 'occupied'})
vals = {'room_id': room_obj.id,
'check_in': rec.checkin_date,
'check_out': rec.checkout_date,
'folio_id': rec.id,
}
folio_room_line_obj.create(vals)
except:
for rec in folio_id:
for room_rec in rec.room_lines:
prod = room_rec.product_id.name
room_obj = h_room_obj.search([('name', '=', prod)])
room_obj.write({'isroom': False, 'status': 'occupied'})
vals = {'room_id': room_obj.id,
'check_in': rec.checkin_date,
'check_out': rec.checkout_date,
'folio_id': rec.id,
}
folio_room_line_obj.create(vals)
folio_id.check_reservation_exists()
folio_id.check_folio_exists()
return folio_id
@api.multi
def write(self, vals):
"""
Overrides orm write method.
@param self: The object pointer
@param vals: dictionary of fields value.
"""
folio_room_line_obj = self.env['folio.room.line']
# reservation_line_obj = self.env['hotel.room.reservation.line']
product_obj = self.env['product.product']
h_room_obj = self.env['hotel.room']
room_lst1 = []
for rec in self:
for res in rec.room_lines:
room_lst1.append(res.product_id.id)
folio_write = super(HotelFolio, self).write(vals)
if 'state' in vals.keys() and vals['state'] not in ('done'):
self.check_reservation_exists()
self.check_folio_exists()
if 'checkout_date' in vals.keys() and self.state!='done':
self.check_reservation_exists()
self.check_folio_exists()
self.update_partner(vals,self.partner_id.id)
room_lst = []
for folio_obj in self:
for folio_rec in folio_obj.room_lines:
room_lst.append(folio_rec.product_id.id)
new_rooms = set(room_lst).difference(set(room_lst1))
if len(list(new_rooms)) != 0:
room_list = product_obj.browse(list(new_rooms))
for rm in room_list:
room_obj = h_room_obj.search([('name', '=', rm.name)])
room_obj.write({'isroom': False, 'status': 'occupied'})
vals = {'room_id': room_obj.id,
'check_in': folio_obj.checkin_date,
'check_out': folio_obj.checkout_date,
'folio_id': folio_obj.id,
}
folio_room_line_obj.create(vals)
if len(list(new_rooms)) == 0:
room_list_obj = product_obj.browse(room_lst1)
for rom in room_list_obj:
room_obj = h_room_obj.search([('name', '=', rom.name)])
room_obj.write({'isroom': False, 'status': 'occupied'})
room_vals = {'room_id': room_obj.id,
'check_in': folio_obj.checkin_date,
'check_out': folio_obj.checkout_date,
'folio_id': folio_obj.id,
}
folio_romline_rec = (folio_room_line_obj.search
([('folio_id', '=', folio_obj.id),('room_id','=',room_obj.id)]))
folio_romline_rec.write(room_vals)
for folio_obj in self:
## elimino los registros viejos
for room in room_lst1:
if room not in room_lst:
room_obj = h_room_obj.search([('product_id', '=', room)])
unlink_ids = folio_room_line_obj.search([('folio_id','=',folio_obj.id),('room_id','=',room_obj.id)])
unlink_ids.unlink()
room_obj.write({'isroom': True, 'status': 'available'})
# if folio_obj.reservation_id:
# for reservation in folio_obj.reservation_id:
# reservation_obj = (reservation_line_obj.search
# ([('reservation_id', '=',
# reservation.id)]))
# if len(reservation_obj) == 1:
# for line_id in reservation.reservation_line:
# line_id = line_id.reserve
# for room_id in line_id:
# vals = {'room_id': room_id.id,
# 'check_in': folio_obj.checkin_date,
# 'check_out': folio_obj.checkout_date,
# 'state': 'assigned',
# 'reservation_id': reservation.id,
# }
# reservation_obj.write(vals)
return folio_write
@api.onchange('warehouse_id')
def onchange_warehouse_id(self):
'''
When you change warehouse it will update the warehouse of
the hotel folio as well
----------------------------------------------------------
@param self: object pointer
'''
return self.order_id._onchange_warehouse_id()
@api.onchange('partner_id')
def onchange_partner_id(self):
'''
When you change partner_id it will update the partner_invoice_id,
partner_shipping_id and pricelist_id of the hotel folio as well
---------------------------------------------------------------
@param self: object pointer
'''
if self.partner_id:
partner_rec = self.env['res.partner'].browse(self.partner_id.id)
order_ids = [folio.order_id.id for folio in self]
if not order_ids:
self.partner_invoice_id = partner_rec.id
self.partner_shipping_id = partner_rec.id
self.pricelist_id = partner_rec.property_product_pricelist.id
raise UserError(_('Not Any Order \
For %s ' % (partner_rec.name)))
else:
self.partner_invoice_id = partner_rec.id
self.partner_shipping_id = partner_rec.id
self.pricelist_id = partner_rec.property_product_pricelist.id
@api.multi
def button_dummy(self):
'''
@param self: object pointer
'''
for folio in self:
folio.order_id.button_dummy()
return True
@api.multi
def action_done(self):
now = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
if now[0:10] != self.checkout_date[0:10]:
raise ValidationError(_('No se puede realizar un checkout en una fecha diferente a la fecha de salida del folio.'))
self.write({'state': 'done', 'checkout_date': now})
for line in self.room_lines:
room_obj = self.env['hotel.room']
room_id = room_obj.search([('name','=',line.product_id.name)])
room = room_obj.browse(room_id.id)
room.state='dirty'
@api.multi
def action_back_to_checkin(self):
self.write({'state': 'sale'})
@api.multi
def action_invoice_create(self, grouped=False, states=None):
'''
@param self: object pointer
'''
if states is None:
states = ['confirmed', 'done']
order_ids = [folio.order_id.id for folio in self]
room_lst = []
sale_obj = self.env['sale.order'].browse(order_ids)
invoice_id = (sale_obj.action_invoice_create
(grouped=False, states=['confirmed', 'done']))
for line in self:
values = {'invoiced': True,
'state': 'progress' if grouped else 'progress',
'hotel_invoice_id': invoice_id
}
line.write(values)
# for rec in line.room_lines:
# room_lst.append(rec.product_id)
# for room in room_lst:
# room_obj = self.env['hotel.room'
# ].search([('name', '=', room.name)])
# room_obj.write({'isroom': True, 'status': 'available'})
return invoice_id
@api.multi
def action_invoice_cancel(self):
'''
@param self: object pointer
'''
order_ids = [folio.order_id.id for folio in self]
sale_obj = self.env['sale.order'].browse(order_ids)
res = sale_obj.action_invoice_cancel()
for sale in self:
for line in sale.order_line:
line.write({'invoiced': 'invoiced'})
sale.write({'state': 'invoice_except'})
return res
@api.multi
def action_cancel(self):
'''
@param self: object pointer
'''
order_ids = [folio.order_id.id for folio in self]
sale_obj = self.env['sale.order'].browse(order_ids)
rv = sale_obj.action_cancel()
for sale in self:
for pick in sale.picking_ids:
workflow.trg_validate(self._uid, 'stock.picking', pick.id,
'button_cancel', self._cr)
for invoice in sale.invoice_ids:
workflow.trg_validate(self._uid, 'account.invoice',
invoice.id, 'invoice_cancel',
self._cr)
sale.write({'state': 'cancel'})
return rv
@api.multi
def action_confirm(self):
self.check_reservation_exists()
self.check_folio_exists()
if not self.room_lines:
raise ValidationError(_('No se puede confirmar folio sin lineas de habitación'))
for order in self.order_id:
order.state = 'sale'
order.order_line._action_procurement_create()
if not order.project_id:
for line in order.order_line:
if line.product_id.invoice_policy == 'cost':
order._create_analytic_account()
break
if self.env['ir.values'].get_default('sale.config.settings',
'auto_done_setting'):
self.order_id.action_done()
@api.multi
def test_state(self, mode):
'''
@param self: object pointer
@param mode: state of workflow
'''
write_done_ids = []
write_cancel_ids = []
if write_done_ids:
test_obj = self.env['sale.order.line'].browse(write_done_ids)
test_obj.write({'state': 'done'})
if write_cancel_ids:
test_obj = self.env['sale.order.line'].browse(write_cancel_ids)
test_obj.write({'state': 'cancel'})
@api.multi
def action_ship_create(self):
'''
@param self: object pointer
'''
for folio in self:
folio.order_id.action_ship_create()
return True
@api.multi
def action_ship_end(self):
'''
@param self: object pointer
'''
for order in self:
order.write({'shipped': True})
@api.multi
def has_stockable_products(self):
'''
@param self: object pointer
'''
for folio in self:
folio.order_id.has_stockable_products()
return True
@api.multi
def action_cancel_draft(self):
'''
@param self: object pointer
'''
if not len(self._ids):
return False
query = "select id from sale_order_line \
where order_id IN %s and state=%s"
self._cr.execute(query, (tuple(self._ids), 'cancel'))
cr1 = self._cr
line_ids = map(lambda x: x[0], cr1.fetchall())
self.write({'state': 'draft', 'invoice_ids': [], 'shipped': 0})
sale_line_obj = self.env['sale.order.line'].browse(line_ids)
sale_line_obj.write({'invoiced': False, 'state': 'draft',
'invoice_lines': [(6, 0, [])]})
return True
class HotelPayment(models.Model):
_name = 'hotel.payment'
_description = 'hotel payment'
_order = 'id desc'
@api.model
def create(self, vals, check=True):
"""
Overrides orm create method.
@param self: The object pointer
@param vals: dictionary of fields value.
@return: new record set for hotel folio line.
"""
if 'amount' in vals and vals['amount']==0:
raise UserError(_('El monto debe ser diferente a cero.'))
return super(HotelPayment, self).create(vals)
@api.multi
def recibo(self):
datas = {
'ids': [],
'model': 'recibo_x',
'form': self.id,
'context': {'active_id': self.id},
}
return {
'type': 'ir.actions.report.xml',
'report_name': 'recibo_x',
'datas': datas,
}
folio_id = fields.Many2one('hotel.folio', string='Folio',
ondelete='cascade')
payment_date = fields.Datetime('Fecha Pago', required=True,
default=(lambda *a:
time.strftime
(DEFAULT_SERVER_DATETIME_FORMAT)))
amount = fields.Float('Monto', digits_compute=dp.get_precision('Product Price'), required=True)
user_id = fields.Many2one('res.users', string='Cobrado por', index=True, default=lambda self: self.env.user, required=True,readonly=True)
journal_id = fields.Many2one('account.journal', string="Método de Pago", domain="[('type','in',['cash','bank'])]", required=False)
invoice_status = fields.Selection([
('upselling', 'Opertunidad de Upselling'),
('invoiced', 'Facturado'),
('to invoice', 'Para facturar'),
('no', 'Nada que facturar')
], string='Invoice Status', readonly=True, related='folio_id.order_id.invoice_status',)
class HotelFolioService(models.Model):
_name = 'hotel.folio.service'
_description = 'hotel folio service'
_order = 'id desc'
@api.depends('quantity','list_price')
def _compute_amount(self):
"""
Compute the amounts of the SO line.
"""
for line in self:
st = line.list_price * line.quantity
line.update({
'price_subtotal': st,
})
@api.onchange('product_id')
def product_id_change(self):
if self.product_id:
self.list_price = self.product_id.lst_price
@api.onchange('cobrado')
def product_cobrado(self):
if self.cobrado=='si':
self.user_id = self.env.user
else:
self.user_id = False
folio_id = fields.Many2one('hotel.folio', string='Folio',
ondelete='cascade')
service_date = fields.Datetime('Fecha', required=True,
default=(lambda *a:
time.strftime
(DEFAULT_SERVER_DATETIME_FORMAT)))
quantity = fields.Float(string='Cantidad', default=1, required=True)
list_price = fields.Float('Precio', digits_compute=dp.get_precision('Product Price'), required=True)
user_id = fields.Many2one('res.users', string='Cobrado por',readonly=False)
product_id = fields.Many2one('product.product', string='Producto',readonly=False, domain=[('isservice','=',True)], required=True)
cobrado = fields.Selection([('no', 'No'), ('si', 'Si')], 'Cobrado', default='no', required=False)
price_subtotal = fields.Float(compute='_compute_amount', string='Subtotal', readonly=True, store=True, track_visibility='always')
journal_id = fields.Many2one('account.journal', string="Método de Pago", domain="[('type','in',['cash','bank'])]", required=False)
class HotelFolioLine(models.Model):
@api.multi
def copy(self, default=None):
'''
@param self: object pointer
@param default: dict of default values to be set
'''
return super(HotelFolioLine, self).copy(default=default)
@api.multi
def _amount_line(self, field_name, arg):
'''
@param self: object pointer
@param field_name: Names of fields.
@param arg: User defined arguments
'''
return self.env['sale.order.line']._amount_line(field_name, arg)
@api.multi
def _number_packages(self, field_name, arg):
'''
@param self: object pointer
@param field_name: Names of fields.
@param arg: User defined arguments
'''
return self.env['sale.order.line']._number_packages(field_name, arg)
@api.model
def _get_checkin_date(self):
if 'checkin' in self._context:
return self._context['checkin']
return time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
@api.model
def _get_checkout_date(self):
if 'checkout' in self._context:
return self._context['checkout']
return time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
# def _get_uom_id(self):
# try:
# proxy = self.pool.get('ir.model.data')
# result = proxy.get_object_reference(self._cr, self._uid,
# 'product','product_uom_unit')
# return result[1]
# except Exception:
# return False
_name = 'hotel.folio.line'
_description = 'hotel folio1 room line'
order_line_id = fields.Many2one('sale.order.line', string='Order Line',
required=True, delegate=True,
ondelete='cascade')
folio_id = fields.Many2one('hotel.folio', string='Folio',
ondelete='cascade')
checkin_date = fields.Datetime('Check In', required=True,
default=_get_checkin_date)
checkout_date = fields.Datetime('Check Out', required=True,
default=_get_checkout_date)
categ_id = fields.Many2one('product.category', 'Categoria' , related='product_id.categ_id', required=False)
# product_uom = fields.Many2one('product.uom',string='Unit of Measure',
# required=True, default=_get_uom_id)
@api.model
def create(self, vals, check=True):
"""
Overrides orm create method.
@param self: The object pointer
@param vals: dictionary of fields value.
@return: new record set for hotel folio line.
"""
if 'folio_id' in vals:
folio = self.env["hotel.folio"].browse(vals['folio_id'])
vals.update({'order_id': folio.order_id.id})
return super(HotelFolioLine, self).create(vals)
@api.constrains('checkin_date', 'checkout_date')
def check_dates(self):
'''
This method is used to validate the checkin_date and checkout_date.
-------------------------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation
'''
if self.checkin_date >= self.checkout_date:
raise ValidationError(_('Room line Check In Date Should be \
less than the Check Out Date!'))
# if self.folio_id.date_order and self.checkin_date:
# if self.checkin_date <= self.folio_id.date_order:
# raise ValidationError(_('Room line check in date should be \
# greater than the current date.'))
@api.multi
def unlink(self):
"""
Overrides orm unlink method.
@param self: The object pointer
@return: True/False.
"""
sale_line_obj = self.env['sale.order.line']
fr_obj = self.env['folio.room.line']
for line in self:
if line.order_line_id:
sale_unlink_obj = (sale_line_obj.browse
([line.order_line_id.id]))
for rec in sale_unlink_obj:
room_obj = self.env['hotel.room'
].search([('name', '=', rec.name)])
if room_obj.id:
folio_arg = [('folio_id', '=', line.folio_id.id),
('room_id', '=', room_obj.id)]
folio_room_line_myobj = fr_obj.search(folio_arg)
if folio_room_line_myobj.id:
folio_room_line_myobj.unlink()
room_obj.write({'isroom': True,
'status': 'available'})
sale_unlink_obj.unlink()
return super(HotelFolioLine, self).unlink()
@api.multi
def uos_change(self, product_uos, product_uos_qty=0, product_id=None):
'''
@param self: object pointer
'''
for folio in self:
line = folio.order_line_id
line.uos_change(product_uos, product_uos_qty=0,
product_id=None)
return True
@api.onchange('product_id')
def product_id_change(self):
if self.product_id and self.folio_id.partner_id:
self.name = self.product_id.name
self.price_unit = self.product_id.lst_price
self.product_uom = self.product_id.uom_id
# self.categ_id = self.product_id.categ_id.rtype_ids.id
tax_obj = self.env['account.tax']
prod = self.product_id
self.price_unit = self.product_id.categ_id.rtype_ids.list_price
if self.folio_id.partner_id.discount_id:
self.discount_id = self.folio_id.partner_id.discount_id.id
self.discount = self.folio_id.partner_id.discount_id.discount
# self.price_unit = tax_obj._fix_tax_included_price(prod.price,
# prod.taxes_id,
# self.tax_id)
@api.onchange('product_uom')
def product_uom_change(self):
if not self.product_uom:
self.price_unit = 0.0
return
self.price_unit = self.product_id.categ_id.rtype_ids.list_price
if self.folio_id.partner_id:
prod = self.product_id.with_context(
lang=self.folio_id.partner_id.lang,
partner=self.folio_id.partner_id.id,
quantity=1,
date_order=self.folio_id.checkin_date,
pricelist=self.folio_id.pricelist_id.id,
uom=self.product_uom.id
)
tax_obj = self.env['account.tax']
# self.price_unit = tax_obj._fix_tax_included_price(prod.price,
# prod.taxes_id,
# self.tax_id)
@api.onchange('checkin_date', 'checkout_date')
def on_change_checkout(self):
'''
When you change checkin_date or checkout_date it will checked it
and update the qty of hotel folio line
-----------------------------------------------------------------
@param self: object pointer
'''
if not self.checkin_date:
self.checkin_date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
if not self.checkout_date:
self.checkout_date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
chckin = self.checkin_date
chckout = self.checkout_date
if chckin and chckout:
server_dt = DEFAULT_SERVER_DATETIME_FORMAT
chkin_dt = datetime.datetime.strptime(chckin, server_dt)
chkout_dt = datetime.datetime.strptime(chckout, server_dt)
dur = chkout_dt - chkin_dt
sec_dur = dur.seconds
additional_hours = abs((dur.seconds / 60) / 60)
if additional_hours <= 12:
myduration = dur.days
else:
myduration = dur.days + 1
self.product_uom_qty = myduration
@api.multi
def button_confirm(self):
'''
@param self: object pointer
'''
for folio in self:
line = folio.order_line_id
line.button_confirm()
return True
@api.multi
def button_done(self):
'''
@param self: object pointer
'''
lines = [folio_line.order_line_id for folio_line in self]
lines.button_done()
self.write({'state': 'done'})
for folio_line in self:
workflow.trg_write(self._uid, 'sale.order',
folio_line.order_line_id.order_id.id,
self._cr)
return True
@api.multi
def copy_data(self, default=None):
'''
@param self: object pointer
@param default: dict of default values to be set
'''
line_id = self.order_line_id.id
sale_line_obj = self.env['sale.order.line'].browse(line_id)
return sale_line_obj.copy_data(default=default)
class HotelServiceLine(models.Model):
@api.multi
def copy(self, default=None):
'''
@param self: object pointer
@param default: dict of default values to be set
'''
return super(HotelServiceLine, self).copy(default=default)
@api.multi
def _amount_line(self, field_name, arg):
'''
@param self: object pointer
@param field_name: Names of fields.
@param arg: User defined arguments
'''
for folio in self:
line = folio.service_line_id
x = line._amount_line(field_name, arg)
return x
@api.multi
def _number_packages(self, field_name, arg):
'''
@param self: object pointer
@param field_name: Names of fields.
@param arg: User defined arguments
'''
for folio in self:
line = folio.service_line_id
x = line._number_packages(field_name, arg)
return x
@api.model
def _service_checkin_date(self):
if 'checkin' in self._context:
return self._context['checkin']
return time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
@api.model
def _service_checkout_date(self):
if 'checkout' in self._context:
return self._context['checkout']
return time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
_name = 'hotel.service.line'
_description = 'hotel Service line'
service_line_id = fields.Many2one('sale.order.line', 'Service Line',
required=True, delegate=True,
ondelete='cascade')
folio_id = fields.Many2one('hotel.folio', 'Folio', ondelete='cascade')
ser_checkin_date = fields.Datetime('From Date', required=True,
default=_service_checkin_date)
ser_checkout_date = fields.Datetime('To Date', required=True,
default=_service_checkout_date)
quantity = fields.Float(string='Cantidad', default=1)
@api.model
def create(self, vals, check=True):
"""
Overrides orm create method.
@param self: The object pointer
@param vals: dictionary of fields value.
@return: new record set for hotel service line.
"""
if 'folio_id' in vals:
folio = self.env['hotel.folio'].browse(vals['folio_id'])
vals.update({'order_id': folio.order_id.id})
return super(HotelServiceLine, self).create(vals)
@api.multi
def unlink(self):
"""
Overrides orm unlink method.
@param self: The object pointer
@return: True/False.
"""
s_line_obj = self.env['sale.order.line']
for line in self:
if line.service_line_id:
sale_unlink_obj = s_line_obj.browse([line.service_line_id.id])
sale_unlink_obj.unlink()
return super(HotelServiceLine, self).unlink()
@api.onchange('product_id')
def product_id_change(self):
'''
@param self: object pointer
'''
if self.product_id and self.folio_id.partner_id:
self.name = self.product_id.name
self.price_unit = self.product_id.lst_price
self.product_uom = self.product_id.uom_id
tax_obj = self.env['account.tax']
prod = self.product_id
self.price_unit = tax_obj._fix_tax_included_price(prod.price,
prod.taxes_id,
self.tax_id)
self.product_uom_qty = 1
@api.onchange('product_uom')
def product_uom_change(self):
'''
@param self: object pointer
'''
if not self.product_uom:
self.price_unit = 0.0
return
self.price_unit = self.product_id.lst_price
if self.folio_id.partner_id:
prod = self.product_id.with_context(
lang=self.folio_id.partner_id.lang,
partner=self.folio_id.partner_id.id,
quantity=1,
date_order=self.folio_id.checkin_date,
pricelist=self.folio_id.pricelist_id.id,
uom=self.product_uom.id
)
tax_obj = self.env['account.tax']
self.price_unit = tax_obj._fix_tax_included_price(prod.price,
prod.taxes_id,
self.tax_id)
@api.onchange('ser_checkin_date', 'ser_checkout_date')
def on_change_checkout(self):
'''
When you change checkin_date or checkout_date it will checked it
and update the qty of hotel service line
-----------------------------------------------------------------
@param self: object pointer
'''
if not self.ser_checkin_date:
time_a = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
self.ser_checkin_date = time_a
if not self.ser_checkout_date:
self.ser_checkout_date = time_a
if self.ser_checkout_date < self.ser_checkin_date:
raise UserError(_('Checkout must be\
greater or equal checkin date'))
if self.ser_checkin_date and self.ser_checkout_date:
date_a = time.strptime(self.ser_checkout_date,
DEFAULT_SERVER_DATETIME_FORMAT)[:5]
date_b = time.strptime(self.ser_checkin_date,
DEFAULT_SERVER_DATETIME_FORMAT)[:5]
diffDate = datetime.datetime(*date_a) - datetime.datetime(*date_b)
qty = diffDate.days + 1
self.product_uom_qty = self.quantity
@api.multi
def button_confirm(self):
'''
@param self: object pointer
'''
for folio in self:
line = folio.service_line_id
x = line.button_confirm()
return x
@api.multi
def button_done(self):
'''
@param self: object pointer
'''
for folio in self:
line = folio.service_line_id
x = line.button_done()
return x
@api.multi
def copy_data(self, default=None):
'''
@param self: object pointer
@param default: dict of default values to be set
'''
sale_line_obj = self.env['sale.order.line'
].browse(self.service_line_id.id)
return sale_line_obj.copy_data(default=default)
class HotelServiceType(models.Model):
_name = "hotel.service.type"
_description = "Service Type"
ser_id = fields.Many2one('product.category', 'category', required=True,
delegate=True, select=True, ondelete='cascade')
class HotelServices(models.Model):
_name = 'hotel.services'
_description = 'Hotel Services and its charges'
service_id = fields.Many2one('product.product', 'Service_id',
required=True, ondelete='cascade',
delegate=True)
class ResCompany(models.Model):
_inherit = 'res.company'
additional_hours = fields.Integer('Additional Hours',
help="Provide the min hours value for \
check in, checkout days, whatever the hours will be provided here based \
on that extra days will be calculated.")
class CurrencyExchangeRate(models.Model):
_name = "currency.exchange"
_description = "currency"
name = fields.Char('Reg Number', readonly=True, default='New')
today_date = fields.Datetime('Date Ordered',
required=True,
default=(lambda *a:
time.strftime
(DEFAULT_SERVER_DATETIME_FORMAT)))
input_curr = fields.Many2one('res.currency', string='Input Currency',
track_visibility='always')
in_amount = fields.Float('Amount Taken', size=64, default=1.0)
out_curr = fields.Many2one('res.currency', string='Output Currency',
track_visibility='always')
out_amount = fields.Float('Subtotal', size=64)
folio_no = fields.Many2one('hotel.folio', 'Folio Number')
guest_name = fields.Many2one('res.partner', string='Guest Name')
room_number = fields.Char(string='Room Number')
state = fields.Selection([('draft', 'Draft'), ('done', 'Done'),
('cancel', 'Cancel')], 'State', default='draft')
rate = fields.Float('Rate(per unit)', size=64)
hotel_id = fields.Many2one('stock.warehouse', 'Hotel Name')
type = fields.Selection([('cash', 'Cash')], 'Type', default='cash')
tax = fields.Selection([('2', '2%'), ('5', '5%'), ('10', '10%')],
'Service Tax', default='2')
total = fields.Float('Amount Given')
@api.model
def create(self, vals):
"""
Overrides orm create method.
@param self: The object pointer
@param vals: dictionary of fields value.
"""
if not vals:
vals = {}
if self._context is None:
self._context = {}
seq_obj = self.env['ir.sequence']
vals['name'] = seq_obj.next_by_code('currency.exchange') or 'New'
return super(CurrencyExchangeRate, self).create(vals)
@api.onchange('folio_no')
def get_folio_no(self):
'''
When you change folio_no, based on that it will update
the guest_name,hotel_id and room_number as well
---------------------------------------------------------
@param self: object pointer
'''
for rec in self:
self.guest_name = False
self.hotel_id = False
self.room_number = False
if rec.folio_no and len(rec.folio_no.room_lines) != 0:
self.guest_name = rec.folio_no.partner_id.id
self.hotel_id = rec.folio_no.warehouse_id.id
self.room_number = rec.folio_no.room_lines[0].product_id.name
@api.multi
def act_cur_done(self):
"""
This method is used to change the state
to done of the currency exchange
---------------------------------------
@param self: object pointer
"""
self.state = 'done'
return True
@api.multi
def act_cur_cancel(self):
"""
This method is used to change the state
to cancel of the currency exchange
---------------------------------------
@param self: object pointer
"""
self.state = 'done'
return True
@api.multi
def act_cur_cancel_draft(self):
"""
This method is used to change the state
to draft of the currency exchange
---------------------------------------
@param self: object pointer
"""
self.state = 'draft'
return True
@api.model
def get_rate(self, a, b):
'''
Calculate rate between two currency
-----------------------------------
@param self: object pointer
'''
try:
url = 'http://finance.yahoo.com/d/quotes.csv?s=%s%s=X&f=l1' % (a,
b)
rate = urllib2.urlopen(url).read().rstrip()
return Decimal(rate)
except:
return Decimal('-1.00')
@api.onchange('input_curr', 'out_curr', 'in_amount')
def get_currency(self):
'''
When you change input_curr, out_curr or in_amount
it will update the out_amount of the currency exchange
------------------------------------------------------
@param self: object pointer
'''
self.out_amount = 0.0
if self.input_curr:
for rec in self:
result = rec.get_rate(self.input_curr.name,
self.out_curr.name)
if self.out_curr:
self.rate = result
if self.rate == Decimal('-1.00'):
raise except_orm(_('Warning'),
_('Please Check Your \
Network Connectivity.'))
self.out_amount = (float(result) * float(self.in_amount))
@api.onchange('out_amount', 'tax')
def tax_change(self):
'''
When you change out_amount or tax
it will update the total of the currency exchange
-------------------------------------------------
@param self: object pointer
'''
if self.out_amount:
ser_tax = ((self.out_amount) * (float(self.tax))) / 100
self.total = self.out_amount - ser_tax
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.model
def create(self, vals):
cr, uid, context = self.env.args
context = dict(context)
if context.get('invoice_origin', False):
vals.update({'origin': context['invoice_origin']})
return super(AccountInvoice, self).create(vals)
@api.multi
def confirm_paid(self):
'''
This method change pos orders states to done when folio invoice
is in done.
----------------------------------------------------------
@param self: object pointer
'''
pos_order_obj = self.env['pos.order']
res = super(AccountInvoice, self).confirm_paid()
pos_odr_rec = pos_order_obj.search([('invoice_id', 'in', self._ids)])
pos_odr_rec and pos_odr_rec.write({'state': 'done'})
return res |
import React, { useState, useEffect } from "react";
import { Route, Redirect } from "react-router-dom";
import { useMsal } from "@azure/msal-react";
export const RouteGuard = ({ Component, ...props }) => {
const { instance } = useMsal();
const [isAuthorized, setIsAuthorized] = useState(false);
const [isOveraged, setIsOveraged] = useState(false);
const onLoad = async () => {
if (props.location.state) {
let intersection = props.groups
.filter(group => props.location.state.groupsData.includes(group));
if (intersection.length > 0) {
setIsAuthorized(true);
}
} else {
const currentAccount = instance.getActiveAccount();
if (currentAccount && currentAccount.idTokenClaims['groups']) {
let intersection = props.groups
.filter(group => currentAccount.idTokenClaims['groups'].includes(group));
if (intersection.length > 0) {
setIsAuthorized(true);
}
} else if (currentAccount && (currentAccount.idTokenClaims['_claim_names'] || currentAccount.idTokenClaims['_claim_sources'])) {
window.alert('You have too many group memberships. The application will now query Microsoft Graph to get the full list of groups that you are a member of.');
setIsOveraged(true);
}
}
}
useEffect(() => {
onLoad();
}, [instance]);
return (
<>
{
isAuthorized
?
<Route {...props} render={routeProps => <Component {...routeProps} />} />
:
isOveraged
?
<Redirect
to={{
pathname: "/overage",
state: { origin: props.location.pathname }
}}
/>
:
<div className="data-area-div">
<h3>You are unauthorized to view this content.</h3>
</div>
}
</>
);
}; |
import { Input } from "@/components/Form/Input";
import { ModalNewAccount } from "@/components/SignUp/newUserModal";
import { AuthContext } from "@/contexts/AuthContext";
import { Button, Flex, HStack, Heading, Link, Text, useDisclosure } from "@chakra-ui/react";
import { useContext } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import { IoIosChatboxes } from "react-icons/io";
type FormState = {
email: string;
password: string;
};
export default function Home() {
const { register, handleSubmit, formState } = useForm<FormState>();
const { signIn } = useContext(AuthContext);
const { isOpen, onOpen, onClose } = useDisclosure()
const handleLogin: SubmitHandler<FormState> = async (values) => {
await signIn(values);
}
return (
<Flex
w="100vw"
h="100vh"
alignItems="Center"
justify="center"
>
<Flex
as="form"
width="100%"
maxWidth={360}
bg="gray.800"
p="8"
borderRadius={8}
flexDir="column"
onSubmit={handleSubmit(handleLogin)}
>
<HStack color={"white.400"} justify={"center"}>
<Heading>ChatPlay</Heading>
<IoIosChatboxes size="3rem" />
</HStack>
<Input
isRequired
label="E-mail"
pk="email"
type="email"
{...register('email')}
/>
<Input
isRequired
label="Password"
pk="password"
type="password"
{...register('password')}
/>
<Button
type="submit"
mt="6"
colorScheme="yellow"
size="lg">
Entrar
</Button>
<Button
mt="6"
colorScheme="green"
onClick={onOpen}
size="lg">
Criar Conta
</Button>
</Flex>
<ModalNewAccount
isOpen={isOpen}
onClose={onClose}
/>
</Flex>
)
} |
import "./styles.css";
import { RadioButtonComponent } from "../../../types";
import { buildMobrixUiReactiveComponent } from "../../../utils";
import component from "./component";
/**
* A single radio button component. Optionally, can prevent user to deselect it
*
* @param {boolean} value actual radio button value (icon visiblity)
* @param {(newValue:boolean)=>void} onChange callback triggered when input change
* @param {boolean} deselectable if `false`, the button can be selected only once (the value can't change then)
* @param {string} className `common MoBrix-ui prop` - custom className
* @param {boolean} unstyled `common MoBrix-ui prop` - Style/unstyle component, enabling or not MoBrix-ui custom styles
* @param {string} id `common MoBrix-ui prop` - `data-id` parameter (for testing purpose, to easily find the component into the DOM)
* @param {boolean} dark `common MoBrix-ui prop` - Enable/disable dark mode
* @param {boolean} hide `common MoBrix-ui prop` - Hide/show component
* @param {boolean} shadow `common MoBrix-ui prop` - Enable/disable shadow behind component
* @param {boolean} animated `common MoBrix-ui prop` enable/disable component animations
* @param {string} key `common MoBrix-ui prop` - custom component React key (the standard {@link https://reactjs.org/docs/lists-and-keys.html key parameter})
* @param {boolean} a11y `common MoBrix-ui prop` - enable/disable accessibility features
* @param {boolean} a11yDark `common MoBrix-ui prop` - if the `a11y` parameter is `true`, override standard focus color style with/without dark mode (normally, the color changes accordingly to the `dark` parameter)
* @param {string} a11yLabel `common MoBrix-ui prop` - if the `a11y` parameter is `true`, this parameter is used as {@link https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label aria-label}
* @param {() => void} onFocus `common MoBrix-ui prop` - callback called when component is focused
* @param {() => void} onFocusLost `common MoBrix-ui prop` - callback called when component focus is lost
* @param {(keyEvent: any) => void} onKeyDown `common MoBrix-ui prop` - callback called when a key is pressed when inside the component
*
* @example <caption>Example RadioButton usage</caption>
* import { render } from "react-dom";
* import { RadioButton } from 'mobrix-ui';
*
* render(<RadioButton animated value={true} />, document.getElementById("root"));
*
* @see https://cianciarusocataldo.github.io/mobrix-ui/components/atoms/RadioButton
*
* @author Cataldo Cianciaruso <https://github.com/CianciarusoCataldo>
*
* @copyright 2023 Cataldo Cianciaruso
*/
const RadioButton: RadioButtonComponent = ({
value: inputValue,
onChange = () => {},
deselectable = true,
onKeyDown = () => {},
...commonProps
}) =>
buildMobrixUiReactiveComponent<boolean>({
name: "radio-button",
defaultValue: false,
inputValue,
props: (value, setValue) => {
const callBack = () => {
if (!value || deselectable) {
onChange(!value);
setValue(!value);
}
};
return {
commonProps: {
...commonProps,
onKeyDown: (e) => {
if (e.code === "Enter") {
callBack();
}
onKeyDown(e);
},
},
additionalProps: {
onClick: callBack,
},
Component: value ? component : "",
};
},
});
export default RadioButton; |
import { FC, ReactNode, useEffect } from 'react';
import {
Box,
Flex,
Heading,
IconButton,
Link,
Stack,
StackItem,
Text,
useDisclosure,
} from '@chakra-ui/react';
import { PageLoader, SideNav, UserMenu } from '@/components';
import { IconBell, IconX, IconMenu2 } from '@tabler/icons';
import NextLink from 'next/link';
import Image from 'next/image';
import { useAuth } from '@/hooks';
import { useRouter } from 'next/router';
export interface MainLayoutProps {
title: string;
children?: ReactNode;
}
export const MainLayout: FC<MainLayoutProps> = ({ children, title }) => {
const { user, isFetching } = useAuth();
const { isOpen, onToggle, onClose } = useDisclosure();
const router = useRouter();
useEffect(() => {
if (!user && !isFetching) {
setTimeout(() => {
router.push('/login');
}, 500);
}
}, [isFetching, router, user]);
useEffect(() => {
router.events.on('routeChangeStart', onClose);
return () => router.events.off('routeChangeStart', onClose);
}, [router, onClose]);
const renderLayout = () => {
return (
<Flex position="relative" flexDir={{ base: 'column-reverse', lg: 'row' }}>
<Box
position={{ base: 'fixed', lg: 'sticky' }}
top={{ base: '64px', lg: '0' }}
left="0"
bottom="0"
shadow="none"
borderRight="1px"
borderColor="neutral.300"
transition="ease-in-out 250ms"
w={{ base: 'full', lg: '250px' }}
transform={{ base: isOpen ? 'translateX(0)' : 'translateX(-100%)', lg: 'translateX(0)' }}
minW="250px"
h={{ base: 'calc(100vh - 64px)', lg: '100vh' }}
zIndex="docked"
>
<SideNav />
</Box>
<Stack w="full" spacing="0">
<Stack
isInline
px={{ base: '16', lg: '32' }}
py={{ base: '16', lg: '34' }}
borderBottom="1px"
borderColor="neutral.300"
justifyContent="space-between"
alignItems="center"
position="sticky"
top="0"
bg="surface.white"
zIndex="docked"
>
<StackItem>
<Stack display={{ lg: 'none' }} isInline alignItems="center" h="100%" spacing="16">
<StackItem>
<IconButton
display="flex"
alignItems="center"
variant="unstyled"
aria-label="Toggle menu"
icon={isOpen ? <IconX /> : <IconMenu2 />}
onClick={onToggle}
h="max-content"
/>
</StackItem>
<StackItem>
<NextLink href="/dashboard" passHref>
<Link display="block" pos="relative" w="88px" h="26px">
<Image src="/logo.png" alt="logo" layout="fill" objectFit="cover" />
</Link>
</NextLink>
</StackItem>
</Stack>
<Heading size="4" fontWeight="semibold" display={{ base: 'none', lg: 'block' }}>
{title}
</Heading>
</StackItem>
<StackItem>
<Stack isInline alignItems="center" spacing="24">
<StackItem>
<NextLink href="/notifikasi" passHref>
<Link
_hover={{ color: 'primary.main' }}
display="block"
_focus={{
boxShadow: 'none',
outlineWidth: '3px',
outlineColor: 'primary.surface',
}}
>
<Box pos="relative">
<Box
pos="absolute"
bg="primary.main"
borderRadius="full"
left="100%"
top="30%"
transform="translate(-12px, -50%)"
px="3px"
py="2px"
>
<Text variant="body-xs" color="surface.white">
9+
</Text>
</Box>
<IconBell />
</Box>
</Link>
</NextLink>
</StackItem>
<StackItem>
<UserMenu />
</StackItem>
</Stack>
</StackItem>
</Stack>
<Box p="32">{children}</Box>
</Stack>
</Flex>
);
};
return <>{user ? renderLayout() : <PageLoader />}</>;
}; |
import React from "react";
import l from './Login.module.css'
import Button from './../Button/Button1'
import {reduxForm} from "redux-form";
import {connect} from "react-redux";
import {LoginThunk} from "../../Redux/AuthReducer";
import {createField, Input} from "../Common/FormControls/FormControls";
import {maxLengthCreator, required} from "../../Utils/Validator/Validators";
import {Redirect} from "react-router-dom";
class Login extends React.Component {
render() {
let con = (formData) => {
this.props.LoginThunk(formData.email, formData.password, formData.rememberMe, formData.captcha)
}
if (this.props.isAuth) {
return <Redirect to='/profile'/>
}
return (
<div className={l.box}>
<h2>Login</h2>
<LoginReduxForm onSubmit={con} captchaURL={this.props.captchaURL}/>
</div>
)
}
}
const maxLength = maxLengthCreator(30)
const loginForm = ({handleSubmit, error, captchaURL}) => {
return (
<form onSubmit={handleSubmit}>
<div className={l.boxInput}>
{createField(l.placeholder, Input, 'email', 'Email', [required, maxLength])}
{createField(l.placeholder, Input, 'password', 'Password', [required, maxLength],
{type: 'password'})}
{captchaURL && <img className={l.captchaImg} src={captchaURL} alt="captcha"/>}
{captchaURL &&
createField(l.placeholder, Input, 'captcha', 'Enter captcha', [required])}
{
error && <div className={l.fullError}>
{error}
</div>
}
</div>
<div className={l.bottom}>
{createField('', 'input', 'rememberMe', null,
null, {type: 'checkbox'}, 'Remember me' )}
<Button text={'Login'}/>
</div>
</form>
)
}
const LoginReduxForm = reduxForm({form: 'login'})(loginForm);
let mapStateToProps = (state) => {
return {
isAuth: state.auth.isAuth,
captchaURL: state.auth.captchaURL
}
}
export default connect(mapStateToProps, {LoginThunk})(Login); |
import boto3
import os
import json
import numpy as np
from pathlib import Path
from pprint import pprint
import sagemaker
from langchain.docstore.document import Document
from langchain.document_loaders import TextLoader
from langchain.embeddings import BedrockEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import FAISS
from langchain.prompts import PromptTemplate
from langchain.llms import Bedrock
from IPython.display import Markdown, display
from langchain.embeddings import HuggingFaceBgeEmbeddings
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
region = os.environ.get("AWS_REGION")
boto3_bedrock = boto3.client(
service_name='bedrock-runtime',
region_name='us-east-1',
)
def embed_text_input(bedrock_client, prompt_data, modelId="amazon.titan-embed-text-v1"):
accept = "application/json"
contentType = "application/json"
body = json.dumps({"inputText": prompt_data})
response = bedrock_client.invoke_model(
body=body, modelId=modelId, accept=accept, contentType=contentType
)
response_body = json.loads(response.get("body").read())
embedding = response_body.get("embedding")
return np.array(embedding)
# Function to get response from Bedrock AI
def get_response_from_bedrock(user_input):
# Perform similarity search
search_results = vs.similarity_search(user_input, k=3)
context_string = '\n\n'.join([f'Document {ind+1}: ' + i.page_content for ind, i in enumerate(search_results)])
prompt_data = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE).format(human_input=user_input, context=context_string)
# Generate response using Bedrock AI
llm = Bedrock(client=boto3_bedrock, model_id="anthropic.claude-v2", model_kwargs={"max_tokens_to_sample": 500, "temperature": 0.9})
output = llm(prompt_data).strip()
return output
## user_input = "What are Jack Sparrow's interests?"
## document_1 = 'his interests are hiking and playing video games'
## document_2 = 'his family is Haochen, Lily, and Priscilla'
## user_input_vector = embed_text_input(boto3_bedrock, user_input)
## document_1_vector = embed_text_input(boto3_bedrock, document_1)
## document_2_vector = embed_text_input(boto3_bedrock, document_2)
## doc_1_match_score = np.dot(user_input_vector, document_1_vector)
## doc_2_match_score = np.dot(user_input_vector, document_2_vector)
## print(f'"{user_input}" matches "{document_1}" with a score of {doc_1_match_score:.1f}')
## print(f'"{user_input}" matches "{document_2}" with a score of {doc_2_match_score:.1f}')
with open('/Users/haochenmiao/Documents/Data_Sciecne_Projects/safeGPT/incidents.txt') as f:
doc_content = f.read()
docs = [Document(page_content=doc_content)]
split_docs = CharacterTextSplitter(separator='\n', chunk_size=1000, chunk_overlap=0).split_documents(docs)
# Set up embedding model and vector store
hf_embedding_model = HuggingFaceBgeEmbeddings(model_name="BAAI/bge-small-en-v1.5", model_kwargs={'device': 'cpu'}, encode_kwargs={'normalize_embeddings': False})
vs = FAISS.from_documents(split_docs, hf_embedding_model)
RAG_PROMPT_TEMPLATE = '''Here is some important context which can help inform the questions the Human asks.
Make sure to not make anything up to answer the question if it is not provided in the context.
<context>
{context}
</context>
Human: {human_input}
Assistant:
'''
PROMPT = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
# Interactive conversation loop
while True:
user_input = input("You: ")
if user_input.lower() in ['exit', 'quit']:
print("Chatbot: Goodbye!")
break
# Perform similarity search and generate response
search_results = vs.similarity_search(user_input, k=3)
context_string = '\n\n'.join([f'Document {ind+1}: ' + i.page_content for ind, i in enumerate(search_results)])
prompt_data = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE).format(human_input=user_input, context=context_string)
# Generate and output response
llm = Bedrock(client=boto3_bedrock, model_id="anthropic.claude-v2", model_kwargs={"max_tokens_to_sample": 500, "temperature": 0.9})
output = llm(prompt_data).strip()
print("Chatbot:", output) |
<div *ngIf="(appService.getGroupe == 'DENDROMAP') && user">
<div class="media align-items-center py-3 mb-3">
<img
[src]="user.img ? appService.urlBase + 'images/' + user.img : appService.default_img"
class="d-block ui-w-100 rounded-circle" alt="">
<div class="media-body ml-4">
<h4 class="font-weight-bold mb-0">{{user.prenom}} {{user.nom}} </h4>
<div class="text-muted mb-2">@{{user.username}}</div>
<button [class]="'btn btn-sm ' + ( user.isActive ? 'btn-success' : 'btn-danger')" [swal]="{title: 'Etes-vous sûr(e)s?',
text: 'Vous êtes sur le point de ' + (user.isActive ? 'désactiver' : 'activer') + ' un utilisateur!',
type:'warning',
showCancelButton:true,
confirmButtonText: user.isActive ? 'DESACTIVER' : 'ACTIVER',
cancelButtonText:'Annuler',
showCloseButton:true,
cancelButtonClass:'btn btn-md btn-default',
confirmButtonClass:'btn btn-md btn-warning'}"
[ngbTooltip]="!user.isActive ? 'Activer' : 'Désactiver'"
(confirm)="DesactiveOrActive(user)"
(cancel)="declineDialog.show()"> {{user.isActive ? 'Actif' : 'Inactif'}}
</button>
<button class="btn btn-default btn-sm"
(click)="open(defaultModal, { windowClass: 'modal-md animate' }, user.profil)">{{user.profil.name}}</button>
</div>
</div>
<div class="card mb-4" style="border:1px solid #02BC77">
<div class="card-body">
<table class="table user-view-table m-0">
<tbody>
<tr>
<td>Email</td>
<td>
<span>{{user.email}}</span>
</td>
</tr>
<tr>
<td>Creation</td>
<td>{{user.createdAt | date: 'dd/MM/yyyy H:mm'}}</td>
</tr>
<tr>
<td>Profil</td>
<td>
<span class="text-primary" style="cursor: pointer"
(click)="open(defaultModal, { windowClass: 'modal-md animate' }, user.profil)"> {{user.profil.name}}</span>
</td>
</tr>
<tr>
<td>groupe</td>
<td>
<span>{{user.groupe.name | lowercase }}</span>
</td>
</tr>
<tr>
<td>Status:</td>
<td>
<span
[class]=" user.isActive? 'badge badge-outline-success' : 'badge badge-outline-danger'">{{ user.isActive ? 'Actif' : 'Inactif'}}</span>
</td>
</tr>
<tr *ngIf="user.groupe.groupeType !== 'DENDROMAP'">
<td>Forfait:</td>
<td>
{{ user.groupe.forfait.name }}
</td>
</tr>
<tr *ngIf="user.groupe.groupeType !== 'DENDROMAP'">
<td>Durée</td>
<td>
{{ displayCodeForfait }}
</td>
</tr>
<tr *ngIf="user.groupe.groupeType !== 'DENDROMAP'">
<td>Date fin</td>
<td>
{{user.groupe.dateEcheance ? (user.groupe.dateEcheance | date: 'dd/MM/yyyy H:mm') : ''}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div *ngIf="(this.appService.getGroupe != 'DENDROMAP') && user">
<div class="row" *ngIf="user">
<div class="col-md-4">
<!-- Side info -->
<div class="card mb-4">
<div class="card-body">
<div class="media text-center">
<img style="max-width: 100%;box-shadow:1px 0px 4px #000000b0;"
[src]="user.img ? appService.urlBase + 'images/' + user.img : this.appService.default_img"
alt class="img-fluid contact-content-img rounded-circle">
</div>
</div>
<hr class="border-light m-0">
<div class="card-body">
<div class="mb-2">
<span class="text-muted" *ngIf="user.nom">Nom et Prenom:</span>
{{user.prenom}} {{user.prenom}}
</div>
<div class="mb-2">
<span class="text-muted">Email :</span>
{{user.email}}
</div>
<div class="mb-2">
<span class="text-muted">Username :</span>
<a href="javascript:void(0)" class="text-dark">{{user.username}}</a>
</div>
<div class="mb-2">
<span class="text-muted">Profil :</span>
<a href="javascript:void(0)" class="text-dark">{{user.profil.name}}</a>
</div>
<div class="mb-2">
<span class="text-muted">Role :</span>
<a href="javascript:void(0)" class="text-dark">{{droit}}</a>
</div>
<div class="mb-2">
<span class="text-muted">Statut : </span>
<a href="javascript:void(0)" class="text-dark">{{user.isActive ? 'Actif' : 'Inactif'}}</a>
</div>
<p class="text-center">
<a href="javascript:void(0)" (click)="resetPassword(user.id)" class="btn btn-success btn-md">
Reinitialiser mot de passe</a></p>
</div>
<div class="card-footer text-center">
<div *ngIf="!user?.emailActive"><span
class="badge badge-danger">{{user?.emailActive ? 'EMAIL VERIFIE' : 'EMAIL NON VERIFIE'}}</span>
<p class="text-center mt-2">Il semble que cet utilisateur n'a pas encore validé son email. <br>
<a href="javascript:void(0)" (click)="onEmailConfirm(user.id)"> Renvoyer le mail de confirmation </a></p>
</div>
</div>
</div>
<!-- / Side info -->
</div>
<div class="col">
<!-- Info -->
<div class="row no-gutters row-bordered ui-bordered text-center mb-4"
style="border-radius:4px;border:1px solid #02BC77">
<a href="javascript:void(0)" class="d-flex col flex-column text-dark py-3">
<div class="font-weight-bold">
<div class="badge badge-success">{{inventaireStat?.arbre}}</div>
</div>
<div class="text-muted small"><strong>Arbres</strong></div>
</a>
<a href="javascript:void(0)" class="d-flex col flex-column text-dark py-3">
<div class="font-weight-bold">
<div class="badge badge-success">{{inventaireStat?.ebc}}</div>
</div>
<div class="text-muted small"><strong>EBC <span
class="d-none d-sm-block">(Espace Boisé Classé)</span></strong></div>
</a>
<a href="javascript:void(0)" class="d-flex col flex-column text-dark py-3">
<div class="font-weight-bold">
<div class="badge badge-success">{{inventaireStat?.epp}}</div>
</div>
<div class="text-muted small"><strong>EPP <span
class="d-none d-sm-block">(Espace Paysager à préserver)</span></strong></div>
</a>
</div>
<!-- / Info -->
<!-- Posts -->
<div [@moveInLeft]="state">
<form [formGroup]="userForm" (ngSubmit)="updateUser()">
<div class="card mb-4">
<div class="card-header mb-0">
<h4 class="text-center">
MODIFIER PROFIL
</h4>
</div>
<div class="card-body">
<div class="form-row">
<div class="col-sm-12">
<app-text-input-form [textFormGroup]="userForm" [textLabel]="'Nom d\'utilisateur *'"
[formName]="'username'"
[errorText]="'Pseudo doit avoir plus de 2 caractères'"></app-text-input-form>
</div>
<div class="col-md-12">
<app-text-input-form [textFormGroup]="userForm" [textLabel]="'Email *'"
[formName]="'email'"
[errorText]="'Saisir un email valide'"></app-text-input-form>
</div>
</div>
<div class="form-row">
<div class="col-md-6">
<app-select-input-form
[selectFormGroup]="userForm"
[textLabel]="'Profil *'"
[formName]="'profil'"
[DATA_TAB]="profilsOptions"
[isMultiple]="false">
</app-select-input-form>
</div>
</div>
</div>
<div class="card-footer">
<a href="javascript:void(0)" (click)="updateUser()" class="btn btn-success btn-md float-right">
Modifier</a>
</div>
</div>
</form>
</div>
<!-- / Posts -->
</div>
</div>
</div>
<ng-template #defaultModal let-c="close" let-d="dismiss">
<div class="modal-header">
<h5 class="modal-title">
Modifier Profil
</h5>
<button type="button" class="close" (click)="d('Cross click')">×</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xl-12">
<div class="custom-controls-stacked">
<label class="custom-control custom-radio" style="display: inline;margin-right: 3rem;"
*ngFor="let profile of profilsOptions; let isLast=last">
<input name="profil" type="radio" [value]="profile.value" [(ngModel)]="profilPop.id"
class="custom-control-input">
<span class="custom-control-label">{{profile.label}}</span>
<br *ngIf="!isLast">
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="col-sm-6 btn btn-default" (click)="d('Cross click')">
Annuler
</button>
<button type="button" class="col-sm-6 btn btn-success"
(click)="modiferProfil(); c('Close click');">
Enregistrer
</button>
</div>
</ng-template>
<!-- SPINNER -->
<app-spinner [visible]="visibleSpinner"></app-spinner>
<!-- FIN SPINNER --> |
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
namespace PrestaShop\PrestaShop\Adapter\Preferences;
use Cookie;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* This class will provide Shop Preferences configuration.
*/
class PreferencesConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
public function __construct(
Configuration $configuration
) {
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return [
'enable_ssl' => $this->configuration->getBoolean('PS_SSL_ENABLED'),
'enable_ssl_everywhere' => $this->configuration->getBoolean('PS_SSL_ENABLED_EVERYWHERE'),
'enable_token' => $this->configuration->getBoolean('PS_TOKEN_ENABLE'),
'allow_html_iframes' => $this->configuration->getBoolean('PS_ALLOW_HTML_IFRAME'),
'use_htmlpurifier' => $this->configuration->getBoolean('PS_USE_HTMLPURIFIER'),
'price_round_mode' => $this->configuration->get('PS_PRICE_ROUND_MODE'),
'price_round_type' => $this->configuration->get('PS_ROUND_TYPE'),
'display_suppliers' => $this->configuration->getBoolean('PS_DISPLAY_SUPPLIERS'),
'display_manufacturers' => $this->configuration->getBoolean('PS_DISPLAY_MANUFACTURERS'),
'display_best_sellers' => $this->configuration->getBoolean('PS_DISPLAY_BEST_SELLERS'),
'multishop_feature_active' => $this->configuration->getBoolean('PS_MULTISHOP_FEATURE_ACTIVE'),
'shop_activity' => $this->configuration->get('PS_SHOP_ACTIVITY'),
];
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
if (false === $this->validateConfiguration($configuration)) {
return [
[
'key' => 'Invalid configuration',
'domain' => 'Admin.Notifications.Warning',
'parameters' => [],
],
];
}
if ($this->validateSameSiteConfiguration($configuration)) {
return [
[
'key' => 'Cannot disable SSL configuration due to the Cookie SameSite=None.',
'domain' => 'Admin.Advparameters.Notification',
'parameters' => [],
],
];
}
$previousMultistoreFeatureState = $this->configuration->get('PS_MULTISHOP_FEATURE_ACTIVE');
$this->configuration->set('PS_SSL_ENABLED', $configuration['enable_ssl']);
$this->configuration->set('PS_SSL_ENABLED_EVERYWHERE', $configuration['enable_ssl_everywhere']);
$this->configuration->set('PS_TOKEN_ENABLE', $configuration['enable_token']);
$this->configuration->set('PS_ALLOW_HTML_IFRAME', $configuration['allow_html_iframes']);
$this->configuration->set('PS_USE_HTMLPURIFIER', $configuration['use_htmlpurifier']);
$this->configuration->set('PS_PRICE_ROUND_MODE', $configuration['price_round_mode']);
$this->configuration->set('PS_ROUND_TYPE', $configuration['price_round_type']);
$this->configuration->set('PS_DISPLAY_SUPPLIERS', $configuration['display_suppliers']);
$this->configuration->set('PS_DISPLAY_MANUFACTURERS', $configuration['display_manufacturers']);
$this->configuration->set('PS_DISPLAY_BEST_SELLERS', $configuration['display_best_sellers']);
$this->configuration->set('PS_MULTISHOP_FEATURE_ACTIVE', $configuration['multishop_feature_active']);
$this->configuration->set('PS_SHOP_ACTIVITY', $configuration['shop_activity']);
return [];
}
/**
* Validate the SSL configuration can be disabled if the SameSite Cookie
* is not settled to None
*
* @param array $configuration
*
* @return bool
*/
protected function validateSameSiteConfiguration(array $configuration): bool
{
return (
$configuration['enable_ssl'] === false
|| $configuration['enable_ssl_everywhere'] === false
)
&& $this->configuration->get('PS_COOKIE_SAMESITE') === Cookie::SAMESITE_NONE;
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
return isset(
$configuration['enable_ssl'],
$configuration['enable_ssl_everywhere'],
$configuration['enable_token'],
$configuration['allow_html_iframes'],
$configuration['use_htmlpurifier'],
$configuration['price_round_mode'],
$configuration['price_round_type'],
$configuration['display_suppliers'],
$configuration['display_manufacturers'],
$configuration['display_best_sellers'],
$configuration['multishop_feature_active']
);
}
} |
#include "binary_trees.h"
/**
* binary_tree_size - measures the size of a binary tree
*
* @tree: pointer to the root node of the tree to traverse
* Return: size of a binary tree
*/
size_t binary_tree_size(const binary_tree_t *tree)
{
if (tree != NULL)
{
return (binary_tree_size(tree->left) + 1 +
binary_tree_size(tree->right));
}
else
{
return (0);
}
} |
import { shared } from "../styles";
import { BaseElement, element, html, css, property, query, observe } from "./base";
@element("pl-select")
export class Select<T> extends BaseElement {
@property()
options: T[] = [];
@property()
selected: T;
@property()
label: string = "";
@property()
icon: string = "";
@query("select")
private _select: HTMLSelectElement;
static styles = [
shared,
css`
:host {
display: block;
position: relative;
padding: 0;
height: var(--row-height);
padding: 0 15px;
background: var(--shade-2-color);
border-radius: var(--border-radius);
}
select {
width: 100%;
height: 100%;
box-sizing: border-box;
cursor: pointer;
}
select.pad-left {
padding-left: 30px;
}
option {
background-color: var(--color-tertiary);
color: var(--color-secondary);
}
label {
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 13px;
opacity: 0.5;
transition: transform 0.2s, color 0.2s, opacity 0.5s;
cursor: text;
pointer-events: none;
}
label[float] {
transform: scale(0.8) translate(0, -32px);
color: var(--color-highlight);
font-weight: bold;
opacity: 1;
}
pl-icon {
position: absolute;
width: 20px;
height: 20px;
top: 0;
bottom: 0;
margin: auto;
pointer-events: none;
}
pl-icon.right {
right: 12px;
}
pl-icon.left {
left: 14px;
}
`
];
render() {
const { options, selected, label, icon } = this;
return html`
${icon
? html`
<pl-icon icon=${icon} class="left"></pl-icon>
`
: ""}
<select
id="selectEl"
class="${icon ? "pad-left" : ""}"
.selectedIndex=${options.indexOf(selected)}
@change=${() => this._changed()}
>
${options.map(
o => html`
<option>${o}</option>
`
)}
</select>
<pl-icon icon="dropdown" class="right"></pl-icon>
<label for="selectEl" float>${label}</label>
`;
}
@observe("options")
@observe("selected")
async _propsChanged() {
if (!this.selected) {
this.selected = this.options[0];
}
await this.updateComplete;
this._select.selectedIndex = this.options.indexOf(this.selected);
}
private _changed() {
this.selected = this.options[this._select.selectedIndex];
this.dispatch("change");
}
} |
//
// Sequence-Sorting.swift
// Travner
//
// Created by Lorenzo Lins Mazzarotto on 03/04/22.
//
import Foundation
extension Sequence {
func sorted<Value>(
by keyPath: KeyPath<Element, Value>,
using areInIncreasingOrder: (Value, Value) throws -> Bool
) rethrows -> [Element] {
try self.sorted {
try areInIncreasingOrder($0[keyPath: keyPath], $1[keyPath: keyPath])
}
}
func sorted<Value: Comparable>(by keyPath: KeyPath<Element, Value>) -> [Element] {
self.sorted(by: keyPath, using: <)
}
} |
from collections import OrderedDict
from typing import List, TypeVar
class _Channel:
def __init__(
self,
name: str,
mung_classes: List[str],
deepscores_classes: List[str],
oversample: bool
):
self.name = name
self.mung_classes = mung_classes
self.deepscores_classes = deepscores_classes
self.oversample = oversample
class SegmentationDescription:
"""Describes a segmentation mask structure (mung classes for each mask channel)"""
Self = TypeVar("Self", bound="SegmentationDescription")
def __init__(self):
self._channels = OrderedDict()
def add_channel(
self,
name: str,
mung_classes: List[str],
deepscores_classes: List[str],
oversample: bool
) -> Self:
"""Fluent segmentation description builder method"""
self._channels[name] = _Channel(
name, mung_classes, deepscores_classes, oversample
)
return self
def channel_names(self) -> List[str]:
return list(self._channels.keys())
def channel_mung_classes(self, channel_name: str):
return self._channels[channel_name].mung_classes
def channel_deepscores_classes(self, channel_name: str):
return self._channels[channel_name].deepscores_classes
def oversampled_channel_indices(self) -> List[int]:
return list(
i for i, channel in enumerate(self._channels.values())
if channel.oversample
)
@staticmethod
def from_name(name) -> Self:
if name == "notehead":
return SegmentationDescription.NOTEHEADS
if name == "stem":
return SegmentationDescription.STEM
if name == "staffline":
return SegmentationDescription.STAFFLINE
if name == "beam":
return SegmentationDescription.BEAM
if name == "flag":
return SegmentationDescription.FLAGS
raise Exception("Unknown symbol class: " + name)
SegmentationDescription.NOTEHEADS = SegmentationDescription() \
.add_channel("noteheads",
mung_classes=[
"noteheadFull", "noteheadHalf", "noteheadWhole",
"noteheadFullSmall", "noteheadHalfSmall"
],
deepscores_classes=[
"noteheadBlackOnLine", "noteheadBlackOnLineSmall",
"noteheadBlackInSpace", "noteheadBlackInSpaceSmall",
"noteheadHalfOnLine", "noteheadHalfOnLineSmall",
"noteheadHalfInSpace", "noteheadHalfInSpaceSmall",
"noteheadWholeOnLine", "noteheadWholeOnLineSmall",
"noteheadWholeInSpace", "noteheadWholeInSpaceSmall",
"noteheadDoubleWholeOnLine", "noteheadDoubleWholeOnLineSmall",
"noteheadDoubleWholeInSpace", "noteheadDoubleWholeInSpaceSmall"
],
oversample=True
)
SegmentationDescription.STEM = SegmentationDescription() \
.add_channel("stem",
mung_classes=["stem"],
deepscores_classes=["stem"],
oversample=True
)
SegmentationDescription.STAFFLINE = SegmentationDescription() \
.add_channel("staffLine",
mung_classes=["staffLine"],
deepscores_classes=["staff"],
oversample=True
)
SegmentationDescription.BEAM = SegmentationDescription() \
.add_channel("beam",
mung_classes=["beam"],
deepscores_classes=["beam"],
oversample=True
)
SegmentationDescription.FLAGS = SegmentationDescription() \
.add_channel("flags",
mung_classes=[
"flag8thUp", "flag8thDown", "flag16thUp", "flag16thDown",
"flag32thUp", "flag32thDown", "flag64thUp", "flag64thDown",
],
deepscores_classes=[
"flag8thUp", "flag8thUpSmall", "flag16thUp", "flag32ndUp",
"flag64thUp", "flag128thUp", "flag8thDown", "flag8thDownSmall",
"flag16thDown", "flag32ndDown", "flag64thDown", "flag128thDown"
],
oversample=True
)
# 16th_rest
# 8th_rest
# quarter_rest
# half_rest
# whole_rest
# c-clef
# f-clef
# g-clef
# barlines
# beam
# stem
# stafflines
# flags
# ledger_line
# noteheads
# duration-dot
# double_sharp
# flat
# natural
# sharp |
import 'package:falcon_net/Theme/Light/LightCardTheme.dart';
import 'package:falcon_net/Theme/Light/LightTextTheme.dart';
import 'package:falcon_net/Theme/NegativeButtonTheme.dart';
import 'package:flutter/material.dart';
import 'package:falcon_net/Theme/Light/LightElevatedTheme.dart';
/*
TODO:
- Use '///' to document classes
- Comment like every line -- probably need to organize these lines
- Explain differences between themes etc.
*/
ThemeData lightTheme = ThemeData(
primaryColor: Colors.white,
focusColor: Colors.grey[200],
highlightColor: const Color.fromARGB(255, 147, 170, 255),
indicatorColor: Colors.blue,
disabledColor: const Color.fromARGB(255, 179, 179, 179),
textTheme: lightTextTheme,
cardTheme: lightCardTheme,
elevatedButtonTheme: lightButtonTheme,
fontFamily: "ProximaNova", // Default font
iconTheme: const IconThemeData(
color: Colors.black), // Default color for icons is black
canvasColor: const Color(0xFFf2f2f2), // Default canvas color is light grey
snackBarTheme: const SnackBarThemeData(
// Default snackbar theme
backgroundColor: Color.fromARGB(255, 50, 50, 50), // Dark grey
contentTextStyle:
TextStyle(fontSize: 15, color: Colors.white), // White text
),
switchTheme: SwitchThemeData(
thumbColor: MaterialStateColor.resolveWith((states) => Colors.blue),
trackColor: MaterialStateColor.resolveWith((states) {
if (states.contains(MaterialState.selected)) {
return Colors.blue;
}
return Colors.grey;
}),
),
extensions: [
NegativeButtonTheme(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.grey,
textStyle: lightTextTheme.labelLarge,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
)
],
colorScheme: const ColorScheme.light(
primary: Colors.blue,
secondary: Colors.black,
error: Color.fromARGB(255, 230, 88, 78),
),
bottomSheetTheme: const BottomSheetThemeData(dragHandleSize: Size(50, 5))); |
<?php
namespace Drupal\image_lazy_load_test\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* The ImageLazyLoadController class.
*/
class ImageLazyLoadController extends ControllerBase {
/**
* Render an image using image theme.
*
* @return array
* The render array.
*/
public function renderImage() {
$images['with-dimensions'] = [
'#theme' => 'image',
'#uri' => '/core/themes/bartik/logo.svg',
'#alt' => 'Image lazy load testing image',
'#prefix' => '<div id="with-dimensions">',
'#suffix' => '</div>',
'#width' => '50%',
'#height' => '50%',
];
$images['without-dimensions'] = [
'#theme' => 'image',
'#uri' => '/core/themes/bartik/logo.svg',
'#alt' => 'Image lazy load testing image without dimensions',
'#prefix' => '<div id="without-dimensions">',
'#suffix' => '</div>',
];
$images['override-loading-attribute'] = [
'#theme' => 'image',
'#uri' => '/core/themes/bartik/logo.svg',
'#alt' => 'Image lazy load test loading attribute can be overridden',
'#prefix' => '<div id="override-loading-attribute">',
'#suffix' => '</div>',
'#width' => '50%',
'#height' => '50%',
];
$images['override-loading-attribute']['#attributes']['loading'] = 'eager';
return $images;
}
} |
// 预算与评分关系图 -xyt
var chartDom = document.getElementById('chart_budgetVote');
var myChart = echarts.init(chartDom);
var option;
function processData(data) {
return data.map(function (item) {
return {
value: [parseInt(item[1] / 1000000), parseFloat(item[2])],
name: item[0]
};
});
}
fetch('../static/json/budget_vote.json')
.then(function(response) {
return response.json();
})
.then(function(jsonData) {
var formattedData = processData(jsonData);
option = {
title: {
text: '预算与评分的关系',
left: 'center',
},
xAxis: {
type: 'value',
name: '预算(百万美元)',
nameLocation: 'middle',
nameGap: 30,
min: 0,
max: 300,
splitLine: {
show: false
}
},
yAxis: {
type: 'value',
name: '评分',
min: 2,
max: 10,
splitLine: {
show: false
}
},
series: [
{
name: '预算 vs 评分',
type: 'scatter',
symbolSize: 8,
data: formattedData,
emphasis: {
focus: 'series'
},
itemStyle: {
color: 'rgba(32,154,253,0.5)',
shadowBlur: 7,
shadowColor: 'rgba(33,56,227,0.5)',
shadowOffsetY: 0
}
}
]
};
// Use the configuration and data specified to show the chart.
myChart.setOption(option);
// 浏览器缩放时,图表也等比例缩放
window.addEventListener("resize", function () {
// 让我们的图表调用 resize这个方法
myChart.resize();
});
})
.catch(function(error) {
console.error('Error fetching or processing data:', error);
}); |
import React, { Suspense } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useAtomValue } from "jotai";
import { profileAtom } from "#/components/lib/jotai";
import {
Drawer,
Box,
Toolbar,
List,
ListSubheader,
Divider,
ListItemIcon,
ListItemText,
Typography,
} from "@mui/material";
import { styled } from "@mui/material/styles";
import ListItemButton, {
ListItemButtonProps,
} from "@mui/material/ListItemButton";
import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
import LoginRoundedIcon from "@mui/icons-material/LoginRounded";
import LogoutRoundedIcon from "@mui/icons-material/LogoutRounded";
import ConfirmationNumberRoundedIcon from "@mui/icons-material/ConfirmationNumberRounded";
import RoomRoundedIcon from "@mui/icons-material/RoomRounded";
import BadgeRoundedIcon from "@mui/icons-material/BadgeRounded";
import ExploreOffRoundedIcon from "@mui/icons-material/ExploreOffRounded";
import MapRoundedIcon from "@mui/icons-material/MapRounded";
import DvrIcon from "@mui/icons-material/Dvr";
import theme from "#/components/lib/theme";
import UserInfo from "#/components/block/UserInfo";
import Version from "#/components/block/Version";
const drawerWidth = localStorage.getItem("viewOnly") === "yes" ? 0 : 250;
const DrawerLeft: React.VFC = () => {
const path = useLocation().pathname;
const navigate = useNavigate();
const profile = useAtomValue(profileAtom);
const StyledListItemButton = styled(ListItemButton)<ListItemButtonProps>(
() => ({
margin: ".1rem .5rem",
borderRadius: theme.shape.borderRadius,
})
);
return (
<Drawer
sx={{
width: drawerWidth,
flexShrink: 0,
"& .MuiDrawer-paper": {
width: drawerWidth,
boxSizing: "border-box",
},
zIndex: 100,
}}
variant="permanent"
anchor="left"
>
<Toolbar>
<Typography
variant="h1"
sx={{ cursor: "pointer" }}
onClick={() => navigate("/", { replace: true })}
>
Gateway
</Typography>
</Toolbar>
<Divider />
<Box sx={{ p: 2 }}>
<Suspense fallback={<p>hey</p>}>
<UserInfo />
</Suspense>
</Box>
{profile && profile.available && (
<>
<Divider />
<List>
<StyledListItemButton
selected={path === "/"}
onClick={() => navigate("/")}
>
<ListItemIcon>
<HomeRoundedIcon />
</ListItemIcon>
<ListItemText primary="ホーム" />
</StyledListItemButton>
</List>
{["exhibit"].includes(profile.user_type) && (
<>
<List subheader={<ListSubheader>展示企画</ListSubheader>}>
<StyledListItemButton
selected={
path === `/exhibit/${profile.user_id || "unknown"}/enter`
}
onClick={() =>
navigate(`/exhibit/${profile.user_id || "unknown"}/enter`)
}
>
<ListItemIcon>
<LoginRoundedIcon />
</ListItemIcon>
<ListItemText primary="入室スキャン" />
</StyledListItemButton>
<StyledListItemButton
selected={
path === `/exhibit/${profile.user_id || "unknown"}/exit`
}
onClick={() =>
navigate(`/exhibit/${profile.user_id || "unknown"}/exit`)
}
>
<ListItemIcon>
<LogoutRoundedIcon />
</ListItemIcon>
<ListItemText primary="退室スキャン" />
</StyledListItemButton>
<StyledListItemButton
selected={
path ===
`/analytics/exhibit/${profile.user_id || "unknown"}`
}
onClick={() =>
navigate(
`/analytics/exhibit/${profile.user_id || "unknown"}`
)
}
>
<ListItemIcon>
<MapRoundedIcon />
</ListItemIcon>
<ListItemText primary="滞在状況" />
</StyledListItemButton>
</List>
</>
)}
{["moderator", "executive"].includes(profile.user_type) && (
<>
<List subheader={<ListSubheader>展示企画</ListSubheader>}>
<StyledListItemButton
selected={path === `/exhibit/`}
onClick={() => navigate(`/exhibit/`)}
>
<ListItemIcon>
<RoomRoundedIcon />
</ListItemIcon>
<ListItemText primary="展示選択" />
</StyledListItemButton>
</List>
<List subheader={<ListSubheader>エントランス</ListSubheader>}>
<StyledListItemButton
selected={
path === `/entrance/reserve-check` ||
path === `/entrance/enter`
}
onClick={() => navigate("/entrance/reserve-check")}
>
<ListItemIcon>
<LoginRoundedIcon />
</ListItemIcon>
<ListItemText primary="入場スキャン" />
</StyledListItemButton>
<StyledListItemButton
selected={path === `/entrance/exit`}
onClick={() => navigate("/entrance/exit")}
>
<ListItemIcon>
<LogoutRoundedIcon />
</ListItemIcon>
<ListItemText primary="退場スキャン" />
</StyledListItemButton>
<StyledListItemButton
selected={path === `/entrance/other-enter`}
onClick={() => navigate("/entrance/other-enter")}
>
<ListItemIcon>
<ConfirmationNumberRoundedIcon />
</ListItemIcon>
<ListItemText primary="特別入場" />
</StyledListItemButton>
</List>
</>
)}
{["moderator"].includes(profile.user_type) && (
<>
<List subheader={<ListSubheader>データ</ListSubheader>}>
<StyledListItemButton
selected={path === `/analytics`}
onClick={() => navigate("/analytics")}
>
<ListItemIcon>
<MapRoundedIcon />
</ListItemIcon>
<ListItemText primary="滞在状況" />
</StyledListItemButton>
<StyledListItemButton
selected={path === `/analytics/summary`}
onClick={() => navigate("/analytics/summary")}
>
<ListItemIcon>
<DvrIcon />
</ListItemIcon>
<ListItemText primary="展示一覧" />
</StyledListItemButton>
</List>
<List subheader={<ListSubheader>管理用操作</ListSubheader>}>
<StyledListItemButton
selected={path === `/admin/guest`}
onClick={() => navigate("/admin/guest")}
>
<ListItemIcon>
<BadgeRoundedIcon />
</ListItemIcon>
<ListItemText primary="ゲスト照会" />
</StyledListItemButton>
<StyledListItemButton
selected={path === `/admin/lost-wristband`}
onClick={() => navigate("/admin/lost-wristband")}
>
<ListItemIcon>
<ExploreOffRoundedIcon />
</ListItemIcon>
<ListItemText primary="紛失対応" />
</StyledListItemButton>
</List>
</>
)}
</>
)}
<Divider />
<Box sx={{ p: 2 }}>
<Version />
</Box>
</Drawer>
);
};
export default DrawerLeft; |
import React from "react";
import styled from "styled-components";
// styled components
import Title from "./StyledComponents/Title";
import Flex from "./StyledComponents/Flex";
import Button from "./StyledComponents/Button";
const Wrapper = styled.div`
width: 95%;
min-height: 10vh;
padding: 2rem;
margin: 0 auto;
background-color: #000000;
`;
const StyledComponent = () => {
return (
<Wrapper>
<Flex justify={"center"} align={"center"}>
<Title color={"white"} border={"1px solid #c7c4c4"} hover={"black"}>
Children automaticaly fill from props. And we can put some special
style values also from props.
</Title>
<Button primary color={"#a8a8ff"}>police</Button>
</Flex>
</Wrapper>
);
};
export default StyledComponent; |
const std = @import("std");
const simd = std.simd;
const Interval = @import("interval.zig");
const Vec = @This();
pub const Vec3 = @Vector(3, f64);
pub const z = Vec3{ 0, 0, 0 };
pub fn lensq(v: Vec3) f64 {
return v[0] * v[0] +
v[1] * v[1] +
v[2] * v[2];
}
pub fn len(v: Vec3) f64 {
return @sqrt(lensq(v));
}
pub fn dot(a: Vec3, b: Vec3) f64 {
return @reduce(.Add, a * b);
}
pub fn cross(a: Vec3, b: Vec3) Vec3 {
return Vec3{
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
};
}
pub fn dup(v: Vec3) Vec3 {
return Vec3{ v[0], v[1], v[2] };
}
pub fn unit(v: Vec3) Vec3 {
return v / sc(len(v));
}
pub fn sc(x: f64) Vec3 {
return @splat(x);
}
pub fn near_zero(v: Vec3) bool {
const e = sc(1e-8);
return 3 == std.simd.countTrues(@abs(v) < e);
}
pub fn reflect(v: Vec3, n: Vec3) Vec3 {
return v - sc(2 * dot(v, n)) * n;
}
pub fn refract(uv: Vec3, n: Vec3, eta2: f64) Vec3 {
const cos_theta = @min(dot(-uv, n), 1.0);
const r_out_perp = sc(eta2) * (uv + sc(cos_theta) * n);
const r_out_parallel = sc(-@sqrt(@abs(1.0 - lensq(r_out_perp)))) * n;
return r_out_perp + r_out_parallel;
}
fn linear_to_gamma(x: f64) f64 {
return if (x > 0) @sqrt(x) else 0;
}
fn real_color_to_byte(c: f64) u8 {
const r = Interval{ .min = 0, .max = 0.999 };
return @intFromFloat(256 * r.clamp(linear_to_gamma(c)));
}
pub fn print(rgb: Vec3, writer: anytype) !void {
const r: u8 = real_color_to_byte(rgb[0]);
const g: u8 = real_color_to_byte(rgb[1]);
const b: u8 = real_color_to_byte(rgb[2]);
try writer.print("{d} {d} {d}\n", .{ r, g, b });
} |
import { FC } from 'react';
import Button from '@mui/material/Button';
import MUIDialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import { DialogProps } from '@/src/types/modal/dialog';
import { Box } from '@mui/material';
const Dialog: FC<DialogProps> = ({
setOpen,
isOpen,
Trigger,
Content,
description,
cbOnSubscribe,
cbOnCancel,
title,
height,
width,
disableSubmitBtn,
}) => {
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
cbOnCancel?.();
setOpen(false);
};
const stylesOptions = () => {
const styles = Object.assign(
{},
{
minWidth: '100%',
minHeight: '100%',
}
) as { [key: string]: string };
if (height) {
styles.height = height;
}
if (width) {
styles.width = width;
}
return styles;
};
return (
<div>
<div onClick={handleClickOpen}>
<Trigger />
</div>
<MUIDialog open={isOpen} onClose={handleClose}>
<DialogTitle
sx={{
color: (theme) => theme.palette.secondary.main,
}}
>
{' '}
{title}{' '}
</DialogTitle>
<DialogContentText
sx={{
padding: '0 24px',
color: (theme) => theme.palette.secondary.light,
}}
>
{description}
</DialogContentText>
<DialogContent style={stylesOptions()}>
<Box component='article'>{Content}</Box>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancelar</Button>
<Button
onClick={cbOnSubscribe}
disabled={disableSubmitBtn}
variant='contained'
>
Enviar
</Button>
</DialogActions>
</MUIDialog>
</div>
);
};
export default Dialog; |
import API from "@/utils/API";
import Add from "./add";
import ImageView from "@/component/ImageView";
import Edit from "./edit";
import Delete from "./delete";
import axios from "axios";
type Galeri = {
id: number;
title: string;
image: string;
};
async function getGaleri() {
const res = await axios.get(API.API_URL + "/galeri");
return res.data.data;
}
export default async function Home() {
const data: Galeri[] = await getGaleri();
return (
<>
<h1 className="mb-4">Data Galeri</h1>
<Add />
<div>
<table className="table w-full">
<thead className="">
<tr>
<td>No</td>
<td>Title</td>
<td>Image</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{data.map((galeri, index) => (
<tr key={galeri.id}>
<td>{index + 1}</td>
<td>{galeri.title}</td>
<td>
<ImageView file={galeri.image} path="galeri" />
</td>
<td>
<div className="flex">
<Edit {...galeri} />
<Delete {...galeri} />
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</>
);
} |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract MyContract{
address public owner ;
// Constructor executed once
constructor() public{
owner = msg.sender ;
}
// state var
uint256 amountEth ;
// 2d Array
uint256[][] public myArr = [[1,3],[2,4],[7,8]];
uint256[] public numbers =[1,2,3,4,5,6,7,8,9,10,11];
// Creat new type
struct Holder{
string nameHolder ;
uint256 amountEth ;
}
// declare type created
Holder[] public holder ;
// Creat mapping var
mapping(uint => Holder) public idToHolder ;
// Nested mapping is map inside map
mapping(address => mapping(uint => Holder)) public myHold ;
// Store holders
function storeHolders(uint _id ,string memory _nameHolder, uint256 _amountEth) public{
idToHolder[_id] = Holder(_nameHolder,_amountEth);
}
function addhold (uint _id ,string memory _nameHolder, uint256 _amountEth) public {
myHold[msg.sender][_id] = Holder(_nameHolder,_amountEth);
}
function isEvenNumber(uint _number) public pure returns(bool){
if(_number % 2 == 0){
return true;
}
return false;
}
function countEven() public view returns (uint){
uint count = 0 ;
for(uint i = 0 ; i < numbers.length ;i++)
{
if(isEvenNumber(numbers[i])){
count += 1;
}
else{
count += 0;
}
}
return count ;
}
function isOwner() public view returns(bool){
return (msg.sender == owner);
}
} |
/*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* 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/.
*
*/
export function chunk<T>(array: T[], size: number): T[][];
export function chunk(array: Float32Array, size: number): Float32Array[];
export function chunk<T>(array: T[] | Float32Array, size: number) {
const chunks = [];
for (let index = 0, length = array.length; index < length; index += size) {
chunks.push(array.slice(index, index + size));
}
return chunks;
}
/**
* Gets all the values that are in array2 which are not in array1.
*
* @param array1 the base array
* @param array2 the array to compare with
* @param matcher a custom matching function in case referencial equality is not enough
* @returns the array containing values in array2 that are not in array1
*/
export const getDifference = <T>(array1: T[] = [], array2: T[] = [], matcher?: (t1: T, t2: T) => boolean): T[] => {
if (matcher) {
return array2.filter(el1 => !array1.some(el2 => matcher(el1, el2)));
}
return array2.filter(element => !array1.includes(element));
};
export const getNextItem = <T>(array: T[], currentItem: T): T | undefined => {
const currentIndex = array.indexOf(currentItem);
// couldn't find the item
if (currentIndex === -1) {
return undefined;
}
const nextIndex = currentIndex + 1;
// item is last item in the array
if (nextIndex === array.length) {
return currentIndex > 0 ? array[currentIndex - 1] : undefined;
}
return array[nextIndex];
};
/**
* Interpolates an array of numbers using linear interpolation
*
* @param array source
* @param length new length
* @returns new array with interpolated values
*/
export const interpolate = (array: number[], length: number) => {
const newArray = [];
const scaleFactor = (array.length - 1) / (length - 1);
newArray[0] = array[0];
newArray[length - 1] = array[array.length - 1];
for (let index = 1; index < length - 1; index++) {
const originalIndex = index * scaleFactor;
const before = Math.floor(originalIndex);
const after = Math.ceil(originalIndex);
const point = originalIndex - before;
newArray[index] = array[before] + (array[after] - array[before]) * point; // linear interpolation
}
return newArray;
};
export const isLastItem = <T>(array: T[], item: T) => array.indexOf(item) === array.length - 1;
export const iterateIndex = <T>(array: T, currentIndex: number, reverse = false): number | undefined => {
if (Array.isArray(array) && array.length && Number.isFinite(currentIndex)) {
if (reverse) {
const isZeroIndex = currentIndex === 0;
return isZeroIndex ? array.length - 1 : (currentIndex - 1) % array.length;
}
return (currentIndex + 1) % array.length;
}
return undefined;
};
export const iterateItem = <T>(array: T[], currentItem: T, reverse = false): T | undefined => {
if (Array.isArray(array) && array.length) {
const currentIndex = array.indexOf(currentItem);
// If item could not be found
const isNegativeIndex = currentIndex === -1;
return isNegativeIndex ? undefined : array[iterateIndex(array, currentIndex, reverse)];
}
return undefined;
};
/**
* Returns random element
* @param array source
* @returns random element
*/
export const randomElement = <T>(array: T[] = []) => array[Math.floor(Math.random() * array.length)];
export const deArrayify = <T>(value: T[] | T): T => (value instanceof Array ? value[0] : value);
export const uniquify = <T>(elements: T[]): T[] => Array.from(new Set<T>(elements));
export const flatten = <T>(arrays: T[][]): T[] => ([] as T[]).concat(...arrays);
export const partition = <T>(array: T[], condition: (element: T) => boolean): [T[], T[]] => {
const matching: T[] = [];
const notMatching: T[] = [];
array.forEach(element => {
if (condition(element)) {
matching.push(element);
} else {
notMatching.push(element);
}
});
return [matching, notMatching];
}; |
import * as React from "react";
import { useTheme } from "@mui/material/styles";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import { AppBar, Divider, Fade, makeStyles, Tooltip } from "@material-ui/core";
import clsx from "clsx";
import { drawerWidth } from "../../const/drawerOptions";
import Flexer from "../../../../../Elements/Layout/Container/Flexer";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import BuildIcon from "@mui/icons-material/Build";
import ExitToAppIcon from "@mui/icons-material/ExitToApp";
import { Link } from "react-router-dom";
const useStyles = makeStyles((theme) => ({
tooltip: {
backgroundColor: theme.palette.text.secondary,
color: "#ffffff",
fontSize: "13px",
},
appBar: {
backgroundColor: "#2e3b55",
zIndex: theme.zIndex.drawer + 1,
boxShadow: theme.shadows[1],
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
marginLeft: drawerWidth,
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
},
menu: {
"& .MuiPaper-root": {
borderRadius: 4,
minWidth: 120,
boxShadow:
"rgb(255, 255, 255) 0px 0px 0px 0px, rgba(0, 0, 0, 0.05) 0px 0px 0px 1px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.05) 0px 4px 6px -2px",
"& .MuiMenu-list": {
padding: 0,
},
"& .MuiMenuItem-root": {
fontSize: "0.9rem",
fontWeight: 500,
"& .MuiSvgIcon-root": {
fontSize: 12,
color: theme.palette.text.secondary,
marginRight: theme.spacing(1.5),
},
"&:active": {
backgroundColor: theme.palette.text.secondary,
},
},
},
},
}));
const builderOptions = [
{ label: "Element Set", value: "Element Set" },
{ label: "Component", value: "Component" },
{ label: "Page", value: "Page" },
{ label: "List", value: "List" },
{ label: "FAQ", value: "FAQ" },
{ label: "Card", value: "Card" },
{ label: "TaskList", value: "TaskList" },
{ label: "Table", value: "Table" },
];
export default function BuilderNavTopBar({
open,
handleDrawerOpen,
currentBuilder,
changeBuilder,
}) {
const theme = useTheme();
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const menuOpen = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const handleChange = (newBuilder) => {
changeBuilder(newBuilder);
handleClose();
};
return (
<AppBar
position="fixed"
open={open}
className={clsx(classes.appBar, {
[classes.appBarShift]: open,
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
sx={{
marginRight: 5,
...(open && { display: "none" }),
color: theme.palette.primary.light,
}}
>
<MenuIcon />
</IconButton>
<Flexer j="sb" style={{ marginRight: 16 }}>
<Typography
variant="h6"
align="center"
noWrap
component="div"
color="#F5F5F5"
>
{currentBuilder} Builder
</Typography>
<div style={{ marginRight: 8 }}>
<Tooltip
title={`Change Builder`}
placement="bottom"
classes={{ tooltip: classes.tooltip }}
>
<IconButton
disableRipple
color="inherit"
aria-label="open drawer"
onClick={handleClick}
sx={{
color: theme.palette.primary.light,
marginRight: 0.5,
}}
>
<BuildIcon />
</IconButton>
</Tooltip>
<Tooltip
title={`Exit to Site`}
placement="bottom"
classes={{ tooltip: classes.tooltip }}
>
<Link to="/">
<IconButton
color="inherit"
onClick={handleClick}
sx={{
color: theme.palette.primary.light,
marginLeft: 0.5,
}}
>
<ExitToAppIcon />
</IconButton>
</Link>
</Tooltip>
</div>
<Menu
className={classes.menu}
anchorEl={anchorEl}
open={menuOpen}
onClose={handleClose}
elevation={0}
getContentAnchorEl={null}
anchorOrigin={{
vertical: "bottom",
horizontal: "right",
}}
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
TransitionComponent={Fade}
>
{builderOptions.map((item) => (
<MenuItem
key={item.value}
divider
onClick={() => handleChange(item.value)}
disableRipple
selected={item.label === currentBuilder}
>
{item.label}
</MenuItem>
))}
</Menu>
</Flexer>
</Toolbar>
</AppBar>
);
} |
## @file
# @brief
# Implementation of the
# @ref DesignPatternExamples_python.memento.memento_exercise.Memento_Exercise "Memento_Exercise"()
# function as used in the @ref memento_pattern.
from io import StringIO
from .memento import IMemento, Memento_TextObject
## The list of memento objects that form a series of snapshots in time
# of a Memento_TextObject.
_mementoUndoList = [] # type: list[IMemento]
## Take a snapshot of the given text object associated with the name of
# given operation.
#
# @param text
# The Memento_TextObject to take a snapshot of.
# @param operation
# A string describing the operation that will be applied after the
# snapshot is taken.
def Memento_SaveForUndo(text : Memento_TextObject, operation : str) -> None:
memento = text.GetMemento(operation)
_mementoUndoList.append(memento)
## An operation to search and replace text in a Memento_TextObject.
#
# @param source
# The Memento_TextObject to affect.
# @param searchPattern
# What to look for in the Memento_TextObject.
# @param replaceText
# What to replace the searchPattern with.
def Memento_Operation_Replace(source : Memento_TextObject, searchPattern : str, replaceText : str) -> None:
source.SetText = source.Text.replace(searchPattern, replaceText)
## An operation to reverse the characters in the given Memento_TextObject.
#
# @param source
# The Memento_TextObject to affect.
def Memento_Operation_Reverse(source : Memento_TextObject) -> None:
output = StringIO()
text = source.Text
textLength = len(text)
for index in range(0, textLength):
output.write(text[textLength - 1 - index])
source.SetText = output.getvalue()
## Perform an undo on the given Command_TextObject, using the mementos in the
# "global" undo list. If the undo list is empty, nothing happens.
#
# @param text
# The Command_TextObject to affect.
def Memento_Undo(text : Memento_TextObject) -> None:
if _mementoUndoList:
lastMemento = _mementoUndoList.pop()
text.RestoreMemento(lastMemento)
# Show off what we (un)did.
print(" undoing operation {0:<31}: \"{1}\"".format(lastMemento.Name, text.ToString()))
## Helper function to replace a pattern with another string in the
# given Memento_TextObject after adding a snapshot of the text
# object to the undo list. Finally, it shows off what was done.
#
# @param text
# The Memento_TextObject to affect.
# @param searchPattern
# What to look for in the Memento_TextObject.
# @param replaceText
# What to replace the searchPattern with.
def Memento_ApplyReplaceOperation(text : Memento_TextObject, searchPattern : str, replaceText : str) -> None:
operationName = "Replace '{0}' with '{1}'".format(searchPattern, replaceText)
Memento_SaveForUndo(text, operationName)
Memento_Operation_Replace(text, searchPattern, replaceText)
print(" operation {0:<31}: \"{1}\"".format(operationName, text.ToString()))
## Helper function to reverse the order of the characters in the
# given Memento_TextObject after adding a snapshot of the text
# object to an undo list. Finally, it shows what was done.
#
# @param text
# The Memento_TextObject to affect.
def Memento_ApplyReverseOperation(text : Memento_TextObject) -> None:
operationName = "Reverse"
Memento_SaveForUndo(text, operationName)
Memento_Operation_Reverse(text)
print(" operation {0:<31}: \"{1}\"".format(operationName, text.ToString()))
## Example of using the @ref memento_pattern.
#
# In this exercise, the Memento pattern is used to take snapshots of
# a text object so as to form an undo list of changes to the text
# object. Undoing an operation means restoring a snapshot of the
# text object.
#
# The undo list is implemented as a stack of memento objects that
# each represent a snapshot of the text object taken before each
# operation is applied. After all operations are applied, the
# mementos are used to restore the text object in reverse order,
# effectively undoing each operation in turn.
#
# Compare this to the Command_Exercise() and note that the steps
# taken there are identical to here (except for method names, of
# course). The difference lies in how operations are executed
# and undone. Mementos make the undo process much cleaner and
# faster since operations do not need to be applied repeatedly to
# get the text object into a specific state. Specifically,
# compare Command_Undo() with Memento_Undo(). Also note the
# differences in the "Memento_ApplyXXOperation()" methods, which
# more cleanly separate the save from the operation.
# ! [Using Memento in Python]
def Memento_Exercise():
print()
print("Memento Exercise")
# Start with a fresh undo list.
_mementoUndoList.clear()
# The base text object to work from.
text = Memento_TextObject("This is a line of text on which to experiment.")
print(" Starting text: \"{0}\"".format(text.ToString()))
# Apply four operations to the text.
Memento_ApplyReplaceOperation(text, "text", "painting")
Memento_ApplyReplaceOperation(text, "on", "off")
Memento_ApplyReverseOperation(text)
Memento_ApplyReplaceOperation(text, "i", "!")
print(" Now perform undo until back to original")
# Now undo the four operations.
Memento_Undo(text)
Memento_Undo(text)
Memento_Undo(text)
Memento_Undo(text)
print(" Final text : \"{0}\"".format(text.ToString()))
print(" Done.")
# ! [Using Memento in Python] |
import os
import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
import statistics
from scipy.stats import weibull_min, weibull_max
from sklearn import preprocessing
import tensorflow as tf
from tensorflow.keras import initializers, regularizers
from tensorflow.keras import backend as k
from tensorflow.keras.layers import Input, multiply, Layer
from tensorflow.keras.regularizers import l2
from tensorflow.keras.optimizers import RMSprop, SGD, Adam
from tensorflow.keras.models import Model
from lifelines import KaplanMeierFitter
from lifelines.statistics import logrank_test
from lifelines.utils import concordance_index
# n:lambda a:kappa
def weib(x, a, n):
return (a / n) * (x / n) ** (a - 1) * np.exp(-((x / n) ** a))
# Loss function
def weibull_loglik_discrete(y_true, ab_pred, name=None):
y_ = y_true[:, 0]
u_ = y_true[:, 1]
a_ = ab_pred[:, 0]
b_ = ab_pred[:, 1]
hazard0 = k.pow((y_ + 1e-35) / a_, b_)
hazard1 = k.pow((y_ + 1) / a_, b_)
return -1 * k.mean(u_ * k.log(k.exp(hazard1 - hazard0) - 1.0) - hazard1)
def weibull_loglik_continuous(y_true, ab_pred, name=None):
y_ = y_true[:, 0]
u_ = y_true[:, 1]
a_ = ab_pred[:, 0]
b_ = ab_pred[:, 1] # death / live
ya = (y_ + 1e-35) / a_
return -1 * k.mean(u_ * (k.log(b_) + b_ * k.log(ya)) - k.pow(ya, b_))
def activate(ab):
a = k.exp(ab[:, 0])
b = k.softplus(ab[:, 1])
a = k.reshape(a, (k.shape(a)[0], 1))
b = k.reshape(b, (k.shape(b)[0], 1))
return k.concatenate((a, b), axis=1)
class Mil_Attention(Layer):
"""
# copy from https://github.com/utayao/Atten_Deep_MIL
Mil Attention Mechanism
This layer contains Mil Attention Mechanism
# Input Shape
2D tensor with shape: (batch_size, input_dim)
# Output Shape
2D tensor with shape: (1, units)
"""
def __init__(
self,
L_dim,
output_dim,
kernel_initializer="glorot_uniform",
kernel_regularizer=None,
use_bias=True,
use_gated=False,
**kwargs
):
self.L_dim = L_dim
self.output_dim = output_dim
self.use_bias = use_bias
self.use_gated = use_gated
self.v_init = initializers.get(kernel_initializer)
self.w_init = initializers.get(kernel_initializer)
self.u_init = initializers.get(kernel_initializer)
self.v_regularizer = regularizers.get(kernel_regularizer)
self.w_regularizer = regularizers.get(kernel_regularizer)
self.u_regularizer = regularizers.get(kernel_regularizer)
super(Mil_Attention, self).__init__(**kwargs)
def build(self, input_shape):
assert len(input_shape) == 2
input_dim = input_shape[1]
self.V = self.add_weight(
shape=(input_dim, self.L_dim),
initializer=self.v_init,
name="v",
regularizer=self.v_regularizer,
trainable=True,
)
self.w = self.add_weight(
shape=(self.L_dim, 1),
initializer=self.w_init,
name="w",
regularizer=self.w_regularizer,
trainable=True,
)
if self.use_gated:
self.U = self.add_weight(
shape=(input_dim, self.L_dim),
initializer=self.u_init,
name="U",
regularizer=self.u_regularizer,
trainable=True,
)
else:
self.U = None
self.input_built = True
def call(self, x, mask=None):
n, d = x.shape
ori_x = x
# do Vhk^T
x = k.tanh(k.dot(x, self.V)) # (2,64)
if self.use_gated: # no gate
gate_x = k.sigmoid(k.dot(ori_x, self.U))
ac_x = x * gate_x
else:
ac_x = x
# do w^T x
soft_x = k.dot(ac_x, self.w) # (2,64) * (64, 1) = (2,1)
alpha = k.softmax(k.transpose(soft_x)) # (2,1) #change
alpha = k.transpose(alpha)
return alpha
def compute_output_shape(self, input_shape):
shape = list(input_shape)
assert len(shape) == 2
shape[1] = self.output_dim
return tuple(shape)
def get_config(self):
config = {
"output_dim": self.output_dim,
"v_initializer": initializers.serialize(self.V.initializer),
"w_initializer": initializers.serialize(self.w.initializer),
"v_regularizer": regularizers.serialize(self.v_regularizer),
"w_regularizer": regularizers.serialize(self.w_regularizer),
"use_bias": self.use_bias,
}
base_config = super(Mil_Attention, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class Last_Sigmoid(Layer):
"""
Attention Activation
This layer contains a FC layer which only has one neural with sigmoid actiavtion
and MIL pooling. The input of this layer is instance features. Then we obtain
instance scores via this FC layer. And use MIL pooling to aggregate instance scores
into bag score that is the output of Score pooling layer.
This layer is used in mi-Net.
# Arguments
output_dim: Positive integer, dimensionality of the output space
kernel_initializer: Initializer of the `kernel` weights matrix
bias_initializer: Initializer of the `bias` weights
kernel_regularizer: Regularizer function applied to the `kernel` weights matrix
bias_regularizer: Regularizer function applied to the `bias` weights
use_bias: Boolean, whether use bias or not
pooling_mode: A string,
the mode of MIL pooling method, like 'max' (max pooling),
'ave' (average pooling), 'lse' (log-sum-exp pooling)
# Input shape
2D tensor with shape: (batch_size, input_dim)
# Output shape
2D tensor with shape: (1, units)
"""
def __init__(
self,
output_dim,
kernel_initializer="glorot_uniform",
bias_initializer="zeros",
kernel_regularizer=None,
bias_regularizer=None,
use_bias=True,
**kwargs
):
self.output_dim = output_dim
self.kernel_initializer = initializers.get(kernel_initializer)
self.bias_initializer = initializers.get(bias_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.use_bias = use_bias
super(Last_Sigmoid, self).__init__(**kwargs)
def build(self, input_shape):
assert len(input_shape) == 2
input_dim = input_shape[1]
self.kernel = self.add_weight(
shape=(input_dim, self.output_dim),
initializer=self.kernel_initializer,
name="kernel",
regularizer=self.kernel_regularizer,
)
if self.use_bias:
self.bias = self.add_weight(
shape=(self.output_dim,),
initializer=self.bias_initializer,
name="bias",
regularizer=self.bias_regularizer,
)
else:
self.bias = None
self.input_built = True
def activate(ab):
a = k.exp(ab[:, 0])
b = k.softplus(ab[:, 1])
a = k.reshape(a, (k.shape(a)[0], 1))
b = k.reshape(b, (k.shape(b)[0], 1))
return k.concatenate((a, b), axis=1)
def call(self, x, mask=None):
n, d = x.shape
x = k.sum(x, axis=0, keepdims=True)
# compute instance-level score
x = k.dot(x, self.kernel)
if self.use_bias:
x = k.bias_add(x, self.bias)
# sigmoid
out = activate(x) # change
return out
def compute_output_shape(self, input_shape):
shape = list(input_shape)
assert len(shape) == 2
shape[1] = self.output_dim
return tuple(shape)
def get_config(self):
config = {
"output_dim": self.output_dim,
"kernel_initializer": initializers.serialize(self.kernel.initializer),
"bias_initializer": initializers.serialize(self.bias_initializer),
"kernel_regularizer": regularizers.serialize(self.kernel_regularizer),
"bias_regularizer": regularizers.serialize(self.bias_regularizer),
"use_bias": self.use_bias,
}
base_config = super(Last_Sigmoid, self).get_config()
return dict(list(base_config.items()) + list(config.items())) |
import Box from "@mui/material/Box";
import Button, { ButtonProps } from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import { useTheme } from "@mui/material/styles";
import * as React from "react";
export interface LoadingButtonProps extends Omit<ButtonProps, "ref"> {
isLoading?: boolean;
}
export const LoadingButton: React.FC<LoadingButtonProps> = React.forwardRef<
HTMLButtonElement,
LoadingButtonProps
>(function RefLoadingButton({ isLoading, children, ...props }, ref) {
const theme = useTheme();
return (
<Button
ref={ref}
disabled={isLoading}
sx={{ position: "relative" }}
{...props}
>
<Box
sx={{
visibility: isLoading ? "hidden" : "visible",
}}
>
{children}
</Box>
{isLoading && (
<CircularProgress
size={24}
sx={{
position: "absolute",
top: "50%",
left: "50%",
marginTop: "-12px", // half of size
marginLeft: "-12px", // half of size
color: theme.palette.common.black,
}}
/>
)}
</Button>
);
}); |
// Copyright (c) 2003-2007, John Harrison. //
// Copyright (c) 2012 Eric Taucher, Jack Pappas, Anh-Dung Phan //
// (See "LICENSE.txt" for details.) //
// LCF-style basis for Tarski-style Hilbert system of first order logic. //
/// <summary>
/// LCF-style system for first order logic.
/// </summary>
///
/// <remarks>
/// Basic first order deductive system.
/// <p></p>
/// This is based on Tarski's trick for avoiding use of a substitution
/// primitive. It seems about the simplest possible system we could use.
/// </remarks>
///
/// <category index="7">Interactive theorem proving</category>
module Calculemus.Lcf
// if |- p ==> q and |- p then |- q
// if |- p then |- forall x. p
//
// |- p ==> (q ==> p)
// |- (p ==> q ==> r) ==> (p ==> q) ==> (p ==> r)
// |- ((p ==> false) ==> false) ==> p
// |- (forall x. p ==> q) ==> (forall x. p) ==> (forall x. q)
// |- p ==> forall x. p [x not free in p]
// |- exists x. x = t [x not free in t]
// |- t = t
// |- s1 = t1 ==> ... ==> sn = tn ==> f(s1,..,sn) = f(t1,..,tn)
// |- s1 = t1 ==> ... ==> sn = tn ==> P(s1,..,sn) ==> P(t1,..,tn)
// |- (p <=> q) ==> p ==> q
// |- (p <=> q) ==> q ==> p
// |- (p ==> q) ==> (q ==> p) ==> (p <=> q)
// |- true <=> (false ==> false)
// |- -p <=> (p ==> false)
// |- p /\ q <=> (p ==> q ==> false) ==> false
// |- p \/ q <=> -(-p /\ -q)
// |- (exists x. p) <=> -(forall x. -p)
open Calculemus.Lib.String
open Formulas
open Fol
open Equal
// ------------------------------------------------------------------------- //
// Auxiliary functions. //
// ------------------------------------------------------------------------- //
/// checks whether a term s occurs as a sub-term of another term t
let rec occurs_in s t =
s = t ||
match t with
| Var y -> false
| Fn (f, args) ->
List.exists (occurs_in s) args
/// checks whether a term t occurs free in a formula fm
let rec free_in t fm =
match fm with
| False | True -> false
| Not p -> free_in t p
| And (p, q) | Or (p, q)
| Imp (p, q) | Iff (p, q) -> free_in t p || free_in t q
| Forall (y, p)
| Exists (y, p) -> not (occurs_in (Var y) t) && free_in t p
| Atom (R (p, args)) -> List.exists (occurs_in t) args
/// The Core LCF proof system
///
/// The core proof system is the minimum set of inference rules and/or axioms
/// sound and complete with respect to the defined semantics.
[<AutoOpen>]
module ProofSystem =
(*************************************************************)
(* Core LCF proof system *)
(*************************************************************)
type thm = private Theorem of formula<fol>
/// modusponens (proper inference rule)
///
/// |- p -> q |- p ==> |- q
let modusponens (pq : thm) (Theorem p : thm) : thm =
match pq with
| Theorem (Imp (p', q)) when p = p' -> Theorem q
| _ -> failwith "modusponens"
/// generalization (proper inference rule)
///
/// |- p ==> !x. p
let gen x (Theorem p : thm) : thm =
Theorem (Forall (x, p))
/// |- p -> (q -> p)
let axiom_addimp p q : thm =
Theorem (Imp (p,Imp (q, p)))
/// |- (p -> q -> r) -> (p -> q) -> (p -> r)
let axiom_distribimp p q r : thm =
Theorem (Imp (Imp (p, Imp (q, r)), Imp (Imp (p, q), Imp (p, r))))
/// |- ((p -> ⊥) -> ⊥) -> p
let axiom_doubleneg p : thm =
Theorem (Imp (Imp (Imp (p, False), False), p))
/// |- (!x. p -> q) -> (!x. p) -> (!x. q)
let axiom_allimp x p q : thm =
Theorem (Imp (Forall (x, Imp (p, q)), Imp (Forall (x, p), Forall (x, q))))
/// |- p -> !x. p [provided x not in FV(p)]
let axiom_impall x p : thm =
if free_in (Var x) p then
failwith "axiom_impall: variable free in formula"
else
Theorem (Imp (p, Forall (x, p)))
/// |- (?x. x = t) [provided x not in FVT(t)]
let axiom_existseq x t : thm =
if occurs_in (Var x) t then
failwith "axiom_existseq: variable free in term"
else
Theorem (Exists (x, mk_eq (Var x) t))
/// |- t = t
let axiom_eqrefl t : thm =
Theorem (mk_eq t t)
/// |- s1 = t1 -> ... -> sn = tn -> f(s1, ..., sn) = f(t1, ..., tn)
let axiom_funcong f lefts rights : thm =
List.foldBack2 (fun s t (Theorem p) -> Theorem (Imp (mk_eq s t, p))) lefts rights
(Theorem (mk_eq (Fn (f, lefts)) (Fn (f, rights))))
/// |- s1 = t1 -> ... -> sn = tn -> f(s1, ..., sn) = f(t1, ..., tn)
let axiom_predcong p lefts rights : thm =
List.foldBack2 (fun s t (Theorem p) -> Theorem (Imp (mk_eq s t, p))) lefts rights
(Theorem (Imp (Atom (R (p, lefts)), Atom (R (p, rights)))))
(*************************************************************)
(* Definitions of other connectives *)
(*************************************************************)
/// |- (p <-> q) -> p -> q
let axiom_iffimp1 p q : thm =
Theorem (Imp (Iff (p, q), Imp (p, q)))
/// |- (p <-> q) -> q -> p
let axiom_iffimp2 p q : thm =
Theorem (Imp (Iff (p, q), Imp (q, p)))
/// |- (p -> q) -> (q -> p) -> (p <-> q)
let axiom_impiff p q : thm =
Theorem (Imp (Imp (p, q), Imp (Imp (q, p), Iff (p, q))))
/// |- ⊤ <-> (⊥ -> ⊥)
let axiom_true : thm =
Theorem (Iff (True, Imp (False, False)))
/// |- ~p <-> (p -> ⊥)
let axiom_not p : thm =
Theorem (Iff (Not p, Imp (p, False)))
/// |- p /\ q <-> (p -> q -> ⊥) -> ⊥
let axiom_and p q : thm =
Theorem (Iff (And (p, q), Imp (Imp (p, Imp (q, False)), False)))
/// |- p \/ q <-> ~(~p /\ ~q)
let axiom_or p q : thm =
Theorem (Iff (Or (p, q), Not (And (Not p, Not q))))
/// (?x. p) <-> ~(!x. ~p)
let axiom_exists x p : thm =
Theorem (Iff (Exists (x, p), Not (Forall (x, Not p))))
/// maps a theorem back to the formula that it proves
let concl (Theorem c : thm) : formula<fol> = c
// ------------------------------------------------------------------------- //
// A printer for theorems. //
// ------------------------------------------------------------------------- //
/// Prints a theorem using a TextWriter.
let fprint_thm sw th =
fprintf sw "|- " // write on the same line
fprint_formula sw (fprint_atom sw) (concl th)
/// A printer for theorems
let inline print_thm th = fprint_thm stdout th
/// Theorem to string
let inline sprint_thm th = writeToString (fun sw -> fprint_thm sw th) |
---
sidebar_custom_props:
icon: /img/connector_icons/salesloft.png
category: 'Sales engagement'
description: ''
---
# Salesloft
## Overview
**Category:** `engagement`
Supaglue uses the Salesloft v2 API.
| Feature | Available |
| ------------------------------------ | -------------- |
| Authentication (`oauth2`) | Yes |
| Managed syncs | Yes |
| Sync strategies | (listed below) |
| Unified API | Yes |
| Data invalidation | Yes |
| Real-time events | No |
| Passthrough API | Yes |
#### Supported common objects:
| Object | Soft delete supported | Sync strategy |
| ---------------- | --------------------- | ------------------- |
| Users | No\* | Full or Incremental |
| Accounts | No\* | Full or Incremental |
| Contacts | No\* | Full or Incremental |
| Emails | No\* | Full or Incremental |
| Sequences | Yes | Full or Incremental |
| Sequences States | No\* | Full or Incremental |
| Mailboxes | No\* | Full or Incremental |
[*] Soft deletes are supported if the sync strategy is "Full"
#### Supported standard objects:
N/A
#### Supported custom objects:
N/A
## Provider setup
To connect to your customers' Salesloft instances, you'll need to update the redirect URL to point to Supaglue and fetch the API access credentials in your [Salesloft developer account](https://developers.salesloft.com/).
### Add Redirect URL to your Salesloft developer app
Supaglue provides a redirect URL to send information to your app. To add the redirect URL to your new or existing Salesloft app:
1. Login to your Salesloft developer dashboard: <https://developers.salesloft.com/>
1. Navigate to Manage Apps, find your developer app in the OAuth Applications list, and click "Edit".

1. Update the redirect URI to point to Supaglue:
```
https://api.supaglue.io/oauth/callback
```
1. Click Save to update your changes.
### Fetch OAuth app credentials
1. Select your OAuth application again from the list view (not the edit button).
1. Copy the Application ID and Secret, and paste them into the Salesloft provider configuration form in the management portal, for client ID and client secret, respectively. |
import React from 'react'
import Produto from './Produto';
// Os links abaixo puxam dados de um produto em formato JSON
// https://ranekapi.origamid.dev/json/api/produto/tablet
// https://ranekapi.origamid.dev/json/api/produto/smartphone
// https://ranekapi.origamid.dev/json/api/produto/notebook
// Crie uma interface com 3 botões, um para cada produto.
// Ao clicar no botão faça um fetch a api e mostre os dados do produto na tela.
// Mostre apenas um produto por vez
// Mostre a mensagem carregando... enquanto o fetch é realizado
const App = () => {
const [dadosProduto, setDadosProduto] = React.useState(null)
const [loading, setLoading] = React.useState(null)
async function fetchProduto(event) {
setLoading(true)
await fetch(`https://ranekapi.origamid.dev/json/api/produto/${event.target.innerText}`)
.then((response) => response.json())
.then((data) => {
if(data) {
setDadosProduto(data)
}
})
.catch((error) => {
console.log(error)
})
.finally(() => {
setLoading(false)
})
}
return (
<React.Fragment>
<button onClick={fetchProduto}>tablet</button>
<button onClick={fetchProduto}>smartphone</button>
<button onClick={fetchProduto}>notebook</button>
{loading && <p>Carregando...</p>}
{!loading && dadosProduto && <Produto produto={dadosProduto}/>}
</React.Fragment>
)
};
export default App |
//local shortcuts
//third-party shortcuts
use serde::{Serialize, Deserialize};
//standard shortcuts
//-------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------
/// message from server
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct DemoServerResponse(pub u64);
/// message from client
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct DemoClientRequest(pub u64);
#[derive(Debug, Clone)]
pub struct DemoChannel;
impl bevy_simplenet::ChannelPack for DemoChannel
{
type ConnectMsg = ();
type ClientMsg = ();
type ClientRequest = DemoClientRequest;
type ServerMsg = ();
type ServerResponse = DemoServerResponse;
}
type _DemoServer = bevy_simplenet::Server<DemoChannel>;
type _DemoClient = bevy_simplenet::Client<DemoChannel>;
type DemoClientEvent = bevy_simplenet::ClientEventFrom<DemoChannel>;
type DemoServerEvent = bevy_simplenet::ServerEventFrom<DemoChannel>;
type DemoServerReport = bevy_simplenet::ServerReport<<DemoChannel as bevy_simplenet::ChannelPack>::ConnectMsg>;
fn server_demo_factory() -> bevy_simplenet::ServerFactory<DemoChannel>
{
bevy_simplenet::ServerFactory::<DemoChannel>::new("test")
}
fn client_demo_factory() -> bevy_simplenet::ClientFactory<DemoChannel>
{
bevy_simplenet::ClientFactory::<DemoChannel>::new("test")
}
//-------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------
#[test]
fn request_response()
{
// prepare tracing
/*
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_max_level(tracing::Level::TRACE)
.finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
*/
// prepare tokio runtimes for server and client
let server_runtime = enfync::builtin::native::TokioHandle::default();
let client_runtime = enfync::builtin::Handle::default();
// launch websocket server
let websocket_server = server_demo_factory().new_server(
server_runtime,
"127.0.0.1:0",
bevy_simplenet::AcceptorConfig::Default,
bevy_simplenet::Authenticator::None,
bevy_simplenet::ServerConfig::default(),
);
let websocket_url = websocket_server.url();
assert_eq!(websocket_server.num_connections(), 0u64);
// make client
let websocket_client = client_demo_factory().new_client(
client_runtime.clone(),
websocket_url.clone(),
bevy_simplenet::AuthRequest::None{ client_id: 44718u128 },
bevy_simplenet::ClientConfig::default(),
()
);
assert!(!websocket_client.is_dead());
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some((client_id, DemoServerEvent::Report(DemoServerReport::Connected(_, ())))) = websocket_server.next()
else { panic!("server should be connected once client is connected"); };
let Some(DemoClientEvent::Report(bevy_simplenet::ClientReport::Connected)) = websocket_client.next()
else { panic!("client should be connected to server"); };
assert_eq!(websocket_server.num_connections(), 1u64);
// send request: client -> server
let client_val = 42;
let signal = websocket_client.request(DemoClientRequest(client_val)).unwrap();
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Sending);
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some((
msg_client_id,
DemoServerEvent::Request(DemoClientRequest(msg_client_val), token)
)) = websocket_server.next()
else { panic!("server did not receive client msg"); };
assert_eq!(client_id, msg_client_id);
assert_eq!(client_id, token.client_id());
assert_eq!(signal.id(), token.request_id());
assert_eq!(client_val, msg_client_val);
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Waiting);
assert!(!token.destination_is_dead());
// send response: server -> client
let server_val = 24;
websocket_server.respond(token, DemoServerResponse(server_val)).unwrap();
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some(DemoClientEvent::Response(DemoServerResponse(msg_server_val), request_id)) = websocket_client.next()
else { panic!("client did not receive server msg"); };
assert_eq!(server_val, msg_server_val);
assert_eq!(signal.id(), request_id);
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Responded);
// no more outputs
let None = websocket_server.next()
else { panic!("server should receive no more connection reports"); };
let None = websocket_client.next()
else { panic!("client should receive no more values"); };
}
//-------------------------------------------------------------------------------------------------------------------
#[test]
fn request_ack()
{
// prepare tracing
/*
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_max_level(tracing::Level::TRACE)
.finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
*/
// prepare tokio runtimes for server and client
let server_runtime = enfync::builtin::native::TokioHandle::default();
let client_runtime = enfync::builtin::Handle::default();
// launch websocket server
let websocket_server = server_demo_factory().new_server(
server_runtime,
"127.0.0.1:0",
bevy_simplenet::AcceptorConfig::Default,
bevy_simplenet::Authenticator::None,
bevy_simplenet::ServerConfig::default(),
);
let websocket_url = websocket_server.url();
assert_eq!(websocket_server.num_connections(), 0u64);
// make client
let websocket_client = client_demo_factory().new_client(
client_runtime.clone(),
websocket_url.clone(),
bevy_simplenet::AuthRequest::None{ client_id: 44718u128 },
bevy_simplenet::ClientConfig::default(),
()
);
assert!(!websocket_client.is_dead());
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some((client_id, DemoServerEvent::Report(DemoServerReport::Connected(_, ())))) = websocket_server.next()
else { panic!("server should be connected once client is connected"); };
let Some(DemoClientEvent::Report(bevy_simplenet::ClientReport::Connected)) = websocket_client.next()
else { panic!("client should be connected to server"); };
assert_eq!(websocket_server.num_connections(), 1u64);
// send request: client -> server
let client_val = 42;
let signal = websocket_client.request(DemoClientRequest(client_val)).unwrap();
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Sending);
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some((
msg_client_id,
DemoServerEvent::Request(DemoClientRequest(msg_client_val), token)
)) = websocket_server.next()
else { panic!("server did not receive client msg"); };
assert_eq!(client_id, msg_client_id);
assert_eq!(client_id, token.client_id());
assert_eq!(signal.id(), token.request_id());
assert_eq!(client_val, msg_client_val);
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Waiting);
assert!(!token.destination_is_dead());
// send ack: server -> client
websocket_server.ack(token).unwrap();
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some(DemoClientEvent::Ack(request_id)) = websocket_client.next()
else { panic!("client did not receive server msg"); };
assert_eq!(signal.id(), request_id);
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Acknowledged);
// no more outputs
let None = websocket_server.next()
else { panic!("server should receive no more connection reports"); };
let None = websocket_client.next()
else { panic!("client should receive no more values"); };
}
//-------------------------------------------------------------------------------------------------------------------
#[test]
fn request_rejected()
{
// prepare tracing
/*
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_max_level(tracing::Level::TRACE)
.finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
*/
// prepare tokio runtimes for server and client
let server_runtime = enfync::builtin::native::TokioHandle::default();
let client_runtime = enfync::builtin::Handle::default();
// launch websocket server
let websocket_server = server_demo_factory().new_server(
server_runtime,
"127.0.0.1:0",
bevy_simplenet::AcceptorConfig::Default,
bevy_simplenet::Authenticator::None,
bevy_simplenet::ServerConfig::default(),
);
let websocket_url = websocket_server.url();
assert_eq!(websocket_server.num_connections(), 0u64);
// make client
let websocket_client = client_demo_factory().new_client(
client_runtime.clone(),
websocket_url.clone(),
bevy_simplenet::AuthRequest::None{ client_id: 44718u128 },
bevy_simplenet::ClientConfig::default(),
()
);
assert!(!websocket_client.is_dead());
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some((client_id, DemoServerEvent::Report(DemoServerReport::Connected(_, ())))) = websocket_server.next()
else { panic!("server should be connected once client is connected"); };
let Some(DemoClientEvent::Report(bevy_simplenet::ClientReport::Connected)) = websocket_client.next()
else { panic!("client should be connected to server"); };
assert_eq!(websocket_server.num_connections(), 1u64);
// send request: client -> server
let client_val = 42;
let signal = websocket_client.request(DemoClientRequest(client_val)).unwrap();
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Sending);
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some((
msg_client_id,
DemoServerEvent::Request(DemoClientRequest(msg_client_val), token)
)) = websocket_server.next()
else { panic!("server did not receive client msg"); };
assert_eq!(client_id, msg_client_id);
assert_eq!(client_id, token.client_id());
assert_eq!(signal.id(), token.request_id());
assert_eq!(client_val, msg_client_val);
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Waiting);
assert!(!token.destination_is_dead());
// reject
websocket_server.reject(token);
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some(DemoClientEvent::Reject(request_id)) = websocket_client.next()
else { panic!("client did not receive server msg"); };
assert_eq!(signal.id(), request_id);
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Rejected);
// no more outputs
let None = websocket_server.next()
else { panic!("server should receive no more connection reports"); };
let None = websocket_client.next()
else { panic!("client should receive no more values"); };
}
//-------------------------------------------------------------------------------------------------------------------
#[test]
fn request_dropped()
{
// prepare tracing
/*
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_max_level(tracing::Level::TRACE)
.finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
*/
// prepare tokio runtimes for server and client
let server_runtime = enfync::builtin::native::TokioHandle::default();
let client_runtime = enfync::builtin::Handle::default();
// launch websocket server
let websocket_server = server_demo_factory().new_server(
server_runtime,
"127.0.0.1:0",
bevy_simplenet::AcceptorConfig::Default,
bevy_simplenet::Authenticator::None,
bevy_simplenet::ServerConfig::default(),
);
let websocket_url = websocket_server.url();
assert_eq!(websocket_server.num_connections(), 0u64);
// make client
let websocket_client = client_demo_factory().new_client(
client_runtime.clone(),
websocket_url.clone(),
bevy_simplenet::AuthRequest::None{ client_id: 44718u128 },
bevy_simplenet::ClientConfig{
reconnect_on_disconnect : true,
reconnect_on_server_close : true, //we want client to reconnect but fail to get response
..Default::default()
},
()
);
assert!(!websocket_client.is_dead());
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some((client_id, DemoServerEvent::Report(DemoServerReport::Connected(_, ())))) = websocket_server.next()
else { panic!("server should be connected once client is connected"); };
let Some(DemoClientEvent::Report(bevy_simplenet::ClientReport::Connected)) = websocket_client.next()
else { panic!("client should be connected to server"); };
assert_eq!(websocket_server.num_connections(), 1u64);
// send request: client -> server
let client_val = 42;
let signal = websocket_client.request(DemoClientRequest(client_val)).unwrap();
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Sending);
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some((
msg_client_id,
DemoServerEvent::Request(DemoClientRequest(msg_client_val), token)
)) = websocket_server.next()
else { panic!("server did not receive client msg"); };
assert_eq!(client_id, msg_client_id);
assert_eq!(client_id, token.client_id());
assert_eq!(signal.id(), token.request_id());
assert_eq!(client_val, msg_client_val);
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::Waiting);
assert!(!token.destination_is_dead());
// server closes client
let closure_frame =
ezsockets::CloseFrame{
code : ezsockets::CloseCode::Normal,
reason : String::from("test")
};
websocket_server.close_session(client_id, closure_frame).unwrap();
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
let Some(DemoClientEvent::Report(bevy_simplenet::ClientReport::ClosedByServer(_))) = websocket_client.next()
else { panic!("client should be closed by server"); };
let Some((dc_client_id, DemoServerEvent::Report(DemoServerReport::Disconnected))) = websocket_server.next()
else { panic!("server should be disconnected after client is disconnected (by server)"); };
assert_eq!(client_id, dc_client_id);
// client auto-reconnects
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
// request has updated
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
assert!(token.destination_is_dead());
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::ResponseLost);
// receive response lost
let Some(DemoClientEvent::ResponseLost(request_id)) = websocket_client.next()
else { panic!("client did not receive server msg"); };
assert_eq!(signal.id(), request_id);
// client receives connection report
let Some((_, DemoServerEvent::Report(DemoServerReport::Connected(_, ())))) = websocket_server.next()
else { panic!("server should be connected once client is connected"); };
let Some(DemoClientEvent::Report(bevy_simplenet::ClientReport::Connected)) = websocket_client.next()
else { panic!("client should be connected to server"); };
assert_eq!(websocket_server.num_connections(), 1u64);
// try to acknowledge the token (nothing should happen since the original target session was replaced)
websocket_server.ack(token).unwrap();
std::thread::sleep(std::time::Duration::from_millis(25)); //wait for async machinery
assert_eq!(signal.status(), bevy_simplenet::RequestStatus::ResponseLost);
// no more outputs
let None = websocket_server.next()
else { panic!("server should receive no more connection reports"); };
let None = websocket_client.next()
else { panic!("client should receive no more values"); };
}
//------------------------------------------------------------------------------------------------------------------- |
#!/usr/bin/env node
const PROCESS = require('process');
const READLINE = require('readline');
const { Client } = require('pg');
require('dotenv').config();
function logAndExit(err) {
console.log(err);
process.exit(1);
};
class ExpenseData {
constructor() {
this.client = new Client({ database: 'expense_project' });
}
async listExpenses() {
await this.client.connect().catch(err => logAndExit(err));
await this.setupSchema().catch(err => logAndExit(err));
let res = await this.client.query("SELECT * FROM expenses ORDER BY created_on ASC")
.catch(err => logAndExit(err));
if (res.rowCount === 0) {
console.log('No expenses added yet');
} else {
this.displayCount(res.rowCount);
this.displayExpenses(res);
if (res.rowCount > 1) this.displayTotal(res);
}
await this.client.end().catch(err => logAndExit(err));
}
async addExpense(amount, memo) {
await this.client.connect().catch(err => logAndExit(err));
await this.setupSchema().catch(err => logAndExit(err));
let date = new Date();
date = date.toLocaleDateString();
let queryText = 'INSERT INTO expenses (amount, memo, created_on) VALUES ($1, $2, $3)';
let queryValues = [amount, memo, date];
await this.client.query(queryText, queryValues).catch(err => logAndExit(err));
await this.client.end().catch(err => logAndExit(err));
}
async searchExpenses(searchTerm) {
await this.client.connect().catch(err => logAndExit(err));
await this.setupSchema().catch(err => logAndExit(err));
let res = await this.client.query(`SELECT * FROM expenses
WHERE memo ILIKE $1`, [`%${searchTerm}%`]).catch(err => logAndExit(err));
if (res.rowCount === 0) {
console.log('No expenses to search for');
} else {
this.displayCount(rowCount);
this.displayExpenses(res);
if (res.rowCount > 1) this.displayTotal(res);
}
await this.client.end().catch(err => logAndExit(err));
}
async deleteExpense(id) {
await this.client.connect().catch(err => logAndExit(err));
await this.setupSchema().catch(err => logAndExit(err));
let res = await this.client.query(`SELECT * FROM expenses
WHERE id = $1`, [id]).catch(err => logAndExit(err));
if (res.rowCount === 1) {
await this.client.query(`DELETE FROM expenses
WHERE id = $1`, [id]).catch(err => logAndExit(err));
console.log('The following expense has been deleted:');
this.displayExpenses(res.rows);
} else {
console.log(`There is no expense with the id ${id}`);
}
await this.client.end().catch(err => logAndExit(err));
}
async deleteAllExpenses() {
await this.client.connect().catch(err => logAndExit(err));
await this.setupSchema().catch(err => logAndExit(err));
await this.client.query(`DELETE FROM expenses`).catch(err => logAndExit(err));
console.log('All expenses have been deleted');
await this.client.end().catch(err => logAndExit(err));
}
async setupSchema() {
let tableExistsQuery = `SELECT COUNT(*) FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'expenses'`;
let tableCreationQuery = `
CREATE TABLE expenses (
id serial PRIMARY KEY,
amount numeric NOT NULL CHECK(amount > 0.01),
memo text NOT NULL,
created_on date NOT NULL
);`
let res = await this.client.query(tableExistsQuery).catch(err => logAndExit(err));
if (res.rows[0].count === '0') {
await this.client.query(tableCreationQuery).catch(err => logAndExit(err));
}
}
displayExpenses(res) {
res.rows.forEach(tuple => {
let columns = [
`${tuple.id}`.padStart(3),
tuple.created_on.toDateString().padStart(10),
tuple.amount.padStart(12),
tuple.memo
];
console.log(columns.join(' | '));
});
}
displayCount(rowCount) {
if (rowCount === 0) {
console.log('There are no expenses');
} else if (rowCount === 1) {
console.log(`There is ${rowCount} expense`);
} else {
console.log(`There are ${rowCount} expenses`);
}
}
displayTotal(res) {
let total = res.rows.reduce((acc, tuple) => {
acc += Number(tuple.amount);
return acc;
}, 0);
console.log('-'.repeat(45));
console.log('Total', String(total.toFixed(2)).padStart(30));
}
}
class CLI {
constructor() {
this.application = new ExpenseData();
}
static HELP() {
return `An expense recording system
Commands:
add AMOUNT MEMO [DATE] - record a new expense
clear - delete all expenses
list - list all expenses
delete NUMBER - remove expense with id NUMBER
search QUERY - list expenses with a matching memo field`;
}
displayHelp() {
console.log(CLI.HELP());
}
run(args) {
let command = args[2];
if (command === 'list') {
this.application.listExpenses();
} else if (command === 'add') {
let amount = args[3];
let memo = args[4];
if (amount && memo) {
this.application.addExpense(amount, memo);
} else {
console.log('You must provide an amount and memo.')
}
} else if (command === 'search') {
this.application.searchExpenses(args[3]);
} else if (command === 'delete') {
this.application.deleteExpense(args[3]);
} else if (command === 'clear') {
let rl = READLINE.createInterface({
input: process.stdin,
output: process.stdout
});
let questionText = 'This will remove all expenses. Are you sure? (y/n) ';
rl.question(questionText, (answer) => {
if (answer === 'y') {
this.application.deleteAllExpenses();
}
rl.close();
});
} else {
this.displayHelp();
}
}
}
let cli = new CLI();
cli.run(PROCESS.argv); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.