text stringlengths 184 4.48M |
|---|
import React, { useState, useEffect } from "react";
import leftArrow from "../icons/arrow-left-solid.svg";
import rightArrow from "../icons/arrow-right-solid.svg";
import image1 from "./images/dog1.jpg";
import image2 from "./images/dog2.jpg";
import image3 from "./images/dog3.jpg";
import image4 from "./images/dog4.jpg";
import style from "../../../styles/perfect-pup/Slider.module.scss";
import Image from "next/image";
const Slider = () => {
const [slider, setSlider] = useState(0);
const dogs = [image1, image2, image3, image4];
const nextSlide = () => {
setSlider(slider === 3 ? 0 : slider + 1);
};
const previousSlide = () => {
setSlider(slider === 0 ? 3 : slider - 1);
};
useEffect(() => {
const intervalId = setInterval(nextSlide, 3000);
return () => clearInterval(intervalId);
}, [slider]);
return (
<section className={style.sliderBody}>
<section className={style.carousel}>
<button
data-testid={`left-slider-button`}
className={style.buttonLeft}
onClick={previousSlide}
>
<Image
className={style.sliderButton}
src={leftArrow}
alt="Left arrow button to move back an image"
/>
</button>
<Image
width="500"
height="500"
className={style.dogImage}
src={dogs[slider]}
alt="Pictures of Dogs"
></Image>
<button
data-testid={`right-slider-button`}
className={style.buttonRight}
onClick={nextSlide}
>
<Image
className={style.sliderButton}
src={rightArrow}
alt="Right arrow button to move back an image"
/>
</button>
</section>
</section>
);
};
export default Slider; |
import React from 'react'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import { Navbar, Sidebar, Footer } from './components'
import { Home, Products, SingleProduct, About, Cart, Error, Checkout, Private } from './pages'
function App() {
return (
<Router>
<Navbar/>
<Sidebar/>
<Routes>
<Route exact path="/" element={<Home/>}/>
<Route path="/about" element={<About/>}/>
<Route path="/cart" element={<Cart/>}/>
<Route path="/products" element={<Products/>}/>
<Route path="/checkout" element={<Checkout/>}/>
<Route path="/*" element={<Error/>}/>
<Route path="/singleproduct/:id" element={<SingleProduct/>}/>
</Routes>
<Footer/>
</Router>
)
}
export default App |
# InventoryPart
The `InventoryPart` adds basic inventory management capabilities to a product. Requires [`ProductPart`](product-part.md) to be present on the content type as well.
## Fields and properties
- **AllowsBackOrder** (`BooleanField`): When set to true, product can be ordered even when the Inventory field's value is below 1.
- **IgnoreInventory** (`BooleanField`): When set to true, all inventory checks (within [`InventoryShoppingCartEvents`](https://github.com/OrchardCMS/OrchardCore.Commerce/blob/main/src/Modules/OrchardCore.Commerce/Events/InventoryShoppingCartEvents.cs)) are bypassed.
- **Inventory** (`IDictionary<string, int>`): Sets the number of available products. Uses a `Dictionary<string, int>` object to keep track of multiple inventories (which is mostly relevant for products with a [`PriceVariantsPart`](price-variants-part.md) attached to them).
- **MaximumOrderQuantity** (`NumericField`): Determines the maximum amount of products that can be placed in an order. Also sets the upper limit for the _Quantity_ input on the product's page. This field is ignored if its value is set to 0 or below.
- **MinimumOrderQuantity** (`NumericField`): Determines the minimum amount of products that can be placed in an order. Also sets the lower limit for the _Quantity_ input on the product's page. This field is ignored if its value is set to 0 or below.
- **OutOfStockMessage** (`HtmlField`): Enables providing a specific message for an out of stock product. Defaults to "Out of Stock".
By default, the below fields' shapes are empty, so they do not show up on the user-facing part of the site:
- _AllowsBackOrder_
- _IgnoreInventory_
- _MaximumOrderQuantity_
- _MinimumOrderQuantity_
## Usage examples
All the inventory-related settings can be found in the product's editor.

With a product's inventory set to a valid value, the current inventory count will appear on the product's page.

With a maximum order quantity specified, trying to add more products to the cart than allowed will result in a validation error.

With a minimum order quantity specified, trying to add fewer products to the cart than allowed will result in a validation error.

With a custom out of stock message provided, the message will show up on the product's page when its inventory is below 1 and back ordering is not allowed.
 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script typea="text/javascript" src="../../js/vue.js"></script>
</head>
<body>
<div id="root">
<h1>插值语法</h1>
<h3>hello,{{name}}</h3>
<hr/>
<h1>指令语法</h1>
<a v-bind:href="url.toUpperCase()">点我去{{school.name}}1</a>
<a :href="url">点我去百度3</a>
</div>
</body>
<script>
Vue.config.productionTip = false
new Vue({
el:'#root',
data:{
name:'jack',
school:{
name:'百度'
},
url:"https://www.baidu.com"
}
})
</script>
</html> |
<?php
/*********************************************************************************
* By installing or using this file, you are confirming on behalf of the entity
* subscribed to the SugarCRM Inc. product ("Company") that Company is bound by
* the SugarCRM Inc. Master Subscription Agreement (“MSA”), which is viewable at:
* http://www.sugarcrm.com/master-subscription-agreement
*
* If Company is not bound by the MSA, then by installing or using this file
* you are agreeing unconditionally that Company will be bound by the MSA and
* certifying that you have authority to bind Company accordingly.
*
* Copyright (C) 2004-2013 SugarCRM Inc. All rights reserved.
********************************************************************************/
require_once("include/Expressions/Expression/Boolean/BooleanExpression.php");
/**
* <b>isValidDBName(String name)</b><br/>
* Returns true if <i>name</i> is legal as a column name in the database.
*/
class IsValidDBNameExpression extends BooleanExpression {
/**
* Returns itself when evaluating.
*/
function evaluate() {
$nameStr = $this->getParameters()->evaluate();
if( strlen($nameStr) == 0) return AbstractExpression::$TRUE;
if(! preg_match('/^[a-zA-Z][a-zA-Z\_0-9]+$/', $nameStr) )
return AbstractExpression::$FALSE;
return AbstractExpression::$TRUE;
}
/**
* Returns the JS Equivalent of the evaluate function.
*/
static function getJSEvaluate() {
return <<<EOQ
var str = this.getParameters().evaluate();
if(str.length== 0) {
return true;
}
// must start with a letter
if(!/^[a-zA-Z][a-zA-Z\_0-9]+$/.test(str))
return SUGAR.expressions.Expression.FALSE;
return SUGAR.expressions.Expression.TRUE;
EOQ;
}
/**
* Any generic type will suffice.
*/
static function getParameterTypes() {
return array("string");
}
/**
* Returns the maximum number of parameters needed.
*/
static function getParamCount() {
return 1;
}
/**
* Returns the opreation name that this Expression should be
* called by.
*/
static function getOperationName() {
return "isValidDBName";
}
/**
* Returns the String representation of this Expression.
*/
function toString() {
}
}
?> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
Cara Menghitung Determinan Matriks
</title>
<style>:root{--border-radius:5px;--box-shadow:2px 2px 10px;--color:#118bee;--color-accent:#118bee15;--color-bg:#fff;--color-bg-secondary:#e9e9e9;--color-secondary:#0645AD;--color-secondary-accent:#920de90b;--color-shadow:#f4f4f4;--color-text:#000;--color-text-secondary:#999;--font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;--hover-brightness:1.2;--justify-important:center;--justify-normal:left;--line-height:1.5;--width-card:285px;--width-card-medium:460px;--width-card-wide:800px;--width-content:1080px}article aside{background:var(--color-secondary-accent);border-left:4px solid var(--color-secondary);padding:.01rem .8rem}body{background:var(--color-bg);color:var(--color-text);font-family:var(--font-family);line-height:var(--line-height);margin:0;overflow-x:hidden;padding:1rem 0}footer,header,main{margin:0 auto;max-width:var(--width-content);padding:0rem 1rem}hr{background-color:var(--color-bg-secondary);border:none;height:1px;margin:4rem 0}section{display:flex;flex-wrap:wrap;justify-content:var(--justify-important)}section aside{border:1px solid var(--color-bg-secondary);border-radius:var(--border-radius);box-shadow:var(--box-shadow) var(--color-shadow);margin:1rem;padding:1.25rem;width:var(--width-card)}section aside:hover{box-shadow:var(--box-shadow) var(--color-bg-secondary)}section aside img{max-width:100%}[hidden]{display:none}article header,div header,main header{padding-top:0}header{text-align:var(--justify-important)}header a b,header a em,header a i,header a strong{margin-left:.5rem;margin-right:.5rem}header nav img{margin:1rem 0}section header{padding-top:0;width:100%}nav{align-items:center;display:flex;font-weight:700;justify-content:space-between;margin-bottom:7rem}nav ul{list-style:none;padding:0}nav ul li{display:inline-block;margin:0 .5rem;position:relative;text-align:left}nav ul li:hover ul{display:block}nav ul li ul{background:var(--color-bg);border:1px solid var(--color-bg-secondary);border-radius:var(--border-radius);box-shadow:var(--box-shadow) var(--color-shadow);display:none;height:auto;left:-2px;padding:.5rem 1rem;position:absolute;top:1.7rem;white-space:nowrap;width:auto}nav ul li ul li,nav ul li ul li a{display:block}code,samp{background-color:var(--color-accent);border-radius:var(--border-radius);color:var(--color-text);display:inline-block;margin:0 .1rem;padding:0 .5rem}details{margin:1.3rem 0}details summary{font-weight:700;cursor:pointer}h1,h2,h3,h4,h5,h6{line-height:var(--line-height)}mark{padding:.1rem}ol li,ul li{padding:.2rem 0}p{margin:.75rem 0;padding:0}pre{margin:1rem 0;max-width:var(--width-card-wide);padding:1rem 0}pre code,pre samp{display:block;max-width:var(--width-card-wide);padding:.5rem 2rem;white-space:pre-wrap}small{color:var(--color-text-secondary)}sup{background-color:var(--color-secondary);border-radius:var(--border-radius);color:var(--color-bg);font-size:xx-small;font-weight:700;margin:.2rem;padding:.2rem .3rem;position:relative;top:-2px}a{color:var(--color-secondary);display:inline-block;text-decoration:none}a:hover{filter:brightness(var(--hover-brightness));text-decoration:underline}a b,a em,a i,a strong,button{border-radius:var(--border-radius);display:inline-block;font-size:medium;font-weight:700;line-height:var(--line-height);margin:.5rem 0;padding:1rem 2rem}button{font-family:var(--font-family)}button:hover{cursor:pointer;filter:brightness(var(--hover-brightness))}a b,a strong,button{background-color:var(--color);border:2px solid var(--color);color:var(--color-bg)}a em,a i{border:2px solid var(--color);border-radius:var(--border-radius);color:var(--color);display:inline-block;padding:1rem}figure{margin:0;padding:0}figure img{max-width:100%}figure figcaption{color:var(--color-text-secondary)}button:disabled,input:disabled{background:var(--color-bg-secondary);border-color:var(--color-bg-secondary);color:var(--color-text-secondary);cursor:not-allowed}button[disabled]:hover{filter:none}form{border:1px solid var(--color-bg-secondary);border-radius:var(--border-radius);box-shadow:var(--box-shadow) var(--color-shadow);display:block;max-width:var(--width-card-wide);min-width:var(--width-card);padding:1.5rem;text-align:var(--justify-normal)}form header{margin:1.5rem 0;padding:1.5rem 0}input,label,select,textarea{display:block;font-size:inherit;max-width:var(--width-card-wide)}input[type=checkbox],input[type=radio]{display:inline-block}input[type=checkbox]+label,input[type=radio]+label{display:inline-block;font-weight:400;position:relative;top:1px}input,select,textarea{border:1px solid var(--color-bg-secondary);border-radius:var(--border-radius);margin-bottom:1rem;padding:.4rem .8rem}input[readonly],textarea[readonly]{background-color:var(--color-bg-secondary)}label{font-weight:700;margin-bottom:.2rem}table{border:1px solid var(--color-bg-secondary);border-radius:var(--border-radius);border-spacing:0;display:inline-block;max-width:100%;overflow-x:auto;padding:0;white-space:nowrap}table td,table th,table tr{padding:.4rem .8rem;text-align:var(--justify-important)}table thead{background-color:var(--color);border-collapse:collapse;border-radius:var(--border-radius);color:var(--color-bg);margin:0;padding:0}table thead th:first-child{border-top-left-radius:var(--border-radius)}table thead th:last-child{border-top-right-radius:var(--border-radius)}table thead th:first-child,table tr td:first-child{text-align:var(--justify-normal)}table tr:nth-child(even){background-color:var(--color-accent)}blockquote{display:block;font-size:x-large;line-height:var(--line-height);margin:1rem auto;max-width:var(--width-card-medium);padding:1.5rem 1rem;text-align:var(--justify-important)}blockquote footer{color:var(--color-text-secondary);display:block;font-size:small;line-height:var(--line-height);padding:1.5rem 0} article{padding: 1.25rem;}.v-cover{height: 480px; object-fit: cover;width: 100vw;cursor: pointer;}.v-image{height: 250px; object-fit: cover;width: 100vw;cursor: pointer;}.dwn-cover{max-height: 460px; object-fit: cover;}.w-100{width: 100vw}.search-box{color:#333;background-color:#f5f5f5;width:85%;height:50px;padding:0 20px;border:none;border-radius:20px;outline:0;border:1px solid #002cd92e}.search-box:active,.search-box:focus,.search-box:hover{border:1px solid #d9008e}.btn{display:inline-block;font-weight:400;color:#212529;text-align:center;vertical-align:middle;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:transparent;border:1px solid transparent;border-top-color:transparent;border-right-color:transparent;border-bottom-color:transparent;border-left-color:transparent;padding:.375rem .75rem;margin:0.5rem;font-size:1rem;line-height:1.5;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}.btn-danger{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-success{color:#fff;background-color:#28a745;border-color:#28a745}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}
</style>
<script type="application/ld+json">
{
"@context": "https://schema.org/",
"@type": "Article",
"author": {
"@type": "Person",
"name": "Guru"
},
"headline": "Cara Menghitung Determinan Matriks",
"datePublished": "2021-05-11",
"image": "https://i.ytimg.com/vi/nSYKEkL7_ig/maxresdefault.jpg",
"publisher": {
"@type": "Organization",
"name": "Pendidikan",
"logo": {
"@type": "ImageObject",
"url": "https://via.placeholder.com/512.png?text=cara+menghitung+determinan+matriks",
"width": 512,
"height": 512
}
}
}
</script>
<!-- Head tag Code -->
<script type='text/javascript' src='//jd3j7g5z1fqs.com/96/78/7a/96787a1945876b1a9c10f79941441964.js'></script></head>
<body>
<header>
<h1>
<a href="/">
Cara Menghitung Determinan Matriks
</a>
</h1>
<p>
Kumpulan Materi Pendidikan.
</p>
<center>
<input class='search-box' id="search-box" placeholder='Search and hit enter..' type='text' name="q" required autocomplete="off" id="search-query">
<div class="d-block p-4">
<center>
<!-- TOP BANNER ADS -->
</center>
</div> </center>
</header>
<main>
<article>
<p><strong>Cara Menghitung Determinan Matriks</strong>. Perhatikanlah soal latihan berikut ini. Jika A dan B merupakan matriks bujursangkar berukuran sama maka det A det B det AB 3.</p>
<figure>
<img class="v-cover ads-img" src="https://caraharian.com/wp-content/uploads/2020/05/Menentukan-kebalikan-dari-matriks-di-atas-A.jpg" alt="Contoh Soal Dan Rumus Matriks Invers 2x2 3x3 4x4 Lengkap" style="width: 100%; padding: 5px; background-color: grey;" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRFFKPhh9p21S_H0wvGXuFy7s-tdaYogytNk3VNCUJycyRW9mDuB-urZ40PFeg5ExIy9wE';">
<figcaption>Contoh Soal Dan Rumus Matriks Invers 2x2 3x3 4x4 Lengkap from caraharian.com</figcaption>
</figure>
<p>
Determinan untuk matriks 22. Berdasarkan rumus minor-kofaktor di atas determinan matriks A dapat dicari dengan menghitung jumlah seluruh hasil kali antara kofaktor matriks bagian dari matriks A dengan elemen-elemen pada salah satu baris atau kolom matriks A. Cara sarrus ini adalah cara yang paling mudah untuk mencari determinan matriks 3 3.
</p>
<h3>Hal ini sesuai secara teori dengan menggunakan metode Sarrus.</h3>
<p>Det 1 1 adj A A A det 1 1 det A A. Bagaimanakah cara menghitung determinan pada matriks. Determinan A Determinan A T. Semua unsur matriks yang berada di 2 kolom pertama kamu salin ke kolom paling belakang kolom 4 dengan tanpa mengubah urutan kolomnya ya.</p>
</article>
<section>
<aside>
<img class="v-image ads-img" alt="Contoh Soal Dan Rumus Matriks Invers 2x2 3x3 4x4 Lengkap" src="https://caraharian.com/wp-content/uploads/2020/05/Menentukan-kebalikan-dari-matriks-di-atas-A.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRFFKPhh9p21S_H0wvGXuFy7s-tdaYogytNk3VNCUJycyRW9mDuB-urZ40PFeg5ExIy9wE';" />
<small>Source: caraharian.com</small>
<p>Nah di bawah ini kita akan membahasnya satu per satu.</p>
</aside>
<aside>
<img class="v-image ads-img" alt="Menentukan Invers Suatu Matriks Ilmu Hitung" src="https://ilmuhitung.com/wp-content/uploads/2017/03/invers.png" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQh3PPBQ0PaEA4-_D6_9-ZYlxExzI-8bxScqjUuJpVq_yenqA0ONWcb4wyfG2pZjfm0V1U';" />
<small>Source: ilmuhitung.com</small>
<p>Beberapa sifat determinan matriks adalah.</p>
</aside>
<aside>
<img class="v-image ads-img" alt="Catatan Amir Cara Mencari Determinan Matriks Dengan Matlab" src="https://1.bp.blogspot.com/-pZ22G-g2u3s/XplevhTPmhI/AAAAAAAACSY/d5Rwh-7BHUIo4ebeVxneYIcqYosODHYLwCLcBGAsYHQ/s1600/determinanmatlab.JPG" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSw-AvMHRAki4WaDAJxoCgqgV9O7mVHvotbGEThcYdEq7NhZ-EMqRtbrShwPvpyL1vlpE4';" />
<small>Source: amirtjolleng.blogspot.com</small>
<p>Determinan adalah nilai yang didapatkan dari sebuah matriks dengan jumlah kolom dan baris yang sama atau matriks persegi.</p>
</aside>
<aside>
<img class="v-image ads-img" alt="Cara Menghitung Determinan Matriks Ordo 2x2 Youtube" src="https://i.ytimg.com/vi/KoAvA5kF7N0/maxresdefault.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQq5QgQVbdCf8HdPo-n2maK8ztb5YJv32iL35u-xZjfOaYKpc5VWlGnY69COX1tC5l6EYA';" />
<small>Source: www.youtube.com</small>
<p>Determinants and Matrices 2008 oleh Anthony Nicolaides suatu matriks A memiliki determinan yang dinotasikan sebagai berikut.</p>
</aside>
<aside>
<img class="v-image ads-img" alt="Matriks Cara Mencari Determinan Matriks 2x2 Dan 3x3 Youtube" src="https://i.ytimg.com/vi/68q1gDVV4q8/maxresdefault.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTy2dYF0O4FwPoYTMaJjN8I7GYgecIGAfQehbih4fsZBSYbsx8KlX0eUKoCazHdecqJefs';" />
<small>Source: www.youtube.com</small>
<p>Determinan matriks memiliki sifat-sifat berikut.</p>
</aside>
<aside>
<img class="v-image ads-img" alt="Determinan Matriks Invers Matriks Sifat Sifatnya Idschool" src="https://idschool.net/wp-content/uploads/2017/11/Determinan-Matriks-Ordo-3.png" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQE-02HV7m9Lm-Qh0-40f2V7hjplVta3jPQ5hhiWwPqUPs5A1tp7LmRrmlO38W_hTKNgNA';" />
<small>Source: idschool.net</small>
<p>Cara menentukan determinan matriks akan berbeda pada tiap ordo.</p>
</aside>
<aside>
<img class="v-image ads-img" alt="Tutorial Cara Mudah Menentukan Determinan Matriks Ordo 3 X 3 Youtube" src="https://i.ytimg.com/vi/nSYKEkL7_ig/maxresdefault.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ2tQJCRiiU4T0rYctjScpLa8e4JpSJsfN18GSjD6xnBtqfl3sLORQK7_yip_FqUGq5lTs';" />
<small>Source: www.youtube.com</small>
<p>Jika A adalah sembarang matriks bujur sangkar maka det A det At 2.</p>
</aside>
<aside>
<img class="v-image ads-img" alt="Cara Menentukan Determinan Matriks Sm4tik" src="https://1.bp.blogspot.com/-VRsSsO2a6Pg/XcpAtGo4O-I/AAAAAAAAArk/fqk113B9J-8dwFVW4j-XvgHkvUFuw94SQCLcBGAsYHQ/s1600/condet.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTE7AB_nQHc81QPs3QWSQ1nETnXrDTAVXwg_vLF_YUk_DwWn7KWbZZlcE-wMIfthRvTDNI';" />
<small>Source: sm4tik.blogspot.com</small>
<p>Tiga cara menghitung determinan matriks 44 yaitu.</p>
</aside>
<aside>
<img class="v-image ads-img" alt="Tutorial Cara Menentukan Invers Matriks Ordo 2 X 2 Youtube" src="https://i.ytimg.com/vi/2T091oZAm_k/maxresdefault.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTrceVHcU5BKg6875aY-nJv8atsJlwsOO4Y3NJ8vA6wxBP8RcmrcPGwWgWegNKlcbSVwQ4';" />
<small>Source: www.youtube.com</small>
<p>Dalam banyak pembahasan sering kita jumpai materi-materi matriks yang berisikan pembahasan determinan matriks ordo 2x2 dan matriks.</p>
</aside>
</section>
<section>
<article>
<p>
<a href="/ski-kelas-8-kurikulum-2013.html"><i>← ski kelas 8 kurikulum 2013</i></a>
<a href="/skhu-sd-2017.html"><i>skhu sd 2017 →</i></a>
</p>
</article>
</section>
<center>
<div class="d-block p-4">
<center>
</center>
</div> </center>
</main>
<footer style="padding-top: 50px;">
<center>
<a href="/p/dmca.html">Dmca</a>
<a href="/p/contact.html">Contact</a>
<a href="/p/privacy-policy.html">Privacy Policy</a>
<a href="/p/copyright.html">Copyright</a>
</center>
</footer>
<!-- Footer CSS JS --> <script type="text/javascript">
var search = document.getElementById("search-box");
search.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
var target = 'site:'+location.host+' '+search.value;
var uri= 'https://www.google.com/search?q='+encodeURIComponent(target);
window.location= uri;
}
});
</script>
</body>
</html> |
package PracticePrograms;
import PracticePrograms.Utility.PrintArray;
public class MergeSortFive {
public static void main ( String[] args) {
int[] array = {12,98,87,76,65,43,45,56,67,78};
PrintArray.printArray(array);
mergeSort( array,0,array.length-1);
PrintArray.printArray(array);
}
private static void mergeSort(int[] array, int l, int r) {
// TODO Auto-generated method stub
if(l < r)
{
int mid = (l+r)/2;
mergeSort(array,l,mid);
mergeSort(array,mid+1,r);
mergeArray(array,l,mid,r);
}
}
private static void mergeArray(int[] array, int l, int mid, int r) {
// TODO Auto-generated method stub
int n1 = mid-l+1;
int n2 = r-mid;
int L[] = new int[n1];
int R[] = new int[n2];
for ( int i=0; i<n1;++i)
L[i] = array[l+i];
for ( int j=0 ; j<n2;++j)
R[j] = array[mid+1+j];
int i =0,j=0;
int k = l;
while(i<n1 && j<n2)
{
if(L[i] <= R[j])
{
array[k] = L[i];
i++;
}
else
{
array[k]=R[j];
j++;
}
k++;
}
while (i<n1)
{
array[k] =L[i];
i++;
k++;
}
while ( j<n2)
{
array[k] = R[j];
j++;
k++;
}
}
} |
(ns isbn-verifier)
(defn- valid-format? [s]
(and
(= s (re-find #"[0-9]{9,10}X*" s))
(= 10 (count s))))
(defn- mod11 [n] (mod n 11))
(defn isbn? [isbn]
(let [char-value (fn [ch] (if (= \X ch) 10 (- (int ch) (int \0))))
checksum-chars (->> isbn (remove #(= \- %)) (apply str))]
(and
(valid-format? checksum-chars)
(->> checksum-chars
reverse
(map-indexed (fn [idx ch] (* (inc idx) (char-value ch))))
(apply +)
mod11
zero?)))) |
import 'package:flutter/material.dart';
import '../../../../core/constants.dart';
import '../../../../domain/models/booking.dart';
import '../../../widgets/table_row.dart';
class PriceDetails extends StatelessWidget {
final Booking booking;
final int sum;
const PriceDetails({
super.key,
required this.booking, required this.sum,
});
@override
Widget build(BuildContext context) {
return Column(
children: [
Table(
columnWidths: const <int, TableColumnWidth>{
0: FixedColumnWidth(140),
1: FlexColumnWidth(),
},
children: [
myRow(
title: "Тур",
value:
"${booking.tourPrice ~/ 1000} ${booking.tourPrice % 1000} ₽",
align: TextAlign.right),
myRow(
title: "Топливный сбор",
value:
"${booking.fuelCharge ~/ 1000} ${booking.fuelCharge % 1000} ₽",
align: TextAlign.right),
myRow(
title: "Сервисный сбор",
value:
"${booking.serviceCharge ~/ 1000} ${booking.serviceCharge % 1000} ₽",
align: TextAlign.right),
myRow(
title: "К оплате",
value:
"${sum ~/ 1000} ${sum % 1000} ₽",
padding: 0,
color: blue,
align: TextAlign.right),
],
),
],
);
}
} |
<template>
<div style="padding-bottom:100px;">
<spin v-if="loading"></spin>
<a-skeleton active :loading="loading" v-show="exactSearch.length > 0">
<a-row type="flex" justify="start" style="margin:16px 0">
<a-col
:span="4"
:offset="1"
v-for="(ar, idx) in exactSearch"
:key="idx"
style="margin-bottom:16px"
>
<div class="img-box">
<img
v-lazy="ar.picUrl + '?param=200y200'"
width="100%"
alt="img"
@click="goDjDetail(ar.id)"
/>
</div>
<p>{{ ar.name }}</p>
</a-col>
</a-row>
</a-skeleton>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import {
IPageJumpConfig,
ISearchDjProgram,
ResponseSearch,
ResponseSearchDjProgramResult,
SearchParams
} from '@/utils/types';
import { searchByKeywordAndType } from '@/api/search';
import Spin from '@/components/Spin/index.vue';
@Component({
components: { Spin }
})
export default class ProgramSearch extends Vue {
@Prop({ default: '' })
keywords: string | undefined;
exactSearch: ISearchDjProgram[] = [];
loading = false;
@Watch('keywords')
async watchKeywords(newVal: string, oldVal: string) {
if (newVal !== oldVal) {
await this.search({ keywords: newVal, type: 1009 });
}
}
private async mounted() {
if (this.keywords !== '') {
await this.search({ keywords: this.keywords!, type: 1009 });
}
}
async search(data: SearchParams) {
this.loading = true;
const res = await searchByKeywordAndType<
ResponseSearch<ResponseSearchDjProgramResult>
>(data);
this.exactSearch = res.data.result.djRadios;
this.loading = false;
}
goDjDetail(id: number) {
this.pageJump({
path: '/djDetail',
id
});
}
pageJump(config: IPageJumpConfig) {
const { id, path } = config;
this.$router.push({
path: path,
query: {
id: id!.toString()
}
});
}
}
</script>
<style scoped>
img {
cursor: pointer;
}
</style> |
import discord
from discord.ext import commands
import mysql.connector
# Connect to the MySQL database
db_connection = mysql.connector.connect(
host="localhost",
user="root",
password="root@1234",
database="discord_bot_db"
)
# Create a cursor object to interact with the database
db_cursor = db_connection.cursor()
intents = discord.Intents.default()
intents.messages = True # Enable the message event
# Set up the bot with intents
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def authenticate(ctx):
# Check if the server is already authenticated
db_cursor.execute("SELECT * FROM discord_tokens WHERE server_id = %s", (str(ctx.guild.id),))
result = db_cursor.fetchone()
if result:
await ctx.send("Bot is already authenticated for this server.")
else:
# Save the token for the current server in the database
db_cursor.execute("INSERT INTO discord_tokens (server_id, token) VALUES (%s, %s)",
(str(ctx.guild.id), "your_discord_bot_token_here"))
db_connection.commit()
await ctx.send("Bot authenticated successfully!")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith('!hello'):
# Replace YOUR_GUILD_ID with the actual ID of your Discord server
guild = bot.get_guild(1185134192682610760)
if guild:
await message.channel.send(f"Hello World {guild.name}")
else:
print("Guild not found.")
# Run the bot with your Discord bot token
bot.run('copy your token here') |
import { asc, count, desc, ilike } from 'drizzle-orm'
import { userTable } from '../../database/schema'
const inputFormat = z.object({
filter: z.string().optional(),
limit: z.number().min(1).max(100).default(10).optional(),
offset: z.number().min(0).default(0).optional(),
orderBy: z.enum(['username']).default('username').optional(),
orderByASC: z.boolean().default(true).optional(),
roles: z.boolean().default(false).optional(),
})
const outputFormat = z.object({
total: z.number(),
users: z.array(
z.object({
id: z.string(),
username: z.string(),
roles: z
.array(
z.object({
id: z.string(),
name: z.string(),
}),
)
.optional(),
}),
),
})
export type APIUserGetInput = zinfer<typeof inputFormat>
export type APIUserGetOutput = zinfer<typeof outputFormat>
export default defineEventHandler(async (event: H3Event) => {
const { db, isAdmin, validateInput, checkAuthorized } = context.get(event)
const input = await validateInput(inputFormat)
await checkAuthorized(isAdmin)
const whereUsername = input.filter ? ilike(userTable.username, `%${input.filter}%`) : undefined
const orderByColumn = userTable[input.orderBy || 'username']
const orderBy = input.orderByASC ? asc(orderByColumn) : desc(orderByColumn)
const totalUsersResult = await db
.select({ value: count(userTable.id) })
.from(userTable)
.where(whereUsername)
const totalUsers = totalUsersResult[0].value || 0
const users = await db.query.userTable.findMany({
limit: input.limit,
offset: input.offset,
where: whereUsername,
orderBy,
with: {
userRoles: {
with: {
role: input.roles || undefined,
},
},
},
})
const usersWithRoles = users.map((user) => ({
...user,
roles: user.userRoles.map((userRole) => userRole.role),
}))
return validate.output({ total: totalUsers, users: usersWithRoles }, outputFormat)
}) |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late final GoogleMapController _mapController;
late Location _location = Location();
LatLng? _currentLocation;
StreamSubscription? _streamSubLocation;
late Marker _marker;
final List<LatLng> _latLngList = [];
final Set<Polyline> _polyLines = {};
final Set<Marker> _markers = {};
bool isFollowing = true;
@override
void initState() {
super.initState();
listenToLocation();
}
void updateMarker() {
_marker = Marker(
markerId: const MarkerId('current_location'),
position: _currentLocation!,
infoWindow: InfoWindow(
title: 'My current location',
snippet:
'Lat: ${_currentLocation?.latitude}, Lng: ${_currentLocation?.longitude}',
),
onTap: () {
_mapController.showMarkerInfoWindow(const MarkerId('current_location'));
},
);
_markers.clear();
_markers.add(_marker);
}
void updatePolyline() {
_latLngList.add(_currentLocation!);
_polyLines.add(Polyline(
polylineId: const PolylineId('Basic-polyline'),
points: _latLngList,
color: Colors.blue,
width: 5,
));
}
void listenToLocation() {
_location.requestPermission();
_location.hasPermission().then((value) {
if (value == PermissionStatus.granted) {
_location.changeSettings(interval: 10000);
_streamSubLocation = _location.onLocationChanged.listen((LocationData locationData) {
if(mounted) {
setState(() {
try {
_currentLocation =
LatLng(locationData.latitude!, locationData.longitude!);
updateMarker();
updatePolyline();
if (isFollowing) {
_mapController.animateCamera(CameraUpdate.newLatLng(_currentLocation!));
}
} catch (e) {
print(e);
}
});
}
});
} else {}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Real-Time Location Tracker'),
),
body: _currentLocation == null
? Container()
: GoogleMap(
initialCameraPosition:
CameraPosition(zoom: 19, target: _currentLocation!),
compassEnabled: true,
onMapCreated: (GoogleMapController controller) {
_mapController = controller;
},
markers: _markers,
polylines: _polyLines,
myLocationEnabled: true,
myLocationButtonEnabled: true,
),
);
}
@override
void dispose() {
_streamSubLocation?.cancel();
super.dispose();
}
} |
# Курс Валюты Django-приложение
## Задание:
- Предлагаем вам создать "голый" джанго проект, который по переходу на страницу /get-current-usd/ бужет отображать в json формате актуальный курс доллара к рублю
(запрос по апи, найти самостоятельно) и показывать 10 последних запросов (паузу между запросами курсов должна быть не менее 10 секунд)
Это приложение Django предназначено для отслеживания и отображения текущего обменного курса рубля к доллару США. Оно использует
данные от Free Currency API, позволяя пользователям получать обновленную информацию о курсах валют.
## Особенности
- Интеграция Free Currency API: Приложение использует Free Currency API для получения актуальных данных о курсах валют в реальном времени.
- Регулирование Частоты Запросов: Чтобы соблюдать ограничения API и оптимизировать использование ресурсов, приложение включает механизм кэширования для задержки выполнения повторных запросов к API не чаще, чем раз в 10 секунд.
- Логирование: Для удобства отладки и мониторинга приложение включает подробное логирование всех запросов к API и операций сохранения данных.
## Как это работает
Приложение использует Django-кэш для хранения времени последнего успешного запроса к API.
Каждый запрос к endpoint /get-current-usd/ проверяет, прошло ли достаточно времени с последнего запроса. Если запросы сделаны слишком часто, приложение возвращает сообщение об ошибке, предотвращая чрезмерную нагрузку на API.
## Установка и Запуск
1. Клонируйте репозиторий:
```sh
git clone https://github.com/radiant2958/CurrencyRateDjangoApp.git
cd myproject
```
2. Установите виртуальное окружение и активируйте его:
```sh
python -m venv venv
source venv/bin/activate # Для Windows: venv\Scripts\activate
```
3. Установите зависимости:
```sh
pip install -r requirements.txt
```
4. Настройка переменных окружения:
Создайте файл .env в корневой директории проекта и добавьте туда ваш API ключ c https://freecurrencyapi.com
```sh
FREE_CURRENCY_API_KEY=ваш_секретный_ключ_api
```
5. Выполнение миграций:
```sh
python manage.py runserver
```
6. Запуск разработческого сервера:
```sh
python manage.py runserver
```
Откройте веб-браузер и перейдите по адресу http://127.0.0.1:8000/get-current-usd/, чтобы просмотреть текущий курс обмена и историю запросов. |
const expect = chai.expect;
import Vue from 'vue'
import Toast from '../src/toast'
Vue.config.productionTip = false
Vue.config.devtools = false
describe('Toast 组件', () => {
it('存在', () => {
expect(Toast).to.exist
})
describe('props 测试', function () {
it('接受 autoClose', (done) => {
const div = document.createElement('div')
document.body.appendChild(div)
const Constructor = Vue.extend(Toast)
const vm = new Constructor({
propsData: {
autoClose: 1,
}
}).$mount(div)
vm.$on('close', () => {
expect(document.body.contains(vm.$el)).to.eq(false)
done()
})
})
})
it('接受 closeButton', (done) => {
const callback = sinon.fake();
const Constructor = Vue.extend(Toast)
const vm = new Constructor({
propsData: {
closeButton: {
text: '关闭',
callback,
},
}
}).$mount()
let closeButton = vm.$el.querySelector('.close')
expect(closeButton.textContent.trim()).to.eq('关闭')
// 点击关闭太快,this.$nextTick 中 this.$refs.line 就拿不到
setTimeout(() => {
closeButton.click()
expect(callback).to.have.been.called
done()
})
})
it('接受 enableHtml', () => {
const Constructor = Vue.extend(Toast)
const vm = new Constructor({
propsData: {enableHtml: true}
})
vm.$slots.default = ['<strong id="test">hi</strong>']
vm.$mount()
// 可以通过选择器选到 test 那就是标签而不是文本
const strong = vm.$el.querySelector('#test')
expect(strong).to.exist
})
it('接受 position', () => {
const Constructor = Vue.extend(Toast)
const vm = new Constructor({
propsData: {
position: 'bottom'
}
}).$mount()
expect(vm.$el.classList.contains('position-bottom')).to.eq(true)
})
}) |
import * as a from 'fp-ts/lib/Array'
import * as o from 'fp-ts/lib/Option'
import * as e from 'fp-ts/lib/Either'
import { readSync, CASELESS_SORT } from 'readdir';
import { pipe } from 'fp-ts/lib/pipeable';
import { Mutation, MutationType } from '../../core/definitions/mutation.definition';
import { Analyzer as analyze } from '../../services/achievements/analyzer.service';
import { TAchievement } from '../../core/definitions/achievement.definition';
import * as fs from 'fs';
const VERSION_ERRORS = {
ERROR_GETTING_NEW_VERSION_NUMBER: (err: any, path: string) => `There was an error getting a new versio number for ${path}. Error: \n${err.toString()}`,
ERROR_COMMITTING_MUTATIONS_TO_NEW_VERSION: (err: any) => `There was an error committing the mutations from a changeset to a new version. Error: \n${err.toString()}`
}
export class Version {
static newVersionNumber = (versionDirPath: string) =>
e.tryCatch(() => pipe(
readSync(versionDirPath, ['*.json'], [CASELESS_SORT]),
a.reverse,
a.findFirst(_ => true),
v => o.getOrElse(() => '1.json')(v),
v => Number(v.split('.').slice(0, -1).join('.')),
v => v === NaN ? 1 : v + 1
), err => e.toError(
VERSION_ERRORS.ERROR_GETTING_NEW_VERSION_NUMBER(err, versionDirPath)
))
static create = (mutations: Mutation[], newVersionNumber: number, versionDirPath: string) => {
const newVersionFilePath = `${versionDirPath}${(newVersionNumber)}.json`;
return pipe(
analyze.validateList(`${versionDirPath}${(newVersionNumber - 1)}.json`),
e.chain(a => Version._commitMutations(a, mutations)),
e.chain(a => e.tryCatch(() => {
fs.writeFileSync(newVersionFilePath, JSON.stringify(a), 'utf8')
return newVersionFilePath;
}, err => e.toError(
VERSION_ERRORS.ERROR_GETTING_NEW_VERSION_NUMBER(err, versionDirPath)
)))
)
}
private static _commitMutations = (achievements: TAchievement[], mutations: Mutation[]) => e.tryCatch(() =>
mutations.reduce((acc, m) => {
const ai = acc.findIndex(a => a.name === m.name);
if (ai > -1) {
switch (m.column) {
case MutationType.newCategory:
acc[ai] = {
...acc[ai],
category: m.newValue?.toString() ?? ''
}
break;
case MutationType.newName:
acc[ai] = {
...acc[ai],
name: m.newValue?.toString() ?? ''
}
break;
case MutationType.newPoints:
acc[ai] = {
...acc[ai],
points: Number(m.newValue) ?? 0
}
break;
case MutationType.IS_DUPLICATE:
acc.splice(ai, 1);
break;
}
}
return acc
}, achievements), err => e.toError(
VERSION_ERRORS.ERROR_COMMITTING_MUTATIONS_TO_NEW_VERSION(err)
))
} |
<template>
<div ref="el" class="relative !h-full w-full overflow-hidden" />
</template>
<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, ref, unref, watch, watchEffect } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { useAppStore } from 'fe-ent-core/es/store';
import { useWindowSizeFn } from 'fe-ent-core/es/hooks';
import { MODE } from '../typing';
import { CodeMirror } from './codemirror';
import type { PropType } from 'vue';
import type { Nullable } from 'fe-ent-core/es/types';
const props = defineProps({
mode: {
type: String as PropType<MODE>,
default: MODE.JSON,
validator(value: any) {
// 这个值必须匹配下列字符串中的一个
return Object.values(MODE).includes(value);
},
},
value: { type: String, default: '' },
readonly: { type: Boolean, default: false },
});
const emit = defineEmits(['change']);
const el = ref();
let editor: Nullable<CodeMirror.Editor>;
const debounceRefresh = useDebounceFn(refresh, 100);
const appStore = useAppStore();
watch(
() => props.value,
async (value) => {
await nextTick();
const oldValue = editor?.getValue();
if (value !== oldValue) {
editor?.setValue(value ? value : '');
}
},
{ flush: 'post' },
);
watchEffect(() => {
editor?.setOption('mode', props.mode);
});
watch(
() => appStore.getThemeSetting.theme,
async () => {
setTheme();
},
{
immediate: true,
},
);
function setTheme() {
unref(editor)?.setOption(
'theme',
appStore.getThemeSetting.theme === 'light' ? 'idea' : 'material-palenight',
);
}
function refresh() {
editor?.refresh();
}
async function init() {
const addonOptions = {
autoCloseBrackets: true,
autoCloseTags: true,
foldGutter: true,
gutters: ['CodeMirror-linenumbers'],
};
editor = CodeMirror(el.value!, {
value: '',
mode: props.mode,
readOnly: props.readonly,
tabSize: 2,
theme: 'material-palenight',
lineWrapping: true,
lineNumbers: true,
...addonOptions,
});
editor?.setValue(props.value);
setTheme();
editor?.on('change', () => {
emit('change', editor?.getValue());
});
}
onMounted(async () => {
await nextTick();
init();
useWindowSizeFn(debounceRefresh);
});
onUnmounted(() => {
editor = null;
});
</script> |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Maybe.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: htsang <htsang@student.42heilbronn.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/17 20:45:13 by htsang #+# #+# */
/* Updated: 2023/11/18 19:34:54 by htsang ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIBCPP_MAYBE_HPP
# define LIBCPP_MAYBE_HPP
# include "Nothing.hpp"
namespace libcpp
{
template <typename T>
class Maybe
{
public:
Maybe();
Maybe(const Nothing value);
Maybe(const T& value);
Maybe(const Maybe& other);
~Maybe();
Maybe& operator=(const Maybe& other);
bool is_ok() const;
T value() const;
template <typename T2>
Maybe<T2> chain(Maybe<T2> (*f)()) const;
template <typename T2>
Maybe<T2> chain(Maybe<T2> (*f)(T)) const;
template <typename T2, typename Env>
Maybe<T2> chain(Maybe<T2> (*f)(Env), Env data) const;
template <typename T2, typename Env>
Maybe<T2> chain(Maybe<T2> (*f)(Env&), Env& data) const;
template <typename T2, typename Env>
Maybe<T2> chain(Maybe<T2> (*f)(T, Env), Env data) const;
template <typename T2, typename Env>
Maybe<T2> chain(Maybe<T2> (*f)(T, Env&), Env& data) const;
template <typename T2, typename Class>
Maybe<T2> chain(Maybe<T2> (Class::*f)(), Class& obj) const;
template <typename T2, typename Class>
Maybe<T2> chain(Maybe<T2> (Class::*f)(T), Class& obj) const;
template <typename T2, typename Class, typename Env>
Maybe<T2> chain(Maybe<T2> (Class::*f)(Env), Class& obj, Env data) const;
template <typename T2, typename Class, typename Env>
Maybe<T2> chain(Maybe<T2> (Class::*f)(Env&), Class& obj, Env& data) const;
template <typename T2, typename Class, typename Env>
Maybe<T2> chain(Maybe<T2> (Class::*f)(T, Env), Class& obj, Env data) const;
template <typename T2, typename Class, typename Env>
Maybe<T2> chain(Maybe<T2> (Class::*f)(T, Env&), Class& obj, Env& data) const;
private:
T value_;
bool is_ok_;
};
template <typename T>
Maybe<T>::Maybe()
: value_(), is_ok_(false) {}
template <typename T>
Maybe<T>::Maybe(const Nothing value)
: value_(), is_ok_(false) {}
template <typename T>
Maybe<T>::Maybe(const T& value)
: value_(value), is_ok_(true) {}
template <typename T>
Maybe<T>::Maybe(const Maybe& other)
: value_(other.value_), is_ok_(other.is_ok_) {}
template <typename T>
Maybe<T>::~Maybe() {}
template <typename T>
Maybe<T>& Maybe<T>::operator=(const Maybe& other)
{
if (this != &other)
{
this->value_ = other.value_;
this->is_ok_ = other.is_ok_;
}
return *this;
}
template <typename T>
bool Maybe<T>::is_ok() const
{
return this->is_ok_;
}
template <typename T>
T Maybe<T>::value() const
{
return this->value_;
}
template <typename T>
template <typename T2>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (*f)()) const
{
if (this->is_ok())
return f();
return Nothing();
}
template <typename T>
template <typename T2>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (*f)(T)) const
{
if (this->is_ok())
return f(this->value_);
return Nothing();
}
template <typename T>
template <typename T2, typename Env>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (*f)(Env), Env data) const
{
if (this->is_ok())
return f(data);
return Nothing();
}
template <typename T>
template <typename T2, typename Env>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (*f)(Env&), Env& data) const
{
if (this->is_ok())
return f(data);
return Nothing();
}
template <typename T>
template <typename T2, typename Env>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (*f)(T, Env), Env data) const
{
if (this->is_ok())
return f(this->value_, data);
return Nothing();
}
template <typename T>
template <typename T2, typename Env>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (*f)(T, Env&), Env& data) const
{
if (this->is_ok())
return f(tthis->value_, data);
return Nothing();
}
template <typename T>
template <typename T2, typename Class>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (Class::*f)(), Class& obj) const
{
if (this->is_ok())
return (obj.*f)();
return Nothing();
}
template <typename T>
template <typename T2, typename Class>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (Class::*f)(T), Class& obj) const
{
if (this->is_ok())
return (obj.*f)(this->value_);
return Nothing();
}
template <typename T>
template <typename T2, typename Class, typename Env>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (Class::*f)(Env), Class& obj, Env data) const
{
if (this->is_ok())
return (obj.*f)(data);
return Nothing();
}
template <typename T>
template <typename T2, typename Class, typename Env>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (Class::*f)(Env&), Class& obj, Env& data) const
{
if (this->is_ok())
return (obj.*f)(data);
return Nothing();
}
template <typename T>
template <typename T2, typename Class, typename Env>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (Class::*f)(T, Env), Class& obj, Env data) const
{
if (this->is_ok())
return (obj.*f)(this->value_, data);
return Nothing();
}
template <typename T>
template <typename T2, typename Class, typename Env>
Maybe<T2> Maybe<T>::chain(Maybe<T2> (Class::*f)(T, Env&), Class& obj, Env& data) const
{
if (this->is_ok())
return (obj.*f)(this->value_, data);
return Nothing();
}
} // namespace libcpp
#endif |
import { expect } from 'chai';
import { BigNumber, Contract, ContractFactory, Transaction } from 'ethers';
import { ethers } from 'hardhat';
import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';
import { beforeEach } from 'mocha';
const { constants, provider, utils } = ethers;
const { AddressZero, MaxUint256, Zero } = constants;
const { parseEther: toWei } = utils;
import { permitSignature } from './utils/permitSignature';
import { getEvents as getEventsUtil } from './utils/getEvents';
import { increaseTime as increaseTimeUtil } from './utils/increaseTime';
const getEvents = (tx: Transaction, contract: Contract) => getEventsUtil(provider, tx, contract);
const increaseTime = (time: number) => increaseTimeUtil(provider, time);
const MAX_EXPIRY = 15552000; // 180 days
const getTimestamp = async () => (await provider.getBlock('latest')).timestamp;
const getMaxExpiryTimestamp = async () =>
(await provider.getBlock('latest')).timestamp + MAX_EXPIRY;
describe('Test Set Name', () => {
let owner: SignerWithAddress;
let representative: SignerWithAddress;
let controller: SignerWithAddress;
let firstDelegatee: SignerWithAddress;
let secondDelegatee: SignerWithAddress;
let stranger: SignerWithAddress;
let ticket: Contract;
let twabDelegator: Contract;
let constructorTest = false;
const getDelegationAddress = async (transaction: any) => {
const ticketEvents = await getEvents(transaction, twabDelegator);
const delegationCreatedEvent = ticketEvents.find(
(event) => event && event.name === 'DelegationCreated',
);
return delegationCreatedEvent?.args['delegation'];
};
const deployTwabDelegator = async (ticketAddress = ticket.address) => {
const twabDelegatorContractFactory: ContractFactory = await ethers.getContractFactory(
'TWABDelegatorHarness',
);
return await twabDelegatorContractFactory.deploy(
'PoolTogether Staked aUSDC Ticket',
'stkPTaUSDC',
ticketAddress,
);
};
beforeEach(async () => {
[owner, representative, controller, firstDelegatee, secondDelegatee, stranger] =
await ethers.getSigners();
const ticketContractFactory: ContractFactory = await ethers.getContractFactory('TicketHarness');
ticket = await ticketContractFactory.deploy(
'PoolTogether aUSDC Ticket',
'PTaUSDC',
6,
controller.address,
);
if (!constructorTest) {
twabDelegator = await deployTwabDelegator();
}
});
describe('constructor()', () => {
beforeEach(() => {
constructorTest = true;
});
afterEach(() => {
constructorTest = false;
});
it('should deploy and set ticket', async () => {
const twabDelegator = await deployTwabDelegator();
await expect(twabDelegator.deployTransaction)
.to.emit(twabDelegator, 'TicketSet')
.withArgs(ticket.address);
});
it('should fail to deploy if ticket address is address zero', async () => {
await expect(deployTwabDelegator(AddressZero)).to.be.revertedWith(
'TWABDelegator/tick-not-zero-addr',
);
});
});
describe('stake()', () => {
let amount: BigNumber;
beforeEach(async () => {
amount = toWei('1000');
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
});
it('should allow a ticket holder to stake tickets', async () => {
await expect(twabDelegator.stake(owner.address, amount))
.to.emit(twabDelegator, 'TicketsStaked')
.withArgs(owner.address, amount);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(amount);
expect(await ticket.balanceOf(owner.address)).to.eq(Zero);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(amount);
});
it('should allow a ticket holder to stake tickets on behalf of another user', async () => {
await expect(twabDelegator.stake(stranger.address, amount))
.to.emit(twabDelegator, 'TicketsStaked')
.withArgs(stranger.address, amount);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(amount);
expect(await ticket.balanceOf(owner.address)).to.eq(Zero);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await twabDelegator.balanceOf(stranger.address)).to.eq(amount);
});
it('should fail to stake tickets if recipient is address zero', async () => {
await expect(twabDelegator.stake(AddressZero, amount)).to.be.revertedWith(
'ERC20: mint to the zero address',
);
});
it('should fail to stake tickets if amount is not greater than zero', async () => {
await expect(twabDelegator.stake(owner.address, Zero)).to.be.revertedWith(
'TWABDelegator/amount-gt-zero',
);
});
});
describe('unstake()', () => {
let amount: BigNumber;
beforeEach(async () => {
amount = toWei('1000');
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
});
it('should allow a delegator to unstake tickets', async () => {
await twabDelegator.stake(owner.address, amount);
await expect(twabDelegator.unstake(owner.address, amount))
.to.emit(twabDelegator, 'TicketsUnstaked')
.withArgs(owner.address, owner.address, amount);
expect(await twabDelegator.callStatic.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(owner.address)).to.eq(amount);
});
it('should allow a delegator to unstake tickets and transfer them to another user', async () => {
await twabDelegator.stake(owner.address, amount);
await expect(twabDelegator.unstake(stranger.address, amount))
.to.emit(twabDelegator, 'TicketsUnstaked')
.withArgs(owner.address, stranger.address, amount);
expect(await twabDelegator.callStatic.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(stranger.address)).to.eq(amount);
});
it('should fail to unstake if caller has no stake', async () => {
await expect(twabDelegator.unstake(owner.address, amount)).to.be.revertedWith(
'ERC20: burn amount exceeds balance',
);
});
it('should fail to unstake if recipient is address zero', async () => {
await twabDelegator.stake(owner.address, amount);
await expect(twabDelegator.unstake(AddressZero, amount)).to.be.revertedWith(
'TWABDelegator/to-not-zero-addr',
);
});
it('should fail to unstake if amount is zero', async () => {
await twabDelegator.stake(owner.address, amount);
await expect(twabDelegator.unstake(owner.address, Zero)).to.be.revertedWith(
'TWABDelegator/amount-gt-zero',
);
});
it('should fail to unstake if amount is greater than staked amount', async () => {
await twabDelegator.stake(owner.address, amount);
await expect(twabDelegator.unstake(owner.address, toWei('1500'))).to.be.revertedWith(
'ERC20: burn amount exceeds balance',
);
});
});
describe('createDelegation()', () => {
const amount = toWei('1000');
beforeEach(async () => {
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
});
it('should allow anyone to create a delegation', async () => {
const transaction = await twabDelegator.createDelegation(
owner.address,
0,
firstDelegatee.address,
MAX_EXPIRY,
);
const delegationAddress = await getDelegationAddress(transaction);
const expiryTimestamp = await getMaxExpiryTimestamp();
await expect(transaction)
.to.emit(twabDelegator, 'DelegationCreated')
.withArgs(
owner.address,
0,
expiryTimestamp,
firstDelegatee.address,
delegationAddress,
owner.address,
);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(owner.address)).to.eq(amount);
const accountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(accountDetails.balance).to.eq(Zero);
const delegation = await ethers.getContractAt('Delegation', delegationAddress);
expect(await delegation.lockUntil()).to.eq(expiryTimestamp);
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should fail to create a delegation if slot passed is already used', async () => {
await twabDelegator.createDelegation(owner.address, 0, firstDelegatee.address, MAX_EXPIRY);
await expect(
twabDelegator.createDelegation(owner.address, 0, secondDelegatee.address, MAX_EXPIRY),
).to.be.revertedWith('ERC1167: create2 failed');
});
it('should fail to create delegation if delegator is address zero', async () => {
await expect(
twabDelegator.createDelegation(AddressZero, 0, firstDelegatee.address, MAX_EXPIRY),
).to.be.revertedWith('TWABDelegator/not-dlgtr-or-rep');
});
it('should fail to create delegation if delegatee is address zero', async () => {
await expect(
twabDelegator.createDelegation(owner.address, 0, AddressZero, MAX_EXPIRY),
).to.be.revertedWith('TWABDelegator/dlgt-not-zero-addr');
});
it('should fail to create delegation if expiry is greater than 180 days', async () => {
await expect(
twabDelegator.createDelegation(owner.address, 0, firstDelegatee.address, MAX_EXPIRY + 1),
).to.be.revertedWith('TWABDelegator/lock-too-long');
});
});
describe('updateDelegatee()', () => {
const amount = toWei('1000');
let delegationAddress = '';
beforeEach(async () => {
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
await twabDelegator.stake(owner.address, amount);
const transaction = await twabDelegator.createDelegation(
owner.address,
0,
firstDelegatee.address,
MAX_EXPIRY,
);
delegationAddress = await getDelegationAddress(transaction);
await twabDelegator.fundDelegationFromStake(owner.address, 0, amount);
});
it('should allow a delegator to transfer a delegation to another delegatee', async () => {
await increaseTime(MAX_EXPIRY + 1);
expect(await twabDelegator.updateDelegatee(owner.address, 0, secondDelegatee.address, 0))
.to.emit(twabDelegator, 'DelegateeUpdated')
.withArgs(owner.address, 0, secondDelegatee.address, await getTimestamp(), owner.address);
const firstDelegateeAccountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(firstDelegateeAccountDetails.balance).to.eq(Zero);
const secondDelegateeAccountDetails = await ticket.getAccountDetails(secondDelegatee.address);
expect(secondDelegateeAccountDetails.balance).to.eq(amount);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(amount);
expect(await ticket.delegateOf(delegationAddress)).to.eq(secondDelegatee.address);
});
it('should allow a representative to transfer a delegation to another delegatee', async () => {
await increaseTime(MAX_EXPIRY + 1);
await twabDelegator.setRepresentative(representative.address, true);
expect(
await twabDelegator
.connect(representative)
.updateDelegatee(owner.address, 0, secondDelegatee.address, 0),
)
.to.emit(twabDelegator, 'DelegateeUpdated')
.withArgs(
owner.address,
0,
secondDelegatee.address,
await getTimestamp(),
representative.address,
);
const firstDelegateeAccountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(firstDelegateeAccountDetails.balance).to.eq(Zero);
const secondDelegateeAccountDetails = await ticket.getAccountDetails(secondDelegatee.address);
expect(secondDelegateeAccountDetails.balance).to.eq(amount);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(amount);
expect(await ticket.delegateOf(delegationAddress)).to.eq(secondDelegatee.address);
});
it('should allow a delegator to update the lock duration', async () => {
await increaseTime(MAX_EXPIRY + 1);
expect(
await twabDelegator.updateDelegatee(owner.address, 0, secondDelegatee.address, MAX_EXPIRY),
)
.to.emit(twabDelegator, 'DelegateeUpdated')
.withArgs(
owner.address,
0,
secondDelegatee.address,
await getMaxExpiryTimestamp(),
owner.address,
);
const delegation = await twabDelegator.getDelegation(owner.address, 0);
expect(delegation.lockUntil).to.equal((await getTimestamp()) + MAX_EXPIRY);
});
it('should allow a delegator to withdraw from a delegation that was transferred to another delegatee', async () => {
await increaseTime(MAX_EXPIRY + 1);
await twabDelegator.updateDelegatee(owner.address, 0, secondDelegatee.address, 0);
expect(await twabDelegator.withdrawDelegationToStake(owner.address, 0, amount))
.to.emit(twabDelegator, 'WithdrewDelegationToStake')
.withArgs(owner.address, 0, amount, owner.address);
const firstDelegateeAccountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(firstDelegateeAccountDetails.balance).to.eq(Zero);
const secondDelegateeAccountDetails = await ticket.getAccountDetails(secondDelegatee.address);
expect(secondDelegateeAccountDetails.balance).to.eq(Zero);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(amount);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(amount);
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(await ticket.delegateOf(delegationAddress)).to.eq(secondDelegatee.address);
});
it('should fail to update a delegatee if caller is not the delegator or representative of the delegation', async () => {
await expect(
twabDelegator
.connect(stranger)
.updateDelegatee(owner.address, 0, secondDelegatee.address, 0),
).to.be.revertedWith('TWABDelegator/not-dlgtr-or-rep');
});
it('should fail to update a delegatee if delegatee address passed is address zero', async () => {
await expect(
twabDelegator.updateDelegatee(owner.address, 0, AddressZero, 0),
).to.be.revertedWith('TWABDelegator/dlgt-not-zero-addr');
});
it('should fail to update an inexistent delegation', async () => {
await expect(
twabDelegator.updateDelegatee(owner.address, 1, secondDelegatee.address, 0),
).to.be.revertedWith('Transaction reverted: function call to a non-contract account');
});
it('should fail to update a delegatee if delegation is still locked', async () => {
await expect(
twabDelegator.updateDelegatee(owner.address, 0, secondDelegatee.address, 0),
).to.be.revertedWith('TWABDelegator/delegation-locked');
});
});
describe('fundDelegation()', () => {
const amount = toWei('1000');
let delegationAddress = '';
beforeEach(async () => {
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
await ticket.mint(stranger.address, amount);
await ticket.connect(stranger).approve(twabDelegator.address, MaxUint256);
const transaction = await twabDelegator.createDelegation(
owner.address,
0,
firstDelegatee.address,
MAX_EXPIRY,
);
delegationAddress = await getDelegationAddress(transaction);
});
it('should allow anyone to transfer tickets to a delegation', async () => {
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(await twabDelegator.connect(stranger).fundDelegation(owner.address, 0, amount))
.to.emit(twabDelegator, 'DelegationFunded')
.withArgs(owner.address, 0, amount, stranger.address);
const firstDelegateeAccountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(firstDelegateeAccountDetails.balance).to.eq(amount);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await twabDelegator.balanceOf(stranger.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(amount);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should fund an inexistent delegation and then create it', async () => {
await twabDelegator.connect(stranger).fundDelegation(owner.address, 1, amount);
const transaction = await twabDelegator.createDelegation(
owner.address,
1,
firstDelegatee.address,
MAX_EXPIRY,
);
delegationAddress = await getDelegationAddress(transaction);
const firstDelegateeAccountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(firstDelegateeAccountDetails.balance).to.eq(amount);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await twabDelegator.balanceOf(stranger.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(amount);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should fail to transfer tickets to a delegation if delegator passed is address zero', async () => {
await expect(
twabDelegator.connect(stranger).fundDelegation(AddressZero, 0, amount),
).to.be.revertedWith('TWABDelegator/dlgtr-not-zero-adr');
});
it('should fail to transfer tickets to a delegation if amount passed is not greater than zero', async () => {
await expect(
twabDelegator.connect(stranger).fundDelegation(owner.address, 0, Zero),
).to.be.revertedWith('TWABDelegator/amount-gt-zero');
});
});
describe('fundDelegationFromStake()', () => {
const amount = toWei('1000');
let delegationAddress = '';
beforeEach(async () => {
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
await ticket.mint(stranger.address, amount);
await ticket.connect(stranger).approve(twabDelegator.address, MaxUint256);
await twabDelegator.stake(owner.address, amount);
const transaction = await twabDelegator.createDelegation(
owner.address,
0,
firstDelegatee.address,
MAX_EXPIRY,
);
delegationAddress = await getDelegationAddress(transaction);
});
it('should allow a delegator to transfer tickets from their stake to a delegation', async () => {
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(await twabDelegator.fundDelegationFromStake(owner.address, 0, amount))
.to.emit(twabDelegator, 'DelegationFundedFromStake')
.withArgs(owner.address, 0, amount, owner.address);
const firstDelegateeAccountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(firstDelegateeAccountDetails.balance).to.eq(amount);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(amount);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should allow a representative to transfer tickets from their delegator stake to a delegation', async () => {
await twabDelegator.setRepresentative(representative.address, true);
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(
await twabDelegator
.connect(representative)
.fundDelegationFromStake(owner.address, 0, amount),
)
.to.emit(twabDelegator, 'DelegationFundedFromStake')
.withArgs(owner.address, 0, amount, representative.address);
const firstDelegateeAccountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(firstDelegateeAccountDetails.balance).to.eq(amount);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(amount);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should transfer tickets to an inexistent delegation and then create it', async () => {
await twabDelegator.fundDelegationFromStake(owner.address, 1, amount);
const transaction = await twabDelegator.createDelegation(
owner.address,
1,
firstDelegatee.address,
MAX_EXPIRY,
);
delegationAddress = await getDelegationAddress(transaction);
const firstDelegateeAccountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(firstDelegateeAccountDetails.balance).to.eq(amount);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(amount);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should fail to transfer tickets to a delegation if delegator passed is not a delegator', async () => {
await expect(
twabDelegator.fundDelegationFromStake(stranger.address, 0, amount),
).to.be.revertedWith('TWABDelegator/not-dlgtr-or-rep');
});
it('should fail to transfer tickets to a delegation if amount passed is not greater than zero', async () => {
await expect(
twabDelegator.fundDelegationFromStake(owner.address, 0, Zero),
).to.be.revertedWith('TWABDelegator/amount-gt-zero');
});
it('should fail to transfer tickets to a delegation if amount passed is greater than amount staked', async () => {
await expect(
twabDelegator.fundDelegationFromStake(owner.address, 0, amount.mul(2)),
).to.be.revertedWith('ERC20: burn amount exceeds balance');
});
});
describe('withdrawDelegationToStake()', () => {
const amount = toWei('1000');
let delegationAddress = '';
beforeEach(async () => {
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
await twabDelegator.stake(owner.address, amount);
const transaction = await twabDelegator.createDelegation(
owner.address,
0,
firstDelegatee.address,
MAX_EXPIRY,
);
delegationAddress = await getDelegationAddress(transaction);
await twabDelegator.fundDelegationFromStake(owner.address, 0, amount);
});
it('should allow a delegator to withdraw from a delegation to the stake', async () => {
await increaseTime(MAX_EXPIRY + 1);
expect(await twabDelegator.withdrawDelegationToStake(owner.address, 0, amount))
.to.emit(twabDelegator, 'WithdrewDelegationToStake')
.withArgs(owner.address, 0, amount, owner.address);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(amount);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(amount);
const accountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(accountDetails.balance).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should allow a representative to withdraw from a delegation to the stake', async () => {
await increaseTime(MAX_EXPIRY + 1);
await twabDelegator.setRepresentative(representative.address, true);
expect(
await twabDelegator
.connect(representative)
.withdrawDelegationToStake(owner.address, 0, amount),
)
.to.emit(twabDelegator, 'WithdrewDelegationToStake')
.withArgs(owner.address, 0, amount, representative.address);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(amount);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(amount);
const accountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(accountDetails.balance).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should fail to withdraw from a delegation to the stake if amount is not greater than zero', async () => {
await expect(
twabDelegator.withdrawDelegationToStake(owner.address, 0, Zero),
).to.be.revertedWith('TWABDelegator/amount-gt-zero');
});
it('should fail to withdraw from a delegation to the stake if caller is not the delegator or representative of the delegation', async () => {
await expect(
twabDelegator.connect(stranger).withdrawDelegationToStake(owner.address, 0, amount),
).to.be.revertedWith('TWABDelegator/not-dlgtr-or-rep');
});
it('should fail to withdraw from a delegation to the stake an inexistent delegation', async () => {
await expect(
twabDelegator.withdrawDelegationToStake(owner.address, 1, amount),
).to.be.revertedWith('Transaction reverted: function call to a non-contract account');
});
it('should fail to withdraw from a delegation to the stake a delegation if delegation is still locked', async () => {
await expect(
twabDelegator.withdrawDelegationToStake(owner.address, 0, amount),
).to.be.revertedWith('TWABDelegator/delegation-locked');
});
});
describe('transferDelegationTo()', () => {
const amount = toWei('1000');
let delegationAddress = '';
beforeEach(async () => {
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
await twabDelegator.stake(owner.address, amount);
const transaction = await twabDelegator.createDelegation(
owner.address,
0,
firstDelegatee.address,
MAX_EXPIRY,
);
delegationAddress = await getDelegationAddress(transaction);
await twabDelegator.fundDelegationFromStake(owner.address, 0, amount);
});
it('should allow a delegator to transfer tickets from a delegation', async () => {
await increaseTime(MAX_EXPIRY + 1);
expect(await twabDelegator.transferDelegationTo(0, amount, owner.address))
.to.emit(twabDelegator, 'TransferredDelegation')
.withArgs(owner.address, 0, amount, owner.address);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(owner.address)).to.eq(amount);
const accountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(accountDetails.balance).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should allow a delegator to transfer tickets from a delegation to another user', async () => {
await increaseTime(MAX_EXPIRY + 1);
expect(await twabDelegator.transferDelegationTo(0, amount, stranger.address))
.to.emit(twabDelegator, 'TransferredDelegation')
.withArgs(owner.address, 0, amount, stranger.address);
expect(await twabDelegator.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(twabDelegator.address)).to.eq(Zero);
expect(await ticket.balanceOf(owner.address)).to.eq(Zero);
expect(await ticket.balanceOf(stranger.address)).to.eq(amount);
const accountDetails = await ticket.getAccountDetails(firstDelegatee.address);
expect(accountDetails.balance).to.eq(Zero);
expect(await ticket.balanceOf(delegationAddress)).to.eq(Zero);
expect(await ticket.delegateOf(delegationAddress)).to.eq(firstDelegatee.address);
});
it('should not allow a representative to transfer tickets from a delegation', async () => {
await increaseTime(MAX_EXPIRY + 1);
await twabDelegator.setRepresentative(representative.address, true);
await expect(
twabDelegator.connect(representative).transferDelegationTo(0, amount, owner.address),
).to.be.revertedWith('Transaction reverted: function call to a non-contract account');
});
it('should fail to transfer tickets from a delegation if caller is not the delegator', async () => {
await expect(
twabDelegator.connect(stranger).transferDelegationTo(0, amount, owner.address),
).to.be.revertedWith('Transaction reverted: function call to a non-contract account');
});
it('should fail to transfer tickets from a delegation if amount is not greater than zero', async () => {
await expect(twabDelegator.transferDelegationTo(0, Zero, owner.address)).to.be.revertedWith(
'TWABDelegator/amount-gt-zero',
);
});
it('should fail to transfer tickets from a delegation if recipient is address zero', async () => {
await expect(twabDelegator.transferDelegationTo(0, amount, AddressZero)).to.be.revertedWith(
'TWABDelegator/to-not-zero-addr',
);
});
it('should fail to transfer tickets from an inexistent delegation', async () => {
await expect(twabDelegator.transferDelegationTo(1, amount, owner.address)).to.be.revertedWith(
'Transaction reverted: function call to a non-contract account',
);
});
it('should fail to transfer tickets from a delegation if still locked', async () => {
await expect(twabDelegator.transferDelegationTo(0, amount, owner.address)).to.be.revertedWith(
'TWABDelegator/delegation-locked',
);
});
});
describe('setRepresentative()', () => {
it('should set a representative', async () => {
expect(await twabDelegator.setRepresentative(representative.address, true))
.to.emit(twabDelegator, 'RepresentativeSet')
.withArgs(owner.address, representative.address, true);
expect(await twabDelegator.isRepresentativeOf(owner.address, representative.address)).to.eq(
true,
);
});
it('should unset a representative', async () => {
expect(await twabDelegator.setRepresentative(representative.address, false))
.to.emit(twabDelegator, 'RepresentativeSet')
.withArgs(owner.address, representative.address, false);
expect(await twabDelegator.isRepresentativeOf(owner.address, representative.address)).to.eq(
false,
);
});
it('should fail to set a representative if passed address is address zero', async () => {
await expect(twabDelegator.setRepresentative(AddressZero, true)).to.be.revertedWith(
'TWABDelegator/rep-not-zero-addr',
);
});
});
describe('multicall()', () => {
it('should allow a user to run multiple transactions in one go', async () => {
const amount = toWei('1000');
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, amount);
const stakeTx = await twabDelegator.populateTransaction.stake(owner.address, amount);
const createDelegationTx = await twabDelegator.populateTransaction.createDelegation(
owner.address,
0,
firstDelegatee.address,
0,
);
await twabDelegator.multicall([stakeTx.data, createDelegationTx.data]);
});
});
describe('permitAndMulticall()', () => {
it('should allow a user to stake in one transaction', async () => {
const amount = toWei('1000');
await ticket.mint(owner.address, amount);
const signature = await permitSignature({
permitToken: ticket.address,
fromWallet: owner,
spender: twabDelegator.address,
amount,
provider,
});
const stakeTx = await twabDelegator.populateTransaction.stake(owner.address, amount);
const createDelegationTx = await twabDelegator.populateTransaction.createDelegation(
owner.address,
0,
firstDelegatee.address,
0,
);
await twabDelegator.permitAndMulticall(
amount,
{ v: signature.v, r: signature.r, s: signature.s, deadline: signature.deadline },
[stakeTx.data, createDelegationTx.data],
);
});
});
describe('getDelegation()', () => {
it('should return an empty one', async () => {
const position = await twabDelegator.computeDelegationAddress(owner.address, 0);
const { delegation, delegatee, balance, lockUntil, wasCreated } =
await twabDelegator.getDelegation(owner.address, 0);
expect(delegation).to.equal(position);
expect(delegatee).to.equal(AddressZero);
expect(balance).to.equal('0');
expect(lockUntil).to.equal('0');
expect(wasCreated).to.equal(false);
});
it('should allow a user to get the delegation info', async () => {
const amount = toWei('1000');
await ticket.mint(owner.address, amount);
await ticket.approve(twabDelegator.address, MaxUint256);
await twabDelegator.stake(owner.address, amount);
const transaction = await twabDelegator.createDelegation(
owner.address,
0,
firstDelegatee.address,
MAX_EXPIRY,
);
await twabDelegator.fundDelegationFromStake(owner.address, 0, amount);
const block = await ethers.provider.getBlock(transaction.blockNumber);
const position = await twabDelegator.computeDelegationAddress(owner.address, 0);
const { delegation, delegatee, balance, lockUntil, wasCreated } =
await twabDelegator.getDelegation(owner.address, 0);
expect(delegation).to.equal(position);
expect(delegatee).to.equal(firstDelegatee.address);
expect(balance).to.equal(amount);
expect(lockUntil).to.equal(block.timestamp + MAX_EXPIRY);
expect(wasCreated).to.equal(true);
});
});
describe('decimals()', () => {
it('should return ticket decimals', async () => {
expect(await twabDelegator.decimals()).to.eq(6);
});
});
}); |
import { Website } from "@prisma/client";
import classNames from "classnames";
import Image from "next/image";
const MobileDisplay = ({
theme,
website,
links,
}: {
theme: string;
website: Website;
links: {
linkedWebsite: {
type: string;
link: string;
icon: JSX.Element;
} | null;
linkedFacebook: {
type: string;
link: string;
icon: JSX.Element;
} | null;
linkedInstagram: {
type: string;
link: string;
icon: JSX.Element;
} | null;
linkedTwitter: {
type: string;
link: string;
icon: JSX.Element;
} | null;
linkedLinkedin: {
type: string;
link: string;
icon: JSX.Element;
} | null;
linkedEmail: {
type: string;
link: string;
icon: JSX.Element;
} | null;
};
}) => {
return (
<div
className={classNames(
"no-scrollbar mx-auto mb-6 flex h-[450px] w-1/2 min-w-[220px] max-w-[250px] flex-col items-center overflow-y-auto rounded-3xl border-8 border-neutral-800 pt-8",
{
"bg-neutral-100 text-neutral-900": theme === "light",
"bg-neutral-900 text-neutral-100": theme === "dark",
}
)}
>
<Image
src={website.image}
width={50}
height={50}
alt="Website Logo"
className="mb-3 rounded-full"
/>
<h1 className="mb-6 font-bold">{website.name}</h1>
<div className="mb-6 flex w-full flex-col gap-3 px-6">
{Object.entries(links).map(([key, value]) => {
if (value) {
return (
<div key={key} className="w-full rounded border p-2 text-center">
<a
href={
value.type !== "Email"
? value.link
: `mailto: ${value.link}`
}
target="_blank"
rel="noreferrer"
className="flex w-full items-center gap-2"
>
{value.icon}
<span className="text-center">{value.type}</span>
</a>
</div>
);
}
})}
</div>
</div>
);
};
export default MobileDisplay; |
/*
* HashSum
*
* Copyright (c) 2023 chatgptdev
*
* This software was written mostly by ChatGPT 4.0 using instructions by
* @chatgptdev. It is provided under the Apache License, Version 2.0
* (the "License"); you may not use this software except in compliance with
* the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "WindowsHash.h"
#include <algorithm>
WindowsHash::WindowsHash() : hAlgorithm(nullptr), hHash(nullptr), initialized(false) {}
WindowsHash::~WindowsHash() {
if (initialized) {
BCryptDestroyHash(hHash);
BCryptCloseAlgorithmProvider(hAlgorithm, 0);
}
}
bool WindowsHash::Init(const std::string& algorithm) {
std::string lowerAlgorithm = algorithm;
std::transform(lowerAlgorithm.begin(), lowerAlgorithm.end(), lowerAlgorithm.begin(), ::tolower);
LPCWSTR algId;
if (lowerAlgorithm == "md5") {
algId = BCRYPT_MD5_ALGORITHM;
} else if (lowerAlgorithm == "sha1" ) {
algId = BCRYPT_SHA1_ALGORITHM;
} else if (lowerAlgorithm == "sha256") {
algId = BCRYPT_SHA256_ALGORITHM;
} else if (lowerAlgorithm == "sha384") {
algId = BCRYPT_SHA384_ALGORITHM;
} else if (lowerAlgorithm == "sha512") {
algId = BCRYPT_SHA512_ALGORITHM;
} else {
return false;
}
NTSTATUS status;
// Open the algorithm provider
status = BCryptOpenAlgorithmProvider(&hAlgorithm, algId, nullptr, 0);
if (!BCRYPT_SUCCESS(status)) {
return false;
}
// Create the hash object
status = BCryptCreateHash(hAlgorithm, &hHash, nullptr, 0, nullptr, 0, 0);
if (!BCRYPT_SUCCESS(status)) {
BCryptCloseAlgorithmProvider(hAlgorithm, 0);
return false;
}
initialized = true;
return true;
}
bool WindowsHash::Update(const unsigned char* data, size_t dataSize) {
if (!initialized) {
return false;
}
NTSTATUS status = BCryptHashData(hHash, const_cast<PUCHAR>(data), dataSize, 0);
if (!BCRYPT_SUCCESS(status)) {
return false;
}
return true;
}
bool WindowsHash::Final(std::vector<unsigned char>& digest) {
if (!initialized) {
return false;
}
// Get the hash length
DWORD hashLength;
DWORD cbData;
NTSTATUS status = BCryptGetProperty(hAlgorithm, BCRYPT_HASH_LENGTH, (PBYTE)&hashLength, sizeof(DWORD), &cbData, 0);
if (!BCRYPT_SUCCESS(status)) {
return false;
}
// Resize the hash vector and finish the hash
digest.resize(hashLength);
status = BCryptFinishHash(hHash, digest.data(), hashLength, 0);
if (!BCRYPT_SUCCESS(status)) {
digest.clear();
return false;
}
return true;
}
std::vector<std::string> WindowsHash::GetSupportedAlgorithms() {
std::vector<std::string> supportedAlgorithms;
supportedAlgorithms.push_back("md5");
supportedAlgorithms.push_back("sha1");
supportedAlgorithms.push_back("sha256");
supportedAlgorithms.push_back("sha384");
supportedAlgorithms.push_back("sha512");
return supportedAlgorithms;
} |
package com.itgate.ProShift.entity;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Invitation {
public enum Status{ACCEPTE,REFUSE,DEFAULT}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date dateCreation;
@Enumerated(EnumType.STRING)
private Status status=Status.DEFAULT;
@ManyToOne
@JoinColumn(name = "evennement_id")
@JsonIgnore
private Evennement evennement;
@ManyToOne
@JoinColumn(name = "coordinateur_id")
@JsonIgnore
private User coordinateur;
@ManyToOne
@JoinColumn(name = "invitee_id")
private User invitee;
@PrePersist
private void prePersist() {
dateCreation = new Date();
}
} |
//
// MovieDetailViewController.swift
// TMDB Challenge
//
// Created by Agustin Russo on 25/04/2022.
//
import UIKit
protocol MovieDetailDelegate {
func showLoading()
func hideLoading()
func movieData(movie: MovieDetail)
func showError()
}
class MovieDetailViewController: UIViewController {
var movieUrl: String = ""
var movieId: Int = 0
var popularity: Double = 0
private var imagen: String? {
didSet {
guard let stringImage = imagen else { return }
if let url = URL(string: "https://image.tmdb.org/t/p/w500/" + stringImage) {
movieImage.load(url: url)
}
}
}
private var name: String? {
didSet {
movieName.text = name?.uppercased()
}
}
private var originalLanguage: String? {
didSet {
movieOriginalLanguage.text = originalLanguage?.uppercased()
}
}
private var releaseDate: String? {
didSet {
movieReleaseDate.text = releaseDate?.uppercased()
}
}
private var service = MovieDetailService()
private var viewModel:MovieDetailViewModel?
private lazy var backgroudImage: UIImageView = {
let aImage = UIImageView()
aImage.translatesAutoresizingMaskIntoConstraints = false
aImage.image = UIImage(named: "background")
aImage.contentMode = .scaleAspectFill
return aImage
}()
private lazy var movieImage: UIImageView = {
let aImage = UIImageView()
aImage.clipsToBounds = true
aImage.contentMode = .scaleAspectFill
aImage.layer.cornerRadius = 30
aImage.translatesAutoresizingMaskIntoConstraints = false
return aImage
}()
private lazy var movieName: UILabel = {
let aLabel = UILabel()
aLabel.translatesAutoresizingMaskIntoConstraints = false
aLabel.textColor = .white
aLabel.font = UIFont.boldSystemFont(ofSize: 30)
aLabel.textAlignment = .center
aLabel.numberOfLines = 0
return aLabel
}()
private lazy var movieOriginalLanguage: UILabel = {
let aLabel = UILabel()
aLabel.translatesAutoresizingMaskIntoConstraints = false
aLabel.textColor = .white
aLabel.font = UIFont.systemFont(ofSize: 20)
aLabel.textAlignment = .center
return aLabel
}()
private lazy var moviePopularity: UILabel = {
let aLabel = UILabel()
aLabel.translatesAutoresizingMaskIntoConstraints = false
aLabel.textColor = .white
aLabel.font = UIFont.systemFont(ofSize: 20)
aLabel.textAlignment = .center
return aLabel
}()
private lazy var movieReleaseDate: UILabel = {
let aLabel = UILabel()
aLabel.translatesAutoresizingMaskIntoConstraints = false
aLabel.textColor = .white
aLabel.font = UIFont.systemFont(ofSize: 20)
aLabel.textAlignment = .center
return aLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupConstraints()
self.viewModel = MovieDetailViewModel(id: movieId, movieUrl: movieUrl, service: service, delegate: self)
self.viewModel?.getMovie()
}
private func setupView(){
view.addSubview(backgroudImage)
view.addSubview(movieImage)
view.addSubview(movieName)
view.addSubview(movieOriginalLanguage)
view.addSubview(moviePopularity)
view.addSubview(movieReleaseDate)
}
private func setupConstraints(){
NSLayoutConstraint.activate([
backgroudImage.leadingAnchor.constraint(equalTo: view.leadingAnchor),
backgroudImage.bottomAnchor.constraint(equalTo: view.bottomAnchor),
backgroudImage.topAnchor.constraint(equalTo: view.topAnchor),
movieImage.heightAnchor.constraint(equalToConstant: round(UIScreen.main.bounds.height * 0.7)),
movieImage.leadingAnchor.constraint(equalTo: view.leadingAnchor),
movieImage.trailingAnchor.constraint(equalTo: view.trailingAnchor),
movieImage.centerXAnchor.constraint(equalTo: view.centerXAnchor),
movieImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
movieName.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
movieName.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
movieName.topAnchor.constraint(equalTo: movieImage.bottomAnchor, constant: 30),
movieOriginalLanguage.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
movieOriginalLanguage.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
movieOriginalLanguage.topAnchor.constraint(equalTo: movieName.bottomAnchor, constant: 22),
movieReleaseDate.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
movieReleaseDate.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
movieReleaseDate.topAnchor.constraint(equalTo: movieOriginalLanguage.bottomAnchor, constant: 22),
moviePopularity.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
moviePopularity.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
moviePopularity.topAnchor.constraint(equalTo: movieReleaseDate.bottomAnchor, constant: 22),
])
}
}
extension MovieDetailViewController: MovieDetailDelegate {
func showLoading() {
}
func hideLoading() {
}
func movieData(movie: MovieDetail) {
name = movie.title
imagen = movie.posterPath
originalLanguage = movie.originalLanguage
popularity = movie.popularity
releaseDate = movie.releaseDate
}
func showError() {
print("Se rompio todo..")
}
} |
import { DBManager, Version } from '@pwrdrvr/microapps-datalib';
import { AppVersionCache } from './app-cache';
import { RedirectToDefaultFile } from './redirect-default-file';
jest.mock('./app-cache');
describe('RedirectToDefaultFile', () => {
const mockDbManager = {} as DBManager;
afterEach(() => {
jest.clearAllMocks();
});
it('should return undefined if GetVersionInfo throws an error', async () => {
(AppVersionCache.GetInstance as jest.Mock).mockImplementation(() => {
return {
GetVersionInfo: () => {
throw new Error('GetVersionInfo error');
},
};
});
const result = await RedirectToDefaultFile({
dbManager: mockDbManager,
appName: 'testApp',
semVer: '1.0.0',
appNameOrRootTrailingSlash: '',
});
expect(result).toBeUndefined();
});
it('should return undefined if versionInfo is undefined', async () => {
(AppVersionCache.GetInstance as jest.Mock).mockImplementation(() => {
return {
GetVersionInfo: () => undefined,
};
});
const result = await RedirectToDefaultFile({
dbManager: mockDbManager,
appName: 'testApp',
semVer: '1.0.0',
appNameOrRootTrailingSlash: '',
});
expect(result).toBeUndefined();
});
it('should return undefined if versionInfo.DefaultFile is not set', async () => {
const versionInfo: Version = {
AppName: 'testApp',
SemVer: '1.0.0',
// @ts-expect-error this is a test after-all
DefaultFile: undefined,
};
(AppVersionCache.GetInstance as jest.Mock).mockImplementation(() => {
return {
GetVersionInfo: () => versionInfo,
};
});
const result = await RedirectToDefaultFile({
dbManager: mockDbManager,
appName: 'testApp',
semVer: '1.0.0',
appNameOrRootTrailingSlash: '',
});
expect(result).toBeUndefined();
});
it('should return a redirect with status code 302 when versionInfo.DefaultFile is set', async () => {
// @ts-expect-error This is ok to be incomplete for the test
const versionInfo: Version = {
AppName: 'testApp',
SemVer: '1.0.0',
DefaultFile: 'index.html',
};
(AppVersionCache.GetInstance as jest.Mock).mockImplementation(() => {
return {
GetVersionInfo: () => versionInfo,
};
});
const result = await RedirectToDefaultFile({
dbManager: mockDbManager,
appName: 'testApp',
semVer: '1.0.0',
appNameOrRootTrailingSlash: 'testapp/',
});
expect(result).toEqual({
statusCode: 302,
redirectLocation: '/testapp/1.0.0/index.html',
});
});
}); |
---
title: Best Ways on How to Unlock/Bypass/Swipe/Remove Realme 12+ 5G Fingerprint Lock
date: 2024-04-02 15:27:47
updated: 2024-04-05 12:29:58
tags:
- unlock
- remove screen lock
categories:
- android
description: This article describes Best Ways on How to Unlock/Bypass/Swipe/Remove Realme 12+ 5G Fingerprint Lock
excerpt: This article describes Best Ways on How to Unlock/Bypass/Swipe/Remove Realme 12+ 5G Fingerprint Lock
keywords: Realme 12+ 5G pattern lock,vnrom bypass google account verification,Realme 12+ 5G android password reset,remove screen lock pin on android,network unlock,how to unlock android phone
thumbnail: https://www.lifewire.com/thmb/hlshSPtDf3zsXAhW4UAOkuNWyQM=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/GettyImages-Macys-59e6c3699abed500118af858.jpg
---
## Best Ways on How to Unlock/Bypass/Swipe/Remove Realme 12+ 5G Fingerprint Lock
If you cannot remember your pin, pattern or password to access your Android device, this content will introduce you to the most effective method to handle the fingerprint lock, unlocking, bypassing and swiping in Android based gadgets. Your lock screen appears on your phone immediately after you turn your device on and it is there to save your privacy, data also to make your screen user-friendly and more functional. The additional material that definitely helps you to solve your limited access issue in your Android phone can be viewed here.
### The Best Way to Unlock, Bypass, Swipe and Remove Android Fingerprint Lock
[Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is a highly straightforward, fast and handy [phone unlocking software](https://drfone.wondershare.com/sim-unlock/android-unlock-software.html). With that particular application, you will be able to solve the lock screen removal issue in 5 minutes. It is really powerful as it can handle 4 types of screen locks such as password, fingerprints, pin and pattern. All you data will not be touched by the app and you do not have to possess some knowledge in tech field. So far, Dr.Fone - Android Lock Screen Removal is available for Samsung Galaxy S, Note and Tab Series and LG series for unlocking without any data losing.Temporarily, this tool can't mantain all the data when unlocking the screen from other mobile devices including Onepus, Xiaomi, iPhone. However really soon, the app will be available for the users of other operating systems. Before you purchase it, you are free to try it. You can acquire the app for 49.95 USD. You will be getting advantage using this app as comes with free lifetime update, also you will receive the keycode in minutes. Comments and feedback on Dr.Fone - Android Lock Screen Removal can be viewed here. You definitely will be interested as the app has 5 stars rating and tons of positive feedback.
### [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/)
Remove 4 Types of Android Screen Lock without Data Loss
- It can remove 4 screen lock types - pattern, PIN, password & fingerprints.
- Only remove the lock screen, no data loss at all.
- No tech knowledge asked, everybody can handle it.
- Work for Samsung Galaxy S/Note/Tab series, and LG G2/G3/G4, etc.
**4,230,631** people have downloaded it
**Follow these steps to get your lock screen issue solved:**
**Step 1.** Install Dr.Fone, then click "Screen Unlock".

**Step 2.** Connect your Android phone and then select the Realme 12+ 5G device mode on the list. If it's not on the list, select "I can't find my device model from the list above".

**Step 3.** Type the download mode on your Android gadget.

**Step 4**. Have recovery package downloaded.

**Step 5.** Remove Android lock screen without losing any data.This process will take some times.

_Remove Android Screen Lock_
<iframe width="854" height="480" src="https://www.youtube.com/embed/TQnsFr9oUHA?list=PLUrYm4QGcoz8IHR2-1WtKqPnJOnSShtFB" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
## Best 10 Fingerprint Lock Apps for Android Gadgets
The lock screen app is a navigation screen that should be user friendly and allow you to jump quickly to those features that you actively use. For those, who want to make their smartphone screens much more functional and fun, we have prepared a list of best 10 Android Fingerprint Lock Apps and Widgets. The list that will be describing the apps will not be in the form of A Ranking or Top 10. The aim of our list is just to share with you those apps which are really good at handling the functions that we need from our gadgets.
### 1st - Hi Locker
This fingerprint lock for android devices comes with a 3 modes of lock screen: Classic, iOS and Lollipop. Also, it has a separate screen dedicated to your calendar. Cyanogen Mod Style quick launcher is the main feature of Hi Locker. The secondary characteristics include custom greetings, various fonts, automatic wallpaper changes and additional customizations using an arrow key.

### 2nd - ICE Unlock Fingerprint Scanner
This app is a real fingerprint lock for Android that features a true biometric lock screen solution. ICE Unlock is powered by ONYX that allows you to take a picture of your fingerprint using your standard phone camera. Now, it supports x86 CPU architectures and MIPS. Additional notable characteristics include auto-capturing and adjustment of ellipse size to achieve optimal focal length of camera among others.

### 3rd - Finger Scanner
One of many free to download Android Fingerprint Lock app is Finger Scanner. It offers 2 work modes: double protection and single. You can unlock by scanning or pin, also, it features different scanning times. Finger Scanner is highly customizable and you can use background and colors that you prefer. It immediately will turn your screen off whenever you cover the camera lens.

### 4th - GO Locker - Theme & Wallpaper
The total downloads of Go – Locker Theme & Wallpaper is close to 1.5 million which has made this app number one with close to 4.5 stars rating on googleplay.com. This real fingerprint lock for android allows you to read incoming messages on your screen, user friendly icons will quickly take you to systems and settings and it has a huge amount of unlocking styles such as Android, iPhone and those that you have never imagined. It successfully handles over 8,000 models of various Android powered gadgets.

### 5th - Locker Master- Do It Yourself (DIY) Lock Screen
Whether you prefer having simple or complex, solid or multi colored lock screens, Locker Master- DIY Lock Screen offers you tons of options to design the lock screen that will match to your desires. Swipe gestures options and passcode patterns are designed like never before. Be informed on incoming messages or missed calls on your lock screen, share your own lock screen style or download from a huge amount of themes which are being shared daily, worldwide. Locker Master- DIY Lock Screen is a free to download fingerprint lock app as many others that we are listing here.

### 6th – Start
With [Start](https://play.google.com/store/apps/details?id=com.celltick.lockscreen), your lock screen becomes into your Start screen. Right from the lock screen, you will have a quick access to the most of apps that you actively use. You can set the security level, enjoy simple but smart navigation characteristics noticeably faster. It is a real fingerprint lock for Android devices which can be your one-stop lock screen application.

### 7th – Solo Locker (DIY Locker)
[This particular app](https://play.google.com/store/apps/details?id=com.ztapps.lockermaster) is considered as the world's first DIY that can lock your phone using a photo too. It is really smooth in functioning, lite and always ready to put your privacy onto higher level. Password interface is easily customizable and application shortcuts make your smartphone very easy to use. Solo Locker (DIY) Android fingerprint lock must be immediately downloaded by the people who would like to have an app that offers nearly uncountable wallpapers and design settings.

### 8th – Widget Locker
Out of all the apps that we have listed here, Widget Locker is the one that is not free to download. It will cost you 2, 99 United States Dollars and it has really attractive features such as a control of the mood and layouts of your smartphone. "Your privacy is the app's number one priority" (that is what the designers of Widget Locker state). Drag and drop options, selectable sliders, Slide to Launch a Camera or Slide to call My Mom options and easy resizing of widgets are some of the really efficient features of this fingerprint lock app for android devices.

### 9th - M Locker - KKM Marshmallow 6.0
This real fingerprint lock app for android is known to the users as A Top Android 6.0 Lock application with numerous upgraded and developed features such as: a multi-functional lock screen, easy to navigate and simply comprehensive look. M Locker - KKM Marshmallow 6.0 includes a torch on your locker, easy but powerful swiping options, your music can be controlled from the locker and provides the snapshots of intruders who enters the wrong passcode continuously or will be placing his fingerprint for several times to log into your device.

### 10th - Fireflies Lock Screen
With over 300,000 downloads and the rate of 4.3 stars, [Fireflies Lock Screen](https://play.google.com/store/apps/details?id=com.app.free.studio.firefly.locker) more than deserves to be downloaded and installed if you own one of those smartphones that comes with a fingerprint reader. In this app, you can change, resize, command and set almost everything the way you wish. Swipe to jump to a particular app or swipe to remove the notifications. Provides highest level of functionality and you have wide variety of options on locking your device or apps/widgets/folders. The most of comments given to this particular app describe it as "Best of its kind" and this characteristic makes it to be a real fingerprint lock for android devices.

The unlock method that was described in the beginning of our content, is the most functional approach to handle a lock screen problem successfully. In Non-Ranking and No-Comparisons form, we have presented you the list of best 10 fingerprint lock apps for Android devices. Each user is different and that is why there are various applications for your gadget. Try them out and find the one that suits you best!
## How to Use Google Assistant on Your Lock Screen Of Realme 12+ 5G Phone
Android has undergone numerous changes to enhance user experience and security. One notable feature that was once present was the ability to **unlock phones with voice Google Assistant**. However, Google Assistant has removed this feature across all versions since 2021.
While this voice-unlocking feature is no longer available, there are still many things you can do with Google Assistant, even when the Realme 12+ 5G device is locked. This tool brings an added layer of convenience to your smartphone experience.
Let's dig deeper into how you can **use Google Assistant on the lock screen** and make the most out of this tool in the following article.

## Part 1. What You Can Do With Voice Google Assistant
Google Assistant is a virtual assistant powered by artificial intelligence (AI) developed by tech giant Google. This application is readily available on most recent mobile phone models, especially those operating on Android 6.0 and newer versions.
Although you can no longer use the **Google Assistant unlock** feature, you can still perform a myriad of tasks using Google Assistant. These include:
- Getting the weather
- Setting alarms
- Playing music
- Sending texts
- Making a call
- Asking Google for information, etc.
### Enable Google Assistant on Lock Screen: A Step-by-Step Guide
Now that you're eager to try the potential of Google Assistant on your lock screen, let's walk through the simple steps on how to enable this tool.
- **Step 1:** Open Google Assistant:
Look for "Google Assistant" and open the app.
- **Step 2:** Ask Google Assistant to open the settings.
You can ask, "Hey Google, open the Google Assistant settings," and it will show you the Google Assistant settings.
- **Step 3:** Allow Google Assistant on the lock screen.
Locate the “Lock Screen” settings and make sure to switch on “Assistant responses on lock screen.”

## Part 2. How To Use Google Assistant on Lock Screen
After you've successfully enabled Google Assistant on your lock screen, let's see how to use Google Assistant to do certain tasks more efficiently and hands-free.
- **Step 1:** Wake Up Google Assistant
Start by waking up Google Assistant. You can do this by saying the wake word "Hey Google" or "OK Google." If it doesn’t work, you can long-press the home button or use any dedicated gesture to activate Google Assistant.
- **Step 2:** Issue a Voice Command
Once Google Assistant is active, issue a voice command related to the task you want to perform. For example:
"Hey Google, what's the weather today?"
"OK Google, set an alarm for 5 PM."
"Hey Google, play my Spotify playlist."
When you can still **unlock with Google Assistant**, you can ask it to “unlock my phone” or use any similar command.
- **Step 3:** Interact with Responses
Google Assistant will then provide spoken responses and display relevant information on the lock screen. For instance, if you ask for the weather, it might verbally provide the current conditions and display a brief summary on your lock screen.

## Part 3. Common Problems When Using Google Assistant
Unable to use **Google Assistant to unlock phone** is not the only drawback that users may have encountered in recent changes. Although Google Assistant on the lock screen presents a revolutionary way to interact with your phone, like any technology, it also comes with its share of challenges. Some of the common problems when using Google Assistant are:
1. **Misunderstandings and misinterpretations**
One prevalent issue users encounter is Google Assistant misunderstanding or misinterpreting voice commands. This can be influenced by factors such as background noise, accent variations, or pronunciation differences.
2. **Limited context understanding**
While Google Assistant is adept at understanding individual commands, it may struggle with complex, multi-step requests that rely heavily on context. Break down your tasks into simpler commands to enhance comprehension and execute it more accurately.
3. **Inability to execute certain tasks**
Google Assistant's capabilities are extensive, but there are instances where it may struggle to execute specific tasks. For example, it can’t execute tasks that involve interacting with certain third-party applications or services. You can't also **unlock phone with voice Google Assistant.**

### Tips to Make Voice Google Assistant Recognize Your Commands
One of the most infuriating problems with voice Google Assistant is that users often encounter difficulties in having their commands accurately recognized. To enhance the accuracy of voice recognition with Google Assistant, you can consider implementing the following tips:
1. **Speak Clearly and Naturally**
Make sure that you speak in a clear and natural manner. Avoid mumbling or speaking too quickly. Enunciate your words, giving Google Assistant a better chance to interpret your commands accurately.
2. **Use Simple and Direct Phrases**
Keep your commands simple and direct. Avoid unnecessary elaboration or complex sentence structures. Google Assistant is more likely to understand straightforward commands.
3. **Check Your Microphone**
Ensure that your device's microphone is in good working condition. Dirt or debris on your phone's microphone can affect its performance. Clean the microphone area and try again.
4. **Quiet Environment**
Background noise can interfere with voice recognition. Try to issue commands in a quiet environment to minimize any potential confusion caused by external sounds.
## Part 4. How to Unlock Android Phone Screen Without Passcode
Now, you know that you can't **unlock phone via Google Assistant** anymore. But what if you accidentally [<u>forget your phone’s passcode</u>](https://drfone.wondershare.com/unlock/forgot-android-password.html)? Is there a reliable method to regain access to your Android device without the passcode?
Fortunately, [<u>Wondershare Dr.Fone</u>](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) offers a straightforward solution for precisely such scenarios. It provides a simple and effective way to unlock your Android phone screen through Dr.Fone - Screen Unlock when the screen lock is forgotten or becomes inaccessible.

### [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/)
The Best UnlockJunky Alternative to Solve Your Screen Locks
- Completely unlinked from the previous Google account, it won’t be traced or blocked by it anymore.
- Remove all Android screen locks (PIN/pattern/fingerprints/face ID) in minutes.
- Compatiable with various Android models.
- Provide specific removal solutions to promise good success rate.
**4,008,670** people have downloaded it
If you are wondering how to unlock your Android phone screen without a passcode with Dr.Fone – Screen Unlock, follow the steps below.
- **Step 1:** Launch the Screen Unlock Tool
Open the latest version of Wondershare Dr.Fone on your computer and connect your phone device using a USB cable. Once connected, navigate to the Toolbox > Screen Unlock to access Dr.Fone – Screen Unlock tool.

- **Step 2:** Select Android for your device type.
As the Dr.Fone Screen Unlock tool supports both Android and iOS, you will need to indicate the specific device you are using. Opt for the Android option if you are unlocking an Android device. Then, continue to choose "Unlock Android Screen" on the next screen.

- **Step 3:** Remove Screen Lock Without Data Loss
- In this step, you will be directed to select your device brand. Choose the Android device brand you are using and opt for "Remove without Data Loss" if you don't want to lose your data.

- **Step 4:** Define Device Details
Next, make sure to check and confirm the Brand, Device Name, and Device Model to unlock your Android screen. Tick the checkmark that says you agree with the warning and are ready to proceed. Click "Next" to unlock your screen.

- **Step 5:** Confirm to Unlock Screen
Type "000000" continue by clicking Confirm.

- **Step 6:** Put Android in Download Mode
Dr.Fone will then guide you to put your Android device into Download Mode according to the model you have identified. After you have followed the instructions, Dr.Fone will automatically lead to the next screen to proceed the unlocking process.

After that, you can monitor the progress and wait for a few minutes until it shows “Unlocked successfully.”
You May Also Interested:
[<u>Unlocking Your Realme Phone Made Easy: Step-by-Step Guide</u>](https://drfone.wondershare.com/unlock/how-to-unlock-realme-phone-without-losing-data.html)
[<u>8 Safe and Effective Methods to Unlock Your iPhone Without a Passcode</u>](https://drfone.wondershare.com/unlock/unlock-iphone-without-passcode.html)
[<u>Complete Guide to Unlock Mi Account Without Password In 2024</u>](https://drfone.wondershare.com/unlock/guide-to-unlock-mi-account-without-password.html)
## Conclusion
Google Assistant is a versatile virtual assistant that is designed to help you with a wide range of tasks and make your daily life more convenient. Accessible on most modern Android devices, it enables users to perform several tasks through voice commands.
However, if you are looking for ways to **unlock phone with Google Assistant**, this function is no longer available. **Google Assistant unlock** feature has been discontinued since 2021. But in case you've forgotten the screen lock passcode, you can use Wondershare Dr.Fone Screen Unlock tool to regain access to your Android phone. This tool facilitates the unlocking process without data loss, featuring a user-friendly learning curve.
## How to Unlock Realme 12+ 5G Phone with Broken Screen
Seeing as the only way to control your Realme 12+ 5G deviceis the touch screen, a broken device can cause you a lot of worries. Most people think that there is no way to get their device to work again let alone be able to unlock it if [the screen is broken or cracked](https://www.wondershare.com/android/access-android-phone-with-broken-screen.html). It is, however, important to find a way to unlock the broken device so that you can gain access to your data and create a backup to restore to a new device.
In this article, we are going to look at a few simple ways you can unlock an Android device with a broken screen.
**Here is a video for you to learn how to unlock Android phone or access phone with broken screen:**
<iframe width="100%" height="450" src="https://www.youtube.com/embed/KaWEiQhxBTQ" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
## Method 1: Using Android Debug Bridge (ADB)
For this method, you will need your device and access to a PC. It is the most powerful method to unlock a broken Android device. It will however only work if you have enabled USB debugging on your android phone. If you haven’t, skip this method and see if method 2 or 3 might be of help.
ADB creates a bridge between the PC and your device which can then be used to unlock the Realme 12+ 5G device. Here’s how to use this bridge.
**Step 1:** Download the Android SDK package on your PC. You can download it here: [http://developer.android.com/sdk/index.html](http://developer.android.com/sdk/index.html). Extract the ZIP file on your PC.
**Step 2:** Download the necessary drivers for your device. The USB drivers for your device can be found on the manufacturer’s website.
**Step 3:** Launch Command Prompt on your PC and change the location of the ADB file. Type in the following into Command Prompt; _cd C:/android/platform-tools_
**Step 4:** Connect the Realme 12+ 5G device to your PC using USB cables. Enter the command “ ADB _device_” (without quotation marks). If your phone is recognized, you will see numbers in the Command Prompt message.
**Step 5:** Type in the following two commands. You will need to type in the second one immediately after the first. Replace 1234 with your password.
_ADB shell input text 1234_
_Shell input key event 66_
**Step 6:** Your phone will now be unlocked and you can proceed to back up its contents.

### [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/)
The Best Tool to Reset Phones Without Android Factory Reset Codes
- It enables your Android phones to get safe, simple, and trustful after reset.
- It is still helpful even though you don't know the OS version of your devices.
- Everybody can handle it without any technical background.
- Provide specific removal solutions to promise good success rate.
**4,008,670** people have downloaded it
## Method 2: Using a USB Mouse and the On the Go Adapter
This is a great solution if you don’t have USB debugging enabled on your device. You will need your device, an OTG adapter and a USB mouse. It involves connecting the Realme 12+ 5G device to the USB mouse using the OTG adapter. Check if your device can be connected to a USB mouse. You can find an OTG adapter online, they are relatively inexpensive and very useful.
Before we begin, it is a good idea to ensure your device is sufficiently charged because the Mouse may drain your battery.
**Step 1:** Connect the Micro USB side of the OTG adapter to your device and then plug in the USB mouse to the adapter.

**Step 2:** As soon as the Realme 12+ 5G devices are connected, you will be able to see a pointer on your screen. You can then use the pointer to unlock the pattern or enter the Realme 12+ 5G device’s password lock.

You can then go about backing up the contents of your device.
## Method 3: Using your Samsung Account
This method is a reliable way to unlock a Samsung device that has a broken screen or is not working correctly. While it is highly effective you will need to have a Samsung account registered with your device. The problem is that not many Samsung device users have registered their devices with the service. If you are among the lucky few who have, here’s how to use your account to unlock your device.
**Step 1:** Visit the [https://findmymobile.samsung.com/login.do](https://findmymobile.samsung.com/login.do) on your PC or any other device and log in with your account information.

**Step 2:** Select your device from the menu on the left-hand side of the screen.
**Step 3:** You should see the option “Unlock my screen” on the sidebar. Click on it and you will get instructions on how to access your device.

## Conclusion
Being unable to unlock your device is never a good place to be. We hope one of the above solutions will work for you. You can then gain access to your device and back up the files and contacts. This way your life doesn’t have to be disrupted- you can just restore the backup on a new device or the old one once the screen is fixed.
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins> |
#' Extracts Notes and Annotations
#' Read, format, and merge Notes and Annotations from Black Box Analyzer
#' @param x EM data annotations/notes with geographic coordinates in decimal as lon/lat
#' @param by.year Are the files sorted by year (default)?
#' @return A dataset with all notes/annotations in long format, where rows are unique for hauls for no or one bycatch within that haul (each additional bycatch is listed as one supplementary row).
#' @import data.table
#' @export
BBimport <- function(x = "Q:/scientific-projects/cctv-monitoring/data/blackbox extractions/annotations_notes/",
by.year = TRUE) {
review.info <- Id <- d <- m <- y <- Activity.type <- Note.type <- Color.name <- colour.name <- Haul.no <- Mesh.color <- Vesselid <- vessel <- time.start <- haul_number <- IDFD <- IDhaul <- IDevent <- haul.lon.start <- haul.lon.stop <- haul.lat.start <- haul.lat.stop <- Distance..m. <- Soaking.time..h. <- Review.info <- gps <- Start.longitude <- End.longitude <- Start.latitude <- End.latitude <- time.stop <- Note <- Activity.comment <- mitigation <- mitigation_type <- ID3 <- IDevent <- NULL
`%notin%` <- Negate(`%in%`)
if( by.year == FALSE ){
all_files <- list.files(x, pattern = "^[A-Za-z]", full.names = TRUE,
recursive = FALSE)
filenames <- all_files[!file.info(all_files)$isdir]
} else{
all_files <- list.files(x, pattern = "^20", full.names = TRUE,
recursive = FALSE)
filenames <- all_files[!file.info(all_files)$isdir]
}
list_BBdata <- lapply(filenames,
utils::read.csv,
header=TRUE, sep = ";",
stringsAsFactors = FALSE, quote = "")
names(list_BBdata) <- tolower(gsub(".*/(.+).csv.*", "\\1", filenames))
list_BBdata <- Map(function(x){
x <- x[!x$Vesselid == "",]
x <- x[!is.na(x$Vesselid),]
x <- x[!x$Vesselid == "HAV01",]
x <- x %>%
dplyr::filter(substr(Id,1,1) == "a" | substr(Id,1,1) == "n")
x <- x %>%
dplyr::mutate(gps = if_else(is.na(Start.latitude),
0, 1))
x$time.start <- as.character(strptime(x$Start.time.local..log.,
"%d-%m-%Y %H:%M:%S"))
x$time.stop <- as.character(strptime(x$End.time.local..log.,
"%d-%m-%Y %H:%M:%S"))
x <- x[with(x, order(x$Vesselid,x$time.start)),]
x <- x[!x$Type == "Videofile",]
x <- x[!x$Type == "Trip",]
x <- x[!x$Type == "BlackBoxNote",]
x <- x[!x$Type == "MiniDisc",]
x$Mesh.color <- as.character(x$Mesh.color)
x <- x[!x$Color.code == "",]
x$Start.latitude <- as.numeric(x$Start.latitude) ## in decimal
x$Start.longitude <- as.numeric(x$Start.longitude) ## in decimal
x$End.latitude <- as.numeric(x$End.latitude) ## in decimal
x$End.longitude <- as.numeric(x$End.longitude) ## in decimal
x$date <- as.Date(lubridate::dmy_hms(x$Start.time.local..log.))
x <- x %>%
tidyr::separate(date, c("y","m","d")) %>%
tidyr::unite(col = date, c(d,m,y), sep = "-") %>%
dplyr::mutate(Date = date)
x$IDFD <- paste(x$Vesselid, x$Date, sep = ".")
x <- x %>%
tidyr::separate(date, c("y","m","d")) %>%
tidyr::unite(col = date, c(d,m,y), sep = "-")
x <- x %>%
dplyr::filter(Activity.type != 'Gear out') %>%
dplyr::filter(Note.type %notin% c('Anchor 1', 'Anchor 2', 'Start', 'Stop')) %>%
dplyr::filter(Color.name %notin% c('PaleGreen', 'LightSalmon', 'Green', 'Red')) %>%
dplyr::rename(haul_number = Haul.no) %>%
dplyr::mutate(Mesh.color = na_if(Mesh.color,"")) %>%
dplyr::arrange(Vesselid, time.start) %>%
tidyr::fill(haul_number) %>%
dplyr::group_by(IDFD) %>%
dplyr::mutate(IDhaul = paste(IDFD, haul_number, sep = ".")) %>%
dplyr::ungroup() %>%
dplyr::mutate(haul.lon.start = NA,
haul.lat.start = NA,
haul.lon.stop = NA,
haul.lat.stop = NA) %>%
dplyr::mutate(haul.lon.start = dplyr::case_when(Activity.type == 'Gear in'~Start.longitude,.default = NA_integer_),
haul.lat.start = dplyr::case_when(Activity.type == 'Gear in'~Start.latitude,.default = NA_integer_),
haul.lon.stop = dplyr::case_when(Activity.type == 'Gear in'~End.longitude,.default = NA_integer_),
haul.lat.stop = dplyr::case_when(Activity.type == 'Gear in'~End.latitude,.default = NA_integer_)) %>%
dplyr::group_by(IDhaul) %>%
tidyr::fill(haul.lon.start) %>%
tidyr::fill(haul.lat.start) %>%
tidyr::fill(haul.lon.stop) %>%
tidyr::fill(haul.lat.stop) %>%
tidyr::fill(Distance..m.) %>%
tidyr::fill(Soaking.time..h.) %>%
dplyr::ungroup() %>%
dplyr::select(vessel = Vesselid,
date,
review.info = Review.info,
mesh.colour = Mesh.color,
netlength = Distance..m.,
soak = Soaking.time..h.,
haul_number = haul_number,
Id,
IDhaul,
IDFD,
gps,
haul.lon.start,
haul.lat.start,
haul.lon.stop,
haul.lat.stop,
lat.start = Start.latitude,
lon.start = Start.longitude,
lat.stop = End.latitude,
lon.stop = End.longitude,
time.start,
time.stop,
colour.name = Color.name,
note.type = Note.type,
comments = Note,
add.comments = Activity.comment
) %>%
dplyr::mutate(review.info = dplyr::case_when(
is.na(review.info) & is.na(mesh.colour) ~ 0,
is.na(review.info) & !is.na(mesh.colour) ~ 1,
is.na(review.info) & !is.na(colour.name) ~ 1,
.default = review.info)) %>%
dplyr::group_by(IDhaul) %>%
dplyr::mutate(review.info = if_else(rep(any(review.info == 1),
dplyr::n()), 1, review.info)
) %>%
dplyr::ungroup() %>%
dplyr::mutate(mitigation = dplyr::case_when(
colour.name == "Yellow" ~ 1,
.default = NA_integer_)) %>%
dplyr::group_by(IDhaul) %>%
tidyr::fill(mitigation) %>%
dplyr::mutate(mitigation = dplyr::if_else(is.na(mitigation),
0,
mitigation)) %>%
dplyr::ungroup() %>%
dplyr::mutate(mitigation_type = dplyr::case_when(
colour.name == "Yellow" ~ 'pinger',
#colour.name == "colour-to-define" ~ 'LED',
#colour.name == "colour-to-define" ~ 'thin-thread',
#colour.name == "colour-to-define" ~ 'other_mitigation',
.default = NA)) %>%
dplyr::group_by(IDhaul) %>%
tidyr::fill(mitigation_type) %>%
dplyr::mutate(mitigation_type = dplyr::if_else(is.na(mitigation_type),
"no mitigation",
mitigation_type)) %>%
dplyr::ungroup() %>%
## Create an event ID
dplyr::group_by(IDhaul) %>%
dplyr::mutate(ID3 = rank(haul_number,
ties.method = "first")) %>% # ID3 = note "number" (rank) per haul (sorted chronologically)
dplyr::mutate(IDevent = paste(IDhaul, "event", ID3, sep = ".")) %>%
dplyr::ungroup() %>%
dplyr::select(-ID3)
},
list_BBdata)
BBdata <- data.table::rbindlist(list_BBdata)
## Add variable IDbc
tmp.bc <- BBdata %>%
dplyr::select(c(haul_number, IDhaul, IDevent, colour.name)) %>%
dplyr::filter(colour.name %notin% c( "","Brown","DarkKhaki","DeepPink",
"Gray","LawnGreen","Orange","Purple",
"Yellow")) %>%
dplyr::group_by(IDhaul) %>%
dplyr::mutate(ID3 = rank(haul_number,
ties.method = "first")) %>% # ID3 = bycatch "number" (rank) per haul
dplyr::ungroup() %>%
dplyr::mutate(IDbc = paste(IDhaul, ID3, sep = ".")) %>%
dplyr::select(-ID3,-haul_number,-IDhaul,-colour.name)
BBdata <- merge(BBdata, tmp.bc, by = 'IDevent', all.x = TRUE) %>%
dplyr::arrange(vessel, as.Date(date), IDevent)
return(BBdata)
} |
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "IKRigDefinition.h"
#include "IKRetargeter.generated.h"
struct FIKRetargetPose;
struct UE_DEPRECATED(5.1, "Use URetargetChainSettings instead.") FRetargetChainMap;
USTRUCT()
struct IKRIG_API FRetargetChainMap
{
GENERATED_BODY()
FRetargetChainMap() = default;
FRetargetChainMap(const FName& TargetChain) : TargetChain(TargetChain){}
UPROPERTY(EditAnywhere, Category = Offsets)
FName SourceChain = NAME_None;
UPROPERTY(EditAnywhere, Category = Offsets)
FName TargetChain = NAME_None;
};
UENUM(BlueprintType)
enum class ERetargetTranslationMode : uint8
{
None UMETA(DisplayName = "None"),
GloballyScaled UMETA(DisplayName = "Globally Scaled"),
Absolute UMETA(DisplayName = "Absolute"),
};
UENUM(BlueprintType)
enum class ERetargetRotationMode : uint8
{
Interpolated UMETA(DisplayName = "Interpolated"),
OneToOne UMETA(DisplayName = "One to One"),
OneToOneReversed UMETA(DisplayName = "One to One Reversed"),
None UMETA(DisplayName = "None"),
};
UCLASS()
class IKRIG_API URetargetChainSettings: public UObject
{
GENERATED_BODY()
public:
URetargetChainSettings() = default;
URetargetChainSettings(const FName& TargetChain) : TargetChain(TargetChain){}
/** The chain on the Source IK Rig asset to copy animation FROM. */
UPROPERTY(VisibleAnywhere, Category = "Chain Mapping")
FName SourceChain = NAME_None;
/** The chain on the Target IK Rig asset to copy animation TO. */
UPROPERTY(VisibleAnywhere, Category = "Chain Mapping")
FName TargetChain = NAME_None;
/** Whether to copy the shape of the chain from the source skeleton using the Rotation and Translation modes. Default is true.
* NOTE: All FK operations run before the IK pass to copy the shape of the FK chain from the source skeleton. */
UPROPERTY(EditAnywhere, Category = "FK Adjustments")
bool CopyPoseUsingFK = true;
/** Determines how rotation is copied from the source chain to the target chain. Default is Interpolated.
* Interpolated: Source and target chains are normalized by their length, then each target bone rotation is generated by finding the rotation at the same normalized distance on the source chain and interpolating between the neighboring bones.
* One to One: Each target bone rotation is copied from the equivalent bone in the source chain, based on the order in the chain, starting at the root of the chain. If the target chain has more bones than the source, the extra bones will remain at their reference pose.
* One to One Reversed: Same as One-to-One, but starting from the tip of the chain.
* None: The rotation of each target bone in the chain is left at the reference pose. */
UPROPERTY(EditAnywhere, Category = "FK Adjustments")
ERetargetRotationMode RotationMode;
/** Range +/- infinity. Default 1. Scales the amount of rotation that is applied.
* If Rotation Mode is None this parameter has no effect.
* Otherwise, this parameter blends the rotation of each bone in the chain from the base retarget pose (0) to the retargeted pose (1).*/
UPROPERTY(EditAnywhere, Category = "FK Adjustments", meta = (UIMin = "0.0", UIMax = "1.0"))
float RotationAlpha = 1.0f;
/** Determines how translation is copied from the source chain to the target chain. Default is None.
* None: Translation of target bones are left unmodified from the retarget pose.
* Globally Scaled: Translation of target bone is set to the source bone offset multiplied by the global scale of the skeleton (determined by the relative height difference between retarget root bones).
* Absolute: Translation of target bone is set to the absolute position of the source bone. */
UPROPERTY(EditAnywhere, Category = "FK Adjustments")
ERetargetTranslationMode TranslationMode;
/** Range +/- infinity. Default 1. Scales the amount of translation that is applied. Exact behavior depends on the Translation Mode.
* In None Mode, this parameter has no effect.
* In Globally Scaled and Absolute modes, the translation offset is scaled by this parameter.*/
UPROPERTY(EditAnywhere, Category = "FK Adjustments", meta = (UIMin = "0.0", UIMax = "1.0"))
float TranslationAlpha = 1.0f;
/** Whether to modify the location of the IK goal on this chain. Default is true.
* NOTE: This only has an effect if the chain has an IK Goal assigned to it in the Target IK Rig asset.
* NOTE: If off, and this chain has an IK Goal, the IK will still be evaluated, but the Goal is set to the input bone location (from the FK pass).*/
UPROPERTY(EditAnywhere, Category = "IK Adjustments")
bool DriveIKGoal = true;
/** Range 0 to 1. Default 0. Blends IK goal position from retargeted location (0) to source bone location (1).
* At 0 the goal is placed at the retargeted location.
* At 1 the goal is placed at the location of the source chain's end bone. */
UPROPERTY(EditAnywhere, Category = "IK Adjustments", meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
float BlendToSource = 0.0f;
/** Range 0 to 1. Default 1. Weight each axis separately when using Blend To Source.
* At 0 the goal is placed at the retargeted location.
* At 1 the goal is placed at the location of the source chain's end bone. */
UPROPERTY(EditAnywhere, Category = "IK Adjustments", meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
FVector BlendToSourceWeights = FVector::OneVector;
/** Default 0, 0, 0. Apply static global-space offset to IK goal position. */
UPROPERTY(EditAnywhere, Category = "IK Adjustments")
FVector StaticOffset;
/** Range 0 to 5. Default 1. Brings IK goal closer (-) or further (+) from origin of chain.
* At 0 the effector is placed at the origin of the chain.
* Values greater than 1 will stretch the chain beyond the retargeted length. */
UPROPERTY(EditAnywhere, Category = "IK Adjustments", meta = (ClampMin = "0.0", ClampMax = "5.0", UIMin = "0.1", UIMax = "2.0"))
float Extension = 1.0f;
/** Range 0 to 1. Default 0. Blends IK goal from retargeted velocity (0) to source bone velocity (1).
* At 0 the goal is placed at the retargeted location.
* At 1 the goal is placed at the retargeted location but clamped by the velocity of the source chain's end bone.
* Values between 0 and 1 will blend the applied velocity between the retargeted amount and the source bone amount.*/
UPROPERTY(EditAnywhere, Category = "Experimental (May Change)", meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
float MatchSourceVelocity = 0.0f;
/** Range 0 to 1000. Default 5. The maximum speed a source goal can be moving before being considered statically planted.
* At 0 the goal is placed at the retargeted location.
* At 1 the goal is placed at the retargeted location but clamped by the velocity of the source chain's end bone.
* Values between 0 and 1 will blend the applied velocity between the retargeted amount and the source bone amount.*/
UPROPERTY(EditAnywhere, Category = "Experimental (May Change)", meta = (ClampMin = "0.0", ClampMax = "100.0", UIMin = "0.0", UIMax = "100.0"))
float VelocityThreshold = 5.0f;
/** Range 0 to 1. Default is 1.0. Blend IK effector at the end of this chain towards the original position
* on the source skeleton (0.0) or the position on the retargeted target skeleton (1.0). */
//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = IkMode, meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
//float IkToSourceOrTarget = 1.0f;
/** Range 0 to 1. Default 0. Allow the chain to stretch by translating to reach the IK goal locations.
* At 0 the chain will not stretch at all. At 1 the chain will be allowed to stretch double it's full length to reach IK. */
//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Stretch, meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0"))
//float StretchTolerance = 0.0f;
/** When true, the source IK position is calculated relative to a source bone and applied relative to a target bone. */
//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = IkMode)
//bool bIkRelativeToSourceBone = false;
/** A bone in the SOURCE skeleton that the IK location is relative to. */
//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = IkMode, meta = (EditCondition="bIkRelativeToSourceBone"))
//FName IkRelativeSourceBone;
/** A bone in the TARGET skeleton that the IK location is relative to.
* This is usually the same bone as the source skeleton, but may have a different name in the target skeleton. */
//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = IkMode, meta = (EditCondition="bIkRelativeToSourceBone"))
//FName IkRelativeTargetBone;
};
USTRUCT()
struct IKRIG_API FIKRetargetPose
{
GENERATED_BODY()
public:
FIKRetargetPose() = default;
UPROPERTY(EditAnywhere, Category = RetargetPose)
FVector RootTranslationOffset = FVector::ZeroVector;
UPROPERTY(EditAnywhere, Category = RetargetPose)
TMap<FName, FQuat> BoneRotationOffsets;
// returns true if this is a new offset (not previously recorded)
void SetBoneRotationOffset(FName BoneName, FQuat RotationOffset, const FIKRigSkeleton& Skeleton);
void AddTranslationDeltaToRoot(FVector TranslateDelta);
void SortHierarchically(const FIKRigSkeleton& Skeleton);
};
UCLASS(Blueprintable)
class IKRIG_API UIKRetargeter : public UObject
{
GENERATED_BODY()
public:
/** Get read-only access to the source IK Rig asset */
const UIKRigDefinition* GetSourceIKRig() const { return SourceIKRigAsset.Get(); };
/** Get read-only access to the target IK Rig asset */
const UIKRigDefinition* GetTargetIKRig() const { return TargetIKRigAsset.Get(); };
/** Get read-write access to the source IK Rig asset.
* WARNING: do not use for editing the data model. Use Controller class instead. */
UIKRigDefinition* GetSourceIKRigWriteable() const { return SourceIKRigAsset.Get(); };
/** Get read-write access to the target IK Rig asset.
* WARNING: do not use for editing the data model. Use Controller class instead. */
UIKRigDefinition* GetTargetIKRigWriteable() const { return TargetIKRigAsset.Get(); };
/** Get read-only access to the chain mapping */
const TArray<TObjectPtr<URetargetChainSettings>> GetAllChainSettings() const { return ChainSettings; };
/** Get read-only access to a retarget pose */
const FIKRetargetPose* GetCurrentRetargetPose() const { return &RetargetPoses[CurrentRetargetPose]; };
/* Get name of Source IK Rig property */
static const FName GetSourceIKRigPropertyName();
/* Get name of Target IK Rig property */
static const FName GetTargetIKRigPropertyName();
#if WITH_EDITOR
/* Get name of Target Preview Mesh property */
static const FName GetTargetPreviewMeshPropertyName();
#endif
/* Get name of default pose */
static const FName GetDefaultPoseName();
#if WITH_EDITOR
bool IsInEditRetargetPoseMode() const { return bEditRetargetPoseMode; }
#endif
virtual void PostLoad() override;
private:
/** The rig to copy animation FROM.*/
UPROPERTY(VisibleAnywhere, Category = Rigs)
TObjectPtr<UIKRigDefinition> SourceIKRigAsset = nullptr;
/** The rig to copy animation TO.*/
UPROPERTY(EditAnywhere, Category = Rigs)
TObjectPtr<UIKRigDefinition> TargetIKRigAsset = nullptr;
public:
#if WITH_EDITORONLY_DATA
/** The Skeletal Mesh to preview the retarget on.*/
UPROPERTY(EditAnywhere, Category = Rigs)
TObjectPtr<USkeletalMesh> TargetPreviewMesh = nullptr;
#endif
/** When false, translational motion of skeleton root is not copied. Useful for debugging.*/
UPROPERTY(EditAnywhere, Category = RetargetPhases)
bool bRetargetRoot = true;
/** When false, limbs are not copied via FK. Useful for debugging limb issues suspected to be caused by FK pose.*/
UPROPERTY(EditAnywhere, Category = RetargetPhases)
bool bRetargetFK = true;
/** When false, IK is not applied as part of retargeter. Useful for debugging limb issues suspected to be caused by IK.*/
UPROPERTY(EditAnywhere, Category = RetargetPhases)
bool bRetargetIK = true;
#if WITH_EDITORONLY_DATA
/** Move the target actor in the viewport for easier visualization next to the source actor.*/
UPROPERTY(EditAnywhere, Category = TargetActorPreview, meta = (UIMin = "-2000.0", UIMax = "2000.0"))
float TargetActorOffset = 150.0f;
/** Scale the target actor in the viewport for easier visualization next to the source actor.*/
UPROPERTY(EditAnywhere, Category = TargetActorPreview, meta = (UIMin = "0.01", UIMax = "10.0"))
float TargetActorScale = 1.0f;
/** The visual size of the bones in the viewport when editing the retarget pose.*/
UPROPERTY(EditAnywhere, Category = PoseEditSettings, meta = (ClampMin = "0.0", UIMin = "0.01", UIMax = "10.0"))
float BoneDrawSize = 8.0f;
private:
/** A special editor-only mode which forces the retargeter to output the current retarget reference pose,
* rather than actually running the retarget and outputting the retargeted pose. Used in Edit-Pose mode.*/
UPROPERTY()
bool bEditRetargetPoseMode = false;
/** The controller responsible for managing this asset's data (all editor mutation goes through this) */
UPROPERTY(Transient)
TObjectPtr<UObject> Controller;
#endif
private:
/** The set of retarget poses available as options for retargeting.*/
UPROPERTY()
TMap<FName, FIKRetargetPose> RetargetPoses;
/** (OLD VERSION) Mapping of chains to copy animation between source and target rigs.*/
PRAGMA_DISABLE_DEPRECATION_WARNINGS
UPROPERTY()
TArray<FRetargetChainMap> ChainMapping_DEPRECATED;
PRAGMA_ENABLE_DEPRECATION_WARNINGS
/** Settings for how to map source chains to target chains.*/
UPROPERTY()
TArray<TObjectPtr<URetargetChainSettings>> ChainSettings;
/** The set of retarget poses available as options for retargeting.*/
UPROPERTY()
FName CurrentRetargetPose = DefaultPoseName;
static const FName DefaultPoseName;
friend class UIKRetargeterController;
}; |
# Chapter 5 Exercises
Below are my solutions to the exercises presented at the end of chapter 5 of Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow.
### 1. What is the fundamental idea behind support vector machines?
The idea befind support vector machines is to fit a decision boundary in between classes that is as large as possible, allowing for some "margin violations" to maintain a more flexible model. (Soft margin classification).
### 2. What is a support vector?
Instance that determine the edge of the "street"
### 3. Why is it important to scale the inputs when using SVMs?
SVMs are sensitive to feature scale. Without scaling, the decision boundary may not look as good as it should, as the SVM will tend to neglect small features.
### 4. Can an SVM classifier output a confidence score when it classifies an instance? What about a probability?
An SVM classifier can output a confidence score based on the instances distance from the decision boundary. These cannot be directly converted into an estimation.
### 5. How can you choose between LinearSVC, SVC, and SGDClassifier?
The SVC class supports the kernel task, which allows it to handle nonlinear tasks. However, SVC does not scale well with many instances. LinearSVC uses an optimized version of linear SVMs. SGDClassifier uses stochastic gradient descent.
### 6. Say you've trained an SVM classifier with an RBF kernel, but it seems to underfit the training set. Should you increase or decrease gamma? What about C?
Increase gamma or C, or both.
### 7. What does it mean for a model to be ϵ-insensitive?
If you add instances to a SVM regression model, the model will not be affected at all.
### 8. What is the point of using the kernel trick?
The kernel trick allows a nonlinear SVM to be trained. It finds the optimal nonlinear model without needing to change the inputs at all.
### 9. Train a LinearSVC on a linearly separable dataset. Then train a SVC and a SGDClassifier on the same dataset. See if you can get them to produce roughly the same model.
### 10. Train an SVM classifier on the wine dataset, which you can load using sklearn.datasets.load_wine(). This dataset contains the chemical analyses of 178 wine samples produced by 3 different cultivators: the goal is to train a classification model capable of predicting the cultivator based on the wine’s chemical analysis. Since SVM classifiers are binary classifiers, you will need to use one-versus-all to classify all three classes. What accuracy can you reach?
### 11. Train and fine-tune an SVM regressor on the California housing dataset. You can use the original dataset rather than the tweaked version we used in Chapter 2, which you can load using sklearn.datasets.fetch_california_housing(). The targets represent hundreds of thousands of dollars. Since there are over 20,000 instances, SVMs can be slow, so for hyperparameter tuning you should use far fewer instances (e.g., 2,000) to test many more hyperparameter combinations. What is your best model’s RMSE? |
#
# (C) Tenable Network Security, Inc.
#
# The descriptive text and package checks in this plugin were
# extracted from Debian Security Advisory DSA-1759. The text
# itself is copyright (C) Software in the Public Interest, Inc.
#
include("compat.inc");
if (description)
{
script_id(36052);
script_version("$Revision: 1.11 $");
script_cvs_date("$Date: 2013/09/13 10:43:45 $");
script_cve_id("CVE-2009-0790");
script_bugtraq_id(34296);
script_osvdb_id(53208, 53209);
script_xref(name:"DSA", value:"1759");
script_name(english:"Debian DSA-1759-1 : strongswan - denial of service");
script_summary(english:"Checks dpkg output for the updated package");
script_set_attribute(
attribute:"synopsis",
value:"The remote Debian host is missing a security-related update."
);
script_set_attribute(
attribute:"description",
value:
"Gerd v. Egidy discovered that the Pluto IKE daemon in strongswan, an
IPSec implementation for linux, is prone to a denial of service attack
via a malicious packet."
);
script_set_attribute(
attribute:"see_also",
value:"http://www.debian.org/security/2009/dsa-1759"
);
script_set_attribute(
attribute:"solution",
value:
"Upgrade the strongswan packages.
For the oldstable distribution (etch), this problem has been fixed in
version 2.8.0+dfsg-1+etch1.
For the stable distribution (lenny), this problem has been fixed in
version 4.2.4-5+lenny1."
);
script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:N/I:N/A:P");
script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available");
script_set_attribute(attribute:"exploit_available", value:"false");
script_cwe_id(20);
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:strongswan");
script_set_attribute(attribute:"cpe", value:"cpe:/o:debian:debian_linux:4.0");
script_set_attribute(attribute:"cpe", value:"cpe:/o:debian:debian_linux:5.0");
script_set_attribute(attribute:"patch_publication_date", value:"2009/03/30");
script_set_attribute(attribute:"plugin_publication_date", value:"2009/03/31");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_copyright(english:"This script is Copyright (C) 2009-2013 Tenable Network Security, Inc.");
script_family(english:"Debian Local Security Checks");
script_dependencies("ssh_get_info.nasl");
script_require_keys("Host/local_checks_enabled", "Host/Debian/release", "Host/Debian/dpkg-l");
exit(0);
}
include("audit.inc");
include("debian_package.inc");
if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED);
if (!get_kb_item("Host/Debian/release")) audit(AUDIT_OS_NOT, "Debian");
if (!get_kb_item("Host/Debian/dpkg-l")) audit(AUDIT_PACKAGE_LIST_MISSING);
flag = 0;
if (deb_check(release:"4.0", prefix:"strongswan", reference:"2.8.0+dfsg-1+etch1")) flag++;
if (deb_check(release:"5.0", prefix:"strongswan", reference:"4.2.4-5+lenny1")) flag++;
if (flag)
{
if (report_verbosity > 0) security_warning(port:0, extra:deb_report_get());
else security_warning(0);
exit(0);
}
else audit(AUDIT_HOST_NOT, "affected"); |
package com.android.burdacontractor.feature.suratjalan.presentation.main
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.AppCompatButton
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import com.android.burdacontractor.R
import com.android.burdacontractor.core.domain.model.enums.CreatedByOrFor
import com.android.burdacontractor.core.utils.getDateFromMillis
import com.android.burdacontractor.core.utils.setGone
import com.android.burdacontractor.core.utils.setVisible
import com.android.burdacontractor.core.utils.withDateFormat
import com.android.burdacontractor.databinding.FragmentFilterSuratJalanListDialogBinding
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.datepicker.MaterialDatePicker
class FilterSuratJalanFragment : BottomSheetDialogFragment() {
private var onClickListener: OnClickListener? = null
private val suratJalanViewModel: SuratJalanViewModel by activityViewModels()
interface OnClickListener {
fun onClickListener()
}
fun setOnClickListener(onClickListener: OnClickListener) {
this.onClickListener = onClickListener
}
private var _binding: FragmentFilterSuratJalanListDialogBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentFilterSuratJalanListDialogBinding.inflate(inflater, container, false)
return binding.root
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val bottomSheetDialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
bottomSheetDialog.setOnShowListener { dialog: DialogInterface ->
val bsd = dialog as BottomSheetDialog
val bottomSheet =
bsd.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)
bottomSheet?.setBackgroundResource(R.drawable.semi_rounded_top_white)
}
return bottomSheetDialog
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
suratJalanViewModel.createdByOrFor.observe(viewLifecycleOwner) { createdByOrFor ->
setCurrentButtonCreatedByOrFor(createdByOrFor)
}
setCurrentDateStartAndEnd(
suratJalanViewModel.dateStart.value,
suratJalanViewModel.dateEnd.value
)
binding.btnChooseDate.setOnClickListener {
val builder = MaterialDatePicker.Builder.dateRangePicker()
builder.setTitleText("Pilih Rentang Tanggal")
val datePicker = builder.build()
datePicker.addOnPositiveButtonClickListener { selection ->
val currentDateStart = getDateFromMillis(selection.first, "yyyy/MM/dd")
val currentDateEnd = getDateFromMillis(selection.second, "yyyy/MM/dd")
setCurrentDateStartAndEnd(currentDateStart, currentDateEnd)
}
datePicker.show(requireActivity().supportFragmentManager, "DATE_PICKER")
}
binding.btnForAll.setOnClickListener {
suratJalanViewModel.setCreatedByOrFor(CreatedByOrFor.all)
setCurrentButtonCreatedByOrFor(suratJalanViewModel.createdByOrFor.value!!)
}
binding.btnForSelf.setOnClickListener {
suratJalanViewModel.setCreatedByOrFor(CreatedByOrFor.self)
setCurrentButtonCreatedByOrFor(suratJalanViewModel.createdByOrFor.value!!)
}
binding.btnResetDate.setOnClickListener {
suratJalanViewModel.setDate(null, null)
binding.tvRangeDate.text = getString(R.string.tanggal_belum_diatur)
binding.btnResetDate.setGone()
}
binding.btnAtur.setOnClickListener {
onClickListener?.onClickListener()
dismiss()
}
binding.btnClose.setOnClickListener {
dismiss()
}
}
private fun setButtonStyle(buttonSelected: AppCompatButton, buttonUnselected: AppCompatButton) {
buttonSelected.background =
AppCompatResources.getDrawable(requireContext(), R.drawable.semi_rounded_secondary_main)
buttonSelected.setTextColor(
AppCompatResources.getColorStateList(
requireContext(),
R.color.white
)
)
buttonSelected.isEnabled = false
buttonUnselected.background = AppCompatResources.getDrawable(
requireContext(),
R.drawable.semi_rounded_outline_secondary_main
)
buttonUnselected.setTextColor(
AppCompatResources.getColorStateList(
requireContext(),
R.color.secondary_main
)
)
buttonUnselected.isEnabled = true
}
private fun setCurrentButtonCreatedByOrFor(createdByOrFor: CreatedByOrFor) {
when (createdByOrFor) {
CreatedByOrFor.all -> {
setButtonStyle(binding.btnForAll, binding.btnForSelf)
}
CreatedByOrFor.self -> {
setButtonStyle(binding.btnForSelf, binding.btnForAll)
}
}
}
private fun setCurrentDateStartAndEnd(dateStart: String?, dateEnd: String?) {
dateStart?.let { start ->
dateEnd?.let { end ->
binding.btnResetDate.setVisible()
suratJalanViewModel.setDate(start, end)
val formattedStartDate = start.withDateFormat()
val formattedEndDate = end.withDateFormat()
binding.tvRangeDate.text =
getString(R.string.range_date, formattedStartDate, formattedEndDate)
}
} ?: binding.btnResetDate.setGone()
}
fun show(fragmentManager: FragmentManager) {
super.show(fragmentManager, TAG)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
val TAG = FilterSuratJalanFragment::class.java.simpleName
fun newInstance(): FilterSuratJalanFragment {
val fragment = FilterSuratJalanFragment()
val bundle = Bundle()
fragment.arguments = bundle
return fragment
}
}
} |
package com.example.lab5
import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.setPadding
import com.example.lab5.databinding.ActivitySurveyBinding
class SurveyActivity : AppCompatActivity() {
private lateinit var binding: ActivitySurveyBinding
private val surveyResponses = mutableMapOf<String, String>()
private var numOfQuestions = 0;
// Sample data structure for questions
private val dietaryHabitsQuestions = mapOf(
"Are you vegetarian?" to listOf("Yes", "No"),
"Do you prefer organic food?" to listOf("Yes", "No"),
"Do you consume diary products?" to listOf("Yes","No"),
"Do you eat fast food?" to listOf("Yes","No"),
"Do you have any food allergies?" to listOf("Yes","No"),
)
private val foodPreferencesQuestions = mapOf(
"What is your favorite cuisine?" to listOf("Chinese", "French", "Italian", "Indian", "Japanese", "Thai", "Turkish"),
"How often do you eat out?" to listOf("Never", "Rarely", "Sometimes", "Frequently"),
"Do you prefer spicy food?" to listOf("Yes", "No"),
"Do you prefer vegetarian food?" to listOf("Yes", "No"),
"Do you like seafood?" to listOf("Yes", "No")
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySurveyBinding.inflate(layoutInflater)
setContentView(binding.root)
val surveyType = intent.getStringExtra("surveyType") ?: ""
when (surveyType) {
"FoodPreferences" -> {
binding.tvSurveyTitle.text = "Food Preferences"
generateSurvey(foodPreferencesQuestions)
numOfQuestions = foodPreferencesQuestions.size
}
"DietaryHabits" -> {
binding.tvSurveyTitle.text = "Dietary Habits"
generateSurvey(dietaryHabitsQuestions)
numOfQuestions = dietaryHabitsQuestions.size
}
}
binding.btnSubmit.setOnClickListener {
displaySurveyResults()
}
}
private fun displaySurveyResults() {
val resultsBuilder = StringBuilder()
if (surveyResponses.size < numOfQuestions) {
Toast.makeText(this, "Please answer all questions", Toast.LENGTH_LONG).show()
return
}
for ((question, answer) in surveyResponses) {
resultsBuilder.append("$question: $answer\n\n")
}
binding.tvSurveyResults.text = resultsBuilder.toString()
binding.tvSurveyResults.visibility = View.VISIBLE
}
private fun generateSurvey(questionsMap: Map<String, List<String>>) {
questionsMap.forEach { (question, answers) ->
// Create a TextView for the question
val questionText = createTextView(question)
binding.linearLayoutQuestions.addView(questionText) // Add to the questions LinearLayout
// Create a RadioGroup for the answers
val radioGroup = RadioGroup(this).apply {
orientation = RadioGroup.VERTICAL
setPadding(resources.getDimension(R.dimen.padding_standard).toInt())
}
answers.forEach { answer ->
val radioButton = createRadioButton(answer)
radioGroup.addView(radioButton)
}
// Set listener for the RadioGroup to store the selected answer
radioGroup.setOnCheckedChangeListener { group, checkedId ->
val selectedAnswer = group.findViewById<RadioButton>(checkedId).text.toString()
surveyResponses[question] = selectedAnswer
}
binding.linearLayoutQuestions.addView(radioGroup) // Add to the questions LinearLayout
}
}
private fun createTextView(question: String) = TextView(this).apply {
text = question
textSize = 18f
setTypeface(typeface, Typeface.BOLD)
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
setMargins(0, 0, 0, resources.getDimension(R.dimen.margin_standard).toInt())
}
}
private fun createRadioButton(answer: String) = RadioButton(this).apply {
text = answer
layoutParams = RadioGroup.LayoutParams(
RadioGroup.LayoutParams.MATCH_PARENT,
RadioGroup.LayoutParams.WRAP_CONTENT
)
}
} |
<script lang="ts">
import { createEventDispatcher } from 'svelte'
import { getCurrencyFormatter, getDateTimeFormatter } from '$shared/formatter'
export let entry: Entry
const dispatcher = createEventDispatcher<TableEvents<Entry>>()
const select = () => dispatcher('select', entry)
const remove = () => dispatcher('remove', entry)
const currencyFormatter = getCurrencyFormatter(true)
const dateTimeFormatter = getDateTimeFormatter('medium')
</script>
<tr
class="border-b bg-white hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-800 hover:dark:bg-gray-600"
on:click={select}>
<th scope="row" class="whitespace-nowrap px-6 py-4 font-medium text-gray-900 dark:text-white">
{entry.customer}
</th>
<td class="hidden px-6 py-4 lg:block">{dateTimeFormatter.format(new Date(entry.timestamp))}</td>
<td class="px-6 py-4"> {entry.product} </td>
<td class="px-6 py-4"> {entry.description} </td>
<td class="px-6 py-4"> {currencyFormatter.format(entry.amount)} </td>
<td class="py-2">
<button
type="button"
class="rounded p-2 text-sm font-medium text-red-500 hover:underline"
on:click|stopPropagation={remove}>
Remove
</button>
</td>
</tr> |
package br.com.sicredi.votacao.application.config.handler;
import br.com.sicredi.votacao.core.exception.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import javax.validation.ConstraintViolationException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RestControllerAdvice
@Slf4j
public class ApiExceptionHandler {
@Autowired
private MessageSource messageSource;
@ExceptionHandler(RecursoNaoEncontradoException.class)
protected ResponseEntity<Object> handleRecursoNaoEncontradoException(RecursoNaoEncontradoException ex, WebRequest request){
var problema = criarProblemaBuilder(HttpStatus.NOT_FOUND, TipoProblema.RECURSO_NAO_ENCONTRADO,
"O recurso desejado não foi encontrado.")
.mensagemUsuario(ex.getMessage())
.build();
return handleExceptionInternal(ex, problema, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
@ExceptionHandler(AssociacaoDesabilitadoParaVotoException.class)
protected ResponseEntity<Object> handleAssociacaoDesabilitadoParaVotoException(AssociacaoDesabilitadoParaVotoException ex, WebRequest request) {
var problema = criarProblemaBuilder(HttpStatus.UNPROCESSABLE_ENTITY, TipoProblema.ASSOCIADO_DESABILITADO,
"CPF do associado não o permite votar.")
.mensagemUsuario(ex.getMessage())
.build();
return handleExceptionInternal(ex, problema, new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY, request);
}
@ExceptionHandler(ServicoException.class)
protected ResponseEntity<Object> handleServicoException(ServicoException ex, WebRequest request){
var problema = criarProblemaBuilder(HttpStatus.UNPROCESSABLE_ENTITY, TipoProblema.ERRO_NEGOCIO,
"O fluxo de negócio não obteve êxito.")
.mensagemUsuario(ex.getMessage())
.build();
return handleExceptionInternal(ex, problema, new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY, request);
}
@ExceptionHandler(TempoExcedidoException.class)
protected ResponseEntity<Object> handleTempoExcedidoException(TempoExcedidoException ex, WebRequest request) {
var problema = criarProblemaBuilder(HttpStatus.NOT_FOUND, TipoProblema.TEMPO_DE_SESSAO_EXPIRADO,
"O tempo para utilização do recurso expirou.")
.mensagemUsuario(ex.getMessage())
.build();
return handleExceptionInternal(ex, problema, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
@ExceptionHandler(SessaoNaoConcluidaException.class)
protected ResponseEntity<Object> handleSessaoNaoConcluidaException(SessaoNaoConcluidaException ex, WebRequest request) {
var problema = criarProblemaBuilder(HttpStatus.INTERNAL_SERVER_ERROR, TipoProblema.APLICACAO_ERRO,
"Aplicação passou por problemas.")
.mensagemUsuario(ex.getMessage())
.build();
return handleExceptionInternal(ex, problema, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
@ExceptionHandler(AssociadoJaVotouException.class)
protected ResponseEntity<Object> handleAssociadoJaVotouException(AssociadoJaVotouException ex, WebRequest request) {
var problema = criarProblemaBuilder(HttpStatus.UNPROCESSABLE_ENTITY, TipoProblema.ERRO_NEGOCIO,
"Associado já efetuou o voto.")
.mensagemUsuario(ex.getMessage())
.build();
return handleExceptionInternal(ex, problema, new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY, request);
}
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public List<MensagemErro> handleConstraintViolationException(ConstraintViolationException ex) {
log.error(TipoProblema.PARAMETRO_INVALIDO.getTitulo(), ex);
return Arrays.asList(
MensagemErro.builder()
.codigo(String.valueOf(HttpStatus.BAD_REQUEST.value()))
.mensagem("Solicitação Imprópria")
.campos(ex.getConstraintViolations().stream()
.map(constraint -> {
String jsonName = getJsonPropertyValue(
constraint.getPropertyPath().toString(), constraint.getRootBeanClass());
String nome = StringUtils.isNotBlank(jsonName) ? jsonName :
((PathImpl)constraint.getPropertyPath()).getLeafNode().getName();
String mensagem = constraint.getMessage() == null ? "Campo Obrigatório" : constraint.getMessage();
String valor = constraint.getInvalidValue() == null ? "null" : constraint.getInvalidValue().toString();
return new MensagemErro.Campo(nome, mensagem, valor);
}).collect(Collectors.toList())
)
.build());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Problema> handleValidationExceptions(
MethodArgumentNotValidException ex) {
log.error(TipoProblema.DADOS_INVALIDOS.getTitulo()
.concat(", retornando " + HttpStatus.BAD_REQUEST));
var problemType = TipoProblema.DADOS_INVALIDOS;
var detail = "Um ou mais campos estão inválidos. Faça o preenchimento correto e tente novamente.";
var bindingResult = ex.getBindingResult();
var problema = criarProblemaBuilder(HttpStatus.BAD_REQUEST, problemType, detail)
.objetos(bindingResult.getAllErrors().stream()
.map(objectError -> Problema.Objeto.builder()
.nome(objectError instanceof FieldError ?
((FieldError) objectError).getField() :
objectError.getObjectName())
.mensagemUsuario(messageSource.getMessage(objectError, LocaleContextHolder.getLocale()))
.build())
.collect(Collectors.toList()))
.build();
return ResponseEntity.badRequest().body(problema);
}
private Problema.ProblemaBuilder criarProblemaBuilder(HttpStatus status, TipoProblema tipoProblema, String detalhe){
return Problema.builder()
.status(status)
.detalhe(detalhe)
.tipo(tipoProblema.getUri())
.titulo(tipoProblema.getTitulo());
}
@SuppressWarnings("rawtypes")
public String getJsonPropertyValue(String declaredName, Class classe) {
Field[] fields = classe.getDeclaredFields();
Map<String, String> map = new HashMap<>();
for (Field field : fields) {
if (field.isAnnotationPresent(JsonProperty.class)) {
String annotationValue = field.getAnnotation(JsonProperty.class).value();
map.put(field.getName(), annotationValue);
}
}
return map.get(declaredName);
}
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute("javax.servlet.error.exception", ex, 0);
}
return new ResponseEntity<>(body, headers, status);
}
} |
/*
발상 참조 https://www.acmicpc.net/board/view/2249
x^n 을 구하는 걸 O(log n) 으로 할 수 있다.
예를들어
f(7,100,11)을 구한다면 실행되는 함수는
f(7,50,11), f(7,25,11), f(7,24,11), f(7,12,11), f(7,6,11), f(7,3,11), f(7,2,11), f(7,1,11), f(7,0,11)
이렇게 실행되고, log n 이다.
바텀업으로도 가능할 듯함
*/
import java.io.*;
import java.util.StringTokenizer;
public class Main
{
public static void main (String[] args) throws IOException
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(input.readLine(), " ");
int A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
int C = Integer.parseInt(st.nextToken());
output.write(f(A,B,C) + "");
output.close();
}
public static long f (int A, int B, int C)
{
if ( B == 0 )
return 1;
if ( B % 2 == 1 )
return ((A % C) * (f(A, B-1, C) % C)) % C;
else
{
long half = f(A, B/2, C);
return ((half % C) * (half % C)) % C;
}
}
} |
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package Controlador;
import Conexion.Conexion;
import com.mysql.jdbc.PreparedStatement;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
/**
*
* @author Usuario
*/
public class ControladorImportarAlumnos {
// Método para importar datos desde un archivo CSV a una tabla en la base de datos
public void importarCSV(String nombreArchivo) {
Conexion con = new Conexion();
// Consulta SQL para verificar si el número de control del alumno ya existe y coincide con el idMaestro
String consultaExistencia = "SELECT COUNT(*) FROM Alumno WHERE nControlAlum = ? AND idMaestro = ?";
// Consulta SQL para insertar los datos en la tabla Alumno
String sql = "INSERT INTO Alumno(nombAlum, apePatAlum, apeMatAlum, semestreAlum, fechaNacAlum, curpAlum, nControlAlum, correoAlum, idMaestro) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (BufferedReader lectorCSV = new BufferedReader(new FileReader(nombreArchivo));
PreparedStatement psConsultaExistencia = (PreparedStatement) con.prepareStatement(consultaExistencia);
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql)) {
String linea;
lectorCSV.readLine(); // Saltar la primera línea (encabezados)
while ((linea = lectorCSV.readLine()) != null) {
// Dividir la línea en campos utilizando la coma como delimitador
String[] campos = linea.split(",");
// Verificar si el número de control del alumno ya existe para el maestro especificado
psConsultaExistencia.setString(1, campos[6]); // nControlAlum
psConsultaExistencia.setInt(2, Integer.parseInt(campos[8].trim())); // idMaestro
ResultSet rsExistencia = psConsultaExistencia.executeQuery();
rsExistencia.next();
int count = rsExistencia.getInt(1);
rsExistencia.close();
if (count > 0) {
// Si el número de control del alumno ya existe, mostrar un mensaje de advertencia y continuar con el siguiente registro
JOptionPane.showMessageDialog(null, "El número de control del alumno '" + campos[6] + "' ya existe para el maestro con ID '" + campos[8] + "'. Se omitirá este registro.", "Advertencia", JOptionPane.WARNING_MESSAGE);
continue;
} else {
// Asignar los valores de los campos a los parámetros de la consulta SQL
ps.setString(1, campos[0]); // nombAlum
ps.setString(2, campos[1]); // apePatAlum
ps.setString(3, campos[2]); // apeMatAlum
ps.setInt(4, Integer.parseInt(campos[3].trim())); // semestreAlum
ps.setString(5, campos[4]); // fechaNacAlum
ps.setString(6, campos[5]); // curpAlum
ps.setString(7, campos[6]); // nControlAlum
ps.setString(8, campos[7]); // correoAlum
ps.setInt(9, Integer.parseInt(campos[8].trim())); // idMaestro
// Ejecutar la consulta SQL para insertar el registro en la tabla Alumno
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Importación completa. Los datos se han insertado en la base de datos correctamente.");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al importar registros: " + e.toString());
}
}
public void importarActCSV(String nombreArchivo) {
Conexion con = new Conexion();
// Consulta SQL para verificar si el número de control del alumno ya existe y coincide con el idMaestro
String consultaExistencia = "SELECT COUNT(*) FROM Obtiene WHERE idMat = ? && idUnidad && idAlumno = ?";
// Consulta SQL para insertar los datos en la tabla Alumno
String sql = "INSERT INTO Alumno(idMat, idUnidad, idAlumno, califFinalUni, idMaestro) VALUES (?, ?, ?, ?, ?)";
try (BufferedReader lectorCSV = new BufferedReader(new FileReader(nombreArchivo));
PreparedStatement psConsultaExistencia = (PreparedStatement) con.prepareStatement(consultaExistencia);
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql)) {
String linea;
lectorCSV.readLine(); // Saltar la primera línea (encabezados)
while ((linea = lectorCSV.readLine()) != null) {
// Dividir la línea en campos utilizando la coma como delimitador
String[] campos = linea.split(",");
// Verificar si el número de control del alumno ya existe para el maestro especificado
psConsultaExistencia.setString(1, campos[6]); // nControlAlum
psConsultaExistencia.setInt(2, Integer.parseInt(campos[8].trim())); // idMaestro
ResultSet rsExistencia = psConsultaExistencia.executeQuery();
rsExistencia.next();
int count = rsExistencia.getInt(1);
rsExistencia.close();
if (count > 0) {
// Si el número de control del alumno ya existe, mostrar un mensaje de advertencia y continuar con el siguiente registro
JOptionPane.showMessageDialog(null, "El número de control del alumno '" + campos[6] + "' ya existe para el maestro con ID '" + campos[8] + "'. Se omitirá este registro.", "Advertencia", JOptionPane.WARNING_MESSAGE);
continue;
} else {
// Asignar los valores de los campos a los parámetros de la consulta SQL
ps.setString(1, campos[0]); // nombAlum
ps.setString(2, campos[1]); // apePatAlum
ps.setString(3, campos[2]); // apeMatAlum
ps.setInt(4, Integer.parseInt(campos[3].trim())); // semestreAlum
ps.setString(5, campos[4]); // fechaNacAlum
ps.setString(6, campos[5]); // curpAlum
ps.setString(7, campos[6]); // nControlAlum
ps.setString(8, campos[7]); // correoAlum
ps.setInt(9, Integer.parseInt(campos[8].trim())); // idMaestro
// Ejecutar la consulta SQL para insertar el registro en la tabla Alumno
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Importación completa. Los datos se han insertado en la base de datos correctamente.");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al importar registros: " + e.toString());
}
}
} |
---
layout: post
title: Building A Portable Lab
---
## Introduction
This post will show you how to setup a portable lab that can house all your day to day security tools.
For quite a while I maintained two labs, one for work and one for home. Both had sets of tools that would expand apart from one another and after a while it became too cumbersome.
I had the bright spark idea loading a Windows XP virtual machine onto a USB drive and attempting to run it. It works but as soon as you do anything that required the transfer for data. The virtual machine ground to halt, as expected.
I wondered if results would be better with a Solid State Drive (SSD) and E-Sata or USB 3.0.
A co-worker finally pulled the trigger on the idea and turns out it works well so I decided to build my own.
---
## Required Components
Here are the recommended parts for a basic portable lab.
- Solid State Drive
- Sata to USB 3.0 Adapter/E-Sata
- Protect Drive Case
For my build I used the following components, these cost a total of $156 AUD.
- Samsung 850 Evo 250GB = $120
- StarTech USB 3.0 to 2.5” SATA HDD Adapter Cable = $26
- J. Burrows Portable Hard Drive Case Black = $10
I would recommend getting a 500GB+ capacity hard drive. At the time of writing this I have only 83GB free.
---
## Setup
Once you've pulled apart all the packaging and assembled the portable lab you can get down to the fun stuff.
### Encryption
Having a lab that is portable increase it's risk profile, it's much more prone to loss or theft. So you should consider deploying the same protections to it as you would a workstation.
Generally I would tell you not to keep anything confidential on a portable lab. My lab only has free tools, virtual machines and a few malware samples. So I could go without encryption but that would be against best practice.
#### VeryCrypt
The tool I decided to use was [VeraCrypt](https://veracrypt.codeplex.com/). I attempted to use BitLocker-To-Go but it turned out to have incompatibility issues.
VeraCrypt offers a [Portable Mode](https://veracrypt.codeplex.com/wikipage?title=Portable%20Mode). This allows you to run the executable without installation.
### Partitioning
To keep things simple I decided to create two partitions on the SSD.
- Public NTFS Volume (1GB)
- Private NTFS VeraCrypt volume (231GB)
This allows you to house the portable tools needed to mount the drive. You don't have to worry about having them available on any machines you decide to use the lab on.
Partitioning can all done via [Disk Management](https://support.microsoft.com/en-us/help/17418/windows-7-create-format-hard-disk-partition).
### Encrypting
Once partitioned you can move to encrypting your drive. I installed VeraCrypt using the 'Extract' method as I won't be needing it on my workstations.
Follow the below steps to encrypt your partition.
1. Select `Create Volume`.
2. Select `Encrypt a non-system partition/drive`.
3. Leave radio button checked on `Standard VeryCrypt Volume`.
4. Select `Device` and select your partition.
5. Leave radio button checked on `Create encrypted volume and format it`.
6. Leave `AES` selected under `Encryption Algorithm`, under `Hash Algorithm` select `SHA-256`.
7. Confirm your volume size.
8. Input your password, be sure to store it somewhere safe.
9. Optional, select `Use keyfiles` and select a keyfile on your choosing.
10. Under `Options` change `Filesystem` to `NTFS`.
11. Generate a random pool by moving your mouse and select `Format`.
Encrypting can take quite a while, around 1-4 hours depending on your system.
---
## Traveler Disk Setup
Once your volume is encrypted you can deploy VeraCrypt's [Traveler Disk](https://veracrypt.codeplex.com/wikipage?title=Portable%20Mode) to your public NTFS partition with the following instructions.
1. Select `Tools` and then `Traveler Disk Setup`.
2. Select `Browse` and select your partition.
3. Optional, adjust `AutoRun Configuration` settings to your requirements.
4. Select `Create`.
This will deploy a lighter version of VeraCrypt to your public volume.
---
## Mounting
Once encrypted and your portable files loaded. You can mount the partition with the following instructions.
1. Plug in your portable drive.
2. Execute `VeraCrypt.exe`.
3. Select which drive letter you want to mount your lab on.
4. Under `Volume` select `Select Device` and select your encrypted partition.
5. Select `Mount`.
6. Enter your password.
7. Optional, select `Mount Options` and adjust settings to your requirements.
8. Select `OK`.
Wait for your volume to mount, this can take a few minutes.
---
## Closing
Congratulations! You've now got a portable lab, you can now begin moving over all your tools.
I've found a portable lab to be an indispensable tool for my day to day work. Being able to have a ever changing tool set on hands at all times is a real game changer. Best of all your spend more time doing the interesting stuff and less on maintenance.
I hope you found this post informative. If you have any questions you can contact me via the [About](/about/) section.
---
## Tips
Here are some general tips I've come across after using a portable lab.
1. If you have issues mounting the drive. Check `Mount volume and removal able medium` under `Mount Options`.
2. Always be sure to use VeraCrypt to dismount your drives when finished.
3. You might use tools that get flagged as malicious. Putting them in a password protected zip file fixes this issue. |
/*
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.forestescape.renderer
import android.content.Context
import android.graphics.BitmapFactory
import android.opengl.GLES20
import android.opengl.GLUtils
import android.opengl.Matrix
import de.javagl.obj.ObjData
import de.javagl.obj.ObjReader
import de.javagl.obj.ObjUtils
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
import kotlin.math.sqrt
class ObjectRenderer {
enum class BlendMode {
Shadow,
AlphaBlending
}
private val viewLightDirection = FloatArray(4)
// Object vertex buffer variables.
private var vertexBufferId = 0
private var verticesBaseAddress = 0
private var texCoordsBaseAddress = 0
private var normalsBaseAddress = 0
private var indexBufferId = 0
private var indexCount = 0
private var program = 0
private val textures = IntArray(1)
// Shader location: model view projection matrix.
private var modelViewUniform = 0
private var modelViewProjectionUniform = 0
// Shader location: object attributes.
private var positionAttribute = 0
private var normalAttribute = 0
private var texCoordAttribute = 0
// Shader location: texture sampler.
private var textureUniform = 0
// Shader location: environment properties.
private var lightingParametersUniform = 0
// Shader location: material properties.
private var materialParametersUniform = 0
// Shader location: color correction property.
private var colorCorrectionParameterUniform = 0
// Shader location: object color property (to change the primary color of the object).
private var colorUniform = 0
// Shader location: depth texture.
private var depthTextureUniform = 0
// Shader location: transform to depth uvs.
private var depthUvTransformUniform = 0
// Shader location: the aspect ratio of the depth texture.
private var depthAspectRatioUniform = 0
private var blendMode: BlendMode? = null
// Temporary matrices allocated here to reduce number of allocations for each frame.
private val modelMatrix = FloatArray(16)
private val modelViewMatrix = FloatArray(16)
private val modelViewProjectionMatrix = FloatArray(16)
// Set some default material properties to use for lighting.
private var ambient = 0.3f
private var diffuse = 1.0f
private var specular = 1.0f
private var specularPower = 6.0f
private var useDepthForOcclusion = false
private var depthAspectRatio = 0.0f
private var uvTransform: FloatArray? = null
private var depthTextureId = 0
@Throws(IOException::class)
fun createOnGlThread(
context: Context,
objAssetName: String?,
diffuseTextureAssetName: String?
) {
compileAndLoadShaderProgram(context)
readTexture(context, diffuseTextureAssetName)
val objInputStream = context.assets.open(objAssetName!!)
var obj = ObjReader.read(objInputStream)
obj = ObjUtils.convertToRenderable(obj)
val wideIndices = ObjData.getFaceVertexIndices(obj, 3)
val vertices = ObjData.getVertices(obj)
val texCoords = ObjData.getTexCoords(obj, 2)
val normals = ObjData.getNormals(obj)
val indices = ByteBuffer.allocateDirect(2 * wideIndices.limit())
.order(ByteOrder.nativeOrder())
.asShortBuffer()
while (wideIndices.hasRemaining()) {
indices.put(wideIndices.get().toShort())
}
indices.rewind()
val buffers = IntArray(2)
GLES20.glGenBuffers(2, buffers, 0)
vertexBufferId = buffers[0]
indexBufferId = buffers[1]
verticesBaseAddress = 0
texCoordsBaseAddress = verticesBaseAddress + 4 * vertices.limit()
normalsBaseAddress = texCoordsBaseAddress + 4 * texCoords.limit()
val totalBytes = normalsBaseAddress + 4 * normals.limit()
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBufferId)
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, totalBytes, null, GLES20.GL_STATIC_DRAW)
GLES20.glBufferSubData(
GLES20.GL_ARRAY_BUFFER, verticesBaseAddress, 4 * vertices.limit(), vertices
)
GLES20.glBufferSubData(
GLES20.GL_ARRAY_BUFFER, texCoordsBaseAddress, 4 * texCoords.limit(), texCoords
)
GLES20.glBufferSubData(
GLES20.GL_ARRAY_BUFFER, normalsBaseAddress, 4 * normals.limit(), normals
)
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0)
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBufferId)
indexCount = indices.limit()
GLES20.glBufferData(
GLES20.GL_ELEMENT_ARRAY_BUFFER, 2 * indexCount, indices, GLES20.GL_STATIC_DRAW
)
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0)
ShaderUtil.checkGLError(TAG, "OBJ buffer load")
Matrix.setIdentityM(modelMatrix, 0)
}
private fun readTexture(context: Context, diffuseTextureAssetName: String?) {
val textureBitmap =
BitmapFactory.decodeStream(context.assets.open(diffuseTextureAssetName!!))
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
GLES20.glGenTextures(textures.size, textures, 0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0])
GLES20.glTexParameteri(
GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR
)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, textureBitmap, 0)
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0)
textureBitmap.recycle()
ShaderUtil.checkGLError(TAG, "Texture loading")
}
fun setBlendMode(blendMode: BlendMode?) {
this.blendMode = blendMode
}
@Throws(IOException::class)
private fun compileAndLoadShaderProgram(context: Context) {
val defineValuesMap: MutableMap<String, Int> = TreeMap()
defineValuesMap[USE_DEPTH_FOR_OCCLUSION_SHADER_FLAG] = if (useDepthForOcclusion) 1 else 0
val vertexShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_NAME)
val fragmentShader = ShaderUtil.loadGLShader(
TAG, context, GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_NAME, defineValuesMap
)
program = GLES20.glCreateProgram()
GLES20.glAttachShader(program, vertexShader)
GLES20.glAttachShader(program, fragmentShader)
GLES20.glLinkProgram(program)
GLES20.glUseProgram(program)
ShaderUtil.checkGLError(TAG, "Program creation")
modelViewUniform = GLES20.glGetUniformLocation(program, "u_ModelView")
modelViewProjectionUniform = GLES20.glGetUniformLocation(program, "u_ModelViewProjection")
positionAttribute = GLES20.glGetAttribLocation(program, "a_Position")
normalAttribute = GLES20.glGetAttribLocation(program, "a_Normal")
texCoordAttribute = GLES20.glGetAttribLocation(program, "a_TexCoord")
textureUniform = GLES20.glGetUniformLocation(program, "u_Texture")
lightingParametersUniform = GLES20.glGetUniformLocation(program, "u_LightingParameters")
materialParametersUniform = GLES20.glGetUniformLocation(program, "u_MaterialParameters")
colorCorrectionParameterUniform =
GLES20.glGetUniformLocation(program, "u_ColorCorrectionParameters")
colorUniform = GLES20.glGetUniformLocation(program, "u_ObjColor")
if (useDepthForOcclusion) {
depthTextureUniform = GLES20.glGetUniformLocation(program, "u_DepthTexture")
depthUvTransformUniform = GLES20.glGetUniformLocation(program, "u_DepthUvTransform")
depthAspectRatioUniform = GLES20.glGetUniformLocation(program, "u_DepthAspectRatio")
}
ShaderUtil.checkGLError(TAG, "Program parameters")
}
fun updateModelMatrix(modelMatrix: FloatArray?, scaleFactor: Float) {
val scaleMatrix = FloatArray(16)
Matrix.setIdentityM(scaleMatrix, 0)
scaleMatrix[0] = scaleFactor
scaleMatrix[5] = scaleFactor
scaleMatrix[10] = scaleFactor
Matrix.multiplyMM(this.modelMatrix, 0, modelMatrix, 0, scaleMatrix, 0)
}
fun setMaterialProperties(
ambient: Float, diffuse: Float, specular: Float, specularPower: Float
) {
this.ambient = ambient
this.diffuse = diffuse
this.specular = specular
this.specularPower = specularPower
}
@JvmOverloads
fun draw(
cameraView: FloatArray?,
cameraPerspective: FloatArray?,
colorCorrectionRgba: FloatArray?,
objColor: FloatArray? = DEFAULT_COLOR
) {
ShaderUtil.checkGLError(TAG, "Before draw")
Matrix.multiplyMM(modelViewMatrix, 0, cameraView, 0, modelMatrix, 0)
Matrix.multiplyMM(modelViewProjectionMatrix, 0, cameraPerspective, 0, modelViewMatrix, 0)
GLES20.glUseProgram(program)
Matrix.multiplyMV(viewLightDirection, 0, modelViewMatrix, 0, LIGHT_DIRECTION, 0)
normalizeVec3(viewLightDirection)
GLES20.glUniform4f(
lightingParametersUniform,
viewLightDirection[0],
viewLightDirection[1],
viewLightDirection[2],
1f
)
GLES20.glUniform4fv(colorCorrectionParameterUniform, 1, colorCorrectionRgba, 0)
GLES20.glUniform4fv(colorUniform, 1, objColor, 0)
GLES20.glUniform4f(materialParametersUniform, ambient, diffuse, specular, specularPower)
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0])
GLES20.glUniform1i(textureUniform, 0)
if (useDepthForOcclusion) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE1)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, depthTextureId)
GLES20.glUniform1i(depthTextureUniform, 1)
GLES20.glUniformMatrix3fv(depthUvTransformUniform, 1, false, uvTransform, 0)
GLES20.glUniform1f(depthAspectRatioUniform, depthAspectRatio)
}
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBufferId)
GLES20.glVertexAttribPointer(
positionAttribute, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, 0, verticesBaseAddress
)
GLES20.glVertexAttribPointer(
normalAttribute,
3,
GLES20.GL_FLOAT,
false,
0,
normalsBaseAddress
)
GLES20.glVertexAttribPointer(
texCoordAttribute, 2, GLES20.GL_FLOAT, false, 0, texCoordsBaseAddress
)
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0)
GLES20.glUniformMatrix4fv(modelViewUniform, 1, false, modelViewMatrix, 0)
GLES20.glUniformMatrix4fv(
modelViewProjectionUniform,
1,
false,
modelViewProjectionMatrix,
0
)
GLES20.glEnableVertexAttribArray(positionAttribute)
GLES20.glEnableVertexAttribArray(normalAttribute)
GLES20.glEnableVertexAttribArray(texCoordAttribute)
if (blendMode != null) {
GLES20.glEnable(GLES20.GL_BLEND)
when (blendMode) {
BlendMode.Shadow -> {
GLES20.glDepthMask(false)
GLES20.glBlendFunc(GLES20.GL_ZERO, GLES20.GL_ONE_MINUS_SRC_ALPHA)
}
BlendMode.AlphaBlending -> {
GLES20.glDepthMask(true)
GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA)
}
}
}
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBufferId)
GLES20.glDrawElements(GLES20.GL_TRIANGLES, indexCount, GLES20.GL_UNSIGNED_SHORT, 0)
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0)
if (blendMode != null) {
GLES20.glDisable(GLES20.GL_BLEND)
GLES20.glDepthMask(true)
}
GLES20.glDisableVertexAttribArray(positionAttribute)
GLES20.glDisableVertexAttribArray(normalAttribute)
GLES20.glDisableVertexAttribArray(texCoordAttribute)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0)
ShaderUtil.checkGLError(TAG, "After draw")
}
companion object {
private val TAG = ObjectRenderer::class.java.simpleName
private const val VERTEX_SHADER_NAME = "shaders/ar_object.vert"
private const val FRAGMENT_SHADER_NAME = "shaders/ar_object.frag"
private const val COORDS_PER_VERTEX = 3
private val DEFAULT_COLOR = floatArrayOf(0f, 0f, 0f, 0f)
private val LIGHT_DIRECTION = floatArrayOf(0.250f, 0.866f, 0.433f, 0.0f)
private const val USE_DEPTH_FOR_OCCLUSION_SHADER_FLAG = "USE_DEPTH_FOR_OCCLUSION"
private fun normalizeVec3(v: FloatArray) {
val reciprocalLength =
1.0f / sqrt((v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).toDouble())
.toFloat()
v[0] *= reciprocalLength
v[1] *= reciprocalLength
v[2] *= reciprocalLength
}
}
} |
import math
import random
import shutil
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from pathlib import Path
from typing import List, Tuple, Optional
from argparse import ArgumentParser
from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union
from collections import defaultdict
import transformers
transformers.logging.set_verbosity_error()
from transformers import BertTokenizer, AdamW
from transformers.models.bert.modeling_bert import BertOnlyMLMHead
from transformers.models.bert.modeling_bert import BertPreTrainedModel, BertEmbeddings, BertEncoder
from transformers import AutoTokenizer, AutoModel, AutoConfig, BertTokenizer,AutoModelForMaskedLM, BertConfig
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import Dataset, DataLoader
from torch.cuda.amp import autocast as autocast, GradScaler
from models.nezha.modeling_nezha import NeZhaConfig, NeZhaForMaskedLM
from masklm import MaskLM, MaskVideo, ShuffleVideo
from pretrain_utils import WarmupLinearSchedule, get_scheduler, build_optimizer, batch2cuda, create_dirs, save_model, create_dataloaders
import gc
import zipfile
from io import BytesIO
warnings.filterwarnings('ignore')
def pretrain(args):
print('Define the train dataloader')
train_dataloader = create_dataloaders(args)
model = WCUniModel(args, task=['mlm', 'itm'])
if args.device == 'cuda':
model = torch.nn.parallel.DataParallel(model.to(args.device))
# if not os.path.exists(os.path.join(args.data_cache_path)):
# read_data(args, tokenizer)
total_steps = args.num_epochs * len(train_dataloader)
optimizer, scheduler = build_optimizer(args, model, total_steps)
total_loss, cur_avg_loss, global_steps = 0., 0., 0
if args.fp16:
scaler = GradScaler()
pretrain_loss_list, global_steps_list = [], []
for epoch in range(1, args.num_epochs + 1):
train_iterator = tqdm(train_dataloader, desc=f'Epoch : {epoch}', total=len(train_dataloader))
model.train()
for step, batch in enumerate(train_iterator):
batch_cuda = batch2cuda(args, batch)
input_ids, attention_mask = batch_cuda['text_input'], batch_cuda['text_mask']
visual_embeds, visual_attention_mask = batch_cuda['frame_input'], batch_cuda['frame_mask']
if args.fp16:
with autocast():
loss, masked_lm_loss, itm_loss = model(visual_embeds, visual_attention_mask, input_ids, attention_mask)
loss = loss.mean()
masked_lm_loss = masked_lm_loss.mean()
#masked_vm_loss = masked_lm_loss.mean()
itm_loss = itm_loss.mean()
scaler.scale(loss).backward()
else:
loss, masked_lm_loss, itm_loss = model(visual_embeds, visual_attention_mask, input_ids, attention_mask)
loss = loss.mean()
masked_lm_loss = masked_lm_loss.mean()
#masked_vm_loss = masked_lm_loss.mean()
itm_loss = itm_loss.mean()
loss.backward()
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
pretrain_loss_list.append(loss.item())
global_steps_list.append(global_steps + 1)
total_loss += loss.item()
cur_avg_loss += loss.item()
if (step + 1) % args.gradient_accumulation_steps == 0:
if args.fp16:
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
if args.fp16:
scaler.step(optimizer)
scaler.update()
else:
optimizer.step()
scheduler.step()
optimizer.zero_grad()
if (global_steps + 1) % args.logging_step == 0:
epoch_avg_loss = cur_avg_loss / args.logging_step
global_avg_loss = total_loss / (global_steps + 1)
print(f"\n>> epoch - {epoch}, global steps - {global_steps + 1}, "
f"epoch avg loss - {epoch_avg_loss:.4f}, global avg loss - {global_avg_loss:.4f}.")
cur_avg_loss = 0.0
global_steps += 1
train_iterator.set_postfix_str(f'loss : {loss.item():.4f}, masked_lm_loss : {masked_lm_loss.item():.4f}, global steps : {global_steps} .')
torch.save({'epoch': epoch, 'model_state_dict': model.module.state_dict()},
f'{args.record_save_path}/model_{epoch}.bin')
del model, tokenizer, optimizer, scheduler
torch.cuda.empty_cache()
gc.collect()
def main():
args = parse_args()
setup_device(args)
setup_seed(args)
os.makedirs(args.savedmodel_path, exist_ok=True)
pretrain(args)
if __name__ == '__main__':
main() |
@page "/report"
@using System.Net.Http.Json
@using MudBlazor.Examples.Data.Models
@inject HttpClient httpClient
<div class="container-fluid px-5">
<div class="row">
<div class="col-12">
<MudTable class="customize-mud-table" Items="@Elements" Dense="true" Hover="true" Bordered="@bordered" Striped="@striped" Filter="new Func<Element,bool>(FilterFunc1)">
<ToolBarContent>
@*<MudSpacer />*@
<div class="row">
<div class="col-md-6 col-9">
<MudTextField @bind-Value="searchString1" Placeholder="Search by Name" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0 ml-0 customize-mud-search"></MudTextField>
</div>
<div class="col-md-6 col-3">
<div class="justify-content-end d-flex align-items-center">
<button type="button" class="buttoncss1 mt-2" data-bs-toggle="modal" data-bs-target="#addReportModal">Add</button>
@* Add Model *@
<div class="modal fade model-component-wrapper modal-fullscreen-sm-down" id="addReportModal" tabindex="-1" aria-labelledby="addReportModalLabel" aria-hidden="true" data-bs-backdrop="false">
<div class="modal-dialog modal-fullscreen">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addReportModalLabel">Add Report</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="workspaceId" class="form-label">Workspace Id</label>
<input type="text" class="form-control" id="workspaceId" aria-describedby="emailHelp">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="reportId" class="form-label">Report Id</label>
<input type="text" class="form-control" id="reportId" aria-describedby="emailHelp">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="datasetId" class="form-label">Dataset Id</label>
<input type="text" class="form-control" id="datasetId" aria-describedby="emailHelp">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="embeddedURL" class="form-label">Embedded URL</label>
<input type="text" class="form-control" id="embeddedURL" aria-describedby="emailHelp">
</div>
</div>
</div>
<div class="mb-3">
<label for="application" class="form-label">Application</label>
<input type="text" class="form-control" id="application" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<textarea class="form-control" id="description" rows="3"></textarea>
</div>
@*<div class="mb-3">
<label for="uploadLogo" class="form-label">Upload Logo</label>
<input class="choose-file form-control form-control-lg" type="file" id="uploadLogo" multiple>
</div>*@
@*<button class="me-2 red-btn-outline">Cancel</button>
<button variant="danger" class="ms-2 red-btn">Add</button>*@
</form>
</div>
<div class="modal-footer justify-content-start">
<button type="button" class="me-2 red-btn-outline" data-bs-dismiss="modal">Cancel</button>
<button type="button" variant="danger" class="ms-2 red-btn">Add</button>
</div>
</div>
</div>
</div>
@*Add Model end*@
@* View Model *@
<div class="modal fade model-component-wrapper modal-fullscreen-sm-down" id="viewReportModal" tabindex="-1" aria-labelledby="viewReportModalLabel" aria-hidden="true" data-bs-backdrop="false">
<div class="modal-dialog modal-fullscreen">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="viewReportModalLabel">View Report</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="" class="form-label">Name of report</label>
<p><b>Report 53464</b></p>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="reportId" class="form-label">Created Date</label>
<p><b>12/05/2022</b></p>
</div>
</div>
</div>
@*<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="datasetId" class="form-label">Dataset Id</label>
<input type="text" class="form-control" id="datasetId" aria-describedby="emailHelp">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="embeddedURL" class="form-label">Embedded URL</label>
<input type="text" class="form-control" id="embeddedURL" aria-describedby="emailHelp">
</div>
</div>
</div>*@
@*<div class="mb-3">
<label for="application" class="form-label">Application</label>
<input type="text" class="form-control" id="application" aria-describedby="emailHelp">
</div>*@
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<p>
<b>
It is a long established fact that a reader will be
distracted by the readable content of a page when
looking at its layout.
</b>
</p>
</div>
@*<div class="mb-3">
<label for="uploadLogo" class="form-label">Upload Logo</label>
<input class="choose-file form-control form-control-lg" type="file" id="uploadLogo" multiple>
</div>*@
@*<button class="me-2 red-btn-outline">Cancel</button>
<button variant="danger" class="ms-2 red-btn">Add</button>*@
</form>
</div>
<div class="modal-footer justify-content-start">
<button type="button" class="me-2 red-btn-outline" data-bs-dismiss="modal">Cancel</button>
<button type="button" variant="danger" class="ms-2 red-btn">Add</button>
</div>
</div>
</div>
</div>
@*View Model end*@
@* Delete Model *@
<div class="modal fade" id="deleteReportModal" tabindex="-1" aria-labelledby="deleteReportModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteReportModalLabel">Delete Report</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body text-center">
<svg width="55" height="55" viewBox="0 0 55 55" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M31.3971 9.75L44.8205 33C46.5526 36 44.3875 39.75 40.9234 39.75H14.0766C10.6125 39.75 8.44744 36 10.1795 33L23.6029 9.75001C25.3349 6.75 29.6651 6.75 31.3971 9.75Z" stroke="#F7BE16" stroke-width="3" />
<path d="M26.2963 21.3954C26.2463 20.2287 26.1463 18.9037 25.9963 17.4204V17.1704H27.0213C27.288 17.1704 27.5796 17.1621 27.8963 17.1454C28.213 17.1287 28.463 17.1037 28.6463 17.0704L28.6963 17.2704C28.663 17.5871 28.6296 17.9037 28.5963 18.2204C28.5796 18.5371 28.5546 18.8621 28.5213 19.1954C28.5046 19.5621 28.4796 19.9287 28.4463 20.2954C28.4296 20.6621 28.413 21.0287 28.3963 21.3954L28.0963 29.1454H26.5713L26.2963 21.3954ZM27.3213 34.8704C26.9046 34.8704 26.5463 34.7204 26.2463 34.4204C25.963 34.1204 25.8213 33.7621 25.8213 33.3454C25.8213 32.9121 25.9713 32.5537 26.2713 32.2704C26.5713 31.9871 26.9213 31.8454 27.3213 31.8454C27.7546 31.8454 28.113 31.9871 28.3963 32.2704C28.6796 32.5537 28.8213 32.9121 28.8213 33.3454C28.8213 33.7621 28.6796 34.1204 28.3963 34.4204C28.113 34.7204 27.7546 34.8704 27.3213 34.8704Z" fill="black" />
</svg>
<p class="text-center">Are you sure want to delete <span>Report 53464</span>.</p>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="me-2 red-btn-outline" data-bs-dismiss="modal">Cancel</button>
<button type="button" variant="danger" class="ms-2 red-btn">Add</button>
</div>
</div>
</div>
</div>
@*Delete Model end*@
</div>
</div>
</div>
</ToolBarContent>
<HeaderContent>
<MudTh>Name of report</MudTh>
<MudTh>Created Date</MudTh>
<MudTh><MudTableSortLabel InitialDirection="SortDirection.Ascending" SortBy="new Func<Element, object>(x=>x.Name)">Customer User</MudTableSortLabel></MudTh>
<MudTh>Public User</MudTh>
<MudTh>Description</MudTh>
<MudTh>Actions</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Nr">Dummy5667</MudTd>
<MudTd DataLabel="Sign">13/10/12</MudTd>
<MudTd DataLabel="Name">@context.Name</MudTd>
<MudTd DataLabel="Position">@context.Position</MudTd>
<MudTd DataLabel="Molar mass">@context.Molar</MudTd>
<MudTd DataLabel="Actions">
<MudTooltip Text="View">
<MudIconButton Icon="@Icons.Material.Outlined.RemoveRedEye" Style="@($"color:{Colors.Red.Darken1};")" data-bs-toggle="modal" data-bs-target="#viewReportModal" />
</MudTooltip>
<MudTooltip Text="Delete">
<MudIconButton Icon="@Icons.Material.Outlined.Delete" Style="@($"color:{Colors.Red.Darken1};")" data-bs-toggle="modal" data-bs-target="#deleteReportModal" />
</MudTooltip>
</MudTd>
</RowTemplate>
<PagerContent>
<MudTablePager class="customize-pagination" HorizontalAlignment="HorizontalAlignment.Left" />
</PagerContent>
</MudTable>
</div>
</div>
</div>
@code {
private bool dense = false;
private bool hover = true;
private bool striped = false;
private bool bordered = false;
private string searchString1 = "";
private HashSet<Element> selectedItems = new HashSet<Element>();
private IEnumerable<Element> Elements = new List<Element>();
protected override async Task OnInitializedAsync()
{
Elements = await httpClient.GetFromJsonAsync<List<Element>>("https://getdetailsfaragut-apim.azure-api.net/FarragutApis/reappraisal/beaufort");
}
private bool FilterFunc1(Element element) => FilterFunc(element, searchString1);
private bool FilterFunc(Element element, string searchString)
{
if (string.IsNullOrWhiteSpace(searchString))
return true;
if (element.Sign.Contains(searchString, StringComparison.OrdinalIgnoreCase))
return true;
if (element.Name.Contains(searchString, StringComparison.OrdinalIgnoreCase))
return true;
if ($"{element.Number} {element.Position} {element.Molar}".Contains(searchString))
return true;
return false;
}
} |
import { Entity } from './Entity.entities';
import { Ball } from './Ball.entities';
import {
randomNb,
WIDTH,
HEIGHT,
BONUS_LIFETIME,
X_BONUS_LIMIT,
Y_BONUS_LIMIT,
BONUS_WIDTH,
BONUS_HEIGHT,
SIZE_DECREASE_PATH,
SIZE_INCREASE_PATH,
REVERSE_KEYS_BONUS_PATH,
SLOWER_BONUS_PATH,
SNIPER_BONUS_PATH
}
from './utils.entities';
import { Server } from 'socket.io';
export class Bonus extends Entity {
constructor(effect: string, spawningNb: number, gameId:string, _server: Server){
super();
this.effect = effect;
this.spawningNb = spawningNb;
this.gameId = gameId;
this._server = _server;
this.init();
}
effect: string;
// image: HTMLImageElement;
imagePath: string;
spawningNb: number;
lifetime: number = BONUS_LIFETIME;
gameId: string;
_server: Server;
init()
{
switch (this.effect) {
case 'SIZE_DECREASE':
this.imagePath = SIZE_DECREASE_PATH;
break;
case 'SIZE_INCREASE':
this.imagePath = SIZE_INCREASE_PATH;
break;
case 'REVERSE_KEYS_BONUS':
this.imagePath = REVERSE_KEYS_BONUS_PATH;
break;
case 'SLOWER_BONUS':
this.imagePath = SLOWER_BONUS_PATH;
break;
case 'SNIPER_BONUS':
this.imagePath = SNIPER_BONUS_PATH;
break;
}
this.height = BONUS_HEIGHT;
this.width = BONUS_WIDTH;
}
sendBonusData(ball: Ball)
{
this.setRandBonusPos(ball);
let bonusData = {
name: this.effect,
imgURL: this.imagePath,
x: this.positionX,
y: this.positionY,
h: this.height,
w: this.width
}
this._server.to(this.gameId).emit("bonus_spawn", bonusData);
}
// randomNb(min: number, max: number): number
// {
// let randomNumber:number = min + Math.random() * (max - min);
// return (randomNumber);
// }
private randomY(min: number, max: number, ball: Ball): number
{
while (1) // finds randomNumber for Y to not be on the ball's trajectory
{
let randomNumber: number = min + Math.random() * (max - min);
if (ball.velocityX > 0) // if ball goes right
{
if (((ball.velocityY > 0))) // if ball goes down
{
if (this.positionX + BONUS_WIDTH >= ball.positionX) // if BONUS is right of the ball
{
if (randomNumber + BONUS_HEIGHT < ball.positionY) // if BONUS is not under the ball
return (randomNumber as number);
else if (BONUS_HEIGHT >= ball.positionY - Y_BONUS_LIMIT) // if BONUS cannot be above the ball
this.positionX = randomNb(X_BONUS_LIMIT, ball.positionX - BONUS_WIDTH); // forces BONUS to be left of the ball
}
else // if BONUS is left of the ball
return (randomNumber as number);
}
else // if ball goes up
{
if (this.positionX + BONUS_WIDTH >= ball.positionX) // if BONUS is right of the ball
{
if (randomNumber > ball.positionY) // if BONUS is not above the ball
return (randomNumber as number);
else if (BONUS_HEIGHT >= HEIGHT - Y_BONUS_LIMIT - ball.positionY) // if BONUS cannot be under the ball
this.positionX = randomNb(X_BONUS_LIMIT, ball.positionX - BONUS_WIDTH); // forces BONUS to be left of the ball
}
else // if BONUS is left of the ball
return (randomNumber as number);
}
}
else // if ball goes left
{
if (((ball.velocityY > 0))) // if ball goes down
{
if (this.positionX <= ball.positionX) // if BONUS left of the ball
{
if (randomNumber + BONUS_HEIGHT < ball.positionY) // if BONUS is not under the ball
return (randomNumber as number);
else if (BONUS_HEIGHT >= ball.positionY - Y_BONUS_LIMIT) // if BONUS cannot be above the ball
this.positionX = randomNb(ball.positionX, (WIDTH - BONUS_WIDTH - X_BONUS_LIMIT)); // forces BONUS to be right of the ball
}
else // if BONUS is right of the ball
return (randomNumber as number);
}
else // if ball goes up
{
if (this.positionX <= ball.positionX) // if BONUS is left of the ball
{
if (randomNumber > ball.positionY) // if BONUS is not above the ball
return (randomNumber as number);
else if (BONUS_HEIGHT >= HEIGHT - Y_BONUS_LIMIT - ball.positionY) // if BONUS cannot be under the ball
this.positionX = randomNb(ball.positionX, (WIDTH - BONUS_WIDTH - X_BONUS_LIMIT)); // forces BONUS to be right of the ball
}
else // if BONUS is right of the ball
return (randomNumber as number);
}
}
}
return (0);
}
setRandBonusPos(ball: Ball)
{
this.positionX = randomNb((X_BONUS_LIMIT), (WIDTH - BONUS_WIDTH - X_BONUS_LIMIT));
this.positionY = this.randomY(Y_BONUS_LIMIT, HEIGHT - BONUS_HEIGHT - Y_BONUS_LIMIT, ball);
}
} |
<?php
namespace App\View\Components\site;
use App\Models\Admin\Article;
use Illuminate\View\Component;
class articlecategory extends Component
{
public $articles;
/**
* Create a new component instance.
*
* @return void
*/
public function __construct($category)
{
$this->articles = Article::query()
->where('category_id', '=', $category)
->where('lang', '=', app()->getLocale())
->orderBy('id', 'desc')->limit(4)->get();
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.site.articlecategory');
}
} |
import { useNavigate } from "react-router-dom";
import PhoneIphoneIcon from "@mui/icons-material/PhoneIphone";
import LaptopIcon from "@mui/icons-material/Laptop";
import LiveTvIcon from "@mui/icons-material/LiveTv";
import CoffeeIcon from "@mui/icons-material/Coffee";
import ChildFriendlyIcon from "@mui/icons-material/ChildFriendly";
import DeckIcon from "@mui/icons-material/Deck";
import styled from "styled-components";
import { useProductSource } from "@/hooks/useProductSource";
type CategoryItem = {
id: string;
category: number;
};
const categories: CategoryItem[] = [
{ id: "phone-tablets", category: 1 },
{ id: "tv-audio-video", category: 2 },
{ id: "laptops-tablets", category: 3 },
{ id: "dishes", category: 4 },
{ id: "childrens-world", category: 5 },
{ id: "house-garden", category: 6 },
];
const TopCategory = () => {
const navigate = useNavigate();
const { setCategoryID } = useProductSource();
const handleNavigate = (category: number) => {
setCategoryID(category);
console.log("Selected Category ID:", category);
navigate("/category");
};
return (
<Main>
<h1>Top Category</h1>
<div className="card-container">
<div className="upper-card">
{categories.slice(0, 3).map((item) => (
<div
className="cards"
key={item.id}
onClick={() => handleNavigate(item.category)}
>
{getIcon(item.id)}
<p>{getCategoryName(item.id)}</p>
</div>
))}
</div>
<div className="lower-card">
{categories.slice(3).map((item) => (
<div
className="cards"
key={item.id}
onClick={() => handleNavigate(item.category)}
id={item.id === "dishes" ? "dish-id" : ""}
>
{getIcon(item.id)}
<p>{getCategoryName(item.id)}</p>
</div>
))}
</div>
</div>
</Main>
);
};
const getIcon = (id: string) => {
switch (id) {
case "phone-tablets":
return <PhoneIphoneIcon />;
case "tv-audio-video":
return <LiveTvIcon />;
case "laptops-tablets":
return <LaptopIcon />;
case "dishes":
return <CoffeeIcon />;
case "childrens-world":
return <ChildFriendlyIcon />;
case "house-garden":
return <DeckIcon />;
default:
return null;
}
};
const getCategoryName = (id: string) => {
return id.replace(/-/g, " ");
};
const Main = styled.div`
margin-top: 1.5rem;
padding: 0rem 1rem;
width: 100%;
height: 45vh;
display: flex;
justify-content: center;
align-items: flex-start;
flex-direction: column;
.card-container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 2rem;
width: 100%;
height: 100%;
.upper-card {
display: flex;
justify-content: center;
align-items: center;
gap: 1.5rem;
}
.lower-card {
display: flex;
justify-content: center;
align-items: center;
gap: 1.5rem;
}
.cards {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 0.5rem;
padding: 1.5rem 1rem;
border-radius: 15px;
width: 100%;
border: 1px solid gray;
svg {
width: 80%;
}
p {
text-align: center;
}
&[id="dish-id"] {
padding: 2rem 1rem;
}
}
}
`;
export default TopCategory; |
# Share Recipes App
## Table of Contents
- [Introduction](#introduction)
- [Features](#features)
- [Technologies Used](#technologies-used)
- [Installation](#installation)
- [Usage](#usage)
- [Admin Panel](#admin-panel)
## Introduction
Welcome to "Share Food"! This application allows users to share their favorite recipes with others. Whether you're a seasoned chef or just starting out in the kitchen, this platform provides a space to discover and exchange culinary creations.
## Features
- **User Authentication:** Users can sign up, log in, and manage their profiles.
- **Recipe Management:** Registered Users can create, edit, and delete their recipes. Not registered users can only view the recipes.
- **Search Functionality:** Users can search for recipes based on the recipe title
- **Admin Panel:** Administrators have additional privileges to manage categories, recipes and users.
- **Responsive Design:** The application is optimized for various screen sizes, ensuring a seamless experience across devices.
## Technologies Used
- **Angular:** Frontend freamwork for building the user interface.
- **Express:** Backend framework for handling server-side logic and API endpoints.
- **MongoDB:** NoSQL database fpr storing recipe data.
- **Mongoose:** MongoDB object modeling tool for Node.js.
- **JWT Authentication:** JSON Web Tokens for secure user authentication.
## Installation
To run this project locally, follow these steps:
1. Clone the repository
2. Navigate to the project directory
3. Install dependencies for both frontend and backend
4. Set up MongoDB:
- install MongoDB on your machine if you haven't already.
5. Run the application:
- start the backend server
- start the frontend server
6. Open your browser and navigate to `http://localhost:4200` to view the application.
## Usage
- Register a new account or log in if you already have one.
- Explore recipes shared by other users.
- Create your own recipes and share them.
- Edit or delete your recipes as needed.
- Use the search functionality to find recipes.
## Admin Panel
- **Manage Categories:** Add, edit, and delete recipe categories.
- **Manage Recipes:** Add, edit, and delete recipes.
- **Manage Users:** View registered users and delete them if necessary. |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Alumnado {
string private Nombre;
string private Apellido;
string private Curso;
address private Docente;
mapping (string => uint8) private NotasMaterias;
string[] private NombreMaterias;
constructor(string memory nombre_, string memory apellido_, string memory curso_)
{
Nombre = nombre_;
Apellido = apellido_;
Curso = curso_;
Docente = msg.sender;
}
function apellido() public view returns (string memory)
{
return Apellido;
}
function nombre_completo() public view returns (string memory, string memory)
{
return (Nombre, Apellido);
}
function curso() public view returns (string memory)
{
return Curso;
}
function set_nota_materia(uint8 nota, string memory materia) public
{
require(Docente == msg.sender, "Ingrese un address con permisos suficientes");
require(nota <= 100 && nota >= 1, "Nota Invalida");
NotasMaterias[materia] = nota;
NombreMaterias.push(materia);
}
function nota_materia(string memory materia) public view returns (uint)
{
uint nota = NotasMaterias[materia];
return nota;
}
function aprobo(string memory materia) public view returns (bool)
{
require (NotasMaterias[materia] >= 60);
return true;
}
function promedio() public view returns (uint)
{
uint cantItems = NombreMaterias.length;
uint notaParaPromedio;
uint notaFinal;
for (uint i = 0; i < cantItems; i++){
notaParaPromedio += NotasMaterias[NombreMaterias[i]];
}
notaFinal = notaParaPromedio / cantItems;
return notaFinal;
}
} |
import 'dart:convert';
import 'package:auto_pro/view_taxi.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:http/http.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'constants.dart';
class TaxiList extends StatefulWidget {
const TaxiList({super.key});
@override
State<TaxiList> createState() => _TaxiListState();
}
class _TaxiListState extends State<TaxiList> {
Future<dynamic> getData() async {
SharedPreferences spref = await SharedPreferences.getInstance();
var sp = spref.getString('district');
print('$sp');
var data={
"local":sp,
};
var response = await post(Uri.parse('${Con.url}taxilist.php'),body: data);
print(response.body);
var res = jsonDecode(response.body);
print(res);
return res;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.cyanAccent,
appBar: AppBar(),
body: FutureBuilder(
future: getData(),
builder: (context,snap) {
if (!snap.hasData) {
return Center(child: CircularProgressIndicator());
}
if (snap.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
return ListView.separated(
separatorBuilder: (context, index) {
return Divider();
},
itemCount: snap.data.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return TaxiView(id :'${snap.data[index]['transportation_id']}');
},));
},
child: ListTile(
title: Text('${snap.data[index]['vehicle']}'),
subtitle: Text('${snap.data[index]['seats']} seats'),
// trailing: Text('date'),
),
);
},
);
}
),
);
}
} |
"use client"
import Link from 'next/link'
import '../app/app.css'
import {RxCross2} from 'react-icons/rx'
import {useState} from 'react'
import React, { FormEvent } from 'react';
import { useRouter } from 'next/navigation'
interface EditFormProps {
title: string;
link: string;
topic: string;
difficulty: string;
notes: string;
id: number;
}
export default function EditForm({title,link,topic,difficulty,notes,id}:EditFormProps){
const [newtitle, setTitle] = useState(title);
const [newlink, setLink] = useState(link);
const [newtopic, setTopic] = useState(topic);
const [newdifficulty, setDifficulty] = useState(difficulty);
const [newnotes, setNotes] = useState(notes);
const router = useRouter();
const handleSubmit = async (e: FormEvent<HTMLFormElement>)=>{
e.preventDefault()
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/notes/${id}`, {
method:"PUT",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify({newtitle,newlink,newtopic,newdifficulty,newnotes})
})
if(res.ok){
router.push('/');
} else{
throw new Error("Failed to Create Notes")
}
} catch (error) {
console.log(error)
}
}
return(
<div className='w-screen h-screen flex justify-center items-center' >
<form className='w-3/4 lg:w-1/2 box-shadow rounded-md' onSubmit={handleSubmit}>
<div className='p-5 border-b-2 flex flex-row justify-between items-center'>
<div><h1 className='text-3xl font-bold font-sans'>Edit Notes</h1></div>
<div className='text-3xl'><Link href={'/'}><RxCross2/></Link></div>
</div>
<div className='flex flex-col justify-between items-center m-5'>
<input type="text" placeholder='Title' className='add-input' value={newtitle} onChange={(e)=>setTitle(e.target.value)}/>
<input type="text" placeholder='Link' className='add-input' value={newlink} onChange={(e)=>setLink(e.target.value)}/>
<input type="text" placeholder='Topic' className='add-input' value={newtopic} onChange={(e)=>setTopic(e.target.value)}/>
<input type="text" placeholder='Difficulty' className='add-input' value={newdifficulty} onChange={(e)=>setDifficulty(e.target.value)}/>
<textarea rows={4} placeholder='Notes' className='add-input' value={newnotes} onChange={(e)=>setNotes(e.target.value)} />
<button type='submit' className='mt-5 px-10 py-3 bg-black rounded-md text-white'>Submit</button>
</div>
</form>
</div>
)
} |
<template>
<div class="meedu-main-body">
<back-bar class="mb-30" title="直播课程分类"></back-bar>
<div class="float-left mb-30">
<p-button
text="新建分类"
@click="addCategory"
type="primary"
p="addons.Zhibo.course_category.store"
>
</p-button>
</div>
<div class="float-left" v-loading="loading">
<div class="float-left">
<el-table
:header-cell-style="{ background: '#f1f2f9' }"
:data="list"
row-key="id"
class="float-left"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
>
<el-table-column prop="sort" label="排序" width="100">
</el-table-column>
<el-table-column prop="name" label="课程名"> </el-table-column>
<el-table-column label="下属课程" width="150">
<template slot-scope="scope">
<span>{{ scope.row.courses_count }}个</span>
</template>
</el-table-column>
<el-table-column fixed="right" label="操作" width="100">
<template slot-scope="scope">
<p-link
text="编辑"
type="primary"
@click="updateCategory(scope.row.id)"
p="addons.Zhibo.course_category.update"
></p-link>
<p-link
class="ml-5"
text="删除"
type="danger"
@click="destory(scope.row.id)"
p="addons.Zhibo.course_category.delete"
></p-link>
</template>
</el-table-column>
</el-table>
</div>
</div>
<categories-dialog
:key="updateId"
v-if="showAddWin"
:categories="categories"
:text="tit"
:id="updateId"
@close="showAddWin = false"
@success="successEvt"
></categories-dialog>
</div>
</template>
<script>
import CategoriesDialog from "./components/categories-dialog";
export default {
components: {
CategoriesDialog,
},
data() {
return {
pageName: "liveCategory-list",
loading: false,
list: [],
categories: [],
showAddWin: false,
tit: null,
updateId: null,
};
},
mounted() {
this.params();
},
activated() {
this.getData();
this.$utils.scrollTopSet(this.pageName);
},
beforeRouteLeave(to, from, next) {
this.$utils.scrollTopRecord(this.pageName);
next();
},
methods: {
addCategory() {
this.tit = "新建分类";
this.updateId = null;
this.showAddWin = true;
},
updateCategory(id) {
this.tit = "编辑分类";
this.updateId = id;
this.showAddWin = true;
},
successEvt() {
this.showAddWin = false;
this.params();
this.getData();
},
params() {
this.$api.Course.Live.Course.Category.Create().then((res) => {
this.categories = res.data.categories;
});
},
getData() {
if (this.loading) {
return;
}
this.loading = true;
this.$api.Course.Live.Course.Category.List().then((res) => {
this.loading = false;
this.list = res.data;
});
},
destory(item) {
this.$confirm("确认操作?", "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
//点击确定按钮的操作
if (this.loading) {
return;
}
this.loading = true;
this.$api.Course.Live.Course.Category.Destory(item)
.then(() => {
this.loading = false;
this.$message.success(this.$t("common.success"));
this.params();
this.getData();
})
.catch((e) => {
this.loading = false;
this.$message.warning(e.message);
});
})
.catch(() => {
//点击删除按钮的操作
});
},
},
};
</script> |
package com.rarible.protocol.union.integration.ethereum.converter
import com.rarible.core.test.data.randomAddress
import com.rarible.core.test.data.randomBigDecimal
import com.rarible.core.test.data.randomBigInt
import com.rarible.protocol.dto.Erc20DecimalBalanceDto
import com.rarible.protocol.dto.EthBalanceDto
import com.rarible.protocol.union.core.converter.UnionAddressConverter
import com.rarible.protocol.union.dto.BlockchainDto
import com.rarible.protocol.union.dto.CurrencyIdDto
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import scalether.domain.Address
class EthBalanceConverterTest {
private val blockchain = BlockchainDto.ETHEREUM
@Test
fun `convert - ok, native currency`() = runBlocking<Unit> {
val ethBalance = EthBalanceDto(
owner = randomAddress(),
balance = randomBigInt(),
decimalBalance = randomBigDecimal()
)
val result = EthBalanceConverter.convert(ethBalance, blockchain)
assertThat(result.balance).isEqualTo(ethBalance.balance)
assertThat(result.decimal).isEqualTo(ethBalance.decimalBalance)
assertThat(result.owner).isEqualTo(UnionAddressConverter.convert(blockchain, ethBalance.owner.prefixed()))
assertThat(result.currencyId).isEqualTo(CurrencyIdDto(blockchain, Address.ZERO().prefixed(), null))
}
@Test
fun `convert - ok, erc20 currency`() = runBlocking<Unit> {
val ethBalance = Erc20DecimalBalanceDto(
owner = randomAddress(),
balance = randomBigInt(),
decimalBalance = randomBigDecimal(),
contract = randomAddress()
)
val result = EthBalanceConverter.convert(ethBalance, blockchain)
assertThat(result.balance).isEqualTo(ethBalance.balance)
assertThat(result.decimal).isEqualTo(ethBalance.decimalBalance)
assertThat(result.owner).isEqualTo(UnionAddressConverter.convert(blockchain, ethBalance.owner.prefixed()))
assertThat(result.currencyId).isEqualTo(CurrencyIdDto(blockchain, ethBalance.contract.prefixed(), null))
}
} |
import React, { Component } from "react";
import { getAnnotations } from "../../services/annotationServices";
import ReactTable from "react-table";
import selectTableHOC from "react-table/lib/hoc/selectTable";
import treeTableHOC from "react-table/lib/hoc/treeTable";
import "react-table/react-table.css";
const SelectTreeTable = selectTableHOC(treeTableHOC(ReactTable));
function getNodes(data, node = []) {
data.forEach(item => {
if (item.hasOwnProperty("_subRows") && item._subRows) {
node = getNodes(item._subRows, node);
} else {
node.push(item._original);
}
});
return node;
}
class Annotations extends Component {
constructor(props) {
super(props);
this.state = {
columns: [],
selection: [],
selectAll: false,
selectType: "checkbox",
expanded: {}
};
}
async componentDidMount() {
const {
data: {
ResultSet: { Result: data }
}
} = await getAnnotations(
this.props.projectId,
this.props.subjectId,
this.props.studyId,
this.props.seriesId
);
this.setState({ data });
this.setState({ columns: this.setColumns() });
}
setColumns() {
const columns = [
{
Header: "Annotation Name",
Cell: row => <div>{row.original.name}</div>
},
{
Header: "Type",
Cell: row => <div>{row.original.template}</div>
},
{
Header: "Created Date",
Cell: row => row.original.date
},
{
Header: "Identifier",
Cell: row => row.original.aimID
}
];
return columns;
}
toggleSelection = (key, shift, row) => {
/*
Implementation of how to manage the selection state is up to the developer.
This implementation uses an array stored in the component state.
Other implementations could use object keys, a Javascript Set, or Redux... etc.
*/
// start off with the existing state
if (this.state.selectType === "radio") {
let selection = [];
if (selection.indexOf(key) < 0) selection.push(key);
this.setState({ selection });
} else {
let selection = [...this.state.selection];
const keyIndex = selection.indexOf(key);
// check to see if the key exists
if (keyIndex >= 0) {
// it does exist so we will remove it using destructing
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
// it does not exist so add it
selection.push(key);
}
// update the state
this.setState({ selection });
}
};
toggleAll = () => {
/*
'toggleAll' is a tricky concept with any filterable table
do you just select ALL the records that are in your data?
OR
do you only select ALL the records that are in the current filtered data?
The latter makes more sense because 'selection' is a visual thing for the user.
This is especially true if you are going to implement a set of external functions
that act on the selected information (you would not want to DELETE the wrong thing!).
So, to that end, access to the internals of ReactTable are required to get what is
currently visible in the table (either on the current page or any other page).
The HOC provides a method call 'getWrappedInstance' to get a ref to the wrapped
ReactTable and then get the internal state and the 'sortedData'.
That can then be iterrated to get all the currently visible records and set
the selection state.
*/
const selectAll = this.state.selectAll ? false : true;
const selection = [];
if (selectAll) {
// we need to get at the internals of ReactTable
const wrappedInstance = this.selectTable.getWrappedInstance();
// the 'sortedData' property contains the currently accessible records based on the filter and sort
const currentRecords = wrappedInstance.getResolvedState().sortedData;
// we need to get all the 'real' (original) records out to get at their IDs
const nodes = getNodes(currentRecords);
// we just push all the IDs onto the selection array
nodes.forEach(item => {
selection.push(item._id);
});
}
this.setState({ selectAll, selection });
};
isSelected = key => {
/*
Instead of passing our external selection state we provide an 'isSelected'
callback and detect the selection state ourselves. This allows any implementation
for selection (either an array, object keys, or even a Javascript Set object).
*/
return this.state.selection.includes(key);
};
logSelection = () => {
console.log("selection:", this.state.selection);
};
toggleType = () => {
this.setState({
selectType: this.state.selectType === "radio" ? "checkbox" : "radio",
selection: [],
selectAll: false
});
};
toggleTree = () => {
if (this.state.pivotBy.length) {
this.setState({ pivotBy: [], expanded: {} });
} else {
this.setState({ pivotBy: [], expanded: {} });
}
};
onExpandedChange = expanded => {
this.setState({ expanded });
};
render() {
const {
toggleSelection,
toggleAll,
isSelected,
logSelection,
toggleType,
onExpandedChange,
toggleTree
} = this;
const { data, columns, selectAll, selectType, expanded } = this.state;
const extraProps = {
selectAll,
isSelected,
toggleAll,
toggleSelection,
selectType,
expanded,
onExpandedChange
};
return (
<div>
{this.state.data ? (
<SelectTreeTable
data={this.state.data}
columns={this.state.columns}
defaultPageSize={this.state.data.length}
ref={r => (this.selectTable = r)}
className="-striped -highlight"
freezWhenExpanded={false}
showPagination={false}
{...extraProps}
/>
) : null}
</div>
);
}
}
export default Annotations; |
// example store
// -------------
// a simple collection of points of interest (poi) read from a JSON file
// the collection is exposed as a Svelte store, and implemented with a JS Map (to support id-based lookup)
// the collection is also indexed with fuse.js in order to support full-text searching
import { readable, derived, get } from 'svelte/store'
import Fuse from 'fuse.js'
import type { Entity } from 'anymapper'
export const pois = readable(new Map(), function start(set) {
fetch('data/pois.json')
.then(async function (response) {
let data = await response.json()
let entities: Array<Entity> = data.map(d => ({...d, position: {...d.position, layers: new Set(d.position.layers)}, type: 'poi'}))
set( new Map(entities.map(d => [d.id, d] )) )
})
})
export const pois_index = derived(pois,
($pois) => {
const fuse = new Fuse(Array.from($pois.values()), {
ignoreLocation: true,
threshold: 0.3,
keys: [
"title",
"subtitle",
"content"
]
})
return fuse
}
)
export function search(query) {
let result: Array<Fuse.FuseResult<Entity>> = get(pois_index).search(query)
return result
} |
import React, { useState, SyntheticEvent } from "react";
import TitleActionForm from "./title-action-form";
import styled from "@emotion/styled";
import actionButtonData from "../data/actionButtonData";
import { ActionButtonType } from "./add-action-button";
import MuiCard from "@mui/material/Card";
import IconButton from "@mui/material/IconButton";
import DeleteIcon from "@mui/icons-material/Delete";
import Modal from "./modal";
import Message from "./message";
import Typography from "@mui/material/Typography";
import regexifyContent from "../utils/regexifyContent";
export default function TitleActionButton({
type,
title,
onUpdate,
onDelete,
}: {
type: ActionButtonType;
title: string;
onUpdate: (title: string) => void;
onDelete?: () => void;
}) {
const [showForm, setShowForm] = useState(false);
const [showModal, setShowModal] = useState(false);
const onClickDelete = (e: SyntheticEvent) => {
e.stopPropagation();
setShowModal(true);
};
const onCloseModal = () => setShowModal(false);
return (
<Container onClick={() => setShowForm((prev) => !prev)}>
<Card
style={
showForm
? actionButtonData[type].formCardStyle
: actionButtonData[type].textCardStyle
}
>
{showForm ? (
<TitleActionForm
type={type}
title={title}
onClose={() => setShowForm(false)}
onUpdate={onUpdate}
/>
) : (
<Typography
style={{
fontSize: 15,
color: "#182b4e",
}}
color="text.primary"
gutterBottom
>
{regexifyContent(title)}
</Typography>
)}
{type === "card" && onDelete && (
<>
<IconButton
onClick={onClickDelete}
aria-label="delete"
className="icon"
size={"small"}
style={{ position: "absolute", top: 1, right: 1 }}
>
<DeleteIcon />
</IconButton>
<Modal show={showModal} onClose={onCloseModal}>
<Message
message="해당 카드를 삭제할까요?"
accept={{ text: "네", action: onDelete }}
refuse={{ text: "아니요", action: onCloseModal }}
/>
</Modal>
</>
)}
</Card>
</Container>
);
}
const Container = styled.div`
color: #28395a;
font-size: 15px;
background-color: #eaecf0;
border-radius: 3;
width: 100%;
margin-bottom: 10px;
position: relative;
`;
const Card = styled(MuiCard)`
margin-bottom: 10px;
.icon {
visibility: hidden;
transition: 0.2s;
opacity: 0;
}
&:hover {
.icon {
visibility: visible;
opacity: 1;
}
}
`; |
import React, { useState } from "react";
import { Link } from "react-router-dom";
const Navbar = () => {
const [isNavOpen, setIsNavOpen] = useState(false);
const toggleNav = () => {
setIsNavOpen(!isNavOpen);
};
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<button className="navbar-toggler" type="button" onClick={toggleNav}>
<span className="navbar-toggler-icon"></span>
</button>
<div className={`collapse navbar-collapse ${isNavOpen ? "show" : ""}`}>
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<Link className="nav-link" to="/dashboard">
Dashboard
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/mysubjects">
My Subjects
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/attendance">
Attendance
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/timetable">
Timetable
</Link>
</li>
</ul>
</div>
</nav>
);
};
export default Navbar; |
package com.example.algorithm.sort;
import com.example.algorithm.array.ArrayFactory;
import java.util.Arrays;
/**
* @author jitwxs
* @date 2024年05月04日 15:37
*/
public class MergeSort {
public static int[] sort(int[] arr) {
if (arr != null && arr.length > 1) {
int[] left = slice(arr, 0, arr.length / 2);
int[] right = slice(arr, arr.length / 2, arr.length);
arr = merge(sort(left), sort(right));
}
return arr;
}
private static int[] merge(int[] left, int[] right) {
int[] tmp = new int[left.length + right.length];
int leftIndex = 0, rightIndex = 0;
int i = 0;
while (leftIndex < left.length && rightIndex < right.length) {
tmp[i++] = left[leftIndex] > right[rightIndex]
? right[rightIndex++] : left[leftIndex++];
}
while (leftIndex < left.length) {
tmp[i++] = left[leftIndex++];
}
while (rightIndex < right.length) {
tmp[i++] = right[rightIndex++];
}
return tmp;
}
private static int[] slice(int[] arr, int start, int end) {
int[] tmp = new int[end - start];
for (int i = 0; i < end - start; i++) {
tmp[i] = arr[i + start];
}
return tmp;
}
public static void main(String[] args) {
int[] array = ArrayFactory.createRandomArray();
System.out.println("original:" + Arrays.toString(array));
array = sort(array);
ArrayFactory.checkSortResultASC(array);
int[] array1 = ArrayFactory.createRandomAndEqualArray();
System.out.println("original:" + Arrays.toString(array1));
array1 = sort(array1);
ArrayFactory.checkSortResultASC(array1);
}
} |
// (C) University College London 2017
// This file is part of Optimet, licensed under the terms of the GNU Public License
//
// Optimet is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Optimet is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Optimet. If not, see <http://www.gnu.org/licenses/>.
#ifndef OPTIMET_RUN_H_
#define OPTIMET_RUN_H_
#include "CompoundIterator.h"
#include "Excitation.h"
#include "Geometry.h"
#include "Types.h"
#include "mpi/Communicator.h"
#include "scalapack/Context.h"
#include "scalapack/Parameters.h"
#include <array>
#include <memory>
#ifdef OPTIMET_BELOS
#include <Teuchos_ParameterList.hpp>
#include <Teuchos_ParameterListExceptions.hpp>
#endif
namespace optimet {
/**
* The Run class implements a single instance of a run.
* Run has several components:
* 1. The Geometry - needed on all nodes so must be copied.
* 2. The Excitation - specific excitation data; iteration of wavelength,
* etc. will be done using this.
* 3. The Solver - solves the problem.
* 4. The Result - the final data once request is processed.
*/
class Run {
public:
//! The Geometry of the case
std::shared_ptr<Geometry> geometry;
//! The Excitation of the case
std::shared_ptr<Excitation> excitation;
//! Parameters needed to setup parallel computations
scalapack::Parameters parallel_params;
#ifdef OPTIMET_BELOS
Teuchos::RCP<Teuchos::ParameterList> belos_params;
#endif
//! The maximum value of the n iterator
t_int nMax;
//! This bit will be moved to the case or where it is appropiate
t_int projection;
std::array<t_real, 9> params;
//! Output type required: 0 -> Field, 1 -> Cross Sections, 2 -> Scattering Coefficients
t_int outputType;
//! Output only one mode (harmonic) in the field profile
bool singleMode;
//! Index of single mode to output in the field profile
CompoundIterator singleModeIndex;
//! Get dominant mode automatically
bool dominantAuto;
//! Get only one or both components: 0 -> Both, 1 - > TE, 2 - > TM
t_int singleComponent;
scalapack::Context context;
mpi::Communicator communicator;
//! Wether to run with FMM or concrete matrix
bool do_fmm;
//! Number of subdiagonals when setting up fmm local vs non-local mpi distribution
t_int fmm_subdiagonals;
/**
* Params:
* -> for Field see OutputGrid
* -> For cross section only 3 used: params[0] - initial lambda, params[1]
* - final lambda, params[2] - number of steps
*/
/**
* Default constructor for the Case class.
* Does NOT initialize the instance.
*/
Run() : geometry(new Geometry), context(scalapack::Context::Squarest()){};
/**
* Default destructor for the Case class.
*/
virtual ~Run(){};
};
}
#endif /* RUN_H_ */ |
<?php
namespace App\Entity;
use App\Repository\ReservationRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity(repositoryClass=ReservationRepository::class)
* @UniqueEntity(fields={"nom"}, message="This reservation name is already in use.")
*/
class Reservation
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private ?int $id = null;
/**
* @ORM\Column(length=255)
* @Assert\NotBlank(message="The name cannot be empty.")
* @Assert\Length(
* max=255,
* maxMessage="The name must not exceed {{ limit }} characters."
* )
*/
private ?string $nom = null;
/**
* @ORM\Column(type=Types::DATE_MUTABLE)
* @Assert\NotNull(message="The start date cannot be null.")
* @Assert\Type(\DateTimeInterface::class)
*/
private ?\DateTimeInterface $datedebutres = null;
/**
* @ORM\Column(type=Types::DATE_MUTABLE)
* @Assert\NotNull(message="The end date cannot be null.")
* @Assert\Type(\DateTimeInterface::class)
* @Assert\GreaterThan(propertyPath="datedebutres", message="The end date must be after the start date.")
*/
private ?\DateTimeInterface $datefinres = null;
/**
* @ORM\Column(length=255)
* @Assert\NotBlank(message="The type cannot be empty.")
* @Assert\Length(
* max=255,
* maxMessage="The type must not exceed {{ limit }} characters."
* )
*/
private ?string $type = null;
/**
* @ORM\Column(type="float")
* @Assert\NotNull(message="The deposit cannot be null.")
* @Assert\PositiveOrZero(message="The deposit must be zero or a positive number.")
*/
private ?float $deposit = null;
/**
* @ORM\ManyToOne(inversedBy="reservations")
* @ORM\JoinColumn(name="id_equipement", referencedColumnName="id")
* @Assert\NotNull(message="The equipment cannot be null.")
*/
private ?Equipement $idEquipement = null;
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(?string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getDatedebutres(): ?\DateTimeInterface
{
return $this->datedebutres;
}
public function setDatedebutres(?\DateTimeInterface $datedebutres): self
{
$this->datedebutres = $datedebutres;
return $this;
}
public function getDatefinres(): ?\DateTimeInterface
{
return $this->datefinres;
}
public function setDatefinres(?\DateTimeInterface $datefinres): self
{
$this->datefinres = $datefinres;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): self
{
$this->type = $type;
return $this;
}
public function getDeposit(): ?float
{
return $this->deposit;
}
public function setDeposit(?float $deposit): self
{
$this->deposit = $deposit;
return $this;
}
public function getIdEquipement(): ?Equipement
{
return $this->idEquipement;
}
public function setIdEquipement(?Equipement $idEquipement): self
{
$this->idEquipement = $idEquipement;
return $this;
}
} |
<?php
namespace Drupal\iiif_media_source\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
/**
* IIIF ID Widget.
*
* @FieldWidget(
* id = "iiif_id_widget",
* label = @Translation("IIIF ID Widget"),
* field_types = {
* "iiif_id"
* }
* )
*/
class IiifIdWidget extends WidgetBase implements ContainerFactoryPluginInterface {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'size' => 60,
'placeholder' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['size'] = [
'#type' => 'number',
'#title' => $this->t('Size of textfield'),
'#default_value' => $this->getSetting('size'),
'#required' => TRUE,
'#min' => 1,
];
$element['placeholder'] = [
'#type' => 'textfield',
'#title' => $this->t('Placeholder'),
'#default_value' => $this->getSetting('placeholder'),
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
];
return $element;
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['value'] = $element + [
'#type' => 'textfield',
'#default_value' => $items[$delta]->value ?? NULL,
'#size' => $this->getSetting('size'),
'#placeholder' => $this->getSetting('placeholder'),
'#maxlength' => $this->getFieldSetting('max_length'),
'#attributes' => ['class' => ['js-text-full', 'text-full']],
];
$element['info'] = [
'#type' => 'hidden',
"#default_value" => $items[$delta]->info,
];
return $element;
}
} |
/*
* Project: Car Rev Alarm and Gear Indicator
* Author: Zak Kemble, contact@zakkemble.co.uk
* Copyright: (C) 2017 by Zak Kemble
* License: GNU GPL v3 (see License.txt)
* Web: http://blog.zakkemble.co.uk/car-rev-alarm-and-gear-indicator/
*/
#include <mcp_can.h>
#include <SPI.h>
#include <EEPROM.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#define SERIAL_ENABLE 0
// These gear ratios are for a manual Honda Civic Type-S GT 2006 Hatchback
static float gearRatios[] = {
3.142,
1.869,
1.303,
1.054,
0.853,
0.727 // If your vehicle has 5 gears then remove this line, if it has more than 6 then just add them to the array
};
#define RATIO_FINAL 4.294 // Final drive ratio
#define WHEEL_CIRCUMFERENCE 192 //200 // Wheel circumference in centimeters, also used for fine tuning
#define CAN0_SPEED CAN_500KBPS
#define CAN0_FOSC MCP_8MHZ
#define PIN_CAN0_INT 8
#define PIN_BUZZER 9
#define PIN_CAN0_SS 10
#define PIN_SWITCH1 A0
#define PIN_SWITCH2 A1
#define PIN_LDR A2
// NOTE:
// LED and MCP2561 standby are controlled via the crystal pins B6 and B7
// These are bit positions for PORTD
// They also happen to match up with the Arduino Uno pin numbers that map to PORTD
#define PIN_7SEG_A 5
#define PIN_7SEG_B 4
#define PIN_7SEG_C 1
#define PIN_7SEG_D 2
#define PIN_7SEG_E 3
#define PIN_7SEG_F 6
#define PIN_7SEG_G 7
#define PIN_7SEG_DP 0
#define PID_ID_EXTENDED 1
#define PID_ID 0x18DB33F1 // 0x7DF // Address to send requests to
#define PID_ID_RECV 0x18DAF110 // Address to receive replies from
#define DATA_PAD 0x55
#define PID_MODE_CURR_DATA 0x01
#define PID_ENGINE_RPM 0x0C
#define PID_VEHICLE_SPEED 0x0D
#define PID_NONE 0xFF
#define NUM_GEARS (sizeof(gearRatios) / sizeof(float))
#define NUM_BTNS 2
#define CAN_TIMEOUT 200
#define CAN_REQINTERVAL 200
#define SLEEP_TIMEOUT 3000
#define EEPROM_ADDR_REV 1 // Size: 2 bytes
#define EEPROM_ADDR_7SEG 3 // Size: 1 byte
#define CAN_INTASSERTED() (digitalRead(PIN_CAN0_INT) == LOW)
// LED and CANTRX standby control are connected to the crystal pins, which Arduino digitalRead/digitalWrite/pinMode doesn't support by default
// So we have to do some manual port manipulation
#define LED_ON() PORTB |= _BV(PORTB7)
#define LED_OFF() PORTB &= ~_BV(PORTB7)
#define CANTRX_DISABLE() PORTB |= _BV(PORTB6)
#define CANTRX_ENABLE() PORTB &= ~_BV(PORTB6)
#define XTAL_PIN_CFG() DDRB |= _BV(DDB7)|_BV(DDB6)
#define PORT7SEGOFF 0xFF
typedef unsigned int tune_t;
static byte segChars[] = {
_BV(PIN_7SEG_A)|_BV(PIN_7SEG_B)|_BV(PIN_7SEG_C)|_BV(PIN_7SEG_D)|_BV(PIN_7SEG_E)|_BV(PIN_7SEG_F), // 0
_BV(PIN_7SEG_B)|_BV(PIN_7SEG_C), // 1
_BV(PIN_7SEG_A)|_BV(PIN_7SEG_B)|_BV(PIN_7SEG_D)|_BV(PIN_7SEG_E)|_BV(PIN_7SEG_G), // 2
_BV(PIN_7SEG_A)|_BV(PIN_7SEG_B)|_BV(PIN_7SEG_C)|_BV(PIN_7SEG_D)|_BV(PIN_7SEG_G), // 3
_BV(PIN_7SEG_B)|_BV(PIN_7SEG_C)|_BV(PIN_7SEG_F)|_BV(PIN_7SEG_G), // 4
_BV(PIN_7SEG_A)|_BV(PIN_7SEG_C)|_BV(PIN_7SEG_D)|_BV(PIN_7SEG_F)|_BV(PIN_7SEG_G), // 5
_BV(PIN_7SEG_A)|_BV(PIN_7SEG_C)|_BV(PIN_7SEG_D)|_BV(PIN_7SEG_E)|_BV(PIN_7SEG_F)|_BV(PIN_7SEG_G), // 6
_BV(PIN_7SEG_A)|_BV(PIN_7SEG_B)|_BV(PIN_7SEG_C), // 7
_BV(PIN_7SEG_A)|_BV(PIN_7SEG_B)|_BV(PIN_7SEG_C)|_BV(PIN_7SEG_D)|_BV(PIN_7SEG_E)|_BV(PIN_7SEG_F)|_BV(PIN_7SEG_G), // 8
_BV(PIN_7SEG_A)|_BV(PIN_7SEG_B)|_BV(PIN_7SEG_C)|_BV(PIN_7SEG_D)|_BV(PIN_7SEG_F)|_BV(PIN_7SEG_G), // 9
};
typedef enum
{
TONE_STOP = 0,
TONE_PAUSE = 1,
TONE_REPEAT = 2,
TONE_2KHZ = 250,
TONE_2_5KHZ = 200,
TONE_3KHZ = 166,
TONE_3_5KHZ = 143,
TONE_4KHZ = 125,
TONE_4_5KHZ = 111,
TONE_5KHZ = 100,
} tone_t;
static const tune_t tuneRevAlarm[] PROGMEM = {
TONE_4KHZ<<8 | 200,
TONE_PAUSE<<8 |50,
TONE_4KHZ<<8 | 80,
TONE_PAUSE<<8 | 50,
TONE_4KHZ<<8 | 80,
TONE_STOP
};
static const tune_t tuneBtnSuccess[] PROGMEM = {
TONE_4KHZ<<8 | 80,
TONE_PAUSE<<8 | 50,
TONE_4_5KHZ<<8 | 80,
TONE_STOP
};
/*
static const tune_t tuneBtnFail[] PROGMEM = {
TONE_4KHZ<<8 | 80,
TONE_PAUSE<<8 | 50,
(tune_t)(TONE_2KHZ<<8 | 200), // Cast because the compiler was moaning about 'narrowing conversion of '-1336' from 'int' to 'const tune_t {aka const unsigned int}' inside { }'
TONE_STOP
};
*/
static MCP_CAN CAN0(PIN_CAN0_SS);
static unsigned int lastActivity;
static volatile byte portValue7Seg;
static volatile byte pinValueLed;
static bool displayEnabled;
static unsigned int rpm;
static byte speed;
static byte gear;
static bool revAlarmTriggered;
static byte mode7Seg;
static unsigned int revAlarmValue;
static byte tuneIdx; // Position in tune
static const tune_t* tune; // The tune
static byte buzzLen;
static byte buzzStartTime;
static void pinSetup(void)
{
pinMode(PIN_CAN0_INT, INPUT_PULLUP);
pinMode(PIN_SWITCH1, INPUT_PULLUP);
pinMode(PIN_SWITCH2, INPUT_PULLUP);
pinMode(PIN_LDR, INPUT_PULLUP);
pinMode(PIN_BUZZER, OUTPUT);
XTAL_PIN_CFG();
CANTRX_ENABLE();
portValue7Seg = PORT7SEGOFF;
PORTD = PORT7SEGOFF;
pinMode(PIN_7SEG_A, OUTPUT);
pinMode(PIN_7SEG_B, OUTPUT);
pinMode(PIN_7SEG_C, OUTPUT);
pinMode(PIN_7SEG_D, OUTPUT);
pinMode(PIN_7SEG_E, OUTPUT);
pinMode(PIN_7SEG_F, OUTPUT);
pinMode(PIN_7SEG_G, OUTPUT);
pinMode(PIN_7SEG_DP, OUTPUT);
// Unused pins
pinMode(A3, INPUT_PULLUP);
pinMode(A4, INPUT_PULLUP);
pinMode(A5, INPUT_PULLUP);
}
static void timerSetup(void)
{
// Timer1 buzzer
TCCR1A = _BV(WGM11);
TCCR1B = _BV(CS10)|_BV(WGM13);
OCR1A = 512;
ICR1 = 512 * 2;
// Timer2 brightness
TCCR2A = 0;
TCCR2B = _BV(CS21)|_BV(CS20);
TIMSK2 = _BV(OCIE2A)|_BV(TOIE2);
OCR2A = 127;
}
void setup()
{
clock_prescale_set(clock_div_1);
pinSetup();
timerSetup();
// Pin change interrupt for CAN controller and buttons
PCMSK0 |= _BV(PCINT0);
PCMSK1 |= _BV(PCINT8)|_BV(PCINT9);
PCICR |= _BV(PCIE0)|_BV(PCIE1);
//attachInterrupt(digitalPinToInterrupt(PIN_CAN0_INT), ISR_CAN, FALLING);
// Turn ADC off (ADEN) and set prescaler to 32 instead of 128
ADCSRA = _BV(ADPS2)|_BV(ADPS0);
power_twi_disable();
power_timer1_disable();
power_timer2_disable();
power_adc_disable();
ACSR |= _BV(ACD);
LED_OFF();
delay(50);
LED_ON();
delay(50);
LED_OFF();
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
#if SERIAL_ENABLE
Serial.begin(115200);
#endif
#if SERIAL_ENABLE
if(CAN0.begin(MCP_STDEXT, CAN0_SPEED, CAN0_FOSC) == CAN_OK)
Serial.println(F("MCP2515 Initialized Successfully!"));
else
Serial.println(F("Error Initializing MCP2515..."));
#else
CAN0.begin(MCP_STDEXT, CAN0_SPEED, CAN0_FOSC);
#endif
// We only want to process frames with ID PID_ID_RECV
// Masks are set to 0x1FFFFFFF so that all bits in the ID are examined to get an exact match
CAN0.init_Mask(0, 1, 0x1FFFFFFF);
CAN0.init_Mask(1, 1, 0x1FFFFFFF);
for(byte i=0;i<6;i++)
CAN0.init_Filt(i, 1, PID_ID_RECV);
CAN0.setMode(MCP_NORMAL);
CAN0.setSleepWakeup(1);
// Load saved values
EEPROM.get(EEPROM_ADDR_REV, revAlarmValue);
EEPROM.get(EEPROM_ADDR_7SEG, mode7Seg);
//revAlarmValue = 6000;
#if SERIAL_ENABLE
Serial.print(F("Rev: "));
Serial.println(revAlarmValue);
Serial.print(F("7 Seg mode: "));
Serial.println(mode7Seg);
#endif
}
void loop()
{
CANStuff();
display_update();
buttons();
buzzer_update();
ldr();
sleep();
}
static void display_update()
{
if(mode7Seg == 0) // Off
portValue7Seg = PORT7SEGOFF;
else if(mode7Seg == 1) // Gear
{
if(gear > 0 && gear <= NUM_GEARS)
portValue7Seg = ~segChars[gear];
else
portValue7Seg = (byte)~_BV(PIN_7SEG_G); // - (dash)
}
else if(mode7Seg == 2) // RPM
{
byte val = (rpm + 500) / 1000; // Round to nearest 1000
if(val < 10)
portValue7Seg = ~segChars[val];
else
portValue7Seg = (byte)~_BV(PIN_7SEG_G); // - (dash)
}
pinValueLed = revAlarmTriggered;
}
static void display_enable()
{
if(!displayEnabled)
{
power_timer2_enable();
displayEnabled = true;
}
}
static void display_disable()
{
if(displayEnabled)
{
power_timer2_disable();
PORTD = PORT7SEGOFF;
LED_OFF();
displayEnabled = false;
//timer2on = 0;
}
}
static void display_setBrightness(byte brightness)
{
if(displayEnabled)
{
if(brightness == 255)
{
power_timer2_disable();
PORTD = portValue7Seg;
pinValueLed ? LED_ON() : LED_OFF();
}
else
{
power_timer2_enable();
OCR2A = ~brightness;
}
}
}
static void btnPress1()
{
// if(speed == 0)
// {
// Only set rev alarm value if the vehicle is not moving
revAlarmValue = rpm;
EEPROM.put(EEPROM_ADDR_REV, revAlarmValue);
tune_play(tuneBtnSuccess);
// }
// else
// tune_play(tuneBtnFail);
}
static void btnPress2()
{
// Change display mode
mode7Seg++;
if(mode7Seg > 2)
mode7Seg = 0;
EEPROM.put(EEPROM_ADDR_7SEG, mode7Seg);
tune_play(tuneBtnSuccess);
}
static bool buttons_busy()
{
return !(digitalRead(PIN_SWITCH1) && digitalRead(PIN_SWITCH2));
}
static void buttons()
{
static bool btnState[NUM_BTNS];
static unsigned int btnTime[NUM_BTNS];
static bool btnDebounceOk[NUM_BTNS];
bool btnStateNow[NUM_BTNS];
// Get pin input states
btnStateNow[0] = !digitalRead(PIN_SWITCH1);
btnStateNow[1] = !digitalRead(PIN_SWITCH2);
unsigned int now = millis();
for(byte i=0;i<NUM_BTNS;i++)
{
if(btnStateNow[i]) // Button is currently pressed
{
lastActivity = now;
display_enable();
btnTime[i] = now;
if(!btnState[i]) // Button has just been pressed (was released lat time it was checked)
{
if(btnDebounceOk[i])
{
btnDebounceOk[i] = false;
switch(i)
{
case 0:
btnPress1();
break;
case 1:
btnPress2();
break;
default:
break;
}
}
}
}
else // Not pressed (or bouncing)
{
if((byte)(now - btnTime[i]) >= 50) // If last press was over 50ms ago then we're now ready for another press
btnDebounceOk[i] = true;
}
btnState[i] = btnStateNow[i];
}
}
static void tune_play(const tune_t* _tune)
{
tune = _tune;
tuneIdx = 0;
// Begin playing
tune_next();
}
/*
static void tune_stop()
{
buzzer_buzz(TONE_STOP, 0);
}
*/
static void tune_next()
{
// Read next tone
unsigned int data = pgm_read_word(&tune[tuneIdx++]);
byte len = data;
if(len != TONE_REPEAT)
buzzer_buzz((tone_t)(data>>8), len); // Play next tone
else
{
// Repeat
tuneIdx = 0;
tune_next();
}
}
static void buzzer_buzz(tone_t tone, byte len)
{
if(tone == TONE_STOP)
{
buzzer_stop();
return;
}
buzzLen = len;
buzzStartTime = millis();
// Silent pause tone
if(tone == TONE_PAUSE)
{
TCCR1A &= ~(_BV(COM1A1)|_BV(COM1A0));
power_timer1_disable();
return;
}
unsigned int icr = tone * 8;
unsigned int ocr = tone * 4;
power_timer1_enable();
//TIFR1 = 0;
//TIMSK1 |= _BV(TOIE1);
TCNT1 = 0;
OCR1A = ocr;
ICR1 = icr;
TCCR1A |= _BV(COM1A1)|_BV(COM1A0);
}
static void buzzer_update()
{
if(buzzLen && (byte)(millis() - buzzStartTime) >= buzzLen)
tune_next();
}
static void buzzer_stop()
{
TCCR1A &= ~(_BV(COM1A1)|_BV(COM1A0));
power_timer1_disable();
buzzLen = 0;
}
static void ldr()
{
if(!displayEnabled)
return;
static byte lastRead;
if((byte)(millis() - lastRead) < 50)
return;
lastRead = millis();
power_adc_enable();
ADCSRA |= _BV(ADEN);
unsigned int val = analogRead(PIN_LDR);
ADCSRA &= ~_BV(ADEN);
power_adc_disable();
// Brighter = lower value
// 10 = Very bright
// 800 = Very dark
display_setBrightness(map(constrain(val, 60, 650), 60, 650, 255, 5));
#if SERIAL_ENABLE
// Serial.print(F("LDR: "));
// Serial.println(val);
#endif
}
static void sleep()
{
if((unsigned int)(millis() - lastActivity) < SLEEP_TIMEOUT)
return;
else if(CAN_INTASSERTED() || buzzLen || buttons_busy())
return;
/*
// TODO debugging
display_enable();
pinValueLed = 0;
delay(50);
pinValueLed = 1;
delay(50);
//pinValueLed = 0;
*/
#if SERIAL_ENABLE
Serial.println(F("SLEEP"));
#endif
CAN0.setMode(MCP_SLEEP);
#if SERIAL_ENABLE
Serial.flush();
#endif
display_disable();
speed = 0;
rpm = 0;
gear = 0;
revAlarmTriggered = 0;
cli();
if(!CAN_INTASSERTED() && !buttons_busy())
{
//pinValueLed = 0;
//LED_OFF();
//PORTD = PORT7SEGOFF;
pinMode(PIN_LDR, INPUT);
CANTRX_DISABLE();
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();
sleep_disable();
CANTRX_ENABLE();
pinMode(PIN_LDR, INPUT_PULLUP);
lastActivity = millis();
}
sei();
// Timer2 will be enabled later if a valid reponse from the ECU is received
//power_timer2_enable();
#if SERIAL_ENABLE
Serial.println(F("WAKE"));
#endif
CAN0.setMode(MCP_NORMAL);
}
static void revAlarm()
{
if(rpm >= revAlarmValue)
{
if(!revAlarmTriggered)
{
revAlarmTriggered = true;
tune_play(tuneRevAlarm);
}
}
else
revAlarmTriggered = false;
}
static void calcGear()
{
gear = 0;
if(speed == 0 || rpm == 0)
return;
// TODO 1666.66 is so we use kilometers per hour instead of cm per minute??
// I can't remember how I got this value lol
float currentGearRatio = rpm / (((1666.66f / WHEEL_CIRCUMFERENCE) * RATIO_FINAL) * speed);
// TODO
// Need to allow a larger difference at lower speeds since the speed is
// in whole kph numbers and doesn't change much, while the RPM can change a lot
float allowableRange;
if(speed < 26)
allowableRange = (((float)speed + 1) / (float)speed) + 0.01f;
else
allowableRange = 1.05f; // 5%
#if SERIAL_ENABLE
// Serial.print(allowableRange);
// Serial.print(F(","));
#endif
while(1)
{
if(gear >= NUM_GEARS)
{
gear = 0;
break;
}
float diff = gearRatios[gear] / currentGearRatio;
gear++;
if(diff < allowableRange && diff > 2 - allowableRange)
break;
}
}
static void CANStuff()
{
static bool waitingForResponse;
static unsigned int requestSentTime;
static byte nextPIDRequest = PID_NONE;
unsigned int now = millis();
if(!CAN_INTASSERTED())
{
if(waitingForResponse && (unsigned int)(now - requestSentTime) >= CAN_TIMEOUT)
{
// Request timed out, restart PID request batch
waitingForResponse = false;
nextPIDRequest = PID_NONE;
requestSentTime = now - CAN_REQINTERVAL;
#if SERIAL_ENABLE
Serial.println(F("CAN Request timed out"));
#endif
}
}
else
{
unsigned long rxId;
byte len;
byte rxBuf[CAN_MAX_CHAR_IN_MESSAGE];
#if SERIAL_ENABLE
Serial.println(F("Checking for messages..."));
#endif
if(CAN0.readMsgBuf(&rxId, &len, rxBuf) == CAN_OK)
{
#if SERIAL_ENABLE
char msgString[128];
if(rxId & CAN_IS_EXTENDED) // Determine if ID is standard (11 bits) or extended (29 bits)
sprintf_P(msgString, PSTR("Extended ID: 0x%.8lX DLC: %hhu Data:"), (rxId & CAN_EXTENDED_ID), len);
else
sprintf_P(msgString, PSTR("Standard ID: 0x%.3lX DLC: %hhu Data:"), rxId, len);
Serial.print(msgString);
for(byte i=0;i<len;i++)
{
sprintf_P(msgString, PSTR(" 0x%.2X"), rxBuf[i]);
Serial.print(msgString);
}
Serial.println();
#endif
if(
(rxId & CAN_EXTENDED_ID) == PID_ID_RECV &&
rxBuf[1] == (PID_MODE_CURR_DATA | 0x40)
)
{
//power_timer0_disable();
lastActivity = now;
display_enable();
if(rxBuf[2] == PID_ENGINE_RPM)
{
rpm = rxBuf[3]<<8 | rxBuf[4];
rpm /= 4;
#if SERIAL_ENABLE
Serial.print(F("*RPM: "));
Serial.println(rpm);
#endif
revAlarm();
waitingForResponse = false;
}
else if(rxBuf[2] == PID_VEHICLE_SPEED)
{
speed = rxBuf[3];
#if SERIAL_ENABLE
Serial.print(F("*MPH: "));
Serial.println(speed * 0.621371f);
#endif
calcGear(); // PID_VEHICLE_SPEED is the last of the batch, now work out gear
waitingForResponse = false;
#if SERIAL_ENABLE
//Serial.begin(115200);
Serial.print(rpm);
Serial.print(F(","));
Serial.print(speed);
Serial.print(F(","));
Serial.println(gear);
#endif
}
}
#if SERIAL_ENABLE
else
Serial.println(F("Bad CAN ID or PID mode is not current"));
#endif
}
#if SERIAL_ENABLE
else
Serial.println(F("Interrupt is asserted, but there are no messages"));
#endif
}
if(!waitingForResponse)
{
if(nextPIDRequest != PID_NONE || (unsigned int)(now - requestSentTime) >= CAN_REQINTERVAL)
{
if(nextPIDRequest == PID_NONE)
nextPIDRequest = PID_ENGINE_RPM;
CANRequest(nextPIDRequest);
waitingForResponse = true;
requestSentTime = now;
// Decide what PID to get next
switch(nextPIDRequest)
{
case PID_ENGINE_RPM:
nextPIDRequest = PID_VEHICLE_SPEED;
break;
default:
nextPIDRequest = PID_NONE;
break;
}
}
}
}
static void CANRequest(byte pid)
{
#if SERIAL_ENABLE
static byte counter;
counter++;
#endif
byte data[] = {
0x02, // Length
PID_MODE_CURR_DATA,
pid,
DATA_PAD,
DATA_PAD,
DATA_PAD,
DATA_PAD,
#if SERIAL_ENABLE
counter
#else
DATA_PAD
#endif
};
#if SERIAL_ENABLE
if(CAN0.sendMsgBuf(PID_ID, PID_ID_EXTENDED, sizeof(data), data) == CAN_OK)
Serial.println(F("Message Sent Successfully!"));
else
Serial.println(F("Error Sending Message..."));
#else
CAN0.sendMsgBuf(PID_ID, PID_ID_EXTENDED, sizeof(data), data);
#endif
}
ISR(TIMER2_COMPA_vect)
{
PORTD = portValue7Seg;
pinValueLed ? LED_ON() : LED_OFF();
}
ISR(TIMER2_OVF_vect)
{
PORTD = PORT7SEGOFF;
LED_OFF();
}
// CAN controller wakeup
EMPTY_INTERRUPT(PCINT0_vect);
// Button wakeup
EMPTY_INTERRUPT(PCINT1_vect); |
<template>
<q-dialog ref="dialogRef" @hide="onDialogHide">
<q-card class="q-dialog-plugin q-pa-xl">
<h6 class="q-mb-lg q-mt-sm">New recipe</h6>
<div class="flex row justify-between">
<q-input v-model="row.title" label="Title" style="width: 45%;"/>
<q-input v-model="row.ingredients" label="Ingredients" style="width: 45%;"/>
<q-input v-model="row.steps" label="Steps" style="width: 45%;"/>
</div>
<q-btn class="full-width q-mt-lg" color="primary" @click="onAddClick">Add</q-btn>
</q-card>
</q-dialog>
</template>
<script>
import { reactive, ref } from 'vue'
import { defineComponent } from 'vue'
import { useDialogPluginComponent } from 'quasar'
import { useRecipesStore } from '../stores/recipes'
import { useUserStore } from '../stores/user'
import { storeToRefs } from 'pinia'
export default defineComponent({
name: 'DialogAddRecipe',
emits: [
// REQUIRED; need to specify some events that your
// component will emit through useDialogPluginComponent()
...useDialogPluginComponent.emits
],
setup() {
const row = reactive({
title: '',
ingredients: '',
steps: '',
});
const recipeStore = useRecipesStore();
const { recipes } = storeToRefs(recipeStore);
const userStore = useUserStore();
const { user } = storeToRefs(userStore);
const { dialogRef, onDialogHide, onDialogOK } = useDialogPluginComponent();
const newRecipe= async() => {
await userStore.fetchUser();
await recipeStore.insertRecipe(user.value.id, row.title, row.ingredients, row.steps);
await recipeStore.fetchRecipes();
}
const onAddClick = () => {
newRecipe()
onDialogOK()
console.log(user.value.id)
};
return {
row,
dialogRef,
onDialogHide,
onAddClick,
newRecipe,
recipes,
user
}
},
});
</script> |
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { ProfileComponent } from './components/profile/profile.component';
import {AuthGuard} from './auth.guard';
@NgModule({
imports: [
RouterModule.forRoot([
{ path: '', component: HomeComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] }
])
],
exports: [
RouterModule
]
})
export class AppRoutingModule {} |
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _04_A_Sockets_Async
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Resize(object sender, EventArgs e)
{
tbLogCli.Width = (Width / 2) - 15;
tbLogSrv.Width = tbLogCli.Width;
tbLogSrv.Left = tbLogCli.Bounds.Right + 5;
panel1.Width = tbLogCli.Width;
panel2.Width = panel1.Width;
panel2.Left = panel1.Bounds.Right + 5;
}
delegate void del(TextBox tb, string s);
static void l(TextBox tb, string s)
{
tb.AppendText("\r\n");
tb.AppendText($"{DateTime.Now.ToString("HH:mm:ss")} - {s}");
}
static del d = new del(l);
void log(TextBox tb, string s)
{
if (this.InvokeRequired)
this.Invoke(d, tb, s);
else
l(tb, s);
}
void logC(string s)
{
log(tbLogCli, s);
}
void logS(string s)
{
log(tbLogSrv, s);
}
delegate void logd(string s);
private void Send(string msg, logd log, Socket socket)
{
try
{
SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
byte[] b = Encoding.ASCII.GetBytes(msg);
saea.SetBuffer(b, 0, b.Length);
saea.Completed += (os, oe) =>
{
if (oe.SocketError == SocketError.Success)
{
if (log != null) log($"SendAsync: {oe.SocketError}!");
if (log != null) log($"SendAsync: sended - '{msg}'");
}
else
if (log != null) log($"SendAsync: SocketError - {oe.SocketError}!");
};
socket.SendAsync(saea);
if (log != null) log($"SendAsync: in progress...)");
}
catch (Exception exc)
{
if (log != null) log(exc.Message);
}
}
private void SendT(string msg, logd log, Socket socket)
{
try
{
SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
byte[] b = Encoding.ASCII.GetBytes(msg);
//saea.SetBuffer(b, 0, b.Length);
//saea.Completed += (os, oe) =>
//{
// if (oe.SocketError == SocketError.Success)
// {
// if (log != null) log($"SendAsync: sended - '{msg}'");
// }
// else
// if (log != null) log($"SendAsync: SocketError - {oe.SocketError}!");
//};
Task<int> t1 = socket.SendToAsync(new ArraySegment<byte>(b), SocketFlags.None,socket.RemoteEndPoint);
if (log != null) log($"SendAsync: in progress...)");
t1.ContinueWith(new Action<Task<int>>(
(t2) =>
{
if (t2.Exception == null)
{
if (log != null) log($"SendAsync: sended - '{msg}'");
}
else
if (log != null) log($"SendAsync: SocketError - {t2.Exception.Message}!");
}
),TaskContinuationOptions.OnlyOnRanToCompletion);
}
catch (Exception exc)
{
if (log != null) log(exc.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
}
private void Receive(logd log, Socket socket)
{
StringBuilder sb = new StringBuilder();
try
{
SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
saea.SetBuffer(new byte[16], 0, 16);
saea.Completed += (os, oe) =>
{
if (sb.Length > 1000 && log != null)
{
log($"ReceiveAsync: BIG DATA!!!!");
log = null;
}
if (oe.SocketError == SocketError.Success)
{
if (log != null) log($"ReceiveAsync: {oe.SocketError}!");
if (log != null) log($"ReceiveAsync: {oe.BytesTransferred} bytes transferred!");
sb.Append(Encoding.ASCII.GetString(oe.Buffer, 0, oe.BytesTransferred));
//"<EOF>" - koniec transferu
if (EndsWithEOF(sb))
{
if (log != null) log($"ReceiveAsync: EOF");
if (log != null) log($"\r\n*************\r\n{sb.ToString()}\r\n***********");
//SERVER
if (socket == srvSocket)
{
string sreq = sb.ToString();
sreq = sreq.Substring(0, sreq.Length - 5);
if (sreq == "FILES")
{
string[] files = Directory.GetFiles(@"e:\pict");
string s = string.Join("\r\n", files) + "<EOF>";
Send(s, null, srvSocket);
Receive(log, socket);
}
else
{
byte[] pic = File.ReadAllBytes(sreq);
string spic = Convert.ToBase64String(pic) + "<EOF>";
Send(spic, null, srvSocket);
Receive(log, socket);
}
}
//CLIENT
if (socket == cliSocket && sb.Length > 1000)
{
sb.Remove(sb.Length - 5, 5);
string sbs = sb.ToString();
byte[] bsb = Convert.FromBase64String(sbs);
string fn = $@"e:\pict\{Path.GetFileName(Path.GetTempFileName())}.jpg";
File.WriteAllBytes(fn, bsb);
Process.Start(fn);
}
}
else
{
saea.SetBuffer(0, 16);
socket.ReceiveAsync(saea);
if (log != null) log($"ReceiveAsync: in progress...)");
}
}
else
if (log != null) log($"ReceiveAsync: SocketError - {oe.SocketError}!");
};
socket.ReceiveAsync(saea);
if (log != null) log($"ReceiveAsync: in progress...)");
}
catch (Exception exc)
{
if (log != null) log(exc.Message);
}
}
/**********************************************************************
* Client *
**********************************************************************/
Socket cliSocket;
private void btnCliConn_Click(object sender, EventArgs e)
{
cliSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(cbxSrvIP.Text), (int)nudSrvPort.Value);
SocketAsyncEventArgs saev = new SocketAsyncEventArgs();
saev.RemoteEndPoint = ep;
saev.Completed += (os, oe) =>
{
if (oe.SocketError == SocketError.Success)
{
logC($"ConnectAsync: Success :)");
if (cliSocket.Connected)
{
logC($"ConnectAsync: connected :)");
//...
}
else
logC($"ConnectAsync: not connected ! :(");
}
else
logC($"ConnectAsync: SocketError - {oe.SocketError}!");
};
cliSocket.ConnectAsync(saev);
logC($"ConnectAsync: in progress...)");
}
private void btnCliConn2_Click(object sender, EventArgs e)
{
try
{
cliSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
logC($"ConnectAsync: in progress...)");
Task t1 = cliSocket.ConnectAsync(cbxSrvIP.Text, (int)nudSrvPort.Value);
t1.ContinueWith(new Action<Task>((t2) =>
{
if (t2.Exception == null)
{
logC($"ConnectAsync: Success :)");
if (cliSocket.Connected)
{
logC($"ConnectAsync: connected :)");
//...
}
else
logC($"ConnectAsync: not connected ! :(");
}
else
logC($"ConnectAsync: SocketError - {t2.Exception.Message}!");
}), TaskContinuationOptions.OnlyOnRanToCompletion);
}
catch (Exception exc) { logC(exc.Message); }
}
private void btnCliSend_Click(object sender, EventArgs e)
{
//Send(tbCliMsg.Text, logC, cliSocket);
SendT(tbCliMsg.Text, logC, cliSocket);
}
private void btnCliRec_Click(object sender, EventArgs e)
{
Receive(logC, cliSocket);
}
private void btnCliEnd_Click(object sender, EventArgs e)
{
cliSocket.Shutdown(SocketShutdown.Both);
cliSocket.Close();
}
/**********************************************************************
* Server *
**********************************************************************/
Socket lstSocket, srvSocket;
private void bnSrvIni_Click(object sender, EventArgs e)
{
try
{
lstSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(cbxSrvIP.Text), (int)nudSrvPort.Value);
lstSocket.Bind(ep);
logS($"Socket Bind to {ep}");
lstSocket.Listen(10);
SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
saea.Completed += (os, oe) =>
{
if (oe.SocketError == SocketError.Success)
{
logS($"AcceptAsync: Success :)!");
srvSocket = oe.AcceptSocket;
if (srvSocket != null && srvSocket.Connected)
{
logS($"Socket connected :)");
//...
}
else
logS($"Socket not connected :(");
}
else
logS($"AcceptAsync: SocketError - {oe.SocketError}!");
};
lstSocket.AcceptAsync(saea);
logS($"AcceptAsync: in progress...)");
}
catch (Exception exc)
{
logS(exc.Message);
}
}
bool EndsWithEOF(StringBuilder sb)
{
if (sb.Length < 5)
return false;
else
{
int n = sb.Length;
return
sb[n - 5] == '<' &&
sb[n - 4] == 'E' &&
sb[n - 3] == 'O' &&
sb[n - 2] == 'F' &&
sb[n - 1] == '>';
}
}
private void btnSrvRec_Click(object sender, EventArgs e)
{
Receive(logS, srvSocket);
}
private void btnSrvSend_Click(object sender, EventArgs e)
{
Send(tbSrvMsg.Text, logS, srvSocket);
}
private void btnSrvStart_Click(object sender, EventArgs e)
{
try
{
lstSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(cbxSrvIP.Text), (int)nudSrvPort.Value);
lstSocket.Bind(ep);
logS($"Socket Bind to {ep}");
lstSocket.Listen(10);
SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
saea.Completed += (os, oe) =>
{
if (oe.SocketError == SocketError.Success)
{
logS($"AcceptAsync: Success :)!");
srvSocket = oe.AcceptSocket;
if (srvSocket != null && srvSocket.Connected)
{
logS($"Socket connected :)");
Receive(logS, srvSocket);
}
else
logS($"Socket not connected :(");
}
else
logS($"AcceptAsync: SocketError - {oe.SocketError}!");
};
lstSocket.AcceptAsync(saea);
logS($"AcceptAsync: in progress...)");
}
catch (Exception exc)
{
logS(exc.Message);
}
}
private void btnSrvEnd_Click(object sender, EventArgs e)
{
srvSocket.Shutdown(SocketShutdown.Both);
srvSocket.Close();
}
}
} |
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import { EventManager, ParseLinks, PaginationUtil, JhiLanguageService, AlertService } from 'ng-jhipster';
import { Blog } from './blog.model';
import { BlogService } from './blog.service';
import { ITEMS_PER_PAGE, Principal, ResponseWrapper } from '../../shared';
import { PaginationConfig } from '../../blocks/config/uib-pagination.config';
@Component({
selector: 'jhi-blog',
templateUrl: './blog.component.html'
})
export class BlogComponent implements OnInit, OnDestroy {
blogs: Blog[];
currentAccount: any;
eventSubscriber: Subscription;
constructor(
private blogService: BlogService,
private alertService: AlertService,
private eventManager: EventManager,
private principal: Principal
) {
}
loadAll() {
this.blogService.query().subscribe(
(res: ResponseWrapper) => {
this.blogs = res.json;
},
(res: ResponseWrapper) => this.onError(res.json)
);
}
ngOnInit() {
this.loadAll();
this.principal.identity().then((account) => {
this.currentAccount = account;
});
this.registerChangeInBlogs();
}
ngOnDestroy() {
this.eventManager.destroy(this.eventSubscriber);
}
trackId(index: number, item: Blog) {
return item.id;
}
registerChangeInBlogs() {
this.eventSubscriber = this.eventManager.subscribe('blogListModification', (response) => this.loadAll());
}
private onError(error) {
this.alertService.error(error.message, null, null);
}
} |
import React from 'react';
import { View, Text, StyleSheet, ScrollView, TextInput, Image, Pressable } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useSelector } from 'react-redux';
import { SelectPosts } from '../../redux/posts/postsSlice';
import { useState, useEffect } from 'react';
import { useNavigation } from '@react-navigation/native';
import { useDispatch } from 'react-redux';
import { fetchCars } from '../../redux/auth/Cars/carsSlice';
const Home = () => {
const posts = useSelector(SelectPosts);
const [searchField, setSearchField] = useState('');
const [filteredPosts, setFilteredPosts] = useState(posts);
const navigation = useNavigation();
const dispatch = useDispatch();
const searchHandler = (text) => {
setSearchField(text);
};
useEffect(() => {
const newFilteredPosts = posts.filter((post) => {
return post.title.toLowerCase().includes(searchField.toLowerCase());
});
newFilteredPosts.sort((a, b) => new Date(b.date) - new Date(a.date));
setFilteredPosts(newFilteredPosts);
}, [posts, searchField]);
useEffect(() => {
dispatch(fetchCars());
}, []);
return (
<SafeAreaView style={styles.container}>
<View style={styles.searchBarContainer}>
<View style={styles.searchBar}>
<TextInput
placeholder='Search...'
style={styles.searchInput}
onChangeText={searchHandler}
/>
</View>
</View>
{posts?.length > 0 ? (
<View style={styles.contentContainer}>
<ScrollView style={styles.postsContainer}>
{filteredPosts.map((post) => (
<Pressable key={post.id} style={styles.postCard} onPress={() =>
navigation.navigate('Detail', { post })
}>
<Text style={styles.userName}>{post.user.name}</Text>
<Image source={{ uri: post.image }} style={styles.imagePost} resizeMode="cover" />
<Text style={styles.postTitle}>{post.title}</Text>
<Text style={styles.postCategory}>{post.category}</Text>
<Text style={styles.postContent}>{post.content}</Text>
{post.category === 'Car' && <Text style={styles.postContent}>Brand: {post.brand}</Text>}
<Text style={styles.price}>Price: ${post.price}</Text>
<Text style={styles.postDate}>
Date: {new Date(post.date).toLocaleString()}
</Text>
</Pressable>
))}
</ScrollView>
</View>
) : (
<Text style={styles.noPostsText}>There are no posts at the moment.</Text>
)}
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F4F4F4',
height: '100%',
paddingBottom: 40,
},
contentContainer: {
marginTop: 10,
paddingHorizontal: 20,
},
searchBarContainer: {
justifyContent: 'center',
alignItems: 'center',
},
searchBar: {
width: '90%',
height: 40,
borderWidth: 1,
borderRadius: 10,
backgroundColor: 'white',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginTop: 10,
},
searchInput: {
flex: 1,
fontSize: 16,
color: 'black',
padding: 10,
},
postsContainer: {
marginTop: 20,
},
postCard: {
backgroundColor: 'white',
padding: 15,
borderRadius: 15,
marginBottom: 20,
elevation: 3,
},
userName: {
fontSize: 18,
fontWeight: 'bold',
color: 'black',
marginBottom: 8,
},
postTitle: {
fontSize: 22,
fontWeight: 'bold',
color: 'black',
marginBottom: 8,
},
postCategory: {
fontSize: 16,
color: 'gray',
marginBottom: 8,
},
postContent: {
fontSize: 18,
color: 'black',
marginBottom: 8,
},
price: {
fontSize: 22,
color: 'green',
},
postDate: {
fontSize: 16,
color: 'blue',
},
noPostsText: {
fontSize: 22,
marginTop: 100,
textAlign: 'center',
margin: 16,
color: 'black',
},
imagePost: {
height: 200,
width: '100%',
marginTop: 20,
marginBottom: 20,
borderRadius: 10,
},
});
export default Home; |
package com.sdk.itjobs.initializer;
import com.sdk.itjobs.database.entity.user.User;
import com.sdk.itjobs.database.repository.user.UserRepository;
import com.sdk.itjobs.util.constant.enumeration.UserRole;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class AdminInitializer {
private final PasswordEncoder passwordEncoder;
private final UserRepository userRepository;
@PostConstruct
public void init() {
String adminEmail = "admin@mail.ru";
if (!userRepository.existsByEmail(adminEmail)) {
String passwordHash = passwordEncoder.encode("password");
User admin = User.builder().email(adminEmail).passwordHash(passwordHash).role(UserRole.ADMIN).build();
userRepository.save(admin);
}
}
} |
//create schema
import { gql } from "apollo-server-core";
//Query is written as what the client will query
// if he query greet we will return a string
//! is used for madatory
const typeDefs = gql`
type Query{
users:[User]
user(_id:ID!):User
quotes:[QuoteWithName]
quote(by:ID!):[Quotes]
}
type Mutation{
signUpUser(userNew:UserInput!):User
signInUser(userSignIn:UserSignInInput!):Token
createQuote(name:String!):String
}
type User{
_id:ID!
firstName:String!
lastName:String!
email:String!
password:String!
quotes:[Quotes]
}
type Quotes{
name:String
by:ID
}
type Token{
token:String
}
type QuoteWithName{
name:String
by:IdName
}
type IdName{
_id:String
firstName:String
}
input UserInput{
firstName:String!
lastName:String!
email:String!
password:String!
}
input UserSignInInput{
email:String!
password:String!
}
input createNewQuote{
name:String!
by:ID!
}
`
export default typeDefs; |
package com.mobius.software.telco.protocols.diameter.primitives.mm10;
/*
* Mobius Software LTD
* Copyright 2023, Mobius Software LTD and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* 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/>
*/
import com.mobius.software.telco.protocols.diameter.TgppAvpCodes;
import com.mobius.software.telco.protocols.diameter.VendorIDs;
import com.mobius.software.telco.protocols.diameter.annotations.DiameterAvpDefinition;
import com.mobius.software.telco.protocols.diameter.exceptions.MissingAvpException;
import com.mobius.software.telco.protocols.diameter.primitives.DiameterGroupedAvp;
/**
*
* @author yulian oifa
*
*/
/*
* 6.3.8 Initial-Recipient-Address AVP
The Initial-Recipient-Address AVP (AVP code 1105) is of type Grouped. It contains recipient address information sent to the MSCF.
Initial-Recipient-Address ::= <AVP header: 1105 10415>
{Sequence-Number}
{Recipient-Address}
*[AVP]
*/
@DiameterAvpDefinition(code = TgppAvpCodes.INITIAL_RECIPIENT_ADDRESS, vendorId = VendorIDs.TGPP_ID, name = "Initial-Recipient-Address")
public interface InitialRecipientAddress extends DiameterGroupedAvp
{
Long getSequenceNumber();
void setSequenceNumber(Long value) throws MissingAvpException;
String getRecipientAddress();
void setRecipientAddress(String value) throws MissingAvpException;
} |
using System;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using OPCUAServerManager.Data;
using OPCUAServerManager.Models;
using OPCUAServerManager.Helpers;
namespace OPCUAServerManager.Services
{
public class OPCUAServerService : IOPCUAServerService
{
private readonly OPCUAServerContext _db;
private readonly ILogger<OPCUAServerService> _logger;
private readonly string ProjectPath = Directory.GetCurrentDirectory();
private readonly string DestinationFileForServers = "Servers/";
public OPCUAServerService(OPCUAServerContext db, ILogger<OPCUAServerService> logger)
{
_db = db;
_logger = logger;
}
public async Task<List<OPCUAServer>> GetAllServers()
{
return await _db.OPCUAServers.ToListAsync();
}
public async Task<OPCUAServer?> AddServer(OPCUAServer data, string url)
{
Uri urn = new Uri(url);
string path = urn.AbsolutePath;
string uri = Environment.GetEnvironmentVariable("ASPNETCORE_AAS_SERVER_SERVICE_URL") + path;
_logger.LogInformation("Adding a new server to the database...");
var existingItem = _db.OPCUAServers.FirstOrDefault(t => t.Name == data.Name);
if (existingItem != null || string.IsNullOrEmpty(data.FileName))
{
throw new InvalidOperationException("Bad request: Item with the same identifier already exists or URL is empty or null");
}
string? downloadResult = await DownloadHelper.DownloadFile(uri);
if (downloadResult == null)
{
_logger.LogError($"Failed to download file for {data.Name}");
throw new Exception("Error downloading the file");
}
_logger.LogInformation($"File downloaded successfully as {data.Name}");
if (!UnzipHelper.UnzipAndDelete(downloadResult, DestinationFileForServers + data.Name))
{
throw new Exception("Error durring unziping the file");
}
_db.OPCUAServers.Add(data);
await _db.SaveChangesAsync();
return data;
}
public async Task DeleteServer(int id)
{
_logger.LogInformation("Deleting server from the database and file system...");
var item = await _db.OPCUAServers.FindAsync(id);
if (item == null)
{
throw new KeyNotFoundException("Server not found in the database.");
}
if (item.Online ?? false)
{
throw new InvalidOperationException("Server is currently online and cannot be deleted.");
}
try
{
Directory.Delete(DestinationFileForServers + item.Name, true);
_logger.LogInformation($"Server folder '{item.Name}' deleted successfully.");
}
catch (Exception ex)
{
throw new Exception($"Error deleting server folder '{item.Name}': {ex.Message}");
}
_db.OPCUAServers.Remove(item);
await _db.SaveChangesAsync();
}
public async Task<OPCUAServer> RunServer(int id)
{
_logger.LogInformation($"Running server with ID {id}...");
var server = _db.OPCUAServers.Find(id);
if (server == null)
{
throw new KeyNotFoundException("Server not found in the database.");
}
server.Online = true;
string serverDir = Path.Combine(ProjectPath, "Servers", $"{server.Name}");
try
{
int processId = await ServerHelper.RunOPCUAServerAsync(serverDir);
server.ProcessID = processId;
_logger.LogInformation("Server starting with process ID: {ProcessId}", processId);
_db.SaveChanges();
return server;
}
catch (Exception ex)
{
_logger.LogError($"Error running the server: {ex.Message}");
throw;
}
}
public async Task<OPCUAServer> StopServer(int id)
{
_logger.LogInformation("Stopping server from the backend...");
var server = _db.OPCUAServers.Find(id);
if (server == null)
{
throw new KeyNotFoundException("Server not found in the database.");
}
try
{
Process process = Process.GetProcessById(server.ProcessID);
Console.WriteLine($"Process with ID {server.ProcessID} was killed.");
process.Kill();
process.Close();
server.ProcessID = 0;
server.Online = false;
_db.SaveChanges();
return server;
}
catch (ArgumentException)
{
Console.WriteLine($"No process found with ID {server.ProcessID}.");
throw new InvalidOperationException("No process found with the specified ID.");
}
}
public async Task<string?> GetServer(int id)
{
_logger.LogInformation($"Getting Server from Backend with id {id}!");
var server = _db.OPCUAServers.Find(id);
if (server == null)
{
return null;
}
try
{
Process process = Process.GetProcessById(server.ProcessID);
_logger.LogInformation($"Process ID: {server.ProcessID}");
string result = await ScriptHelper.ExecuteScriptAsync(Environment.GetEnvironmentVariable("DETAIL_SCRIPT_NAME") ?? "getServerDetail.sh", process.Id.ToString());
_logger.LogInformation(result);
return result;
}
catch (ArgumentException)
{
_logger.LogInformation($"No process found with ID {server.ProcessID}.");
return null;
}
}
}
} |
#ifndef ZIPTHREAD_H
#define ZIPTHREAD_H
#include <QThread>
//! Classe du thread qui zip le dossier suite à la sauvegarde d'une base
/*!
Cette classe héritant de \a QThread et réimplémentant naturellement la méthode \a run(), exécutée lors du lancement
du thread par start().
*/
class ZipThread : public QThread
{
Q_OBJECT
public:
ZipThread(QString zipName,QString dirName,QObject *parent);
void run();
signals:
//! Signal émis lors d'un archivage réussi
void zipCreated(const QString &dir);
private:
QString zipName;
QString dirName;
};
#endif // ZIPTHREAD_H |
//
// EditView.swift
// BucketList
//
// Created by Peter Molnar on 12/05/2022.
//
import SwiftUI
struct EditView: View {
enum LoadingState {
case loading, loaded, failed
}
@Environment(\.dismiss) var dismiss
@StateObject private var viewModel: EditViewModel
var onSave: (Location) -> Void
init(location: Location, onSave: @escaping (Location) -> Void) {
_viewModel = StateObject(wrappedValue: EditViewModel(location: location))
self.onSave = onSave
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Place name", text: $viewModel.name)
TextField("Description", text: $viewModel.description)
}
Section("Nearby...") {
switch viewModel.loadingState {
case .loading:
Text("Loading...")
case .failed:
Text("Please try again later.")
case .loaded:
ForEach(viewModel.pages, id: \.pageid) { page in
HStack {
Text(page.title)
.font(.headline)
+ Text(": ") +
Text(page.description)
.italic()
}
.onTapGesture {
viewModel.name = page.title
viewModel.description = page.description
}
}
}
}
}
.navigationTitle("Place details")
.toolbar {
Button("Save") {
var newLocation = viewModel.location
newLocation.id = UUID()
newLocation.name = viewModel.name
newLocation.description = viewModel.description
onSave(newLocation)
dismiss()
}
}
.task {
await viewModel.fetchNearbyPlaces()
}
}
}
}
struct EditView_Previews: PreviewProvider {
static var previews: some View {
EditView(location: Location.example) { newLocation in }
}
} |
<section class="countdown">
<div class="countdown-days">
<span class="countdown-number">--</span>
<span class="countdown-label">dagar</span>
</div>
<div class="countdown-hours">
<span class="countdown-number">--</span>
<span class="countdown-label">timmar</span>
</div>
<div class="countdown-minutes">
<span class="countdown-number">--</span>
<span class="countdown-label">minuter</span>
</div>
<div class="countdown-seconds">
<span class="countdown-number">--</span>
<span class="countdown-label">sekunder</span>
</div>
</section>
<script type="text/javascript">
window.addEventListener('load', function() {
var CountDown = {
launchTime: new Date(Date.parse("2022-11-12T07:00:00.000Z")), // time in UTC
zeroPad: function(value, size) {
value = value.toString();
if(size-value.length > 0) {
value = "0".repeat(size-value.length) + value;
}
return value;
},
secondsToTimeSegments: function(s) {
var days = Math.trunc(s / (60 * 60 * 24));
s -= days * (60 * 60 * 24);
var hours = Math.trunc(s / (60 * 60));
s -= hours * (60 * 60);
var minutes = Math.trunc(s / 60);
s -= minutes * (60);
var seconds = s % 60;
return {
"days": days,
"hours": hours,
"minutes": minutes,
"seconds": seconds
};
},
updateVisualCounter: function(secondsLeft) {
var parts = CountDown.secondsToTimeSegments(secondsLeft);
for(var key in parts) {
var elm = document.querySelector(".countdown .countdown-"+key+" span");
elm.innerHTML = CountDown.zeroPad(parts[key], 2);
}
if(secondsLeft <= 0) {
clearInterval(CountDown.countdownHandler);
}
},
tickCountdown: function() {
var nowTime = new Date();
var secondsLeft = Math.round((CountDown.launchTime.valueOf() - nowTime.valueOf())/1000);
CountDown.updateVisualCounter(Math.max(secondsLeft, 0));
},
countdownHandler: null,
start: function() {
CountDown.countdownHandler = setInterval(CountDown.tickCountdown, 1000);
CountDown.tickCountdown();
}
};
CountDown.start();
});
</script> |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jose.dataflow;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO;
import org.apache.beam.sdk.options.*;
import org.apache.beam.sdk.transforms.SerializableFunction;
import com.google.cloud.bigquery.*;
import com.google.cloud.bigquery.BigQueryOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MinimalCopyBqTable {
private static final Logger LOG = LoggerFactory.getLogger(MinimalCopyBqTable.class);
public interface Options extends PipelineOptions {
@Description("Input table")
@Validation.Required
String getInputTable();
void setInputTable(String value);
@Description("Output table")
@Validation.Required
String getOutputTable();
void setOutputTable(String value);
}
static final SerializableFunction<TableRow, TableRow> IDENTITY_FORMATTER =
new SerializableFunction<TableRow, TableRow>() {
@Override
public TableRow apply(TableRow input) {
return input;
}
};
public static void main(String[] args) throws Exception {
Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
Pipeline p = Pipeline.create(options);
TableSchema ts = getTableSchema(options.getInputTable());
//TableSchema ts = getTableSchema();
p.apply("Reading BQ Table", BigQueryIO.read().from(options.getInputTable()))
.apply("Writing BQ Table", BigQueryIO.<TableRow>write()
.to(options.getOutputTable())
.withFormatFunction(IDENTITY_FORMATTER)
.withSchema(ts));
p.run().waitUntilFinish();
}
private static List<String> splitBigQueryTableName (String tableName) {
List<String> s1 = Arrays.asList(tableName.split(":"));
List<String> s2 = Arrays.asList(s1.get(1).split("\\."));
return Arrays.asList(s1.get(0), s2.get(0), s2.get(1));
}
private static TableSchema getTableSchema(String tableName) {
List<String> bqTableName = splitBigQueryTableName(tableName);
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
Table t = bigquery.getTable(bqTableName.get(1), bqTableName.get(2));
Schema schema = t.getDefinition().getSchema();
List<TableFieldSchema> fields = new ArrayList<TableFieldSchema>();
for (Field fld: schema.getFields()) {
LOG.info("name: " + fld.getName());
LOG.info("type: " + fld.getType().getValue().toString());
LOG.info("mode: " + fld.getMode().toString());
fields.add(new TableFieldSchema().setName(fld.getName())
.setType(fld.getType().getValue().toString())
.setMode(fld.getMode().toString()));
}
LOG.info("number of fields: " + fields.size());
return new TableSchema().setFields(fields);
}
// public static TableSchema getTableSchema() {
// List<TableFieldSchema> fields = new ArrayList<TableFieldSchema>();
// fields.add(new TableFieldSchema().setName("id").setType("INTEGER").setMode("NULLABLE"));
// fields.add(new TableFieldSchema().setName("value").setType("STRING").setMode("NULLABLE"));
// return new TableSchema().setFields(fields);
// }
} |
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: { lat: 43.4643, lng: 80.5204 }//Waterloo, ON,
});
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer({
draggable: true,
map,
panel: document.getElementById("panel"),
});
directionsRenderer.addListener("directions_changed", () => {
const directions = directionsRenderer.getDirections();
if (directions) {
computeTotalDistance(directions);
}
});
displayRoute(
"Toronto, ON",
"Waterloo, ON",
directionsService,
directionsRenderer
);
}
function displayRoute(origin, destination, service, display) {
service
.route({
origin: origin,
destination: destination,
waypoints: [],
travelMode: google.maps.TravelMode.WALKING
})
.then((result) => {
display.setDirections(result);
})
.catch((e) => {
alert("Could not display directions due to: " + e);
});
}
function computeTotalDistance(result) {
let total = 0;
const myroute = result.routes[0];
if (!myroute) {
return;
}
for (let i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
document.getElementById("total").innerHTML = total + " km";
}
window.initMap = initMap; |
// Productive keywords
export const productivityKeywords = [
"tutorial",
"how-to",
"lecture",
"educational",
"course",
"training",
"workshop",
"seminar",
"skills",
"learning",
"professional development",
"certification",
"guide",
"diy",
"productivity tips",
"motivational speech",
"knowledge",
"instructional",
"webinar",
"web development",
"programming",
"coding tutorial",
"science",
"mathematics",
"history",
"documentary",
"business strategy",
"language learning",
"health and wellness",
"personal finance",
"investment",
"technology review",
"research",
"university",
"college",
"interview skills",
"resume building",
"career advice",
"time management",
"productivity tools",
"mindfulness",
"yoga",
"meditation",
"self-improvement",
"study techniques",
"exam preparation",
];
// Distraction keywords
export const distractionKeywords = [
"funny",
"prank",
"comedy",
"entertainment",
"vlog",
"gaming",
"let's play",
"music video",
"viral",
"challenge",
"reaction",
"unboxing",
"movie review",
"celebrity",
"gossip",
"trailer",
"haul",
"asmr",
"memes",
"entertainment news",
"celebrity gossip",
"reality show",
"comedy skits",
"parody",
"satire",
"dance challenge",
"trending dances",
"lip sync",
"meme review",
"pop culture",
"TV series recap",
"fantasy sports",
"sports highlights",
"fashion and beauty vlog",
"food challenge",
"mukbang",
"travel vlog",
"pet videos",
"car reviews",
"tech unboxing",
"gadget reviews",
"video game walkthroughs",
"role-playing games",
"virtual reality content",
"fan theories",
"superhero movies",
"anime",
"scary",
];
export function analyzeVideoForKeywords(videoDetails) {
let productivityScore = 0;
let distractionScore = 0;
const textToAnalyze = `${videoDetails.title} ${
videoDetails.description
} ${videoDetails.tags.join(" ")}`.toLowerCase();
productivityKeywords.forEach((keyword) => {
if (textToAnalyze.includes(keyword)) productivityScore++;
});
distractionKeywords.forEach((keyword) => {
if (textToAnalyze.includes(keyword)) distractionScore++;
});
// will return {"calc productive score", "distraction score"}
return { productivityScore, distractionScore };
}
// Video Classification Model
export function classifyVideo(videoInfo) {
let productivityScore = 0;
let distractionScore = 0;
// Function to calculate score based on keywords
function calculateScore(text, keywords) {
let score = 0;
keywords.forEach((keyword) => {
if (text.toLowerCase().includes(keyword)) {
score += 1; // Increment score for each occurrence
}
});
return score;
}
// Analyze video title, description, and tags
productivityScore += calculateScore(videoInfo.title, productivityKeywords);
productivityScore += calculateScore(
videoInfo.description,
productivityKeywords
);
videoInfo.tags.forEach((tag) => {
productivityScore += calculateScore(tag, productivityKeywords);
});
distractionScore += calculateScore(videoInfo.title, distractionKeywords);
distractionScore += calculateScore(
videoInfo.description,
distractionKeywords
);
videoInfo.tags.forEach((tag) => {
distractionScore += calculateScore(tag, distractionKeywords);
});
// Determine video category
if (productivityScore > distractionScore) {
return "Productive";
} else if (distractionScore > productivityScore) {
return "Distracting";
} else {
return "Neutral/Inconclusive";
}
}
export function classifyMultipleVideos(videoDetailsArray) {
// Array to hold the classification results
let classifiedVideos = [];
videoDetailsArray.forEach((video) => {
// Extract necessary video info
const videoInfo = {
title: video.snippet.title,
description: video.snippet.description,
tags: video.snippet.tags || [], // Some videos may not have tags
// ...any other info
};
// Classify the video
const classification = classifyVideo(videoInfo);
// Add the result to the array
classifiedVideos.push({
videoId: video.id,
title: videoInfo.title,
classification,
});
});
return classifiedVideos;
} |
import { FormEvent, ChangeEvent, createRef, useContext, useEffect, useState } from "react";
import "./chat.css";
import { StateContext } from "../../../context";
import { Button, Col, Row, Form, Card, InputGroup } from "react-bootstrap";
import { EmojiConvertor } from "emoji-js";
interface ChatProps {
roomName: string;
roomId: string;
}
const emoji = new EmojiConvertor();
emoji.replace_mode = 'unified';
emoji.allow_native = true;
function Chat(props: ChatProps) {
const [messages, setMessages] = useState<string[]>([]);
const [chatInput, setChatInput] = useState("");
const [showValidation, setShowValidation] = useState(false);
const inputRef = createRef<HTMLInputElement>();
const messageContainerRef = createRef<HTMLDivElement>();
const { socket } = useContext(StateContext);
useEffect(() => {
socket.on("messages", (messages) => {
setMessages(messages);
});
socket.on("chatMessage", (message) => {
setMessages((prevState) => [...prevState, message]);
});
return () => {
socket.off("messages");
socket.off("chatMessage");
}
}, []);
useEffect(() => {
if (messageContainerRef.current) {
messageContainerRef.current.scrollTop =
messageContainerRef.current.scrollHeight
- messageContainerRef.current.clientHeight;
}
}, [messages, messageContainerRef]);
const send = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() !== false) {
socket.emit("chatMessage", { message: emoji.replace_colons(chatInput) });
setChatInput("");
inputRef.current?.focus();
setShowValidation(false);
} else {
setShowValidation(true);
}
}
const onChatInput = (event: ChangeEvent<HTMLInputElement>) => {
setChatInput(event.target.value);
}
return (
<Col xs={12} md={4} className="chatContainer my-4 flex-grow-0">
<Card className="h-100 shadow">
<Row className="h-100">
<Col className="messageContainer" ref={messageContainerRef}>
{
messages.map((message, index) => {
return (
<Row key={index}>
<Col className="mx-2">{message}</Col>
</Row>
);
})
}
</Col>
</Row>
<Row>
<Form noValidate validated={showValidation} onSubmit={send}>
<InputGroup>
<Form.Control
onInput={onChatInput}
value={chatInput}
ref={inputRef}
autoFocus
required
/>
<Button variant="primary" type="submit">
Send
</Button>
</InputGroup>
</Form>
</Row>
</Card>
</Col>
);
}
export default Chat; |
#include <check.h>
#include <stdio.h>
#include "../lib/buffer.h"
#include "../lib/leech.h"
START_TEST(test_LCH_Buffer) {
LCH_Buffer *buffer = LCH_BufferCreate();
ck_assert_ptr_nonnull(buffer);
for (int i = 0; i < 10; i++) {
ck_assert(LCH_BufferPrintFormat(buffer, "Hello %s!\n", "buffer"));
}
char *actual = LCH_BufferToString(buffer);
ck_assert_ptr_nonnull(buffer);
char exptected[] = {
"Hello buffer!\n"
"Hello buffer!\n"
"Hello buffer!\n"
"Hello buffer!\n"
"Hello buffer!\n"
"Hello buffer!\n"
"Hello buffer!\n"
"Hello buffer!\n"
"Hello buffer!\n"
"Hello buffer!\n"};
ck_assert_str_eq(actual, exptected);
free(actual);
}
END_TEST
START_TEST(test_LCH_BufferAllocate) {
LCH_Buffer *buffer = LCH_BufferCreate();
ck_assert_ptr_nonnull(buffer);
LCH_BufferPrintFormat(buffer, "first");
size_t first_offset;
ck_assert(LCH_BufferAllocate(buffer, sizeof(uint32_t), &first_offset));
LCH_BufferPrintFormat(buffer, "second");
size_t second_offset;
ck_assert(LCH_BufferAllocate(buffer, sizeof(uint32_t), &second_offset));
LCH_BufferPrintFormat(buffer, "end");
const uint32_t second_value = 4321;
LCH_BufferSet(buffer, second_offset, &second_value, sizeof(uint32_t));
const uint32_t first_value = 1234;
LCH_BufferSet(buffer, first_offset, &first_value, sizeof(uint32_t));
uint32_t *first_actual = (uint32_t *)LCH_BufferGet(buffer, first_offset);
ck_assert_int_eq(*first_actual, 1234);
uint32_t *second_actual = (uint32_t *)LCH_BufferGet(buffer, second_offset);
ck_assert_int_eq(*second_actual, 4321);
LCH_BufferDestroy(buffer);
}
END_TEST
START_TEST(test_LCH_BufferAllocate2) {
LCH_Buffer *buffer = LCH_BufferCreate();
ck_assert_ptr_nonnull(buffer);
ck_assert_int_eq(LCH_BufferLength(buffer), 0);
/****************************************************/
size_t offset;
ck_assert(LCH_BufferAllocate(buffer, sizeof(uint32_t), &offset));
size_t before = LCH_BufferLength(buffer);
ck_assert(LCH_BufferPrintFormat(buffer, "beatles"));
size_t after = LCH_BufferLength(buffer);
uint32_t length = htonl(after - before);
LCH_BufferSet(buffer, offset, &length, sizeof(uint32_t));
/****************************************************/
ck_assert(LCH_BufferAllocate(buffer, sizeof(uint32_t), &offset));
before = LCH_BufferLength(buffer);
ck_assert(LCH_BufferPrintFormat(buffer, "pinkfloyd"));
after = LCH_BufferLength(buffer);
length = htonl(after - before);
LCH_BufferSet(buffer, offset, &length, sizeof(uint32_t));
/****************************************************/
offset = 0;
const uint32_t *len_ptr = (uint32_t *)LCH_BufferGet(buffer, offset);
length = ntohl(*len_ptr);
offset += sizeof(uint32_t);
char *str = strndup((const char *)LCH_BufferGet(buffer, offset), length);
ck_assert_ptr_nonnull(str);
ck_assert_str_eq(str, "beatles");
offset += length;
free(str);
/****************************************************/
len_ptr = (const uint32_t *)LCH_BufferGet(buffer, offset);
length = ntohl(*len_ptr);
offset += sizeof(uint32_t);
str = strndup((const char *)LCH_BufferGet(buffer, offset), length);
ck_assert_ptr_nonnull(str);
ck_assert_str_eq(str, "pinkfloyd");
offset += length;
free(str);
/****************************************************/
LCH_BufferDestroy(buffer);
}
END_TEST
START_TEST(test_LCH_BufferBytesToHex) {
const char data[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
LCH_Buffer *bytes = LCH_BufferCreate();
ck_assert_ptr_nonnull(bytes);
for (size_t i = 0; i < sizeof(data); i++) {
ck_assert(LCH_BufferAppend(bytes, data[i]));
}
LCH_Buffer *hex = LCH_BufferCreate();
ck_assert_ptr_nonnull(hex);
ck_assert(LCH_BufferBytesToHex(hex, bytes));
LCH_BufferDestroy(bytes);
char *str = LCH_BufferToString(hex);
ck_assert_ptr_nonnull(str);
ck_assert_str_eq(str, "0123456789abcdef");
free(str);
}
END_TEST
START_TEST(test_LCH_BufferHexToBytes) {
LCH_Buffer *hex = LCH_BufferCreate();
ck_assert_ptr_nonnull(hex);
ck_assert(LCH_BufferPrintFormat(hex, "0123456789abcdef"));
LCH_Buffer *bytes = LCH_BufferCreate();
ck_assert_ptr_nonnull(bytes);
ck_assert(LCH_BufferHexToBytes(bytes, hex));
const unsigned char data[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
for (size_t i = 0; i < sizeof(data); i++) {
ck_assert_int_eq(*((unsigned char *)LCH_BufferGet(bytes, i)), data[i]);
}
LCH_BufferDestroy(hex);
LCH_BufferDestroy(bytes);
}
END_TEST
START_TEST(test_LCH_BufferUnicodeToUTF8) {
const char *code_points = "0041";
LCH_Buffer *buffer = LCH_BufferCreate();
ck_assert_ptr_nonnull(buffer);
ck_assert(LCH_BufferUnicodeToUTF8(buffer, code_points));
char *str = LCH_BufferToString(buffer);
ck_assert_ptr_nonnull(str);
ck_assert_str_eq(str, "A");
free(str);
code_points = "0100";
buffer = LCH_BufferCreate();
ck_assert_ptr_nonnull(buffer);
ck_assert(LCH_BufferUnicodeToUTF8(buffer, code_points));
str = LCH_BufferToString(buffer);
ck_assert_ptr_nonnull(str);
ck_assert_str_eq(str, "Ā");
free(str);
code_points = "0101";
buffer = LCH_BufferCreate();
ck_assert_ptr_nonnull(buffer);
ck_assert(LCH_BufferUnicodeToUTF8(buffer, code_points));
str = LCH_BufferToString(buffer);
ck_assert_ptr_nonnull(str);
ck_assert_str_eq(str, "ā");
free(str);
}
END_TEST
Suite *BufferSuite(void) {
Suite *s = suite_create("buffer.c");
{
TCase *tc = tcase_create("LCH_Buffer*");
tcase_add_test(tc, test_LCH_Buffer);
suite_add_tcase(s, tc);
}
{
TCase *tc = tcase_create("LCH_BufferAllocate");
tcase_add_test(tc, test_LCH_BufferAllocate);
suite_add_tcase(s, tc);
}
{
TCase *tc = tcase_create("LCH_BufferAllocate2");
tcase_add_test(tc, test_LCH_BufferAllocate2);
suite_add_tcase(s, tc);
}
{
TCase *tc = tcase_create("LCH_BufferBytesToHex");
tcase_add_test(tc, test_LCH_BufferBytesToHex);
suite_add_tcase(s, tc);
}
{
TCase *tc = tcase_create("LCH_BufferHexToBytes");
tcase_add_test(tc, test_LCH_BufferHexToBytes);
suite_add_tcase(s, tc);
}
{
TCase *tc = tcase_create("LCH_BufferUnicodeToUTF8");
tcase_add_test(tc, test_LCH_BufferUnicodeToUTF8);
suite_add_tcase(s, tc);
}
return s;
} |
import React, {useState} from 'react';
import {Button, TextInput, StyleSheet, View, Text, ScrollView, FlatList} from 'react-native';
export default function App() {
const [enteredGoalText, setEnteredGoalText] = useState('');
const [courseGoals, setCourseGoals] = useState([]);
const goalInputHandler = (enteredText) => {
setEnteredGoalText(enteredText);
};
const addGoalHandler = () => {
setCourseGoals((currentCourseGoals) => [...currentCourseGoals, enteredGoalText]);
setEnteredGoalText('');
};
const getPastelColor = (index) => {
const colors = ['#B4B4B8', '#C7C8CC', '#E3E1D9', '#F2EFE5', '#B5C0D0', '#CCD3CA', '#F5E8DD']; //pwede palitan ibang colors
return { backgroundColor: colors[index % colors.length] };
};
return (
<View style={styles.appContainer}>
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
placeholder='My Goal'
onChangeText={goalInputHandler}
value={enteredGoalText}
/>
<Button title="My Goal" onPress={addGoalHandler} />
</View>
<FlatList data = {courseGoals}
renderItem={({item, index }) => (
<View style={[styles.goalsContainer, getPastelColor(index)]}>
<Text style={styles.textMod}>•<Text>{item}</Text></Text>
</View> //text with bullet
)}
keyExtractor={ (index) => index.toString()}
/>
</View>
);
}
const styles = StyleSheet.create({
appContainer: {
flex: 1,
paddingTop: 50,
paddingHorizontal: 16,
},
inputContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingBottom: 25,
borderBottomWidth: 1,
borderColor: '#CCCC',
},
textInput: {
borderWidth: 1,
width: '70%',
marginRight: 8,
padding: 8,
},
goalsContainer: {
paddingTop: 20,
padding: 10,
marginTop: 5,
},
textMod: {
fontSize:20,
}
}); |
<template>
<b-modal :id="modalId" centered hide-footer hide-header>
<div class="customModal">
<div class="modalHeader">
<button class="closeModal" @click="$bvModal.hide(modalId)">
<font-awesome-icon :icon="['fas', 'times']" />
</button>
</div>
<div class="modalBody">
<div class="modalContent text-center">
<img :src="require(`./../assets/images/${modalSuccess ? 'success.png' : 'alert.png'}`)" alt="" class="modalImage"/>
<h2 class="modalHeading my-3">{{ modalSuccess ? 'Confirmation' : 'Alert' }}</h2>
<p class="modalText">{{ modalText }}</p>
<div v-if="!modalSuccess">
<BaseButton
:type="modalButtonType"
:btnText="modalButtonText"
class="baseButton primaryButton mt-3"
@click="
$bvModal.hide(modalId);
"
/>
</div>
</div>
</div>
</div>
</b-modal>
</template>
<script>
import BaseButton from "./../components/BaseButton.vue";
export default {
name: "BaseModal",
props: {
modalId: {
type: String,
},
modalSuccess: {
type: Boolean,
},
modalText: {
type: String,
},
modalButtonType: {
type: String,
default: "button",
},
modalButtonText: {
type: String,
default: "Ok",
},
},
components: {
BaseButton
}
};
</script> |
//
// NewItemView.swift
// MC1GD
//
// Created by Leonard Theodorus on 24/04/23.
//
import SwiftUI
import Combine
let dateNotif = PassthroughSubject<Date, Never>()
struct NewItemView: View {
private let categories = ["Makanan dan Minuman", "Transportasi", "Barang"]
@Binding var showSheet : Bool
@StateObject var formVm = addItemFormViewModel()
@State var newItemImage = UIImage()
@State var newItemPrice = ""
@State var newItemCategory = ""
@State var newItemTag : String = ""
@State var newItemDesc : String = ""
@EnvironmentObject var viewModel : coreDataViewModel
@FocusState var isFocusedName : Bool
@FocusState var isFocusedPrice : Bool
@FocusState var isFocusedDesc : Bool
@State var isNeeds = false
@State var isWants = false
@State private var maxChars: Int = 50
@State var isZeroPrice: Bool = false
@State var showQuestions = false
@Binding var todayDateComponent : Date
@State var showDatePicker : Bool = false
@State var showDeleteIcon : Bool = false
@State var priceValid : Bool = false
@State var num : Double = 0
@FocusState private var focusedField: Field?
@State var const = ""
var body: some View {
NavigationView {
VStack(alignment: .center){
ScrollView {
VStack(alignment: .leading){
// MARK: harga barang
Group{
HStack{
ItemPriceTextField(newItemPrice: $newItemPrice, num: $num, priceValid: $priceValid)
.focused($focusedField, equals: Field.itemPrice)
.onTapGesture {
focusedField = Field.itemPrice
}
}
.padding(.bottom, 5)
if !priceValid && focusedField == .itemPrice{
Text("Harga tidak boleh 0")
.foregroundColor(.red)
.font(.caption2)
.multilineTextAlignment(.leading)
.padding(.leading,60)
}
else if priceValid && focusedField == .itemPrice {
Image(systemName: "checkmark").foregroundColor(.green)
.padding(.horizontal,15)
}
}
Divider()
// MARK: Nama Barang
Group{
HStack {
itemNameTextField(formVm: formVm)
.focused($focusedField, equals: Field.itemName)
.onTapGesture {
focusedField = Field.itemName
}
}.padding(.vertical, 5)
if !formVm.textIsValid && focusedField == .itemName{
Text("Harus diisi, tidak diawali ataupun diakhiri dengan spasi")
.foregroundColor(.red)
.font(.caption2)
.multilineTextAlignment(.leading)
.padding(.leading,60)
}else if formVm.textIsValid && focusedField == .itemName {
Image(systemName: "checkmark").foregroundColor(.green)
.padding(.horizontal,15)
}
}
Divider()
// MARK: pilih itemCategory
Group {
itemCategoryPicker(newItemCategory: $newItemCategory)
}
// MARK: pilih itemTag needs/wants
Group {
itemTagField(isNeeds: $isNeeds, isWants: $isWants, showQuestions: $showQuestions, newItemTag: $newItemTag)
}
// MARK: input deskripsi item
Group {
VStack {
HStack(alignment: .top){
Image(systemName: "text.alignleft")
.imageScale(.large)
.foregroundColor(Color.primary_gray)
.padding(.horizontal,15)
TextField("Deskripsi (50 Karakter)", text: $newItemDesc, axis: .vertical)
.focused($isFocusedDesc)
.lineLimit(5, reservesSpace: true)
.disableAutocorrection(true)
.textFieldStyle(.roundedBorder)
.font(.body)
.fontWeight(.thin)
.onChange(of: newItemDesc) {newValue in
if newValue.count >= maxChars {
newItemDesc = String(newValue.prefix(maxChars))
}
}
}
HStack{
Spacer()
Text("\($newItemDesc.wrappedValue.count)/50")
.font(.caption)
.foregroundColor($newItemDesc.wrappedValue.count == maxChars ? .red : .gray)
}
}.padding(.top, 10)
Divider()
}
// MARK: select tanggal
Group{
datePickerField(showDatePicker: $showDatePicker, todayDateComponent: $todayDateComponent)
}
}
.padding(.horizontal,20)
.padding(.bottom, 30)
.onTapGesture{
focusedField = nil
}
Spacer()
}
}
.onAppear{
newItemCategory = categories.first!
}
.toolbar{
ToolbarItem(placement: .navigationBarLeading) {
Button("Kembali"){
showSheet.toggle()
}
}
ToolbarItem(placement: .principal) {
Text("Tambah Pengeluaran").font(.headline)
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Simpan"){
viewModel.addNewItem(date: todayDateComponent, price: newItemPrice.stripComma(for: newItemPrice), itemName: formVm.itemName, itemDescription: newItemDesc, itemCategory: newItemCategory, itemTag: newItemTag)
dateNotif.send(todayDateComponent)
showSheet = false
}
.disabled(!formVm.textIsValid || !priceValid || newItemTag == "")
}
}
}
}
struct NewItemView_Previews: PreviewProvider {
static var previews: some View {
NewItemView(showSheet: .constant(false), todayDateComponent: .constant(Date()))
}
}
} |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11
// <experimental/iterator>
//
// template <class _Delim, class _CharT = char, class _Traits = char_traits<_CharT>>
// class ostream_joiner;
//
// ostream_joiner(ostream_type& __os, _Delim&& __d);
// ostream_joiner(ostream_type& __os, const _Delim& __d);
#include <experimental/iterator>
#include <iostream>
#include <string>
#include "test_macros.h"
namespace exper = std::experimental;
int main(int, char**) {
const char eight = '8';
const std::string nine = "9";
const std::wstring ten = L"10";
const int eleven = 11;
// Narrow streams w/rvalues
{ exper::ostream_joiner<char> oj(std::cout, '8'); }
{ exper::ostream_joiner<std::string> oj(std::cout, std::string("9")); }
{ exper::ostream_joiner<std::wstring> oj(std::cout, std::wstring(L"10")); }
{ exper::ostream_joiner<int> oj(std::cout, 11); }
// Narrow streams w/lvalues
{ exper::ostream_joiner<char> oj(std::cout, eight); }
{ exper::ostream_joiner<std::string> oj(std::cout, nine); }
{ exper::ostream_joiner<std::wstring> oj(std::cout, ten); }
{ exper::ostream_joiner<int> oj(std::cout, eleven); }
// Wide streams w/rvalues
{ exper::ostream_joiner<char, wchar_t> oj(std::wcout, '8'); }
{ exper::ostream_joiner<std::string, wchar_t> oj(std::wcout, std::string("9")); }
{ exper::ostream_joiner<std::wstring, wchar_t> oj(std::wcout, std::wstring(L"10")); }
{ exper::ostream_joiner<int, wchar_t> oj(std::wcout, 11); }
// Wide streams w/lvalues
{ exper::ostream_joiner<char, wchar_t> oj(std::wcout, eight); }
{ exper::ostream_joiner<std::string, wchar_t> oj(std::wcout, nine); }
{ exper::ostream_joiner<std::wstring, wchar_t> oj(std::wcout, ten); }
{ exper::ostream_joiner<int, wchar_t> oj(std::wcout, eleven); }
return 0;
} |
from rest_framework import serializers
from .models import BestDeals
from likes.models import DealLike
class BestDealsSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
is_owner = serializers.SerializerMethodField()
profile_id = serializers.ReadOnlyField(source='owner.profile.id')
profile_image = serializers.ReadOnlyField(source='owner.profile.image.url')
deals_like_id = serializers.SerializerMethodField()
deals_likes_count = serializers.ReadOnlyField()
deals_comments_count = serializers.ReadOnlyField()
def validate_image(self, value):
if value.size > 1024 * 1024 * 2:
raise serializers.ValidationError(
'Image size larger tham 2MB!'
)
if value.image.width > 4096:
raise serializers.ValidationError(
'Image width larger than 4096px!'
)
if value.image.height > 4096:
raise serializers.ValidationError(
'Image height larger than 4096px!'
)
return value
def get_is_owner(self, obj):
request = self.context['request']
return request.user == obj.owner
def get_deals_like_id(self, obj):
user = self.context['request'].user
if user.is_authenticated:
like = DealLike.objects.filter(
owner=user, deal=obj
).first()
return like.id if like else None
return None
class Meta:
model = BestDeals
fields = [
'id', 'owner', 'is_owner', 'profile_id',
'profile_image', 'created_at', 'updated_at',
'title', 'content', 'category', 'image', 'deals_like_id',
'deals_likes_count', 'deals_comments_count'
] |
seminar1
Что напечатает следующая программа. Ответ записывается с учетом строки
форматирования, указанной при вызове функции printf.
#include <stdio.h>
int main(void)
{
int a[] = {0, 1, 2, 3, 4};
int i, *p;
for (p = &a[0]; p <= &a[4]; p++)
printf("%d ", *p);
// 0 1 2 3 4
printf("\n");
for (p = a + 4, i = 0; i <= 4; i++)
printf("%d ", p[-i]);
// 4 3 2 1 0
printf("\n");
for (p = a, i = 0; p + i <= a + 4; i++)
printf("%d ", *(p + i));
// 0 1 2 3 4
printf("\n");
for (p = a + 4; p >= a; p--)
printf("%d ", a[p - a]);
// 4 3 2 1 0
printf("\n");
return 0;
}
Пусть задан массив
int arr[10];
Что тогда означают выражения?
&arr[2] +адрес элемента с индексом 2
arr[2] +значение элемента с индексом 2
arr + 2 +адрес на элемент с индексом 2
arr +адрес на элемент с индексом 0
arr[0] +значение элемента с индексом 0
*arr + 2 +значение элемента с индексом 0 +2
*(arr + 2) +значение элемента с индексом 2
*arr +значение элемента с индексом 0
Дан фрагмент текста программы
int a[] = {0, 1, 2};
int *b = a + 1;
Чему равны значения выражений?
b[-1] // 0
b[2] // неизвестно
Дан фрагмент текста программы
int a[] = {0, 1, 2};
int *b = a + 1;
Какие из операторов приведенных ниже скомпилируются?
Выберите один или несколько ответов:
a. a = b; // no
b. a++; // no
c. b++; // yes
d. b = a; // yes
Чему будут равны значения переменных? Предположим, что переменная i располагается в памяти по адресу 100, j – 104, k – 108.
int main(void)
{
int i = 10, j = 14, k;
int *p = &i;
// p = 100
int *q = &j;
// q = 104
*p += 1;
// изменится переменная i=11
p = &k;
// p = 108
*p = *q;
// изменится переменная k=14
p = q;
// p = 104
*p = *q;
// изменится переменная j=14
return 0;
}
seminar2
int zippo [4][2] - массив из 4х элементов типа int[2]
zippo int(*)[2] адрес нулевой строки
zippo+2 int(*)[2] адрес второй строки
*(zippo+2) int* адрес нулевого элемента второй строки
*(zippo+2)+1 int* адрес первого элемента второй строки
*(*(zippo+2)+1) int первый элемент второй строки
определены следующие переменные
int *pt; указатель на int
int (*pa)[3]; указатель на массив из 3х элементов
int ar1[2][3]; массив из 2х элементов типа int[3]
int ar2[3][2]; массив из 3х элементов типа int[2]
int **p2; указатель на указатель на int
скомпилируется ли
pt = &ar1[0][0]; +
pt = ar1[0]; +
pt = ar1; -
pa = ar1; +
pa = ar2; -
p2 = &pt; +
*p2 = ar2[0]; +
p2 = ar2; -
int *ptr; указатель на int
int torf[2][2] = {12,14,16}; массив из 2х элементов типа int[2]
ptr = torf[0];
какое значение имеет выражение
*prt 12
*(prt+2) 16
int (*ptr)[2];
int fort[2][2] = {{12},{14,16}};
ptr = fort;
какое значение имеет выражение
**prt 12
**(ptr+1) 14
что будет выведено на экран в результате выполнения программы
#include <stdio.h>
int main(void)
{
int a[0] = {0,1,2,3,4};
int *p[] = {a,a+1,a+2,a+3,a+4};
int **pp = p;
printf("%d %d\n", a, *a); // адрес_массива_а 0
printf("%d %d %d\n", p, *p, **p); // адрес массива_р адрес_массива_а 0
printf("%d %d %d \n", pp, *pp, **pp); // адрес_массива_р адрес_массива_а 0
pp++;
printf("%d %d %d\n", pp-p, *pp-a, **pp); // 1 1 1
*pp++;
printf("%d %d %d\n", pp-p, *pp-a, **pp); // 2 2 2
*++pp;
printf("%d %d %d\n", pp-p, *pp-a, **pp); // 3 3 3
++*pp;
printf("%d %d %d\n", pp-p, *pp-a, **pp); // 3 4 4
pp = p;
*(*(pp++));
printf("%d %d %d\n", pp-p, *pp-a, **pp); // 1 1 1
*(++(*pp));
printf("%d %d %d\n", pp-p, *pp-a, **pp); // 1 2 2
++(*(*pp));
printf("%d %d %d\n", pp-p, *pp-a, **pp); // 1 2 3
} |
import React, { useState } from "react";
const defaultContext = {
isLoggedIn: false,
setLoginStatus: (arg: boolean) => {},
};
export const AuthContext = React.createContext(defaultContext);
type Props = {
children: JSX.Element;
};
export default function AuthContextProvider({ children }: Props) {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const contextValue = {
isLoggedIn: isLoggedIn,
setLoginStatus: setIsLoggedIn,
};
return (
<AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
);
} |
package baza;
import model.*;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class BazaKonekcija {
private static String DB_user = "root";
private static String DB_password = "";
private static String connectionUrl;
private static int port = 3306;
private static String DB_name = "agencija";
private static Connection connection;
public static void DBConnect() throws SQLException /*, ClassNotFoundException*/ {
//Class.forName("com.mysql.cj.jdbc.Driver");
connectionUrl = "jdbc:mysql://localhost" + ":" + port + "/" + DB_name;
connection = DriverManager.getConnection(connectionUrl, DB_user, DB_password);
}
public static <T> List<T> getObjects(String tableName, RowMapper<T> rowMapper) throws SQLException {
DBConnect();
List<T> objects = new ArrayList<>();
ResultSet resultSet = null;
Statement statement = connection.createStatement();
String SQLQuery = "SELECT * FROM " + tableName;
resultSet = statement.executeQuery(SQLQuery);
while (resultSet.next())
objects.add(rowMapper.mapRow(resultSet));
statement.close();
connection.close();
return objects;
}
interface RowMapper<T> {
T mapRow(ResultSet resultSet) throws SQLException;
}
public static List<BankovniRacun> getBankAccounts() throws SQLException {
return getObjects("bankovni_racun", resultSet ->
new BankovniRacun(
resultSet.getInt(1),
resultSet.getString(3),
resultSet.getString(2),
resultSet.getDouble(4)
)
);
}
public static List<Klijent> getClients() throws SQLException {
return getObjects("klijent", resultSet ->
new Klijent(
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getString(7),
resultSet.getString(8),
resultSet.getString(4),
resultSet.getString(5),
resultSet.getString(6)
)
);
}
public static List<Admin> getAdmins() throws SQLException {
return getObjects("admin", resultSet ->
new Admin(
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getString(4),
resultSet.getString(5)
)
);
}
public static List<Korisnik> getUsers() throws SQLException {
List<Klijent> klijenti = getClients();
List<Admin> admins = getAdmins();
List<Korisnik> korisnici = new ArrayList<>();
korisnici.addAll(admins);
korisnici.addAll(klijenti);
return korisnici;
}
public static List<Smjestaj> getAccommodations() throws SQLException {
return getObjects("smjestaj", resultSet ->
new Smjestaj(
resultSet.getInt(1),
Integer.parseInt(resultSet.getString(3)),
resultSet.getString(2),
resultSet.getString(4),
Double.parseDouble(resultSet.getString(5))
)
);
}
public static List<Aranzman> getArrangements() throws SQLException {
return getObjects("aranzman", resultSet ->
new Aranzman(
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getString(4),
LocalDate.parse(resultSet.getString(5)),
LocalDate.parse(resultSet.getString(6)),
Double.parseDouble(resultSet.getString(7)),
getAccommodationByID(resultSet.getInt(8))
)
);
}
private static Smjestaj getAccommodationByID(int id) throws SQLException {
return getAccommodations()
.stream()
.filter(a -> a.getId() == id)
.findFirst()
.orElse(null);
}
public static List<Rezervacija> getReservations() throws SQLException {
return getObjects("rezervacija", resultSet ->
new Rezervacija(
getClientByID(resultSet.getInt(1)),
getArrangementByID(Integer.parseInt(resultSet.getString(2))),
TipRezervacije.fromInt(1),
Double.parseDouble(resultSet.getString(4)),
Double.parseDouble(resultSet.getString(3))
)
);
}
public static BankovniRacun getAgencyBankAccount() throws SQLException {
return getBankAccounts()
.stream()
.filter(BankovniRacun::isAgencyBankAccount)
.findFirst()
.orElse(null);
}
private static Klijent getClientByID(int id) throws SQLException {
return getClients()
.stream()
.filter(c -> c.getId() == id)
.findFirst()
.orElse(null);
}
private static Aranzman getArrangementByID(int id) throws SQLException {
return getArrangements()
.stream()
.filter(a -> a.getId() == id)
.findFirst()
.orElse(null);
}
public static void changePassword(int id, String newPassword, String table) throws SQLException {
DBConnect();
String SQLUpdate = "UPDATE " + table + " SET lozinka=? where id=?";
PreparedStatement preparedStatement = connection.prepareStatement(SQLUpdate);
preparedStatement.setString(1, newPassword);
preparedStatement.setInt(2, id);
preparedStatement.executeUpdate();
connection.close();
}
public static void updateBalance(int id, double newBalance) throws SQLException {
DBConnect();
String SQLUpdate = "UPDATE bankovni_racun SET stanje=? where id=?";
PreparedStatement preparedStatement = connection.prepareStatement(SQLUpdate);
preparedStatement.setDouble(1, newBalance);
preparedStatement.setInt(2, id);
preparedStatement.executeUpdate();
connection.close();
}
public static void updateReservationPaidAmount(int id, int arrID, double price) throws SQLException {
DBConnect();
String SQLUpdate = "UPDATE rezervacija SET placena_cijena=? where Klijent_id=? AND Aranzman_id=?";
PreparedStatement preparedStatement = connection.prepareStatement(SQLUpdate);
preparedStatement.setString(1, price + "");
preparedStatement.setInt(2, id);
preparedStatement.setInt(3, arrID);
preparedStatement.executeUpdate();
connection.close();
}
public static void registerClient(int id, String firstName, String lastName, String phoneNumber, String jmbg, String bankAccNumber, String username, String password) throws SQLException {
DBConnect();
String SQLQuery = "INSERT INTO klijent (id, ime, prezime, broj_telefona, jmbg, broj_racuna, korisnicko_ime, lozinka) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(SQLQuery);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, firstName);
preparedStatement.setString(3, lastName);
preparedStatement.setString(4, phoneNumber);
preparedStatement.setString(5, jmbg);
preparedStatement.setString(6, bankAccNumber);
preparedStatement.setString(7, username);
preparedStatement.setString(8, password);
preparedStatement.executeUpdate();
connection.close();
}
public static void addReservation(int clientID, int arrangementID, double totalPrice, double paidAmount) throws SQLException {
DBConnect();
String SQLQuery = "INSERT INTO rezervacija (Klijent_id, Aranzman_id, ukupna_cijena, placena_cijena) VALUES (?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(SQLQuery);
preparedStatement.setInt(1, clientID);
preparedStatement.setString(2, "" + arrangementID);
preparedStatement.setString(3, "" + totalPrice);
preparedStatement.setString(4, "" + paidAmount);
preparedStatement.executeUpdate();
connection.close();
}
public static void registerAdmin(int id, String firstName, String lastName, String username, String password) throws SQLException {
DBConnect();
String SQLQuery = "INSERT INTO admin (id, ime, prezime, korisnicko_ime, lozinka) VALUES (?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(SQLQuery);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, firstName);
preparedStatement.setString(3, lastName);
preparedStatement.setString(4, username);
preparedStatement.setString(5, password);
preparedStatement.executeUpdate();
connection.close();
}
public static void addAccommodation(int id, String name, int starReview, String roomType, double pricePerNight) throws SQLException {
DBConnect();
String SQLQuery = "INSERT INTO smjestaj (id, naziv, broj_zvjezdica, vrsta_sobe, cjena_po_nocenju) VALUES (?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(SQLQuery);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setString(3, starReview + "");
preparedStatement.setString(4, roomType);
preparedStatement.setString(5, pricePerNight + "");
preparedStatement.executeUpdate();
connection.close();
}
public static void addArrangement(int id, String name, String destination, String transport, LocalDate tripDate, LocalDate arrivalDate, double price, Integer accommodationID) throws SQLException{
DBConnect();
String SQLQuery = "INSERT INTO aranzman (id, naziv_putovanja, destinacija, prevoz, datum_polaska, datum_dolaska, cijena_aranzmana, Smjestaj_id)" +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(SQLQuery);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setString(3, destination);
preparedStatement.setString(4, transport);
preparedStatement.setDate(5, Date.valueOf(tripDate));
preparedStatement.setDate(6, Date.valueOf(arrivalDate));
preparedStatement.setString(7, price + "");
preparedStatement.setObject(8, accommodationID);
preparedStatement.executeUpdate();
connection.close();
}
public static void deleteObject(int id, String table, String where) throws SQLException {
DBConnect();
String SQLQuery = "DELETE FROM " + table + " WHERE " + where + " = ?";
PreparedStatement preparedStatement = connection.prepareStatement(SQLQuery);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
connection.close();
}
} |
//
// Created by jarod on 2020/2/20.
//
#include "util/tc_clientsocket.h"
#include "gtest/gtest.h"
using namespace tars;
class UtilEndpointTest : public testing::Test
{
public:
//添加日志
static void SetUpTestCase()
{
// cout<<"SetUpTestCase"<<endl;
}
static void TearDownTestCase()
{
// cout<<"TearDownTestCase"<<endl;
}
virtual void SetUp() //TEST跑之前会执行SetUp
{
// cout<<"SetUp"<<endl;
}
virtual void TearDown() //TEST跑完之后会执行TearDown
{
// cout<<"TearDown"<<endl;
}
};
TEST_F(UtilEndpointTest, sep)
{
string str = "udp -h ::1 -p 25460 -t 60000";
vector<string> eps = TC_Endpoint::sepEndpoint(str);
EXPECT_EQ(eps.size(), 1);
EXPECT_EQ(eps[0], str);
str = "tcp -h ::1 -p 25460 -t 60000";
eps = TC_Endpoint::sepEndpoint(str);
EXPECT_EQ(eps.size(), 1);
EXPECT_EQ(eps[0], str);
str = "ssl -h ::1 -p 25460 -t 60000";
eps = TC_Endpoint::sepEndpoint(str);
EXPECT_EQ(eps.size(), 1);
EXPECT_EQ(eps[0], str);
str = " tcp -h ::1 -p 25460 -t 60000 ";
eps = TC_Endpoint::sepEndpoint(str);
EXPECT_EQ(eps.size(), 1);
EXPECT_EQ(eps[0], TC_Common::trim(str));
str = " tcp -h ::1 -p 25460 -t 60000: ";
eps = TC_Endpoint::sepEndpoint(str);
EXPECT_EQ(eps.size(), 1);
EXPECT_EQ(eps[0], TC_Common::trim("tcp -h ::1 -p 25460 -t 60000"));
}
TEST_F(UtilEndpointTest, seps)
{
string str = " udp -h ::1 -p 25460 -t 60000 : tcp -h 127.0.0.1 -p 25460 -t 60000 : ssl -h ::1 -p 25460 -t 60000: ";
vector<string> eps = TC_Endpoint::sepEndpoint(str);
EXPECT_EQ(eps.size(), 3);
EXPECT_EQ(eps[0], "udp -h ::1 -p 25460 -t 60000");
EXPECT_EQ(eps[1], "tcp -h 127.0.0.1 -p 25460 -t 60000");
EXPECT_EQ(eps[2], "ssl -h ::1 -p 25460 -t 60000");
} |
import { Avatar, Divider, ListItem, ListItemAvatar, ListItemText, Typography } from "@mui/material";
import * as React from "react";
import { MessageWithPersonsDto } from "../../types";
import convertDate from "../../utils/dates";
export default function Message(props: { message: MessageWithPersonsDto }) {
return (
<>
<ListItem alignItems="flex-start">
<ListItemAvatar>
<Avatar alt={props.message.sender.nameFirst.slice(0, 1).toUpperCase()} src="/" />
</ListItemAvatar>
<ListItemText
// primary={props.message.subject}
secondary={
<React.Fragment>
<Typography
sx={{ display: 'flex' }}
component="span"
variant="body2"
color="text.primary"
>
{props.message.sender.nameFirst}
</Typography>
<Typography>
{props.message.content}
</Typography>
<Typography variant="caption">
{convertDate(props.message.created)}
</Typography>
</React.Fragment>
}
/>
</ListItem>
<Divider variant="inset" component="li" />
</>
)
} |
import { useRef } from "react";
import Accordion from "./Accordion";
import useParams from "../hooks/useParams";
function ZipAccordion() {
const inputRef = useRef<HTMLInputElement | null>(null);
const { append, removeKeyValue, searchParams, resetPagination } = useParams();
const zips = searchParams.getAll("zipCode");
function addZip(event: React.KeyboardEvent<HTMLInputElement>) {
if (inputRef.current && event.key === "Enter") {
const value = inputRef.current.value;
const url = searchParams.toString();
if (!url.includes(`zipCode=${value}`)) {
//only append if the exact zip is not already included in the searchparams
append("zipCode", value);
resetPagination();
}
inputRef.current.value = "";
}
}
function removeZip(zip: string) {
removeKeyValue("zipCode", zip);
}
return (
<div className=" bg-slate-300">
<Accordion title="Zip Code">
<div className="flex flex-row justify-between relative p-4">
<input
className="p-4 w-full mt-2 mb-4"
ref={inputRef}
type="number"
placeholder="ZipCode"
onKeyDown={addZip}
/>
</div>
<div className="flex flex-col p-4 gap-4 ml-3">
{zips.map((zip) => (
<div key={zip} className="flex flex-row justify-between">
<p key={zip}>{zip}</p>
<button onClick={() => removeZip(zip)}>-</button>
</div>
))}
</div>
</Accordion>
</div>
);
}
export default ZipAccordion; |
import * as flubber from "flubber";
import React from "react";
const tri = [
[1, 0],
[2, 2],
[0, 2],
];
const rect = [
[0, 0],
[0, 2],
[2, 2],
[2, 0],
];
const interpolator = flubber.interpolate(tri, rect);
function FlubberExam() {
const [motionValue, setMotionValue] = React.useState<number>(0);
React.useEffect(() => {
console.log(interpolator(motionValue));
}, [motionValue]);
return (
<>
<svg width="200" height="200" viewBox="0 0 2 2">
<path d={interpolator(motionValue)} />
</svg>
<button onClick={() => setMotionValue((prev) => prev - 0.1)}>prev</button>
<button onClick={() => setMotionValue((prev) => prev + 0.1)}>next</button>
</>
);
}
export default FlubberExam; |
= Module Description =
This module explains the complete approach of Web Application Security when developping or deploying web applications as part of the [[:Category:OWASP Education Project|Education Project]].
There is no silver bullet when it comes to securing web applications. This problem has to be addressed from different angles, covering the involved actors, processes: development as well as deployment and Technologies.
* People Awareness and Education
* Web Application Security Training
* Security Requirements and Abuse Cases
* Threat Modelling
* Secure Design Guidelines
* Secure Coding Guidelines and Security Code Review
* Testing for web application security
* Secure administration and Security within Change Management
* Deployment WebAppSec Controls
* WebAppSec Tools
* Starting and improving an SDLC
* Web Application Security Roles and Responsibilities
For the WebAppSec for Developers track this can be trimmed down to 20 minutes:
* People Awareness and Education
* Development WebAppSec Controls
* Deployment WebAppSec Controls
* WebAppSec Tools
= Target audience =
Novice.
= Presentation =
The presentation can be found in [[:Image:Education_Module_Embed_within_SDLC.ppt|Embed within SDLC]].
Normally this presentation is performed in 100 minutes.
= Resources =
== OWASP pointers ==
* [[Phoenix/Tools]]
* [[OWASP Code Review Project]]
* [[Threat Modeling]]
* [[OWASP Testing Project]]
* [[OWASP CLASP Project]]
== External pointers ==
* [http://msdn2.microsoft.com/en-us/security/aa570413.aspx Microsoft Application Threat Modeling]
[[Category:OWASP Education Modules]] |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Katlik</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<!-- header/navbar -->
<header id="navigation-bar" >
<div class="header">
<h2 class="judul">Welcome to Katlik</h2>
<h4 class="ket-judul">Hai Sobat, Selamat Datang di Katlik</h4>
<h5 class="ket-judul-penj">Sebuah web apps sederhanayang berfungsi untuk menghitungilai luas dan keliling bangun datar</h5>
</div>
<div class="navbar">
<button class="btn-segitiga">
<a style="text-decoration:none" href="#section-1">Luas Segitiga</a>
</button>
<br>
<button class="btn-kel">
<a style="text-decoration:none" href="#section-2">Keliling Segitiga</a>
</button>
</div>
</header>
<!-- section 1-->
<section id="section-1">
<!-- judul ls -->
<div class="judul-ls">
<h2>Luas Segitiga</h2>
<img src="./assets/segitiga.png" alt="Luas-segitiga">
<h5>Rumus Luas Segitiga yaitu : </h5>
<p class="rumus-ls">L = 1/2 x A x T</p>
<div class="keterangan">
<p>Dimana :</p>
<p>L = luas</p>
<p>A = Panjang Alas</p>
<p>T = Tinggi</p>
</div>
<hr class="garis">
</div>
<!-- Hitung Luas Segitiga -->
<!-- L = ½ x a x t -->
<div class="hitung-ls">
<!-- input -->
<div class="input">
<div id="error"></div>
<h2>Hitung Luas Segitiga</h2>
<form id="form" action="" method="GET">
<input class="i-alas" type="number" id="alas" placeholder="Nilai Alas" required="" oninvalid="this.setCustomValidity('Nilai Alas Tidak Boleh Kosong!')" oninput="setCustomValidity('')">
<input class="i-tinggi" type="number" id="tinggi" placeholder="Nilai Alas" required="" oninvalid="this.setCustomValidity('Nilai Tinggi Tidak Boleh Kosong!')" oninput="setCustomValidity('')">
<input type="text" id="hasil-luas" disabled>
<button onclick="hitungLuas()">Hitung</button>
<!-- <br> -->
<button type="reset" value="reset">Reset</button>
</form>
</div>
<!-- <div class="btn-ls">
<p id="ls-hasil"></p>
<button class="btn-hitung-ls" onclick="document.getElementById('demo').innerHTML">Hitung</button>
<button type="submit">Hitung</button>
<p id="hasil"></p>
<br>
<button class="btn-reset-ls">Reset</button>
</div> -->
</div>
</section>
<section id="section-2">
<div class="judul-ks">
<h2>Keliling Segitiga</h2>
<img src="./assets/segitiga.png" alt="">
<h5>Rumus Keliling Segitiga yaitu : </h5>
<p class="rumus-ks">K= S1 + S2 + S3</p>
<div class="keterangan">
<p>Dimana :</p>
<p>K = Keliling</p>
<p>S1 = Sisi A</p>
<p>S2 = Sisi B</p>
<p>S3 = Sisi C</p>
</div>
<hr class="garis">
</div>
<!-- Hitung Luas Segitiga -->
<!-- L = ½ x a x t -->
<div class="hitung-ks">
<!-- input -->
<div class="input">
<div id="error"></div>
<h2>Hitung Keliling Segitiga</h2>
<form id="form" action="" method="GET">
<input class="i-alas" type="number" id="s1" placeholder="Sisi A" required="" oninvalid="this.setCustomValidity('Sisi A Tidak Boleh Kosong!')" oninput="setCustomValidity('')">
<input class="i-tinggi" type="number" id="s2" placeholder="Sisi B" required="" oninvalid="this.setCustomValidity('Sisi B Boleh Kosong!')" oninput="setCustomValidity('')">
<input class="form-control" type="number" id="s3" placeholder="Sisi C" required="" oninvalid="this.setCustomValidity('Sisi C Tidak Boleh Kosong!')" oninput="setCustomValidity('')">
<input type="text" id="hasil-kel" disabled>
<button onclick="hitungKel()">Hitung</button>
<!-- <br> -->
<button type="reset" value="reset">Reset</button>
</form>
</div>
</div>
</section>
<!-- footer -->
<footer>
<p>Author by Jefry Kurniawan</p>
</footer>
<script src="./js/script.js" type="text/javascript"></script>
</body>
</html> |
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Op } from 'sequelize';
import { BoilerParts } from './boiler-parts.model';
import { IBoilerPartsFilter, IBoilerPartsQuery } from './types';
@Injectable()
export class BoilerPartsService {
constructor(
@InjectModel(BoilerParts)
private boilerPartsModel: typeof BoilerParts,
) {}
async paginateAndFilter(
query: IBoilerPartsQuery,
): Promise<{ count: number; rows: BoilerParts[] }> {
const limit = +query.limit;
const offset = +query.offset * 20;
const filter = {} as Partial<IBoilerPartsFilter>;
if (query.priceFrom && query.priceTo) {
filter.price = {
[Op.between]: [+query.priceFrom, +query.priceTo],
};
}
if (query.boiler) {
filter.boiler_manufacturer = JSON.parse(decodeURIComponent(query.boiler));
}
if (query.parts) {
filter.parts_manufacturer = JSON.parse(decodeURIComponent(query.parts));
}
return this.boilerPartsModel.findAndCountAll({
limit,
offset,
where: filter,
});
}
async bestsellers(): Promise<{ count: number; rows: BoilerParts[] }> {
return this.boilerPartsModel.findAndCountAll({
where: { bestseller: true },
});
}
async new(): Promise<{ count: number; rows: BoilerParts[] }> {
return this.boilerPartsModel.findAndCountAll({
where: { new: true },
});
}
async findOne(id: number | string): Promise<BoilerParts> {
return this.boilerPartsModel.findOne({
where: { id },
});
}
async findOneByName(name: string): Promise<BoilerParts> {
return this.boilerPartsModel.findOne({
where: { name },
});
}
async searchByString(
str: string,
): Promise<{ count: number; rows: BoilerParts[] }> {
return this.boilerPartsModel.findAndCountAll({
limit: 20,
where: { name: { [Op.like]: `%${str}%` } },
});
}
} |
package util
import (
"context"
"fmt"
"net/http"
"os"
"runtime"
"connectrpc.com/connect"
"github.com/grafana/dskit/httpgrpc"
"github.com/grafana/dskit/middleware"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
httputil "github.com/grafana/pyroscope/pkg/util/http"
)
const maxStacksize = 8 * 1024
var (
panicTotal = promauto.NewCounter(prometheus.CounterOpts{
Namespace: "pyroscope",
Name: "panic_total",
Help: "The total number of panic triggered",
})
RecoveryHTTPMiddleware = middleware.Func(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer func() {
if p := recover(); p != nil {
httputil.Error(w, httpgrpc.Errorf(http.StatusInternalServerError, "error while processing request: %v", panicError(p)))
}
}()
next.ServeHTTP(w, req)
})
})
RecoveryInterceptor recoveryInterceptor
)
func panicError(p interface{}) error {
stack := make([]byte, maxStacksize)
stack = stack[:runtime.Stack(stack, true)]
// keep a multiline stack
fmt.Fprintf(os.Stderr, "panic: %v\n%s", p, stack)
panicTotal.Inc()
return fmt.Errorf("%v", p)
}
// RecoverPanic is a helper function to recover from panic and return an error.
func RecoverPanic(f func() error) func() error {
return func() (err error) {
defer func() {
if p := recover(); p != nil {
err = panicError(p)
}
}()
return f()
}
}
type recoveryInterceptor struct{}
func (recoveryInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (resp connect.AnyResponse, err error) {
defer func() {
if p := recover(); p != nil {
err = connect.NewError(connect.CodeInternal, panicError(p))
}
}()
return next(ctx, req)
}
}
func (recoveryInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
return func(ctx context.Context, conn connect.StreamingHandlerConn) (err error) {
defer func() {
if p := recover(); p != nil {
err = connect.NewError(connect.CodeInternal, panicError(p))
}
}()
return next(ctx, conn)
}
}
func (recoveryInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
return next
} |
"use client";
import React, { useEffect, useRef, useState } from "react";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
TableFooter,
} from "@/components/ui/table";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { format } from "date-fns";
import { Button } from "@/components/ui/button";
import { Pencil, Trash2, X, Forward, CalendarIcon } from "lucide-react";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import { Calendar } from "@/components/ui/calendar";
import { cn } from "@/lib/utils";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import Image from "next/image";
import { supabase } from "@/app/utils/supabase/supabase";
const DataRow = ({ data, categoryData }) => {
const [isEdit, setIsEdit] = useState(false);
const Ref = useRef();
const Ref_second = useRef();
const Ref_third = useRef();
const { categoryName, ...editData } = categoryData;
// categoryDataからcategoryNameとそれ以外をeditDataとして取得
const [date, setDate_] = useState(
(categoryName === "notice" || categoryName === "gallery") &&
new Date(data.event_date).toISOString().replace(/T.*/, "T00:00:00.000Z")
);
const editForm = useForm({
resolver: zodResolver(editData.FormSchema),
defaultValues:
categoryName === "notice"
? { event_date: data.event_date, content: data.content }
: categoryName === "movie"
? { title: data.title, description: data.description, url: data.url }
: categoryName === "gallery"
? {
event_date: data.event_date,
title: data.title,
description: data.description,
url: data.url,
}
: categoryName === "faq"
? { question: data.question, answer: data.answer }
: "aaa",
});
// 投稿の更新
const onSubmit = async () => {
// 手動でバリデーションチェック
const value =
categoryName === "notice"
? { event_date: "", content: "" }
: categoryName === "movie"
? { title: "", description: "", url: "" }
: categoryName === "gallery"
? { event_date: "", title: "", description: "", url: "" }
: categoryName === "faq"
? { question: "", answer: "" }
: "";
if (categoryName === "notice") {
value.content = Ref.current.value;
const modifiedDate = new Date(date);
modifiedDate.setDate(modifiedDate.getDate() + 1);
value.event_date = modifiedDate;
} else if (categoryName === "movie") {
value.title = Ref.current.value;
value.description = Ref_second.current.value;
value.url = Ref_third.current.value;
} else if (categoryName === "gallery") {
value.title = Ref.current.value;
const modifiedDate = new Date(date);
modifiedDate.setDate(modifiedDate.getDate() + 1);
value.event_date = modifiedDate;
value.description = Ref_second.current.value;
value.url = Ref_third.current.value;
} else if (categoryName === "faq") {
value.question = Ref.current.value;
value.answer = Ref_second.current.value;
}
try {
await editData.updateFunc(data.id, value);
window.location.reload();
} catch (error) {
toast("更新に失敗しました.");
console.error(error);
}
};
// 投稿の削除
const onDelete = async () => {
try {
// if (categoryName === "notice")
await editData.deleteFunc(data.id);
// galleryの削除
if (categoryName === "gallery") {
const image_name = data.url.match(/[^/]+$/)[0];
await supabase.storage.from("gallery").remove([`images/${image_name}`]);
}
// else if (categoryName === "faq") await editData.deleteFAQData(data.id);
window.location.reload();
} catch (error) {
toast("削除に失敗しました.");
console.error(error);
}
};
if (categoryName === "notice") {
return (
<>
{isEdit ? (
<>
<TableCell>{data.id}</TableCell>
<Form {...editForm}>
<TableCell>
<FormField
control={editForm.control}
name="event_date"
render={({ field }) => (
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant="outline"
className={cn(
"w-full justify-start text-left font-normal",
!date && "text-muted-foreground"
)}
>
{date ? format(date, "PPP") : <span>日を選択</span>}
<CalendarIcon className="ml-auto size-4 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={new Date(date)}
onSelect={setDate_}
/>
</PopoverContent>
</Popover>
)}
/>
</TableCell>
<TableCell>
<FormField
control={editForm.control}
name="content"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input
placeholder="お知らせ内容"
{...field}
ref={Ref}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell className="flex items-center gap-3 p-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsEdit(!isEdit)}
>
<X className="size-[1.2rem] cursor-pointer" />
</Button>
<Button
variant="ghost"
size="icon"
type="submit"
onClick={() => onSubmit()}
>
<Forward className="size-[1.2rem] cursor-pointer" />
</Button>
</TableCell>
{/* </form> */}
</Form>
</>
) : (
<>
{Object.entries(data).map(
([key, value]) =>
key !== "createdAt" &&
key !== "updatedAt" && <TableCell key={key}>{value}</TableCell>
)}
<TableCell className="flex items-center gap-3 p-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsEdit(!isEdit)}
>
<Pencil className="size-[1.2rem] cursor-pointer" />
</Button>
<Dialog>
<DialogTrigger>
<Button variant="ghost" size="icon">
<Trash2 className="size-[1.2rem] cursor-pointer" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>このお知らせを削除しますか?</DialogTitle>
<DialogDescription>
この操作は取り消せません.
</DialogDescription>
<Button
variant="destructive"
className="mt-3"
onClick={() => onDelete()}
>
Delete
</Button>
</DialogHeader>
</DialogContent>
</Dialog>
</TableCell>
</>
)}
</>
);
} else if (categoryName === "movie") {
return (
<>
{isEdit ? (
<>
<TableCell>{data.id}</TableCell>
<Form {...editForm}>
<TableCell>
<FormField
control={editForm.control}
name="title"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input placeholder="タイトル" {...field} ref={Ref} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={editForm.control}
name="description"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input
placeholder="映像の説明"
{...field}
ref={Ref_second}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={editForm.control}
name="url"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input
placeholder="動画URL"
type="url"
{...field}
ref={Ref_third}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell className="flex items-center gap-3 p-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsEdit(!isEdit)}
>
<X className="size-[1.2rem] cursor-pointer" />
</Button>
<Button
variant="ghost"
size="icon"
type="submit"
onClick={() => onSubmit()}
>
<Forward className="size-[1.2rem] cursor-pointer" />
</Button>
</TableCell>
{/* </form> */}
</Form>
</>
) : (
<>
{/* {Object.entries(data).map(
([key, value]) =>
key !== "createdAt" &&
key !== "updatedAt" && <TableCell key={key}>{value}</TableCell>
key === "url" && <p>aaa</p>
)} */}
{Object.entries(data).map(([key, value]) => {
if (key === "createdAt" || key === "updatedAt") {
return null;
} else if (key === "url") {
return (
<TableCell key={key}>
<iframe
className="movie-iframe-rounded"
width="100"
height="56"
src={`${value}&controls=0&disablekb=1&loop=1&mute=1`}
title={value}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerPolicy="strict-origin-when-cross-origin"
allowFullScreen
></iframe>
</TableCell>
);
} else {
return <TableCell key={key}>{value}</TableCell>;
}
})}
<TableCell className="flex items-center gap-3 p-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsEdit(!isEdit)}
>
<Pencil className="size-[1.2rem] cursor-pointer" />
</Button>
<Dialog>
<DialogTrigger>
<Button variant="ghost" size="icon">
<Trash2 className="size-[1.2rem] cursor-pointer" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>この映像投稿を削除しますか?</DialogTitle>
<DialogDescription>
この操作は取り消せません.
</DialogDescription>
<Button
variant="destructive"
className="mt-3"
onClick={() => onDelete()}
>
Delete
</Button>
</DialogHeader>
</DialogContent>
</Dialog>
</TableCell>
</>
)}
</>
);
} else if (categoryName === "gallery") {
return (
<>
{isEdit ? (
<>
<TableCell>{data.id}</TableCell>
<Form {...editForm}>
<TableCell>
<FormField
control={editForm.control}
name="event_date"
render={({ field }) => (
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant="outline"
className={cn(
"w-full justify-start text-left font-normal",
!date && "text-muted-foreground"
)}
>
{date ? format(date, "PPP") : <span>日を選択</span>}
<CalendarIcon className="ml-auto size-4 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={new Date(date)}
onSelect={setDate_}
/>
</PopoverContent>
</Popover>
)}
/>
</TableCell>
<TableCell>
<FormField
control={editForm.control}
name="title"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input placeholder="タイトル" {...field} ref={Ref} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={editForm.control}
name="description"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input placeholder="説明" {...field} ref={Ref_second} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={editForm.control}
name="url"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input
placeholder="説明"
{...field}
ref={Ref_third}
disabled
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell className="flex items-center gap-3 p-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsEdit(!isEdit)}
>
<X className="size-[1.2rem] cursor-pointer" />
</Button>
<Button
variant="ghost"
size="icon"
type="submit"
onClick={() => onSubmit()}
>
<Forward className="size-[1.2rem] cursor-pointer" />
</Button>
</TableCell>
{/* </form> */}
</Form>
</>
) : (
<>
{/* {Object.entries(data).map(
([key, value]) =>
key !== "createdAt" &&
key !== "updatedAt" && <TableCell key={key}>{value}</TableCell>
)} */}
{Object.entries(data).map(([key, value]) => {
if (key === "createdAt" || key === "updatedAt") {
return null;
} else if (key === "url") {
return (
<TableCell key={key}>
<Image src={`${value}`} width={100} height={45} alt="" />
</TableCell>
);
} else {
return <TableCell key={key}>{value}</TableCell>;
}
})}
<TableCell className="flex items-center gap-3 p-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsEdit(!isEdit)}
>
<Pencil className="size-[1.2rem] cursor-pointer" />
</Button>
<Dialog>
<DialogTrigger>
<Button variant="ghost" size="icon">
<Trash2 className="size-[1.2rem] cursor-pointer" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>この写真を削除しますか?</DialogTitle>
<DialogDescription>
この操作は取り消せません.
</DialogDescription>
<Button
variant="destructive"
className="mt-3"
onClick={() => onDelete()}
>
Delete
</Button>
</DialogHeader>
</DialogContent>
</Dialog>
</TableCell>
</>
)}
</>
);
} else if (categoryName === "faq") {
return (
<>
{isEdit ? (
<>
<TableCell>{data.id}</TableCell>
<Form {...editForm}>
<TableCell>
<FormField
control={editForm.control}
name="question"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input placeholder="質問内容" {...field} ref={Ref} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={editForm.control}
name="answer"
render={({ field }) => (
<FormItem className="w-full space-y-1">
<FormControl>
<Input placeholder="回答" {...field} ref={Ref_second} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell className="flex items-center gap-3 p-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsEdit(!isEdit)}
>
<X className="size-[1.2rem] cursor-pointer" />
</Button>
<Button
variant="ghost"
size="icon"
type="submit"
onClick={() => onSubmit()}
>
<Forward className="size-[1.2rem] cursor-pointer" />
</Button>
</TableCell>
{/* </form> */}
</Form>
</>
) : (
<>
{Object.entries(data).map(
([key, value]) =>
key !== "createdAt" &&
key !== "updatedAt" && <TableCell key={key}>{value}</TableCell>
)}
<TableCell className="flex items-center gap-3 p-4">
<Button
variant="ghost"
size="icon"
onClick={() => setIsEdit(!isEdit)}
>
<Pencil className="size-[1.2rem] cursor-pointer" />
</Button>
<Dialog>
<DialogTrigger>
<Button variant="ghost" size="icon">
<Trash2 className="size-[1.2rem] cursor-pointer" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>このFAQを削除しますか?</DialogTitle>
<DialogDescription>
この操作は取り消せません.
</DialogDescription>
<Button
variant="destructive"
className="mt-3"
onClick={() => onDelete()}
>
Delete
</Button>
</DialogHeader>
</DialogContent>
</Dialog>
</TableCell>
</>
)}
</>
);
}
};
export default DataRow; |
//
// MusicListView.swift
// YouTube Music
//
// Created by 은서우 on 2023/10/10.
//
import SwiftUI
struct MusicListView: View {
@State private var columns: [GridItem] = [GridItem(.flexible())]
@State private var rows: [GridItem] = [GridItem(.flexible())]
var body: some View {
VStack(alignment: .leading){
Text("이 노래로 뮤직 스테이션 시작하기")
HStack {
Text("빠른 선곡")
.font(.title)
.fontWeight(.bold)
Spacer()
Text("모두 재생")
.padding(6)
.cornerRadius(100)
.overlay(RoundedRectangle(cornerRadius: 100)
.stroke(Color.customColorBorderGray, lineWidth: 2))
}
// [Problem] 기존 앱과 다름
// page가 넘어가는 형식으로 구성,
// 오른쪽 부분에 다음 페이지의 요소들이 보임
// --- --- --- --- --- --- --- ---
// 해결 방법?
// 1. SwiftUI로 만들수있는가?
// 2. Tabview로 구현하는 것이 아닌가?
// FIXME: 우선, SwiftUI Snap Carousel 이라고 검색해보면 좋음
TabView {
ForEach(0..<5, id: \.self) {_ in
LazyVGrid(columns: columns, spacing: 0) {
ForEach(1...4, id: \.self) { count in
MusicListDetailView()
.frame(width: 350)
}
}
}
} //: TABVIEW
.tabViewStyle(.page(indexDisplayMode: .never))
.frame(height: 300) //수정하기 : 크기 geometry로 읽어오기(?)
}
.padding()
}
}
#Preview {
MusicListView()
} |
from argparse import ArgumentParser
import numpy as np
import pandas as pd
import random, math
import networkx as nx
import logging, os, time, csv
from dateutil.parser import parse
from datetime import datetime, timezone
import calendar, time;
pd.options.mode.chained_assignment = None
from WiDNeR_extended import WiDNeR_extended
from node2vec_master.src import node2vec as nv
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("generate_property_paths.log", mode='w'),
logging.StreamHandler()
]
)
def parse_args():
'''
Parses the arguments.
'''
parser = ArgumentParser(description="Run generate_numerical_features.")
parser.add_argument('command', choices=['generate_numerical_features'])
parser.add_argument('--structured_triples', help='Input the file with structured triples')
parser.add_argument('--attributive_triples', help='Input the file with attributive triples')
parser.add_argument('--ent2id', help='Input the file with ent2id')
parser.add_argument('--rel2id', help='Input the file with rel2id')
parser.add_argument('--attr2id', help='Input the file with attr2id')
parser.add_argument('--walk-length', type=int, default=3, help='Length of walk per source. Default is 3.')
parser.add_argument('--num-walks', type=int, default=10, help='Number of walks per source. Default is 10.')
parser.add_argument('--p', type=float, default=1, help='Return hyperparameter. Default is 1.')
parser.add_argument('--q', type=float, default=1, help='Inout hyperparameter. Default is 1.')
parser.add_argument('--weighted', dest='weighted', action='store_true', help='Boolean specifying (un)weighted. Default is unweighted.')
parser.add_argument('--unweighted', dest='unweighted', action='store_false')
parser.set_defaults(weighted=False)
parser.add_argument('--directed', dest='directed', action='store_true', help='Graph is (un)directed. Default is undirected.')
parser.add_argument('--undirected', dest='undirected', action='store_false')
parser.set_defaults(directed=False)
parser.add_argument('--random-state', type=int, default=0000, help='Random seed for the random walk algorithm. Default is 0000.')
parser.add_argument('--normalize_date', dest='normalize_date', action='store_true', help='Boolean specifying date should be normalized or not. Default is not to normalize.')
#parser.add_argument('--not_to_normalize_date', dest='not_to_normalize_date', action='store_false')
parser.set_defaults(normalize_date=False)
return parser.parse_args()
def generate_numerical_features(structured_triples, attributive_triples, ent2id, rel2id, attr2id, normalize_date):
## read Triples
structured_triples_ = pd.read_csv(structured_triples, header=None, names=['head','relation', 'tail'], delimiter='\t| ')
attributive_triples_ = pd.read_csv(attributive_triples, header=None, names=['head','attribute', 'value'], delimiter='\t| ')
#print(structured_triples_)
#print(attributive_triples_)
## normaliz date values
if normalize_date:
attributive_triples_ = normalize_date_values(attributive_triples_)
print('normalized')
## generate a network using WiDNeR_extended
input_file_name = os.path.splitext(structured_triples)[0]
_,_,_, filename = WiDNeR_extended(structured_triples_, attributive_triples_, input_file_name)
print(filename)
## generate random walk using node2vec's algorithm
nx_G = read_graph(filename)
G = nv.Graph(nx_G, args.directed, args.p, args.q)
G.preprocess_transition_probs()
print(args.num_walks, args.walk_length, args.random_state)
cutpt = len(pd.read_csv(rel2id, header=None)) ## the number of relations to give as the smallest id of attributes for LW48k - 257, Fb15k-237 ..
print(cutpt)
walks = G.simulate_walks(args.num_walks, args.walk_length, args.random_state, cutpt)
print(len(walks), ' walks in total')
walks_2hop = []
walks_3hop = []
for w in walks:
if len(w) == 2:
walks_2hop.append(w)
elif len(w) == 3:
walks_3hop.append(w)
print(len(walks_2hop), '2 hop walks in total')
print(len(walks_3hop), '3 hop walks in total')
## usig the walks as templates get all the entries for each feature/walk
features_h2 = get_feature_values(2, walks_2hop, structured_triples_, attributive_triples_)
features_h3 = get_feature_values(3, walks_3hop, structured_triples_, attributive_triples_)
## combine features from different hopes, features_h1, features_h2, and features_h2
features_h1 = attributive_triples_.rename(columns={'attribute': 'property_path'}, inplace=False)
features = pd.concat([features_h1, features_h2, features_h3])
features['value'] = pd.to_numeric(features['value'], downcast="float", errors='coerce')
#print(features[features.isna().any(axis=1)])
features=features.dropna().reset_index(drop=True)
print(features[features.isna().any(axis=1)])
print('features', features)
print(features.nunique())
## take the average of the values of multivalued attributes
features_averaged = features.groupby(['head','property_path']).agg(value_mean = ('value', 'mean')).reset_index()
print(features_averaged)
print(features_averaged.nunique())
##convert entity ids to names
ent2id_= pd.read_csv(ent2id, header=None, names=['head','id'], delimiter='\t| ')
features_averaged = ent_id_to_name(features_averaged, ent2id_)
##convert rel and attr ids with names
rel2id_ = pd.read_csv(rel2id, header=None, names=['property_path','id'], delimiter='\t| ')
attr2id_ = pd.read_csv(attr2id, header=None, names=['property_path','id'], delimiter='\t| ')
features_averaged = prop_id_to_name(features_averaged, rel2id_, attr2id_)
return features_averaged
def get_feature_values(num_hops, walks, structured_triples_, attributive_triples_):
if num_hops ==2:
rels = [item[0] for item in walks]
#print(rels)
props = [item[1] for item in walks]
str_trip = structured_triples_.loc[structured_triples_['relation'].isin(rels)]
attr_trip = attributive_triples_.loc[attributive_triples_['attribute'].isin(props)]
result_h2 = str_trip.merge(attr_trip, left_on='tail', right_on='head', how='inner')
result_h2['property_path'] = result_h2[['relation', 'attribute']].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)
result_h2.drop(columns=['relation', 'attribute'], inplace=True)
result_h2 = result_h2.reindex(columns=['head_x', 'property_path', 'value'])
result_h2.rename(columns={'head_x': 'head'}, inplace=True)
return result_h2
if num_hops ==3:
rels1 = [item[0] for item in walks]
rels2 = [item[1] for item in walks]
props = [item[2] for item in walks]
str_trip1 = structured_triples_.loc[structured_triples_['relation'].isin(rels1)]
str_trip2 = structured_triples_.loc[structured_triples_['relation'].isin(rels2)]
attr_trip = attributive_triples_.loc[attributive_triples_['attribute'].isin(props)]
result = str_trip1.merge(str_trip2, left_on='tail', right_on='head', how='inner')
result_h3 = result.merge(attr_trip, left_on='tail_y', right_on='head', how='inner')
result_h3['property_path'] = result_h3[['relation_x', 'relation_y', 'attribute']].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)
result_h3.drop(columns=['relation_x', 'relation_y', 'attribute'], inplace=True)
result_h3 = result_h3.reindex(columns=['head_x', 'property_path', 'value'])
result_h3.rename(columns={'head_x': 'head'}, inplace=True)
return result_h3
def read_graph(filename):
'''
Reads the input network in networkx.
'''
if args.weighted:
G = nx.read_edgelist(filename, nodetype=int, data=(('weight',float),), create_using=nx.DiGraph())
else:
G = nx.read_edgelist(filename, nodetype=int, create_using=nx.DiGraph())
for edge in G.edges():
G[edge[0]][edge[1]]['weight'] = 1
if not args.directed:
G = G.to_undirected()
return G
def normalize_date_values(attributive_triples_):
## normaliz date values
attributive_triples_date= attributive_triples_[attributive_triples_['value'].astype(str).str.contains("XMLSchema#dateTime")]
attributive_triples_date['value']= attributive_triples_date['value'].astype(str).str.replace(r'\^\^.*', '', regex=True)
attributive_triples_date['value']=attributive_triples_date['value'].astype(str)
attributive_triples_date['value'] = attributive_triples_date['value'].map(lambda x: x.replace('"', ''))
print(attributive_triples_date)
attributive_triples_date["value"] = attributive_triples_date["value"].map(lambda x: (np.datetime64(x) - np.datetime64('1970-01-01T00:00:00Z'))/np.timedelta64(1, 's'))
print(attributive_triples_date)
## other values different from date (i.e., time and geo)
attributive_triples_= attributive_triples_[~attributive_triples_['value'].astype(str).str.contains("XMLSchema#dateTime")]
attributive_triples_['value'] = attributive_triples_['value'].astype(str).str.replace(r'\^\^.*', '', regex=True)
attributive_triples_['value'] = attributive_triples_['value'].astype(str).str.replace('+', '')
attributive_triples_['value'] = attributive_triples_['value'].astype(str).str.replace('"', '')
## combine date and other values
attributive_triples_ = pd.concat([attributive_triples_, attributive_triples_date])
attributive_triples_ = attributive_triples_.astype({"value": float})
return attributive_triples_
def ent_id_to_name(features_averaged, ent2id):
features_averaged['head'] = features_averaged['head'].map(ent2id.set_index('id')['head']).fillna(features_averaged['head'])
return features_averaged
def prop_id_to_name(features_averaged, relids, attrids):
ids = pd.concat([relids, attrids], ignore_index=True)
ids_pps = ids
all_pps = features_averaged[features_averaged['property_path'].astype(str).str.contains('_')]['property_path'].tolist()
all_pps = list(set(all_pps))
#print(len(all_pps), len(set(all_pps)))
for path in all_pps:
path_ids = path.split('_')
#print(path_ids)
path_name = ''
for id in path_ids:
#print('id', ids['id'])
name = ids.loc[ids['id']==int(id)]['property_path'].values[0]
#print('name', name)
path_name = path_name + '_' + name
path_name = path_name.lstrip('_')
#print('path_name', path_name)
new_row = {'property_path':path_name, 'id':path}
ids_pps = ids_pps.append(new_row, ignore_index=True)
features_averaged['property_path'] = features_averaged['property_path'].map(ids_pps.set_index('id')['property_path']).fillna(features_averaged['property_path'])
return features_averaged
if __name__ == '__main__':
args = parse_args()
if args.command == 'generate_numerical_features':
numerical_fatures = generate_numerical_features(structured_triples=args.structured_triples, attributive_triples=args.attributive_triples, \
ent2id=args.ent2id, rel2id=args.rel2id, attr2id=args.attr2id, normalize_date=args.normalize_date)
filename = os.path.splitext(args.structured_triples)[0]
numerical_fatures.to_csv(f'{filename}_numerical_features.txt', sep='\t', index=False, header=False) |
import 'package:fl_lib/fl_lib.dart';
import '../model/server/private_key_info.dart';
class PrivateKeyStore extends PersistentStore {
PrivateKeyStore() : super('key');
void put(PrivateKeyInfo info) {
box.put(info.id, info);
box.updateLastModified();
}
List<PrivateKeyInfo> fetch() {
final keys = box.keys;
final ps = <PrivateKeyInfo>[];
for (final key in keys) {
final s = box.get(key);
if (s != null && s is PrivateKeyInfo) {
ps.add(s);
}
}
return ps;
}
PrivateKeyInfo? get(String? id) {
if (id == null) return null;
return box.get(id);
}
void delete(PrivateKeyInfo s) {
box.delete(s.id);
box.updateLastModified();
}
} |
<template>
<Page>
<h1 class="text-2xl font-bold mb-4">Students</h1>
<button @click="showModal = true" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mb-4">
Add New Student
</button>
<AddStudentModal :is-visible="showModal" @close="showModal = false" @studentAdded="handleStudentAdded" />
<EditStudentModal v-if="selectedStudent" :is-visible="editModalVisible" @close="editModalVisible = false" :student="selectedStudent" />
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
ID
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Username
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Email
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr v-for="student in studentsData" :key="student.id">
<td class="px-6 py-4 whitespace-nowrap">{{ student.id }}</td>
<td class="px-6 py-4 whitespace-nowrap">{{ student.username }}</td>
<td class="px-6 py-4 whitespace-nowrap">{{ student.email }}</td>
<td class="px-6 py-4 whitespace-nowrap">
<Link :href="`/students/${student.id}`" class="text-blue-500 hover:text-blue-700 mr-2">View</Link>
<button @click="editStudent(student)" class="text-yellow-500 hover:text-yellow-600 mr-2">
Edit
</button>
<button @click="deleteStudent(student.id)" class="text-red-500 hover:text-red-700">
Delete
</button>
</td>
</tr>
</tbody>
</table>
</Page>
</template>
<script setup>
import { ref, defineProps } from "vue";
import { useForm } from "@inertiajs/inertia-vue3";
import AddStudentModal from "../../Components/AddStudentModal.vue";
import EditStudentModal from "../../Components/EditStudentModal.vue";
import { router, Link } from "@inertiajs/vue3";
import Page from "../Layout/Index.vue";
const showModal = ref(false);
const editModalVisible = ref(false);
const selectedStudent = ref(null);
const { students } = defineProps(["students"]);
const studentsData = ref(students);
const form = useForm({});
const deleteStudent = async (id) => {
if (confirm("Are you sure you want to delete this student?")) {
try {
form.delete(`students/${id}`);
getStudents();
} catch (error) {
console.error("Error deleting student:", error);
}
}
};
const editStudent = (student) => {
if (student) {
selectedStudent.value = student;
editModalVisible.value = true;
}
};
const getStudents = () => {
router.get("/students");
};
</script> |
using Regira.IO.Extensions;
using Regira.IO.Utilities;
using Regira.Office.PDF.Models;
using Regira.Office.PDF.SelectPdf;
using Regira.Serializing.Newtonsoft.Json;
using Regira.Utilities;
using Regira.Web.HTML;
namespace Office.PDF.Testing;
[TestFixture]
[Parallelizable(ParallelScope.All)]
public class SelectPdfTests
{
private readonly string _tableContent;
private readonly string _loremIpsumContent;
private readonly string _regiraLogoPath;
private readonly HtmlTemplateParser _htmlParser;
private readonly string _inputDir;
private readonly string _outputDir;
public SelectPdfTests()
{
_htmlParser = new HtmlTemplateParser(new JsonSerializer());
var assemblyDir = AssemblyUtility.GetAssemblyDirectory()!;
var assetsDir = Path.Combine(assemblyDir, "../../../", "Assets");
_inputDir = Path.Combine(assetsDir, "Input");
_outputDir = Path.Combine(assetsDir, "Output", "SelectPdf");
Directory.CreateDirectory(_outputDir);
_tableContent = File.ReadAllText(Path.Combine(assetsDir, "Input", "table.html"));
_loremIpsumContent = File.ReadAllText(Path.Combine(assetsDir, "Input", "lorem-ipsum.html"));
_regiraLogoPath = Path.Combine(assetsDir, "Input", "regira-logo.png");
}
[Test]
public void CreatePdf()
{
var html = _htmlParser.Parse(_tableContent, (object?)null).Result;
// ReSharper disable once RedundantArgumentDefaultValue
var marginPoints = DimensionsUtility.MmToPt(10f, DimensionsUtility.DPI.DEFAULT);
var pdfPrinter = new PdfManager();
var template = new HtmlInput
{
HtmlContent = html,
Margins = marginPoints
};
using var pdf = pdfPrinter.Create(template);
using var stream = pdf.GetStream()!;
Assert.IsNotNull(stream);
Assert.IsTrue(stream.Length > 0);
var outputPath = Path.Combine(_outputDir, "pdf-table.pdf");
File.WriteAllBytes(outputPath, FileUtility.GetBytes(stream)!);
}
[Test]
public void FillParameters()
{
var date = DateTime.Now;
var logoBytes = File.ReadAllBytes(_regiraLogoPath);
var logoBase64 = $"data:image/png;base64,{FileUtility.GetBase64String(logoBytes)}";
var parameters = new
{
title = "Test Title",
date = date.ToString("dd/MM/yyyy"),
lijnen = Enumerable.Repeat((object?)null, 25).Select((_, i) => new { title = $"Item {char.ConvertFromUtf32(i + 65)}" }).ToList(),
logo = logoBase64
};
var html = _htmlParser.Parse(_loremIpsumContent, parameters).Result;
var template = new HtmlInput
{
HtmlContent = html
};
var pdfPrinter = new PdfManager();
using var pdf = pdfPrinter.Create(template);
using var stream = pdf.GetStream()!;
Assert.IsNotNull(stream);
Assert.IsTrue(stream.Length > 0);
var outputPath = Path.Combine(_outputDir, "pdf-with-parameters.pdf");
File.WriteAllBytes(outputPath, FileUtility.GetBytes(stream)!);
}
[Test]
public void With_Header()
{
var date = DateTime.Now;
var logoBytes = File.ReadAllBytes(_regiraLogoPath);
var logoBase64 = $"data:image/png;base64,{FileUtility.GetBase64String(logoBytes)}";
var parameters = new
{
title = "Test Title",
date = date.ToString("dd/MM/yyyy"),
lijnen = Enumerable.Repeat((object?)null, 25).Select((_, i) => new { title = $"Item {char.ConvertFromUtf32(i + 65)}" }).ToList(),
logo = logoBase64
};
var html = _htmlParser.Parse(_loremIpsumContent, parameters).Result;
var headerHtml = _htmlParser.Parse(File.ReadAllText(Path.Combine(_inputDir, "header.html")), parameters).Result;
var template = new HtmlInput
{
HtmlContent = html,
HeaderHtmlContent = headerHtml,
HeaderHeight = 10
};
var pdfPrinter = new PdfManager();
using var pdf = pdfPrinter.Create(template);
using var stream = pdf.GetStream()!;
Assert.IsNotNull(stream);
Assert.IsTrue(stream.Length > 0);
var outputPath = Path.Combine(_outputDir, "pdf-with-header.pdf");
File.WriteAllBytes(outputPath, FileUtility.GetBytes(stream)!);
}
} |
import { Component, OnInit, ViewEncapsulation, AfterViewInit } from '@angular/core';
import { FormBuilder, Validators, FormArray } from '@angular/forms';
import { Helpers } from '../../../../../../helpers';
import { Router } from "@angular/router";
import { CountryService } from '../country.service';
declare let $: any;
@Component({
selector: 'app-primary-country-add',
templateUrl: './primary-country-add.component.html',
encapsulation: ViewEncapsulation.None
})
export class PrimaryCountryAddComponent implements OnInit {
countryList: any;
createForm: any;
formError = false;
countryLinkedList: any;
constructor(public formBuilder: FormBuilder, private router: Router, private _countryService: CountryService) {
this.formInit();
}
ngOnInit() {
this.getCountry();
this.getLinkedCountry();
}
formInit() {
this.createForm = this.formBuilder.group({
PrimaryCountryId: [0],
LinkedCountry: this.formBuilder.array([])
});
}
getCountry() {
return this._countryService.primaryCountryPossibility().subscribe(
data => {
this.countryList = data.data;
setTimeout(() => {
$('.m_select_country').selectpicker();
}, 0);
},
error => {
console.log("Some error tiggered" + error)
});
}
getLinkedCountry() {
return this._countryService.linkedCountryPossibility("").subscribe(
data => {
this.countryLinkedList = data.data;
},
error => {
console.log("Some error tiggered" + error)
});
}
onChange(id, isChecked: boolean) {
const LinkedCountry = this.createForm.get('LinkedCountry') as FormArray;
if (isChecked) {
LinkedCountry.push(this.formBuilder.group({
Id: id
}));
} else {
let index = LinkedCountry.controls.findIndex(x => x.value == id)
LinkedCountry.removeAt(index);
}
}
create() {
console.log(this.createForm.value);
this.formError = true;
if (!this.createForm.valid) {
Helpers.DisplayMsg({ status: 'error', msg: 'Please fill all mandatory fields' })
} else {
Helpers.setLoading(true);
this._countryService.PrimaryCountryAdd(this.createForm.value).subscribe(
data => {
if (data.status == 'success') {
Helpers.setLoading(false);
Helpers.DisplayMsg(data)
this.createForm.reset()
this.formInit();
this.getCountry();
this.getLinkedCountry();
this.formError = false;
this.router.navigateByUrl('/setting/primary-country/edit/' + data.data.PrimaryCountryId);
} else {
Helpers.setLoading(false);
Helpers.DisplayMsg(data)
}
},
error => {
Helpers.DisplayMsg({ status: 'error', msg: 'Something when wrong.Please try later' })
Helpers.setLoading(false);
});
}
}
} |
package com.rbxu.market.application.impl;
import com.alibaba.cola.dto.SingleResponse;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.rbxu.market.application.ProjectApplicationService;
import com.rbxu.market.aspect.digest.TimeCost;
import com.rbxu.market.domain.model.ProjectModel;
import com.rbxu.market.domain.model.TenantModel;
import com.rbxu.market.domain.service.ProjectDomainService;
import com.rbxu.market.dto.ProjectModifyDTO;
import com.rbxu.market.domain.enums.ErrorCodeEnum;
import com.rbxu.market.domain.exception.ExceptionBuilder;
import com.yomahub.tlog.core.annotation.TLogAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@TimeCost(businessIdentify = "ProjectApplicationService")
@Service
@Slf4j
public class ProjectApplicationServiceImpl implements ProjectApplicationService {
public static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat("MARKET_EXECUTE_TEST_POOL_%d").build();
public static final ThreadPoolExecutor MARKET_EXECUTE_TEST_POOL = new ThreadPoolExecutor(
2,
5,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(2000),
THREAD_FACTORY);
@Resource
private ProjectDomainService projectDomainService;
@Override
public SingleResponse<Boolean> createProject(ProjectModifyDTO projectModifyDTO) {
// 参数处理校验
if (Objects.isNull(projectModifyDTO.getTenantId())) {
throw ExceptionBuilder.build(ErrorCodeEnum.PARAM_IS_NULL);
}
// 参数转换映射
ProjectModel projectModel = new ProjectModel();
TenantModel tenantModel = new TenantModel();
tenantModel.setId(projectModel.getId());
projectModel.setName(projectModifyDTO.getName());
projectModel.setCreator(projectModifyDTO.getOperatorId());
projectModel.setDesc("create by product");
projectModel.setTenantModel(tenantModel);
// 调用领域服务
Boolean result = projectDomainService.create(projectModel);
if (Boolean.TRUE.equals(result)) {
return SingleResponse.of(true);
}
return SingleResponse.of(false);
}
@TimeCost(businessIdentify = "MOCK")
@Override
public SingleResponse<Boolean> mockBusiness(Long id, String name) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return SingleResponse.of(true);
}
@Override
public SingleResponse<Boolean> mockExecutorBusiness() {
MARKET_EXECUTE_TEST_POOL.execute(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info("mockExecutorBusiness execute");
});
return SingleResponse.of(true);
}
} |
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { notify } from 'notiwind'
import { getAuth, signInWithEmailAndPassword, signOut } from 'firebase/auth'
import { useCurrentUser } from 'vuefire'
import { AppPage, AppText } from '@/components/ui'
import { AppBtn, AppLinkBtn } from '@/components/ui'
const userCreds = reactive({
email: '',
password: ''
})
const user = useCurrentUser()
const error = ref<string | null>(null)
const loading = ref<boolean>(false)
const auth = getAuth()
const router = useRouter()
const handleLogin = () => {
loading.value = true
signInWithEmailAndPassword(auth, userCreds.email, userCreds.password)
.then(() => {
// Signed in
loading.value = false
notify(
{
group: 'success',
title: 'Success',
text: 'You have successfully logged in'
},
2000
)
setTimeout(() => {
router.push('/app')
}, 2000)
})
.catch((error) => {
const errorCode = error.code
const errorMessage = error.message
error.value = `Error: ${errorCode} - ${errorMessage}`
loading.value = false
notify(
{
group: 'error',
title: 'Error',
text: `Error: ${errorCode} - ${errorMessage}`
},
4000
)
})
}
// const isRoot = computed(() => route.fullPath === '/')
const onLogoutClick = () => {
const auth = getAuth()
signOut(auth)
.then(() => {
// Sign-out successful.
router.push('/')
})
.catch((error) => {
// An error happened.
// eslint-disable-next-line no-alert
alert(error.message)
})
}
</script>
<template>
<AppPage>
<template v-if="!user">
<form class="login-form" @submit.prevent="handleLogin">
<AppText tag="h1" color="zinc-600" size="4xl" weight="bold"> TaskDo </AppText>
<div class="w-80">
<AppText tag="p" color="zinc-600" size="base" align="center">
Login to be able to create and manage your tasks
</AppText>
</div>
<input
type="email"
placeholder="email"
class="input w-full input-bordered"
v-model="userCreds.email"
/>
<input
type="password"
placeholder="password"
class="input w-full input-bordered"
v-model="userCreds.password"
/>
<AppBtn
v-if="!error && !user && !loading"
type="submit"
:disabled="!userCreds.email || !userCreds.password"
btn-block
>
Login
</AppBtn>
<AppBtn btn-block v-else type="button" loading> Authenticating </AppBtn>
</form>
</template>
<template v-else>
<div class="flex flex-col justify-center gap-y-2">
<AppText tag="h1" color="zinc-600" size="3xl" weight="bold" align="center">
TaskDo
</AppText>
<AppText tag="p" color="zinc-600" size="base" align="center">
You are already logged in
</AppText>
<div class="flex justify-between">
<AppBtn alert text-case="normal-case" size="sm" @click="onLogoutClick"> Logout </AppBtn>
<AppLinkBtn alert text-case="normal-case" size="sm" to="/app"> Back to app </AppLinkBtn>
</div>
</div>
</template>
</AppPage>
</template>
<style scoped lang="scss">
.login-form {
@apply flex flex-col items-center card p-10 bg-base-100 gap-y-5 border-purple-200 border-solid border-4;
}
</style> |
import java.util.Scanner;
public class Main {
static int[][] dp = new int[30][30]; // 최댓값이 29
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 테케만큼 반복
int testCase = sc.nextInt();
// mCn 의 경우의 수를 구해주면 된다. (mCn = m-1Cn-1 + m-1Cn)
int[][] dp = new int[30][30]; // 최대 29
// mCm = 1, mC0 = 1 (m == n, n == 0)
for (int i = 0; i < 30; i++) {
dp[i][i] = 1;
dp[i][0] = 1;
}
for (int i = 2; i < 30; i++) {
for (int j = 1; j < 30; j++) {
// mCn = m-1Cn-1 + m-1Cn
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}
}
StringBuilder sb = new StringBuilder();
for (int tc = 1; tc <= testCase; tc++) {
// n, m개 사이트
int n = sc.nextInt();
int m = sc.nextInt();
sb.append(dp[m][n]).append("\n");
}
// 출력
System.out.println(sb);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.