text
stringlengths 184
4.48M
|
---|
package com.dublikunt.nclient.components;
import androidx.appcompat.app.AppCompatActivity;
public abstract class ThreadAsyncTask<Params, Progress, Result> {
private final AppCompatActivity activity;
private Thread thread;
public ThreadAsyncTask(AppCompatActivity activity) {
this.activity = activity;
}
public void execute(Params... params) {
thread = new AsyncThread(params);
thread.start();
}
protected void onPreExecute() {
}
protected void onPostExecute(Result result) {
}
protected void onProgressUpdate(Progress... values) {
}
protected abstract Result doInBackground(Params... params);
protected final void publishProgress(Progress... values) {
if (!activity.isDestroyed())
activity.runOnUiThread(() -> onProgressUpdate(values));
}
class AsyncThread extends Thread {
Params[] params;
AsyncThread(Params[] params) {
this.params = params;
}
@Override
public void run() {
if (!activity.isDestroyed())
activity.runOnUiThread(ThreadAsyncTask.this::onPreExecute);
Result result = doInBackground(params);
if (!activity.isDestroyed())
activity.runOnUiThread(() -> onPostExecute(result));
}
}
} |
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<title>Exercice 4</title>
</head>
<body>
<div class="container-fluid">
<div class="row justify-content-center text-center">
<div class="col-3">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">La Manu Le Havre</h5>
<p class="card-text">L'รcole des mรฉtiers du Numรฉrique</p>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">+
d'infos</button>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">La Manu Le Havre</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body bg-primary text-white">
https://lamanu.fr/le-havre
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous">
</script>
</body>
</html> |
import React, { useState } from "react";
import Footer from "../../components/footer/Footer";
import Navbar from "../../components/navbar/Navbar";
import "../../components/footer/Footer.css";
import "../../components/navbar/Navbar.css";
import GetProductFamily from "../../components/utils/GetProductFamily";
import ProductCard from "../../components/product_card/product_card";
import api_product_getAll from "../../api/product/api_product_getAll";
import api_product_getWeightPricesByProductName from "../../api/product/api_product_getWeightPricesByProductName";
import api_product_getFlavorQuantitiesByProductName from "../../api/product/api_product_getFlavorQuantitiesByProductName";
export default function HomePage(props) {
const [prodsHtml, setProdsHtml] = useState(null)
var prods = []
async function GetProductCards() {
if (prodsHtml != null)
return
var pdcts = await api_product_getAll()
if (pdcts != null && pdcts.length >= 8) {
var shuffled = [...pdcts].sort(() => 0.5 - Math.random());
pdcts = shuffled.slice(0, 8)
for (var j = 0; j < pdcts.length; j++) {
var weightPrices = await api_product_getWeightPricesByProductName(pdcts[j].name)
var flavorQuantities = await api_product_getFlavorQuantitiesByProductName(pdcts[j].name)
pdcts[j].weight_price = weightPrices
pdcts[j].flavor_quantity = flavorQuantities
prods.push(pdcts[j])
}
const returnable = prods.map((item) => (
<div key={item.name}> <ProductCard productTitle={item.name} price={item.weight_price[0].price}/> </div>
))
setProdsHtml(returnable)
}
}
GetProductCards()
return(
<div className="content">
<div className="navbar">
<Navbar GetProductFamily={ GetProductFamily }/>
</div>
<div className="spotlight">
<img src={require("../../images/spotlight-3.png")} alt="site-logo" height="600"></img>
</div>
<div className="products-section">
{ prodsHtml }
</div>
<div className="footer">
<Footer/>
</div>
</div>
)
} |
import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import '../../index.css'
import Protected from '../Protected'
const Projects = () => {
const [projects, setProjects] = useState([])
useEffect(() => {
const fetchProjects = async () => {
try {
const res = await fetch('http://localhost:8080/project/fetch', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
})
const data = await res.json()
setProjects(data.projects)
} catch (error) {
throw new Error(error)
}
}
fetchProjects()
}, [])
return (
<Protected>
<div className='main_container'>
<div className='projects_container'>
<h1 className=''> Liste des projets </h1>
<div >
{projects?.map(({ _id, title }) => (
<div key={_id}>
{'>'}<Link to={`/projects/${_id}`}>{title}</Link>
</div>
))}
</div>
<Link to={`/newProject`} className="blue_btn">Nouveau projet</Link>
</div>
</div>
</Protected>
)
}
export default Projects |
pragma solidity ^0.5.3;
import "./Date.sol";
contract Project{
uint256 public Date = 0;
uint256 public payOfflimit = 0;
address payable public walletXYZ = msg.sender;
Employee[] public employees;
mapping(string=>uint256) public jobSchedule;
mapping(string=>uint256) public jobSchedule2;
modifier onlyXYZ(){
require(msg.sender == walletXYZ);
_;
}
modifier OnlyAfter6{
require(getHour(now)>16);
_;
}
struct Employee{
address payable eadress;
string name;
}
function employeeGetName(uint256 index)public payable returns(string memory) {
return employees[index].name;
}
function employeeGetAddress(uint256 index) public payable returns(address payable){
return employees[index].eadress;
}
function addEmployee(string memory _name, address payable _eadress) public onlyXYZ{
require(chechIfExists(_eadress)==false);
employees.push(Employee( _eadress, _name));
}
function popEmployee(address payable _eadress) public onlyXYZ{
require(chechIfExists(_eadress)==true);
for(uint256 i = 0; i<=employees.length; i++){
if(_eadress==employeeGetAddress(i)){
employees[i] = employees[employees.length - 1];
delete employees[employees.length - 1];
employees.length--;
}
}
}
function chechIfExists(address payable addr) public returns(bool){
uint256 lengthOf = employees.length;
for(uint256 i = 0;i<lengthOf;i++){
if(employees[i].eadress == addr){
return true;
}
}
return false;
}
function sendXYZ(address payable _walletXYZ) public payable{
uint256 value = msg.value;
require(value<100 ether);
walletXYZ = _walletXYZ;
walletXYZ.transfer(msg.value);
}
function sendSalary(uint256 index) public payable onlyXYZ{
employeeGetAddress(index).transfer(msg.value);
}
function sendToEveryone(uint256 value) public payable{
uint256 lengthOf = employees.length;
for(uint256 i = 0; i<lengthOf; i++){
Employee memory employee = employees[i];
address payable addres = employee.eadress;
addres.transfer(value*1000000000000000000);
}
}
function enterStart(string memory _name, uint _hour) public returns(uint){
jobSchedule[_name] = _hour;
return _hour;
}
function enterEnd(string memory _name, uint _hour) public returns(uint){
jobSchedule2[_name] = _hour;
return _hour;
}
function getHour(uint timestamp) internal pure returns (uint hour) {
hour = BokkyPooBahsDateTimeLibrary.getHour(timestamp);
}
/*function calculateSalary(string memory _name)public view returns(uint256){
uint256 salary = (jobSchedule2[_name]-jobSchedule[_name])*0.5 ether;
return salary;
}*/
function calculateSalary(uint256 index)public returns(uint256){
uint256 salary = (jobSchedule2[employeeGetName(index)]-jobSchedule[employeeGetName(index)])*0.5 ether;
return salary;
}
function getYear(uint timestamp) public pure returns (uint year) {
year = BokkyPooBahsDateTimeLibrary.getYear(timestamp);
}
function getMonth(uint timestamp) public pure returns (uint month) {
month = BokkyPooBahsDateTimeLibrary.getMonth(timestamp);
}
function getDay(uint timestamp) public pure returns (uint day) {
day = BokkyPooBahsDateTimeLibrary.getDay(timestamp);
}
function checkDay() public{
if(getDay(Date)==getDay(now)&&getYear(Date)==getYear(now)&&getMonth(Date)==getMonth(now)){
payOfflimit = 1;
}
}
/* function payOff(string memory _name) public payable OnlyAfter6{
if(Date != 0){
checkDay();
}
require(payOfflimit == 0);
uint256 lengthOf = employees.length;
for(uint256 i = 0; i<lengthOf; i++){
if( keccak256(abi.encodePacked(_name)) == keccak256(abi.encodePacked(employeeGetName(i)))){
Employee memory employee = employees[i];
address payable addres = employee.eadress;
addres.transfer(calculateSalary(_name));
}
}
Date = block.timestamp;
}
*/
function payOff() public payable OnlyAfter6{
if(Date != 0){
checkDay();
}
require(payOfflimit == 0);
uint256 lengthOf = employees.length;
for(uint256 i = 0; i<lengthOf; i++){
Employee memory employee = employees[i];
address payable addres = employee.eadress;
addres.transfer(calculateSalary(i));
}
Date = block.timestamp;
}
function depositToContract(uint256 value, address payable addr) public payable{
require(msg.value==value*1 ether);
addr.transfer(msg.value-(value*1000000000000000000));
}
/*function sendToContract(address payable addr) payable public{
addr.transfer(msg.value);
}*/
function getBalance(address addr) public view returns(uint256){
return addr.balance;
}
} |
/**
* React component that renders the dashboard of the application.
* @author Michael Imerman and Kaushal Patel
* @version 1.0
* @return {Element} JSX - Returns the JSX element that renders the dashboard
*/
import React, { useState, useEffect } from 'react';
import { useLocation } from "react-router-dom";
import io from 'socket.io-client';
import MessageBox from "../dashboard_components/MessageBox.js";
import AppName from "../dashboard_components/AppName.js";
import UserName from "../dashboard_components/UserName.js";
import ChatLists from "../dashboard_components/ChatLists.js";
import MessageList from "../dashboard_components/MessageList.js";
// Connect to the socket server
const socket = io('http://localhost:5000');
/**
* Dashboard component
* @returns {Element} Dashboard component
*/
function Dashboard() {
// Use the location hook to get the user id
const location = useLocation();
// Get the user id from the location state
const clientId = location.state.userId;
// Set the client id
const [client, setClient] = useState("");
// Called on every render
useEffect(() => {
// Set the client id
setClient(clientId);
// Register user on the backend
//console.log("Connected");
// Room name is the user id
const roomName = client;
//console.log("Room ID: " + roomName);
// Join the room with the user id
socket.emit('connection', roomName);
});
return (
<div className={"grid grid-cols-5 grid-rows-7 gap-2 h-screen w-screen bg-gray-300"}>
<div className={"flex items-center justify-center h-full w-full bg-gray-200"}>
<AppName></AppName>
</div>
<div className={"col-span-4 flex items-center justify-center h-full w-full bg-gray-200"}>
<UserName></UserName>
</div>
<div className={"row-span-6 col-start-1 row-start-2 flex-wrap justify-center h-full" +
" w-full bg-gray-200"}>
<ChatLists client={client}></ChatLists>
</div>
<div className={"col-span-4 row-span-5 col-start-2 row-start-2 flex items-center justify-center h-full w-full bg-gray-200"}>
<MessageList sender={client}></MessageList>
</div>
<div className={"col-span-4 col-start-2 row-start-7 flex items-center justify-center h-full w-full bg-gray-200"}>
<MessageBox sender={client}></MessageBox>
</div>
</div>
);
}
export default Dashboard; |
---
description: ์ปจํ
์ธ ํจํค์ง์ ์น์ ํตํด ์ฌ์ํ ๋น๋์ค ์ปจํ
์ธ ๋ฅผ ์ค๋นํ๋ ํ๋ก์ธ์ค์
๋๋ค. ํจํค์ง์๋ ์์ ๋น๋์ค๋ฅผ ๋งค๋ํ์คํธ ํ์ผ๋ก ๋ณํํ๊ณ , ์ ํ์ ์ผ๋ก ์๋ก ๋ค๋ฅธ ์ฅ์น ๋ฐ ๋ธ๋ผ์ฐ์ ์ ๋ํด ์๋ก ๋ค๋ฅธ DRM ์๋ฃจ์
์ ์ฌ์ฉํ์ฌ ์ฝํ
์ธ ๋ฅผ ์ํธํํ๋ ์์
์ด ํฌํจ๋ฉ๋๋ค.
title: ์ฝํ
์ธ ํจํค์ง
source-git-commit: 02ebc3548a254b2a6554f1ab34afbb3ea5f09bb8
workflow-type: tm+mt
source-wordcount: '561'
ht-degree: 0%
---
# ์ฝํ
์ธ ํจํค์ง {#package-your-content}
์ปจํ
์ธ ํจํค์ง์ ์น์ ํตํด ์ฌ์ํ ๋น๋์ค ์ปจํ
์ธ ๋ฅผ ์ค๋นํ๋ ํ๋ก์ธ์ค์
๋๋ค. ํจํค์ง์๋ ์์ ๋น๋์ค๋ฅผ ๋งค๋ํ์คํธ ํ์ผ๋ก ๋ณํํ๊ณ , ์ ํ์ ์ผ๋ก ์๋ก ๋ค๋ฅธ ์ฅ์น ๋ฐ ๋ธ๋ผ์ฐ์ ์ ๋ํด ์๋ก ๋ค๋ฅธ DRM ์๋ฃจ์
์ ์ฌ์ฉํ์ฌ ์ฝํ
์ธ ๋ฅผ ์ํธํํ๋ ์์
์ด ํฌํจ๋ฉ๋๋ค.
์ฝํ
์ธ ๋ฅผ ์ค๋นํ๋ ค๋ฉด ์คํ๋ผ์ธ ํจํค์ง Adobe ๋๋ ExpressPlay์ Bento4 ํจํค์ง ํ๋ก๊ทธ๋จ๊ณผ ๊ฐ์ ๊ธฐํ ๋๊ตฌ๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค. ํจํค์ ๋ ๋ ๋ค ์ฌ์์ ์ํด ๋น๋์ค๋ฅผ ์ค๋นํ๊ณ (์: ์๋ณธ ํ์ผ์ ์กฐ๊ฐํํ์ฌ ๋งค๋ํ์คํธ์ ๋ฃ๊ธฐ) ์ ํํ DRM ์๋ฃจ์
(PlayReady, Widevine, FairPlay, Access ๋ฑ)์ผ๋ก ๋น๋์ค๋ฅผ ๋ณดํธํฉ๋๋ค.:
* [Adobe ์คํ๋ผ์ธ ํจํค์ง](https://helpx.adobe.com/content/dam/help/en/primetime/guides/offline_packager_getting_started.pdf)
* [์ต์คํ๋ ์คํ๋ ์ด ํจ์ปค์ ](https://www.expressplay.com/developer/packaging-tools/)
<!--<a id="fig_jbn_fw5_xw"></a>-->

1. ์ค์ ์ ํ
์คํธํ๋ ๋ฐ ์ฌ์ฉํ ์ฝํ
์ธ ๋ฅผ ํจํค์งํ๊ฑฐ๋ ๊ฐ์ ธ์ต๋๋ค.
ํจํค์ง์ ๋ํด ๊ธฐ์ตํด์ผ ํ ์ค์ํ ์ฌํญ ์ค ํ๋๋ ์ด ํจํค์ง ๋จ๊ณ์์ ์ฌ์ฉํ๋ ํค ID(์ฝํ
์ธ ID)๊ฐ ํ์ ๋ผ์ด์ ์ค ํ ํฐ ์์ฒญ์์ ์ ๊ณตํด์ผ ํ๋ ID์ ๋์ผํ๋ค๋ ๊ฒ์
๋๋ค. Key ID๋ CEK๋ฅผ ์๋ณํ๋ ์ ์ผํ ํญ๋ชฉ์
๋๋ค(์์ฒด ํค ๊ด๋ฆฌ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅ๋๊ฑฐ๋ [ExpressPlay์ ์ฃผ์ ์คํ ๋ฆฌ์ง ์๋น์ค](https://www.expressplay.com/developer/key-storage/).
>[!NOTE]
>
>Adobe ์ก์ธ์ค์ ์ต์ํ ์ฌ์ฉ์์ ๊ฒฝ์ฐ, ์ด๋ ๋ค์ํ ์๋ฃจ์
์ด ์๋ํ๋ ๋ฐฉ์์ ์์ด ์ค์ํ ์ฐจ์ด์ ์
๋๋ค. Access์์ ๋ผ์ด์ ์ค ํค๋ DRM ๋ฉํ๋ฐ์ดํฐ์ ํฌํจ๋์ด ์์ผ๋ฉฐ ๋ณดํธ๋ ์ฝํ
์ธ ์ ํจ๊ป ์๋ค๋ก ์ ๋ฌ๋ฉ๋๋ค. ์ฌ๊ธฐ์ ์ค๋ช
๋ ๋ค์ค DRM ์์คํ
์์๋ ์ค์ ๋ผ์ด์ ์ค๊ฐ ์ ๋ฌ๋์ง ์๊ณ ์์ ํ๊ฒ ์ ์ฅ๋๋ฉฐ ํค ID๋ฅผ ํตํด ํ๋๋ฉ๋๋ค.
<!--<a id="example_52AF76B730174B79B6088280FCDF126D"></a>-->
๋ค์์ Widevine์ฉ Offline Packager Adobe ๋ฅผ ์ฌ์ฉํ๋ ํจํค์ง ์์
๋๋ค. Packager๋ ๊ตฌ์ฑ ํ์ผ(์: [!DNL widevine.xml])๋ฅผ ์กฐ์ ํ ๋ ์ ์ฉํฉ๋๋ค.
```
<config>
<in_path>sample.mp4</in_path>
<out_type>dash</out_type>
<out_path>dash2</out_path>
<drm/>
<drm_sys>widevine</drm_sys>
<frag_dur>4</frag_dur>
<target_dur>6</target_dur>
<key_file_path>keyfile.bin</key_file_path>
<widevine_content_id>2a</widevine_content_id>
<widevine_provider>intertrust</widevine_provider>
<widevine_key_id>7debe705d938c76bfd886f077b8fa5f7</widevine_key_id>
</config>
```
* `in_path` - ์ด ํญ๋ชฉ์ ๋ก์ปฌ ํจํค์ง ์ปดํจํฐ์ ์์ค ๋น๋์ค ์์น๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
* `out_type` - ์ด ํญ๋ชฉ์ ํจํค์ง๋ ์ถ๋ ฅ์ ์ ํ์ ์ค๋ช
ํฉ๋๋ค(์ด ๊ฒฝ์ฐ DASH)(HTML 5์ Widevine ๋ณดํธ์ฉ).
* `out_path` - ๋ก์ปฌ ์์คํ
์์ ์ถ๋ ฅ์ ๋ณด๋ผ ์์น์
๋๋ค.
* `drm_sys` - ํจํค์งํ๋ DRM ์๋ฃจ์
. ๋ค์ ์ค ํ๋๊ฐ ๋ฉ๋๋ค. `widevine`, `fairplay`, ๋๋ `playready`.
* `frag_dur` ๋ฐ `target_dur` ๋ ๋น๋์ค ์ฌ์๊ณผ ๊ด๋ จ๋ DASH ๊ด๋ จ ์ง์ ์๊ฐ ํญ๋ชฉ์
๋๋ค.
* `key_file_path` - CEK(์ฝํ
์ธ ์ํธํ ํค) ์ญํ ์ ํ๋ ํจํค์ง ์ปดํจํฐ์ ๋ผ์ด์ ์ค ํ์ผ ์์น์
๋๋ค. Base-64๋ก ์ธ์ฝ๋ฉ๋ 16๋ฐ์ดํธ 16์ง์ ๋ฌธ์์ด์
๋๋ค.
* `widevine_content_id` - ์ด๊ฒ์ Widevine "boilerplate"์
๋๋ค; ๊ทธ๊ฒ์ ํญ์ `2a`. (์ด๊ฒ์ ์ ํผ๋ํ์ง ๋ง์ญ์์ค. `widevine_key_id`.)
* `widevine_provider` - For our purposes ํญ์ set this to `intertrust`.
* `widevine_key_id` - ๋ค์์์ ์ง์ ํ ๋ผ์ด์ ์ค์ ์๋ณ์์
๋๋ค. `key_file_path` ์
๋ ฅ. ์ฆ, ์ฝํ
์ธ ๋ฅผ ์ํธํํ๋ ๋ฐ ์ฌ์ฉํ๋ ํค๋ฅผ ์๋ณํฉ๋๋ค. ์ด ID๋ ์ง์ ๋ง๋๋ 16๋ฐ์ดํธ HEX ๋ฌธ์์ด์
๋๋ค.
์ ๋ช
์๋ ๋๋ก [Packager ์ค๋ช
์](https://helpx.adobe.com/content/dam/help/en/primetime/guides/offline_packager_getting_started.pdf)๋ฅผ ์ค์ ํ๋ ๊ฒ์ด ์ข์ต๋๋ค. ์ถ๋ ฅ ์์ฑ์ ์ฌ์ฉํ ์ผ๋ฐ ์ต์
์ด ํฌํจ๋ ๊ตฌ์ฑ ํ์ผ์ ๋ง๋ญ๋๋ค. ๊ทธ๋ฐ ๋ค์ ํน์ ์ต์
์ ๋ช
๋ น์ค ์ธ์๋ก ์ ๊ณตํ์ฌ ์ถ๋ ฅ์ ๋ง๋ญ๋๋ค." ์ด ๊ฒฝ์ฐ ๊ตฌ์ฑ ํ์ผ์ด ์๋นํ ์์ฑ๋์์ผ๋ฏ๋ก ๋ค์๊ณผ ๊ฐ์ด ์ถ๋ ฅ์ ์์ฑํ ์ ์์ต๋๋ค.
```
java -jar OfflinePackager.jar -conf_path widevine.xml -out_path test_dash/
```
>[!NOTE]
>
>๋ช
๋ น์ค ๋งค๊ฐ ๋ณ์๊ฐ ๊ตฌ์ฑ ํ์ผ ๋งค๊ฐ ๋ณ์๋ณด๋ค ์ฐ์ ํฉ๋๋ค. ์ด ์์ ์์ ํ์ํ ๋ชจ๋ ๊ฒ์ ๊ตฌ์ฑ ํ์ผ์ ์์ง๋ง ๊ตฌ์ฑ ํ์ผ์ ์ง์ ๋ ์ถ๋ ฅ ๊ฒฝ๋ก๋ฅผ `-out_path test_dash/`. |
package com.dwarfeng.settingrepo.sdk.bean.dto;
import com.alibaba.fastjson.annotation.JSONField;
import com.dwarfeng.settingrepo.stack.bean.dto.SettingNodeRemoveInfo;
import com.dwarfeng.subgrade.stack.bean.dto.Dto;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Objects;
/**
* WebInput ่ฎพ็ฝฎ่็น็งป้คไฟกๆฏใ
*
* @author DwArFeng
* @since 1.0.0
*/
public class WebInputSettingNodeRemoveInfo implements Dto {
private static final long serialVersionUID = -7264808900538970951L;
public static SettingNodeRemoveInfo toStackBean(WebInputSettingNodeRemoveInfo webInputSettingNodeRemoveInfo) {
if (Objects.isNull(webInputSettingNodeRemoveInfo)) {
return null;
} else {
return new SettingNodeRemoveInfo(
webInputSettingNodeRemoveInfo.getCategory(), webInputSettingNodeRemoveInfo.getArgs()
);
}
}
@JSONField(name = "category")
@NotNull
@NotEmpty
private String category;
@JSONField(name = "args")
@NotNull
private String[] args;
public WebInputSettingNodeRemoveInfo() {
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String[] getArgs() {
return args;
}
public void setArgs(String[] args) {
this.args = args;
}
@Override
public String toString() {
return "WebInputSettingNodeRemoveInfo{" +
"category='" + category + '\'' +
", args=" + Arrays.toString(args) +
'}';
}
} |
import { Poppins } from '@next/font/google'
import { TbForbid2, TbMinus, TbPlus, TbTrash } from 'react-icons/tb'
import { IconType } from 'react-icons'
import classNames from 'classnames'
import Button from './button'
import styles from '../styles/components/counter.module.css'
import Tooltip from './tooltip'
const poppins = Poppins({ weight: "400", subsets: ['latin'] })
interface CounterProps {
icon: IconType
label?: string
tooltip?: string
value: number
maxQuantity?: number
noBackground?: boolean
disabled?: boolean
removable?: boolean
onRemove?: () => void
onChange?: (value: number) => void
}
export default function Counter({
icon: Icon,
label,
tooltip,
value,
maxQuantity,
noBackground,
disabled,
removable,
onRemove,
onChange
}: CounterProps) {
const containerStyle = classNames({
[styles.container]: true,
[styles.noBackground]: noBackground,
[styles.disabled]: disabled
})
const labelStyle = classNames({
[poppins.className]: true,
[styles.label]: true
})
function handleInput(newValue: string) {
if (maxQuantity && Number(newValue) > maxQuantity) return
onChange && onChange(Number(newValue))
}
function handleMinus() {
if (removable && onRemove && value === 1) {
return onRemove()
}
if (onChange && value > 0) {
return onChange(value - 1)
}
}
function handlePlus() {
if (maxQuantity && value + 1 > maxQuantity) return
onChange && onChange(value + 1)
}
return (
<div>
{label && <label className={labelStyle}>{label}</label>}
<div className={containerStyle}>
{tooltip ? (
<Tooltip label={tooltip}>
<Icon />
</Tooltip>
) : <Icon />}
{!disabled && (
<Button
label="Diminuir"
type="button"
icon={removable && value === 1 ? TbTrash : TbMinus}
secondary
onClick={handleMinus}
/>
)}
<input
className={poppins.className}
disabled={disabled}
value={value}
type="number"
onChange={e => handleInput(e.target.value)}
/>
{!disabled ? (
<Button
label="Aumentar"
type="button"
disabled={maxQuantity && value + 1 > maxQuantity || false}
icon={maxQuantity && value + 1 > maxQuantity ? TbForbid2 : TbPlus}
onClick={handlePlus}
secondary
/>
) : <div />}
</div>
</div>
)
} |
@import url('https://fonts.googleapis.com/css2?family=Righteous&family=Work+Sans:wght@100;300;400;600;800&display=swap');
*{
box-sizing: border-box;
font-family: 'work Sans';
margin: 0;
padding: 0;
}
html{
/* esto me va a permitir deslizar cuando hago clic en los links del menu */
scroll-behavior: smooth;
}
/* Menu */ /* esta es la parte del fondo del menu*/
.contenedor-header{
background: #1e2326;
position: fixed;
width: 100%;
top: 0;
left: 0;
z-index: 99;
}
/* Menu */ /* esta es la parte del centro es el contenido del menu*/
.contenedor-header header{
max-width: 1100px;
margin: auto;
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 20px;
}
/* Menu */ /* modifica Mi nombre*/
.contenedor-header header .logo a{
font-family: 'Righteous';
font-size: 36px;
color: #1cb698;
text-decoration: none;
}
/* Menu */ /* esta es la parte del contenido del menu le cambia el estilo*/
.contenedor-header header ul{
display: flex;
list-style: none;
}
/* Menu */ /* esta es la parte del contenido del menu los deja alineados
de forma horizontal en el centro y separados uno del otro y le quita el subrayado*/
.contenedor-header header nav ul li a{
text-align: none;
color: #fff;
margin: 0 15px;
padding: 3px;
transition: .5s;
text-decoration: none;
}
/* Menu */ /* esto hace que cuando pongan el raton sobre alguna seleccion del menu cambie de color*/
.contenedor-header header nav ul li a:hover{
color: #1cb698;
}
/* Menu */ /* esto hace que nuestro boton de menu (el de las tres lineas) cambie de color y tamaรฑo*/
.nav-responsive{
background-color: #1cb698;
color: #fff;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
display: none; /* desaparece el boton*/
}
/*Esto es de la parte del INICIO para modificar el fondo*/
.inicio{
background: linear-gradient(to top, rgba(30,35,38,.8), rgba(30,35,38,1)),
url(Img/fondo.jpg);
background-size: cover;
height: 100vh;
color: #fff;
display: flex;
align-items: center;
}
/*para que la foto de perfil se ponga en el medio con los demas datos del mismo*/
.inicio .contenido-banner{
padding: 20px;
background-color: #1e2326;
max-width: 350px;
margin: auto;
text-align: center;
border-radius: 40px;
}
/*hace arreglos a mi foto de perfil y su estructura*/
.inicio .contenido-banner img{
margin-top: 40px;
border: 10px solid #1cb698;
display: block;
width: 80%;
margin: auto;
border-radius: 100%;
}
/*modifica mi nombre*/
.inicio .contenido-banner h1{
margin-top: 40px;
font-size: 42px;
font-family: 'Righteous';
}
/*modifica la seccion H2*/
.inicio .contenido-banner h2{
font-size: 15px;
font-weight: normal;
}
/*modifica la parte de las redes*/
.inicio .contenido-banner .redes a{
color: #fff;
display: inline-block;
text-decoration: none;
border: 1px solid #fff;
border-radius: 100%;
width: 42px;
height: 42px;
line-height: 42px;
margin: 40px 5px;
font-size: 20px;
transition: .3s;
}
/*en la parte de las redes cuando se selecciona se pondra de color*/
.inicio .contenido-banner .redes a:hover{
background-color: #1cb698;
}
/*Desde aqui comienza la seecion SOBRE MI*/
/*se modificara el fondo de dicha seccion*/
.sobremi{
background-color: #1e2326;
color: #fff;
padding: 50px 20px;
}
/*se modificara el texto*/
.sobremi .contenido-seccion{
max-width: 1100px;
margin: auto;
}
/*se modificara el sobre mi (H2)*/
.sobremi h2{
font-size: 40px;
font-family: 'Righteous';
text-align: center;
padding: 20px 0;
}
/*se modificara el texto descriptivo*/
.sobremi .contenido-seccion p{
font: 18px;
line-height: 22px;
margin-bottom: 20px;
}
/*pone en negrilla las primeras palabras del texto*/
.sobremi .contenido-seccion p span{
color: #1cb698;
font-weight: bold;
}
/*seciona por fila la parte de los intereses*/
.sobremi .fila{
display: flex;
}
/*separa la seccion interes de datos personales*/
.sobremi .fila .col{
width: 50%;
}
/*resalta los texto de datos personales e intereses*/
.sobremi .fila .col h3{
font-size: 28px;
font-family: 'Righteous';
margin-bottom: 25px;
}
/*se quita el guion de forma de lista de los datos personales*/
.sobremi .fila .col ul{
list-style: none;
}
/*separacion por renglon de los datos personlaes*/
.sobremi .fila .col ul li{
margin: 12px 0;
}
/*cambia de color los datos personales*/
.sobremi .fila .col ul li strong{
display: inline-block;
color: #1cb698;
width: 130px;
}
/*resalta la seccion del cargo*/
.sobremi .fila .col ul li span{
background-color: #1cb698;
padding: 3px;
font-weight: bold;
border-radius: 5px;
}
/*pone en fila la parte de los intereses*/
.sobremi .fila .col .contenedor-intereses{
display: flex;
flex-wrap: wrap;
}
/*cambia la forma y el contenido de los iconos de los intereses*/
.sobremi .fila .col .contenedor-intereses .interes{
width: 100px;
height: 100px;
background-color: #252A2E;
border-radius: 10px;
margin: 0 15px 15px 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
transition: .3s;
}
/*hace que cundo pongas el cursos sobre los items de interes alumbren de color*/
.sobremi .fila .col .contenedor-intereses .interes:hover{
background-color: #1cb698;
}
/*ajusta el tamaรฑo de los items de interes*/
.sobremi .fila .col .contenedor-intereses .interes i{
font-size: 30px;
margin-bottom: 10px;
}
/*modifica el boton de descargar CV y lo ubica en el centro*/
.sobremi button{
cursor: pointer;
background-color: transparent;
border: 2px solid #fff;
width: fit-content;
display: block;
margin: 20px auto;
padding: 10px 22px;
font-size: 16px;
color: #fff;
position: relative;
z-index: 10;
}
/*animacion de llenado en modo barra del boton CV*/
.sobremi button .overlay{
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #1cb698;
z-index: -1;
transition: 1s;
}
/*muestra el color del codigo anterior*/
.sobremi button:hover .overlay{
width: 100%;
}
/*Seccion SKILL Aqui comienza esta seccion*/
/*se modificara el fondo de dicha seccion*/
.skills{
background-color: #252A2E;
color: #fff;
padding: 50px 20px;
}
/*se modificara el texto*/
.skills .contenido-seccion{
max-width: 1100px;
margin: auto;
}
/*se modificara el Skills (H2)*/
.skills h2{
font-size: 40px;
font-family: 'Righteous';
text-align: center;
padding: 20px 0;
}
/*ubica en filas los skills*/
.skills .fila{
display: flex;
}
/*separa los textos de los skills*/
.skills .fila .col{
width: 50%;
padding: 0 20px;
}
/*se modificara los titulos de los Skills (H3)*/
.skills .fila .col h3{
font-size: 28px;
font-family: 'Righteous';
margin-bottom: 25px;
}
/*separa los textos de los porcentajes*/
.skills .skill > span{
font-weight: bold;
display: block;
margin-bottom: 10px;
}
/*crea una barra de porcentajes para los Skills*/
.skills .skill .barra-skill{
height: 8px;
width: 80%;
background-color: #131517;
position: relative;
margin-bottom: 30px;
}
/*muestra la barra de un color*/
.skills .skill .progreso{
background-color: #1cb698;
position: absolute;
top: 0;
left: 0;
height: 8px;
}
/*vuelve el porcentaje de los skills en un circulo de color*/
.skills .skill .barra-skill span{
position: absolute;
height: 40px;
width: 40px;
background-color: #1cb698;
border-radius: 50px;
line-height: 40px;
text-align: center;
top: -17px;
right: -15px;
font-size: 14px;
}
/*hace que el porcentaje se mueva segun su nivel*/
.skills .skill .javascript{
width: 0%;
animation: 2s javascript forwards;
}
@keyframes javascript{
0%{width: 0%;}
100%{width: 30%;}
}
.skills .skill .htmlcss{
width: 0%;
animation: 2s htmlcss forwards;
}
@keyframes htmlcss{
0%{width: 0%;}
100%{width: 30%;}
}
.skills .skill .postman{
width: 0%;
animation: 2s postman forwards;
}
@keyframes postman{
0%{width: 0%;}
100%{width: 75%;}
}
.skills .skill .as400{
width: 0%;
animation: 2s as400 forwards;
}
@keyframes as400{
0%{width: 0%;}
100%{width: 50%;}
}
.skills .skill .jira{
width: 0%;
animation: 2s jira forwards;
}
@keyframes jira{
0%{width: 0%;}
100%{width: 70%;}
}
.skills .skill .comunicacion{
width: 0%;
animation: 2s comunicacion forwards;
}
@keyframes comunicacion{
0%{width: 0%;}
100%{width: 80%;}
}
.skills .skill .trabajo{
width: 0%;
animation: 2s trabajo forwards;
}
@keyframes trabajo{
0%{width: 0%;}
100%{width: 80%;}
}
.skills .skill .adaptabilidad{
width: 0%;
animation: 2s adaptabilidad forwards;
}
@keyframes adaptabilidad{
0%{width: 0%;}
100%{width: 90%;}
}
.skills .skill .capacidad{
width: 0%;
animation: 2s capacidad forwards;
}
@keyframes capacidad{
0%{width: 0%;}
100%{width: 75%;}
}
.skills .skill .autoaprendizaje{
width: 0%;
animation: 2s autoaprendizaje forwards;
}
@keyframes autoaprendizaje{
0%{width: 0%;}
100%{width: 90%;}
}
/*Seccion CURRICULUM*/
/*se modificara el fondo de dicha seccion*/
.curriculum{
background-color: #1e2326;
color: #fff;
padding: 50px 20px;
}
/*se modificara el texto*/
.curriculum .contenido-seccion{
max-width: 1100px;
margin: auto;
}
/*se modificara el Curriculum (H2)*/
.curriculum h2{
font-size: 48px;
font-family: 'Righteous';
text-align: center;
padding: 20px 0;
}
/*ubica en filas los Curriculum*/
.curriculum .fila{
display: flex;
justify-content: space-between;
}
/*separa las filas*/
.curriculum .fila .col{
width: 49%;
padding: 0 20px;
}
/*cambia el estilo de letra de los titulos del H3*/
.curriculum .fila .col h3{
font-size: 28px;
font-family: 'Righteous';
margin-bottom: 25px;
}
/*separacion con una linea algo visible de las 2 columnas*/
.curriculum .fila .izquierda{
border-right: 2px solid #252A2E;
}
.curriculum .fila .derecha{
border-left: 2px solid #252A2E;
}
/*separa en recuadros todos los textos*/
.curriculum .fila .item{
padding: 25px;
margin-bottom: 30px;
background-color: #252A2E;
position: relative;
}
/*ajusta los textos*/
.curriculum .fila .item h4{
font-size: 20px;
margin-bottom: 10px;
}
/*resalta los textos de los CentrosE*/
.curriculum .fila .item .CentroE{
color: #1cb698;
font-size: 22px;
font-weight: bold;
display: block;
}
/*resalta la fecha*/
.curriculum .fila .item .fecha{
display: block;
color: #1cb698;
margin-bottom: 10px;
}
/*separacion de texto*/
.curriculum .fila .item p{
line-height: 24px;
}
/*pequeรฑa margen en la parte derecha e izquierda de las cajas de textos*/
.curriculum .fila .izq{
border-right: 2px solid #1cb698;
margin-right: 20px;
}
.curriculum .fila .der{
border-left: 2px solid #1cb698;
margin-left: 20px;
}
/*conector de linea parte izquierda*/
.curriculum .fila .item .conectori{
height: 2px;
background-color: #1cb698;
width: 47px;
position: absolute;
top: 50%;
right: -47px;
z-index: 5;
}
/*coloca un pequeรฑo circulo entre los conectores*/
.curriculum .fila .item .conectori .circuloi{
display: block;
height: 10px;
width: 10px;
border-radius: 50%;
background-color: #1cb698;
float: right;
position: relative;
bottom: 4px;
}
/*conector de linea parte derecha*/
.curriculum .fila .item .conectord{
height: 2px;
background-color: #1cb698;
width: 47px;
position: absolute;
top: 50%;
left: -47px;
z-index: 5;
}
/*coloca un pequeรฑo circulo entre los conectores*/
.curriculum .fila .item .conectord .circulod{
display: block;
height: 10px;
width: 10px;
border-radius: 50%;
background-color: #1cb698;
float: left;
position: relative;
bottom: 4px;
}
/*SECCION PORTAFOLIO*/
/*cambia el fondo de la seccion*/
.portafolio{
background-color: #252A2E;
color: #fff;
padding: 50px 20px;
}
/*ajusta las imagenes*/
.portafolio .contenido-seccion{
max-width: 1100px;
margin: auto;
}
/*ajuste del texto H2*/
.portafolio h2{
font-size: 48px;
font-family: 'Righteous';
text-align: center;
padding: 20px 0;
}
/*centra las imagenes*/
.portafolio .galeria{
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
/*ajusta el tamaรฑo de las imagenes y las pone en modo galeria*/
.portafolio .galeria .proyecto{
position: relative;
max-width: 340px;
height: fit-content;
margin: 10px;
cursor: pointer;
}
/*muestra en bloques las imagenes*/
.portafolio .galeria .proyecto img{
width: 100%;
display: block;
}
/*para mejorar el contenido visual y da opacidad a las imagenes*/
.portafolio .galeria .proyecto .overlay{
position: absolute;
top: 0;
width: 100%;
height: 100%;
text-align: center;
background: linear-gradient(rgba(28,182,152,.8), rgba(28,182,152,.8));
display: flex;
flex-direction: column;
justify-content: center;
transition: 1s;
font-size: 18px;
letter-spacing: 3px;
opacity: 0; /*si se omite esto mantiene la opacidad en ls imagenes junto con el texto*/
}
/*coloca un boton sobre el text H3*/
.portafolio .galeria .proyecto .overlay h3{
margin-bottom: 20px;
transition: 1s;
}
/*cuando se pasa el cursos por la imagen se opoca y muestra el texto*/
.portafolio .galeria .proyecto .overlay:hover{
opacity: 1;
}
/*da animacion al texto de las imagenes*/
.portafolio .galeria .proyecto .overlay:hover h3{
margin-bottom: 0px;
}
/*SECCION CONTACTO*/
/*cambia el fondo de la seccion contacto*/
.contacto{
background-image: url(Img/contact_bg.png);
background-color: #1e2326;
color: #fff;
padding: 50px 0;
}
/*ajusta el contenido*/
.contacto .contenido-seccion{
max-width: 1100px;
margin: auto;
}
/*ajusta el texto H2*/
.contacto h2{
font-size: 48px;
font-family: 'Righteous';
text-align: center;
padding: 20px 0;
}
.contacto .fila{
display: flex;
}
/*separa las columnas*/
.contacto .col{
width: 50%;
padding: 10px;
position: relative;
}
/*optimiza la parte de envio de mensajes*/
.contacto .col input, .contacto .col textarea{
display: block;
width: 100%;
padding: 18px;
border: none;
margin-bottom: 20px;
background-color: #252A2E;
color: #fff;
font-size: 18px;
}
/*arregla el boton de eniar mensaje*/
.contacto button{
cursor: pointer;
background-color: transparent;
border: 2px solid #fff;
width: fit-content;
display: block;
margin: 20px auto;
padding: 10px 22px;
font-size: 16px;
color: #fff;
position: relative;
z-index: 10;
}
/*para crear la animacion de caga del envio mensaje*/
.contacto button .overlay{
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #1cb698;
z-index: -1;
transition: 1s;
}
.contacto button:hover .overlay{
width: 100%;
}
/*ajusta la imagen de la ubicacion*/
.contacto .col img{
width: 100%;
}
/*coloca los datos de informacion sobre el mapa*/
.contacto .col .info{
position: absolute;
top: 40%;
background-color: #252A2E;
padding: 20px;
max-width: 350px;
left: 50%;
transform: translate(-50%, -50%);
}
/*cambio de color y estilo de los datos e iconos*/
.contacto .col .info ul{
list-style: none;
}
.contacto .col .info ul li{
margin-bottom: 20px;
}
.contacto .col .info ul li i{
color: #1cb698;
display: inline-block;
margin-right: 20px;
}
/*SECCION PIE DE PAGINA*/
/*centra el pie de pagina y da el tamaรฑo de la seccion*/
footer{
background-color: #25262e;
color: #fff;
padding: 5px 0 5px 0;
text-align: center;
position: relative;
width: 100%;
}
footer .redes{
margin-bottom: 1px;
}
/*agranda el icono de las redes*/
footer .redes a{
color: #fff;
display: inline-block;
text-decoration: none;
border: 1px solid #fff;
border-radius: 100%;
width: 42px;
height: 42px;
line-height: 42px;
margin: 40px 5px;
font-size: 20px;
transition: .3s;
}
/*el icono de desplazamiento se modifica*/
footer .arriba{
display: block;
width: 50px;
height: 50px;
background-color: #1cb698;
color: #fff;
position: absolute;
left: 50%;
transform: translateX(-50%);
top: -25px;
border-radius: 50%;
line-height: 50px;
font-size: 18px;
}
/*SECCION RESPONSIVE*/
/**/
@media screen and (max-width:980px){
nav{
display: none;
}
.nav-responsive{
display: block;
}
nav.responsive{
display: block;
position: absolute;
right: 0;
top: 75px;
background-color: #252A2E;
width: 180px;
}
nav.responsive ul{
display: block !important;
}
nav.resposive ul li{
border-bottom: 1px solid #fff;
padding: 10px 0;
}
}
@media screen and (max-width:700px){
.sobremi .fila{
display: block;
}
.sobremi .fila .col{
width: fit-content;
}
.skills .fila{
display: block;
}
.skills .fila .col{
width: 100%;
}
.skills .fila .col .barra-skill{
width: 100%;
}
.curriculum .fila{
display: block;
}
.curriculum .fila .col{
width: 90%;
}
.curriculum .fila .derecha{
margin-left: 20px;
}
.portafolio .galeria{
display: block;
width: 100%;
}
.portafolio .galeria .proyecto{
max-width: 100%;
}
.portafolio .galeria .proyecto img{
width: 100%;
}
.contacto .fila{
display: block;
}
.contacto .fila .col{
width: 100%;
}
} |
<template>
<!-- -->
<div class="row mt-3">
<div class="col-5 ms-5">
<router-link class="btn btn-simple d-flex align-items-center mt-0"
to="/">
<span class="material-symbols-outlined">
arrow_back
</span>
Volver
</router-link>
</div>
</div>
<!-- -->
<div id="Arrendatario" class="card mt-5 m-5">
<div class="card-header">
<h5>Datos del Arrendatario</h5>
</div>
<div class="card-body pt-0">
<div class="row">
<div v-if="!arrendatarioContrato" class="row mt-4">
<div class="col-3">
<material-switch id="tipo_arrendatario" v-model:checked="esEmpresa" checked
label-class="mb-0 text-body text-truncate w-100"
name="tipo_arrendatario">
{{ esEmpresa ? 'Es empresa' : 'Es persona' }}
</material-switch>
</div>
<!-- Seccion Propietario general-->
<div v-if="!esEmpresa" class="row mt-4">
<h5 class="mt-3 mb-3">Persona</h5>
<div class="col-sm-3">
<material-input
id="RutArrendatario"
label="Rut arrendatario"
placeholder="Con guiรณn"
type="text"
variant="static"
/>
</div>
<div class="col-4">
<material-input
id="NombreArrendatario"
label="Nombre arrendatario"
placeholder="Nombre"
variant="static"
/>
</div>
<div class="col-4">
<material-input
id="ApellidoPaternoArrendatario"
label="Apellido Paterno Arrendatario"
placeholder="Apellido"
variant="static"
/>
</div>
<div class="col-4">
<material-input
id="ApellidoMaternoArrendatario"
label="Apellido Materno arrendatario"
placeholder="Apellido"
variant="static"
/>
</div>
<div class="col-sm-3">
<material-input
id="Ocupacion"
label="Ocupaciรณn Arrendatario"
placeholder="Ingenieria"
type="text"
variant="static"
/>
</div>
</div>
<div v-if="!esEmpresa" class="row mt-3">
<h5 class="mt-3 mb-3">Contacto</h5>
<div class="col-4 mt-4">
<material-input
id="emailArrendatario"
label="Email arrendatario"
placeholder="Email"
type="email"
variant="static"
/>
</div>
<div class="col-4 mt-4">
<material-input
id="confirmEmailArrendatario"
label="Confimar Email arrendatario"
placeholder="Confirma Email"
type="email"
variant="static"
/>
</div>
<div class="col-3 mt-4">
<material-input
id="numeroArrendatario"
label="Numero de telรฉfono"
placeholder="+569 xxxxxxxx"
type="phone"
variant="static"
/>
</div>
</div>
<!-- Seccion Empresa-->
<div v-if="esEmpresa" class="row mt-4">
<h5 class=" mt-3 mb-3">Empresa</h5>
</div>
<div v-if="esEmpresa" class="row mt-4">
<div class="col-sm-3">
<material-input
id="Rut"
label="Rut Empresa"
placeholder="Con guiรณn"
type="text"
variant="static"
/>
</div>
<div class="col-sm-3">
<material-input
id="Rut"
label="Rut Representante Legal"
placeholder="Con guiรณn"
type="text"
variant="static"
/>
</div>
</div>
<div v-if="esEmpresa" class="row mt-4">
<div class="col-4">
<material-input
id="NombreRepresentanteLegal"
label="Nombre Representante Legal"
placeholder="Nombre"
variant="static"
/>
</div>
<div class="col-4">
<material-input
id="ApellidoPaternoRepresentanteLegal"
label="Apellido Paterno Representante Legal"
placeholder="Apellido"
variant="static"
/>
</div>
<div class="col-4">
<material-input
id="ApellidoMaternoRepresentanteLegal"
label="Apellido Materno Representante Legal"
placeholder="Apellido"
variant="static"
/>
</div>
</div>
<div v-if="esEmpresa" class="row mt-4">
<div class="col-sm-3">
<material-input
id="Ocupacion"
label="Ocupaciรณn Representante Legal"
placeholder="Ingenieria"
type="text"
variant="static"
/>
</div>
<div class="col-sm-5">
<material-input
id="RazonSocial"
label="Razรณn Social"
placeholder="Razรณn Social"
variant="static"
/>
</div>
<div class="col-sm-4">
<material-input
id="Giro"
label="Giro"
placeholder="Giro"
variant="static"
/>
</div>
</div>
<div v-if="esEmpresa" class="row">
<h5 class=" mt-3 mb-3">Contacto</h5>
<div class="col-4 mt-4">
<material-input
id="emailRepresentanteLegal"
label="Email Representante Legal"
placeholder="Email"
type="email"
variant="static"
/>
</div>
<div class="col-4 mt-4">
<material-input
id="confirmEmailRepresentanteLegal"
label="Confimar Email Representante Legal"
placeholder="Confirma Email"
type="email"
variant="static"
/>
</div>
<div class="col-3 mt-4">
<material-input
id="numeroRepresentanteLegal"
label="Numero de telรฉfono"
placeholder="+569 xxxxxxxx"
type="phone"
variant="static"
/>
</div>
</div>
</div>
</div>
<!-- Seccion RepresentanteLegal Empresa-->
<!-- generales propietario-->
<div v-if="!arrendatarioContrato" class="row mt-4 text-start">
<LocalidadForm v-model="persona.direccion"></LocalidadForm>
</div>
</div>
<div class="card-footer">
<material-button class="mt-2 " full-width size="lg" variant="success">Enviar</material-button>
</div>
</div>
</template>
<script setup>
import MaterialInput from '@/components/MaterialInput.vue'
import MaterialSwitch from '@/components/MaterialSwitch.vue'
import { onMounted, onUnmounted, ref } from 'vue'
import LocalidadForm from '@/views/Propiedades/components/LocalidadForm.vue'
import { useAppStore } from '@/store/index.js'
import MaterialButton from '@/components/MaterialButton.vue'
const arrendatarioContrato = ref(false)
const esEmpresa = ref(true)
const persona = ref({
direccion: {
pais: '',
region: '',
ciudad: '',
calle: '',
numero: '',
detalle: '',
codigoPostal: ''
}
})
const store = useAppStore()
const { toggleEveryDisplay, toggleHideConfig } = store
onMounted(() => {
toggleEveryDisplay()
toggleHideConfig()
})
onUnmounted(() => {
toggleEveryDisplay()
toggleHideConfig()
})
</script> |
import './App.css'
import { Routes, Route, useLocation } from 'react-router-dom'
import Create from './component/Create'
import Home from './component/Home'
import Update from './component/Update'
import Read from './component/Read'
import 'bootstrap/dist/css/bootstrap.min.css'
import Email from './component/Email'
import Login from './LandingPage/Login'
import Signup from './LandingPage/Signup'
import UserDashboard from './Dashboard/UserDashboard'
import ProjectPage from './Project/AddProjectPage'
import { Provider } from 'react-redux'
import store from './Redux/store'
import UpdateProjectPage from './Project/UpdateProject'
import OnlyUserCanSee from './Dashboard/OnlyUserCanSee'
import UpdateProjectPageForUser from './Project/UpdateProjectPageForUser'
import AddProjectPageForUser from './Project/AddProjectPageForUser'
import PrivateRoute from './PrivateRoute'
import { useState } from 'react'
import { Navigate } from 'react-router-dom'
import { useEffect } from 'react'
function App() {
const [isAuthenticated, setIsAuthenticated] = useState(() => {
const storedAuthState = sessionStorage.getItem("isAuthenticated");
return storedAuthState ? JSON.parse(storedAuthState) : false;
});
useEffect(() => {
sessionStorage.setItem("isAuthenticated", JSON.stringify(isAuthenticated));
}, [isAuthenticated]);
const location = useLocation();
useEffect(() => {
const isLoginPage = location.pathname === "/";
if (isLoginPage) {
sessionStorage.clear();
setIsAuthenticated(false);
}
}, [location.pathname]);
const handleLogin = (value) => {
setIsAuthenticated(value);
};
const handleLogout = () => {
setIsAuthenticated(false);
};
return (
<Provider store={store}>
<Routes>
<Route path='/login' element={<Login onLogin={handleLogin} />} />
<Route path='/' element={<Login onLogin={handleLogin} />} />
<Route path='/signup' element={<Signup />} />
{/* Private routes using isAuthenticated */}
<Route path='/home' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<Home handleLogout={handleLogout} />} />} />
<Route path='/create' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<Create />} />} />
<Route path='/update/:id' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<Update />} />} />
<Route path='/read/:id' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<Read />} />} />
<Route path='/email' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<Email />} />} />
<Route path='/user' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<UserDashboard />} />} />
<Route path='/project' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<ProjectPage />} />} />
<Route path='/user/update/:id' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<UpdateProjectPage />} />} />
<Route path="/user-page" element={<PrivateRoute isAuthenticated={isAuthenticated} element={<OnlyUserCanSee />} />} />
<Route path='/user-page/update/:id' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<UpdateProjectPageForUser />} />} />
<Route path='/project-page' element={<PrivateRoute isAuthenticated={isAuthenticated} element={<AddProjectPageForUser />} />} />
<Route path="*" element={<Navigate to="/login" />} />
</Routes>
</Provider>
);
}
export default App; |
import { CommandHandler, ICommandHandler } from "@nestjs/cqrs";
import { PostsRepositories } from "../../../infrastructure/posts-repositories";
import { CreateCommentCommand } from "../create-comment-command";
import { CommentsViewType } from "../../../../comments/infrastructure/query-repository/comments-View-Model";
import {
ForbiddenExceptionMY,
NotFoundExceptionMY,
} from "../../../../../helpers/My-HttpExceptionFilter";
import { PreparationCommentForDB } from "../../../../comments/domain/comment-preparation-for-DB";
import { UsersQueryRepositories } from "../../../../users/infrastructure/query-reposirory/users-query.reposit";
import { CommentsRepositories } from "../../../../comments/infrastructure/comments.repositories";
import { BlogsRepositories } from "../../../../blogs/infrastructure/blogs.repositories";
@CommandHandler(CreateCommentCommand)
export class CreateCommentHandler
implements ICommandHandler<CreateCommentCommand> {
constructor(
private readonly postsRepositories: PostsRepositories,
private readonly blogsRepositories: BlogsRepositories,
private readonly commentsRepositories: CommentsRepositories,
private readonly usersQueryRepositories: UsersQueryRepositories
) {
}
async execute(command: CreateCommentCommand): Promise<CommentsViewType> {
const { content } = command.inputCommentModel;
const { id } = command;
const { userId } = command;
//find post for create comment
const post = await this.postsRepositories.findPost(id);
if (!post) throw new NotFoundExceptionMY(`Not found for id: ${id}`);
const user = await this.usersQueryRepositories.findUser(userId);
//check status ban user
const statusBan = await this.blogsRepositories.findStatusBan(userId, post.blogId);
if (statusBan && statusBan.isBanned === true) {
throw new ForbiddenExceptionMY(`For user comment banned`);
}
//preparation comment for save in DB
const newComment = new PreparationCommentForDB(
false,
post._id.toString(),
post.userId,
content,
userId,
user.login,
new Date().toISOString()
);
return await this.commentsRepositories.createCommentByIdPost(newComment);
}
} |
import { useEffect, useState } from "react";
import style from "./Carousel.module.css"
import { Link } from "react-router-dom";
export default function Carousel (autoPlay){
const images = ["Rona.jpeg","Dog-1.jpg","Dog-2.jpg","Ami.jpeg","Otto2.jpeg"];
const [selectedIndex, setSelectedIndex] = useState(0);
const[selectedImage,setSelectedImage]=useState(images[0]);
useEffect(()=>{
if(autoPlay){
const interval = setInterval(()=>{
selectNewImage(selectedIndex,images)
},3000);
return () => clearInterval(interval);
}
})
const selectNewImage = (index,images,next = true) =>{
const condition = next ? selectedIndex <images.length - 1 : selectedIndex > 0;
const nextIndex =
next ? (condition ? selectedIndex + 1 : 0) : condition ? selectedIndex - 1 : images.length -1 ;
setSelectedImage(images[nextIndex]);
setSelectedIndex(nextIndex)
}
const previous = () =>{
selectNewImage(selectedIndex,images,false)
}
const next = () =>{
selectNewImage(selectedIndex,images,true)
}
return(
<>
<div className={style.CarouselContainer}>
<div className={style.sider}>
<h1 className={style.HomeTitle}>Find your best friend with one click...</h1>
<Link className={style.HomeLink} to="/home">Home</Link>
</div>
<img src={require(`../../../public/img/${selectedImage}`).default} alt="Dogs" className={style.CarouselImg}/>
</div>
<div className={style.CarouselButtonContainer}>
<button className={style.CarouselButton} onClick={previous}>{"<"}</button>
<button className={style.CarouselButton} onClick={next}>{">"}</button>
</div>
</>
)
} |
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {Observable} from "rxjs";
import {AuthenticationHandleService, AuthResponseData} from "../../service/authentication-handle.service";
import {Router} from "@angular/router";
@Component({
selector: 'app-signup-component',
templateUrl: './signup-component.component.html',
styleUrls: ['./signup-component.component.css']
})
export class SignupComponentComponent implements OnInit {
signupForm!: FormGroup;
// @ts-ignore
error: string = null;
constructor(private authenticatinoHandleService: AuthenticationHandleService,
private router: Router) {
}
ngOnInit(): void {
this.signupForm = this.returnReactiveSignUpForm();
}
private returnReactiveSignUpForm() {
let signUpForm = new FormGroup({
'email': new FormControl(null),
'password': new FormControl(null),
});
return signUpForm;
}
onSubmit() {
localStorage.clear();
const email = this.signupForm.value.email;
const password = this.signupForm.value.password;
let authObs: Observable<AuthResponseData>;
authObs = this.authenticatinoHandleService.signup(email, password);
authObs.subscribe(
resData => {
this.router.navigate([this.getNavigationRouteOnSuccesfulSignUp()]);
},
errorMessage => {
this.error = errorMessage;
}
);
this.signupForm.reset();
}
private getNavigationRouteOnSuccesfulSignUp() {
return this.authenticatinoHandleService.returnNavigationRouteOnSuccessfulAuthentication();
}
} |
//! ALPIDE words and APEs
use std::{fmt::Display, ops::RangeInclusive};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AlpideProtocolExtension {
/// Padding word - Lane status = OK
Padding,
/// Strip start - Lane status = WARNING
StripStart,
/// Detector timeout - Lane status = FATAL
DetectorTimeout,
/// Out of table (8b10b OOT) - Lane status = FATAL
OutOfTable,
/// Protocol error - Lane status = FATAL
ProtocolError,
/// Lane FIFO overflow error - Lane status = FATAL
LaneFifoOverflowError,
/// FSM error - Lane status = FATAL
FsmError,
/// Pending detector event limit - Lane status = FATAL
PendingDetectorEventLimit,
/// Pending lane event limit - Lane status = FATAL
PendingLaneEventLimit,
/// O2N error - Lane status = FATAL
O2nError,
/// Rate missing trigger error - Lane status = FATAL
RateMissingTriggerError,
/// PE data missing - Lane status = WARNING
PeDataMissing,
/// OOT data missing - Lane status = WARNING
OotDataMissing,
}
impl AlpideProtocolExtension {
// ALPIDE Protocol Extension (APE) words
const APE_PADDING: u8 = 0x00;
const APE_STRIP_START: u8 = 0xF2; // Lane status = WARNING
const APE_DET_TIMEOUT: u8 = 0xF4; // Lane status = FATAL
const APE_OOT: u8 = 0xF5; // Lane status = FATAL
const APE_PROTOCOL_ERROR: u8 = 0xF6; // Lane status = FATAL
const APE_LANE_FIFO_OVERFLOW_ERROR: u8 = 0xF7; // Lane status = FATAL
const APE_FSM_ERROR: u8 = 0xF8; // Lane status = FATAL
const APE_PENDING_DETECTOR_EVENT_LIMIT: u8 = 0xF9; // Lane status = FATAL
const APE_PENDING_LANE_EVENT_LIMIT: u8 = 0xFA; // Lane status = FATAL
const APE_O2N_ERROR: u8 = 0xFB; // Lane status = FATAL
const APE_RATE_MISSING_TRG_ERROR: u8 = 0xFC; // Lane status = FATAL
const APE_PE_DATA_MISSING: u8 = 0xFD; // Lane status = WARNING
const APE_OOT_DATA_MISSING: u8 = 0xFE; // Lane status = WARNING
#[inline]
fn from_byte(b: u8) -> Result<AlpideWord, ()> {
match b {
Self::APE_STRIP_START => Ok(AlpideWord::Ape(AlpideProtocolExtension::StripStart)),
Self::APE_DET_TIMEOUT => Ok(AlpideWord::Ape(AlpideProtocolExtension::DetectorTimeout)),
Self::APE_OOT => Ok(AlpideWord::Ape(AlpideProtocolExtension::OutOfTable)),
Self::APE_PROTOCOL_ERROR => Ok(AlpideWord::Ape(AlpideProtocolExtension::ProtocolError)),
Self::APE_LANE_FIFO_OVERFLOW_ERROR => Ok(AlpideWord::Ape(
AlpideProtocolExtension::LaneFifoOverflowError,
)),
Self::APE_FSM_ERROR => Ok(AlpideWord::Ape(AlpideProtocolExtension::FsmError)),
Self::APE_PENDING_DETECTOR_EVENT_LIMIT => Ok(AlpideWord::Ape(
AlpideProtocolExtension::PendingDetectorEventLimit,
)),
Self::APE_PENDING_LANE_EVENT_LIMIT => Ok(AlpideWord::Ape(
AlpideProtocolExtension::PendingLaneEventLimit,
)),
Self::APE_O2N_ERROR => Ok(AlpideWord::Ape(AlpideProtocolExtension::O2nError)),
Self::APE_RATE_MISSING_TRG_ERROR => Ok(AlpideWord::Ape(
AlpideProtocolExtension::RateMissingTriggerError,
)),
Self::APE_PE_DATA_MISSING => {
Ok(AlpideWord::Ape(AlpideProtocolExtension::PeDataMissing))
}
Self::APE_OOT_DATA_MISSING => {
Ok(AlpideWord::Ape(AlpideProtocolExtension::OotDataMissing))
}
Self::APE_PADDING => Ok(AlpideWord::Ape(AlpideProtocolExtension::Padding)),
_ => Err(()),
}
}
}
impl Display for AlpideProtocolExtension {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AlpideProtocolExtension::Padding => write!(f, "APE_PADDING"),
AlpideProtocolExtension::StripStart => write!(f, "APE_STRIP_START"),
AlpideProtocolExtension::DetectorTimeout => write!(f, "APE_DET_TIMEOUT"),
AlpideProtocolExtension::OutOfTable => write!(f, "APE_OOT"),
AlpideProtocolExtension::ProtocolError => write!(f, "APE_PROTOCOL_ERROR"),
AlpideProtocolExtension::LaneFifoOverflowError => {
write!(f, "APE_LANE_FIFO_OVERFLOW_ERROR")
}
AlpideProtocolExtension::FsmError => write!(f, "APE_FSM_ERROR"),
AlpideProtocolExtension::PendingDetectorEventLimit => {
write!(f, "APE_PENDING_DETECTOR_EVENT_LIMIT")
}
AlpideProtocolExtension::PendingLaneEventLimit => {
write!(f, "APE_PENDING_LANE_EVENT_LIMIT")
}
AlpideProtocolExtension::O2nError => write!(f, "APE_O2N_ERROR"),
AlpideProtocolExtension::RateMissingTriggerError => {
write!(f, "APE_RATE_MISSING_TRG_ERROR")
}
AlpideProtocolExtension::PeDataMissing => write!(f, "APE_PE_DATA_MISSING"),
AlpideProtocolExtension::OotDataMissing => write!(f, "APE_OOT_DATA_MISSING"),
}
}
}
/// All the possible words that can be found in the ALPIDE data stream
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AlpideWord {
ChipHeader, // 1010<chip id[3:0]><BUNCH_COUNTER_FOR_FRAME[10:3]>
ChipEmptyFrame, // 1110<chip id[3:0]><BUNCH COUNTER FOR FRAME[10:3]>
ChipTrailer, // 1011<readout flags[3:0]>
RegionHeader, // 110<region id[4:0]>
DataShort, // 01<encoder id[3:0]><addr[9:0]>
DataLong, // 00<encoder id[3:0]><addr[9:0]>0<hit map[6:0]>
BusyOn, // 1111_0001
BusyOff, // 1111_0000
Ape(AlpideProtocolExtension),
}
impl AlpideWord {
const CHIP_HEADER: u8 = 0xA0; // 1010_<chip_id[3:0]> next 8 bits are bit [10:3] of the bunch counter for the frame
const CHIP_HEADER_RANGE: RangeInclusive<u8> = 0xA0..=0xAF;
const CHIP_EMPTY_FRAME: u8 = 0xE0; // 1110_<chip_id[3:0]> next 8 bits are bit [10:3] of the bunch counter for the frame
const CHIP_EMPTY_FRAME_RANGE: RangeInclusive<u8> = 0xE0..=0xEF;
const CHIP_TRAILER: u8 = 0xB0; // 1011_<readout_flags[3:0]>
const CHIP_TRAILER_RANGE: RangeInclusive<u8> = 0xB0..=0xBF;
const REGION_HEADER: u8 = 0xC0; // 110<region_id[4:0]>
const REGION_HEADER_RANGE: RangeInclusive<u8> = 0xC0..=0xDF;
const DATA_SHORT: u8 = 0b0100_0000; // 01<encoder_id[3:0]> next 10 bits are <addr[9:0]>
const DATA_SHORT_RANGE: RangeInclusive<u8> = 0x40..=0x7F;
const DATA_LONG: u8 = 0b0000_0000; // 00<encoder_id[3:0]> next 18 bits are <addr[9:0]>_0_<hit_map[6:0]>
const DATA_LONG_RANGE: RangeInclusive<u8> = 0x00..=0x3F;
const BUSY_ON: u8 = 0xF0;
const BUSY_OFF: u8 = 0xF1;
#[inline]
pub fn from_byte(b: u8) -> Result<AlpideWord, ()> {
match b {
c if c & 0xC0 == Self::DATA_SHORT => Ok(AlpideWord::DataShort),
c if c & 0xC0 == Self::DATA_LONG => Ok(AlpideWord::DataLong),
c if c & 0xE0 == Self::REGION_HEADER => Ok(AlpideWord::RegionHeader),
c if c & 0xF0 == Self::CHIP_EMPTY_FRAME => Ok(AlpideWord::ChipEmptyFrame),
c if Self::CHIP_HEADER_RANGE.contains(&c) => Ok(AlpideWord::ChipHeader),
c if c & 0xF0 == Self::CHIP_TRAILER => Ok(AlpideWord::ChipTrailer),
_ => Self::match_exact(b),
}
}
#[inline]
fn match_exact(b: u8) -> Result<AlpideWord, ()> {
match b {
Self::BUSY_ON => Ok(AlpideWord::BusyOn),
Self::BUSY_OFF => Ok(AlpideWord::BusyOff),
_ => AlpideProtocolExtension::from_byte(b),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn alpide_word_from_byte_variants() {
assert_eq!(AlpideWord::from_byte(0xA0).unwrap(), AlpideWord::ChipHeader);
assert_eq!(
AlpideWord::from_byte(0xE0).unwrap(),
AlpideWord::ChipEmptyFrame
);
assert_eq!(
AlpideWord::from_byte(0xB0).unwrap(),
AlpideWord::ChipTrailer
);
assert_eq!(
AlpideWord::from_byte(0xC0).unwrap(),
AlpideWord::RegionHeader
);
assert_eq!(
AlpideWord::from_byte(0b0100_0000).unwrap(),
AlpideWord::DataShort
);
assert_eq!(
AlpideWord::from_byte(0b0000_0000).unwrap(),
AlpideWord::DataLong
);
assert_eq!(AlpideWord::from_byte(0xF0).unwrap(), AlpideWord::BusyOn);
assert_eq!(AlpideWord::from_byte(0xF1).unwrap(), AlpideWord::BusyOff);
}
#[test]
fn alpide_word_from_byte_ape_variants() {
// No test for padding as it is state dependent
assert_eq!(
AlpideWord::from_byte(0xF2).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::StripStart)
);
assert_eq!(
AlpideWord::from_byte(0xF4).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::DetectorTimeout)
);
assert_eq!(
AlpideWord::from_byte(0xF5).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::OutOfTable)
);
assert_eq!(
AlpideWord::from_byte(0xF6).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::ProtocolError)
);
assert_eq!(
AlpideWord::from_byte(0xF7).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::LaneFifoOverflowError)
);
assert_eq!(
AlpideWord::from_byte(0xF8).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::FsmError)
);
assert_eq!(
AlpideWord::from_byte(0xF9).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::PendingDetectorEventLimit)
);
assert_eq!(
AlpideWord::from_byte(0xFA).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::PendingLaneEventLimit)
);
assert_eq!(
AlpideWord::from_byte(0xFB).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::O2nError)
);
assert_eq!(
AlpideWord::from_byte(0xFC).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::RateMissingTriggerError)
);
assert_eq!(
AlpideWord::from_byte(0xFD).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::PeDataMissing)
);
assert_eq!(
AlpideWord::from_byte(0xFE).unwrap(),
AlpideWord::Ape(AlpideProtocolExtension::OotDataMissing)
);
}
#[test]
fn alpide_word_from_byte_variants_ranges() {
for b in 0xA0..=0xAF {
assert_eq!(AlpideWord::from_byte(b).unwrap(), AlpideWord::ChipHeader);
}
for b in 0xE0..=0xEF {
assert_eq!(
AlpideWord::from_byte(b).unwrap(),
AlpideWord::ChipEmptyFrame
);
}
for b in 0xB0..=0xBF {
assert_eq!(AlpideWord::from_byte(b).unwrap(), AlpideWord::ChipTrailer);
}
for b in 0xC0..=0xDF {
assert_eq!(AlpideWord::from_byte(b).unwrap(), AlpideWord::RegionHeader);
}
for b in 0x40..=0x7F {
assert_eq!(AlpideWord::from_byte(b).unwrap(), AlpideWord::DataShort);
}
for b in 0x00..=0x3F {
assert_eq!(AlpideWord::from_byte(b).unwrap(), AlpideWord::DataLong);
}
}
} |
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--
This CDN points to the latest official release of Web Chat. If you need to test against Web Chat's latest bits, please refer to using Web Chat's latest bits:
https://github.com/microsoft/BotFramework-WebChat#how-to-test-with-web-chats-latest-bits
-->
<script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
// In this demo, we are using Direct Line token from MockBot.
// Your client code must provide either a secret or a token to talk to your bot.
// Tokens are more secure. To learn about the differences between secrets and tokens
// and to understand the risks associated with using secrets, visit https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0
const userId = 'dl_' + Math.random().toString(36).substr(2, 9);
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer mNza6ZW9s_Y.RVJC7hCT6f9yszOrZgycaoaNDXkSANJj5BDtaM0p-nE");
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"User":{"Id":userId, "channel":"website1"}});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
// redirect: 'follow'
};
const res = await fetch("https://directline.botframework.com/v3/directline/tokens/generate", requestOptions)
const { token } = await res.json();
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token }),
styleOptions: {
botAvatarImage: 'https://docs.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
botAvatarInitials: 'BF',
userAvatarImage: 'https://github.com/compulim.png?size=64',
userAvatarInitials: 'WC'
}
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html> |
<?php
namespace App\Core;
class DB
{
private $host = "127.0.0.1";
private $database_name = "mvc";
private $login = "root";
private $root = "root";
protected $pdo;
protected static $instance;
/**Fonction constructrice de connexion a la Base de Donnรฉe */
private function __construct()
{
try {
$this->pdo = new \PDO('mysql:host=' . $this->host . ';dbname=' . $this->database_name, $this->login, $this->root);
$this->pdo->exec('SET NAMES utf8');
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
} catch (\PDOException $e) {
die($e->getMessage());
}
}
/** Crรฉation d'un Singleton pour ne possรจder qu'une Instance de DB */
//:self indiquรฉ que la mรฉthode renvoie une instance de l'objet lui mรชme
public static function getInstance(): DB
{
if (is_null(self::$instance)) {
self::$instance = new DB();
}
return self::$instance;
}
} |
using System.Collections;
using Unity.WebRTC;
using UnityEngine;
using UnityEngine.UI;
using WebSocketSharp;
public class SimpleMediaStreamSender : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] private Camera cameraStream;
// [SerializeField] private RawImage sourceImage;
private RTCPeerConnection connection;
private MediaStream videoStream;
private VideoStreamTrack videoStreamTrack;
private WebSocket ws;
private string clientId;
private bool hasReceivedAnswer = false;
private SessionDescription receivedAnswerSessionDescTemp;
private void Start()
{
InitClient("192.168.137.1", 8080);
}
private void Update()
{
if (hasReceivedAnswer)
{
hasReceivedAnswer = !hasReceivedAnswer;
StartCoroutine(SetRemoteDesc());
}
}
private void OnDestroy()
{
videoStreamTrack.Stop();
connection.Close();
ws.Close();
}
public void InitClient(string serverIp, int serverPort)
{
int port = serverPort == 0 ? 8080 : serverPort;
clientId = gameObject.name;
string endpoint = $"ws://{serverIp}:{port}/video";
Debug.Log("Sender endpoint " + endpoint);
ws = new WebSocket(endpoint);
ws.OnMessage += (sender, e) =>
{
Debug.Log(e.Data);
var signalingMessage = SignalingMessage.FromJSON(e.Data);
switch (signalingMessage.Type)
{
case SignalingMessageType.ANSWER:
Debug.Log($"{clientId} - Got ANSWER from Maximus: {signalingMessage.Message}");
receivedAnswerSessionDescTemp = SessionDescription.FromJSON(signalingMessage.Message);
hasReceivedAnswer = true;
break;
case SignalingMessageType.CANDIDATE:
Debug.Log($"{clientId} - Got CANDIDATE from Maximus: {signalingMessage.Message}");
var candidateInit = CandidateInit.FromJSON(signalingMessage.Message);
RTCIceCandidateInit init = new RTCIceCandidateInit();
init.sdpMid = candidateInit.SdpMid;
init.sdpMLineIndex = candidateInit.SdpMLineIndex;
init.candidate = candidateInit.Candidate;
RTCIceCandidate candidate = new RTCIceCandidate(init);
connection.AddIceCandidate(candidate);
break;
default:
Debug.Log(clientId + " - Maximus says: " + e.Data);
break;
}
};
ws.Connect();
connection = new RTCPeerConnection();
// Get candidates for caller
connection.OnIceCandidate = candidate =>
{
var candidateInit = new CandidateInit()
{
SdpMid = candidate.SdpMid,
SdpMLineIndex = candidate.SdpMLineIndex ?? 0,
Candidate = candidate.Candidate
};
ws.Send("CANDIDATE!" + candidateInit.ConvertToJSON());
};
connection.OnIceConnectionChange = state =>
{
Debug.Log(state);
};
// When calling create offer, the ice candidates will start to generate
connection.OnNegotiationNeeded = () =>
{
StartCoroutine(CreateOffer());
};
videoStreamTrack = cameraStream.CaptureStreamTrack(1280, 720);
// sourceImage.texture = cameraStream.targetTexture;
connection.AddTrack(videoStreamTrack);
StartCoroutine(WebRTC.Update());
}
private IEnumerator CreateOffer()
{
var offer = connection.CreateOffer();
yield return offer;
var offerDesc = offer.Desc;
var localDescOp = connection.SetLocalDescription(ref offerDesc);
yield return localDescOp;
var offerSessionDesc = new SessionDescription()
{
Type = SignalingMessageType.OFFER,
Sdp = offerDesc.sdp
};
ws.Send("OFFER!" + offerSessionDesc.ConvertToJSON());
}
private IEnumerator SetRemoteDesc()
{
RTCSessionDescription answerSessionDesc = new RTCSessionDescription();
answerSessionDesc.type = RTCSdpType.Answer;
answerSessionDesc.sdp = receivedAnswerSessionDescTemp.Sdp;
var remoteDescOp = connection.SetRemoteDescription(ref answerSessionDesc);
yield return remoteDescOp;
}
} |
import React, { useMemo } from "react";
import { useLocation } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faFaucetDrip,
faTriangleExclamation,
} from "@fortawesome/free-solid-svg-icons";
import ExternalLink from "./components/ExternalLink";
import ContentFrame from "./ContentFrame";
import StandardFrame from "./StandardFrame";
import StandardSubtitle from "./StandardSubtitle";
import { useChainInfo } from "./useChainInfo";
const Faucets: React.FC = () => {
const { network, faucets } = useChainInfo();
const loc = useLocation();
const urls = useMemo(() => {
const s = new URLSearchParams(loc.search);
const address = s.get("address");
const _urls: string[] =
network === "testnet"
? faucets.map((u) =>
// eslint-disable-next-line no-template-curly-in-string
address !== null ? u.replaceAll("${ADDRESS}", address) : u
)
: [];
// Shuffle faucets to avoid UI bias
for (let i = _urls.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[_urls[i], _urls[j]] = [_urls[j], _urls[i]];
}
return _urls;
}, [network, faucets, loc]);
return (
<StandardFrame>
<StandardSubtitle>Faucets</StandardSubtitle>
<ContentFrame>
<div className="space-y-3 py-4">
{urls.length > 0 && (
<div className="flex items-baseline space-x-2 rounded bg-amber-200 px-2 py-1 font-bold text-red-800 underline">
<FontAwesomeIcon
className="self-center"
icon={faTriangleExclamation}
size="1x"
/>
<span>
The following external links come from
https://github.com/ethereum-lists/chains and are *NOT* endorsed
by us. Use at your own risk.
</span>
</div>
)}
{/* Display the shuffling notice only if there are 1+ faucets */}
{urls.length > 1 && (
<div className="flex items-baseline space-x-2 rounded bg-amber-200 px-2 py-1 text-amber-700">
<FontAwesomeIcon
className="self-center"
icon={faTriangleExclamation}
size="1x"
/>
<span>The faucet links below are shuffled on page load.</span>
</div>
)}
{urls.length > 0 ? (
<div className="space-y-3 pt-2">
{urls.map((url) => (
<div className="flex items-baseline space-x-2">
<FontAwesomeIcon
className="text-gray-400"
icon={faFaucetDrip}
size="1x"
/>
<ExternalLink key={url} href={url}>
<span>{url}</span>
</ExternalLink>
</div>
))}
</div>
) : (
<div>There are no registered faucets.</div>
)}
</div>
</ContentFrame>
</StandardFrame>
);
};
export default Faucets; |
import React, { createContext, useContext, useState, useEffect } from "react";
import { toast } from "react-hot-toast";
const Context = createContext<any>("");
export const StateContext = ({ children }: any) => {
const [showCart, setShowCart] = useState(false);
const [cartItems, setCartItems] = useState<any>([]);
const [totalPrice, setTotalPrice] = useState(0);
const [totalQuantity, setTotalQuantity] = useState(0);
const [qty, setQty] = useState(1);
let foundProduct: any;
let index: any;
const onAdd = (product: any, quantity: any) => {
const checkProductInCart = cartItems?.find(
(item: any) => item?._id === product?._id
);
setTotalPrice((prev: any) => prev + product?.price * quantity);
setTotalQuantity((prev: any) => prev + quantity);
if (checkProductInCart) {
const updatedCartItems: any = cartItems?.map((item: any) => {
if (item._id === product._id)
return { ...item, quantity: item?.quantity + quantity };
});
setCartItems(updatedCartItems);
} else {
product.quantity = quantity;
setCartItems([...cartItems, { ...product }]);
}
toast.success(`${qty} ${product?.name} added to cart.`);
};
const onRemove = (product: any) => {
foundProduct = cartItems?.find((item: any) => item?._id === product?._id);
const newCartItem = cartItems?.filter(
(item: any) => item._id !== product?._id
);
setTotalPrice((prev) => prev - foundProduct?.price * foundProduct?.quantity);
setTotalQuantity((prev) => prev - foundProduct?.quantity);
setCartItems(newCartItem);
};
const toggleCartItemQuantity = (id: any, value: any) => {
foundProduct = cartItems?.find((item: any) => item._id === id);
index = cartItems?.findIndex((product: any) => product._id === id);
const newCartItem = cartItems?.filter((item: any) => item._id !== id);
if (value === "inc") {
cartItems[index]={ ...foundProduct, quantity: foundProduct?.quantity + 1 }
setTotalPrice((prev) => prev + foundProduct?.price);
setTotalQuantity((prev) => prev + 1);
} else if (value === "desc") {
if (foundProduct?.quantity > 1) {
cartItems[index]=
{ ...foundProduct, quantity: foundProduct?.quantity - 1 }
setTotalPrice((prev) => prev - foundProduct?.price);
setTotalQuantity((prev) => prev - 1);
}
}
};
const inQty = () => {
setQty((prev) => prev + 1);
};
const decQty = () => {
setQty((prev) => {
if (prev - 1 < 1) return 1;
return prev - 1;
});
};
return (
<Context.Provider
value={{
showCart,
setShowCart,
cartItems,
totalPrice,
totalQuantity,
qty,
inQty,
decQty,
onAdd,
toggleCartItemQuantity,
onRemove,
}}
>
{children}
</Context.Provider>
);
};
export const useStateContext = () => useContext(Context); |
package routes
import (
"Web_Fengyang_Server/controller"
"Web_Fengyang_Server/routes/middleware"
"github.com/gin-gonic/gin"
)
/* routes/routes.go */
func CollectRoutes(r *gin.Engine) *gin.Engine {
// ๅ
่ฎธ่ทจๅ่ฎฟ้ฎ
r.Use(middleware.CORSMiddleware())
// ๅพๅๆไฝ
carouselController := controller.NewCarouselController()
imageRoutes := r.Group("/image")
{
imageRoutes.POST("upload", controller.UploadImage) // ้็จๅพๅไธไผ
imageRoutes.POST("upload/rich_editor_upload", controller.RichEditorUploadImage) // ๅฏๆๆฌ็ผ่พๅจๅ
้จๅพๅไธไผ
imageRoutes.POST("delete", controller.DeleteImage) // blogๅคดๅพๅ ้ค
imageRoutes.POST("uploadCarouselImage", controller.UploadCarousel) // ไธไผ ่ฝฎๆญๅพๅพ็
imageRoutes.POST("addCarousel", carouselController.AddCarousel) // ๆทปๅ ่ฝฎๆญๅพ่กจ้กน
imageRoutes.PUT("updateCarousel", carouselController.UpdateCarousel) // ๆดๆฐ่ฝฎๆญๅพ่กจ้กน
imageRoutes.PUT("deleteCarousel", carouselController.DeleteCarousel) // ๅ ้ค่ฝฎๆญๅพ่กจ้กน
imageRoutes.GET("list", carouselController.List) // ่ทๅ่ฝฎๆญๅพๅ่กจ
imageRoutes.GET("urlList", carouselController.CarouselUrlList) // ่ทๅ่ฝฎๆญๅพurlๅ่กจ
}
// ็จๆทๆไฝ
userController := controller.NewUserController()
userRoutes := r.Group("/user")
{
userRoutes.POST("register", userController.Register) // ๆณจๅ
userRoutes.POST("login", userController.Login) // ็ปๅฝ
userRoutes.GET("info", middleware.AuthMiddleware(), userController.GetMyInfo) // ่ทๅๅฝๅ็จๆทไฟกๆฏ
userRoutes.GET("briefInfo", userController.GetBriefInfo) // ่ทๅๆ็ซ ไฝ่
็ฎ่ฆไฟกๆฏ
userRoutes.PUT("delete", userController.Delete) // ๅ ้ค็จๆท
userRoutes.PUT("update", userController.Update) // ๆดๆฐ็จๆทไฟกๆฏ
userRoutes.GET("list", userController.List) // ่ทๅ็จๆทๅ่กจ
}
//ๆ็ซ ๆไฝ
articleController := controller.NewArticleController()
articleRoutes := r.Group("/article")
{
articleRoutes.POST("create", middleware.AuthMiddleware(), articleController.Create) // ๅๅธๆ็ซ
articleRoutes.PUT("update", middleware.AuthMiddleware(), articleController.Update) // ไฟฎๆนๆ็ซ
articleRoutes.DELETE("delete", middleware.AuthMiddleware(), articleController.Delete) // ๅ ้คๆ็ซ
articleRoutes.GET("detail", articleController.Show) // ๆฅ็ๆ็ซ
articleRoutes.GET("list", articleController.List) // ๆพ็คบๆ็ซ ๅ่กจ
}
//articleRoutes.GET("carousel", articleController.List)
return r
} |
// this file should be dedicated to getting a list of profession items
// and materials used to craft those items
// get recipes from skill tier with profession id + skill tier id
// Iterate through all recipes and add all unique items required to db
// Hard-code blacksmithing and dragonflight skill tier
import { Profession } from "../../interfaces/IProfession";
import { getAccessToken } from "../accessToken";
import { ProfessionIndex } from "../../interfaces/IProfessionIndex";
import { ProfessionIndexItem } from "../../interfaces/IProfessionIndexItem";
import { SkillTier } from "../../interfaces/ISkillTier";
import { AccessToken } from "../../interfaces/IAccessToken";
import { Recipe } from "../../interfaces/IRecipe";
import { avoidRateLimit, sleep } from "../avoidRateLimit";
// // A skill tier is the id of a profession for a specific expansion.
// export async function getSkillTiers(accessToken, professionId) {
// const url = `https://${process.env.HOST_NAME}/data/wow/profession/${professionId}?${process.env.NAMESPACE_STATIC}&access_token=${accessToken.access_token}`;
// try {
// let skillTiers;
// await fetch(url)
// .then((response) => response.json())
// .then((data) => {
// skillTiers = data;
// });
// return skillTiers;
// } catch (error) {
// console.error(error);
// }
// }
// // Skill tier recipes include all recipes for an expansion
// export async function getSkillTier(accessToken, skillTierId, professionId) {
// // Blacksmithing id is 164
// const url = `https://${process.env.HOST_NAME}/data/wow/profession/${professionId}/skill-tier/${skillTierId}?${process.env.NAMESPACE_STATIC}&access_token=${accessToken.access_token}`;
// try {
// let skillTier;
// await fetch(url)
// .then((response) => response.json())
// .then((data) => {
// skillTier = data;
// });
// return skillTier;
// } catch (error) {
// console.error(error);
// }
// }
// export async function getAllSkillTiers(skillTierIndex, professionId) {
// try {
// let accessToken = await getAccessToken();
// let skillTiers;
// let skillTierPromises = await skillTierIndex.skill_tiers.map((skillTier) =>
// getSkillTier(accessToken, skillTier.id, professionId)
// );
// await Promise.all(skillTierPromises).then((data) => {
// console.log(data);
// });
// return skillTiers;
// } catch (error) {
// console.log(error);
// }
// return null;
// }
// export async function getRecipe(recipeId) {
// const accessToken = await getAccessToken();
// const url = `https://${process.env.HOST_NAME}/data/wow/recipe/${recipeId}?${process.env.NAMESPACE_STATIC}&access_token=${accessToken.access_token}`;
// try {
// let recipe;
// await fetch(url)
// .then((response) => response.json())
// .then((data) => {
// recipe = data;
// });
// return recipe;
// } catch (error) {
// console.error(error);
// }
// }
// export async function getRecipes(skillTier) {
// let recipes = [];
// skillTier.categories.map((category) => {
// category.recipes.map((recipe) => {
// recipes.push(recipe);
// });
// });
// return recipes;
// }
// export async function getAllRecipes(accessToken, skillTierIndex, professionId) {
// let allRecipes = [];
// let allSkillTiers = await getAllSkillTiers(
// accessToken,
// skillTierIndex,
// professionId
// );
// // consider using the key given (an href) and attaching the access token instead of getting ids everywhere
// allSkillTiers.map((skillTier) => {
// skillTier.categories.map((category) => {
// category.recipes.map((recipe) => {
// allRecipes.push([recipe.key, recipe.name, recipe.id]);
// });
// });
// });
// return allRecipes;
// }
// // export async function getSkillTierReagents(accessToken, skillTier) {
// // // Iterate through all [recipes] in a skill tier and get the recipe by the id.
// // // In each recipe, add the reagent to the reagent list if not listed
// // let recipes = getRecipes(skillTier);
// // let promises = [];
// // // recipes.forEach((recipe) => {
// // // promises.push(5);
// // // });
// // }
// // export async function getAllReagents(professionId) {
// // let accessToken = await getAccessToken();
// // let skillTierIndex = await getSkillTiers(accessToken, professionId);
// // const allSkillTiers = await getAllSkillTiers(
// // accessToken,
// // skillTierIndex,
// // professionId
// // );
// // setTimeout(() => {
// // console.log("fetch1");
// // }, 1000);
// // setTimeout(() => {
// // console.log("fetch2");
// // }, 2000);
// // setTimeout(() => {
// // console.log("fetch3");
// // }, 3000);
// // setTimeout(() => {
// // console.log("fetch4");
// // }, 4000);
// // let delay = 50;
// // let recipes = await allSkillTiers.map((skillTier) => {
// // skillTier.categories.map((category) =>
// // category.recipes.map((recipe) => {
// // let reagents = [];
// // try {
// // delay += 100;
// // setTimeout(() => {
// // fetch(recipe.key.href + "&access_token=" + accessToken.access_token)
// // .then((response) => response.json())
// // .then((recipe) => {
// // console.log(recipe.reagents);
// // reagents.push(recipe.reagents);
// // });
// // }, delay);
// // return reagents;
// // } catch (error) {
// // console.log(error);
// // }
// // return 0;
// // })
// // );
// // return {
// // name: skillTier.name,
// // reagents: 6,
// // };
// // });
// // // recipes = await Promise.all(recipes).then((recipesData) => recipesData);
// // const reagents = recipes;
// // return reagents;
// // }
// // This function is what is primarily called externally
// export async function getProfessionData() {
// // Blacksmithing
// const professionId = 164;
// const accessToken = await getAccessToken();
// const skillTierIndex = await getSkillTiers(accessToken, professionId);
// const skillTier = await getSkillTier(
// accessToken,
// skillTierIndex.skill_tiers[9].id,
// professionId
// );
// const recipes = await getRecipes(skillTier);
// const allRecipes = await getAllRecipes(
// accessToken,
// skillTierIndex,
// professionId
// );
// const allSkillTiers = await getAllSkillTiers(skillTierIndex, professionId);
// // let professions: Profession[];
// return {
// skillTierIndex,
// skillTier,
// allSkillTiers,
// recipes,
// allRecipes,
// };
// }
export async function getProfessionData() {
try {
// TODO: Don't forget to pop the first initialized
// element from the professions array
let professionIndex = await getProfessionIndex();
let professions = await getProfessions(professionIndex);
// TODO: Implement the following functions that flow
// logically through the blizzard profession API
let skillTier = await getSkillTierById(
professions[0].id,
professions[0].skill_tiers[0].id
);
let professionSkillTiers = await getSkillTiersByProfession(professions[0]);
// let recipes = await getRecipes();
// let items = await getItems();
console.log(
`Profession index: \n${JSON.stringify(professionIndex, null, 2)}`,
`Professions: \n${JSON.stringify(professions, null, 2)}`,
`SkillTier: \n${JSON.stringify(skillTier, null, 2)}`,
`${professions[0].name} skill tiers: \n${JSON.stringify(
professionSkillTiers,
null,
2
)}`
);
} catch (error) {
console.log(error);
}
}
export async function getProfessionIndex(): Promise<ProfessionIndex> {
await sleep(100);
let accessToken: AccessToken = await getAccessToken();
const url = `https://${process.env.HOST_NAME}/data/wow/profession/index?namespace=static-us&locale=${process.env.LOCALE}&access_token=${accessToken.access_token}`;
let professionIndex: ProfessionIndex = {
index: [
{
id: 0,
name: "",
key: { href: "" },
},
],
};
try {
professionIndex.index.pop();
await fetch(url)
.then((response) => response.json())
.then((data) => {
data.professions.forEach((profession: ProfessionIndexItem) => {
if (profession.name === "Soul Cyphering") return;
if (profession.name === "Protoform Synthesis") return;
if (profession.name === "Abominable Stitching") return;
if (profession.name === "Ascension Crafting") return;
if (profession.name === "Stygia Crafting") return;
if (profession.name === "Arcana Manipulation") return;
if (profession.name === "Tuskarr Fishing Gear") return;
professionIndex.index.push({
id: profession.id,
name: profession.name,
key: { href: profession.key.href },
});
});
});
return professionIndex;
} catch (error) {
console.log(error);
}
return professionIndex;
}
export async function getProfessions(
professionIndex: ProfessionIndex
): Promise<Profession[]> {
await sleep(100);
let accessToken: AccessToken = await getAccessToken();
let professions: Profession[] = [
{
_links: {
self: {
href: "",
},
},
id: 0,
name: "",
description: "",
type: {
type: "",
name: "",
},
media: {
key: {
href: "",
},
id: 0,
},
skill_tiers: [
{
key: {
href: "",
},
name: "",
id: 0,
},
],
},
];
try {
let promises: Promise<Profession>[] = professionIndex.index.map(
(profession) => {
let url = `https://${process.env.HOST_NAME}/data/wow/profession/${profession.id}?${process.env.NAMESPACE_STATIC}&access_token=${accessToken.access_token}`;
return fetch(url)
.then((response) => response.json())
.then((profession: Profession) => profession);
}
);
professions = await Promise.all(promises);
return professions;
} catch (error) {
console.log(error);
}
return professions;
}
export async function getSkillTierById(
professionId: number,
skillTierId: number
): Promise<SkillTier> {
await sleep(100);
let skillTier: SkillTier;
let accessToken = await getAccessToken();
const url = `https://${process.env.HOST_NAME}/data/wow/profession/${professionId}/skill-tier/${skillTierId}?${process.env.NAMESPACE_STATIC}&access_token=${accessToken.access_token}`;
try {
skillTier = await fetch(url)
.then((response) => response.json())
.then((data) => data);
return skillTier;
} catch (error) {
console.log(error);
}
skillTier = {
_links: {
self: {
href: "",
},
},
id: 0,
name: "",
minimum_skill_level: 0,
maximum_skill_level: 0,
categories: [
{
name: "",
recipes: [
{
key: {
href: "",
},
name: "",
id: 0,
},
],
},
],
};
return skillTier;
}
export async function getSkillTiersByProfession(
profession: Profession
): Promise<SkillTier[]> {
await sleep(100);
let skillTiers: SkillTier[] = [
{
_links: {
self: {
href: "",
},
},
id: 0,
name: "",
minimum_skill_level: 0,
maximum_skill_level: 0,
categories: [
{
name: "",
recipes: [
{
key: {
href: "",
},
name: "",
id: 0,
},
],
},
],
},
];
let accessToken: AccessToken = await getAccessToken();
try {
skillTiers.pop();
let promises: Promise<SkillTier>[] = profession.skill_tiers.map(
(skillTier) => getSkillTierById(profession.id, skillTier.id)
);
skillTiers = await Promise.all(promises);
console.log(skillTiers);
return skillTiers;
} catch (error) {
console.log(error);
}
return skillTiers;
}
export async function getRecipeById(recipeId: number): Promise<Recipe> {
await sleep(100);
let accessToken = await getAccessToken();
//the href given by some recipes does not match all of blizzard's other
// keys. So the url was implemented manually.
let url = `https://${process.env.HOST_NAME}/data/wow/recipe/${recipeId}?${process.env.NAMESPACE_STATIC}&access_token=${accessToken.access_token}`;
return fetch(url)
.then((response) => {
if (response.status != 200) {
console.log(`URL used: ${url}`);
console.log(`RECIPE ID: ${recipeId}`);
console.log(response);
}
return response.json();
})
.then((data) => data)
.catch((error) => `ERROR:${error}`);
}
export async function getRecipesBySkillTier(
profession: Profession,
skillTier: SkillTier
): Promise<Recipe[]> {
await sleep(100);
let recipes: Recipe[] = [
{
_links: {
self: {
href: "",
},
},
id: 0,
name: "",
professionId: 0,
skillTierId: 0,
skillTierName: "",
category: "",
media: {
key: {
href: "",
},
id: 0,
},
reagents: [
{
reagent: {
key: {
href: "",
},
name: "",
id: 0,
},
quantity: 0,
},
],
modified_crafting_slots: [
{
slot_type: {
key: {
href: "",
},
name: "",
id: 0,
},
display_order: 0,
},
],
},
];
try {
recipes.pop();
let max = 0;
for (let category of skillTier.categories) {
for (let recipe of category.recipes) {
// if (max === 10) break;
let recipeById = await getRecipeById(recipe.id);
recipeById.professionId = profession.id;
recipeById.skillTierId = skillTier.id;
recipeById.skillTierName = skillTier.name;
recipeById.category = category.name;
recipes.push(recipeById);
max++;
}
}
return recipes;
} catch (error) {
console.log(error);
}
return recipes;
}
export async function getRecipesByProfession(
profession: Profession
): Promise<Recipe[]> {
let recipes: Recipe[] = [
{
_links: {
self: {
href: "",
},
},
id: 0,
name: "",
professionId: 0,
skillTierId: 0,
skillTierName: "",
category: "",
media: {
key: {
href: "",
},
id: 0,
},
reagents: [
{
reagent: {
key: {
href: "",
},
name: "",
id: 0,
},
quantity: 0,
},
],
modified_crafting_slots: [
{
slot_type: {
key: {
href: "",
},
name: "",
id: 0,
},
display_order: 0,
},
],
},
];
try {
let skillTiers = await getSkillTiersByProfession(profession);
for (let skillTier of skillTiers) {
let skillTierRecipes = await getRecipesBySkillTier(profession, skillTier);
console.log(skillTierRecipes);
recipes.push(...skillTierRecipes);
}
return recipes;
} catch (error) {
console.log(error);
}
return recipes;
}
export function testFunction() {
return 4;
} |
"""The MAIN module of our FLASK RESTFUL API application - <SQL>"""
from flask import Flask, redirect, url_for
from flask_restful import Api
from importlib import import_module
from flasgger import Swagger
from flask_limiter import Limiter
from loguru import logger
# from flask_migrate import Migrate
from src.models import db
from src.views.students import StudentsListResource, StudentResource, CreateStudentResource
from src.views.groups import AllGroupsResource, GroupsOnRequestResource
from src.views.courses import CoursesAllResource, CourseUpdateResource
from src.views.student_course import StudentsInCourseResource, StudentCourseResource, OneStudentCoursesResource
def register_resources(api: Api) -> None:
"""Register resources with the given Api."""
# from students.py
api.add_resource(StudentsListResource, '/students/')
api.add_resource(StudentResource, '/students/<int:id>')
api.add_resource(CreateStudentResource, '/students/')
# from groups.py
api.add_resource(AllGroupsResource, '/groups/students')
api.add_resource(GroupsOnRequestResource, '/groups/<int:num>/students')
# from courses.py
api.add_resource(CoursesAllResource, '/courses/')
api.add_resource(CourseUpdateResource, '/courses/<int:id>')
# from student-course.py
api.add_resource(StudentsInCourseResource, '/courses/<string:course>/students/')
api.add_resource(OneStudentCoursesResource, '/students/<int:id>/courses/')
api.add_resource(StudentCourseResource, '/students/<int:id_student>/courses/<int:id_course>')
logger.info("--Registration of all URLs as API resources completed--")
def create_app(config_name: str) -> Flask:
"""Create a Flask src using the provided configuration name."""
app = Flask(__name__)
config_module = import_module(f'config.{config_name}')
app.config.from_object(config_module)
Limiter(app)
logger.add('api_logs.json', colorize=True, format='{time} {level} {message}',
level='DEBUG', rotation='10 days', retention="30 days", serialize=True)
logger.info(f"Creating a Flask app in the 'app factory' using configuration: {config_name}!")
db.init_app(app)
# Migrate(db)
api = Api(app, prefix='/api/v1')
Swagger(app, template_file='swagger/swagger.yml')
register_resources(api)
@app.route('/')
def index():
"""Redirect to API documentation for developers."""
logger.info("--Redirecting from '/' to API documentation for developers--")
return redirect(url_for('flasgger.apidocs', _external=True))
return app
if __name__ == "__main__":
# app = create_app('production')
app = create_app('development')
app.run() |
<template>
<v-main class="mx-auto" width="auto">
<v-btn color="primary" class="ml-auto" :to="`/product/${$route.params.id}/show`">
Show Product
<v-icon class="ml-3">mdi-pencil-box-multiple</v-icon>
</v-btn>
<v-btn color="secondary" class="ml-auto" @click="deleteProduct">
Delete Product
<v-icon class="ml-3">mdi-close-box</v-icon>
</v-btn>
<v-btn color="warning" class="ml-auto" :to="`/product/catalog`">
Back to Shop
<v-icon class="ml-3">mdi-arrow-left-circle</v-icon>
</v-btn>
<v-img
to="/inspire"
class="white--text align-end"
width="300"
:src="require(`~/assets/img/${item.image}`)"
></v-img>
<v-container>
<v-row>
<v-col cols="12" sm="6" md="4">
<v-text-field label="Title*" required v-model="item.title"></v-text-field>
</v-col>
<v-col cols="12" sm="6" md="4">
<v-text-field label="Price*" type="number" min="0" hint="Price in โฌ" v-model="item.price"></v-text-field>
</v-col>
<v-col cols="12" sm="6" md="4">
<v-text-field
v-model="item.image"
label="Image*"
hint="Name PNG store inside static folder on Adonis for the moment"
persistent-hint
required
></v-text-field>
</v-col>
<v-col cols="10">
<v-textarea auto-grow rows="1" v-model="item.description" label="Description*" required></v-textarea>
</v-col>
</v-row>
<v-btn color="success" @click="updateProduct">Update Product</v-btn>
</v-container>
</v-main>
</template>
<script>
export default {
components: {},
data() {
return {
item: {
title: "wait",
price: 0,
image: "question.png",
description: "Wait description",
},
};
},
async mounted() {
const product = await this.getDataWithAxios("get", "getproduct", {
id: this.$route.params.id,
}, false);
this.item = product;
},
methods: {
async updateProduct() {
const product = await this.getDataWithAxios("post", "updateproduct",
{
id: this.$route.params.id,
product: this.item,
});
this.$router.push(`/product/${this.$route.params.id}/show`);
},
async deleteProduct() {
const product = await this.getDataWithAxios("post", "deleteproduct",
{
id: this.$route.params.id,
});
this.$router.push(`/product/catalog`);
},
},
};
</script> |
#include "lists.h"
/**
* add_dnodeint_end - adds a new node at the end of a dlistint_t list.
* @head: pointer.
* @n: integer.
* Return: address of the new element, or NULL if it failed
**/
dlistint_t *add_dnodeint_end(dlistint_t **head, const int n)
{
dlistint_t *node_new, *am = *head;
node_new = malloc(sizeof(dlistint_t));
if (node_new == NULL)
return (NULL);
node_new->n = n;
node_new->next = NULL;
if (am)
{
for (; am->next; am = am->next)
{
}
node_new->prev = am;
am->next = node_new;
}
else
{
*head = node_new;
node_new->prev = NULL;
}
return (node_new);
} |
import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Lesson} from "../../_model/lesson/lesson";
import {Observable} from "rxjs";
import {Page} from "../../_model/page/page";
import {PageParams} from "../../_model/page/page-params";
import {LessonCreate} from "../../_model/lesson/lesson-create";
@Injectable({
providedIn: 'root'
})
export class LessonService {
constructor(private _httpClient: HttpClient) {
}
getLessonList(sort: string, order: string, page: number, pageSize: number): Observable<Page> {
const href = '/api/lesson/list';
const params: PageParams = new PageParams(page * pageSize, pageSize, {
orderBy: sort,
orderDir: order
});
return this._httpClient.post<Page>(href, params);
}
getLessonById(id: number): Observable<Lesson> {
const href = '/api/lesson/' + id;
return this._httpClient.get<Lesson>(href);
}
updateLesson(id: number, data: Lesson): Observable<Object> {
const href = '/api/lesson/' + id;
console.log("before patch:");
console.log(data);
return this._httpClient.patch(href, data);
}
deleteLesson(id: number): Observable<Object> {
const href = '/api/lesson/' + id;
return this._httpClient.delete(href);
}
createLesson(data: LessonCreate): Observable<Object> {
const href = '/api/lesson';
return this._httpClient.post(href, data);
}
} |
import React, { Component } from 'react';
import { hashHistory } from 'react-router';
import moment from 'moment';
import Icon from 'react-icons-kit';
import { pencil } from 'react-icons-kit/fa/pencil';
class HousingFilesListItem extends Component {
constructor(props) {
super(props);
this.state = {
showActionButtons: false,
highlightRow: '',
};
}
onRowEnter() {
this.setState({
showActionButtons: true,
highlightRow: 'highlight-row',
});
}
onRowLeave() {
this.setState({
showActionButtons: false,
highlightRow: '',
});
}
openItem(id) {
hashHistory.push(`/woningdossier/${id}`);
}
render() {
const { id, fullName, createdAt, fullAddress, postalCode, city, buildYear, buildingType, isHouseForSale, energyLabel } = this.props;
return (
<tr
className={this.state.highlightRow}
onDoubleClick={() => this.openItem(id)}
onMouseEnter={() => this.onRowEnter()}
onMouseLeave={() => this.onRowLeave()}
>
<td>{moment(createdAt).format('DD-MM-Y')}</td>
<td>{fullAddress}</td>
<td>{postalCode}</td>
<td>{city}</td>
<td>{fullName}</td>
<td>{buildYear ? buildYear : ''}</td>
<td>{buildingType ? buildingType : ''}</td>
<td>{isHouseForSale ? 'Ja' : 'Nee'}</td>
<td>{energyLabel ? energyLabel : ''}</td>
<td>
{this.state.showActionButtons ? (
<a role="button" onClick={() => this.openItem(id)}>
<Icon className="mybtn-success" size={14} icon={pencil} />
</a>
) : (
''
)}
</td>
</tr>
);
}
}
export default HousingFilesListItem; |
/*
RMIT University Vietnam
Course: COSC2659 iOS Development
Semester: 2022B
Assessment: Assignment 3
Author: Tran Nguyen Anh Khoa
ID: s3863956
Created date: 07/09/2022
Last modified: 09/09/2022
Acknowledgement: Personal coding
*/
import SwiftUI
struct TabSelector: View {
let content: String
@Binding var state: Bool
@EnvironmentObject var env:GlobalEnvironment
var body: some View {
Button {
if(!state) {
state = !state
if(env.tagSelected == 0)
{
env.currentViewStage = .discover
}
else{
env.currentViewStage = .nameDiscover
}
}
}
label: {
VStack(spacing: 5) {
Text(content.uppercased())
.foregroundColor(state ? .white : .white.opacity(0.5))
.font(.system(size: 20).weight(.regular))
//selected bar
RoundedRectangle(cornerRadius: 30)
.fill(state ? .white : .clear)
.frame(width: MySize.width * 0.4, height: 5, alignment: .center)
}
}
}
}
struct OppoTabSelector: View {
let content: String
@Binding var state: Bool
@EnvironmentObject var env:GlobalEnvironment
var body: some View {
Button {
if(state) {
state = !state
env.currentViewStage = .saved
}
}
label: {
VStack(spacing: 5) {
Text(content.uppercased())
.foregroundColor(!state ? .white : .white.opacity(0.5))
.font(.system(size: 20).weight(.regular))
//selected bar
RoundedRectangle(cornerRadius: 30)
.fill(!state ? .white : .clear)
.frame(width: MySize.width*0.4, height: 5, alignment: .center)
}
}
}
}
struct TabSelector_Previews: PreviewProvider {
static var previews: some View {
ZStack {
Background()
HStack {
TabSelector(content: "Discover",state: .constant(true))
.environmentObject(GlobalEnvironment())
OppoTabSelector(content: "Discover",state: .constant(true))
.environmentObject(GlobalEnvironment())
}
}
}
} |
package com.sms.presentation.main.ui.detail.project
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.msg.sms.design.theme.SMSTheme
import com.sms.presentation.main.ui.detail.data.ProjectData
import com.sms.presentation.main.ui.detail.data.RelatedLinksData
import com.sms.presentation.main.ui.mypage.state.ActivityDuration
@Composable
fun ProjectListComponent(
projectList: List<ProjectData>,
) {
SMSTheme { colors, typography ->
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
text = "ํ๋ก์ ํธ",
style = typography.title2,
color = colors.BLACK,
fontWeight = FontWeight.Bold
)
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.padding()
.heightIn(max = 10000.dp),
contentPadding = PaddingValues(bottom = 80.dp),
verticalArrangement = Arrangement.spacedBy(32.dp)
) {
items(projectList.size) {
ProjectComponent(data = projectList[it])
}
}
}
}
}
@Preview
@Composable
private fun ProjectComponentPre() {
ProjectListComponent(
projectList = listOf(
ProjectData(
name = "SMS",
activityDuration = ActivityDuration(start = "2023. 03", end = null),
projectImage = listOf(
"https://avatars.githubusercontent.com/u/82383983?s=400&u=776e1d000088224cbabf4dec2bdea03071aaaef2&v=4",
"https://avatars.githubusercontent.com/u/82383983?s=400&u=776e1d000088224cbabf4dec2bdea03071aaaef2&v=4",
"https://avatars.githubusercontent.com/u/82383983?s=400&u=776e1d000088224cbabf4dec2bdea03071aaaef2&v=4",
"https://avatars.githubusercontent.com/u/82383983?s=400&u=776e1d000088224cbabf4dec2bdea03071aaaef2&v=4"
),
icon = "https://avatars.githubusercontent.com/u/82383983?s=400&u=776e1d000088224cbabf4dec2bdea03071aaaef2&v=4",
techStacks = listOf("Github", "Git", "Kotlin", "Android Studio"),
keyTask = "๋ชจ์ด์ ใ
ใ
",
relatedLinks = listOf(
RelatedLinksData("Youtube", "https://dolmc.com"),
RelatedLinksData("GitHujb", "https://youyu.com"),
RelatedLinksData("X", "https://asdgasgw.com")
),
description = ""
),
ProjectData(
name = "SMS",
activityDuration = ActivityDuration(start = "2023. 03", end = "2023. 07"),
projectImage = listOf("https://avatars.githubusercontent.com/u/82383983?s=400&u=776e1d000088224cbabf4dec2bdea03071aaaef2&v=4"),
icon = "https://avatars.githubusercontent.com/u/82383983?s=400&u=776e1d000088224cbabf4dec2bdea03071aaaef2&v=4",
techStacks = listOf("Github", "Git", "Kotlin", "Android Studio"),
keyTask = "๋ชจ์ด์ ใ
ใ
",
relatedLinks = listOf(
RelatedLinksData("Youtube", "https://dolmc.com"),
RelatedLinksData("GitHujb", "https://youyu.com"),
RelatedLinksData("X", "https://asdgasgw.com")
), description = "รธ"
)
)
)
} |
from fastapi import APIRouter, Depends, HTTPException
from schemas.user import User, create_user, Response
from typing import Annotated
from uuid import UUID
user_router = APIRouter()
users: dict[str, User] = {}
@user_router.post("/", status_code=201)
async def register_a_user(user_in: create_user):
user = User(id=str(UUID(int=len(users) + 1)), **user_in.dict())
users[user.id] = user
return Response(message= f"Your profile has been successfully registered with the unique ID: {user.id}", data= user)
@user_router.get("/",status_code=200)
def get_all_users():
return users
@user_router.get("/{id}",status_code=200)
async def get_user_by_id(id: UUID):
user = users.get(str(id))
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@user_router.put("/{id}",status_code=200)
async def update_user(id: UUID, user_in: create_user):
user = users.get(str(id))
if not user:
raise HTTPException(status_code=404, detail="User not found")
user['firstName'] = user_in.firstName
user['lastName'] = user_in.lastName
user['email'] = user_in.email
user['username'] = user_in.username
user['password'] = user_in.password
return Response(message= "Your data has been updated successfully", data= user)
@user_router.delete("/{id}", status_code=200)
async def delete_book(id: UUID):
user = users.get(str(id))
if not user:
raise HTTPException(status_code=404, detail="Book not found")
del users[user.id]
return Response(message= "Your data has been deleted successfully") |
package hei2017.DTO;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView;
import hei2017.enumeration.StoryStatus;
import hei2017.enumeration.UniteTemps;
import hei2017.json.JsonViews;
import org.hibernate.annotations.Cascade;
import javax.persistence;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
public class Task implements Serializable{
private Long id;
private String nom;
private String description;
private Long tempsDeCharge;
private UniteTemps uniteTempsDeCharge;
private Timestamp dateCreation;
private StoryStatus status;
private Set<User> taskUsers;
private Story taskStory;
private RestTemplate restTemplate = new RestTemplate();
String url = "http://6";
// Constructeurs
public Task() {
this.dateCreation = new Timestamp(System.currentTimeMillis());
}
public Timestamp getDateCreation(){
return dateCreation;
}
public Set<User> getTaskUsers(){
return taskUsers;
}
public void addUser(User user){
this.taskUsers.add(user);
}
public Long getId(){
return id;
}
public Long getTempsDeCharge(){
return tempsDeCharge;
}
@Enumerated(EnumType.STRING)
public StoryStatus getStatus(){
return status;
}
public String getDescription(){
return description;
}
public void setStatus(StoryStatus status){
this.status = status;
}
public void setUniteTempsDeCharge(UniteTemps uniteTempsDeCharge){
this.uniteTempsDeCharge = uniteTempsDeCharge;
}
public UniteTemps getUniteTempsDeCharge(){
return uniteTempsDeCharge;
}
public Story getTaskStory(){
return taskStory;
}
public void setTaskUsers(Set<User> taskUsers){
this.taskUsers = taskUsers;
}
public String getNom(){
return nom;
}
public void setTaskStory(Story taskStory){
this.taskStory = taskStory;
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url.concat("/"+ id).concat("/setTaskStory"))
.queryParam("taskStory",taskStory)
;
restTemplate.put(builder.toUriString(),null);
}
public void setNom(String nom){
this.nom = nom;
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url.concat("/"+ id).concat("/setNom"))
.queryParam("nom",nom)
;
restTemplate.put(builder.toUriString(),null);
}
public void setDescription(String description){
this.description = description;
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url.concat("/"+ id).concat("/setDescription"))
.queryParam("description",description)
;
restTemplate.put(builder.toUriString(),null);
}
public void setTempsDeCharge(Long tempsDeCharge){
this.tempsDeCharge = tempsDeCharge;
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url.concat("/"+ id).concat("/setTempsDeCharge"))
.queryParam("tempsDeCharge",tempsDeCharge)
;
restTemplate.put(builder.toUriString(),null);
}
} |
<div class="container mt-4 text-dark center text-center">
<%= form_with model: @book, local: true do |form| %>
<% if @book.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@book.errors.count, "error") %> prohibited
this book from being saved:
</h2>
<ul>
<% @book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<i class="fas fa-book"></i> <%= form.label :title %><br>
<%= form.text_field :title, class:"rounded border-secondary" %>
</p>
<p>
<i class="fas fa-user-tie"></i> <%= form.label :author %><br>
<%= form.text_field :author, class:"rounded border-secondary" %>
</p>
<p>
<i class="fas fa-sort-numeric-down"></i> <%= form.label :pagecount %><br>
<%= form.number_field :pagecount, class:"rounded border-secondary" %>
</p>
<p>
<p class="d-inline-block"><i class="fas fa-share-square"></i> <%= form.label :share %><br></p>
<%= form.check_box :status %>
</p>
<p>
<p class="d-inline-block"><i class="fas fa-share-alt-square"></i> <%= form.label :tradeable %><br></p>
<%= form.check_box :tradeable %>
</p>
<p>
<%= form.submit "Save Book", class:"btn btn-info text-white"%>
<%= link_to "Back", dashboard_index_path, class:"btn btn-info text-white" %>
</p>
<% end %>
</div> |
require('dotenv').config()
const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const Person = require('./models/person')
const app = express()
app.use(cors())
app.use(express.json())
app.use(express.static('build'))
morgan.token('json', function (req) {
return JSON.stringify({
name: req.body.name,
number: req.body.number
})
})
app.use(morgan(':method :url :status :res[content-length] - :response-time ms :json'))
const generateId = () => {
const id = Math.random() * 20
return id
}
app.post('/api/persons', (request, response, next) => {
const body = request.body
const person = new Person({
id: generateId(),
name: body.name,
number: body.number,
})
person
.save()
.then(savedNote => {
response.json(savedNote.toJSON())
})
.catch(error => next(error))
})
app.get('/api/persons', (req, res) => {
Person.find({}).then(persons => {
res.json(persons)
})
})
app.get('/api/persons/:id', (request, response, next) => {
Person
.findById(request.params.id)
.then(person => {
response.json(person)
})
.catch(error => next(error))
})
app.get('/info', (req, res) => {
Person
.countDocuments(req.params.id)
.then(p => {
res.send('Phonebook has info for ' + p + ' persons' + '</br>' + new Date())
})
})
app.delete('/api/persons/:id', (request, response, next) => {
Person.findByIdAndRemove(request.params.id)
.then(
response.status(204).end()
)
.catch(error => next(error))
})
app.put('/api/persons/:id', (request, response, next) => {
const body = request.body
const person = {
number: body.number
}
Person
.findByIdAndUpdate(request.params.id, person, { new: true, runValidators: true })
.then(updatedNumber => {
response.json(updatedNumber.toJSON())
})
.catch(error => next(error))
})
const errorHandler = (error, request, response, next) => {
console.error(error.message)
if (error.name === 'CastError') {
return response.status(400).send({ error: 'malformatted id' })
} else if (error.name === 'ValidationError') {
return response.status(400).json({ error: error.message })
}
next(error)
}
app.use(errorHandler)
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
}) |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}}</title> <!-- use title declared in run -->
<!-- Bootstrap 5.1.3 CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- CSS for ICONS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<!-- Base CSS -->
<link rel="stylesheet" href="{{ url_for('static', filename='root.css') }}">
{% block navbar %}
{% include "navbar.html" %}
{% endblock %}
</head>
<style>
.alert {
background-color: rgba(200, 200, 200, 0.804);
color: #333;
padding: 1rem;
border-radius: 5px;
text-align: center;
top: -2rem;
margin-bottom: 1rem !important;
width: 70%;
height: 2.5rem;
font-size: 1.8rem;
}
</style>
<body>
<!-- <div class="container w-50 mt-4" style="padding-top: 13rem"> -->
<!-- {% with messages=get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{category}}">
{{message}}
</div>
{% endfor %}
{% endif %}
{% endwith %} -->
{% for message in get_flashed_messages() %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
{{ message }}
</div>
{% endfor %}
<!-- </div> -->
{% block content %}
{% endblock content %}
<!-- Popper, Booststrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>
<script>
$(document).ready(function() {
if ($('.alert').length) {
setTimeout(function() {
$(".alert").fadeOut();
}, 3000);
}
});
</script> |
package main
import "fmt"
func main() {
nums := []int{2, 3, 4} //decalre
sum := 0
for _, num := range nums { //similar to reducer function, iterates over all in array
sum += num
}
fmt.Println("sum:", sum)
for i, num := range nums { // can also get index while ranging
if num == 3 {
fmt.Println("index:", i)
}
}
kvs := map[string]string{"a": "apple", "b": "banana"} // can iterate over maps (nice feature)
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
for k := range kvs {
fmt.Println("key:", k)
}
for i, c := range "go" { //range on strings iterates over Unicode code points. The first value is the starting byte index of the rune and the second the rune itself.
fmt.Println(i, c)
}
} |
import pandas as pd
# Load the dataset
file_path = 'Dataset .csv'
data = pd.read_csv(file_path)
# Split the 'Cuisines' column and explode it to get individual cuisine entries
cuisine_series = data['Cuisines'].str.split(', ').explode()
# Determine the top three most common cuisines
top_cuisines = cuisine_series.value_counts().head(3)
top_cuisines_names = top_cuisines.index.tolist()
# Calculate the percentage of restaurants that serve each of the top cuisines
total_restaurants = len(data)
cuisine_percentages = (top_cuisines / total_restaurants) * 100
# Prepare the results
top_cuisines_results = {
"Top Cuisines": top_cuisines_names,
"Cuisines Count": top_cuisines.tolist(),
"Percentage of Restaurants": cuisine_percentages.tolist()
}
print("Top Three Most Common Cuisines:")
for cuisine, count, percentage in zip(top_cuisines_names, top_cuisines.tolist(), cuisine_percentages.tolist()):
print(f"{cuisine}: {count} restaurants ({percentage:.2f}%)") |
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "BasePickUp.generated.h"
UENUM(BlueprintType)
enum class EPickUpType : uint8
{
E_Armour UMETA(DisplayName = "Armour"),
E_AmmoAssaultRifle UMETA(DisplayName = "Ammo Assault Rifle"),
E_AmmoPistol UMETA(DisplayName = "Ammo Pistol"),
E_AmmoShotgun UMETA(DisplayName = "Ammo Shotgun"),
};
class AFPCharacter;
UCLASS()
class GCFPS_API ABasePickUp : public AActor
{
GENERATED_BODY()
private:
float m_fWeight;
public:
// Sets default values for this actor's properties
ABasePickUp();
UPROPERTY(VisibleAnywhere)
class UBoxComponent* BoxCollision;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Radius")
FVector m_VBoxRadius;
UPROPERTY(EditDefaultsOnly)
class USkeletalMeshComponent* MyMesh;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// -----
// Pickup Drops
UPROPERTY( EditAnywhere, Category = "Pickup | Drops" )
bool IsPickupPlacedDown;
FTimerHandle PickUpDropTimerHandle;
UPROPERTY( EditAnywhere, Category = "Pickup | Drops" )
float TimeToDespawn;
UFUNCTION()
void DestroyPickup();
bool bCanPickUp;
// -----
EPickUpType m_ePickUpType;
FString PickUpNotifText;
public:
virtual void EndPlay( const EEndPlayReason::Type EndPlayReason ) override;
virtual void Interact(AFPCharacter* pPlayer);
EPickUpType GetPickUpType() const { return m_ePickUpType; }
FString GetPickUpNotifText() { return PickUpNotifText; }
float GetWeight() const { return m_fWeight; }
void SetWeight( float weight ) { m_fWeight = weight; }
}; |
/*
ะ ะตะฐะปะธะทัะนัะต ะผะตัะพะด, ะบะพัะพััะน ะฒััะธัะปัะตั ะบะพัะตะฝั ะปัะฑะพะน ะทะฐะดะฐะฝะฝะพะน ััะตะฟะตะฝะธ ะธะท ัะธัะปะฐ.
ะ ะตะฐะปะธะทัะนัะต ะดะฐะฝะฝัะน ะผะตัะพะด ะบะฐะบ extension - ะผะตัะพะด ะดะปั num.
ะะฐะฟัะตัะฐะตััั ะธัะฟะพะปัะทะพะฒะฐัั ะผะตัะพะดั math.
ะ ัะปััะฐะต ะบะพะณะดะฐ ะทะฝะฐัะตะฝะธะต ะฒะตัะฝััั ะฝะตะฒะพะทะผะพะถะฝะพ, ะฝะตะพะฑั
ะพะดะธะผะพ ะฑัะพัะฐัั ะธัะบะปััะตะฝะธะต ั ะพะฟะธัะฐะฝะธะตะผ ะพัะธะฑะบะธ.
*/
extension RootExtension on num {
double nthRoot(int n) {
if (this < 0 && n % 2 == 0) {
throw ArgumentError('Cannot calculate even root of a negative number');
}
if (this == 0) {
return 0.0;
}
double x0 = this.abs().toDouble();
double x1 = (1 / n) * ((n - 1) * x0 + this / _nthPower(x0, n - 1));
while ((x1 - x0).abs() >= 1e-10) {
x0 = x1;
x1 = (1 / n) * ((n - 1) * x0 + this / _nthPower(x0, n - 1));
}
if (this < 0) {
x1 = -x1;
}
return x1;
}
double _nthPower(double base, int exponent) {
double result = 1.0;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
}
void main() {
try {
double result = 27.nthRoot(3);
print('ะัะฑะธัะตัะบะธะน ะบะพัะตะฝั ะธะท 27: $result');
result = 16.nthRoot(4);
print('ะงะตัะฒะตัััะน ะบะพัะตะฝั ะธะท 16: $result');
// ะะพะฟััะบะฐ ะธะทะฒะปะตัั ัะตัะฒะตัััะน ะบะพัะตะฝั ะธะท ะพััะธัะฐัะตะปัะฝะพะณะพ ัะธัะปะฐ (ะฑัะพัะธั ะธัะบะปััะตะฝะธะต)
result = (-16).nthRoot(4);
} catch (e) {
print('ะัะธะฑะบะฐ: $e');
}
} |
import { Avatar, Grid, Typography } from "@mui/material";
import React from "react";
import AddUserTextBox from "../../components/common/Adminhome/AddUserTextBox";
import AddUserButton from "../../components/common/Adminhome/AddUserButton";
import { useDispatch, useSelector } from "react-redux";
import {
createPatient,
setAdminSelectedPatient,
} from "../../store/actions/patientAction";
export default function PatientAddNewDialogBox({ handleClose }) {
const dispatch = useDispatch();
const { adminSelectedPatient } = useSelector((store) => store.patientReducer);
const handleChange = (value, name) => {
dispatch(
setAdminSelectedPatient({ ...adminSelectedPatient, [name]: value })
);
};
console.log(adminSelectedPatient);
const handleOnClick = () => {
dispatch(createPatient(adminSelectedPatient));
handleClose();
};
return (
<div>
<Typography
align="center"
sx={{ fontSize: 29, paddingTop: 1, color: "#017CF1" }}
>
<b>Add New</b>
</Typography>
<Typography align="center" sx={{ fontSize: 13, paddingTop: 1 }}>
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen book.
</Typography>
<Grid container justifyContent="space-between" alignItems="center">
<Grid item pl={5}>
<AddUserTextBox
name="firstName"
placeholder="Enter your Name"
fieldname="Name"
handleChange={handleChange}
/>
<AddUserTextBox
name="email"
placeholder="Enter your email address"
fieldname="Email"
handleChange={handleChange}
/>
<AddUserTextBox
name="password"
placeholder="Enter Your Password"
fieldname="Password"
handleChange={handleChange}
/>
<AddUserTextBox
name="mobileNumber"
placeholder="Enter your Number"
fieldname="Phone Number"
handleChange={handleChange}
/>
<AddUserTextBox
name="dateofBath"
placeholder="Enter date of Bath"
fieldname="DateofBath"
handleChange={handleChange}
/>
</Grid>
<Grid item pr={17} pt={1} sx={{ textAlign: "center" }}>
<Avatar sx={{ width: 180, height: 180 }}></Avatar>
<Typography pt={4} sx={{ fontSize: 13 }}>
Profile Picture
</Typography>
<div style={{ paddingTop: 35 }}>
<AddUserButton handleOnClick={handleOnClick} />
</div>
</Grid>
</Grid>
</div>
);
} |
;;; -*- Mode: Lisp; Package: BATTLE-SPACE; Syntax: COMMON-LISP; Base: 10 -*-
;;; HPKB Military unit ontology
;;; Version: $Id: military-units.loom,v 1.11 1998/06/12 04:00:43 hans Exp $
(in-package "BATTLE-SPACE")
;;
;;;;;; Military units
;;
;; Related Cyc/Sensus concepts:
#|
|#
;;; Representational issues:
;;; - Type of military unit (e.g., tank, infantry, etc.)
;;; - Typical structure, e.g., a (US) battalion has typically
;;; 3 companies plus a command unit plus some support platoons
;;; - Actual structure which might be quite different
;;; - National affiliation and its influence on the structure of a unit,
;;; e.g., soviet-style battalions are smaller than US-style battalions.
;;; - Kinds and quantities of equipment typically/actually maintained by a
;;; military unit
;;; - Kinds and quantities of equipment typically/actually used by a
;;; military unit in a particular military operation
;;; - Relationship between unit types, e.g., a battalion is "bigger" than
;;; a company and it commands only lower-level units.
(defconcept Military-Unit
:is-primitive Military-Organization)
(defconcept Military-Unit-Type
;; A meta-class. Currently not used.
:is-primitive Existing-Object-Type)
(defset Military-Unit-Order
;; This isn't quite true, since brigades and regiments can be considered
;; to be at the same level - I think.
;; Also: Naval units are structured differently.
:is (:and (:the-ordered-set
'Squad 'Platoon 'Company 'Battalion 'Brigade 'Regiment 'Division 'Army-Unit 'Corps)
Military-Unit-Type))
;; Use CYC's `affiliated-with' instead:
;(defrelation affiliation
; :domain Military-Unit
; :range Social-Entity) ;; E.g., United-States, NATO, ...
;; Maybe use CYC's `controls' instead?
;; OPCOM sub-units
(defrelation subordinate-unit
:domain (:or Military-Unit Concept)
:range Military-Unit
:inverse superordinate-unit
:annotations ((documentation "OPCOM - Operation control sub-units")))
(defrelation subordinate-unit*
"Transitive and reflexive version of `subordinate-unit'."
:domain (:or Military-Unit Military-Unit-Type)
:range Military-Unit
:is (:satisfies (?x ?z)
(:or (:same-as ?x ?z)
(role-values ?x subordinate-unit ?z)
(:for-some ?y
(:and (role-values ?x subordinate-unit ?y)
(role-values ?y subordinate-unit* ?z))))))
;; Organic sub-units
(defrelation organic-subordinate-unit
:domain (:or Military-Unit Concept)
:range Military-Unit
:annotations ((documentation "Organic can be thought of as peristent ownership.")))
;; Attached sub-units
(defrelation attached-subordinate-unit
:domain (:or Military-Unit Concept)
:range Military-Unit
:annotations ((documentation "Tatically attached sub-unit")))
(defrelation superordinate-unit
:domain (:or Military-Unit Concept)
:range Military-Unit
:inverse subordinate-unit)
;;; Corps units by echelon:
(defconcept Corps
:is-primitive (:and Military-Unit
(:all subordinate-unit
(:or Squad Platoon Company Battalion
Brigade Regiment Division Army-Unit)))
:annotations (Military-Unit-Type))
(defconcept Army-Unit ;; fix this name
:is-primitive (:and Military-Unit
(:all subordinate-unit
(:or Squad Platoon Company Battalion
Brigade Regiment Division)))
:annotations (Military-Unit-Type))
(defconcept Division
:is-primitive (:and Military-Unit
(:all subordinate-unit
(:or Squad Platoon Company Battalion
Brigade Regiment)))
:annotations (Military-Unit-Type))
(defconcept Regiment
:is-primitive (:and Military-Unit
(:all subordinate-unit
(:or Squad Platoon Company Battalion)))
:annotations (Military-Unit-Type))
(defconcept Brigade
:is-primitive (:and Military-Unit
(:all subordinate-unit
(:or Squad Platoon Company Battalion)))
:annotations (Military-Unit-Type))
(defconcept Battalion
:is-primitive (:and Military-Unit
(:all subordinate-unit
(:or Squad Platoon Company)))
:annotations (Military-Unit-Type))
(defconcept Company
:is-primitive (:and Military-Unit
(:all subordinate-unit
(:or Squad Platoon)))
:annotations (Military-Unit-Type))
(defconcept Battery
:is-primitive (:and Military-Unit)
:annotations (Military-Unit-Type))
(defconcept Platoon
:is-primitive (:and Military-Unit
(:all subordinate-unit
(:or Squad)))
:annotations (Military-Unit-Type))
(defconcept Squad
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
;;; Army unit by type:
(defconcept Infantry-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Mechanized-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Mechanized-Infantry-Unit
:is (:and Mechanized-Unit Infantry-Unit)
:annotations (Military-Unit-Type))
(defconcept Armored-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Engineer-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Artillery-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Mortar-Unit
:is-primitive Artillery-Unit
:annotations (Military-Unit-Type))
(defconcept Field-Artillery-Unit
:is-primitive Artillery-Unit
:annotations (Military-Unit-Type))
(defconcept Air-defense-Artillery-Unit
:is-primitive Artillery-Unit
:annotations (Military-Unit-Type))
(defconcept Towed-Field-Artillery-Unit
:is-primitive Field-Artillery-Unit
:annotations (Military-Unit-Type))
(defconcept Self-Propelled-Field-Artillery-Unit
:is-primitive Field-Artillery-Unit
:annotations (Military-Unit-Type))
(defconcept SSM-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept SCUD-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept HET-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Reconnaissance-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Headquarter-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Support-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Chemical-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Commando-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Weapons-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Anti-Tank-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Maintenance-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Transport-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
(defconcept Service-Unit
:is-primitive Military-Unit
:annotations (Military-Unit-Type))
;;; Armored units:
(defconcept Tank-Battalion
:is (:and Battalion Armored-Unit)
:annotations (Military-Unit-Type))
(defconcept Tank-Company
:is (:and Company Armored-Unit)
:annotations (Military-Unit-Type))
(defconcept Tank-Platoon
:is (:and Platoon Armored-Unit)
:annotations (Military-Unit-Type))
(defconcept Armored-Battalion
:is (:and Battalion Armored-Unit)
:annotations (Military-Unit-Type))
(defconcept Armored-Company
:is (:and Company Armored-Unit)
:annotations (Military-Unit-Type))
(defconcept Armored-Platoon
:is (:and Platoon Armored-Unit)
:annotations (Military-Unit-Type))
;;; Engineer units:
(defconcept Engineer-Brigade
:is (:and Brigade Engineer-Unit)
:annotations (Military-Unit-Type))
(defconcept Engineer-Battalion
:is (:and Battalion Engineer-Unit)
:annotations (Military-Unit-Type))
(defconcept Engineer-Company
:is (:and Company Engineer-Unit)
:annotations (Military-Unit-Type))
;;; Infantry units
(defconcept Infantry-Division
:is (:and Division Infantry-Unit)
:annotations (Military-Unit-Type))
(defconcept Infantry-Brigade
:is (:and Brigade Infantry-Unit)
:annotations (Military-Unit-Type))
(defconcept Infantry-Battalion
:is (:and Battalion Infantry-Unit)
:annotations (Military-Unit-Type))
(defconcept Infantry-Company
:is (:and Company Infantry-Unit)
:annotations (Military-Unit-Type))
(defconcept Infantry-Platoon
:is (:and Platoon Infantry-Unit)
:annotations (Military-Unit-Type))
;;; Artillery units:
(defconcept Artillery-Brigade
:is (:and Brigade Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Artillery-Battalion
:is (:and Battalion Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Mortar-Battery
:is (:and Battery Mortar-Unit)
:annotations (Military-Unit-Type))
(defconcept Mortar-Platoon
:is (:and Platoon Mortar-Unit)
:annotations (Military-Unit-Type))
(defconcept Artillery-Battery
:is (:and Battery Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Field-Artillery-Brigade
:is (:and Brigade Field-Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Towed-Field-Artillery-Battalion
:is (:and Battalion Towed-Field-Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Towed-Field-Artillery-Battery
:is (:and Battery Towed-Field-Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Self-Propelled-Field-Artillery-Battalion
:is (:and Battalion Self-Propelled-Field-Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Self-Propelled-Field-Artillery-Battery
:is (:and Battery Self-Propelled-Field-Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Air-Defense-Artillery-Brigade
:is (:and Brigade Air-Defense-Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Air-Defense-Artillery-Battalion
:is (:and Battalion Air-Defense-Artillery-Unit)
:annotations (Military-Unit-Type))
(defconcept Air-Defense-Artillery-Battery
:is (:and Battery Air-Defense-Artillery-Unit)
:annotations (Military-Unit-Type))
;;; Mechanized units:
(defconcept Mechanized-Infantry-Brigade
:is (:and Brigade Mechanized-Infantry-Unit)
:annotations (Military-Unit-Type))
(defconcept Mechanized-Infantry-Battalion
:is (:and Battalion Mechanized-Infantry-Unit)
:annotations (Military-Unit-Type))
(defconcept Mechanized-Infantry-Company
:is (:and Company Mechanized-Infantry-Unit)
:annotations (Military-Unit-Type))
(defconcept SSM-Brigade
:is (:and Brigade SSM-Unit)
:annotations (Military-Unit-Type))
(defconcept SSM-Battery
:is (:and Battery SSM-Unit)
:annotations (Military-Unit-Type))
(defconcept SCUD-Brigade
:is (:and Brigade SCUD-Unit)
:annotations (Military-Unit-Type))
(defconcept SCUD-Battalion
:is (:and Battalion SCUD-Unit)
:annotations (Military-Unit-Type))
(defconcept SCUD-Battery
:is (:and Battery SCUD-Unit)
:annotations (Military-Unit-Type))
(defconcept HET-Company
:is (:and Company HET-Unit)
:annotations (Military-Unit-Type))
;;; Reconnaissance units:
(defconcept Recon-Battalion
:is (:and Battalion Reconnaissance-Unit)
:annotations (Military-Unit-Type))
(defconcept Recon-Company
:is (:and Company Reconnaissance-Unit)
:annotations (Military-Unit-Type))
(defconcept Recon-Platoon
:is (:and Platoon Reconnaissance-Unit)
:annotations (Military-Unit-Type))
;;; Anti-Tank units:
(defconcept Anti-Tank-Battalion
:is (:and Battalion Anti-Tank-Unit)
:annotations (Military-Unit-Type))
(defconcept Anti-Tank-Company
:is (:and Company Anti-Tank-Unit)
:annotations (Military-Unit-Type))
(defconcept Anti-Tank-Platoon
:is (:and Platoon Anti-Tank-Unit)
:annotations (Military-Unit-Type))
;;; Headquarter units:
(defconcept Headquarter-Company
:is (:and Company Headquarter-Unit)
:annotations (Military-Unit-Type))
;;; Support units:
(defconcept Support-Battalion
:is (:and Battalion Support-Unit)
:annotations (Military-Unit-Type))
(defconcept Support-Company
:is (:and Company Support-Unit)
:annotations (Military-Unit-Type))
(defconcept Support-Platoon
:is (:and Platoon Support-Unit)
:annotations (Military-Unit-Type))
;;; Chemical units:
(defconcept Chemical-Platoon
:is (:and Platoon Chemical-Unit)
:annotations (Military-Unit-Type))
;;; Commando units
(defconcept Commando-Battalion
:is (:and Battalion Commando-Unit)
:annotations (Military-Unit-Type))
(defconcept Commando-Company
:is (:and Company Commando-Unit)
:annotations (Military-Unit-Type))
;;; Weapons units
(defconcept Weapons-Company
:is (:and Company Weapons-Unit)
:annotations (Military-Unit-Type))
;;; Maintenance units
(defconcept Maintenance-Company
:is (:and Company Maintenance-Unit)
:annotations (Military-Unit-Type))
;;; Transport units
(defconcept Transport-Company
:is (:and Company Transport-Unit)
:annotations (Military-Unit-Type))
;;; Service units
(defconcept Service-Company
:is (:and Company Service-Unit)
:annotations (Military-Unit-Type))
;;; Equipment maintained and operated by a unit:
(defconcept Object-Collection
:is-primitive Group)
;; We use CYC's `group-cardinality' and `group-member-type' to represent
;; collections of certain sizes and types.
(defconcept Equipment-Collection
:is-primitive Object-Collection)
(defrelation maintained-equipment
"Maintained equipment encompasses all equipment a particular unit
has (including spares, etc.). All of that has to move if the whole
unit moves. Example: `(maintained-equipment 1-35 50-M60A3s-1)' means that
the military unit 1-35 maintains the equipment collection 50 50-M60A3s-1,
which is a collection of 50 M60A3 main battle tanks."
:domain Military-Organization
:range Equipment-Collection)
(defrelation mission-equipment
"Mission equipment encompasses all equipment actively involved in a
particular military operation. Right now we don't model differences
based on different types of operations, i.e., the value of that role
describes the equipment involved in a typical mission of that unit.
Example: `(mission-equipment 1-35 40-M60A3s-1)' means that the military
unit 1-35 typically uses the collection 40-M60A3s-1, which is a collection
of 40 M60A3 main battle tanks."
:domain Military-Organization
:range Equipment-Collection)
;;
;;;;;; Aggregating equipment:
;;
(defrelation total-mission-equipment
"An equipment collection which combines all `mission-equipment' collections
of the same equipment type for a military unit and all its subordinate units.
The collection of all `total-mission-equipment' collections of a military unit
summarizes all different available equipment types and their associated
cardinalities.
Example: (retrieve ?e (total-mission-equipment
1st-iranian-infantry-division ?e))
generates a set of equipment collections, where each element represents a
unique equipment type and equipment cardinalities are accumulated for
all subordinate units."
:domain Military-Organization
:range Equipment-Collection
:characteristics :multiple-valued
:function
((?unit)
(aggregate-collections
(retrieve ?equipment
(:for-some (?subUnit)
(:and (subordinate-unit* ?unit ?subUnit)
(mission-equipment ?subUnit ?equipment))))
nil)))
(defrelation total-mission-equipment-of-type
"A computed relation yielding a single equipment collection that
combines all `mission-equipment' collections whose equipment type is
a subtype of some arbitrary type for a military unit and all its
subordinate units.
Example: (retrieve ?e (total-mission-equipment-of-type
1st-iranian-infantry-division Tank--Vehicle ?e))
generates the collection of all tanks of the 1st Iranian infantry division."
:arity 3
:domains (Military-Organization Concept)
:range Equipment-Collection
:characteristics :single-valued
:function
((?unit ?type)
(aggregate-collections
(retrieve ?equipment
(:for-some (?subUnit)
(:and (subordinate-unit* ?unit ?subUnit)
(mission-equipment ?subUnit ?equipment))))
?type)))
(defun aggregate-collections (collections filterType)
;; Aggregate `collections' into a new set of collections where each
;; element type is represented exactly once and where cardinalities
;; of same-type collections are combined.
;; If `filterType' is non-NIL, generate a single collection with
;; `filterType' as the element type and the combined cardinalities
;; of all `collections' whose element type is a subtype of `filterType'.
(let* ((groupMemberType (get-relation 'group-member-type))
(groupCardinality (get-relation 'group-cardinality))
(equipmentCollections
(loop for col in collections
collect (cons (first (get-role-values col groupMemberType))
(first (get-role-values col groupCardinality)))))
(combinedCollections nil)
(currentType nil)
(?collection nil))
(when filterType
(unless (or (symbolp filterType)
(concept-p filterType))
(setq filterType (loom::name filterType)))
(setq filterType (get-concept filterType :no-error-p t))
(unless filterType
(setq equipmentCollections nil)))
(cond (filterType
(setq equipmentCollections
(list
(cons filterType
(loop for (type . count) in equipmentCollections
when (or (eq type filterType)
(and (concept-p type)
(member filterType
(get-superrelations type))))
sum count)))))
(t
(setq equipmentCollections
(sort equipmentCollections
#'(lambda (type1 type2)
(let ((context1 (context type1))
(context2 (context type2)))
(cond ((eq context1 context2)
(string< (loom::name type1)
(loom::name type2)))
((< (loom::ctxt-number
(loom::ctxt context1))
(loom::ctxt-number
(loom::ctxt context2)))))))
:key #'car))))
(when equipmentCollections
(loop for (type . count) in equipmentCollections
do (cond ((not (eq type currentType))
(setq currentType type)
(push (cons type count) combinedCollections))
(t (incf (rest (first combinedCollections)) count)))))
(setq combinedCollections
(loop for (?type . ?count) in (nreverse combinedCollections)
do (setq ?collection (create nil 'Equipment-Collection))
collect (tell (:about ?collection Equipment-Collection
(group-member-type ?type)
(group-cardinality ?count)))))
(if filterType
(first combinedCollections)
combinedCollections)))
(compile 'aggregate-collections)
#|
;; The expression below computes the number of main battle tanks of
;; a typical US tank battalion from scratch:
(apply #'+
(mapcar #'second
;; We have to include the equipment collection instance in
;; every tuple, otherwise we only get the set of distinct
;; collection cardinalities, since duplicates get removed:
(retrieve (?e ?n)
(:for-some (?p ?u ?t)
(:and (prototypical-instance US-Tank-Battalion ?p)
(subordinate-unit* ?p ?u)
(mission-equipment ?u ?e)
(group-member-type ?e ?t)
(:or (:same-as ?t Main-Battle-Tank)
(subrelations Main-Battle-Tank ?t))
(group-cardinality ?e ?n))))))
|#
(defrelation max-load-class-in-military-unit
"The load class of the heaviest piece of mission equipment operated
by a military unit."
:domain Military-Organization
:range Integer
:characteristics :single-valued
:function
((?unit)
(let ((equipmentMasses
(retrieve
?mass (:for-some (?subUnit ?equipment ?type)
(:and (subordinate-unit* ?unit ?subUnit)
(mission-equipment ?subUnit ?equipment)
(group-member-type ?equipment ?type)
(role-values ?type mass-of-object ?mass)))))
(maxMass 0))
(when equipmentMasses
(setq maxMass (apply #'ms:dim-max equipmentMasses)))
(when (ms:dim-number-p maxMass)
(setq maxMass (ms:dim-value maxMass "kg")))
(ceiling maxMass 1000))))
(defrelation min-max-fording-depth-in-military-unit
"The smallest maximum fording depth of all vehicles operated
by a military unit."
:domain Military-Organization
:range Integer
:characteristics :single-valued
:function min-max-fording-depth-in-military-unit-fn)
(defun min-max-fording-depth-in-military-unit-fn (?unit)
(let ((equipmentTypes
(retrieve
?type (:for-some (?subUnit ?equipment)
(:and (subordinate-unit* ?unit ?subUnit)
(mission-equipment ?subUnit ?equipment)
(group-member-type ?equipment ?type)
(concept ?type)))))
(Vehicle (get-concept 'Military-Vehicle))
(FordingVehicle (get-concept 'Military-Fording-Vehicle))
(AmphibiousVehicle (get-concept 'Military-Amphibious-Vehicle))
(maxFordingDepths '(0.5))
(minMaxFordingDepth 0.5))
;; Punt if there is any vehicle that's neither amphibious nor fording:
(when (not (loop for type in equipmentTypes
thereis (and (subconcept-p type Vehicle)
(not (or (subconcept-p type FordingVehicle)
(subconcept-p
type AmphibiousVehicle))))))
;; This is somewhat fishy, since it disregards any vehicle types
;; for which the fording depth isn't known - we could use a default:
(setq maxFordingDepths
(retrieve
?depth (:for-some (?subUnit ?equipment ?type)
(:and (subordinate-unit* ?unit ?subUnit)
(mission-equipment ?subUnit ?equipment)
(group-member-type ?equipment ?type)
(role-values ?type max-fording-depth ?depth)))))
(when maxFordingDepths
(setq minMaxFordingDepth (apply #'ms:dim-min maxFordingDepths)))
(when (ms:dim-number-p minMaxFordingDepth)
(setq minMaxFordingDepth (ms:dim-value minMaxFordingDepth "m"))))
minMaxFordingDepth))
(compile 'min-max-fording-depth-in-military-unit-fn)
;;; Affiliated units:
;; NOTE: Can't use :defaults to define a typical unit organization, since
;; a multi-valued relation cannot be overridden at the instance level,
;; i.e., every instance of `us-tank-battalion' will at least contain
;; the default values below as its subordinate units. BUMMER!
#|
(defconcept US-Tank-Battalion
:is (:and Tank-Battalion
(:filled-by affiliated-with UNITED-STATES))
:defaults (:filled-by subordinate-unit
typical-us-tank-battalion-command-unit
typical-us-tank-company-1
typical-us-tank-company-2
typical-us-tank-company-3
typical-us-medical-platoon))
|#
(defrelation prototypical-instance
:domain Concept
:range Thing
:characteristics :single-valued)
;; Instead, we create prototype unit instances to define default organizations:
(tell (Tank-Battalion typical-us-tank-battalion)
(Tank-Company typical-us-tank-company)
(Tank-Platoon typical-us-tank-platoon))
(defconcept US-Tank-Battalion
:is (:and Tank-Battalion
(:filled-by affiliated-with UNITED-STATES))
:annotations ((prototypical-instance typical-us-tank-battalion)))
(defconcept US-Tank-Company
:is (:and Tank-Company
(:filled-by affiliated-with UNITED-STATES))
:annotations ((prototypical-instance typical-us-tank-company)))
(defconcept US-Tank-Platoon
:is (:and Tank-Platoon
(:filled-by affiliated-with UNITED-STATES))
:annotations ((prototypical-instance typical-us-tank-platoon)))
;;;Iranian Corps
(defconcept Iranian-Corps
:is (:and Corps
(:filled-by affiliated-with IRAN))
:annotations ((prototypical-instance 1st-iranian-corps)))
;;; Iranian infantry units
(defconcept Iranian-Infantry-Division
:is (:and Infantry-Division
(:filled-by affiliated-with IRAN))
:annotations ((prototypical-instance 1st-iranian-infantry-division)))
(defconcept Iranian-Infantry-Brigade
:is (:and Infantry-Brigade
(:filled-by affiliated-with IRAN))
:annotations ((prototypical-instance typical-iranian-infantry-brigade)))
(defconcept Iranian-Infantry-Battalion
:is (:and Infantry-Battalion
(:filled-by affiliated-with IRAN))
:annotations ((prototypical-instance typical-iranian-infantry-battalion)))
(defconcept Iranian-Infantry-Company
:is (:and Infantry-Company
(:filled-by affiliated-with IRAN))
:annotations ((prototypical-instance typical-iranian-infantry-company)))
(defconcept Iranian-Infantry-Platoon
:is (:and Infantry-Platoon
(:filled-by affiliated-with IRAN))
:annotations ((prototypical-instance typical-iranian-infantry-platoon)))
;;; Iranian tank units
(defconcept Iranian-Tank-Battalion
:is (:and Tank-Battalion
(:filled-by affiliated-with IRAN)))
(defconcept Iranian-Tank-Company
:is (:and Tank-Company
(:filled-by affiliated-with IRANS)))
(defconcept Iranian-Tank-Platoon
:is (:and Tank-Platoon
(:filled-by affiliated-with IRANS)))
;;; Iranian engineer units
(defconcept Iranian-Engineer-Brigade
:is (:and Engineer-Brigade
(:filled-by affiliated-with IRAN)))
(defconcept Iranian-Engineer-Battalion
:is (:and Engineer-Battalion
(:filled-by affiliated-with IRAN)))
(defconcept Iranian-Engineer-Company
:is (:and Engineer-Company
(:filled-by affiliated-with IRANS)))
;;; Iranian mechanized infantry units
(defconcept Iranian-Mechanized-Infantry-Brigade
:is (:and Mechanized-Infantry-Brigade
(:filled-by affiliated-with IRAN)))
(defconcept Iranian-Mechanized-Infantry-Battalion
:is (:and Mechanized-Infantry-Battalion
(:filled-by affiliated-with IRAN))
:annotations ((prototypical-instance iranian-d1-mechanized-infantry-battalion)))
(defconcept Iranian-Mechanized-Infantry-Company
:is (:and Mechanized-Infantry-Company
(:filled-by affiliated-with IRAN))
:annotations ((prototypical-instance iranian-d1-mechanized-infantry-company)))
(defconcept Iranian-Artillery-Brigade
:is (:and Artillery-Brigade
(:filled-by affiliated-with IRAN)))
(defconcept Iranian-Recon-Battalion
:is (:and Recon-Battalion
(:filled-by affiliated-with IRAN)))
(defconcept Iranian-Recon-Company
:is (:and Recon-Company
(:filled-by affiliated-with IRAN)))
(defconcept Iranian-Recon-Platoon
:is (:and Recon-Platoon
(:filled-by affiliated-with IRAN)))
;;
;;;;;; Definition support for military unit instances
;;
(defmacro retrieve-military-unit-definition (name)
`(get ,name :military-unit-definition))
(defmacro store-military-unit-definition (name definition)
`(setf (get ,name :military-unit-definition) ,definition))
(defun help-define-military-unit (name arguments &optional parent-name)
;; Helper function for `define-military-unit'.
(let ((seen-type-p nil)
(assertions nil)
(other-assertions nil))
(when (not (symbolp name))
(error "define-military-unit: Illegal unit name `~s'" name))
(loop for arg in arguments
do (typecase arg
(CONS
(case (first arg)
(affiliation
(push `(affiliated-with ,name ,(second arg)) assertions))
(subunits
(setq assertions
(append (yield-subordinate-unit-assertions name (rest arg))
assertions)))
(equipment
(setq assertions
(append (yield-unit-equipment-assertions name (rest arg))
assertions)))
(like
(setq assertions
(append (yield-prototype-unit-assertions
name (second arg) parent-name)
assertions))
(setq seen-type-p t))
(otherwise
(push arg other-assertions))))
(otherwise
(setq seen-type-p t)
(push `(,arg ,name) assertions))))
(when (not seen-type-p)
(error "define-military-unit: Missing unit type for unit `~s'" name))
(store-military-unit-definition name arguments)
`(,@(when other-assertions
`((:about ,name ,@(reverse other-assertions))))
,@assertions)))
(defun yield-absolute-military-unit-name
(parent-name child-name &optional soft-p)
(when (not (symbolp child-name))
(error "define-military-unit: Illegal subordinate unit name `~s' in ~
unit `~s'" child-name parent-name))
(let ((absolute-name (format nil "~a/~a" parent-name child-name)))
(if soft-p
(find-symbol absolute-name (symbol-package parent-name))
(intern absolute-name (symbol-package parent-name)))))
(defun yield-subordinate-unit-assertions (name subunit-specs)
(let ((assertions nil))
(loop for sub in subunit-specs
do (when (consp sub)
(let ((subName
(yield-absolute-military-unit-name name (first sub))))
(setq assertions
(append (help-define-military-unit
subName (rest sub) name)
assertions))
(setq sub subName)))
(cond ((find-concept sub :no-warning-p t)
(warn "define-military-unit: Subordinate unit ~
`~s' of unit `~s' conflicts with a concept ~
of the same name; ignoring it"
sub name))
(t (push `(subordinate-unit ,name ,sub)
assertions))))
assertions))
(defun yield-unit-equipment-assertions (name equipment-specs)
(let ((assertions nil))
(loop for spec in equipment-specs
do (when (not (and (consp spec)
(numberp (first spec))
(symbolp (second spec))))
(error "define-military-unit: Illegal equipment ~
specification for unit `~s'" name))
(when (not (find-concept (second spec) :no-warning-p t))
(warn "define-military-unit: Equipment type `~s' ~
for unit `~s' is not yet defined"
(second spec) name))
(let ((collectionVar (gentemp "$EQUIP-")))
(push `(Equipment-Collection ,collectionVar) assertions)
(push `(group-cardinality ,collectionVar ,(first spec))
assertions)
(push `(group-member-type ,collectionVar ,(second spec))
assertions)
(push `(mission-equipment ,name ,collectionVar) assertions)))
assertions))
(defun yield-prototype-unit-assertions (name prototype parent-name)
(when (not (symbolp prototype))
(error "define-military-unit: Illegal prototype unit name `~s' in ~
unit `~s'" prototype name))
(let ((prototype-definition
(or (retrieve-military-unit-definition
(yield-absolute-military-unit-name parent-name prototype t))
(retrieve-military-unit-definition prototype))))
(when (null prototype-definition)
(error "define-military-unit: Prototype unit `~s' used in ~
unit `~s' has not yet been defined" prototype name))
(help-define-military-unit
name (subst name prototype prototype-definition) parent-name)))
(defmacro define-military-unit (name &rest arguments)
"Definition macro for military unit instances.
Syntax:
(define-military-unit <name>
<unit-type>
[(subunits <subunit-spec>+)]
[(equipment (<count> <type>)+)]
[(like <prototype-name>)]
[(affiliation <country-name>)]
<other-assertion>*)
Subunits in <subunit-spec> can be either symbols which are taken to be the
absolute names of units defined elsewhere, or a list of the form
(<sub-unit-relative-name> <argument>+)
where the accepted arguments to the subunit are the same as to
`define-military-unit'. This allows one to define complex unit structures
in a single definition. The relative name of the subunit is concatenated
with the name of its parent unit to generate a unique absolute name for
the generated instance.
The syntax `(like <prototype-name>)' can be used to avoid repetitive
definitions by including (or copying-in) the definition of a previously defined
prototype unit. The prototype name can be either absolute, or, within a
<subunit-spec>, it can also be relative to the current parent unit and refer
to a previously defined subunit."
(handler-case
`(tell ,@(reverse (help-define-military-unit name arguments)))
(error (condition)
(format t "Error: ~a" condition)
nil)))
;;
;;;;;; Unit instances
;;
;; Some typical US units:
(define-military-unit typical-us-tank-platoon
US-Tank-Platoon
(equipment (4 M1)))
(define-military-unit typical-us-tank-company
US-Tank-Company
(subunits (command-unit Military-Unit
(affiliation UNITED-STATES))
(platoon1 (like typical-us-tank-platoon))
(platoon2 (like platoon1))
(platoon3 (like platoon1))))
(define-military-unit typical-us-tank-battalion
US-Tank-Battalion
(subunits (command-unit Military-Unit
(equipment (2 M1)))
(company1 (like typical-us-tank-company))
(company2 (like company1))
(company3 (like company1))
(medical-platoon Platoon)))
;; Some typical Iranian units:
(define-military-unit typical-iranian-infantry-platoon
Iranian-Infantry-Platoon)
(define-military-unit typical-iranian-infantry-company
Iranian-Infantry-Company
(subunits (command-unit Military-Unit)
(platoon1 (like typical-iranian-infantry-platoon))
(platoon2 (like platoon1))
(platoon3 (like platoon1))))
(define-military-unit typical-iranian-infantry-battalion
Iranian-Infantry-Battalion
(subunits (command-unit Military-Unit
(equipment (3 M577)))
(recon-platoon Recon-Platoon
(equipment (6 BRDM-2)))
(supply-and-transport-company
Company
(equipment (20 Cargo-truck)
(2 Tank-truck)))
(weapons-company
Company
(equipment (2 Cargo-truck)
(4 BRDM-2-AT-3)))
(company1 (like typical-iranian-infantry-company))
(company2 (like company1))
(company3 (like company1))))
(define-military-unit typical-iranian-infantry-brigade
Iranian-Infantry-Brigade
(subunits (command-unit Military-Unit
(equipment (9 Cargo-truck)
(1 Tank-truck)))
(command-company Company) ;; ???
(chemical-platoon Platoon
(equipment (1 Cargo-truck)
(2 Tank-truck)
(1 Generic-Iranian-Decontamination-Truck)))
(recon-company Recon-Company
(equipment (18 BRDM-2)))
(supply-and-transport-company
Company
(equipment (45 Cargo-truck)
(15 Tank-truck)))
(mortar-battery Mortar-Battery
(equipment (12 120mm-mortar)))
(battalion1 (like typical-iranian-infantry-battalion))
(battalion2 (like battalion1))
(battalion3 (like battalion1))))
(define-military-unit typical-iranian-mechanized-infantry-brigade
Iranian-Mechanized-Infantry-Brigade)
(define-military-unit typical-iranian-recon-battalion
Iranian-Recon-Battalion)
;;
;;;;;; Iranian unit instances
;;
;; 1st Iranian Infantry Division
(define-military-unit 1st-iranian-infantry-division
Iranian-Infantry-Division
(subunits (headquarter-company Company
(affiliation IRAN)
(equipment
(43 Cargo-truck)
(3 Tank-truck)
(3 M577)))
(infantry-brigade1 (like typical-iranian-infantry-brigade))
(infantry-brigade2 (like infantry-brigade1))
(infantry-brigade3 (like infantry-brigade1))
(mechanized-brigade Iranian-Mechanized-Infantry-Brigade
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(14 Cargo-truck)
(1 Tank-truck)
(4 M577)))
(mechanized-infantry-battalion Military-Unit
(affiliation IRAN)
(subunits
(command-unit Military-Unit
(equipment
(3 M577)))
(mechanized-recon-platoon Iranian-Recon-Platoon
(affiliation Iran)
(equipment
(6 BRDM-2)))
(mechanized-supply-and-transport-company Company
(affiliation Iran)
(equipment
(12 Cargo-truck)
(2 Tank-truck)))
(mechanized-weapons-company Company
(affiliation Iran)
(equipment
(2 Cargo-truck)
(4 BRDM-2-AT-3)))
(mechanized-company1 Iranian-Mechanized-Infantry-Company
(affiliation Iran)
(equipment
(12 M113)))
(mechanized-company2 (like mechanized-company1))
(mechanized-company3 (like mechanized-company1))))))
(recon-battalion Iranian-Recon-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(2 Cargo-truck)
(1 M577)))
(recon-company1 Iranian-Recon-Company
(affiliation Iran)
(equipment
(15 BRDM-2)))
(recon-company2 (like recon-company1))
(recon-company3 (like recon-company1))))
(field-artillery-brigade Iranian-Artillery-Brigade
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(10 Cargo-truck)
(5 M577)))
(maintenance-company Company
(affiliation Iran)
(equipment
(19 Cargo-truck)))
(transport-company Company
(affiliation Iran)
(equipment
(48 Cargo-truck)
(3 Tank-truck)))
(battalion1-transport Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(7 Cargo-truck)))
(battery1-transport Artillery-Battery
(affiliation Iran)
(equipment
(15 Cargo-truck)
(6 M101)))
(battery2-transport (like battery1-transport))
(battery3-transport (like battery1-transport))
(battery-service Artillery-Battery
(affiliation Iran)
(equipment
(8 Cargo-truck)))))
(battalion2-transport (like battalion1-transport))
(battalion3-transport (like battalion1-transport))
(battalion-supply Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(7 Cargo-truck)))
(battery1-supply Artillery-Battery
(affiliation Iran)
(equipment
(9 Cargo-truck)
(6 M109)))
(battery2-supply (like battery1-supply))
(battery3-supply (like battery1-supply))
(service-company Company
(affiliation Iran)
(equipment
(10 Cargo-truck)
(2 Tank-truck)))))))
(air-defense-artillery-brigade Iranian-Artillery-Brigade
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(15 Cargo-truck)))
(battalion-zpu Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(6 Cargo-truck)))
(battery-zpu4 Artillery-Battery
(affiliation Iran)
(equipment
(15 Cargo-truck)
(6 ZPU-4)))
(battery-m1939 Artillery-Battery
(affiliation Iran)
(equipment
(15 Cargo-truck)
(6 M1939)))
(battery-s60 Artillery-Battery
(affiliation Iran)
(equipment
(15 Cargo-truck)
(6 S-60)))))
(battalion-zsu Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(6 Cargo-truck)))
(battery1-zsu Artillery-Battery
(affiliation Iran)
(equipment
(6 Cargo-truck)
(3 ZSU-23-4M)))
(battery2-zsu (like battery1-zsu))
(battery3-zsu (like battery1-zsu))
(battery-sa Artillery-Battery
(affiliation Iran)
(equipment
(6 Cargo-truck)
(3 SA-9)))))
(battalion-sa Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(6 Cargo-truck)))
(battery1-sa Artillery-Battery
(affiliation Iran)
(equipment
(9 Cargo-truck)))
(battery2-sa (like battery1-sa))
(battery2-sa (like battery1-sa))))))
(anti-tank-battalion Battalion
(affiliation IRAN)
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(2 Cargo-truck)
(1 M577)))
(company1 Company
(affiliation Iran)
(equipment
(15 BRDM-2-AT-3)))
(company2 (like company1))
(company3 (like company1))))
(tank-battalion Iranian-Tank-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(6 Cargo-truck)
(1 M60A1)
(2 M577)))
(service-company Company
(affiliation IRAN)
(equipment
(13 Cargo-truck)
(8 M113)
(3 M88)))
(company1 Iranian-Tank-Company
(affiliation Iran)
(equipment
(13 M60A1)))
(company2 (like company1))
(company3 (like company1))))
(commando-battalion-command-unit Military-Unit
(affiliation IRAN)
(equipment
(7 Cargo-truck)))
(engineer-battalion Iranian-Engineer-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(5 Cargo-truck)))
(service-company Iranian-Engineer-Company
(equipment
(32 Cargo-truck)
(4 Tank-truck)))
(company-large Iranian-Engineer-Company
(equipment
(3 AVLB)
(15 Cargo-truck)
(3 TMMBridge)))
(company1-small Iranian-Engineer-Company
(equipment
(1 AVLB)
(6 Cargo-truck)
(1 CEV)))
(company2-small (like company1-small))))
(support-battalion Battalion
(affiliation Iran)
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(5 Cargo-truck)))
(support-company-small Company
(affiliation Iran)
(equipment
(12 Cargo-truck)))
(support-company1-large Company
(affiliation Iran)
(equipment
(45 Cargo-truck)
(14 Tank-truck)))
(support-company2-large (like support-company1-large))))))
;; 2nd Iranian Infantry Division
(define-military-unit 2nd-iranian-infantry-division
Iranian-Infantry-Division
(subunits (headquarter-company Company
(affiliation IRAN)
(equipment
(43 Cargo-truck)
(3 Tank-truck)
(3 M577)))
(infantry-brigade1 (like typical-iranian-infantry-brigade))
(infantry-brigade2 (like infantry-brigade1))
(infantry-brigade3 (like infantry-brigade1))
(mechanized-brigade Iranian-Mechanized-Infantry-Brigade
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(14 Cargo-truck)
(1 Tank-truck)
(4 M577)))
(mechanized-infantry-battalion Military-Unit
(affiliation IRAN)
(subunits
(command-unit Military-Unit
(equipment
(3 M577)))
(mechanized-recon-platoon Iranian-Recon-Platoon
(affiliation Iran)
(equipment
(6 BRDM-2)))
(mechanized-supply-and-transport-company Company
(affiliation Iran)
(equipment
(12 Cargo-truck)
(2 Tank-truck)))
(mechanized-weapons-company Company
(affiliation Iran)
(equipment
(2 Cargo-truck)
(4 BRDM-2-AT-3)))
(mechanized-company1 Iranian-Mechanized-Infantry-Company
(affiliation Iran)
(equipment
(12 M113)))
(mechanized-company2 (like mechanized-company1))
(mechanized-company3 (like mechanized-company1))))))
(recon-battalion Iranian-Recon-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(2 Cargo-truck)
(1 M577)))
(recon-company1 Iranian-Recon-Company
(affiliation Iran)
(equipment
(15 BRDM-2)))
(recon-company2 (like recon-company1))
(recon-company3 (like recon-company1))))
(field-artillery-brigade Iranian-Artillery-Brigade
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(10 Cargo-truck)
(5 M577)))
(maintenance-company Company
(affiliation Iran)
(equipment
(19 Cargo-truck)))
(transport-company Company
(affiliation Iran)
(equipment
(48 Cargo-truck)
(3 Tank-truck)))
(battalion1-transport Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(7 Cargo-truck)))
(battery1-transport Artillery-Battery
(affiliation Iran)
(equipment
(15 Cargo-truck)
(6 M101)))
(battery2-transport (like battery1-transport))
(battery3-transport (like battery1-transport))
(battery-service Artillery-Battery
(affiliation Iran)
(equipment
(8 Cargo-truck)))))
(battalion2-transport (like battalion1-transport))
(battalion3-transport (like battalion1-transport))
(battalion-supply Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(7 Cargo-truck)))
(battery1-supply Artillery-Battery
(affiliation Iran)
(equipment
(9 Cargo-truck)
(6 M109)))
(battery2-supply (like battery1-supply))
(battery3-supply (like battery1-supply))
(service-company Company
(affiliation Iran)
(equipment
(10 Cargo-truck)
(2 Tank-truck)))))))
(air-defense-artillery-brigade Iranian-Artillery-Brigade
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(15 Cargo-truck)))
(battalion-zpu Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(6 Cargo-truck)))
(battery-zpu4 Artillery-Battery
(affiliation Iran)
(equipment
(15 Cargo-truck)
(6 ZPU-4)))
(battery-m1939 Artillery-Battery
(affiliation Iran)
(equipment
(15 Cargo-truck)
(6 M1939)))
(battery-s60 Artillery-Battery
(affiliation Iran)
(equipment
(15 Cargo-truck)
(6 S-60)))))
(battalion-zsu Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(6 Cargo-truck)))
(battery1-zsu Artillery-Battery
(affiliation Iran)
(equipment
(6 Cargo-truck)
(3 ZSU-23-4M)))
(battery2-zsu (like battery1-zsu))
(battery3-zsu (like battery1-zsu))
(battery-sa Artillery-Battery
(affiliation Iran)
(equipment
(6 Cargo-truck)
(3 SA-9)))))
(battalion-sa Artillery-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(6 Cargo-truck)))
(battery1-sa Artillery-Battery
(affiliation Iran)
(equipment
(9 Cargo-truck)))
(battery2-sa (like battery1-sa))
(battery2-sa (like battery1-sa))))))
(anti-tank-battalion Battalion
(affiliation IRAN)
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(2 Cargo-truck)
(1 M577)))
(company1 Company
(affiliation Iran)
(equipment
(15 BRDM-2-AT-3)))
(company2 (like company1))
(company3 (like company1))))
(101st-armor-battalion Iranian-Tank-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(6 Generic-Iranian-Light-Wheeled-Vehicle)
(1 M60A1)
(2 M113)))
(armor-supply-and-maint-platoon Iranian-Tank-Platoon
(affiliation Iran)
(equipment
(2 M113)
(1 M88)
(2 Generic-Iranian-Light-Wheeled-Vehicle)
(18 Generic-Iranian-Heavy-Wheeled-Vehicle)))
(recon-platoon Iranian-Recon-Platoon
(affiliation Iran)
(equipment
(6 Generic-Iranian-Light-Wheeled-Vehicle)
(8 Bangalore-Torpedo)
(8 Explosives)))
(medical-sect Squad
(affiliation Iran)
(equipment
(5 Generic-Iranian-Light-Wheeled-Vehicle)))
(company1 Iranian-Tank-Company
(affiliation Iran)
(equipment
(13 M60A1)
(2 M113)
(1 M88)
(1 Generic-Iranian-Light-Wheeled-Vehicle)
(2 Generic-Iranian-Heavy-Wheeled-Vehicle)
(3 Tank-Plow)
(1 Tank-Blade)))
(company2 (like company1))
(company3 (like company1))))
(commando-battalion-command-unit Military-Unit
(affiliation IRAN)
(equipment
(7 Cargo-truck)))
(engineer-battalion Iranian-Engineer-Battalion
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(11 Generic-Iranian-Light-Wheeled-Vehicle)
(1 Generic-Iranian-Heavy-Wheeled-Vehicle)
(5 M113)))
(service-company Iranian-Engineer-Company
(affiliation Iran)
(equipment
(2 M88)
(7 Generic-Iranian-Light-Wheeled-Vehicle)
(18 Generic-Iranian-Heavy-Wheeled-Vehicle)
(6 Military-Dozer)))
(company1 Iranian-Engineer-Company
(affiliation Iran)
(equipment
(14 M113)
(6 Generic-Iranian-Light-Wheeled-Vehicle)
(8 Generic-Iranian-Heavy-Wheeled-Vehicle)
(4 AVLB)
(2 CEV)
(4 MICLIC)
(10 Bangalore-Torpedo)))
(company2 (like company1))
(company3 (like company1))))
(support-battalion Battalion
(affiliation Iran)
(subunits
(command-unit Military-Unit
(affiliation IRAN)
(equipment
(5 Cargo-truck)))
(support-company-small Company
(affiliation Iran)
(equipment
(12 Cargo-truck)))
(support-company1-large Company
(affiliation Iran)
(equipment
(45 Cargo-truck)
(14 Tank-truck)))
(support-company2-large (like support-company1-large))))))
;; 201st MGB Company
;; 201st MGB Company of 1st Iranian Corps:
(define-military-unit 201st-mgb-company
Company
(affiliation IRAN)
(equipment
(4 MGB)
(6 Generic-Iranian-Light-Wheeled-Vehicle)
(36 Generic-Iranian-Heavy-Wheeled-Vehicle)
(1 Military-Dozer)
(1 Military-Loader)
(1 Military-Crane)))
;; 202nd M4T6 Float Company
;; 202nd M4T6 Float Company of 1st Iranian Corps:
(define-military-unit 202nd-m4t6-float-company
Company
(affiliation IRAN)
(equipment
(6 M4T6)
(18 BEB)
(10 Generic-Iranian-Light-Wheeled-Vehicle)
(68 Generic-Iranian-Heavy-Wheeled-Vehicle)
(1 Military-Dozer)
(1 Military-Crane)))
;; 203rd Ribbon Company
;; 203rd Ribbon Company of 1st Iranian Corps:
(define-military-unit 203rd-ribbon-company
Company
(affiliation IRAN)
(equipment
(30 Ribbon-Bridge-Bay)
(12 Ribbon-Bridge-Ramp)
(14 BEB)
(9 Generic-Iranian-Light-Wheeled-Vehicle)
(70 Generic-Iranian-Heavy-Wheeled-Vehicle)
(1 Military-Dozer)
(1 Military-Crane)))
;; Engineer Brigade
(define-military-unit 1st-iranian-corps-engineer-brigade
Iranian-Engineer-Brigade
(subunits 201st-mgb-company
202nd-m4t6-float-company
203rd-ribbon-company))
;; 1st Iranian Corps
(define-military-unit 1st-iranian-corps
Iranian-Corps
(subunits 1st-iranian-infantry-division
2nd-iranian-infantry-division
1st-iranian-corps-engineer-brigade))
(tellm) |
#include "\x\alive\addons\x_lib\script_component.hpp"
SCRIPT(eventLog);
/* ----------------------------------------------------------------------------
Function: MAINCLASS
Description:
Event log
Parameters:
Nil or Object - If Nil, return a new instance. If Object, reference an existing instance.
String - The selected function
Array - The selected parameters
Returns:
Any - The new instance or the result of the selected function and parameters
Attributes:
Boolean - debug - Debug enable, disable or refresh
Boolean - state - Store or restore state of analysis
Examples:
(begin example)
// create the command router
_logic = [nil, "create"] call ALIVE_fnc_eventLog;
(end)
See Also:
Author:
ARJay
Peer reviewed:
nil
---------------------------------------------------------------------------- */
#define SUPERCLASS ALIVE_fnc_baseClass
#define MAINCLASS ALIVE_fnc_eventLog
#define MTEMPLATE "ALiVE_EVENT_%1"
TRACE_1("event log - input", _this);
params ["_logic","_operation","_args"];
private _result = true;
switch(_operation) do {
case "init": {
if (isServer) then {
_logic setvariable ["super", QUOTE(SUPERCLASS)];
_logic setvariable ["class", QUOTE(MAINCLASS)];
_logic setvariable ["debug", false];
_logic setvariable ["listenerCount", 0];
_logic setvariable ["eventCount", 0];
_logic setvariable ["firstEvent", 0];
_logic setvariable ["maxEvents", 5];
_logic setvariable ["events", createHashMap];
_logic setvariable ["eventsByType", createHashMap];
_logic setvariable ["listeners", createHashMap];
_logic setvariable ["listenersByFilter", createHashMap];
};
};
case "destroy": {
[_logic,"debug", false] call MAINCLASS;
if (isServer) then {
_logic setvariable ["super", nil];
_logic setvariable ["class", nil];
[_logic,"destroy"] call SUPERCLASS;
};
};
case "debug": {
if(!isnil "_args") then {
_result = _logic getvariable "debug";
} else {
_logic setvariable ["debug", _args];
};
};
case "addListener": {
_args params ["_listener","_filters"];
private _debug = _logic getvariable "debug";
private _listeners = _logic getvariable "listeners";
private _filteredListeners = _logic getvariable "listenersByFilter";
private _listenerID = [_logic,"getNextListenerInsertID"] call MAINCLASS;
// store the listener in a hash by filter type
{
if !(_x in _filteredListeners) then {
_filteredListeners set [_x, createHashMapFromArray [
[_listenerID, _args]
]];
}else{
(_filteredListeners get _x) set [_listenerID, _args];
};
} forEach _filters;
// store the listener in the main hash
_listeners set [_listenerID, _args];
if (_debug) then {
//_listeners call ALIVE_fnc_inspectHash;
//_filteredListeners call ALIVE_fnc_inspectHash;
};
_result = _listenerID;
};
case "removeListener": {
private _listenerID = _args;
private _listeners = _logic getvariable "listeners";
private _filteredListeners = _logic getvariable "listenersByFilter";
private _listener = _listeners get _listenerID;
private _filters = _listener select 1;
{
(_filteredListeners get _x) deleteat _listenerID;
} forEach _filters;
_listeners deleteat _listenerID;
};
case "getListeners": {
_result = _logic getvariable "listeners";
};
case "clearListeners": {
_logic setvariable ["listeners", createHashMap];
_logic setvariable ["listenersByFilter", createHashMap];
};
case "getListenersByFilter": {
private _filter = _args;
private _filteredListeners = _logic getvariable "listenersByFilter";
_result = _filteredListeners get _filter;
};
case "maxEvents": {
if (!isnil "_args") then {
_logic setvariable ["maxEvents", _args];
} else {
_logic getvariable "maxEvents";
};
};
case "addEvent": {
private _event = _args;
private _debug = _logic getvariable "debug";
private _events = _logic getvariable "events";
private _eventsByType = _logic getvariable "eventsByType";
private _maxEvents = _logic getvariable "maxEvents";
private _eventID = [_logic,"getNextEventInsertID"] call MAINCLASS;
[_event,"id", _eventID] call ALIVE_fnc_hashSet;
private _type = [_event,"type"] call ALIVE_fnc_hashGet;
// store the event in a hash by type
if !(_type in _eventsByType) then {
_eventsByType set [_type, createHashMapFromArray [
[_eventID, _event]
]];
} else {
(_eventsByType get _type) set [_eventID, _event];
};
// remove first event if over the max limit
if (count _events > _maxEvents) then {
private _firstEvent = _logic getvariable "firstEvent";
[_logic,"removeEvent", format ["event_%1",_firstEvent]] call MAINCLASS;
_firstEvent = _firstEvent + 1;
_logic setvariable ["firstEvent", _firstEvent];
};
// store the event in the main hash
_events set [_eventID, _event];
if (_debug) then {
_event call ALIVE_fnc_inspectHash;
//_events call ALIVE_fnc_inspectHash;
//_eventsByType call ALIVE_fnc_inspectHash;
};
// dispatch event
private _filteredListeners = _logic getvariable "listenersByFilter";
private _typeListeners = _filteredListeners getOrDefault [_type, []];
private _globalListeners = _filteredListeners getOrDefault ["ALL", []];
private _listeners = [];
{
private _listener = _y select 0;
private _class = if (_listener isEqualType objNull) then {
_listeners pushback [_listener, _listener getVariable "class"];
} else {
_listeners pushback [_listener, [_listener,"class"] call ALIVE_fnc_hashGet];
};
} foreach _typeListeners;
{
private _listener = _y select 0;
private _class = if (_listener isEqualType objNull) then {
_listeners pushback [_listener, _listener getVariable "class"];
} else {
_listeners pushback [_listener, [_listener,"class"] call ALIVE_fnc_hashGet];
};
} foreach _globalListeners;
[_event, _listeners] spawn {
params ["_event","_listeners"];
{
_x params ["_listener","_class"];
if (_class isEqualType "") then {
_class = missionnamespace getvariable _class;
};
[_listener,"handleEvent", _event] call _class;
} foreach _listeners;
};
_result = _eventID;
};
case "removeEvent": {
private _eventID = _args;
private _events = _logic getvariable "events";
private _event = _events get _eventID;
if (isnil "_event") exitwith {};
private _type = [_event,"type"] call ALIVE_fnc_hashGet;
private _eventsByType = _logic getvariable "eventsByType";
private _eventsForType = _eventsByType get _type;
if (!isnil "_eventsForType") then {
_eventsForType deleteat _eventID;
};
_events deleteat _eventID;
};
case "getEventsByType": {
private _type = _args;
private _eventsByType = _logic getvariable "eventsByType";
_result = _eventsByType get _type;
};
case "getEvents": {
_result = _logic getvariable "events";
};
case "clearEvents": {
_logic setvariable ["events", createHashMap];
_logic setvariable ["eventsByType", createHashMap];
};
case "getNextListenerInsertID": {
private _listenerCount = _logic getvariable "listenerCount";
_result = format ["listener_%1", _listenerCount];
_logic setvariable ["listenerCount", _listenerCount + 1];
};
case "getNextEventInsertID": {
private _eventCount = _logic getvariable "eventCount";
_result = format ["event_%1", _eventCount];
_logic setvariable ["eventCount", _eventCount + 1];
};
default {
_result = _this call SUPERCLASS;
};
};
TRACE_1("event log - output",_result);
_result |
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.exceptions import UndefinedMetricWarning
from sklearn.utils import shuffle
from PIL import Image
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import warnings
import argparse
import os
def get_data(directory_path, image_size=(128, 128)):
"""
Load spectrogram images from a specified directory and resize them.
:param directory_path: Path to the directory containing spectrogram images.
:param image_size: A tuple indicating the size to which images should be resized.
:return: A NumPy array of images.
"""
images = []
# Iterate over files in the directory
for file in os.listdir(directory_path):
file_path = os.path.join(directory_path, file)
# Check if file is an image
if os.path.isfile(file_path) and file.lower().endswith(
(".png", ".jpg", ".jpeg")
):
# Open the image
with Image.open(file_path) as img:
# Resize image and convert to grayscale
img = img.resize(image_size).convert("L")
# Convert image to numpy array and normalize
img_array = np.array(img) / 255.0
images.append(img_array)
# Convert list of images to a NumPy array
return np.array(images)
def define_model():
"""
Define and return the CNN model.
"""
model = tf.keras.Sequential(
[
tf.keras.layers.Conv2D(
32, (3, 3), activation="relu", input_shape=(128, 128, 1)
),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3, 3), activation="relu"),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(128, (3, 3), activation="relu"),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(256, activation="relu"),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(1, activation="sigmoid"),
]
)
return model
def lr_schedule(epoch):
"""
Learning rate schedule function.
"""
lr = 1e-4
if epoch > 5:
lr *= 0.1
if epoch > 10:
lr *= 0.1
return lr
def compile_model(model):
"""
Compile the CNN model.
"""
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
return model
def train_model(model, X_train, y_train, X_val, y_val, epochs, patience):
"""
Train the model and return the training history.
"""
lr_scheduler = tf.keras.callbacks.LearningRateScheduler(lr_schedule)
early_stopping = tf.keras.callbacks.EarlyStopping(
monitor="val_loss", patience=patience, restore_best_weights=True
)
model_checkpoint = tf.keras.callbacks.ModelCheckpoint(
"best_model.h5", monitor="val_loss", save_best_only=True
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
history = model.fit(
X_train,
y_train,
epochs=epochs,
validation_data=(X_val, y_val),
callbacks=[early_stopping, model_checkpoint, lr_scheduler],
)
return history
def evaluate_model(model, X_test, y_test):
"""
Evaluate the model on the test set and print metrics.
"""
test_loss, test_accuracy = model.evaluate(X_test, y_test)
print(f"Test Loss: {test_loss}, Test Accuracy: {test_accuracy}")
y_pred = (model.predict(X_test) > 0.5).astype(int)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UndefinedMetricWarning)
print(classification_report(y_test, y_pred))
conf_matrix = confusion_matrix(y_test, y_pred)
print(conf_matrix)
def plot_metrics(history):
"""
Plot training and validation loss and accuracy.
:param history: Training history object from Keras model.
:return: None
"""
# Plot the training and validation loss
plt.figure(figsize=(10, 6))
plt.plot(history.history["loss"], label="Training Loss")
plt.plot(history.history["val_loss"], label="Validation Loss")
plt.title("Training and Validation Loss by Epoch", fontsize=16)
plt.xlabel("Epoch", fontsize=12)
plt.ylabel("Binary Crossentropy", fontsize=12)
plt.xticks(range(0, 20, 1), range(0, 20, 1))
plt.legend(fontsize=12)
# Plot the training and validation accuracy
plt.figure(figsize=(10, 6))
plt.plot(history.history["accuracy"], label="Training Accuracy")
plt.plot(history.history["val_accuracy"], label="Validation Accuracy")
plt.title("Training and Validation Accuracy by Epoch", fontsize=16)
plt.xlabel("Epoch", fontsize=12)
plt.ylabel("Accuracy", fontsize=12)
plt.xticks(range(0, 20, 1), range(0, 20, 1))
plt.legend(fontsize=12)
plt.show()
def train_evaluate_model(
X_train, y_train, X_val, y_val, X_test, y_test, epochs=20, patience=20
):
"""
Train and evaluate a convolutional neural network model.
"""
model = define_model()
model = compile_model(model)
history = train_model(model, X_train, y_train, X_val, y_val, epochs, patience)
model = tf.keras.models.load_model("best_model.h5")
evaluate_model(model, X_test, y_test)
plot_metrics(history)
def main():
parser = argparse.ArgumentParser(
description="Train a CNN model on spectrogram images."
)
parser.add_argument(
"directory_path",
type=str,
help="Path to the directory containing spectrogram images.",
)
args = parser.parse_args()
# Load and preprocess data
images = get_data(args.directory_path)
images = np.array(images)
images = images.reshape(images.shape[0], 128, 128, 1)
labels = np.zeros((images.shape[0],))
# Set the labels dynamically based on a percentage of the total images
percentage_for_label_1 = 0.25 # For example, 25%
num_labels_1 = int(len(images) * percentage_for_label_1)
labels[:num_labels_1] = 1
# Shuffle the data
images, labels = shuffle(images, labels, random_state=42)
# Split the data into training, validation, and test sets
X_train, X_temp, y_train, y_temp = train_test_split(
images, labels, test_size=0.2, random_state=42
)
X_val, X_test, y_val, y_test = train_test_split(
X_temp, y_temp, test_size=0.5, random_state=42
)
# Train and evaluate the model
train_evaluate_model(X_train, y_train, X_val, y_val, X_test, y_test)
# Save the model
model = tf.keras.models.load_model("best_model.h5")
model.save("model.h5")
if __name__ == "__main__":
main() |
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
NULLABLE = {'null': True, 'blank': True}
class UserRoles(models.TextChoices):
MEMBER = 'member', _('member')
MODERATOR = 'moderator', _('moderator')
class User(AbstractUser):
username = None
email = models.EmailField(max_length=100, verbose_name='ะฟะพััะฐ', unique=True)
phone = models.CharField(max_length=35, verbose_name='ะฝะพะผะตั ัะตะปะตัะพะฝะฐ', **NULLABLE)
avatar = models.ImageField(upload_to='users/', verbose_name='ะฐะฒะฐัะฐั', **NULLABLE)
country = models.CharField(max_length=35, verbose_name='ัััะฐะฝะฐ', **NULLABLE)
role = models.CharField(max_length=10, choices=UserRoles.choices, default=UserRoles.MEMBER, verbose_name='ัะพะปั')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
class Meta:
verbose_name = 'ะฟะพะปัะทะพะฒะฐัะตะปั'
verbose_name_plural = 'ะฟะพะปัะทะพะฒะฐัะตะปะธ' |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// ้ป่พ่ฟ็ฎ็ฌฆๆฏ็จๆฅ่ฟ่กๅธๅฐๅผ่ฟ็ฎ็่ฟ็ฎ็ฌฆ๏ผ่ฟๅๅผไนๆฏๅธๅฐๅผ
// && || ๏ผ
console.log(3 < 5 && 3 > 2);
console.log(3 > 5 || 3 > 2);
console.log(!(3 > 5 || 3 > 2));
// (็ญ่ทฏ่ฟ็ฎ)้ป่พไธญๆญ:ๅฝๆๅคไธช่กจ่พพๅผ(ๅผ)ๆถ๏ผๅทฆ่พน็่กจ่พพๅผๅผๅฏไปฅ็กฎๅฎ็ปๆๆถ๏ผๅฐฑไธๅ็ปง็ปญ่ฟ็ฎๅณ่พน็่กจ่พพๅผ็ๅผ
// ้ป่พไธ็ญ่ทฏ่ฟ็ฎ: ่กจ่พพๅผ1 && ่กจ่พพๅผ2 ๅฆๆ่กจ่พพๅผ1็ปๆไธบ็๏ผ่ฟๅ่กจ่พพๅผ1๏ผๅฆๆ่กจ่พพๅผ1ไธบๅ๏ผ่ฟๅ่กจ่พพๅผ1
console.log(132 && 456); // 456
console.log(0 && 456); // 0
console.log(0 && 456 && 1 + 2 ); // 0
console.log(100 && 456 && 1 + 2); // 3
// ้ป่พๆ็ญ่ทฏ่ฟ็ฎ: ่กจ่พพๅผ1 || ่กจ่พพๅผ2 ๅฆๆ่กจ่พพๅผ1็ปๆไธบ็๏ผ่ฟๅ่กจ่พพๅผ1๏ผๅฆๆ่กจ่พพๅผ1ไธบๅ๏ผ่ฟๅ่กจ่พพๅผ2
console.log(132 || 456); // 132
console.log(132 || 456 || 423); // 132
console.log(0 || 456 || 312); // 456
// ่ฟ็ฎ็ฌฆไผๅ
็บง
// ๅฐๆฌๅท > ไธๅ
่ฟ็ฎ็ฌฆ > ็ฎๆฐ่ฟ็ฎ็ฌฆ(ๅ
*ๅ/) > ๅ
ณ็ณป่ฟ็ฎ็ฌฆ > ็ธ็ญ่ฟ็ฎ็ฌฆ > ้ป่พ่ฟ็ฎ็ฌฆ(ๅ
&&ๅ|| ) > ่ตๅผ่ฟ็ฎ็ฌฆ > ้ๅท่ฟ็ฎ็ฌฆ
</script>
</head>
<body>
</body>
</html> |
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import { UserContext } from "../contexts/user";
import { PopupContext } from "../contexts/popup";
import { useContext } from "react";
import { IsLoadingContext } from "../contexts/isLoading";
export default function Navbar() {
const userContext = useContext(UserContext);
const user = userContext.user;
const popupContext = useContext(PopupContext);
const setPopup = popupContext.setPopup;
const isLoadingContext = useContext(IsLoadingContext);
const setIsLoading = isLoadingContext.setIsLoading;
const router = useRouter();
const [openMenu, setOpenMenu] = React.useState(false);
const isDashboard = router.pathname === ("/dashboard" || "/admin");
async function logout() {
setOpenMenu(false);
setIsLoading(true);
const response = await fetch("/api/logout", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
if (data.type === "SUCCESS") {
userContext.setUser(null);
setIsLoading(false);
}
}
return (
<nav>
<div className="logo">
<h1>Url Shortener</h1>
</div>
<div className="links">
{user ? (
<>
<>
<Link href="/">
<a className="link">Home</a>
</Link>
</>
{user.role === "admin" && (
<Link href="/dashboard">
<a className="link">Dashboard</a>
</Link>
)}
{isDashboard && (
<>
<div className="menu">
<button
className="menu-button link"
onClick={() => setOpenMenu(!openMenu)}
>
Menu <p className="down-arrow">^</p>
</button>
<div
className="menu-div"
style={{
transform: `scaleY(${openMenu ? 1 : 0})`,
}}
>
<button
className="option"
onClick={() => {
setPopup("CreateDomain");
setOpenMenu(false);
}}
>
Add Custom Domain
</button>
<button
className="option"
onClick={() => {
setPopup("ChangeYoutubeToken");
setOpenMenu(false);
}}
>
Change Youtube Token
</button>
{/* <button
className="option"
onClick={() => {
setPopup("ChangeFirstToken");
setOpenMenu(false);
}}
>
Change First Token
</button> */}
{/* <button
className="option"
onClick={() => {
setPopup("ChangeGoogleToken");
setOpenMenu(false);
}}
>
Change Google Token
</button> */}
<button
className="option"
onClick={() => {
setPopup("CreateUser");
setOpenMenu(false);
}}
>
Create User
</button>
<button
className="option"
onClick={() => {
setPopup("ChangePassword");
setOpenMenu(false);
}}
>
Change Password
</button>
{/*
<button
className="option"
onClick={() => {
setPopup("RedirectConfig");
setOpenMenu(false);
}}
>
Redirect Config
</button> */}
<button
className="option red"
onClick={() => {
setOpenMenu(false);
}}
>
^
</button>
</div>
</div>
</>
)}
<>
<button className="link red" onClick={logout}>
Logout
</button>
</>
</>
) : (
<p className="msg">You need to login first</p>
)}
</div>
</nav>
);
} |
---
title: Bootcamp โ ่ฎฟ้ฎ็ฝ็ซๅนถๅๅปบๅธๆท
description: Bootcamp โ ่ฎฟ้ฎ็ฝ็ซๅนถๅๅปบๅธๆท
jira: KT-5342
audience: Data Engineer, Data Architect, Marketer
doc-type: tutorial
activity: develop
solution: Journey Optimizer, Experience Platform
feature-set: Journey Optimizer, Experience Platform
feature: Events, Journeys, Profiles, Identities
exl-id: a56cedba-3ac4-4a9b-aeb8-8036c527a878
source-git-commit: 3c86f9b19cecf92c9a324fb6fcfcefaebf82177f
workflow-type: tm+mt
source-wordcount: '347'
ht-degree: 2%
---
# 2.1่ฎฟ้ฎ็ฝ็ซๅนถๅๅปบๅธๆท
## ไธไธๆ
ไปๆช็ฅๅฐๅทฒ็ฅ็่ฟ็จ๏ผไปฅๅๅฎขๆทไปๆถ่ดญๅฐ็ปด็ณป็่ฟ็จ๏ผๆฏ่ฟไบๆฅๅญๅ็ๆ้่ฆ็่ฏ้ขไนไธใ
Adobe Experience Platformๅจๆญคๅ็จไธญๅๆฅ็ๅทจๅคงไฝ็จใ ๅนณๅฐๆฏๆฒ้็ๅคง่ **ไฝ้ช่ฎฐๅฝ็ณป็ป**.
Platformๆฏไธ็ง็ฏๅข๏ผๅ
ถไธญๅฎขๆทไธ่ฏ็ๅซไนๆฏๅทฒ็ฅๅฎขๆทๆดไธบๅนฟๆณใ ไปPlatform็่งๅบฆๆฅ็๏ผ็ฝ็ซไธ็ๆช็ฅ่ฎฟๅฎขไนๆฏๅฎขๆท๏ผๅ ๆญค๏ผไฝไธบๆช็ฅ่ฎฟๅฎข็ๆๆ่กไธบไนไผๅ้ๅฐPlatformใ ็ฑไบ่ฟ็งๆนๆณ๏ผๅฝ่ฏฅ่ฎฟๅฎขๆ็ปๆไธบๅทฒ็ฅๅฎขๆทๆถ๏ผๅ็ไนๅฏไปฅๅฏ่งๅๆญคๆถไนๅๅ็็ไบๆ
ใ ไปๅฝๅ ๅไฝ้ชไผๅ็่งๅบฆๆฅ็๏ผ่ฟๅพๆๅธฎๅฉใ
## ๅฎขๆทๅ็จๆต็จ
่ฝฌๅฐ [https://bootcamp.aepdemo.net](https://bootcamp.aepdemo.net). ๅๅป **ๅ
จ้จๅ
่ฎธ**. ๆ นๆฎๆจๅจไธไธไธช็จๆทๆตไธญ็ๆต่ง่กไธบ๏ผๆจๅฐๅจ็ฝ็ซ็ไธป้กตไธ็ๅฐไธชๆงๅใ

ๅๅปๅฑๅนๅทฆไธ่ง็Adobeๅพฝๆ ๅพๆ ไปฅๆๅผ้
็ฝฎๆไปถๆฅ็ๅจใ ่ฏทๆฅ็้
็ฝฎๆไปถๆฅ็ๅจ้ขๆฟๅๅฎๆถๅฎขๆท้
็ฝฎๆไปถ๏ผๅ
ถไธญๅ
ๅซ **EXPERIENCE CLOUDID** ไฝไธบ่ฏฅๅฝๅๆช็ฅๅฎขๆท็ไธป่ฆๆ ่ฏ็ฌฆใ

ๆจ่ฟๅฏไปฅๆฅ็ๆ นๆฎๅฎขๆท่กไธบๆถ้็ๆๆไฝ้ชไบไปถใ

ๅๅป **ไธชไบบ่ตๆ** ๅพๆ ใ

ๅๅป **ๅๅปบๅธๆท**.

ๅกซๅ่กจๅ็ๆๆๅญๆฎตใ ไธบ็ตๅญ้ฎไปถๅฐๅๅ็ต่ฏๅท็ ไฝฟ็จๅฎ้
ๅผ๏ผๅ ไธบๅฎๅฐๅจไปฅๅ็็ปไน ไธญ็จไบๆๆพ็ตๅญ้ฎไปถๅ็ญไฟกใ

ๅไธๆปๅจๅนถๅๅป **ๆณจๅ**.

ไฝ ๅฐฑ่ฝ็ๅฐ่ฟไธชไบใ

ๆจ่ฟๅฐๆถๅฐไปฅไธ็ตๅญ้ฎไปถ๏ผ

ๅ ๅ้ๅ๏ผๆจ่ฟๅฐๆถๅฐไปฅไธ็ตๅญ้ฎไปถ๏ผ

่ฎฉๆไปฌ็็ไธไธๆญฅๅฆไฝ้
็ฝฎๆญคๅ
ฅ้จๅน่ฎญๅ็จใ
ไธไธๆญฅ๏ผ [2.2ๅๅปบไบไปถ](./ex2.md)
[่ฟๅ็จๆทๆต็จ2](./uc2.md)
[่ฟๅๆๆๆจกๅ](../../overview.md) |
# ะั ะฒัั ัะฐะบ ะถะต ัะฐะฑะพัะฐะตัะต ะฒ ะบะพะฝัะพัะต ะฟะพ ัะฐะทัะฐะฑะพัะบะต ะธะณั
# ะธ ัะผะพััะธัะต ัะฐะทะปะธัะฝัะต ะฟัะพะณัะฐะผะผั ะฟัะพัะปะพะณะพ ะณะพัะต-ะฟัะพะณัะฐะผะผะธััะฐ.
# ะ ะพะดะฝะพะน ะธะท ะธะณั ะดะปั ะดะตัะตะน, ัะฒัะทะฐะฝะฝะพะน ั ะผัะปััััะฝะพะน ัะฐะฑะพัะพะน ั ัะธัะปะฐะผะธ,
# ะฒะฐะผ ะฝัะถะฝะพ ะฑัะปะพ ะฝะฐะฟะธัะฐัั ะบะพะด ัะพะณะปะฐัะฝะพ ัะปะตะดัััะธะผ ััะปะพะฒะธัะผ:
# ะฟัะพะณัะฐะผะผะฐ ะฟะพะปััะฐะตั ะฝะฐ ะฒั
ะพะด ะดะฒะฐ ัะธัะปะฐ;
# ะฒ ะฟะตัะฒะพะผ ัะธัะปะต ะดะพะปะถะฝะพ ะฑััั ะฝะต ะผะตะฝะตะต ัััั
ัะธัั,
# ะฒะพ ะฒัะพัะพะผ โ ะฝะต ะผะตะฝะตะต ัะตััััั
, ะธะฝะฐัะต ะฟัะพะณัะฐะผะผะฐ ะฒัะดะฐัั ะพัะธะฑะบั.
# ะัะปะธ ะฒัั ะฝะพัะผะฐะปัะฝะพ, ัะพ ะฒ ะบะฐะถะดะพะผ ัะธัะปะต ะฟะตัะฒะฐั ะธ ะฟะพัะปะตะดะฝัั ัะธััั ะผะตะฝััััั ะผะตััะฐะผะธ,
# ะฐ ะทะฐัะตะผ ะฒัะฒะพะดะธััั ะธั
ััะผะผะฐ.
# ะ ััั ะฒั ะฝะฐััะบะฐะตัะตัั ะฝะฐ ะฟัะพะณัะฐะผะผั,
# ะบะพัะพัะฐั ะฑัะปะฐ ะฝะฐะฟะธัะฐะฝะฐ ะฟัะตะดัะดััะธะผ ะฟัะพะณัะฐะผะผะธััะพะผ
# ะธ ะบะพัะพัะฐั ะบะฐะบ ัะฐะท ัะตัะฐะตั ัะฐะบัั ะทะฐะดะฐัั.
# ะะดะฝะฐะบะพ ััะฐััะธะน ะฟัะพะณัะฐะผะผะธัั ะฟะพะฟัะพัะธะป ะฒะฐั ะฝะตะผะฝะพะณะพ ะฟะตัะตะฟะธัะฐัั ััะพั ะบะพะด,
# ััะพะฑั ะพะฝ ะฝะต ะฒัะณะปัะดะตะป ัะฐะบ ัะถะฐัะฝะพ.
# ะะฐ ะธ ะฒะฐะผ ัะฐะผะธะผ ััะฐะฝะพะฒะธััั, ะผัะณะบะพ ะณะพะฒะพัั, ะฝะต ะฟะพ ัะตะฑะต ะพั ะฝะตะณะพ.
# ะะพััะฐัะฐะนัะตัั ัะฐะทะดะตะปะธัั ะปะพะณะธะบั ะบะพะดะฐ ะฝะฐ ััะธ ะพัะดะตะปัะฝัะต ะปะพะณะธัะตัะบะธะต ัะฐััะธ (ััะฝะบัะธะธ):
# count_numbers โ ะฟะพะปััะฐะตั ัะธัะปะพ ะธ ะฒะพะทะฒัะฐัะฐะตั ะบะพะปะธัะตััะฒะพ ัะธัั ะฒ ัะธัะปะต;
# change_number โ ะฟะพะปััะฐะตั ัะธัะปะพ,
# ะผะตะฝัะตั ะฒ ะฝัะผ ะผะตััะฐะผะธ ะฟะตัะฒัั ะธ ะฟะพัะปะตะดะฝัั ัะธััั ะธ ะฒะพะทะฒัะฐัะฐะตั ะธะทะผะตะฝัะฝะฝะพะต ัะธัะปะพ;
# main โ ััะฝะบัะธั ะฝะธัะตะณะพ ะฝะต ะฟะพะปััะฐะตั ะฝะฐ ะฒั
ะพะด,
# ะฒะฝัััะธ ะพะฝะฐ ะทะฐะฟัะฐัะธะฒะฐะตั ะฝัะถะฝัะต ะดะฐะฝะฝัะต ะพั ะฟะพะปัะทะพะฒะฐัะตะปั,
# ะฒัะฟะพะปะฝัะตั ะดะพะฟะพะปะฝะธัะตะปัะฝัะต ะฟัะพะฒะตัะบะธ ะธ ะฒัะทัะฒะฐะตั ััะฝะบัะธะธ 1 ะธ 2
# ะดะปั ะฒัะฟะพะปะฝะตะฝะธั ะทะฐะดะฐัะธ (ะฟัะพะฒะตัะบะธ ะธ ะธะทะผะตะฝะตะฝะธั ะดะฒัั
ัะธัะตะป).
# ะ ะฐะทะฑะตะนัะต ะฟัะธะฒะตะดัะฝะฝัั ะฝะธะถะต ะฟัะพะณัะฐะผะผั ะฝะฐ ััะฝะบัะธะธ.
# ะะพะฒัะพัะตะฝะธะน ะบะพะดะฐ ะดะพะปะถะฝะพ ะฑััั ะบะฐะบ ะผะพะถะฝะพ ะผะตะฝััะต.
# ะขะฐะบะถะต ัะดะตะปะฐะนัะต, ััะพะฑั ะฒ ะพัะฝะพะฒะฝะพะน ัะฐััะธ ะฟัะพะณัะฐะผะผั ะฑัะป ัะพะปัะบะพ ะฒะฒะพะด ัะธัะตะป,
# ะทะฐัะตะผ ะธะทะผะตะฝัะฝะฝัะต ัะธัะปะฐ ะธ ะฒัะฒะพะด ะธั
ััะผะผั.
def count_numbers(num):
count = 0
temp = num
while temp > 0:
count += 1
temp //= 10
return count
def change_number(num):
last_digit = num % 10
first_digit = num // 10 ** (count_numbers(num) - 1)
between_digits = num % 10 ** (count_numbers(num) - 1) // 10
return last_digit * 10 ** (count_numbers(num) - 1) + between_digits * 10 + first_digit
def main():
first_n = int(input("ะะฒะตะดะธัะต ะฟะตัะฒะพะต ัะธัะปะพ: "))
second_n = int(input("ะะฒะตะดะธัะต ะฒัะพัะพะต ัะธัะปะพ: "))
if count_numbers(first_n) < 3:
print("ะ ะฟะตัะฒะพะผ ัะธัะปะต ะผะตะฝััะต ัััั
ัะธัั.")
elif count_numbers(second_n) < 4:
print("ะะพ ะฒัะพัะพะผ ัะธัะปะต ะผะตะฝััะต ัะตััััั
ัะธัั.")
else:
first_n_changed = change_number(first_n)
second_n_changed = change_number(second_n)
print('ะะทะผะตะฝัะฝะฝะพะต ะฟะตัะฒะพะต ัะธัะปะพ:', first_n_changed)
print('ะะทะผะตะฝัะฝะฝะพะต ะฒัะพัะพะต ัะธัะปะพ:', second_n_changed)
main() |
import React, { Fragment } from "react";
import statsStyles from "../../scss/Section/SectionLayout.module.scss";
import Card from "../../components/util/Card/Card";
import {
LanguageStats,
ProblemSolved,
TopicStats,
} from "../../Controller/queries/statistics/Statistics";
import { SiJavascript } from "react-icons/si";
import { FaPython } from "react-icons/fa";
export const AllProblemsSolved = () => {
const { allQsCount, usersSolved } = ProblemSolved();
return (
<Card styling={statsStyles.allProblemsContainer}>
<div className={statsStyles.problemsTitle}>
<h2>Difficulty</h2>
<h2>Solved</h2>
<h2>Total</h2>
</div>
<div className={statsStyles.problemsHeader}>
<div className={statsStyles.problemsHeading}>
{allQsCount &&
allQsCount.map((items) => {
return (
<div key={items.difficulty}>
<h4 className={statsStyles.difficultyHeaderFour}>
{items.difficulty}
</h4>
<div className={statsStyles.totalContainer}>
<h4 className={statsStyles.totalHeaderFour}>
{items.count}
</h4>
</div>
</div>
);
})}
</div>
</div>
<div className={statsStyles.countHeader}>
<div className={statsStyles.countHeading}>
{usersSolved &&
usersSolved.map((items) => {
return (
<div key={items.count}>
<h4 className={statsStyles.countHeaderFour}>{items.count}</h4>
</div>
);
})}
</div>
</div>
</Card>
);
};
export const languageStats = () => {
const { languageData } = LanguageStats();
return (
<Card styling={statsStyles.langCardContainer}>
<div className={statsStyles.langInnerContainer}>
<div className={statsStyles.langTitle}>
<h2>Languages</h2>
<h2>Solved</h2>
</div>
<div className={statsStyles.langHeader}>
<div className={statsStyles.langHeading}>
{languageData &&
languageData.map((items) => {
return (
<div key={items.languageName}>
{items.languageName === "JavaScript" ? (
<Fragment>
<h4 className={statsStyles.langHeaderFour}>
<span className={statsStyles.langJS}>
<SiJavascript />
</span>
{items.languageName}
</h4>
<div className={statsStyles.solvedJSContainer}>
<p className={statsStyles.solvedJS}>
{items.problemsSolved}
</p>
</div>
</Fragment>
) : (
<Fragment>
<h4 className={statsStyles.langHeaderFour}>
<span className={statsStyles.langPY}>
<FaPython />
</span>
{items.languageName}
</h4>
<div className={statsStyles.solvedPYContainer}>
<p className={statsStyles.solvedPY}>
{items.problemsSolved}
</p>
</div>
</Fragment>
)}
</div>
);
})}
</div>
</div>
</div>
</Card>
);
};
export const topicStats = () => {
const { advanceTopic, intermediateTopic, fundamentalTopic } = TopicStats();
return (
<Fragment>
<Card styling={statsStyles.advancedTopicContainer}>
<div className={statsStyles.topicTitle}>
<h2>Advanced Topic</h2>
<h2>Solved</h2>
</div>
<div className={statsStyles.advancedHeaders}>
{advanceTopic &&
advanceTopic
.map((items) => {
return (
<div key={items.tagSlug}>
<Fragment>
<h4 className={statsStyles.advancedHeaderFour}>
{items.tagName}
</h4>
<div className={statsStyles.advancedSolved}>
<p>{items.problemsSolved}</p>
</div>
</Fragment>
</div>
);
})
.slice(0, 6)}
</div>
</Card>
<Card styling={statsStyles.intermediateTopicContainer}>
<div className={statsStyles.topicTitle}>
<h2>Intermediate Topic</h2>
<h2>Solved</h2>
</div>
<div className={statsStyles.intermediateHeaders}>
{intermediateTopic &&
intermediateTopic
.map((items) => {
return (
<div key={items.tagSlug}>
<Fragment>
<h4 className={statsStyles.intermediateHeaderFour}>
{items.tagName}
</h4>
<div className={statsStyles.intermediateSolved}>
<p>{items.problemsSolved}</p>
</div>
</Fragment>
</div>
);
})
.slice(0, 6)}
</div>
</Card>
<Card styling={statsStyles.fundamentalTopicContainer}>
<div className={statsStyles.topicTitle}>
<h2>Fundamental Topic</h2>
<h2>Solved</h2>
</div>
<div className={statsStyles.fundamentalHeaders}>
{fundamentalTopic &&
fundamentalTopic
.map((items) => {
return (
<div key={items.tagSlug}>
<Fragment>
<h4 className={statsStyles.fundamentalHeaderFour}>
{items.tagName}
</h4>
<div className={statsStyles.fundamentalSolved}>
<p>{items.problemsSolved}</p>
</div>
</Fragment>
</div>
);
})
.slice(0, 6)}
</div>
</Card>
</Fragment>
);
}; |
/*
Programmer: Diego Vela
Date: March 18, 2023
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#define SIZE ( sizeof(list)/sizeof(*list) )
//Global array
int list[] = {7, 12, 19, 3, 18, 4, 2, -5, 6, 15 , 8} ; // array initially filled with unsorted numbers
int result[SIZE] = {0}; // same contents as unsorted array, but sorted
//Structures for passing data to worker threads
typedef struct
{
int* subArray;
unsigned int size;
} SortingThreadParameters;
typedef struct
{
SortingThreadParameters left;
SortingThreadParameters right;
} MergingThreadParameters;
//Functions for main process to thread
void *sortArr(void *thread_args);
void *mergeArr(void *thread_args);
//Sorting.c Sorts global array using pthread_create()
int main(int argc, char *argv[]) {
//Declarations
pthread_t leftID, rightID, mergeID;
//Thread 1
SortingThreadParameters *paramsLeft = malloc( sizeof( SortingThreadParameters ) );
paramsLeft->subArray = list;
paramsLeft->size = SIZE/2;
if ((pthread_create(&leftID, NULL, sortArr, (void*)paramsLeft)) != 0 ) {
return 1;
}
//Thread 2
SortingThreadParameters *paramsRight = malloc( sizeof( SortingThreadParameters ) );
paramsRight->subArray = list + paramsLeft->size;
paramsRight->size = SIZE - paramsLeft->size;
if ((pthread_create(&rightID, NULL, sortArr, (void*)paramsRight)) != 0 ) {
return 1;
}
//wait for the sorting threads to complete
pthread_join(leftID, NULL);
pthread_join(rightID, NULL);
//Merge
MergingThreadParameters * paramsMerge = malloc( sizeof( MergingThreadParameters ) );
paramsMerge->left = *paramsLeft;
paramsMerge->right = *paramsRight;
if ((pthread_create(&mergeID, NULL, mergeArr, (void*)paramsMerge)) != 0 ) {
return 1;
}
pthread_join(mergeID, NULL);
//Print sorted threads Array
printf("Unsorted Array after sorting threads perform an in-place sort\n");
for (int i = 0; i < SIZE; i++) {
printf("%d ", list[i]);
}
printf("\n");
//Print Final Array
printf("\nSorted Array\n");
for (int i = 0; i < SIZE; i++) {
printf("%d ", result[i]);
}
printf("\n");
return EXIT_SUCCESS;
}
void *sortArr(void *thread_args){
//Declare
SortingThreadParameters *sortMe = (SortingThreadParameters*) thread_args;
int temp;
//Selection Sort
for (int i = 0; i < sortMe->size; i++) {
for (int j = i+1; j < sortMe->size; j++) {
if (*(sortMe->subArray + i) > *(sortMe->subArray + j)) {
temp = *(sortMe->subArray+i);
*(sortMe->subArray + i) = *(sortMe->subArray + j);
*(sortMe->subArray + j) = temp;
}
}
}
pthread_exit(NULL);
}
void *mergeArr(void *thread_args) {
MergingThreadParameters *mergeMe = (MergingThreadParameters*) thread_args;
int i, j, r = 0;
while (i < mergeMe->left.size && j < mergeMe->right.size)
{
if (mergeMe->left.subArray[i] < mergeMe->right.subArray[j])
{
result[r] = mergeMe->left.subArray[i];
i++;
}
else
{
result[r] = mergeMe->right.subArray[j];
j++;
}
r++;
}
if (i < mergeMe->left.size)
{
while (i < mergeMe->left.size)
{
result[r] = mergeMe->left.subArray[i];
i++;
r++;
}
}
else
{
while (j < mergeMe->right.size)
{
result[r] = mergeMe->right.subArray[j];
j++;
r++;
}
}
pthread_exit(NULL);
}; |
import NextImage from "next/image";
import Link from "next/link";
import { getProductsByCategorySlug } from "@/api/products";
import { formatMoney } from "@/utils";
export const SuggestedProductsList = async ({ categorySlug }: { categorySlug: string }) => {
const products = await getProductsByCategorySlug(categorySlug);
if (!products) {
return null;
}
return (
<section
aria-labelledby="related-heading"
className="mt-16 sm:mt-24"
data-testid="related-products"
>
<h2 id="related-heading" className="text-lg font-medium text-gray-900">
Sugerowane produkty
</h2>
<ul className="mt-6 grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-4 xl:gap-x-8">
{products?.slice(0, 4).map((product) => (
<li key={product.id} className="group relative">
<div className="aspect-h-1 aspect-w-1 lg:aspect-none w-full overflow-hidden rounded-md group-hover:opacity-75 lg:h-80">
{product.images[0] && (
<NextImage
priority
width={600}
height={600}
src={product.images[0].url}
alt={product.name}
className="h-full w-full object-contain object-center transition-all duration-300 group-hover:scale-105 group-hover:opacity-75 lg:h-full lg:w-full"
/>
)}
</div>
<div className="mt-4 flex justify-between">
<div>
<h3 className="text-sm text-gray-700">
<Link href={`/product/${product.id}`}>
<span aria-hidden="true" className="absolute inset-0" />
{product.name}
</Link>
</h3>
<p className="mt-1 text-sm text-gray-500">{product.categories[0]?.name}</p>
</div>
<p className="text-sm font-medium text-gray-900">
{formatMoney(product.price / 100)}
</p>
</div>
</li>
))}
</ul>
</section>
);
}; |
REESCRIBIENDO HISTORIA
Un recurso importante pero peligroso de GIT es que podemos reescribir la historia, podemos borrar o modificar commits, combinar o dividros, etc.
Cuando es conveniente hacer esto ? Cuando la historia es mala, por ej:
- Mensajes de commits pobres
- Commits muy grandes con temas que no se relacionan entre si
- Commits muy pequeรฑos dispersos por todos lados
por alguno de estos motivos tal vez no podamos extraer informaciรณn importante del historial. Queremos un historial limpio, legible y facil de seguir, que explique la historia de nuestro proyecto, como evolucionรณ desde el dรญa 1. Para esto podemos:
- Reescribir los mensajes de commits para que tengan un significado y descripciรณn importante
- Dividir commits grandes en pequeรฑos que representen cadenas lรณgicas separadas
- Si tenemos muchos commits pequeรฑos podemos hacer un squash de un grupo de commits que estรฉn relacionados
- Podemos borrar commits enviados por accidente
- Modificar commits, por ej, nos olvidamos de agregar un archivo
Pero reescribir la historia es peligroso y hay que estar seguros.
REGLA DE ORO: -- "NO REESCRIBIR HISTORIA PรBLICA"
Esto quiere decir que si en algรบn momento hicimos pรบblica nuestra historia, nunca modificarlos. En realidad, los commits en el repo remoto son inmutables, no se pueden modificar, entonces cuando "modificamos" un commit, lo que realmente estamos haciendo es crear una copia EXACTA (*) y asignando a ese commit como el รบltimo, pero el commit original no se borra, siempre queda de backup. Para ver un flow, supongamos que nuestro repo local y remoto estรกn en el mismo estado:
Local: MASTER โ Remoto: MASTER
โผ โ โผ
โโโโโ โโโโโ โ โโโโโ โโโโโ
โ A โโโโโโค B โ โ โ A โโโโโโค B โ
โโโโโ โโโโโ โ โโโโโ โโโโโ
Ahora supogamos que modificamos el commit B en nuestro repo local, enrealidad lo que estamos haciendo es crear una copia exacta * y despuรฉs pushearla para designarla como master en nuestro repo local y remoto:
REPO LOCAL REPO REMOTO - OP 1 REPO REMOTO - OP 2
MASTER MASTER
โฒ Al intentar pushear git nos โฒ O la otra forma es MASTER
โโโโโ โโโโโ va a rechazar el push โโโโโ โโโโโ โโโโโ pushear es con un -f โฒ
โ A โโโโโโค B*โ porque tenemos una divergencia, โ A โโโโโโค B โโโโโโค M โ lo que harรญa lo siguiente โโโโโ โโโโโ
โโโโโ โโโโโ una nueva branch.Por lo que podemos โโโโโ โโโโโ โโโฌโโ en el repo remoto โ A โโโโโโค B*โ
โฒ hacer 2 cosas: โฒ โ >>>>>>>>>>>>>>> โโโโโ โโโโโ
โ โโโโโ o hacer un merge de la siguiente manera โ โโโโโ โ
โโโโโโโโค B โ >>>>>>>>>>>>>>>>>>>> โโโโโโโโค B*โโโโโโโโ Git sobreescribe B con B*
โโโโโ que nos dejarรก una historia sucia, โโโโโ
โผ compleja de leer
origin/MASTER
Esta opciรณn 2 parece muy sencilla y deja el remoto como queremos, pero sobreescribir estรก extremadamente mal porque como ya dijimos, en algรบn momento hicimos B pรบblico, por lo que si en algรบn momento otra persona hizo un pull antes de hacer la modificaciรณn, esa persona estรก trabajando con la versiรณn anterior de B, por lo que cuando haga un push de su nuevo commit "C" git va a rechazar el push ya que pertenece a otra branch.
Para solucionar esto, la otra persona tendrรก que hacer un pull para obtener B* y hacer un merge, dejando una historia sucia y compleja sin motivo.
REPO LOCAL DE TERCEROS REPO LOCAL & REMOTO DESPUES DEL PUSH
MASTER โ origin/MASTER & MASTER
โฒ โ โฒ
โโโโโ โโโโโ โโโโโ โโโโโ โ โโโโโ โโโโโ โโโโโ
โ A โโโโโโค B โโโโโค C โโโโโค M โ โ โ A โโโโโโค B*โโโโโโโโโโโโโค M โ
โโโโโ โโโโโ โโโโโ โโโฌโโ โ โโโโโ โโโโโ โโโฌโโ
โฒ โ โ โฒ โ
โ โโโโโ โ โ โ โโโโโ โโโโโ โ
โโโโโโโโค B*โโโโโโโโโโโโโโโ โ โโโโโโโโค B โโโโโค C โโโโโโโ
โโโโโ โ โโโโโ โโโโโ
โผ โ
origin/MASTER โ
Como vemos, el origin/MASTER va a estar en B*, pero esta persona tendrรก su master en el B que luego modificamos, por lo que su commit C estรก basado en B, y tendrรก que hacer un merge para combinar B* y C, y luego tambiรฉn contaminar el repo remoto una vez que pushee estos cambios, contaminando el remoto de una manera desprolija.
Por esto recordar, modificar la historia en nuestro repo privado y local antes de hacerlo pรบblico estรก perfecto, es hasta una buena prรกctica para pushear despuรฉs una historia limpia, pero una vez que pusheamos algo al repo remoto, nunca modificarlo !!! |
import { useEffect, useState } from "react";
import { Button, Form, Icon, Modal, ModalProps } from "semantic-ui-react";
import LoadingSpinner from "../../LoadingSpinner";
import useGlobalError from "../../error/ErrorHooks";
import {
CentralIdentityApp,
CentralIdentityOrg,
} from "../../../types/CentralIdentity";
import axios from "axios";
interface AddUserOrgModalProps extends ModalProps {
show: boolean;
userId: string;
currentOrgs: string[];
onClose: () => void;
}
const AddUserOrgModal: React.FC<AddUserOrgModalProps> = ({
show,
userId,
currentOrgs,
onClose,
...rest
}) => {
// Global state & hooks
const { handleGlobalError } = useGlobalError();
// Data & UI
const [loading, setLoading] = useState(false);
const [availableOrgs, setAvailableOrgs] = useState<CentralIdentityOrg[]>([]);
const [orgsToAdd, setOrgsToAdd] = useState<string[]>([]);
// Effects
useEffect(() => {
if (!show) return;
getAvailableOrgs();
}, [show, userId]);
// Methods
async function getAvailableOrgs() {
try {
setLoading(true);
const res = await axios.get(`/central-identity/orgs`);
if (
res.data.err ||
!res.data.orgs ||
!Array.isArray(res.data.orgs)
) {
handleGlobalError(res.data.err);
return;
}
const filtered = res.data.orgs.filter(
(org: CentralIdentityOrg) => !currentOrgs.includes(org.id.toString())
);
setAvailableOrgs(filtered);
} catch (err) {
handleGlobalError(err);
} finally {
setLoading(false);
}
}
async function submitAddUserOrg() {
try {
setLoading(true);
const res = await axios.post(
`/central-identity/users/${userId}/orgs`,
{
orgs: orgsToAdd,
}
);
if (res.data.err) {
handleGlobalError(res.data.err);
return;
}
onClose();
} catch (err) {
handleGlobalError(err);
} finally {
setLoading(false);
}
}
return (
<Modal open={show} onClose={onClose} {...rest} size="small">
<Modal.Header>Add User Organization(s)</Modal.Header>
<Modal.Content scrolling id="task-view-content">
{loading && (
<div className="my-4r">
<LoadingSpinner />
</div>
)}
{!loading && (
<div className="pa-2r mb-6r">
<Form noValidate>
<Form.Select
label="Add Organizations"
placeholder="Start typing to search by name..."
options={availableOrgs.map((org) => ({
key: org.id,
value: org.id,
text: org.name,
}))}
onChange={(_e, { value }) => {
if (!value) return;
setOrgsToAdd(value as string[]);
}}
fluid
multiple
search
selection
scrolling
loading={loading}
disabled={loading}
/>
</Form>
</div>
)}
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Cancel</Button>
{orgsToAdd.length > 0 && (
<Button color="green" onClick={submitAddUserOrg}>
<Icon name="save" /> Save
</Button>
)}
</Modal.Actions>
</Modal>
);
};
export default AddUserOrgModal; |
import React, { useState, useEffect } from "react";
const AddContact = ({ addContactHandler }) => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const updateName = (e) => {
setName(e.target.value);
};
const updateEmail = (e) => {
setEmail(e.target.value);
};
const add = (e) => {
e.preventDefault();
if (name === "" || email === "") {
alert("All fields are mandatory !!!");
return;
} else {
const contact = { name, email };
addContactHandler(contact);
setName("");
setEmail("");
}
};
return (
<div className="ui main">
<h2>ADD CONTACT</h2>
<form className="ui form" onSubmit={add}>
<div className="field">
<label>Name</label>
<input
type="text"
name="name"
placeholder="Name"
value={name}
onChange={updateName}
/>
</div>
<div className="field">
<label>Email</label>
<input
type="text"
name="email"
placeholder="Email"
value={email}
onChange={updateEmail}
/>
</div>
<button className="ui button blue" >
ADD
</button>
</form>
</div>
);
};
export default AddContact; |
#include <Python.h>
#include <stdio.h>
/**
* print_python_list - Prints basic info about Python lists.
* @p: PyObject list
*/
void print_python_list(PyObject *p)
{
int size, i;
PyObject *item;
printf("[*] Python list info\n");
if (!PyList_Check(p))
{
printf(" [ERROR] Invalid List Object\n");
return;
}
size = PyList_Size(p);
printf("[*] Size of the Python List = %d\n", size);
printf("[*] Allocated = %ld\n", ((PyListObject *)p)->allocated);
for (i = 0; i < size; i++)
{
item = PyList_GetItem(p, i);
printf("Element %d: %s\n", i, Py_TYPE(item)->tp_name);
}
}
/**
* print_python_bytes - Prints basic info about Python bytes objects.
* @p: PyObject bytes
*/
void print_python_bytes(PyObject *p)
{
long size, i;
char *string;
printf("[*] Python bytes\n");
if (!PyBytes_Check(p))
{
printf(" [ERROR] Invalid Bytes Object\n");
return;
}
size = PyBytes_Size(p);
string = PyBytes_AsString(p);
printf(" size: %ld\n", size);
printf(" trying string: %s\n", string);
size = size < 10 ? size + 1 : 10;
printf(" first %ld bytes:", size);
for (i = 0; i < size; i++)
{
printf(" %02hhx", string[i]);
}
printf("\n");
} |
import { APIActionRowComponent, APIButtonComponentWithCustomId, ButtonInteraction, Client, APIEmbed, Message, MessageComponentInteraction, ModalMessageModalSubmitInteraction, Snowflake, TextBasedChannel, ComponentType, APIEmbedField, ButtonStyle, CommandInteraction, APIMessageActionRowComponent } from "discord.js"
import { Serializable } from "./saving";
export type MessageOptions = {
embeds?: APIEmbed[];
components?: APIActionRowComponent<APIMessageActionRowComponent>[];
}
export function createButtonGrid(length: number, generator: (i: number) => Omit<APIButtonComponentWithCustomId, 'type'>): APIActionRowComponent<APIMessageActionRowComponent>[] {
const rows: APIActionRowComponent<APIMessageActionRowComponent>[] = [];
let i = 0;
while (i < length) {
const row: APIMessageActionRowComponent[] = [];
for (let j = 0; j < 5; j++) {
row.push({
type: ComponentType.Button,
...generator(i),
});
i++;
if (i >= length) break;
}
rows.push({
type: ComponentType.ActionRow,
components: row,
});
}
return rows;
}
export function disableButtons(m: APIActionRowComponent<APIMessageActionRowComponent>[], exceptions?: string[]): APIActionRowComponent<APIMessageActionRowComponent>[] {
const newRows: APIActionRowComponent<APIMessageActionRowComponent>[] = [];
for (const row of m) {
const newRow: APIMessageActionRowComponent[] = [];
for (const c of row.components) {
if (!c.disabled && (!exceptions || ('custom_id' in c && !exceptions.includes(c.custom_id)))) {
// newRow.push({ ...c, disabled: true });
} else {
newRow.push(c);
}
}
if (newRow.length > 0) {
newRows.push({
type: ComponentType.ActionRow,
components: newRow,
});
}
}
return newRows;
}
// there are up to:
// - 6000 characters for all embeds
// - 25 fields per embed
// - 1024 characters per field
const fieldLimit = 1024;
const embedLimit = 2048; // lower threshold since 6000 characters are still too much
const embedFieldLimit = 25;
function prepareMessage(msg: MessageOptions): APIEmbed[] {
const embeds: APIEmbed[] = [];
if (msg.embeds) for (const embed of msg.embeds) {
if (!embed.fields) {
embeds.push(embed);
continue;
}
// split up large fields
const fields: APIEmbedField[] = [];
for (let field of embed.fields) {
while (field.value.length > fieldLimit) {
// Split field on newline
let split = field.value.lastIndexOf('\n', fieldLimit);
if (split === -1) {
split = field.value.lastIndexOf(' ', fieldLimit);
if (split === -1) {
split = fieldLimit;
}
}
const fst = field.value.substring(0, split);
const snd = field.value.substring(split).trimStart();
// Create intermediary field
field.value = fst;
fields.push(field);
// Continue
field = { name: ".", value: snd };
}
// Push last field
fields.push(field);
}
// put as many fields in the embed as possible
while (fields.length) {
const first: APIEmbedField[] = [];
let chars =
(embed.title?.length ?? 0) +
(embed.description?.length ?? 0) +
(embed.footer?.text?.length ?? 0) +
(embed.author?.name?.length ?? 0) +
('\nPage 99/99'.length);
while (
fields.length &&
first.length + 1 <= embedFieldLimit &&
chars + fields[0].name.length + fields[0].value.length <= embedLimit
) {
chars += fields[0].name.length + fields[0].value.length;
first.push(fields.shift()!);
}
embeds.push({
...embed,
fields: first,
});
}
}
// Add page count to footer
if (embeds.length > 1) {
for (let i = 0; i < embeds.length; i++) {
const embed = embeds[i];
embed.footer ??= { text: '' };
embed.footer.text += `\nPage ${i + 1}/${embeds.length}`;
}
}
return embeds;
}
function addPageButtons(components: APIActionRowComponent<APIMessageActionRowComponent>[], page: number, max: number): APIActionRowComponent<APIMessageActionRowComponent>[] {
components = components.length ? [ ...components ] : [{
type: ComponentType.ActionRow,
components: [],
}];
const row = { ...components[components.length - 1] };
components[components.length - 1] = row;
row.components.push({
type: ComponentType.Button,
style: ButtonStyle.Primary,
label: "โ",
custom_id: `_prevpage`,
disabled: page === 0,
}, {
type: ComponentType.Button,
style: ButtonStyle.Primary,
label: "โถ",
custom_id: `_nextpage`,
disabled: page + 1 >= max,
});
return components;
}
export type MessageSave = {[key: Snowflake]: {
msg: Snowflake,
cache?: APIEmbed[],
page?: number,
}};
export class MessageController implements Serializable<MessageSave> {
messages: {[key: Snowflake]: {
msg: Message,
cache?: APIEmbed[],
page?: number,
}} = {};
async send(channel: TextBasedChannel, options: MessageOptions, i?: CommandInteraction | MessageComponentInteraction | ModalMessageModalSubmitInteraction) {
const previous = this.messages[channel.id];
let page = previous?.page ?? 0;
const cache = prepareMessage(options);
if (page >= cache.length) page = cache.length - 1;
const prepared = {
embeds: [cache[page]],
components: options.components && cache.length > 1
? addPageButtons(options.components, page, cache.length)
: options.components,
};
let msg: Message;
if (i) {
if (i.isCommand()) {
msg = await i.reply({ ...prepared, fetchReply: true }) as Message;
} else {
msg = await (i as MessageComponentInteraction | ModalMessageModalSubmitInteraction).update({ ...prepared, fetchReply: true }) as Message;
}
} else {
if (previous) {
msg = await previous.msg.edit(prepared);
} else {
msg = await channel.send(prepared);
}
}
this.messages[channel.id] = {
msg,
cache: cache.length > 1 ? cache : undefined,
page: page > 0 ? page : undefined,
}
}
async flipPage(i: ButtonInteraction) {
const previous = this.messages[i.channel!.id];
let page = previous.page ?? 0;
let cache = previous.cache;
if (!cache) {
return;
}
switch (i.customId) {
case '_prevpage':
if (page > 0) page -= 1;
break;
case '_nextpage':
page += 1;
break;
}
if (page >= cache.length) page = cache.length - 1;
const prepared = {
embeds: [cache[page]],
components: addPageButtons(previous.msg.components.map(c => c.toJSON()), page, cache.length),
};
const msg = await i.update({ ...prepared, fetchReply: true }) as Message;
this.messages[msg.channel.id] = {
msg,
page,
cache,
}
}
save(): MessageSave {
return Object.fromEntries(
Object.entries(this.messages)
.map(([k, v]) => [k, { msg: v.msg.id, cache: v.cache, page: v.page }])
);
}
async load(client: Client, save: MessageSave) {
const promises: Promise<void>[] = [];
for (const [k, v] of Object.entries(save)) {
promises.push(client.channels.fetch(k).then(async c => {
if (!c?.isTextBased()) throw new Error();
await c.messages.fetch(v.msg).then((m: Message) => {
this.messages[k] = { msg: m, page: v.page, cache: v.cache };
});
}));
}
await Promise.all(promises);
}
isMyInteraction(i: MessageComponentInteraction | ModalMessageModalSubmitInteraction) {
return this.messages[i.channelId ?? ""]?.msg.id === i.message?.id;
}
} |
package com.source.framework.util;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.annotation.Resources;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioPlayer
{
// to store current position
Long currentFrame;
Clip clip;
// current status of clip
String status;
AudioInputStream audioInputStream;
String filePath;
boolean loop = false;
// constructor to initialize streams and clip
public AudioPlayer(String filePath, boolean loop) throws LineUnavailableException, UnsupportedAudioFileException, IOException
{
// create AudioInputStream object
URL fileURL = Resources.class.getResource("/resource/" + filePath); //get sound
audioInputStream = AudioSystem.getAudioInputStream(new File(fileURL.getPath()));
clip = AudioSystem.getClip(null);
this.filePath = filePath;
// open audioInputStream to the clip
clip.open(audioInputStream);
if(loop) {
clip.loop(clip.LOOP_CONTINUOUSLY);
}
this.loop = loop;
}
// Method to play the audio
public void play()
{
//start the clip
clip.start();
status = "play";
}
// Method to pause the audio
public void pause()
{
if (status.equals("paused"))
{
System.out.println("audio is already paused");
return;
}
this.currentFrame =
this.clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
// Method to resume the audio
public void resumeAudio() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
if (status.equals("play"))
{
System.out.println("Audio is already "+
"being played");
return;
}
clip.close();
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
this.play();
}
// Method to restart the audio
public void restart() throws IOException, LineUnavailableException,
UnsupportedAudioFileException
{
clip.stop();
clip.close();
resetAudioStream();
currentFrame = 0L;
clip.setMicrosecondPosition(0);
this.play();
}
// Method to stop the audio
public void stop() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
currentFrame = 0L;
clip.stop();
clip.close();
}
// Method to jump over a specific part
public void jump(long c) throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
if (c > 0 && c < clip.getMicrosecondLength())
{
clip.stop();
clip.close();
resetAudioStream();
currentFrame = c;
clip.setMicrosecondPosition(c);
this.play();
}
}
// Method to reset audio stream
public void resetAudioStream() throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
URL fileURL = getClass().getResource(filePath);
audioInputStream = AudioSystem.getAudioInputStream(new File(fileURL.getPath()));
clip.open(audioInputStream);
if(loop) {
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
}
} |
package common
import (
"context"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type LoggingServer struct {
Logger *logrus.Entry
}
func NewLoggingServer(serverName string) LoggingServer {
return LoggingServer{Logger: logrus.WithField("server", serverName)}
}
func (s *LoggingServer) WrapErrorf(ctx context.Context, code codes.Code, fmt string, values ...any) error {
err := status.Errorf(code, fmt, values...)
s.GetMethodLogger(ctx).Errorf("%v", err)
return err // nolint
}
func (s *LoggingServer) LogRequest(ctx context.Context, r any) {
s.GetMethodLogger(ctx).Infof("Request: %v", r)
}
func (s *LoggingServer) GetMethodLogger(ctx context.Context) *logrus.Entry {
if method, ok := grpc.Method(ctx); ok {
return s.Logger.WithField("method", method)
}
return s.Logger
} |
๏ปฟusing FakeItEasy;
using GetAMedic.Controllers;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace GetAMedicTests.Controllers
{
public class UserControllerTests
{
private readonly UserController _userController;
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public UserControllerTests()
{
_userManager = A.Fake<UserManager<IdentityUser>>();
_roleManager = A.Fake<RoleManager<IdentityRole>>();
_userController = new UserController(_userManager, _roleManager);
}
[Fact]
public async Task UserController_Register_ReturnsOk()
{
// Arrange
var user = new IdentityUser
{
UserName = "fakeusername",
Email = "[email protected]"
};
A.CallTo(() => _userManager.CreateAsync(A<IdentityUser>._, A<string>._)).Returns(IdentityResult.Success);
var result = await _userController.Register(user, "Patient");
// Act
Assert.NotNull(result);
Assert.Equal(200, ((OkObjectResult)result).StatusCode);
}
[Fact]
public async Task UserController_Register_ReturnsBadRequest()
{
var user = new IdentityUser
{
UserName = "fakeusername",
Email = ""
};
var failedIdentityResult = IdentityResult.Failed(new IdentityError
{
Code = "fakecode",
Description = "fakedescription"
});
A.CallTo(() => _userManager.CreateAsync(A<IdentityUser>._, A<string>._)).Returns(failedIdentityResult);
var result = await _userController.Register(user, "Patient");
Assert.NotNull(result);
Assert.Equal(400, ((BadRequestObjectResult)result).StatusCode);
}
}
} |
const hre = require("hardhat")
const { ethers } = require("hardhat")
import {
Contract,
Signer
} from "ethers";
const BLACKHOLE = "0x0000000000000000000000000000000000000000"
export async function setupMockVault(
contract_name: string, vault_addr: string, asset_addr: string,
Controller: Contract, timelockSigner: Signer,
governanceSigner: Signer) {
let vaultABI = (await ethers.getContractFactory(contract_name)).interface;
let Vault: Contract
if (vault_addr == "") {
let vault_function = await Controller.functions['vaults'] ? 'vaults' : 'globes';
vault_addr = await Controller.functions[vault_function](asset_addr);
console.log(`controller_addr: ${Controller.address}`);
console.log(`vault_addr: ${vault_addr}`);
if (vault_addr != BLACKHOLE) {
Vault = new ethers.Contract(vault_addr, vaultABI, governanceSigner);
console.log(`connected to vault at ${Vault.address}`);
} else {
const vaultFactory = await ethers.getContractFactory(contract_name);
const governance_addr = await governanceSigner.getAddress()
const controller_addr = Controller.address
const timelock_addr = await timelockSigner.getAddress()
Vault = await vaultFactory.deploy(
asset_addr,
governance_addr,
timelock_addr,
controller_addr
);
console.log(`deployed new vault at ${Vault.address}`);
const setVault = await Controller.setVault(asset_addr, Vault.address);
const tx_setVault = await setVault.wait(1);
if (!tx_setVault.status) {
console.error(`Error setting the vault for: ${contract_name}`);
return Vault;
}
console.log(`Set Vault in the Controller for: ${contract_name}`);
vault_addr = Vault.address;
}
} else {
Vault = new ethers.Contract(vault_addr, vaultABI, governanceSigner);
console.log(`Connected to vault at ${Vault.address}`);
}
return Vault;
} |
import { Injectable } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
@Injectable({
providedIn: 'root',
})
export class FormManagerService {
/**
* Gets specific form control error message
*
* @param form The targeted form (to get validator roles)
* @param formControlName The target to validate
* @param translationKey The field's title to be displayed
*/
public getErrorMessage(
form: any,
formControlName: string,
translationKey: string
) {
let error = '';
if (form.controls[formControlName].hasError('required')) {
error = 'This field is required';
}
if (form.controls[formControlName].hasError('minlength')) {
error =
'Min length is ' +
form.controls[formControlName].errors?.minlength.requiredLength;
}
if (form.controls[formControlName].hasError('maxlength')) {
error =
'Max length is ' +
form.controls[formControlName].errors?.maxlength.requiredLength;
}
if (
form.controls[formControlName].hasError('pattern') ||
form.controls[formControlName].hasError('invalidNationalId')
) {
error = 'Please enter a valid value';
}
if (form.controls[formControlName].hasError('invalidMatch')) {
error = 'Invalid Match';
}
if (form.controls[formControlName].hasError('email')) {
error = 'Invalid Email';
}
if (form.controls[formControlName].hasError('min')) {
error =
'Value must be more than ' + form.get(formControlName)?.errors?.min.min;
}
if (form.controls[formControlName].hasError('matDatepickerMin')) {
const date = new Date(
form.get(formControlName)?.errors?.matDatepickerMin.min
);
const minDate =
date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
error = 'Please select a date after ' + minDate;
}
if (form.controls[formControlName].hasError('max')) {
error =
'Value must be less than ' +
form.get(formControlName)?.errors?.max.max +
1;
}
return error.toLowerCase();
}
/**
* Marks all invalid form controls as touched in order to show validation errors
*
* @param formGroup The target to validate
*/
validateForm(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach((field) => {
const formField = formGroup.get(field);
if (formField instanceof FormArray) {
for (const formArrayControl of formField.controls) {
if (formArrayControl instanceof FormControl) {
formArrayControl.markAsTouched({
onlySelf: true,
});
}
if (formArrayControl instanceof FormGroup) {
this.validateForm(formArrayControl);
}
}
}
if (formField instanceof FormControl) {
formField.markAsTouched({
onlySelf: true,
});
} else if (formField instanceof FormGroup) {
this.validateForm(formField);
}
});
}
/**
* Removes all null value fields from object (Mainly used on form submit)
*
* @param obj The targeted object value
*/
removeEmptyProperties(obj: any) {
Object.keys(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === 'object') {
this.removeEmptyProperties(obj[key]);
} else if (obj[key] === null) {
delete obj[key];
}
});
return obj;
}
/**
* Transforms JSON values to FormData
*
* @param reqData The targeted request value
*/
getFormData(reqData: any) {
const requestFormData = new FormData();
Object.keys(reqData).forEach((key) => {
if (Array.isArray(reqData[key])) {
reqData[key].forEach((item: any, i: number) => {
if (Object.keys(item).length) {
Object.keys(item).forEach((itemKey) => {
requestFormData.append(
key + '[' + i + ']' + '[' + itemKey + ']',
item[itemKey]
);
});
} else {
requestFormData.append(key + '[' + i + ']', item);
}
});
} else {
requestFormData.append(key, reqData[key]);
}
});
return requestFormData;
}
} |
<template>
<el-form-item label="ๆๅฐ้ไธญ">
<el-input-number
v-model="config.options.min"
:min="0"
:max="config.options.options.length"
@change="setDefaultVal('')"
></el-input-number>
</el-form-item>
<el-form-item label="ๆๅค้ไธญ">
<el-input-number
v-model="config.options.max"
:min="1"
:max="config.options.options.length"
@change="setDefaultVal('')"
></el-input-number>
</el-form-item>
<el-form-item label="ๆฏๅฆๅธฆๆ่พนๆก">
<el-switch
v-model="config.options.border"
inline-prompt
active-text="ๆฏ"
inactive-text="ๅฆ"
></el-switch>
</el-form-item>
<el-form-item label="ๆฏๅฆๆพ็คบไธบๆ้ฎ">
<el-switch
v-model="config.options.button"
inline-prompt
active-text="ๆฏ"
inactive-text="ๅฆ"
></el-switch>
</el-form-item>
<template v-if="config.options.button">
<el-form-item label="ๆๆฌ่ฒ">
<el-color-picker v-model="config.options.textColor" />
</el-form-item>
<el-form-item label="ๅกซๅ
่ฒ">
<el-color-picker v-model="config.options.fill" />
</el-form-item>
</template>
<el-form-item label="้้กน่ฎพ็ฝฎ">
<div class="options">
<el-checkbox-group v-model="config.options.defaultValue">
<draggable
class="drag-options"
:list="config.options.options"
tag="div"
item-key="value"
handle=".sort.icon"
>
<template #item="{ element, index }">
<div class="option-item">
<div
class="checkbox"
:class="config.options.defaultValue.includes(element.value) ? 'active' : ''"
@click="setDefaultVal(element.value)"
>
<div class="box">
<check-small theme="outline" size="13" fill="#fff" :strokeWidth="5"/>
</div>
</div>
<el-input class="input" v-model="element.value"></el-input>
<el-input class="input" v-model="element.label"></el-input>
<sort-two class="icon sort" theme="outline" :strokeWidth="3"/>
<reduce-one class="icon remove" theme="outline" size="20" :strokeWidth="3" @click="removeOption(index)" />
</div>
</template>
</draggable>
</el-checkbox-group>
<div class="btn-line">
<el-button type="primary" link @click="addOption">ๆทปๅ ้้กน</el-button>
<el-button type="primary" link @click="setDefaultVal('')">้็ฝฎ้ป่ฎคๅผ</el-button>
</div>
</div>
</el-form-item>
</template>
<script lang="ts" name="el-checkbox-group-config" setup>
import { ref, inject } from 'vue'
import Draggable from "vuedraggable"
import { SortTwo, ReduceOne, CheckSmall } from '@icon-park/vue-next'
const props = defineProps<{
config: any
}>()
const formData = ref<any>(inject('formData'))
const setDefaultVal = (value: any) => {
if(value === '') {
props.config.options.defaultValue = []
formData.value[props.config.prop] = []
} else {
if(formData.value[props.config.prop].length < props.config.options.max || !props.config.options.max) {
if(formData.value[props.config.prop].includes(value)){
const index = formData.value[props.config.prop].findIndex((item: any) => item === value)
props.config.options.defaultValue.splice(index, 1)
formData.value[props.config.prop].splice(index, 1)
} else {
props.config.options.defaultValue.push(value)
formData.value[props.config.prop].push(value)
}
} else {
props.config.options.defaultValue.splice(0, 1)
formData.value[props.config.prop].splice(0, 1)
props.config.options.defaultValue.push(value)
formData.value[props.config.prop].push(value)
}
}
}
const addOption = () => {
const date = new Date();
props.config.options.options.push({
label: `้้กน${date.getTime()}`,
value: date.getTime()
})
}
const removeOption = (index: number) => {
props.config.options.options.splice(index, 1)
}
</script>
<style lang="scss" scoped>
@import "../options";
</style> |
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>tasks-manager</title>
<style>
form {
width: fit-content;
height: fit-content;
color: white;
font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
margin: auto;
}
table {
background-color: #a96ae4;
border: 1px solid #4a0864;
text-align: center;
margin: auto;
}
caption {
background: #4a0864;
box-shadow: 0 2px 4px 0 rgba(0,0,0,.3);
font-size: 30px;
padding: 10px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
text-align: center;
}
td {
padding: 10px;
font-size: 15px;
}
th {
border-bottom: 1px solid #4a0864;
font-size: 17px;
padding: 10px;
text-align: center;
}
.btn {
background-color: #762a94;
display: inline-block;
color: white;
padding: 5px 10px;
border: 1px solid #4a0864;
}
.btn:hover {
background-color: white;
color: #762a94;
}
#addBtn {
width: 100%;
height: 40px;
background-color: #a96ae4;
border: 1px solid #4a0864;
color: white;
font-size: 15px;
margin-top: 5px;
}
#addBtn:hover {
background-color: #762a94;
}
#date {
background-color: #a96ae4;
border: none;
color: white;
text-align: center;
}
</style>
</head>
<body>
<form>
<table>
<caption>MY TASKS</caption>
<tr>
<th>TITLE</th>
<th>DONE</th>
<th>DEAD LINE</th>
<th>OPTIONS</th>
</tr>
<c:forEach var="task" items="${tasks}">
<c:url var="btnDelete" value="/tasks/delete">
<c:param name="id" value="${task.id}"/>
</c:url>
<c:url var="btnView" value="/tasks/edit">
<c:param name="id" value="${task.id}"/>
</c:url>
<tr>
<td>
<label>${task.title}</label>
</td>
<td>
<label id="date">${task.deadLine}</label>
</td>
<td>
<input class="btn" type="button" value="View" onclick="window.location.href='${btnView}'"/>
<input class="btn" type="button" value="Delete" onclick="window.location.href='${btnDelete}'"/>
</td>
</tr>
</c:forEach>
</table>
<input id="addBtn" type="button" value="Add new task" onclick="window.location.href='new'"/>
</form>
</body>
</html> |
/***********************************************************************************************
* *
* THIS PROJECT IS MADE BY: Hazem Shaaban Bakry *
* As part of learn-in-depth: master embedded systems by: keroles shnouda *
* *
* project description: this project is a bare-metal software for a blinking led *
* using stm32f103c6, everything is made by hand including source code, startup *
* linker script, and makefile *
* *
* *
***********************************************************************************************/
#include <stdint.h>
// define linker symbols
extern unsigned int _STACK_TOP;
extern unsigned int _TEXT_END;
extern unsigned int _DATA_START;
extern unsigned int _DATA_END;
extern unsigned int _BSS_START;
extern unsigned int _BSS_END;
extern void main(void);
void RESET_HANDLER(void)
{
// copy data section to ram
//unsigned int SIZE = (unsigned char *) &_DATA_END - (unsigned char *) &_DATA_START; NO LONGER USED
unsigned char *SOURCE = (unsigned char *) &_TEXT_END;
unsigned char *DESTINATION = (unsigned char *) &_DATA_START;
while (DESTINATION < (unsigned char *) &_DATA_END)
{
*DESTINATION++ = *SOURCE++;
}
// initialize bss section in ram
//SIZE = (unsigned char *) &_BSS_END - (unsigned char *) &_BSS_START; NO LONGER USED
DESTINATION = (unsigned char *) &_BSS_START;
while (DESTINATION < (unsigned char *) &_BSS_END)
{
*DESTINATION++ = 0;
}
//call main function
main();
}
// default handler, any vector table handler will execute this vector handler unless it was defined by user
void VECTOR_HANDLER(void)
{
RESET_HANDLER();
}
void NMI_HANDLER(void)__attribute__((weak, alias("VECTOR_HANDLER")));;
void BUS_FAULT_HANDLER(void)__attribute__((weak, alias("VECTOR_HANDLER")));;
void H_FAULT_HANDLER(void)__attribute__((weak, alias("VECTOR_HANDLER")));;
//vector section
volatile uint32_t vectors[] __attribute__((section(".Vectors"))) = {
(uint32_t) &_STACK_TOP,
(uint32_t) &RESET_HANDLER,
(uint32_t) &NMI_HANDLER,
(uint32_t) &BUS_FAULT_HANDLER,
(uint32_t) &H_FAULT_HANDLER
}; |
/**
* Login Scenario for testing.
*/
var util = require('util');
describe('Login', function(){
//Creates an instance of the LoginPage object, which holds most of the specific low level details of the tests.
var loginPage = require('LoginPage.js');
//Variables that I will use through the tests.
var username = '[email protected]';
var password = 'testPassword';
var registerUsername = '[email protected]';
var registerPassword = 'testPassword2';
var registerFirst = 'rFirst';
var registerSecond = 'rSecond';
//Should do this before each and every test, that is the purpose of this function.
//For now set this to be the local host value.
beforeEach(function () {
browser.get('localhost:5000');
});
//Now each test has it's own little summary before the function saying the goal.
it('Should have correct input values', function() {
loginPage.checkLoginInputs(username, password);
expect(this.loginUserName.getText().toEqual(username));
expect(this.loginPassword.getText().toEqual(password));
});
it('Should be able to log in', function(){
loginPage.loginFunction(username, password);
expect(this.loginSuccessButton.getText().toEqual(testUserName));
});
it('Should be able to cancel logging in', function(){
loginPage.loginCancelFunction(username, password);
expect(this.loginMainButton.isDisplayed());
});
it('Should be able to navigate to the register page', function () {
loginPage.testRegisterNavigation();
expect(this.loginRegistrationEmail.isDisplayed());
});
it('Should be able to cancel registration', function(){
loginPage.testRegistrationCancel(registerUsername, registerPassword, registerFirst, registerSecond);
expect(this.loginMainButton.isDisplayed());
});
it('Should be able to register', function(){
loginPage.testRegistration(registerUsername, registerPassword, registerFirst, registerSecond);
expect(this.loginRegistrationConfirmToast.isDisplayed());
});
it('Should be able to log out', function(){
loginPage.testLogoutFunction(username, password);
expect(this.loginMainButton.isDisplayed());
});
}); |
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class MainService {
httpResponse: any;
constructor(private httpClient: HttpClient, private router: Router) {}
/*Backend Links */
//url = 'https://pfizer-pulse.rj.r.appspot.com';
url = 'https://export-comments-backend-nylbyrwc2q-uc.a.run.app';
//url = 'http://127.0.0.1:5000';
/*The variables 'exporting', 'downloading'and 'finishedOperation'
are used to show and hide the banner of informations in the
Download Page
The informations are:
- Gerando Links
- Dowloading
- Operaรงรฃo finalizada*/
/* Gerando Links Banner*/
private exporting = false;
public getExporting() {
return this.exporting;
}
public setExporting(flag: boolean) {
this.exporting = flag;
}
/* Downloading Banner*/
private downloading = false;
public getDownloading() {
return this.downloading;
}
public setDownloading(flag: boolean) {
this.downloading = flag;
}
/* Finished Operation Banner*/
private finishedOperation = false;
public getFinishedOperation() {
return this.finishedOperation;
}
public setFinishedOperation(flag: boolean) {
this.finishedOperation = flag;
}
/*List of URL in the xlsx file passed by user*/
private original_urls_list: string[] = [];
public addOriginal_urls_list(item: string) {
this.original_urls_list.push(item);
}
public getOriginal_urls_list() {
return this.original_urls_list;
}
public original_urls_listSlice() {
this.original_urls_list = this.original_urls_list.slice(1);
}
public original_url_listDeleteItems() {
this.original_urls_list = [];
}
//List of Endpoints returned by the API
private endpointsList: any[] = [];
public getEndpointList() {
return this.endpointsList;
}
public addEndpointsList(original_url: string, endpoint: string) {
this.endpointsList.push({ original_url: original_url, endpoint: endpoint });
}
//If the first item of list == '', remove it
public removeFirstItemFromList() {
this.endpointsList = this.endpointsList.slice(1);
}
/**List of endpoints returned by backend.
Status can be: 0: Downloading;
1: Download Success;
2: Download Error */
private endpointsListStatus = [
{ original_url: '', endpoint: '', status: '' },
];
public getEndpointsListStatus() {
return this.endpointsListStatus;
}
public addEndpointListStatus(
original_url: string,
endpoint: string,
status: string
) {
this.endpointsListStatus.push({
original_url: original_url,
endpoint: endpoint,
status: status,
});
}
public deleteEndPointsListStatus() {
this.endpointsListStatus = [];
}
public removeFirstItemFromListStatus() {
this.endpointsListStatus = this.endpointsListStatus.slice(1);
}
/* This function sends a list of links (original_urls_list) to the backend.
The backend will return a list of endpoints that will be used to make the
download of the .xlsx files */
public sendRequestUsingList(): void {
//show the 'Exporting...' in frontend
this.setExporting(true);
//flag used to determine whether the process has completed
this.setFinishedOperation(false);
//information logs
console.log(`********INรCIO: ${new Date().toString()}`);
//console.log('Gerando endpoints...');
//build the json data to send to backend
let json_data = { list_of_endpoints: this.original_urls_list };
//HTTP Post Method
try {
this.httpClient
.post<any>(this.url + '/api/generateEndpointsFromList', json_data)
.subscribe((response) => {
//get the list that was returned by the backend
this.endpointsList = response.download_url_list;
console.log(this.endpointsList);
//walks by the endpoint in the list to make the download
this.endpointsList.map((e) => {
//add the endpoints in the list with 'status' == 0 (downloading)
if (e.endpoint != '')
this.addEndpointListStatus(e.endpoint, e.full_download_url, '0');
});
console.log(this.getEndpointsListStatus());
//send the endpoints to start the download process
this.sendRequestToEndpoints();
//hide the 'Exporting...' in the download page
this.setExporting(false);
});
} catch (error) {
console.log(error);
}
}
/*Sends the endpoints to API to get the blob response to download the .xlsx file**/
public sendRequestToEndpoints() {
//Remove the first null item from the list
//this.removeFirstItemFromList();
this.removeFirstItemFromListStatus();
//For each item that is on the list
this.getEndpointsListStatus().forEach((ep, index) => {
//If the item URL is different from ''
if (ep.endpoint != '') {
//show the "Downloading" banner
this.setDownloading(true);
//build the json data to send to backend
let json_data = { endpoint: ep.endpoint };
try {
this.httpClient
.post(this.url + '/api/downloadfiles', json_data, {
responseType: 'blob' as 'json',
})
.subscribe({
//if the backend responds with 200 code
next: (response) => {
console.log('Download Realizado : ' + ep.endpoint);
//set the item with 'downloaded' flag
ep.status = '1';
//downloads the reponse as a .xlsx file
this.downloadExcelFile(response, 'response.xlsx');
console.log(`TIME: ${new Date().toString()}`);
//Count the items where the status is different from 0
let i = this.getEndpointsListStatus().filter(
(e) => e.status != '0'
).length;
if (i == this.getEndpointsListStatus().length) {
this.setDownloading(false);
this.setFinishedOperation(true);
}
},
error: (e) => {
ep.status = '2';
let i = this.getEndpointsListStatus().filter(
(e) => e.status != '0'
).length;
if (i == this.getEndpointsListStatus().length) {
this.setDownloading(false);
this.setFinishedOperation(true);
}
},
});
} catch (error) {
console.log(error);
}
}
});
}
/************************************************************************** */
// public sendRequestToEndpointsPromisseAll() {
// //Remove the first null item from the list
// this.removeFirstItemFromList();
// console.log('fazendo download da poha toda !');
// Promise.all(
// this.getEndpointList().map((ep) => {
// let json_data = { endpoint: ep };
// this.httpClient.post(this.url + '/api/downloadfiles', json_data, {
// responseType: 'blob' as 'json',
// });
// })
// ).then((response) => {
// response.map((r) => console.log(r));
// });
// }
/************************************************************************** */
private downloadExcelFile(data: any, filename: string) {
const blob = new Blob([data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
}
} |
import { InversifyExpressServer } from "inversify-express-utils";
import express, { Application, NextFunction, Request, Response } from "express";
import { config } from "./config";
import container from "./core/DIContainer";
import { DBService } from "./DBService";
import compression from "compression";
import morgan from "morgan";
import { DataSource } from "typeorm";
import { BadRequestException } from "./utils/exceptions/bad.request.exception";
import HttpStatus from "http-status";
import { Routes } from "./utils/constants.endpoints";
export default class App {
public setup(): void {
const dbService: DBService = container.get(DBService);
dbService.connect().then(async (dataSource: DataSource): Promise<void> => {
console.log("Database connection established");
await dataSource.runMigrations();
});
const NO_CUSTOM_ROUTER = null;
const server: InversifyExpressServer = new InversifyExpressServer(
container,
NO_CUSTOM_ROUTER,
{
rootPath: Routes.BASE_ROUTE_PATH,
}
);
server.setConfig((app: Application): void => {
app.use(express.json());
app.use(compression());
app.use(morgan("dev"));
});
server.setErrorConfig((app: Application) => {
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
if (err instanceof BadRequestException) {
res.status(err.statusCode).json({
status: err.statusCode,
message: err.message,
info: err.errors,
});
return;
}
console.log(err);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
status: HttpStatus.INTERNAL_SERVER_ERROR,
message: "Oops! an error occurred.",
});
});
});
const app: Application = server.build();
app.listen(config.PORT, (): void => {
console.log(`Server running on http://localhost:${config.PORT}`);
});
}
} |
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ๆ ๆ ้ขๆๆกฃ</title>
<link href="css/common.css" rel="stylesheet" type="text/css" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/WebCalendar.js">
</script>
</head>
<body>
<div class="wrap">
<!-- main begin-->
<div class="sale">
<h1 class="lf">ๅจ็บฟๆๅ็ณป็ป</h1>
<div class="logout right"><a href="#" onclick="zhuxiao()" title="ๆณจ้">ๆณจ้</a></div>
</div>
<div class="forms">
<form id="form_query" action="${pageContext.request.contextPath}/queryAuctions" method="post">
<input id="page" name="pageNum" type="hidden" value="1"/>
<label for="name">ๅ็งฐ</label>
<input name="auctionname" value="${condition.auctionname}" type="text" class="nwinput" id="name"/>
<label for="names">ๆ่ฟฐ</label>
<input name="auctiondesc" value="${condition.auctiondesc}" type="text" id="names" class="nwinput"/>
<label for="time">ๅผๅงๆถ้ด</label>
<input name="auctionstarttime"
value="<fmt:formatDate value="${condition.auctionstarttime}" pattern="yyyy-MM-dd"/>"
type="text" id="time" class="nwinput" readonly="readonly" onclick="selectDate(this,'yyyy-MM-dd')"/>
<label for="end-time">็ปๆๆถ้ด</label>
<input name="auctionendtime"
value="<fmt:formatDate value="${condition.auctionendtime}" pattern="yyyy-MM-dd"/>"
type="text" id="end-time" class="nwinput" readonly="readonly" onclick="selectDate(this,'yyyy-MM-dd')"/>
<label for="price">่ตทๆไปท</label>
<input name="auctionstartprice" value="${condition.auctionstartprice}" type="text" id="price" class="nwinput" />
<input type="submit" value="ๆฅ่ฏข" class="spbg buttombg f14 sale-buttom"/>
</form>
<c:if test="${sessionScope.user.userisadmin==1}">
<input type="button" value="ๅๅธ" onclick="location='${pageContext.request.contextPath}/addAuction.jsp'" class="spbg buttombg f14 sale-buttom buttomb"/>
</c:if>
<c:if test="${sessionScope.user.userisadmin==0}">
<input type="button" value="็ซๆ็ปๆ" onclick="location='${pageContext.request.contextPath}/toAuctionnResult'" class="spbg buttombg f14 sale-buttom buttomb"/>
</c:if>
</div>
<div class="items">
<ul class="rows even strong">
<li>ๅ็งฐ</li>
<li class="list-wd">ๆ่ฟฐ</li>
<li>ๅผๅงๆถ้ด</li>
<li>็ปๆๆถ้ด</li>
<li>่ตทๆไปท</li>
<li class="borderno">ๆไฝ</li>
</ul>
<c:forEach var="auction" items="${auctionList}" varStatus="state">
<ul
<c:if test="${state.index%2==0}"> class="rows"</c:if>
<c:if test="${state.index%2==1}"> class="rows even"</c:if>
>
<li>${auction.auctionname}</li>
<li class="list-wd">${auction.auctiondesc}</li>
<li>
<fmt:formatDate value="${auction.auctionstarttime}" pattern="yyyy-MM-dd"/>
</li>
<li>
<fmt:formatDate value="${auction.auctionendtime}" pattern="yyyy-MM-dd"/>
</li>
<li>${auction.auctionstartprice}</li>
<li class="borderno red">
<c:if test="${sessionScope.user.userisadmin==1}">
<a href="#" title="็ซๆ" onclick="update(${auction.auctionid});">ไฟฎๆน</a>|
<a href="#" title="็ซๆ" onclick="abc(${auction.auctionid});">ๅ ้ค</a>
</c:if>
<c:if test="${sessionScope.user.userisadmin==0}">
<a href="${pageContext.request.contextPath}/toDetail/${auction.auctionid}">็ซๆ</a>
</c:if>
</li>
</ul>
</c:forEach>
<!--
<div class="page">
[ๅฝๅ็ฌฌ${page.pageNum}้กต๏ผๆปๅ
ฑ${page.pages}้กต๏ผๆปๅ
ฑ${page.total}ๆก่ฎฐๅฝ]
<a href="${pageContext.request.contextPath}/queryAuctions?pageNum=1">้ฆ้กต</a>
<a href="${pageContext.request.contextPath}/queryAuctions?pageNum=${page.prePage}" title="">ไธไธ้กต</a>
<a href="${pageContext.request.contextPath}/queryAuctions?pageNum=${page.nextPage}" title="">ไธไธ้กต</a>
<a href="${pageContext.request.contextPath}/queryAuctions?pageNum=${page.pages}" title="">ๅฐพ้กต</a>
</div>
-->
<div class="page">
[ๅฝๅ็ฌฌ${page.pageNum}้กต๏ผๆปๅ
ฑ${page.pages}้กต๏ผๆปๅ
ฑ${page.total}ๆก่ฎฐๅฝ]
<a href="javascript:jumpPage(1)">้ฆ้กต</a>
<a href="javascript:jumpPage(${page.prePage})">ไธไธ้กต</a>
<a href="javascript:jumpPage(${page.nextPage})">ไธไธ้กต</a>
<a href="javascript:jumpPage(${page.pages})">ๅฐพ้กต</a>
</div>
</div>
<script>
function zhuxiao(){
if(confirm("็กฎๅฎ่ฆ้ๅบๅ?")){
window.location.href="${pageContext.request.contextPath}/doLogout"
return true;
}else{
return false;
}
}
//${pageContext.request.contextPath}/doLogout
function jumpPage(pageNo){
document.getElementById("page").value=pageNo;
document.getElementById("form_query").submit();
//document.getElementById("page").value=pageNo;
//ๆๅจๆไบคๆฅ่ฏข่กจๅ(ๅ
ๅซไบๆฅ่ฏข็ๆกไปถ)
//document.getElementById("form_query").submit();
}
function abc(auctionid){
if(confirm("ไฝ ็็็กฎ่ฎค่ฆๅ ้คๅ๏ผ")){
location="${pageContext.request.contextPath}/removeAuction/"+auctionid;
return true;
}
else{
return false;
}
};
function update(auctionid){
if(confirm("ไฝ ็็็กฎ่ฎค่ฆไฟฎๆนๅ๏ผ่ฏท็กฎ่ฎค")){
location="${pageContext.request.contextPath}/toUpdate/"+auctionid;
return true;
}
else{
return false;
}
}
</script>
<!-- main end-->
</div>
</body>
</html> |
{% extends 'layout.twig' %}
{% block title "Mes articles" %}
{% block body %}
<h1>Bienvenue sur le blog</h1>
<div class="row">
{# On recupere les articles que l'on groupe par quatre ( batch(4)) a chaque nouvelle ligne#}
{% for row in posts | batch(4) %}
<div class="card-deck">
{% for post in row %}
<div class="card">
<div class="card-header">
{#Le titre de l'article#}
<h2><a href="{{ path('blog.show', {slug: post.slug, id: post.id}) }}">
{{ post.name }}
</a></h2>
</div>
{#Le texte de chaque article#}
<div class="card-block">
<p class="card-text">
{#On affiche les extraits des articles grace au filtre (excerpt) cree#}
{{ post.content | excerpt | nl2br }}
</p>
<p class="text-muted">{{ post.created_at | ago }}</p>
</div>
<div class="card-footer">
<a href="{{ path('blog.show', {slug: post.slug, id: post.id}) }}" class="btn btn-primary">
Voir l'article
</a>
</div>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
{{ paginate(posts, 'blog.index') }}
{% endblock %} |
import './donations.scss';
import User1 from '../../../assets/user1.png';
import User2 from '../../../assets/user2.png';
import User3 from '../../../assets/user3.png';
import User4 from '../../../assets/user4.png';
import User5 from '../../../assets/user5.png';
import Searchicon from "./search.svg";
import { useState } from 'react';
import { useQuery } from 'react-query';
import { getAllDonations } from '../../../services/donations';
import moment from 'moment'
import { useHistory } from 'react-router-dom';
const Donations = () => {
const [searchValue, setSearchValue] = useState("");
const {data, isLoading, error} = useQuery("get all donations", getAllDonations)
if(isLoading) {
console.log('donations is loading')
}else if(data) {
console.log('donations', data)
} else {
console.log(error)
}
const history = useHistory();
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return (
<div className='don'>
<p className="title">Donations</p>
<div className="top-row">
<div className="left">
<div className="input">
<img src={Searchicon} alt="search_icon" />
<input onChange={e => setSearchValue(e.target.value)} type="text" placeholder="Search donor" />
</div>
</div>
<div className="right">
<select>
<option>Date</option>
</select>
<select>
<option selected disabled>Sponsor</option>
<option value="individual">Individual</option>
<option value="organization">Organization</option>
</select>
</div>
</div>
<div className="donations">
<table>
<tr className='label-row'>
<td>Date</td>
<td>Name</td>
<td>Sponsor Type</td>
<td>Amount</td>
<td>Event</td>
</tr>
{!isLoading && data?.data?.result.filter(el => el.name.toLowerCase().includes(searchValue.toLowerCase())).map(({name, createdAt, sponsorType, _id: id, amountDonated, eventDonatedTo}, index) => {
return (
<tr onClick={() => history.push("/dashboard/donations/view-donation", {donationId: id})} className='content-row' key={index}>
<td>{moment().calendar(createdAt)}</td>
<td>{name}</td>
<td className='spons'>{sponsorType.toUpperCase()}</td>
<td>N{parseInt(amountDonated).toLocaleString()}</td>
<td className='event'>{eventDonatedTo}</td>
</tr>
)
})}
</table>
</div>
<div className="btm-row">
<div className="left">
<p>Showing: {data?.data?.result.length}/{data?.data?.result.length}</p>
</div>
<ul>
<li><i className="fas fa-angle-left"></i></li>
<li>6</li>
<li>7</li>
<li>..</li>
<li>9</li>
<li>10</li>
<li><i className="fas fa-angle-right"></i></li>
</ul>
</div>
</div>
)
}
export default Donations; |
<template>
<div class="register">
<h3>
ๆณจๅๆฐ็จๆท
<span class="go"
>ๆๆ่ดฆๅท๏ผๅป <router-link to="/login" target="_blank">็ป้</router-link>
</span>
</h3>
<div class="content">
<label>ๆๆบๅท:</label>
<input type="text" v-model="phone" placeholder="่ฏท่พๅ
ฅไฝ ็ๆๆบๅท" />
<span class="error-msg">้่ฏฏๆ็คบไฟกๆฏ</span>
</div>
<div class="content">
<label>้ช่ฏ็ :</label>
<input type="text" v-model="code" placeholder="่ฏท่พๅ
ฅ้ช่ฏ็ " />
<button @click="toSmsCode" class="btn-code">่ทๅ้ช่ฏ็ </button>
<span class="error-msg">้่ฏฏๆ็คบไฟกๆฏ</span>
</div>
<div class="content">
<label>็ปๅฝๅฏ็ :</label>
<input type="text" v-model="password" placeholder="่ฏท่พๅ
ฅไฝ ็็ปๅฝๅฏ็ " />
<span class="error-msg">้่ฏฏๆ็คบไฟกๆฏ</span>
</div>
<div class="content">
<label>็กฎ่ฎคๅฏ็ :</label>
<input type="text" v-model="password_2" placeholder="่ฏท่พๅ
ฅ็กฎ่ฎคๅฏ็ " />
<span class="error-msg">้่ฏฏๆ็คบไฟกๆฏ</span>
</div>
<div class="controls">
<input name="m1" @change="agree" type="checkbox" />
<span>ๅๆๅ่ฎฎๅนถๆณจๅใๅฐๅๆฑ็จๆทๅ่ฎฎใ</span>
<span class="error-msg">้่ฏฏๆ็คบไฟกๆฏ</span>
</div>
<div class="btn">
<button @click="handlerRegister">ๅฎๆๆณจๅ</button>
</div>
</div>
</template>
<script>
import {mapActions} from "vuex";
export default {
name: "Register",
data() {
return {
phone: "",
code: "",
password: "",
password_2: "",
checked: false
}
},
computed: {
},
methods: {
...mapActions(["sendSmsCode", "register"]),
// ๅ้็ญไฟก้ช่ฏ็
async toSmsCode() {
if (this.phone) {
this.code = await this.sendSmsCode({phone: this.phone})
}
},
agree(event) {
this.checked = event.target.checked
},
// ๆณจๅ
handlerRegister() {
// ๅๆฐๆ ก้ช
if (this.phone && this.password && this.password_2 && this.code) {
if (this.checked) {
if (this.password === this.password_2) {
this.register({phone: this.phone, password: this.password_2, code: this.code})
// ่ทณ่ฝฌ็ปๅฝ้กต
this.$router.push("/login")
} else {
alert("ๅๅๅฏ็ ไธไธ่ด")
}
} else {
alert("่ฏทๅพ้ๅ่ฎฎ")
}
} else {
alert("ๅฟ
ๅกซๅๆฐไธ่ฝไธบ็ฉบ")
}
}
}
};
</script>
<style lang="less" scoped>
.register {
width: 1200px;
height: 445px;
border: 1px solid rgb(223, 223, 223);
margin: 0 auto;
h3 {
background: #ececec;
margin: 0;
padding: 6px 15px;
color: #333;
border-bottom: 1px solid #dfdfdf;
font-size: 20.04px;
line-height: 30.06px;
span {
font-size: 14px;
float: right;
a {
color: #e1251b;
}
}
}
div:nth-of-type(1) {
margin-top: 40px;
}
.content {
padding-left: 390px;
margin-bottom: 18px;
position: relative;
label {
font-size: 14px;
width: 96px;
text-align: right;
display: inline-block;
}
input {
width: 270px;
height: 38px;
padding-left: 8px;
box-sizing: border-box;
margin-left: 5px;
outline: none;
border: 1px solid #999;
}
img {
vertical-align: sub;
}
.error-msg {
position: absolute;
top: 100%;
left: 495px;
color: red;
}
.btn-code {
height: 38px;
box-sizing: border-box;
outline: none;
border: 1px solid #999;
}
}
.controls {
text-align: center;
position: relative;
input {
vertical-align: middle;
}
.error-msg {
position: absolute;
top: 100%;
left: 495px;
color: red;
}
}
.btn {
text-align: center;
line-height: 36px;
margin: 17px 0 0 55px;
button {
outline: none;
width: 270px;
height: 36px;
background: #e1251b;
color: #fff !important;
display: inline-block;
font-size: 16px;
}
}
}
</style> |
package tests;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import pageObjects.AccountServicesPage;
import pageObjects.MainPage;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AccountRegistrationTest extends TestBase {
@Test
@Tag("RegressionTest")
public void registerNewAccountTest(){
String userName = createRandomUserName(5);
String desiredMessage = "Your account was created successfully. You are now logged in.";
AccountServicesPage accountServicesPage = new MainPage()
.goToRegisterAccountPage()
.typeIntoFirstNameInput("John")
.typeIntoLastNameInput("Johnson")
.typeIntoAddressInput("Brooklyn 99")
.typeIntoCityInput("New York")
.typeIntoStateInput("New York")
.typeIntoZipCodeInput("00-000")
.typeIntoPhoneNumberInput("180080000")
.typeIntoSSNInput("00000")
.typeIntoUserNameInput(userName)
.typeIntoPasswordInput("Pass1")
.typeIntoConfirmPasswordInput("Pass1")
.submitAccountRegistration();
assertEquals(desiredMessage, accountServicesPage.getSuccessfulRegisterMessage());
}
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Finding Biomarker</title>
<link href="../css/bootstrap.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" type="text/css" href="../css/template_index.css">
</head>
<body>
<div>
<div id="back"><img src="../img/bitl.png"></div>
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li><a href="../index.html">HOME</a></li>
<li><a href="../introduction/introduction.html">Intreoduction</a></li>
<li><a href="../professor/professor.html">Professor</a></li>
<li><a href="../members/members.html">Members</a></li>
<li><a href="../research/research_journal.html">Research</a></li>
<li><a href="../education/education.html">Education</a></li>
<li class="active"><a href="../sw/software.html">Software</a></li>
</ul>
</div>
</div>
<div class="board">
<div class="menu">
<ul class="nav nav-pills nav-stacked">
<li>
<a href="./software.html">BIO SOFTWARE</a>
</li>
<li>
<a href="./balancedSampling.html">balancedSampling</a>
</li>
<li>
<a href="./f_interaction.html">f_interaction</a>
</li>
<li>
<a href="./Hybrid_RFE.html">Hybrid RFE</a>
</li>
</ul>
</div>
<h3>[ Feature Selection Library for Biomarker Identification ]</h3>
<table>
<tbody>
<tr>
<td>
<p><font size="2" face="Verdana"><font size="3"><strong>1. Introduction
<br></strong></font>One of important application of gene expression data is to find significant
genes related with specific disease such as lung cancer. These significant genes may be used as
biomarker to diagnose the disease. Data mining approach is useful to find the biomarker and
perform diagnosis. Feature selection and classification schemes are widely used for the purpose.
In this study, we suggest data mining approach for finding biomarker genes based on microarray
dataset. Proposed approach contains procedural steps to finding and testing biomarker genes. We
also implement the proposed method as R library for general usage. We test 12 microarray
datasets using implemented library, and suggest best biomarker genes and proper predictor
(classifier) for each of them. One of identified biomarker genes is compared with differentially
expressed gene list including biological network analysis. </font></p>
<p><font size="2" face="Verdana"><font size="3"><strong>1. Process of disease diagnosis using
biomarker</strong></font>
</font></p>
<p align="center"><font size="2" face="Verdana"><img width="100%" heigh="100%"
src="fig_1.png"></font></p><font size="2"
face="Verdana">
<p><font size="2" face="Verdana"><font size="3"><strong>2. Overall steps of procedure to find
biomarker </strong></font>
</font></p>
<p align="center"><font size="2" face="Verdana"><img width="40%" heigh="40%" src="fig_2.png"></font>
</p><font size="2" face="Verdana">
<p align="left"><font size="2" face="Verdana"><font size="3"><strong>3.
Usage<br></strong></font><br><br>
<b>Format of input dataset: </b><br><br>
The dataset should be .csv format. Columns are genes and rows are samples in the data table.
First column expresses phenotype of samples for target disease. The dataset may contain gene
name or gene id in the first row.<br><br>
</font></p>
<p align="center"><font size="2" face="Verdana"><img width="90%" heigh="90%" src="fig_3.png"></font>
</p><font size="2" face="Verdana">
<b>Execution</b><br><br>
- modify main.R to designate file name of dataset and parameter setting <br>
- User can choose sort of algorithms that he/she wants to test through parameter setting<br>
- Execute main.R <br><br>
<b>Result</b><br><br>
- view RESULT_TOTAL.csv file in 'result' directory <br>
<p align="center"><img width="60%" heigh="60%" src="fig_4.png"></p>
<p align="left"><font size="2" face="Verdana"><font size="3"><strong>3. Download R source
code<br></strong></font><br>
</font></p>
<ul><font size="2" face="Verdana">
<li><a href="published_code_20150121.zip" download>published_code_20150121.zip</a><br>
</li>
</font></ul>
<font size="2" face="Verdana">
<b>Sample Dataset</b><br><br>
<ul>
<li><a href="ALL.csv" target="blank">ALL.csv</a><br>
</li>
</ul>
</font>
<p></p>
<!--P align=left><FONT size=2 face=Verdana><FONT
size=3><STRONG>4. Citation Request: <BR></STRONG></FONT><BR>
Sejong Oh, A new dataset evaluation method based on category overlap, Computers in Biology and Medicine, 41 (2011) 115-122.-->
</font></font></font></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html> |
<template>
<v-main>
<header-app />
<div>
<v-container class="container">
<h1>{{ isNew ? "Agregar un Nuevo" : "Editar" }} Proveedor</h1>
<br />
<v-row>
<v-col cols="12" sm="6">
<v-text-field
label="Nombre del proveedor"
:rules="nameRules"
hide-details="auto"
v-model="name"
>
<v-icon slot="prepend" color="#dAA520"> mdi-account </v-icon>
</v-text-field>
</v-col>
<v-col cols="12" sm="6">
<v-text-field
label="ruc"
hide-details="auto"
v-model="ruc"
type="number"
>
<v-icon slot="prepend" color="#dAA520"> mdi-smart-card </v-icon>
</v-text-field>
</v-col>
<v-col cols="12" sm="6">
<v-text-field
label="Nรบmero de contacto:"
type="number"
hide-details="auto"
v-model="contact"
:rules="numberRules"
>
<v-icon slot="prepend" color="#dAA520"> mdi-cellphone </v-icon>
</v-text-field>
</v-col>
<v-col cols="12" sm="6">
<v-text-field
v-model="mail"
:rules="mailRules"
hide-details="auto"
label="Correo de contacto:"
>
<v-icon slot="prepend" color="#dAA520"> mdi-email </v-icon>
</v-text-field>
</v-col>
</v-row>
</v-container>
<div class="botones">
<v-btn
tile
class="rounded-pill"
style="margin-right: 10px"
dark
color="#E65245"
link
href="/proveedores"
>
<v-icon left wh> mdi-close-thick </v-icon>
Cancelar
</v-btn>
<v-btn
tile
dark
class="rounded-pill"
color="#dAA520"
@click="guardar()"
v-if="isNew"
>
<v-icon left> mdi-account-check </v-icon>
Guardar
</v-btn>
<v-btn
tile
dark
class="rounded-pill"
color="#dAA520"
@click="actualizar()"
v-if="!isNew"
>
<v-icon left> mdi-account-check </v-icon>
Actualizar
</v-btn>
</div>
<v-snackbar v-model="snackbar">
{{ snackbarText }}
<template v-slot:action="{ attrs }">
<v-btn color="blue" text v-bind="attrs" @click="closeConfirmation()">
Cerrar
</v-btn>
</template>
</v-snackbar>
</div>
</v-main>
</template>
<script>
import HeaderApp from "../HeaderApp.vue";
import {
getSuplier,
createSuplier,
updateSuplier,
} from "../../../controllers/Suplier.controller";
export default {
components: { HeaderApp },
data() {
return {
name: "",
ruc: 0,
contact: 0,
mail: "",
select: null,
snackbar: false,
snackbarText: "",
isNew: true,
nameRules: [
(value) => !!value || "Required.",
(value) => (value && value.length >= 3) || "Min 3 characters",
],
mailRules: [
(value) => !!value || "Required.",
(value) => value.length <= 20 || "Max 20 characters",
(value) => {
const pattern =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return pattern.test(value) || "Invalid e-mail.";
},
],
numberRules: [(value) => !!value || "Required."],
};
},
created() {
const ruc = this.$route.params.ruc;
if (ruc != undefined) {
getSuplier(ruc)
.then((response) => {
const suplier = response.data;
this.ruc = suplier.ruc;
this.name = suplier.name;
this.contact = suplier.contact;
this.mail = suplier.mail;
this.isNew = false;
})
.catch((err) => console.error(err));
}
},
methods: {
guardar() {
const suplier = {
ruc: this.ruc,
contact: this.contact,
name: this.name,
mail: this.mail,
};
createSuplier(suplier)
.then(() => {
this.openSuccesDialog("Guardado correctamente");
})
.catch((err) => console.error(err));
},
actualizar() {
if (
this.ruc == undefined ||
this.ruc == "" ||
this.name == undefined ||
this.name == ""
) {
this.openErrorDialog("Ingrese los campos obligatorios");
return;
}
const suplier = {
name: this.name,
ruc: this.ruc,
contact: this.contact,
mail: this.mail,
};
updateSuplier(this.ruc, suplier)
.then(() => {
this.openSuccesDialog("Se ha actualizado el proveedor: " + this.name);
})
.catch(() =>
this.openErrorDialog("Ha ocurrido un error al actualizar el producto")
);
},
openSuccesDialog(mensaje) {
this.snackbarText = mensaje;
this.snackbar = true;
},
openErrorDialog(mensaje) {
this.snackbarText = mensaje;
this.snackbar = true;
},
closeConfirmation() {
this.snackbar = false;
this.$router.push("/Proveedores");
},
},
};
</script>
<style>
.botones {
text-decoration: none !important;
padding-right: 10px;
padding-top: 30px;
float: right;
}
a:hover {
text-decoration: none;
}
input {
border-color: rgba(255, 255, 255, 0) !important;
}
.v-input__slot {
margin-left: 20px;
background: rgba(255, 255, 255, 0) !important;
}
.v-input__prepend-outer {
margin-left: 30px;
}
.v-main {
padding: 50px 0px 0px !important;
}
h1 {
text-align: center;
font-weight: bold;
color: #494949;
}
</style> |
import { useMutation } from "@tanstack/react-query";
import http from "../utils/http";
import { useToast } from "@chakra-ui/react";
interface FailorSuccess {
onSignUpSuccess: () => void,
onSignUpFail: () => void
}
function useSignUp({onSignUpSuccess, onSignUpFail}: FailorSuccess) {
const toast = useToast();
return useMutation({
mutationKey: ["signUp"],
mutationFn: async ({ name, email, password }: { name: string; email: string; password: string }) => {
try {
const formData = { name, email, password };
const res = await http.post("/users", formData);
if (res.status === 201) {
toast({
title: "Sign up success! Proceed to login!",
status: "success",
position: 'top'
});
onSignUpSuccess();
}
} catch (error: any) {
onSignUpFail()
if (error.response) {
// The request was made, but the server responded with a status code that falls out of the range of 2xx
if (error.response.status === 400) {
toast({
title: "User with this email already exists",
status: "error",
position: 'top'
});
} else if (error.response.status === 422) {
toast({
title: "Invalid email address",
status: "warning",
position: 'top',
});
}else {
// Handle other types of errors or exceptions
// For example, network error
console.error("Error:", error);
}
}
}
},
});
}
export default useSignUp; |
import { createSlice } from "@reduxjs/toolkit";
import type { PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "./store";
// Define a type for the slice state
interface CounterState {
mode: boolean;
}
// Define the initial state using that type
const initialState: CounterState = {
mode: false,
};
export const userSlice = createSlice({
name: "user",
// `createSlice` will infer the state type from the `initialState` argument
initialState,
reducers: {
setMode: (state) => {
state.mode = !state.mode;
},
},
});
export const { setMode } = userSlice.actions;
export default userSlice.reducer; |
import * as vscode from 'vscode';
import { Uri } from "vscode";
import * as path from 'path';
import { exec } from 'child_process';
import { getUri } from '../utils/getUri';
import { getWebviewContent } from '../utils/getWebViewContent';
import { readKeyValue2 } from '../utils/kvUtils';
import { readFile } from '../utils/readFile';
import { showStatusBarMessage } from '../module/statusBar';
import { getContentDir, getGameDir } from '../module/addonInfo';
import { getPathInfo } from '../utils/pathUtils';
let spellicons: Table;
let items: Table;
let npcHeroes: Table;
interface CustomIcon {
game: Table,
content: Table,
}
let customSpellicons: CustomIcon = {
game: {},
content: {}
};
let customItems: CustomIcon = {
game: {},
content: {}
};
export async function dota2IconPanelInit(context: vscode.ExtensionContext) {
spellicons = await getFolderIcons(context.extensionUri, "/images/spellicons");
items = await getFolderIcons(context.extensionUri, "/images/items");
npcHeroes = await readHeroesIcon(context.extensionUri, "/images/heroes_icon");
// ่ชๅฎไนๅพๆ
await locdCustomSpellicons();
await locdCustomItems();
}
async function locdCustomSpellicons() {
let gameDir = getGameDir();
if (gameDir) {
if (await getPathInfo(path.join(gameDir, "/resource/flash3/images/spellicons")) !== false) {
customSpellicons.game = await getFolderIcons(vscode.Uri.file(gameDir), "/resource/flash3/images/spellicons");
}
}
let contentDir = getContentDir();
if (contentDir) {
if (await getPathInfo(path.join(contentDir, "/panorama/images/spellicons")) !== false) {
customSpellicons.content = await getFolderIcons(vscode.Uri.file(contentDir), "/panorama/images/spellicons");
}
}
}
async function locdCustomItems() {
let gameDir = getGameDir();
if (gameDir) {
if (await getPathInfo(path.join(gameDir, "/resource/flash3/images/items")) !== false) {
customItems.game = await getFolderIcons(vscode.Uri.file(gameDir), "/resource/flash3/images/items");
}
}
let contentDir = getContentDir();
if (contentDir) {
if (await getPathInfo(path.join(contentDir, "/panorama/images/items")) !== false) {
customItems.content = await getFolderIcons(vscode.Uri.file(contentDir), "/panorama/images/items");
}
}
}
/**
* ๆ่ฝไธ็ฉๅๅพๆ ็ๆฅ่ฏข
* @export
* @param {vscode.ExtensionContext} context
*/
export async function dota2IconPanel(context: vscode.ExtensionContext) {
// ๅๅปบไธไธชWebview่งๅพ
const panel = vscode.window.createWebviewPanel(
'dota2IconPanel', // viewType
"Dota2ๅพๆ ", // ่งๅพๆ ้ข
vscode.ViewColumn.One, // ๆพ็คบๅจ็ผ่พๅจ็ๅชไธช้จไฝ
{
enableScripts: true, // ๅฏ็จJS๏ผ้ป่ฎค็ฆ็จ
retainContextWhenHidden: true, // webview่ขซ้่ๆถไฟๆ็ถๆ๏ผ้ฟๅ
่ขซ้็ฝฎ
}
);
// ้ฒๆญขๆฐๆฎไธบ็ฉบ
if (spellicons === undefined) {
spellicons = await getFolderIcons(context.extensionUri, "/images/spellicons");
}
if (items === undefined) {
items = await getFolderIcons(context.extensionUri, "/images/items");
}
if (npcHeroes === undefined) {
npcHeroes = await readHeroesIcon(context.extensionUri, "/images/heroes_icon");
}
// ่ชๅฎไนๅพๆ
if (customSpellicons === undefined) {
locdCustomSpellicons();
}
if (customItems === undefined) {
locdCustomItems();
}
// ้กต้ขๅ
ๅฎน
panel.webview.html = await getWebviewContent(panel.webview, context.extensionUri, "dota2Icon", html => {
let replaceText = "";
// ่ฑ้ๅพๆ
for (const attributeType in npcHeroes) {
replaceText = "";
for (const heroName in npcHeroes[attributeType]) {
replaceText += `\t\t\t\t\t\t<img class="hero-icon" src="../../${npcHeroes[attributeType][heroName]}" onclick="heroFilter(this,'${heroName}')">\n`;
}
html = html.replace("<div>__replace__</div>", replaceText);
}
// ๆ่ฝๅพๆ
replaceText = "";
for (const iconName in spellicons) {
const iconPath = spellicons[iconName];
replaceText += `\t\t<img id="${iconName}" class="icon texture-icon" src="../../${iconPath}" onclick="copyIconName('${iconName}')" oncontextmenu="openFolder('spellicons/${iconName}')">\n`;
}
if (Object.keys(customSpellicons.game).length > 0) {
let gameDir = getGameDir();
for (const iconName in customSpellicons.game) {
const iconPath = customSpellicons.game[iconName];
const src = getUri(panel.webview, vscode.Uri.file(gameDir), [iconPath]);
replaceText += `\t\t<img id="${iconName}" class="icon texture-icon" src="${src}" onclick="copyIconName('${iconName}')" oncontextmenu="openFolder('spellicons/${iconName}')">\n`;
}
}
if (Object.keys(customSpellicons.content).length > 0) {
let contentDir = getContentDir();
for (const iconName in customSpellicons.content) {
const iconPath = customSpellicons.content[iconName];
const src = getUri(panel.webview, vscode.Uri.file(contentDir), [iconPath]);
replaceText += `\t\t<img id="${iconName}" class="icon texture-icon" src="${src}" onclick="copyIconName('${iconName}')" oncontextmenu="openFolder('spellicons/${iconName}')">\n`;
}
}
html = html.replace("<div>__replace__</div>", replaceText);
// ็ฉๅๅพๆ
replaceText = "";
for (const iconName in items) {
const iconPath = items[iconName];
replaceText += `\t\t<img id="${iconName}" class="icon item-texture-icon" src="../../${iconPath}" onclick="copyIconName('item_${iconName}')" oncontextmenu="openFolder('items/${iconName}')">\n`;
}
if (Object.keys(customItems.game).length > 0) {
let gameDir = getGameDir();
for (const iconName in customItems.game) {
const iconPath = customItems.game[iconName];
const src = getUri(panel.webview, vscode.Uri.file(gameDir), [iconPath]);
replaceText += `\t\t<img id="${iconName}" class="icon item-texture-icon" src="${src}" onclick="copyIconName('item_${iconName}')" oncontextmenu="openFolder('spellicons/${iconName}')">\n`;
}
}
if (Object.keys(customItems.content).length > 0) {
let contentDir = getContentDir();
for (const iconName in customItems.content) {
const iconPath = customItems.content[iconName];
const src = getUri(panel.webview, vscode.Uri.file(contentDir), [iconPath]);
replaceText += `\t\t<img id="${iconName}" class="icon item-texture-icon" src="${src}" onclick="copyIconName('item_${iconName}')" oncontextmenu="openFolder('spellicons/${iconName}')">\n`;
}
}
html = html.replace("<div>__replace__</div>", replaceText);
return html;
});
// ็ๅฌๆถๆฏ
panel.webview.onDidReceiveMessage(async (message: { type: string, text: string; }) => {
console.log(message);
const type = message.type;
const text = message.text;
switch (type) {
case "copy_ability_name": // ๅคๅถๆ่ฝๅ
let texture: string = text.replace(/_png\.png/, '').replace(/\\/g, "/");
vscode.env.clipboard.writeText(texture);
showStatusBarMessage('ๅทฒๅฐๅพๆ ่ทฏๅพๅคๅถๅฐๅชๅๆฟ๏ผ' + texture);
return;
case "copy_ability_file": // ๅคๅถๆไปถ
let fullpath = path.join(context.extensionPath, 'images', text);
exec(`explorer.exe /select,"${fullpath}_png.png"`);
return;
}
}, null, context.subscriptions);
// ้ๆฏๅค็
panel.onDidDispose(() => {
}, null, context.subscriptions);
}
/**
* ่ทๅๆไปถๅคนไธญ็ๅพๆ ไฟกๆฏ
* @param iconPath ๆไปถๅคน่ทฏๅพๆ่
ๆไปถๅคน่ทฏๅพๆฐ็ป
*/
async function getFolderIcons(extensionUri: Uri, iconPath: string | string[]) {
let iconsInfo: Table = {};
if (typeof (iconPath) === 'string') {
let data = await readFolder(extensionUri, iconPath);
iconsInfo = Object.assign(iconsInfo, data);
} else {
for (let i = 0; i < iconPath.length; i++) {
const _path = iconPath[i];
let data = await readFolder(extensionUri, _path);
iconsInfo = Object.assign(iconsInfo, data);
}
}
return iconsInfo;
}
async function readFolder(extensionUri: Uri, relativeIconPath: string, currentPath: string = "") {
let iconsInfo: Table = {};
let folders: [string, vscode.FileType][] = await vscode.workspace.fs.readDirectory(Uri.joinPath(extensionUri, relativeIconPath));
for (let i: number = 0; i < folders.length; i++) {
const [name, isDirectory] = folders[i];
if (name === undefined) {
continue;
}
if (isDirectory === vscode.FileType.Directory) {
let data = await readFolder(extensionUri, path.join(relativeIconPath, name), path.join(currentPath, name));
iconsInfo = Object.assign(iconsInfo, data);
} else if (isDirectory === vscode.FileType.File) {
iconsInfo[path.join(currentPath, name).replace('_png.png', '').replace('.png', '').replace(/\\/g, "/")] = path.join(relativeIconPath, name);
}
}
return iconsInfo;
}
async function readHeroesIcon(extensionUri: Uri, heroesPath: string) {
let heroesData: Table = {};
let heroesInfo: Table = await readKeyValue2(await readFile(Uri.joinPath(extensionUri, "/resource/npc/npc_heroes.txt")));
for (const heroName in heroesInfo.DOTAHeroes) {
const heroData = heroesInfo.DOTAHeroes[heroName];
if (heroName !== "Version" && (heroData.Enabled === "1" || heroName === "npc_dota_hero_base")) {
if (heroesData[heroData.AttributePrimary] === undefined) {
heroesData[heroData.AttributePrimary] = {};
}
heroesData[heroData.AttributePrimary][heroName.replace('npc_dota_hero_', '')] = heroesPath + '/' + heroName + "_png.png";
}
}
return heroesData;
} |
import unittest
import json
import os
from models.base_model import BaseModel
from models.engine.file_storage import FileStorage
class TestFileStorage(unittest.TestCase):
def setUp(self):
"""
Set up the test environment by creating a temporary file path and a new
FileStorage instance.
"""
self.file_path = "test_file.json"
self.storage = FileStorage()
self.storage._FileStorage__file_path = self.file_path
def tearDown(self):
"""
Clean up the test environment by removing the temporary file if it
exists.
"""
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_new(self):
"""
Test that the 'new' method adds a new object to the storage dictionary.
"""
new_model = BaseModel()
self.storage.new(new_model)
all_objects = self.storage.all()
self.assertIn("BaseModel.{}".format(new_model.id), all_objects)
def test_save_and_reload(self):
"""
Test saving and reloading objects from the storage.
"""
new_model = BaseModel()
self.storage.new(new_model)
self.storage.save()
new_storage = FileStorage()
new_storage._FileStorage__file_path = self.file_path
new_storage.reload()
all_objects = new_storage.all()
self.assertIn("BaseModel.{}".format(new_model.id), all_objects)
reloaded_model = all_objects["BaseModel.{}".format(new_model.id)]
self.assertEqual(new_model.to_dict(), reloaded_model.to_dict())
def test_save_empty(self):
"""
Test that saving when there are no objects doesn't create a file.
"""
self.storage.save()
self.assertFalse(os.path.exists(self.file_path))
if __name__ == "__main__":
unittest.main() |
'use strict';
import describe from 'redtea';
import should from 'should';
import testWrapper from 'syn/../../dist/lib/app/test-wrapper';
import selectors from 'syn/../../selectors.json';
import Item from 'syn/../../dist/models/item';
import Type from 'syn/../../dist/models/type';
import Config from 'syn/../../dist/models/config';
import identify from 'syn/../../dist/test/util/e2e-identify';
import createItem from 'syn/../../dist/test/util/e2e-create-item';
function test(props) {
const locals = {};
return testWrapper(
'Story -> Item -> Children',
{ mongodb : true, http : { verbose : true }, driver : true },
wrappers => it => {
it('Populate data', it => {
it('Get top level type', it => {
it('should get top level type from config', () =>
Config.get('top level type').then(type => { locals.type = type })
);
});
it('should get type', () => Type.findById(locals.type)
.then(type => { locals.type = type })
);
it('should get subtype', () => locals.type.getSubtype()
.then(subtype => { locals.subtype = subtype })
);
it('Create item', it => {
it('should create item', () =>
Item.lambda({ type : locals.type })
.then(item => { locals.item = item })
);
});
});
it('should go to home page', () =>
wrappers.driver.client
.url(`http://localhost:${wrappers.http.app.get('port')}`)
);
it('should sign in', describe.use(
() => identify(wrappers.driver.client, locals.user)
));
it('should close training', () => wrappers.driver.click(
selectors.training.close, 5000
));
it('should have a subtype button', () =>
wrappers.driver.exists([
selectors.item.id.prefix + locals.item._id,
selectors.item.subtype
].join(' '))
);
it('should say 0', () =>
wrappers.driver.hasText([
selectors.item.id.prefix + locals.item._id,
selectors.item.subtype,
'> span span:first-child'
].join(' '), '0')
);
it('should click on subtype button', () =>
wrappers.driver.click([
selectors.item.id.prefix + locals.item._id,
selectors.item.subtype
].join(' '))
);
it('should click on toggle create subtype', () =>
wrappers.driver.click([
selectors.item.id.prefix + locals.item._id,
selectors.subtype,
selectors.create.toggle
].join(' '))
);
it('should create item',
describe.use(() => createItem(wrappers.driver, [
selectors.item.id.prefix + locals.item._id,
selectors.subtype
].join(' '), {
subject : 'Test subtype',
description : 'Test subtype'
}))
);
describe.pause(1000)(it);
it('should say 1', () =>
wrappers.driver.hasText([
selectors.item.id.prefix + locals.item._id,
'> .item-buttons ' + selectors.item.subtype,
'> span span:first-child'
].join(' '), '1')
);
}
);
}
export default test; |
# -*- coding: utf-8 -*-
################################################################################
# Creme is a free/open-source Customer Relationship Management software
# Copyright (C) 2009-2018 Hybird
#
# 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/>.
################################################################################
from datetime import timedelta
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.mail import get_connection
from django.core.mail.message import EmailMessage
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _, ugettext
from creme.creme_core.creme_jobs.base import JobType
from creme.creme_core.models import JobResult
from creme.persons.constants import REL_SUB_CUSTOMER_SUPPLIER
class _ComApproachesEmailsSendType(JobType):
id = JobType.generate_id('commercial', 'com_approaches_emails_send')
verbose_name = _(u'Send emails for commercials approaches')
periodic = JobType.PERIODIC # It would be too difficult/inefficient to
# compute the next wake up, so it is not PSEUDO_PERIODIC.
# TODO: add a config form which stores the rules in job.data
list_target_orga = [(REL_SUB_CUSTOMER_SUPPLIER, 30)]
def _execute(self, job):
from creme import persons
from creme.opportunities import get_opportunity_model
from creme.opportunities.constants import REL_SUB_TARGETS
from .models import CommercialApproach
Organisation = persons.get_organisation_model()
Contact = persons.get_contact_model()
Opportunity = get_opportunity_model()
emails = []
get_ct = ContentType.objects.get_for_model
ct_orga = get_ct(Organisation)
ct_contact = get_ct(Contact)
ct_opp = get_ct(Opportunity)
now_value = now()
managed_orga_ids = list(Organisation.objects.filter(is_managed=True).values_list('id', flat=True))
opp_filter = Opportunity.objects.filter
EMAIL_SENDER = settings.EMAIL_SENDER
for rtype, delay in self.list_target_orga:
com_apps_filter = CommercialApproach.objects \
.filter(creation_date__gt=now_value - timedelta(days=delay)) \
.filter
# TODO: are 'values_list' real optimizations here ??
# ==> remove them when CommercialApproach use real ForeignKey
for orga in Organisation.objects.filter(is_managed=False,
relations__type=rtype,
relations__object_entity__in=managed_orga_ids,
):
if com_apps_filter(entity_content_type=ct_orga, entity_id=orga.id).exists():
continue
if com_apps_filter(entity_content_type=ct_contact,
entity_id__in=orga.get_managers().values_list('id', flat=True)
).exists():
continue
if com_apps_filter(entity_content_type=ct_contact,
entity_id__in=orga.get_employees().values_list('id', flat=True)
).exists():
continue
if com_apps_filter(entity_content_type=ct_opp,
entity_id__in=opp_filter(relations__type=REL_SUB_TARGETS,
relations__object_entity=orga,
).values_list('id', flat=True)
).exists():
continue
emails.append(EmailMessage(ugettext(u"[CremeCRM] The organisation ยซ{}ยป seems neglected").format(orga),
ugettext(u"It seems you haven't created a commercial approach for "
u"the organisation ยซ{orga}ยป since {delay} days.").format(
orga=orga,
delay=delay,
),
EMAIL_SENDER, [orga.user.email],
)
)
# TODO: factorise jobs which send emails
if emails:
try:
with get_connection() as connection:
connection.send_messages(emails)
except Exception as e:
JobResult.objects.create(job=job,
messages=[ugettext(u'An error has occurred while sending emails'),
ugettext(u'Original error: {}').format(e),
],
)
def get_description(self, job):
return [ugettext(u"For each customer organisation, an email is sent to its owner (ie: a Creme user), "
u"if there is no commercial approach since {} days linked to: "
u"the organisation, one of its managers/employees, "
u"or an Opportunity which targets this organisation."
).format(self.list_target_orga[0][1]),
]
com_approaches_emails_send_type = _ComApproachesEmailsSendType()
jobs = (com_approaches_emails_send_type,) |
package MethodEnums.Reservation;
import MethodEnums.IMenuInterface;
public enum SGetReservationMenu implements IMenuInterface {
GET_RESERVATIONS_BY_STUDENT_ID("getReservationsByStudentId", "search reservation by student Id"),
GET_RESERVATIONS_BY_COURSE_ID("getReservationsByCourseId", "search reservation by course Id"),
GET_RESERVATION_BY_BOTH_ID("getCourseById", "search reservation by student Id and course Id");
// Variables
private String method;
private String description;
// Getters & Setters
public String getMethod(){return method;}
public String getDescription(){return description;}
public void setMethod(String method){this.method = method;}
public void setDescription(String description){this.description = description;}
// Constructor
SGetReservationMenu(String method, String description){
this.method = method;
this.description = description;
}
} |
from django.db import models
class PackageType(models.Model):
CLOTHING = 'clothing'
ELECTRONICS = 'electronics'
OTHER = 'other'
TYPE_CHOICES = [
(CLOTHING, 'ะะดะตะถะดะฐ'),
(ELECTRONICS, 'ะญะปะตะบััะพะฝะธะบะฐ'),
(OTHER, 'ะ ะฐะทะฝะพะต'),
]
name = models.SlugField(max_length=20, choices=TYPE_CHOICES, unique=True, primary_key=True)
def __str__(self):
return self.get_name_display()
class Package(models.Model):
# ะฝะฐะทะฒะฐะฝะธะต
title = models.CharField(max_length=120)
# ะฒะตั
weight = models.DecimalField(max_digits=10, decimal_places=2)
type = models.ForeignKey(PackageType, on_delete=models.CASCADE, related_name='packages')
user_session = models.CharField(max_length=300)
# ัะตะฝะฐ ัะพะฒะฐัะฐ
cost = models.DecimalField(max_digits=10, decimal_places=2)
# ัะตะฝะฐ ะดะพััะฐะฒะบะธ
delivery = models.DecimalField(max_digits=10, decimal_places=2, null=True)
def __str__(self):
return self.title |
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>aMIGO</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Open+Sans'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.3/jquery.mCustomScrollbar.min.css'>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css' )}}">
</head>
<body>
<div class="chat">
<div class="chat-title">
<h1>aMIGO</h1>
<h2>Your virtual therapist</h2>
<figure class="avatar">
<img src="https://images.hdqwalls.com/download/neon-bot-ck-1125x2436.jpg" /></figure>
</div>
<div class="messages">
<div class="messages-content"></div>
</div>
<div class="message-box">
<textarea type="text" class="message-input" placeholder="Type message..."></textarea>
<button type="submit" class="message-submit">Send</button>
</div>
</div>
<div class="bg"></div>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.3/jquery.mCustomScrollbar.concat.min.js'></script>
<script>
var $messages = $('.messages-content'),
d, h, m,
i = 0;
$(window).load(function() {
$messages.mCustomScrollbar();
});
function updateScrollbar() {
$messages.mCustomScrollbar("update").mCustomScrollbar('scrollTo', 'bottom', {
scrollInertia: 10,
timeout: 0
});
}
function setDate(){
d = new Date()
if (m != d.getMinutes()) {
m = d.getMinutes();
$('<div class="timestamp">' + d.getHours() + ':' + m + '</div>').appendTo($('.message:last'));
}
}
function insertMessage() {
message = $('.message-input').val();
if ($.trim(message) == '') {
return false;
}
$('<div class="message message-personal">' + message + '</div>').appendTo($('.mCSB_container')).addClass('new');
setDate();
$('.message-input').val(null);
updateScrollbar();
Message(message)
}
$('.message-submit').click(function(e) {
e.preventDefault()
insertMessage();
});
$(window).on('keydown', function(e) {
if (e.which == 13) {
insertMessage();
return false;
}
})
function Message(message) {
$('<div class="message loading new"><figure class="avatar"><img src="https://images.hdqwalls.com/download/neon-bot-ck-1125x2436.jpg" /></figure><span></span></div>').appendTo($('.mCSB_container'));
updateScrollbar();
setTimeout(function() {
$('.message.loading').remove();
$.ajax({
type: "POST",
url: "/chatbot",
data: {
question: message
},
success: function(result) {
const d = new Date()
$('<div class="message new"><figure class="avatar"><img src="https://images.hdqwalls.com/download/neon-bot-ck-1125x2436.jpg" /></figure>' + result.response + '</div>').appendTo($('.mCSB_container')).addClass('new');
$(".message-input").val("")
},
error: function(result) {
alert('error');
}
});
// $('<div class="message new"><figure class="avatar"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/156381/profile/profile-80.jpg" /></figure>' + Fake[i] + '</div>').appendTo($('.mCSB_container')).addClass('new');
setDate();
updateScrollbar();
i++;
}, 1000 + (Math.random() * 20) * 100);
}
</script>
</body>
</html> |
import { Grid, Typography } from "@mui/material";
import { FC, useContext } from "react";
import { format } from "utils";
import { CartContext } from "../../context/cart/CartContext";
import { CartSummary } from "../../../core/product/entity/cartSummary";
interface Props {
cartSummary?: CartSummary;
}
const OrderSummary: FC<Props> = ({ cartSummary }) => {
if (!cartSummary) return <></>;
return (
<Grid container>
<Grid item xs={6}>
<Typography>No. Productos</Typography>
</Grid>
<Grid item xs={6} display="flex" justifyContent="end">
<Typography>{format(cartSummary.numberOfItems)} items</Typography>
</Grid>
<Grid item xs={6} display="flex">
<Typography>SubTotal</Typography>
</Grid>
<Grid item xs={6} display="flex" justifyContent="end">
<Typography>{`${format(cartSummary.subTotal)}`}</Typography>
</Grid>
<Grid item xs={6} display="flex">
<Typography>Impuesto ({format(cartSummary.taxRate * 100)}%)</Typography>
</Grid>
<Grid item xs={6} display="flex" justifyContent="end">
<Typography>{`${format(cartSummary.tax)}`}</Typography>
</Grid>
<Grid item xs={6} display="flex" sx={{ mt: 2 }}>
<Typography variant="subtitle1">Total</Typography>
</Grid>
<Grid item xs={6} display="flex" justifyContent="end">
<Typography variant="subtitle1" sx={{ mt: 2 }}>{`${format(
cartSummary.total
)}`}</Typography>
</Grid>
</Grid>
);
};
export default OrderSummary; |
<script setup lang="ts">
import {reactive, ref, toRefs} from "vue";
import type {FormRules} from "element-plus";
import Axios from 'axios'
// ๆฐๆฎๅฎไน
const state = reactive({
ruleForm: {
username: '',
password: ''
}
})
// ่งฃๆ๏ผๅ
ๅพๆฏไธชruleFormไนๅ้ฝ้่ฆๆๅจๆทปๅ state.
let { ruleForm } = toRefs(state)
// ่ชๅฎไนๆ ก้ช
const validatePass = (rule: unknown, value: string | undefined, callback: (msg?: string | Error)=> void) => {
if (value === '') {
callback(new Error('Please input the password'))
} else {
callback()
}
}
// ๆ ก้ช่งๅ
const rules = reactive<FormRules<typeof ruleForm>>({
username: [
{ required: true, message: '่ฏท่พๅ
ฅๆญฃ็กฎ็็จๆทๅ', trigger: 'blur' },
{ min: 6, max: 15, message: 'Length should be 6 to 15', trigger: 'blur' }
],
password: [
{ required: true, message: '่ฏท่พๅ
ฅๅฏ็ ', trigger: 'blur' },
{ min: 6, max: 11, message: 'Length should be 6 to 11', trigger: 'blur' },
// { validator: validatePass, trigger: 'blur' }
]
})
let ruleFormRef = ref()
// ็ปๅฝ
const login = () => {
ruleFormRef.value.validate().then(()=> {
console.log('ๆ ก้ช้่ฟ')
const response = Axios.get('127.0.0.1:7201/test/1')
console.log(response)
}).catch(()=> {
console.log('ๆ ก้ชไธ้่ฟ')
})
}
</script>
<template>
<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
<el-form-item label="็จๆทๅ๏ผ" prop="username">
<el-input v-model="ruleForm.username" type="text" autocomplete="off" />
</el-form-item>
<el-form-item label="ๅฏ็ ๏ผ" prop="password">
<el-input v-model="ruleForm.password" type="password" autocomplete="off" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="login()">็ปๅฝ</el-button>
<!--<el-button @click="resetForm(ruleFormRef)">Reset</el-button>-->
</el-form-item>
</el-form>
</template>
<style scoped lang="less">
</style> |
import { Injectable } from '@angular/core';
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, sendEmailVerification } from "firebase/auth";
import { ReplaySubject } from 'rxjs';
import { User } from '../models/User.model';
import { UsersService } from './users.service';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() { }
createNewUser(user: User, password: string) {
const userService = new UsersService(user)
const auth = getAuth();
return new Promise<void>(
(resolve, reject) => {
createUserWithEmailAndPassword(auth, user.email, password)
.then(
() => {
userService.createNewUser(user)
resolve()
},
(error: Error) => {
reject(error)
}
)
}
)
}
sendSignInLinkToEmail(email: string) {
const auth = getAuth();
var actionCodeSettings = {
url: 'https://final-angular.netlify.app/?email=' + auth.currentUser?.email,
handleCodeInApp: true,
// When multiple custom dynamic link domains are defined, specify which
// one to use.
dynamicLinkDomain: "example.page.link"
};
sendEmailVerification(auth.currentUser!).then(() => {
console.log("email sent");
}).catch((error: Error) => {
console.log('An error happened' + error);
});
}
// Dynamic Links will start with https://prostix.fr/xyz
// "appAssociation": "AUTO",
// "rewrites": [{ "source": "/xyz/**", "dynamicLinks": true }]
//google-site-verification=xwPDowz8YyFrSZuoTqWylQXtArbZmVutZzZ7wnPSC2c
signInUser(email: string, password: string) {
const auth = getAuth()
return new Promise<void>(
(resolve, reject) => {
signInWithEmailAndPassword(auth, email, password)
.then(
() => {
resolve();
},
(error: Error) => {
reject
}
)
}
)
}
signOutUser() {
const auth = getAuth();
signOut(auth).then(() => {
console.log('Sign-out successful.');
}).catch((error: Error) => {
console.log('An error happened' + error);
});
}
} |
import getClassName from "getclassname"
import React from "react"
import { mapWeather } from "../../core/Weather"
import { DayData } from "../../middleware"
import "./style.css"
type Styling = {
fill?: string,
stroke?: string,
}
export type OverlayGenericAction = {
type: "generic",
action: string,
label?: string | React.ReactNode,
idle?: Styling,
hover?: Styling,
transition?: string,
}
export type OverlayWeatherAction = {
type: "weather",
action: "weather",
data: DayData,
}
export type OverlayAction = OverlayGenericAction | OverlayWeatherAction
export type OverlayGenericActionProp = Omit<OverlayGenericAction,"type">
export type OverlayProps = {
blur?: boolean;
actions?: OverlayGenericActionProp[],
sideActions?: OverlayGenericActionProp[],
weatherData?: { day: number, amount: number }[],
selectedDay?: number,
onAction?: (actionData: OverlayAction) => void,
onGoBack?: () => void,
}
const purge = <T,>(obj: { [p: string]: T | undefined }) => {
return Object.fromEntries(Object.entries(obj).filter(([,val]) => val !== undefined ))
}
const cssVars = (pre: string, obj: Styling) => {
return {
[`--${pre}-fill`]: obj.fill,
[`--${pre}-stroke`]: obj.stroke
}
}
const clamp = (lower: number, upper: number) => (val: number): number => {
return val < lower ? lower :
val > upper ? upper :
val
}
const getDropLevel = (amount: number) => {
const m = Number(-(4/15).toFixed(3));
const level = clamp(-10,30)((amount * m) + 30);
return {
transform: `rotateZ(45deg) translateX(${level}px)`
}
}
const Overlay: React.FC<OverlayProps> = ({
children,
blur=true,
actions=[],
sideActions=[],
weatherData=[],
selectedDay=0,
onAction=()=>{},
onGoBack=()=>{},
}={}) => {
const rootCl = getClassName({
base: "overlay",
"&--transparent": !blur,
});
const actionsCl = rootCl.extend("&__actions");
const actionItemCl = actionsCl.extend("&__item");
const sideCl = rootCl.extend("&__sidebar");
const daysCl = getClassName({ base: "day-cards" })
const dayCardCl = daysCl.extend("&__card");
const dayCardRainCl = dayCardCl.extend("&__rain")
const dayCardDayCl = dayCardCl.extend("&__day")
const handleAction = (action: OverlayAction) => (e: React.MouseEvent) => {
onAction?.(action)
}
const handleWeatherAction = (data: DayData) => (e: React.MouseEvent) => {
onAction?.({ data, action: "weather", type: "weather" });
}
const selIndex = weatherData?.findIndex(({ day }) => day === selectedDay)
const computeDayCardClass = (idx: number, placeholder: boolean=false) => dayCardCl.recompute({
"&--selected": idx === selIndex,
"&--prev": idx === selIndex - 1,
"&--next": idx === selIndex + 1,
"&--placeholder": placeholder
})
return <>
{actions.length > 0 && <div className={actionsCl}>
{actions?.map((actionData,index) => {
const { label, idle, hover,transition } = actionData
const style = purge({
...cssVars("idle",idle ?? {}),
...cssVars("hover",hover ?? {}),
[`--transition`]: transition
})
return <button
className={actionItemCl}
style={style}
key={index}
onClick={handleAction({ type: "generic", ...actionData})}
>{label}</button>
})}
</div>}
{sideActions.length > 0 && <div className={sideCl}>
{sideActions?.map((actionData,index) => {
const { label, idle, hover,transition } = actionData
const style = purge({
...cssVars("idle",idle ?? {}),
...cssVars("hover",hover ?? {}),
[`--transition`]: transition
})
return <button
className={actionItemCl}
style={style}
key={index}
onClick={handleAction({ type: "generic" ,...actionData})}
>{label}</button>
})}
</div>}
{weatherData.length > 0 && <><div className={daysCl}>
<div className={computeDayCardClass(-1,true)}></div>
{weatherData.map(({ day, amount },key) => {
const cl = computeDayCardClass(key)
const icon = mapWeather(amount, {
Light: "png/light.png",
Medium: "png/medium.png",
Heavy: "png/heavy.png"
})
const alt = mapWeather(amount, {
Light: "light rain",
Medium: "medium rain",
Heavy: "heavy rain"
})
return <div
key={key}
className={cl}
onClick={handleWeatherAction({ day, amount })}
>
<div className={dayCardRainCl}>
<div className={dayCardRainCl.extend("&__text")}>{amount}</div>
<div
className={dayCardRainCl.extend("&__water")}
style={getDropLevel(amount)}
></div>
</div>
<div className={dayCardDayCl}>{day}</div>
<figure>
<img alt={alt} width="45px" src={icon}/>
</figure>
</div>
})}
<div className={computeDayCardClass(weatherData.length,true)}></div>
</div>
<div className="home">
<button className="home__button" onClick={handleAction({ type: "generic", action: "Home" })}>
<img alt="go home" src="png/home.png"/>
</button>
</div>
</>}
<div className={rootCl}>
{children}
</div>
</>
}
export default Overlay |
//
// ViewController.swift
// Maps
//
// Created by Andy Shi on 1/7/15.
// Copyright (c) 2015 Andy Shi. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var latitude: CLLocationDegrees = 41.878876
var longitude: CLLocationDegrees = -87.635915
var latDel: CLLocationDegrees = 0.01
var longDel: CLLocationDegrees = 0.01
var span: MKCoordinateSpan = MKCoordinateSpanMake(latDel, longDel)
var location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: true)
// preset annotation
var annotation = MKPointAnnotation ()
annotation.coordinate = location
annotation.title = "Chicago"
annotation.subtitle = "Willis Tower"
mapView.addAnnotation(annotation)
// user annotation
var longPress = UILongPressGestureRecognizer(target:self, action: "action:")
longPress.minimumPressDuration = 2.0
mapView.addGestureRecognizer(longPress)
}
func action(gestureRec:UIGestureRecognizer) {
// gather point
var touchPoint = gestureRec.locationInView(self.mapView)
// gather coordinate
var newCoordinate:CLLocationCoordinate2D = mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
var newAnnotation = MKPointAnnotation ()
newAnnotation.coordinate = newCoordinate
newAnnotation.title = "Chicago"
newAnnotation.subtitle = "Chi Town"
mapView.addAnnotation(newAnnotation)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>High-Level Animation</title>
<link rel="stylesheet" type="text/css" href="style.css">
<style>
.container {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.form {
background-color: white;
padding: 40px;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
animation: appear 0.5s ease-in-out;
}
@keyframes appear {
from {
opacity: 0;
transform: scale(0.9);
}
to {
opacity: 1;
transform: scale(1);
}
}
input[type="text"],
input[type="password"] {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border-radius: 5px;
border: none;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease-in-out;
}
input[type="text"]:focus,
input[type="password"]:focus {
outline: none;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.5);
}
button[type="submit"] {
width: 100%;
padding: 10px;
background-color: blue;
color: white;
border: none;
border-radius: 5px;
transition: all 0.3s ease-in-out;
cursor: pointer;
}
button[type="submit"]:hover {
background-color: deepskyblue;
}
</style>
</head>
<body><div class="container">
<form class="form">
<h2>Login</h2>
<input type="text" placeholder="Username">
<input type="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
</div>
<script>
// Add your validation logic here
const form = document.querySelector('.form');
form.addEventListener('submit', event => {
event.preventDefault();
console.log('Form submitted');
});
</script>
</body>
</html> |
import {
Component,
ElementRef,
OnDestroy,
OnInit,
ViewChild,
} from '@angular/core';
import { Store } from '@ngrx/store';
import * as Highcharts from 'highcharts';
import hcNoDataToDisplay from 'highcharts/modules/no-data-to-display';
import { Subject, takeUntil } from 'rxjs';
hcNoDataToDisplay(Highcharts);
import { DATE_RANGES_FILTER_DICTIONARY } from 'src/app/constants/date.constants';
import { BaseWidget } from 'src/app/core/components/base-widget/base-widget.component';
import { PartialDateTimeUnit } from 'src/app/types/date.types';
import { StudentsWidgetData } from '../joined-students-widget.types';
import { studentWidgetActions } from '../state/joined-students-widget.actions';
import {
selectWidgetData,
selectWidgetLoading,
selectWidgetTimeRange,
} from '../state/joined-students-widget.selectors';
@Component({
selector: 'app-joined-students-widget',
templateUrl: './joined-students-widget.component.html',
styleUrls: ['./joined-students-widget.component.scss'],
})
export class JoinedStudentsWidgetComponent extends BaseWidget implements OnInit, OnDestroy {
checkInitialized(): void {
this.store.dispatch(
studentWidgetActions.checkInitializedWidget({ id: this._id })
);
}
private destroy$ = new Subject<void>();
private actualChart!: Highcharts.Chart;
@ViewChild('chart', { read: ElementRef, static: true }) chartRef!: ElementRef;
selectedPeriod$: any;
periods = Object.entries(DATE_RANGES_FILTER_DICTIONARY);
Highcharts = Highcharts;
chartOptions: Highcharts.Options = {
lang: {
loading: 'Loading... Please wait.',
},
loading: {
style: {
backgroundColor: '#424242',
},
},
chart: {
type: 'column',
},
title: {
text: '',
},
xAxis: {
type: 'category',
},
yAxis: {
min: 0,
title: {
text: 'Students amount',
},
},
legend: {
enabled: false,
},
series: [
{
name: 'Students joined',
type: 'line',
data: [],
},
],
};
constructor(private store: Store) { super() }
ngOnInit(): void {
if (!this.chartRef) return;
this.actualChart = Highcharts.chart(
this.chartRef.nativeElement,
this.chartOptions
);
this.initChart();
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
initChart() {
this.selectedPeriod$ = this.store.select(selectWidgetTimeRange(this._id));
this.store.dispatch(studentWidgetActions.loadData({ id: this._id }));
this.initChartSubscriptions();
}
initChartSubscriptions() {
this.selectedPeriod$ = this.store.select(selectWidgetTimeRange(this._id));
this.store
.select(selectWidgetLoading(this._id))
.pipe(takeUntil(this.destroy$))
.subscribe((payload) => this.toggleOnChartLoading(payload));
this.store
.select(selectWidgetData(this._id))
.pipe(takeUntil(this.destroy$))
.subscribe((payload) => this.updateChartData(payload));
}
toggleOnChartLoading(loading: boolean) {
loading && this.actualChart
? this.actualChart.showLoading()
: this.actualChart.hideLoading();
this.actualChart.reflow();
}
updateChartData(data: StudentsWidgetData[]) {
this.actualChart.series[0].update({
name: 'Students joined',
type: 'bar',
data,
});
this.actualChart.reflow();
}
selectPeriod(range: PartialDateTimeUnit) {
this.store.dispatch(
studentWidgetActions.updateConfig({
config: { timeRange: range },
id: this._id,
})
);
}
} |
const express = require("express");
const dotenv = require("dotenv");
const connectDB = require("./config/db");
const path = require("path");
const cors = require("cors");
const { goalSchedule } = require("./jobs/goal.job");
const { notificationSchedule } = require("./jobs/notification.job");
dotenv.config({ path: "./config/config.env" });
connectDB();
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json({ extended: false }));
// CORS
app.use(cors());
// CRON JOBS
goalSchedule();
notificationSchedule();
// ROUTES
app.use("/api/users", require("./routes/user.route"));
app.use("/api/timelogs", require("./routes/timelog.route"));
app.use("/api/goals", require("./routes/goal.route"));
app.use("/api/stats", require("./routes/stats.route"));
app.get("/", (req, res) => {
console.log("Hello world");
return res.status(200).json({ message: "This is TimeOut! API" });
});
app.listen(PORT, () => console.log("This is listening on PORT: " + PORT)); |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Facebook</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600&display=swap');
*{
margin: 0;
padding: 0;
outline: 0;
text-decoration: none;
box-sizing: border-box;
}
html, body {
margin: 0; height: 100%; overflow: hidden
}
body{
font-family: 'Poppins', sans-serif;
font-size: 14px;
color: #1c1e21;
font-weight: normal;
background: #f8f8f8;
}
.loginsignup{
padding: 120px;
}
.container{
max-width: 992px;
margin: auto;
}
.row{
display: flex;
flex-wrap: wrap;
}
.justify-content-between{
justify-content: space-between;
}
.content-left{
max-width: 500px;
margin: auto;
}
.content-left h1{
font-size: 60px;
color: #1877f2;
margin-bottom: 20px;
font-weight: 600;
text-shadow: -3px -3px 4px rgb(255,255,255),
3px 3px 4px rgba(230, 230, 230, 0.96);;
}
.content-left h2{
font-family: SFProDisplay-Regular, Helvetica, Arial, sans-serif;
font-size: 28px;
font-weight: normal;
line-height: 32px;
width: 500px;
}
.content-right{
max-width: 450px;
margin: auto;
text-align: center;
}
.content-right form{
width: 396px;
height: 360px;
align-items: center;
background-color: #fff;
border: none;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, .1), 0 8px 16px rgba(0, 0, 0, .1);
box-sizing: border-box;
margin: 40px 0 0;
padding: 20px 0 28px;
}
.content-right form input{
width: 90%;
height: 52px;
background: #f8f8f8;
padding: 0 15px;
color: rgb(199, 198, 198);
font-size: 17px;
border: 1px solid #dddfe2;
border-radius: 6px;
margin-bottom: 15px;
font-size: 17px;
}
::placeholder
{
color: #9094b6;
}
.content-right form input:focus
{
border: 1px solid #1877f2;
box-shadow: 0 0px 2px #1877f2 ;
}
.btn{
width: 90%;
border-radius: 6px;
font-size: 17px;
line-height: 48px;
padding: 0 16px;
background: #1877f2;
color: #fff;
margin-bottom: 20px;
text-transform: capitalize;
font-weight: 500;
box-shadow: -5px -5px 10px rgb(255,255,255),
5px 5px 10px rgba(230, 230, 230, 0.96);
}
.login a{
display: block;
margin: auto;
}
.login .a:focus {
outline: none !important;
outline-color: currentcolor;
outline-style: none;
outline-width: medium;
}
.create-btn a{
display: inline-block;
padding: 0 17px;
background: #4cd137;
transition: .3s;
}
.create-btn a:hover{
background: #44bd32;
}
.login .btn:active
{
background: #f8f8f8;
color: #1877f2;
}
.forgot a{
font-size: 14px;
line-height: 19px;
color:#1877f2;
}
.forgot a:hover,
.content-right p a:hover{
text-decoration: underline;
}
.content-right p {
color: #1c1e21;
font-weight: 600;
margin-top: 20px;
}
.line
{
align-items: center;
border-bottom: 1px solid #dadde1;
display: flex;
margin: 20px 16px;
text-align: center;
}
.downpage{
width: auto;
height: 800px;
background-color: white;
padding: 50 0 50 0;
color: #1c1e21;
direction: ltr;
line-height: 1.34;
}
.dpage{
line-height: 1.6;
margin-left: -20px;
list-style-type: none;
margin: auto;
padding: 0;
font-family: inherit;
color: #737373;
width: 980px;
background-color: white;
}
.dpage li{
display: inline-block;
padding-left: 20px;
}
</style>
</head>
<body>
<!-- login Page start -->
<div>
<div class="loginsignup">
<div class="container">
<div class="row justify-content-between">
<div class="content-left">
<h1>facebook</h1>
<h2>Facebook pomaga kontaktowaฤ siฤ z <br> innymi osobami oraz udostฤpniaฤ im <br> rรณลผne informacje i materiaลy.</h2>
</div>
<div class="content-right">
<form action="">
<div class="form-group">
<input type="text" placeholder="Adres e-mail lub numer telefonu">
</div>
<div class="form-group">
<input type="password" placeholder="Hasลo">
</div>
<div class="login">
<a href="" class="btn">Zaloguj</a>
</div>
<div class="forgot">
<a href="">Nie pamiฤtasz hasลa?</a>
</div>
<div class="line"></div>
<div class="create-btn">
<a href="" class="btn">Utwรณrz nowe konto</a>
</div>
</form>
<p><a href=""> Utwรณrz stronฤ</a> dla gwiazdy, zespoลu lub firmy.</p>
</div>
</div>
</div>
</div>
</div>
<div class=downpage>
<div>
<div class="dpage">
<div>
<li>Polski</li>
<li>English (US)</li>
<li>ลlลnskล gลdka</li>
<li>ะ ัััะบะธะน</li>
<li>Deutsch</li>
<li>Franรงais (France)</li>
<li>ะฃะบัะฐัะฝััะบะฐ</li>
<li>Espaรฑol (Espaรฑa)</li>
</div>
<div>
<li>Zarejestruj siฤ</li>
<li>Zaloguj siฤ</li>
<li>Messenger</li>
<li>Facebook Lite</li>
<li>Watch</li>
<li>Osoby</li>
<li>Strony</li>
<li>Miejsca</li>
</div>
</div>
</div>
</div>
<!-- login Page end -->
</body>
</html> |
class navBar extends HTMLElement {
connectedCallback() {
this.render();
this.addEventListeners();
}
render() {
this.innerHTML = `
<nav class="bg-[#76885B] fixed w-full z-20 top-0 start-0">
<div class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-4">
<a href="/" class="flex items-center space-x-3 rtl:space-x-reverse">
<span class="self-center text-3xl font-semibold whitespace-nowrap text-white">Purelipuran</span>
</a>
<button id="menuButton" type="button" class="inline-flex items-center p-2 w-10 h-10 justify-center text-sm text-white rounded-lg md:hidden hover:bg-[#76885B] focus:outline-none focus:ring-2 focus:ring-gray-200" aria-controls="navbar-default" aria-expanded="false">
<span class="sr-only">Open main menu</span>
<svg class="w-6 h-6" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 17 14">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 1h15M1 7h15M1 13h15"/>
</svg>
</button>
<div class="hidden w-full md:block md:w-auto" id="navbar-default">
<ul class="flex flex-col p-4 md:p-0 mt-4 font-medium border border-gray-100 rounded-lg bg-[#76885B] md:space-x-8 rtl:space-x-reverse md:flex-row md:mt-0 md:border-0 md:bg-[#76885B]">
<li>
<a href="/home" class="block py-2 px-3 text-white font-bold md:p-0 hover:underline">Beranda</a>
</li>
<li>
<a href="/galery" class="block py-2 px-3 text-white font-bold md:p-0 hover:underline">Galeri</a>
</li>
<li>
<a href="/pemesanan" class="block py-2 px-3 text-white font-bold md:p-0 hover:underline">Pemesanan</a>
</li>
<li>
<a href="/about" class="block py-2 px-3 text-white font-bold md:p-0 hover:underline">Tentang Kami</a>
</li>
</ul>
</div>
</div>
</nav>
`;
}
addEventListeners() {
const menuButton = this.querySelector('#menuButton');
const navbarDefault = this.querySelector('#navbar-default');
menuButton.addEventListener('click', () => {
const isExpanded = menuButton.getAttribute('aria-expanded') === 'true';
menuButton.setAttribute('aria-expanded', !isExpanded);
navbarDefault.classList.toggle('hidden');
});
}
}
customElements.define('nav-bar', navBar); |
"use client";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
// Icons
import { MdAddPhotoAlternate } from "react-icons/md";
const Post = () => {
const router = useRouter();
const [description, setDescription] = useState("");
const [buttonState, setButton] = useState(true);
const [selectedPost, setPost] = useState("");
const [addedPosts, setAddedposts] = useState([]);
useEffect(() => {
if (description.trim() !== "" && selectedPost !== "") {
setButton(false);
}
}, [description, selectedPost]);
useEffect(() => {
const storedPostList = localStorage.getItem("postList");
if (storedPostList) {
setAddedposts(JSON.parse(storedPostList));
}
}, []);
const handlePost = (event) => {
setPost(event.target.files[0]);
};
const handleAddPost = () => {
if (addedPosts) {
setAddedposts((previous) => {
const newPostList = [{url: URL.createObjectURL(selectedPost), description: description}, ...previous];
localStorage.setItem("postList", JSON.stringify(newPostList));
return newPostList;
});
}
setPost("");
setDescription("");
setButton(true);
};
return (
<div className="w-[22rem] md:w-[30rem] lg:w-[35rem] h-[28rem] bg-white rounded-lg shadow-md p-4">
<div className="flex justify-center">
<h1 className="font-semibold text-2xl">Create Post</h1>
</div>
<hr className="my-4" />
<textarea
rows={2}
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
className="outline-none placeholder-gray-600 rounded-full px-5 w-full resize-none mb-4"
placeholder="What's on your mind, User?"
wrap="hard"
/>
{buttonState ? (
<div className="flex justify-center">
<label
htmlFor="fileInput"
className="flex justify-center items-center h-52 w-3/4 bg-gray-300 rounded-lg cursor-pointer hover:brightness-95 border-gray-500 border-2"
>
<div className="flex-col items-center">
<MdAddPhotoAlternate className="rounded-full bg-white text-4xl p-1 mx-auto" />
<p className="text-white">Add photo</p>
</div>
<input
id="fileInput"
type="file"
className="absolute opacity-0"
onChange={handlePost}
/>
</label>
</div>
) : (
<div className="w-80 h-52 flex mx-auto">
<img src={URL.createObjectURL(selectedPost)} width={400} height={450} />
</div>
)}
<button
onClick={handleAddPost}
className="w-full rounded-lg p-2 mt-7 cursor-pointer"
disabled={buttonState}
style={{ backgroundColor: buttonState ? "gray" : "rgb(24, 119, 242)" }}
>
Create Post
</button>
</div>
);
};
export default Post; |
// To parse this JSON data, do
//
// final extractImages = extractImagesFromJson(jsonString);
import 'dart:convert';
ExtractImages extractImagesFromJson(String str) =>
ExtractImages.fromJson(json.decode(str));
String extractImagesToJson(ExtractImages data) => json.encode(data.toJson());
class ExtractImages {
ExtractImages({
this.conversionCost,
this.files,
});
int? conversionCost;
List<FileElement>? files;
factory ExtractImages.fromJson(Map<String, dynamic> json) => ExtractImages(
conversionCost: json["ConversionCost"],
files: List<FileElement>.from(
json["Files"].map((x) => FileElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"ConversionCost": conversionCost,
"Files": List<dynamic>.from(files!.map((x) => x.toJson())),
};
}
class FileElement {
FileElement({
this.fileName,
this.fileExt,
this.fileSize,
this.fileData,
});
String? fileName;
String? fileExt;
int? fileSize;
String? fileData;
factory FileElement.fromJson(Map<String, dynamic> json) => FileElement(
fileName: json["FileName"],
fileExt: json["FileExt"],
fileSize: json["FileSize"],
fileData: json["FileData"],
);
Map<String, dynamic> toJson() => {
"FileName": fileName,
"FileExt": fileExt,
"FileSize": fileSize,
"FileData": fileData,
};
} |
import request from 'supertest'
import { FastifyAdapter } from '../../server/fastify-adapter'
import { TestingFSDatabase } from '@/infra/repositories/file-system/testing-fs-database'
import { ParentsRoutes } from './parents-routes.enum'
import { makeFastifyServerKit } from '@/tests/factories/make-fastify-server-kit'
import { makeParent } from '@/tests/factories/make-parent'
import { FSParentsRepository } from '@/infra/repositories/file-system/fs-parents.repository'
describe('Fetch Parents (e2e)', () => {
let fastify: FastifyAdapter
let testingFSDatabase: TestingFSDatabase
let parentsRepository: FSParentsRepository
beforeAll(async () => {
const fastifyServerKit = await makeFastifyServerKit()
fastify = fastifyServerKit.fastify
testingFSDatabase = fastifyServerKit.parentsTestingFSDatabase
parentsRepository = fastifyServerKit.parentsRepository
await fastify.listen()
})
afterAll(async () => {
await fastify.close()
await testingFSDatabase.excludeFile()
})
test('Deve criar um Parent', async () => {
await parentsRepository.save(makeParent())
await parentsRepository.save(makeParent())
await parentsRepository.save(makeParent())
const responseFetchParents = await request(fastify.server).get(
`${ParentsRoutes.FETCH}?page=1`,
)
expect(responseFetchParents.statusCode).toBe(200)
expect(responseFetchParents.body.parents).toHaveLength(3)
})
}) |
/* Chapter 8 Practice - Date and Time Functions */
/* Setting datetime Field Values*/
CREATE TABLE farmers_market.datetime_demo AS
(SELECT market_date, market_start_time, market_end_time,
STR_TO_DATE(CONCAT(market_date, ' ', market_start_time), '%Y-%m-%d %h:%i %p') AS market_start_datetime,
STR_TO_DATE(CONCAT(market_date, ' ', market_end_time), '%Y-%m-%d %h:%i %p') AS market_end_datetime
FROM farmers_market.market_date_info);
Select * from farmers_market.datetime_demo;
/* EXTRACT and DATE_PART 8*/
SELECT market_start_datetime,
EXTRACT(DAY FROM market_start_datetime) AS mktsrt_day,
EXTRACT(MONTH FROM market_start_datetime) AS mktsrt_month,
EXTRACT(YEAR FROM market_start_datetime) AS mktsrt_year,
EXTRACT(HOUR FROM market_start_datetime) AS mktsrt_hour,
EXTRACT(MINUTE FROM market_start_datetime) AS mktsrt_minute
FROM farmers_market.datetime_demo
WHERE market_start_datetime = '2019-03-02 08:00:00';
/* DATE_ADD and DATE_SUB */
SELECT market_start_datetime,
DATE_ADD(market_start_datetime, INTERVAL 30 MINUTE) AS mktstrt_date_plus_30min
FROM farmers_market.datetime_demo
WHERE market_start_datetime = '2019-03-02 08:00:00';
SELECT market_start_datetime,
DATE_ADD(market_start_datetime, INTERVAL 30 DAY) AS mktstrt_date_plus_30days
FROM farmers_market.datetime_demo
WHERE market_start_datetime = '2019-03-02 08:00:00';
/* DATEDIFF */
SELECT x.first_market, x.last_market,
DATEDIFF(x.last_market, x.first_market) days_first_to_last
FROM
(SELECT min(market_start_datetime) first_market,
max(market_start_datetime) last_market
FROM farmers_market.datetime_demo) x;
/* TIMESTAMPDIFF */
SELECT market_start_datetime, market_end_datetime,
TIMESTAMPDIFF(HOUR, market_start_datetime, market_end_datetime)
AS market_duration_hours,
TIMESTAMPDIFF(MINUTE, market_start_datetime, market_end_datetime)
AS market_duration_mins
FROM farmers_market.datetime_demo;
/* Date Functions in Aggregate Summaries and Window Functions */
SELECT customer_id,
MIN(market_date) AS first_purchase,
MAX(market_date) AS last_purchase,
COUNT(DISTINCT market_date) AS count_of_purchase_dates
FROM farmers_market.customer_purchases
WHERE customer_id = 1
GROUP BY customer_id;
SELECT customer_id, MIN(market_date) AS first_purchase, MAX(market_date) AS last_purchase,
COUNT(DISTINCT market_date) AS count_of_purchase_dates,
DATEDIFF(MAX(market_date), MIN(market_date)) AS days_between_first_last_purchase
FROM farmers_market.customer_purchases
GROUP BY customer_id;
SELECT customer_id, MIN(market_date) AS first_purchase, MAX(market_date) AS last_purchase,
COUNT(DISTINCT market_date) AS count_of_purchase_dates,
DATEDIFF(MAX(market_date), MIN(market_date)) AS days_between_first_last_purchase,
DATEDIFF(CURDATE(), MAX(market_date)) AS days_since_last_purchase
FROM farmers_market.customer_purchases
GROUP BY customer_id;
SELECT customer_id, market_date,
RANK() OVER (PARTITION BY customer_id ORDER BY market_date) AS purchase_number,
LEAD(market_date,1) OVER (PARTITION BY customer_id ORDER BY market_date) AS next_purchase
FROM farmers_market.customer_purchases
WHERE customer_id = 1;
SELECT x.customer_id, x.market_date,
RANK() OVER (PARTITION BY x.customer_id ORDER BY x.market_date) AS purchase_number,
(LEAD(x.market_date,1) OVER (PARTITION BY x.customer_id ORDER BY x.market_date)) AS next_purchase
FROM
(SELECT DISTINCT customer_id, market_date
FROM farmers_market.customer_purchases
WHERE customer_id = 1) x;
SELECT x.customer_id, x.market_date,
RANK() OVER (PARTITION BY x.customer_id ORDER BY x.market_date) AS purchase_number,
LEAD(x.market_date,1) OVER (PARTITION BY x.customer_id ORDER BY x.market_date) AS next_purchase,
DATEDIFF(LEAD(x.market_date,1) OVER (PARTITION BY x.customer_id ORDER BY x.market_date), x.market_date) AS days_between_purchases
FROM
(SELECT DISTINCT customer_id, market_date
FROM farmers_market.customer_purchases
WHERE customer_id = 1) x;
SELECT a.customer_id, a.market_date AS first_purchase, a.next_purchase AS second_purchase,
DATEDIFF(a.next_purchase, a.market_date) AS time_between_1st_2nd_purchase
FROM
(SELECT x.customer_id, x.market_date,
RANK() OVER (PARTITION BY x.customer_id ORDER BY x.market_date) AS purchase_number,
LEAD(x.market_date,1) OVER (PARTITION BY x.customer_id ORDER BY x.market_date) AS next_purchase
FROM
( SELECT DISTINCT customer_id, market_date
FROM farmers_market.customer_purchases) x) a WHERE a.purchase_number = 1; |
import React, { useEffect, useState } from 'react';
import CodeEditorWindow from './CodeEditorWindow';
import { languageOptions } from '../constants/languageOptions';
import useKeyPress from '../hooks/useKey';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import LanguagesDropdown from './LanguagesDropdown';
import ThemeDropdown from './ThemeDropdown';
import { defineTheme } from '../lib/defineTheme';
import axios from 'axios';
import OutputWindow from './OutputWindow';
import OutputDetails from './OutputDetails';
import CustomInput from './CustomInput';
import styled from '@emotion/styled';
const javascriptDefault = `// Write Your Code Here`;
const CompilerLanding = () => {
const [code, setCode] = useState(javascriptDefault);
const [customInput, setCustomInput] = useState('');
const [outputDetails, setOutputDetails] = useState(null);
const [processing, setProcessing] = useState(null);
const [theme, setTheme] = useState('amy');
const [language, setLanguage] = useState(languageOptions[0]);
const enterPress = useKeyPress('Enter');
const ctrlPress = useKeyPress('Control');
const onChange = (action, data) => {
switch (action) {
case 'code': {
setCode(data);
break;
}
default: {
console.warn('case not handled!', action, data);
}
}
};
const onSelectChange = (sl) => {
console.log('selected Option...', sl);
setLanguage(sl);
};
useEffect(() => {
if (enterPress && ctrlPress) {
handleCompile();
}
}, [ctrlPress, enterPress]);
function handleThemeChange(th) {
// console.log(th);
const theme = th;
if (['light', 'vs-dark'].includes(theme.value)) {
setTheme(theme);
} else {
console.log('theme...', theme);
defineTheme(theme.value).then(() => {
console.log(theme);
setTheme(theme);
});
}
}
useEffect(() => {
defineTheme('amy').then(() => setTheme({ value: 'amy', label: 'Amy' }));
}, []);
// Toast
const showSuccessToast = (msg) => {
toast.success(msg || `Compiled Successfully!`, {
position: 'top-right',
autoClose: 1000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: localStorage.getItem('theme').slice(0, -6),
});
};
const showErrorToast = (msg) => {
toast.error(msg || `Something went wrong! Please try again.`, {
position: 'top-right',
autoClose: 1000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: localStorage.getItem('theme').slice(0, -6),
});
};
const handleCompile = () => {
setProcessing(true);
const formData = {
language_id: language.id,
// encode source code in base64
source_code: btoa(code),
stdin: btoa(customInput),
};
// console.log(process.env.NEXT_PUBLIC_RAPID_API_URL);
const options = {
method: 'POST',
url: process.env.NEXT_PUBLIC_RAPID_API_URL,
params: { base64_encoded: 'true', fields: '*' },
headers: {
'content-type': 'application/json',
'Content-Type': 'application/json',
'X-RapidAPI-Host': process.env.NEXT_PUBLIC_RAPID_API_HOST,
'X-RapidAPI-Key': process.env.NEXT_PUBLIC_RAPID_API_KEY,
},
data: formData,
};
console.log(options);
axios
.request(options)
.then(function (response) {
console.log('res.data', response.data);
const token = response.data.token;
checkStatus(token);
})
.catch((err) => {
let error = err.response ? err.response.data : err;
setProcessing(false);
console.log(error);
});
};
const checkStatus = async (token) => {
const options = {
method: 'GET',
url: process.env.NEXT_PUBLIC_RAPID_API_URL + '/' + token,
params: { base64_encoded: 'true', fields: '*' },
headers: {
'X-RapidAPI-Host': process.env.NEXT_PUBLIC_RAPID_API_HOST,
'X-RapidAPI-Key': process.env.NEXT_PUBLIC_RAPID_API_KEY,
},
};
try {
let response = await axios.request(options);
let statusId = response.data.status?.id;
// Processed - we have a result
if (statusId === 1 || statusId === 2) {
// still processing
setTimeout(() => {
checkStatus(token);
}, 2000);
return;
} else {
setProcessing(false);
setOutputDetails(response.data);
showSuccessToast(`Compiled Successfully!`);
console.log('response.data', response.data);
return;
}
} catch (err) {
console.log('err', err);
setProcessing(false);
showErrorToast();
}
};
return (
<Container>
<div className="button">
<div className="dropdown">
<LanguagesDropdown onSelectChange={onSelectChange} />
<ThemeDropdown handleThemeChange={handleThemeChange} theme={theme} />
</div>
<button className="run" onClick={handleCompile} disabled={!code}>
{processing ? 'Processing...' : 'Compile and Execute'}
</button>
</div>
<div className="compiler">
<div className="code-here">
<CodeEditorWindow
code={code}
onChange={onChange}
language={language?.value}
theme={theme?.value}
/>
</div>
<div className="input-output">
<CustomInput
customInput={customInput}
setCustomInput={setCustomInput}
/>
<OutputWindow outputDetails={outputDetails} />
{outputDetails && <OutputDetails outputDetails={outputDetails} />}
</div>
</div>
<ToastContainer />
</Container>
);
};
const Container = styled.div`
width: 90%;
background: var(--box);
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
padding: 1rem;
display: flex;
flex-direction: column;
gap: 1rem;
.button {
width: 100%;
display: flex;
gap: 1.5rem;
.dropdown{
display: flex;
gap: 1rem;
@media (max-width: 575px)
{
display: flex;
flex-direction: column;
}
}
.run {
cursor: pointer;
background-color: #0bdf0b;
color: white;
border-radius: 4px;
padding: 2px;
width: 10rem;
font-weight: bold;
:hover{
background-color: #09d409;
}
}
}
.compiler {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
.code-here {
width: 65%;
z-index: 0;
}
.input-output {
width: 35%;
display: flex;
flex-direction: column;
gap: 1rem;
}
@media (max-width: 680px) {
.code-here{
width: 100%;
}
.input-output{
width: 100%;
}
display: flex;
flex-direction: column;
/* background-color: red; */
}
}
@media (max-width: 680px)
{
width: 100%;
.button{
display: flex;
flex-direction: column;
}
}
`;
export default CompilerLanding; |
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CreateAssetMenu(fileName = "Level Data", menuName = "BGG/Level Data", order = 6)]
public class LevelData : ScriptableObject
{
public LevelID id;
public new string name;
[TextArea]
public string description;
public LevelNumber number;
public DifficultyRating difficultyRating;
public int days;
public int spawnPoints;
public Sprite icon;
public SceneAsset levelScene;
public bool unlocked;
[BV.EnumList(typeof(SeasonID))]
public List<SeasonID> unlockedSeasons;
[Space]
public List<BuildingID> availableBuildings;
public List<ToolID> availableTrees;
public List<HumanID> availableHumans;
[Space]
public int enemySpawnLocations;
[BV.EnumList(typeof(DayID))]
public List<SpawnAmounts> spawnAmounts;
#region Editor
[Header("CSV File")]
public TextAsset csvFile;
public void LoadDataFromFile()
{
string[,] grid = CSVReader.GetCSVGrid("/Assets/_Balancing/" + csvFile.name + ".csv");
spawnAmounts.Clear();
spawnAmounts = new List<SpawnAmounts>();
List<string> keys = new List<string>();
//First create a list for holding our key values
for (int y = 0; y < grid.GetUpperBound(0); ++y)
{
keys.Add(grid[y, 0]);
}
//Loop through the rows, adding the value to the appropriate key
for (int x = 1; x < grid.GetUpperBound(1); x++)
{
Dictionary<string, string> columnData = new Dictionary<string, string>();
for (int k = 0; k < keys.Count; k++)
{
columnData.Add(keys[k], grid[k, x]);
//Debug.Log("Key: " + keys[k] + ", Value: " + grid[x, k]);
}
SpawnAmounts sa = new SpawnAmounts();
//Loop through the dictionary using the key values
foreach (KeyValuePair<string, string> item in columnData)
{
//Gets a unit data based off the ID and updates the spawn amounts data
if (item.Key.Contains(HumanID.Logger.ToString()))
sa.logger = int.TryParse(item.Value, out sa.logger) ? sa.logger : 0;
if (item.Key.Contains(HumanID.Lumberjack.ToString()))
sa.lumberjack = int.TryParse(item.Value, out sa.lumberjack) ? sa.lumberjack : 0;
if (item.Key.Contains(HumanID.LogCutter.ToString()))
sa.logcutter = int.TryParse(item.Value, out sa.logcutter) ? sa.logcutter : 0;
if (item.Key.Contains(HumanID.Wathe.ToString()))
sa.wathe = int.TryParse(item.Value, out sa.wathe) ? sa.wathe : 0;
if (item.Key.Contains(HumanID.Hunter.ToString()))
sa.hunter = int.TryParse(item.Value, out sa.hunter) ? sa.hunter : 0;
if (item.Key.Contains(HumanID.Bjornjeger.ToString()))
sa.bjornjeger = int.TryParse(item.Value, out sa.bjornjeger) ? sa.bjornjeger : 0;
if (item.Key.Contains(HumanID.Dreng.ToString()))
sa.dreng = int.TryParse(item.Value, out sa.dreng) ? sa.dreng : 0;
if (item.Key.Contains(HumanID.Bezerker.ToString()))
sa.bezerker = int.TryParse(item.Value, out sa.bezerker) ? sa.bezerker : 0;
if (item.Key.Contains(HumanID.Knight.ToString()))
sa.knight = int.TryParse(item.Value, out sa.knight) ? sa.knight : 0;
}
UpdateLevel(sa);
}
}
private void UpdateLevel(SpawnAmounts _spawnAmount)
{
spawnAmounts.Add(_spawnAmount);
//flag the object as "dirty" in the editor so it will be saved
EditorUtility.SetDirty(this);
// Prompt the editor database to save dirty assets, committing your changes to disk.
AssetDatabase.SaveAssets();
}
#if UNITY_EDITOR
[CustomEditor(typeof(LevelData))]
public class LevelDataEditor : Editor
{
public override void OnInspectorGUI()
{
LevelData gameData = (LevelData)target;
DrawDefaultInspector();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
GUI.backgroundColor = Color.green;
if (GUILayout.Button("Load Data from file?"))
{
if (EditorUtility.DisplayDialog("Load Spreadsheet Data", "Are you sure you want to load data? This will overwrite any existing data", "Yes", "No"))
{
gameData.LoadDataFromFile();
EditorUtility.SetDirty(gameData);
}
}
GUILayout.EndHorizontal();
}
}
#endif
#endregion
} |
import { useParams } from "react-router-dom";
import useSWR from "swr";
import { apiKey, fetcher } from "../config";
import { MovieDetails } from "../interface";
import MovieSimilar from "../components/movie/MovieSimilar";
import Footer from "../layout/Footer";
import MovieVideos from "../components/movie/MovieVideos";
// `https://api.themoviedb.org/3/movie/${movieID}?api_key=0f2828258a4259490e4802ec8bceef93`
const MovieDetailsPage: React.FC = () => {
const { movieID } = useParams();
const { data } = useSWR<MovieDetails>(
`https://api.themoviedb.org/3/movie/${movieID}?api_key=${apiKey}`,
fetcher
);
if (!data) return null;
const { backdrop_path, title, overview, genres } = data;
return (
<>
<div className="w-full h-[980px] relative">
<div className="absolute inset-0 bg-[#594444] bg-opacity-50"></div>
<div
className="w-full h-full object-cover bg-no-repeat"
style={{
backgroundImage: `url(http://image.tmdb.org/t/p/original/${backdrop_path})`,
}}
></div>
<div className="absolute w-[730px] bottom-[200px] left-[45px]">
<h2 className="font-bold text-2xl mb-5">{title}</h2>
<p className="text-[16px] mb-5">
<span>{overview}</span>
</p>
{genres.length > 0 && (
<div className="flex items-center justify-start gap-x-5">
{genres.map((item) => (
<span
className="border rounded-lg p-2 font-medium"
key={item.id}
>
{item.name}
</span>
))}
</div>
)}
</div>
<MovieVideos></MovieVideos>
<MovieSimilar></MovieSimilar>
<Footer></Footer>
</div>
</>
);
};
export default MovieDetailsPage; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.